Merge pull request #163 from Nwflower/refactor/entropy-convergence
架构降熵:合并重复实现、拆分过大的文件、删除不再使用的代码,并用测试守护这些规则。
This commit is contained in:
312 files changed
+8188
-9026
No files matched your search
@@ -5,7 +5,7 @@ License, Version 2.0 (see `LICENSE`). That license applies to Reims-Go's own cod
|
||||
only and is separate from the portable runtime bundle it invokes as an external
|
||||
child process. Compatibility patches in the runtime repository are licensed
|
||||
under terms compatible with their target upstream projects (see [runtime patch
|
||||
licenses](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)).
|
||||
licenses](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)).
|
||||
|
||||
The Reims-Go desktop executable also incorporates open-source Go and frontend
|
||||
libraries (including Wails, React, Radix UI, Lucide, Inter font, Go `golang.org/x`
|
||||
|
||||
@@ -121,7 +121,7 @@ reims-go vm start macos-tahoe | Out-Host # Start the VM
|
||||
<details>
|
||||
<summary>Build from source</summary>
|
||||
|
||||
With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu).
|
||||
With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/reims-go/reims-vgpu).
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
+1
-1
@@ -117,7 +117,7 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
|
||||
<details>
|
||||
<summary>从源码构建</summary>
|
||||
|
||||
需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 单独构建。
|
||||
需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 单独构建。
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": [
|
||||
"Nwflower"
|
||||
],
|
||||
"zh": "运行时改从 `reims-go/reims-vgpu` 下载。`REIMS_GO_RELEASES_REPO` 现在只影响应用更新,运行时仓库改用 `REIMS_GO_RUNTIME_RELEASES_REPO` 指定。",
|
||||
"en": "Runtimes are now downloaded from `reims-go/reims-vgpu`. `REIMS_GO_RELEASES_REPO` now only affects app updates; set the runtime repository with `REIMS_GO_RUNTIME_RELEASES_REPO`."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复分段选项在保存期间短暂禁用后,当前选项的高亮可能消失的问题。",
|
||||
"en": "Keep the highlight on the current option of a segmented control after it was briefly disabled while saving."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "从命令行启动虚拟机失败时,一并显示 Guest Tools 和网络相关的日志。",
|
||||
"en": "Include Guest Tools and network log lines when a VM fails to start from the command line."
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"group": "removals",
|
||||
"order": 0,
|
||||
"authors": [
|
||||
"Nwflower"
|
||||
],
|
||||
"zh": "主题清单不再支持从未生效的 `sounds` 字段。带交互脚本的主题可以自行播放提示音。",
|
||||
"en": "Theme manifests no longer accept the `sounds` field, which never took effect. Themes with an interactive script can play their own sounds."
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": [
|
||||
"Nwflower"
|
||||
],
|
||||
"zh": "修复只用名称指定虚拟机时读不到 SSH 端口等设置的问题。智能体工具此前会因此误报未启用 SSH 端口转发。",
|
||||
"en": "Fixed missing settings such as the SSH port when a VM is identified by name only. Agent tools used to report that SSH port forwarding was off."
|
||||
}
|
||||
+3
-4
@@ -24,10 +24,9 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"}
|
||||
goDomains = []string{"native", "macos-glossary", "core"}
|
||||
feEagerDomains = []string{"core", "vm"}
|
||||
feLazyDomains = []string{"wizard", "settings", "plugins"}
|
||||
allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"}
|
||||
goDomains = []string{"native", "macos-glossary", "core"}
|
||||
feLazyDomains = []string{"wizard", "settings", "plugins"}
|
||||
)
|
||||
|
||||
type parsedEntry struct {
|
||||
|
||||
@@ -99,6 +99,18 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U
|
||||
|
||||
macOS 专属逻辑集中在 `internal/macos/` 与 `frontend/src/macos/`,宿主核心通过通用驱动路由与扩展接口调用。代码库通过双向架构边界测试锁死跨界依赖白名单,任何新增跨界引用或白名单条目失效都会令测试失败,确保耦合范围只减不增。
|
||||
|
||||
### 唯一入口与自动检查
|
||||
|
||||
以下事项各有一个唯一入口,对应的测试会拒绝绕开入口的新代码。Go 检查位于 `internal/archtest/`,前端检查位于 `frontend/scripts/`。
|
||||
|
||||
| 事项 | 唯一入口 | 检查 |
|
||||
| :--- | :--- | :--- |
|
||||
| 整体替换小文件 | `internal/atomicfile` | `file_replace_test.go` |
|
||||
| 向界面发送事件 | 后端 `App.emit`,前端 `wails.ts` | `events_test.go` |
|
||||
| 界面调用后端 | `App` 的导出方法,修改后重新生成 `frontend/wailsjs` | `bindings_test.go` |
|
||||
|
||||
测试同时拒绝没有调用者的函数、前端导出、样式类与文案,拒绝前端模块循环引用,并限制单个 Go 函数的长度。
|
||||
|
||||
## 便携运行时与跨仓边界
|
||||
|
||||
便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时仓库固定 QEMU 子模块的提交,负责构建、依赖补丁、打包与 Alpha 发布。压缩包包含 `reims-ctl.exe`、`reims-util.exe`、QEMU、自包含运行库、实际应用的补丁和许可证全文。`manifest.json` 记录各组件的实际源码提交及补丁,调试符号单独打包分发。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu)
|
||||
|
||||
@@ -52,7 +52,7 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V
|
||||
|
||||
## 主题、面板桥接与契约演进
|
||||
|
||||
宿主内置浅色与深色外观,同时提供三档主题扩展能力:第一档通过种子色与派生规则生成表面、文字和边框色阶,支持替换包内字体、单色图标、品牌标志与事件提示音;第二档提供面向公开部件类名(`rg-p-*`)与只读状态属性(`data-*`)的样式表及槽位/全窗图层状态装饰,由宿主锁定层叠顺序并清洗外部链接,且始终保护标题栏拖拽区、键盘焦点环与最小点击热区;第三档通过稳定的 `contributes.themes[].uiScript` 字段声明交互脚本,仅对获批 `ui:script` 高危权限的主题按需加载前端交互接口。交互脚本运行在主窗口前端环境并共享页面 DOM(并非隔离沙盒),加载前宿主会自动收起桌面底层绑定全局对象。
|
||||
宿主内置浅色与深色外观,同时提供三档主题扩展能力:第一档通过种子色与派生规则生成表面、文字和边框色阶,支持替换包内字体、单色图标与品牌标志;第二档提供面向公开部件类名(`rg-p-*`)与只读状态属性(`data-*`)的样式表及槽位/全窗图层状态装饰,由宿主锁定层叠顺序并清洗外部链接,且始终保护标题栏拖拽区、键盘焦点环与最小点击热区;第三档通过稳定的 `contributes.themes[].uiScript` 字段声明交互脚本,仅对获批 `ui:script` 高危权限的主题按需加载前端交互接口,提示音也由交互脚本自行播放。交互脚本运行在主窗口前端环境并共享页面 DOM(并非隔离沙盒),加载前宿主会自动收起桌面底层绑定全局对象。
|
||||
|
||||
已激活的外部主题在重启客户端和升级插件后自动保留,并在脚本变更重新批准后带版本哈希参数重载;仅停用或卸载所属主题插件时回退内置默认主题并清空当前配色方案,安全模式或命令行停用无关插件不会影响当前主题。从市场安装并启用主题插件时,仅当当前仍处于内置默认主题才自动切换为该插件的首个主题,不覆盖用户已选的其他外部主题。
|
||||
|
||||
|
||||
@@ -10,12 +10,12 @@
|
||||
| :--- | :--- | :--- |
|
||||
| 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 |
|
||||
| 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 |
|
||||
| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 |
|
||||
| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 的实际构建提交为准。 |
|
||||
| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 |
|
||||
| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 |
|
||||
| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 |
|
||||
| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 |
|
||||
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 |
|
||||
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 |
|
||||
|
||||
同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-endpoints.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs scripts/test-hypervisor.mjs",
|
||||
"test": "node --test --test-concurrency=2 \"scripts/test-*.mjs\"",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"bundle": "vite build && node scripts/check-ui-contract.mjs",
|
||||
"build": "tsc --noEmit && pnpm run bundle",
|
||||
|
||||
@@ -20,79 +20,63 @@ function walkFiles(dir, exts) {
|
||||
return out
|
||||
}
|
||||
|
||||
test('lazy i18n domain keys are always backed by domain .gen imports', () => {
|
||||
/** Static imports and dynamic import() targets of a source file, as absolute paths. */
|
||||
function importsOf(file) {
|
||||
const src = fs.readFileSync(file, 'utf8')
|
||||
const resolve = (spec) => {
|
||||
const target = path.resolve(path.dirname(file), spec)
|
||||
return ['', '.ts', '.tsx', '/index.ts', '/index.tsx'].map((ext) => target + ext).find((p) => fs.existsSync(p) && fs.statSync(p).isFile())
|
||||
}
|
||||
const collect = (re) => [...src.matchAll(re)].map((m) => resolve(m[1])).filter((p) => p && /\.tsx?$/.test(p))
|
||||
return {
|
||||
eager: collect(/^(?:import(?! type\b)|export)\b[^'"]*?['"](\.[^'"]+)['"]/gm),
|
||||
lazy: collect(/\bimport\(\s*['"](\.[^'"]+)['"]\s*\)/g),
|
||||
}
|
||||
}
|
||||
|
||||
/** Every module loaded together with entry. */
|
||||
function loadedWith(entry, imports) {
|
||||
const seen = new Set([entry])
|
||||
for (const file of seen) for (const next of imports.get(file)?.eager ?? []) seen.add(next)
|
||||
return seen
|
||||
}
|
||||
|
||||
test('every chunk registers the lazy i18n domains its keys belong to', () => {
|
||||
const lazyDomains = ['wizard', 'settings', 'plugins']
|
||||
const keyToDomain = new Map()
|
||||
for (const dom of ['core', 'vm', ...lazyDomains]) {
|
||||
for (const dom of lazyDomains) {
|
||||
const raw = JSON.parse(fs.readFileSync(path.join(localesDir, `${dom}.json`), 'utf8'))
|
||||
for (const k of Object.keys(raw)) {
|
||||
if (!k.startsWith('$')) keyToDomain.set(k, dom)
|
||||
}
|
||||
for (const k of Object.keys(raw)) keyToDomain.set(k, dom)
|
||||
}
|
||||
const files = walkFiles(srcDir, ['.ts', '.tsx'])
|
||||
const imports = new Map(files.map((file) => [file, importsOf(file)]))
|
||||
const entries = new Set([path.join(srcDir, 'main.tsx'), ...[...imports.values()].flatMap((i) => i.lazy)])
|
||||
assert.ok(entries.size > 5, 'found no lazy chunks: the import patterns no longer match')
|
||||
|
||||
// Known lazy-loaded chunk entry trees (loaded via React.lazy or dynamic import in App.tsx)
|
||||
const lazyEntryBasenames = new Set([
|
||||
'CreateWizard.tsx',
|
||||
'SettingsModal.tsx',
|
||||
// 网络设置仅随延迟加载的 SettingsModal 进入,使用同一语言域。
|
||||
'VMNetworkSettings.tsx',
|
||||
// 由新建向导和网络设置两个延迟入口共用。
|
||||
'NpcapDependency.tsx',
|
||||
'AffinityDialog.tsx',
|
||||
'Setup.tsx',
|
||||
'RuntimeOnline.tsx',
|
||||
'HostView.tsx',
|
||||
'ImagesPage.tsx',
|
||||
'InstallersPage.tsx',
|
||||
'PluginsPage.tsx',
|
||||
'PluginMarket.tsx',
|
||||
'PluginParts.tsx',
|
||||
'AppSettingsPage.tsx',
|
||||
'AboutPage.tsx',
|
||||
'PluginPanelFrame.tsx',
|
||||
'SchemaForm.tsx',
|
||||
'optimizations.ts',
|
||||
// 仅由延迟加载的 AppSettingsPage、HostView、Setup 共用,自带 settings.gen 域注册。
|
||||
'hypervisor.ts',
|
||||
])
|
||||
|
||||
for (const file of walkFiles(srcDir, ['.ts', '.tsx'])) {
|
||||
const rel = path.relative(srcDir, file).replace(/\\/g, '/')
|
||||
if (rel.startsWith('i18n/')) continue
|
||||
const base = path.basename(file)
|
||||
const src = fs.readFileSync(file, 'utf8')
|
||||
|
||||
// Match string literals passed to t(..., 'key'), tr('key'), labelKey: 'key', detailKey: 'key', titleKey: 'key', descKey: 'key'
|
||||
const referencedLazyDomains = new Set()
|
||||
const callMatches = [
|
||||
...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g),
|
||||
...src.matchAll(/\b(?:labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g),
|
||||
]
|
||||
for (const m of callMatches) {
|
||||
const dom = keyToDomain.get(m[1])
|
||||
if (dom && lazyDomains.includes(dom)) {
|
||||
referencedLazyDomains.add(`${dom}:${m[1]}`)
|
||||
for (const entry of entries) {
|
||||
const modules = [...loadedWith(entry, imports)].filter((file) => !path.relative(srcDir, file).startsWith('i18n'))
|
||||
const registered = new Set()
|
||||
for (const file of modules) {
|
||||
for (const m of fs.readFileSync(file, 'utf8').matchAll(/i18n\/domains\/(\w+)\.gen/g)) registered.add(m[1])
|
||||
}
|
||||
for (const file of modules) {
|
||||
const src = fs.readFileSync(file, 'utf8')
|
||||
const keys = [
|
||||
...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g),
|
||||
...src.matchAll(/\b(?:label|labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g),
|
||||
].map((m) => m[1])
|
||||
for (const key of keys) {
|
||||
const dom = keyToDomain.get(key)
|
||||
assert.ok(
|
||||
!dom || registered.has(dom),
|
||||
`${path.relative(srcDir, file)} uses ${dom} key "${key}", but the chunk of ${path.relative(srcDir, entry)} never imports i18n/domains/${dom}.gen`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (referencedLazyDomains.size === 0) continue
|
||||
|
||||
assert.ok(
|
||||
lazyEntryBasenames.has(base),
|
||||
`Eager module ${rel} references lazy domain keys (${[...referencedLazyDomains].join(', ')})! Either move keys to core/vm or lazy-load the module.`,
|
||||
)
|
||||
|
||||
for (const item of referencedLazyDomains) {
|
||||
const [dom, key] = item.split(':')
|
||||
// Sub-dialogs rendered exclusively inside lazy parent chunks inherit their parent's domain registration
|
||||
if (base === 'AffinityDialog.tsx' && dom === 'settings') continue
|
||||
if (base === 'RuntimeOnline.tsx' && (dom === 'wizard' || dom === 'settings')) continue
|
||||
assert.match(
|
||||
src,
|
||||
new RegExp(`i18n/domains/${dom}\\.gen`),
|
||||
`Module ${rel} uses ${dom} key "${key}" without importing i18n/domains/${dom}.gen`,
|
||||
)
|
||||
}
|
||||
}
|
||||
const eager = loadedWith(path.join(srcDir, 'main.tsx'), imports)
|
||||
for (const dom of lazyDomains) {
|
||||
assert.ok(!eager.has(path.join(srcDir, 'i18n', 'domains', `${dom}.gen.ts`)), `the ${dom} texts must not load with the main window`)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// Rejects import cycles in src/, type imports included: two files that import
|
||||
// each other are one module split in the wrong place.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import ts from 'typescript'
|
||||
|
||||
const src = path.resolve(import.meta.dirname, '..', 'src')
|
||||
const rel = (file) => path.relative(src, file).split(path.sep).join('/')
|
||||
|
||||
function importGraph() {
|
||||
const files = fs.readdirSync(src, { recursive: true })
|
||||
.filter((name) => /\.tsx?$/.test(name))
|
||||
.map((name) => path.join(src, name))
|
||||
const known = new Set(files)
|
||||
return new Map(files.map((file) => {
|
||||
const { importedFiles } = ts.preProcessFile(fs.readFileSync(file, 'utf8'), true, true)
|
||||
const targets = importedFiles
|
||||
.filter(({ fileName }) => fileName.startsWith('.'))
|
||||
.map(({ fileName }) => path.resolve(path.dirname(file), fileName))
|
||||
.map((base) => ['', '.ts', '.tsx', `${path.sep}index.ts`].map((ext) => base + ext).find((p) => known.has(p)))
|
||||
.filter(Boolean)
|
||||
return [file, targets]
|
||||
}))
|
||||
}
|
||||
|
||||
test('source modules do not import each other in a cycle', () => {
|
||||
const graph = importGraph()
|
||||
assert.ok(graph.size > 50, `expected to scan src/, found ${graph.size} files`)
|
||||
const done = new Set()
|
||||
const cycles = []
|
||||
const visit = (file, trail) => {
|
||||
const start = trail.indexOf(file)
|
||||
if (start >= 0) {
|
||||
cycles.push([...trail.slice(start), file].map(rel).join(' -> '))
|
||||
return
|
||||
}
|
||||
if (done.has(file)) return
|
||||
for (const next of graph.get(file)) visit(next, [...trail, file])
|
||||
done.add(file)
|
||||
}
|
||||
for (const file of graph.keys()) visit(file, [])
|
||||
assert.deepEqual(cycles, [])
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
// Rejects classes in app.css that no source file uses. A class built from a
|
||||
// template such as `status-${kind}` counts as used by its prefix.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
const src = path.resolve(import.meta.dirname, '..', 'src')
|
||||
|
||||
test('every class in app.css is used', () => {
|
||||
const code = fs.readdirSync(src, { recursive: true })
|
||||
.filter((name) => /\.tsx?$/.test(name))
|
||||
.map((name) => fs.readFileSync(path.join(src, name), 'utf8'))
|
||||
.join('\n')
|
||||
const css = fs.readFileSync(path.join(src, 'styles', 'app.css'), 'utf8')
|
||||
.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
.replace(/url\([^)]*\)|"[^"]*"/g, '')
|
||||
|
||||
const words = new Set(code.match(/[A-Za-z_][\w-]*/g))
|
||||
const prefixes = [...code.matchAll(/([A-Za-z][\w-]*-)\$\{/g)].map((m) => m[1])
|
||||
const classes = new Set([...css.matchAll(/\.([A-Za-z_][\w-]*)/g)].map((m) => m[1]))
|
||||
assert.ok(classes.size > 300, `found only ${classes.size} classes in app.css`)
|
||||
assert.deepEqual([...classes].filter((c) => !words.has(c) && !prefixes.some((p) => c.startsWith(p))), [])
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
// Rejects exports in src/ that no other file uses: dead code, or an export
|
||||
// keyword that only widens a module's interface.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import ts from 'typescript'
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..')
|
||||
|
||||
function findUnusedExports() {
|
||||
const { config } = ts.readConfigFile(path.join(root, 'tsconfig.json'), ts.sys.readFile)
|
||||
const { fileNames, options } = ts.parseJsonConfigFileContent(config, ts.sys, root)
|
||||
const service = ts.createLanguageService({
|
||||
...ts.sys,
|
||||
getCompilationSettings: () => options,
|
||||
getScriptFileNames: () => fileNames,
|
||||
getScriptVersion: () => '1',
|
||||
getScriptSnapshot: (file) => (fs.existsSync(file) ? ts.ScriptSnapshot.fromString(fs.readFileSync(file, 'utf8')) : undefined),
|
||||
getCurrentDirectory: () => root,
|
||||
getDefaultLibFileName: ts.getDefaultLibFilePath,
|
||||
})
|
||||
// The test and contract scripts import src modules or read them as text. A
|
||||
// name counts as used only in a script that also names its module.
|
||||
const scripts = fs.readdirSync(import.meta.dirname)
|
||||
.filter((name) => name !== path.basename(import.meta.filename))
|
||||
.map((name) => fs.readFileSync(path.join(import.meta.dirname, name), 'utf8'))
|
||||
|
||||
const unused = []
|
||||
for (const file of fileNames) {
|
||||
// bridgeContract.ts also documents the message types for plugin authors.
|
||||
if (file.endsWith('.gen.ts') || file.endsWith('/bridgeContract.ts')) continue
|
||||
const source = service.getProgram().getSourceFile(file)
|
||||
const module = path.relative(path.join(root, 'src'), file).split(path.sep).join('/').replace(/(\/index)?\.tsx?$/, '')
|
||||
const users = scripts.filter((text) => text.includes(`'./${module}'`) || text.includes(`'${path.basename(file)}'`))
|
||||
for (const statement of source.statements) {
|
||||
if (!ts.canHaveModifiers(statement) || !ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) continue
|
||||
const names = ts.isVariableStatement(statement)
|
||||
? statement.declarationList.declarations.map((d) => d.name).filter(ts.isIdentifier)
|
||||
: [statement.name].filter(Boolean)
|
||||
for (const name of names) {
|
||||
if (users.some((text) => new RegExp(`\\b${name.text}\\b`).test(text))) continue
|
||||
const references = (service.findReferences(file, name.getStart(source)) ?? []).flatMap((r) => r.references)
|
||||
if (references.every((r) => r.fileName === file)) {
|
||||
unused.push(`${path.relative(root, file)}: ${name.text}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { unused, files: fileNames.length }
|
||||
}
|
||||
|
||||
test('every export in src/ has a user outside its own file', () => {
|
||||
const { unused, files } = findUnusedExports()
|
||||
assert.ok(files > 50, `expected to scan src/, found ${files} files`)
|
||||
assert.deepEqual(unused, [])
|
||||
})
|
||||
+116
-360
@@ -6,35 +6,38 @@ import { ElevationDialog } from './components/ElevationDialog'
|
||||
import { CloneDialog } from './components/CloneDialog'
|
||||
import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog'
|
||||
import { SendTextDialog } from './components/SendTextDialog'
|
||||
import type { ThemeMode } from './components/AppSettingsPage'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { TitleMenus } from './components/TitleMenus'
|
||||
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
|
||||
import { UpdateCapsule } from './components/UpdateCapsule'
|
||||
import { DataRootReadOnly } from './components/DataRootReadOnly'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
import { PluginViewHost } from './components/PluginViewHost'
|
||||
import { locText } from './components/SchemaForm'
|
||||
import { VMAction, VMBusyAction, VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
|
||||
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
|
||||
import { LogLine, appendLog } from './lib/logs'
|
||||
import { macOSMajor } from './macos/macosRelease'
|
||||
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine'
|
||||
import type { UIStateSnapshot } from './lib/uiSdk'
|
||||
import { hasVisibleDialog } from './lib/dialogState'
|
||||
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
|
||||
import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
|
||||
import { useAppearance } from './lib/useAppearance'
|
||||
import { useAppUpdate } from './lib/useAppUpdate'
|
||||
import { useFileDrop } from './lib/useFileDrop'
|
||||
import { useThemeEvents } from './lib/useThemeEvents'
|
||||
import { useVMBusy } from './lib/useVMBusy'
|
||||
import { vmRefKey } from './lib/vmRef'
|
||||
import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter'
|
||||
import { publishPluginHostEvent } from './lib/pluginViewEvents'
|
||||
import { buildSafePluginAssetURL } from './lib/pluginAssets'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
|
||||
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types'
|
||||
import { Button, Tip, TooltipProvider } from './ui/controls'
|
||||
import { ConfirmDialog, Modal } from './ui/dialog'
|
||||
import { Toaster, useToasts } from './ui/toast'
|
||||
import { errorToast, Toaster, useToasts } from './ui/toast'
|
||||
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
|
||||
import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails'
|
||||
import { api, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails'
|
||||
|
||||
// Opened on demand, so each is its own chunk and stays out of the startup
|
||||
// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and
|
||||
@@ -47,6 +50,7 @@ const HostView = lazy(() => import('./components/HostView').then((m) => ({ defau
|
||||
const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage })))
|
||||
const InstallersPage = lazy(() => import('./macos/InstallersPage').then((m) => ({ default: m.InstallersPage })))
|
||||
const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage })))
|
||||
const PluginViewHost = lazy(() => import('./components/PluginViewHost').then((m) => ({ default: m.PluginViewHost })))
|
||||
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
|
||||
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
|
||||
|
||||
@@ -83,17 +87,6 @@ const failKey: Record<VMBusyAction, I18nKey> = {
|
||||
export const App: React.FC = () => {
|
||||
const [state, setState] = useState<AppState | null>(null)
|
||||
const [selected, setSelectedPage] = useState<string>(HOST_ID)
|
||||
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(null)
|
||||
// Check for a new release once the app is up, then every 6 hours, so the
|
||||
// sidebar's update button shows up without opening the About page.
|
||||
const stateReady = !!state
|
||||
useEffect(() => {
|
||||
if (!stateReady) return
|
||||
const check = () => { api.CheckAppUpdate(false).then(setAppUpdate).catch((e) => console.warn('[app] CheckAppUpdate failed:', e)) }
|
||||
check()
|
||||
const id = window.setInterval(check, 6 * 60 * 60 * 1000)
|
||||
return () => window.clearInterval(id)
|
||||
}, [stateReady])
|
||||
const [detail, setDetail] = useState<VMDetail | null>(null)
|
||||
// GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail).
|
||||
const [vmInfoLoaded, setVMInfoLoaded] = useState<VMInfo | null>(null)
|
||||
@@ -110,26 +103,8 @@ export const App: React.FC = () => {
|
||||
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState<Record<string, VMBusyAction>>({})
|
||||
const busyOpsRef = useRef<Map<string, Map<number, VMBusyAction>>>(new Map())
|
||||
const nextBusyTokenRef = useRef(0)
|
||||
const [dropping, setDropping] = useState(false)
|
||||
const vmBusy = useVMBusy()
|
||||
const [loadError, setLoadError] = useState('')
|
||||
const [themeMode, setThemeModeState] = useState<ThemeMode>(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem('reims-go-theme')
|
||||
if (saved === 'dark' || saved === 'light') return saved
|
||||
} catch (e) {
|
||||
console.warn('[app] read theme preference failed:', e)
|
||||
}
|
||||
return 'system'
|
||||
})
|
||||
const [sysDark, setSysDark] = useState<boolean>(() =>
|
||||
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches,
|
||||
)
|
||||
const [reducedMotion, setReducedMotion] = useState<boolean>(() =>
|
||||
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches,
|
||||
)
|
||||
const [pluginUI, setPluginUI] = useState<PluginUIContributions | null>(null)
|
||||
const [pluginViewState, setPluginViewState] = useState<PluginViewState>(emptyPluginViewState)
|
||||
const [pluginViewMeta, setPluginViewMeta] = useState<Record<string, { title?: string; badge?: { text: string; tone: string } }>>({})
|
||||
@@ -150,50 +125,7 @@ export const App: React.FC = () => {
|
||||
: activeThemeContrib
|
||||
? (activeThemeContrib.appearance === 'light' || activeThemeContrib.appearance === 'dark' ? activeThemeContrib.appearance : 'both')
|
||||
: 'light'
|
||||
const canLight = themeAppearanceCap === 'both' || themeAppearanceCap === 'light'
|
||||
const canDark = themeAppearanceCap === 'both' || themeAppearanceCap === 'dark'
|
||||
const theme: 'light' | 'dark' = !canDark ? 'light' : !canLight ? 'dark' : (themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode)
|
||||
const effectiveThemeMode: ThemeMode = !canDark ? 'light' : !canLight ? 'dark' : themeMode
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme
|
||||
events.emitTheme(theme)
|
||||
}, [theme])
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full'
|
||||
}, [reducedMotion])
|
||||
|
||||
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)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia?.('(prefers-reduced-motion: reduce)')
|
||||
if (!mq) return
|
||||
const onChange = (e: MediaQueryListEvent) => setReducedMotion(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 (e) {
|
||||
console.warn('[app] persist theme preference failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleTheme = () => {
|
||||
if (!canLight || !canDark) return
|
||||
setThemeMode(theme === 'light' ? 'dark' : 'light')
|
||||
}
|
||||
const { theme, themeMode, canLight, canDark, setThemeMode, reducedMotion } = useAppearance(themeAppearanceCap)
|
||||
|
||||
// Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user.
|
||||
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => {
|
||||
@@ -356,23 +288,24 @@ export const App: React.FC = () => {
|
||||
const activePluginView = routedView && viewAvailable(routedView, pluginViewState.route?.vm) ? routedView : undefined
|
||||
const activePluginRoute = activePluginView ? pluginViewState.route : null
|
||||
const renderPluginView = (route: PluginViewRoute, view: ViewContribution, dialog = false) => (
|
||||
<PluginViewHost
|
||||
key={`${pluginViewKey(route)}:${route.vm ?? ''}:${dialog ? 'dialog' : 'page'}`}
|
||||
view={view}
|
||||
locale={locale}
|
||||
appearance={theme}
|
||||
assetToken={pluginUI?.asset_token ?? ''}
|
||||
vm={route.vm}
|
||||
dialog={dialog}
|
||||
metadata={pluginViewMeta[pluginViewKey(route)]}
|
||||
onMetadata={(metadata) => updateViewMetadata(view, metadata)}
|
||||
onOpenView={openView}
|
||||
onCloseView={dialog ? () => {
|
||||
setPluginViewState((current) => closePluginDialog(current, route))
|
||||
return { closed: true }
|
||||
} : closeView}
|
||||
onNavigate={navigateHost}
|
||||
/>
|
||||
<Suspense key={`${pluginViewKey(route)}:${route.vm ?? ''}:${dialog ? 'dialog' : 'page'}`} fallback={null}>
|
||||
<PluginViewHost
|
||||
view={view}
|
||||
locale={locale}
|
||||
appearance={theme}
|
||||
assetToken={pluginUI?.asset_token ?? ''}
|
||||
vm={route.vm}
|
||||
dialog={dialog}
|
||||
metadata={pluginViewMeta[pluginViewKey(route)]}
|
||||
onMetadata={(metadata) => updateViewMetadata(view, metadata)}
|
||||
onOpenView={openView}
|
||||
onCloseView={dialog ? () => {
|
||||
setPluginViewState((current) => closePluginDialog(current, route))
|
||||
return { closed: true }
|
||||
} : closeView}
|
||||
onNavigate={navigateHost}
|
||||
/>
|
||||
</Suspense>
|
||||
)
|
||||
const renderVMTabs = () => {
|
||||
if (!selectedVM) return null
|
||||
@@ -434,9 +367,9 @@ export const App: React.FC = () => {
|
||||
let live = true
|
||||
for (const vm of vms) {
|
||||
const key = vmRefKey(vm)
|
||||
api.GetVMNoteWithDriver(vm.driver_id ?? '', vm.name)
|
||||
api.GetVMNote(vm.driver_id ?? '', vm.name)
|
||||
.then((n) => { if (live) setDisplayNames((m) => ({ ...m, [key]: (n ?? '').trim() })) })
|
||||
.catch((e) => console.warn('[app] GetVMNoteWithDriver failed:', key, e))
|
||||
.catch((e) => console.warn('[app] GetVMNote failed:', key, e))
|
||||
}
|
||||
return () => { live = false }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -557,53 +490,11 @@ export const App: React.FC = () => {
|
||||
: 'stable'
|
||||
const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => {
|
||||
await api.SetAppUpdateChannel(ch)
|
||||
setDismissedUpdate('')
|
||||
try { localStorage.removeItem('reims-go-update-dismissed') } catch (e) { console.warn('[app] clear dismissed update failed:', e) }
|
||||
await refresh()
|
||||
try {
|
||||
setAppUpdate(await api.CheckAppUpdate(true))
|
||||
} catch (e) {
|
||||
setAppUpdate(null)
|
||||
throw e
|
||||
}
|
||||
await update.recheck()
|
||||
}
|
||||
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
|
||||
|
||||
// In-app update: one task per release; its state drives the sidebar capsule
|
||||
// and the About page alike.
|
||||
const updateTask = appUpdate?.has_update
|
||||
? Object.values(taskMap)
|
||||
.filter((x) => x.kind === 'app-update' && x.subject === appUpdate.latest)
|
||||
.sort((a, b) => b.updated_at - a.updated_at)[0] ?? null
|
||||
: null
|
||||
const updatePhase: UpdatePhase = !appUpdate?.has_update ? 'none'
|
||||
: updateTask?.status === 'running' ? 'downloading'
|
||||
: updateTask?.status === 'done' ? 'ready'
|
||||
: updateTask?.status === 'failed' ? 'failed'
|
||||
: 'available'
|
||||
const [dismissedUpdate, setDismissedUpdate] = useState<string>(() => {
|
||||
try { return localStorage.getItem('reims-go-update-dismissed') ?? '' } catch { return '' }
|
||||
})
|
||||
const dismissUpdate = () => {
|
||||
if (!appUpdate) return
|
||||
setDismissedUpdate(appUpdate.latest)
|
||||
try { localStorage.setItem('reims-go-update-dismissed', appUpdate.latest) } catch (e) { console.warn('[app] persist dismissed update failed:', e) }
|
||||
}
|
||||
const [confirmUpdate, setConfirmUpdate] = useState(false)
|
||||
const [installingUpdate, setInstallingUpdate] = useState(false)
|
||||
const downloadUpdate = () => { api.DownloadAppUpdate().catch((e) => fail(tr('updateFailed'), e)) }
|
||||
const runInstallUpdate = () => {
|
||||
setConfirmUpdate(false)
|
||||
setInstallingUpdate(true)
|
||||
api.InstallAppUpdate().catch((e) => {
|
||||
setInstallingUpdate(false)
|
||||
fail(tr('updateFailed'), e)
|
||||
})
|
||||
}
|
||||
// Restarting leaves VMs running but pauses the host-guest bridges: say so first.
|
||||
const installUpdate = () => { if (runningVMCount > 0) setConfirmUpdate(true); else runInstallUpdate() }
|
||||
const showUpdateCard = updatePhase !== 'none' && !(updatePhase === 'available' && dismissedUpdate === appUpdate?.latest)
|
||||
|
||||
// One toast after an update restart: the version changed since the last run.
|
||||
useEffect(() => {
|
||||
const v = state?.app_version
|
||||
@@ -638,7 +529,7 @@ export const App: React.FC = () => {
|
||||
|
||||
// UI Contract v2 read-only document state attributes.
|
||||
const currentView = showSetup ? 'setup' : activePluginRoute?.location === 'sidebar' ? 'plugins' : activePluginRoute?.location === 'settings' ? 'settings' : activePluginRoute?.location === 'vm.tab' ? 'vm' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm'
|
||||
const isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0
|
||||
const isBusyAny = Object.keys(vmBusy.busy).length > 0 || runningTasks > 0
|
||||
const hasAnyError = unseenErrors > 0 || !!loadError
|
||||
const uiStateRef = useRef<UIStateSnapshot>({
|
||||
appearance: theme,
|
||||
@@ -679,43 +570,7 @@ export const App: React.FC = () => {
|
||||
notifyInteractiveThemeState(uiStateRef.current)
|
||||
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme, reducedMotion])
|
||||
|
||||
// UI SDK event stream (ui-contract UI_CONTRACT_SDK_EVENTS). emitThemeEvent is
|
||||
// a no-op unless an interactive theme is loaded; payloads carry no paths.
|
||||
const selectedRef = selectedVM ? vmRefKey(selectedVM) : ''
|
||||
useEffect(() => {
|
||||
emitThemeEvent('view.changed', { view: currentView, vm: selectedRef })
|
||||
}, [currentView, selectedRef])
|
||||
const vmStatesRef = useRef<Record<string, string> | null>(null)
|
||||
useEffect(() => {
|
||||
const next: Record<string, string> = {}
|
||||
for (const v of vms) next[vmRefKey(v)] = state?.transitions[vmRefKey(v)] ?? v.state
|
||||
const prev = vmStatesRef.current
|
||||
vmStatesRef.current = next
|
||||
if (!prev) return
|
||||
for (const v of vms) {
|
||||
const key = vmRefKey(v)
|
||||
if (prev[key] !== undefined && prev[key] !== next[key]) {
|
||||
const payload = { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] }
|
||||
emitThemeEvent('vm.stateChanged', payload)
|
||||
publishPluginHostEvent('vm.stateChanged', payload)
|
||||
}
|
||||
}
|
||||
}, [vms, state?.transitions])
|
||||
const taskStatesRef = useRef<Record<string, { status: string; percent: number }> | null>(null)
|
||||
useEffect(() => {
|
||||
const prev = taskStatesRef.current
|
||||
const next: Record<string, { status: string; percent: number }> = {}
|
||||
for (const t of Object.values(taskMap)) next[t.id] = { status: t.status, percent: t.percent }
|
||||
taskStatesRef.current = next
|
||||
if (!prev) return
|
||||
for (const t of Object.values(taskMap)) {
|
||||
const was = prev[t.id]
|
||||
const info = { id: t.id, kind: t.kind, vm: t.vm ?? '', percent: t.percent }
|
||||
if (!was && t.status === 'running') emitThemeEvent('task.started', info)
|
||||
else if (was?.status === 'running' && t.status === 'running' && was.percent !== t.percent) emitThemeEvent('task.progress', info)
|
||||
if ((!was || was.status === 'running') && t.status !== 'running') emitThemeEvent('task.finished', { ...info, status: t.status })
|
||||
}
|
||||
}, [taskMap])
|
||||
useThemeEvents({ view: currentView, selectedVM: selectedVM ? vmRefKey(selectedVM) : '', vms, transitions: state?.transitions, tasks: taskMap })
|
||||
|
||||
// Refresh contributions together with the active theme after registry changes.
|
||||
useEffect(() => {
|
||||
@@ -742,7 +597,7 @@ export const App: React.FC = () => {
|
||||
openSettings: () => setSelected(SETTINGS_ID),
|
||||
focusVMWindow: (vmName) => {
|
||||
const vm = vmsRef.current.find((v) => vmRefKey(v) === vmName) ?? vmsRef.current.find((v) => v.name === vmName)
|
||||
void api.FocusVMWindowWithDriver(vm?.driver_id ?? '', vm?.name ?? vmName).catch((e) => console.warn('[theme] FocusVMWindowWithDriver failed:', vmName, e))
|
||||
void api.FocusVMWindow(vm?.driver_id ?? '', vm?.name ?? vmName).catch((e) => console.warn('[theme] FocusVMWindow failed:', vmName, e))
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -765,7 +620,7 @@ export const App: React.FC = () => {
|
||||
try {
|
||||
const logVM = name === selectedVM?.name ? selectedVM : vms.find((v) => v.name === name)
|
||||
const logDriverID = logVM?.driver_id ?? ''
|
||||
const text = await api.ReadVMLogsWithDriver(logDriverID, name, serial)
|
||||
const text = await api.ReadVMLogs(logDriverID, name, serial)
|
||||
if (serial) setSerialLog(text)
|
||||
else setQemuLog(text)
|
||||
} catch (e) {
|
||||
@@ -778,67 +633,18 @@ export const App: React.FC = () => {
|
||||
const loadQemu = (name?: string) => loadVMLog(false, name)
|
||||
|
||||
const fail = (title: string, e: unknown) => {
|
||||
const parsed = parseAppError(e)
|
||||
toasts.push({
|
||||
kind: 'error',
|
||||
title,
|
||||
description: parsed.summary,
|
||||
errorCode: parsed.code,
|
||||
rawDetail: parsed.rawDetail,
|
||||
detailsLabel: tr('errRawDetailsToggle'),
|
||||
copyDetailsLabel: tr('errCopyDetails'),
|
||||
...errorToast(locale, title, e),
|
||||
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
|
||||
})
|
||||
}
|
||||
const update = useAppUpdate({ ready: !!state, tasks: taskMap, runningVMCount, onError: (e) => fail(tr('updateFailed'), e) })
|
||||
onHostDropAckRef.current = (ack) => {
|
||||
if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '')
|
||||
}
|
||||
|
||||
// Busy state is keyed by VM reference (driver and name), so same-name VMs of
|
||||
// different drivers never block each other.
|
||||
const activeVMBusy = (key: string): VMBusyAction | undefined => {
|
||||
const ops = busyOpsRef.current.get(key)
|
||||
if (!ops || ops.size === 0) return undefined
|
||||
let latest: VMBusyAction | undefined
|
||||
for (const act of ops.values()) latest = act
|
||||
return latest
|
||||
}
|
||||
|
||||
const syncBusyState = () => {
|
||||
const next: Record<string, VMBusyAction> = Object.create(null)
|
||||
for (const [vmName, ops] of busyOpsRef.current) {
|
||||
let latest: VMBusyAction | undefined
|
||||
for (const act of ops.values()) latest = act
|
||||
if (latest) next[vmName] = latest
|
||||
}
|
||||
setBusy(next)
|
||||
}
|
||||
|
||||
const beginVMBusy = (name: string, action: VMBusyAction): number | null => {
|
||||
const ops = busyOpsRef.current.get(name)
|
||||
if (ops && ops.size > 0) {
|
||||
if (action !== 'forceStop') return null
|
||||
for (const act of ops.values()) {
|
||||
if (act === 'forceStop') return null
|
||||
}
|
||||
}
|
||||
const token = ++nextBusyTokenRef.current
|
||||
const vmOps = ops ?? new Map<number, VMBusyAction>()
|
||||
vmOps.set(token, action)
|
||||
busyOpsRef.current.set(name, vmOps)
|
||||
syncBusyState()
|
||||
return token
|
||||
}
|
||||
|
||||
const endVMBusy = (name: string, token: number) => {
|
||||
const ops = busyOpsRef.current.get(name)
|
||||
if (!ops || !ops.delete(token)) return
|
||||
if (ops.size === 0) busyOpsRef.current.delete(name)
|
||||
syncBusyState()
|
||||
}
|
||||
|
||||
const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise<void>, okTitle?: string) => {
|
||||
const token = beginVMBusy(name, action)
|
||||
const token = vmBusy.begin(name, action)
|
||||
if (token === null) return
|
||||
try {
|
||||
await fn()
|
||||
@@ -847,14 +653,14 @@ export const App: React.FC = () => {
|
||||
} catch (e) {
|
||||
fail(tr(failKey[action]), e)
|
||||
} finally {
|
||||
endVMBusy(name, token)
|
||||
vmBusy.end(name, token)
|
||||
}
|
||||
}
|
||||
|
||||
// Paste as keystrokes: the backend refuses text a US keyboard can't type
|
||||
// (ErrNotTypeable in type_flow.go), which gets a message of its own.
|
||||
const typeInto = async (busyKey: string, fn: () => Promise<number>) => {
|
||||
const token = beginVMBusy(busyKey, 'type')
|
||||
const token = vmBusy.begin(busyKey, 'type')
|
||||
if (token === null) return
|
||||
try {
|
||||
const n = await fn()
|
||||
@@ -866,7 +672,7 @@ export const App: React.FC = () => {
|
||||
fail(tr('failType'), e)
|
||||
}
|
||||
} finally {
|
||||
endVMBusy(busyKey, token)
|
||||
vmBusy.end(busyKey, token)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -884,7 +690,7 @@ export const App: React.FC = () => {
|
||||
return
|
||||
}
|
||||
}
|
||||
const token = beginVMBusy(busyKey, 'attachInstaller')
|
||||
const token = vmBusy.begin(busyKey, 'attachInstaller')
|
||||
if (token === null) return
|
||||
try {
|
||||
const fileName = await api.AttachInstaller(name, picked)
|
||||
@@ -894,7 +700,7 @@ export const App: React.FC = () => {
|
||||
})
|
||||
await refresh()
|
||||
} finally {
|
||||
endVMBusy(busyKey, token)
|
||||
vmBusy.end(busyKey, token)
|
||||
}
|
||||
} catch (e) {
|
||||
fail(tr('failAttachInstaller'), e)
|
||||
@@ -903,7 +709,7 @@ export const App: React.FC = () => {
|
||||
|
||||
// Hosted VMs have no window: the primary action is their best ready endpoint.
|
||||
const openEndpoint = (vm: VMListItem, kind: string) => {
|
||||
api.OpenVMEndpointWithDriver(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
|
||||
api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e))
|
||||
}
|
||||
const openPrimaryEndpoint = (vm: VMListItem) => {
|
||||
const { primary } = splitEndpoints(vm.endpoints)
|
||||
@@ -931,7 +737,7 @@ export const App: React.FC = () => {
|
||||
if (actionVM) openPrimaryEndpoint(actionVM)
|
||||
return
|
||||
}
|
||||
const activeBusy = activeVMBusy(key)
|
||||
const activeBusy = vmBusy.current(key)
|
||||
if (
|
||||
activeBusy
|
||||
&& action !== 'openFolder'
|
||||
@@ -941,21 +747,21 @@ export const App: React.FC = () => {
|
||||
return
|
||||
}
|
||||
switch (action) {
|
||||
case 'start': return runVMAction(key, action, () => api.StartVMWithDriver(actionDriverID, name))
|
||||
case 'suspend': return runVMAction(key, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name }))
|
||||
case 'resume': return runVMAction(key, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name }))
|
||||
case 'start': return runVMAction(key, action, () => api.StartVM(actionDriverID, name))
|
||||
case 'suspend': return runVMAction(key, action, () => api.SuspendVM(actionDriverID, name), tr('toastSuspended', { name }))
|
||||
case 'resume': return runVMAction(key, action, () => api.ResumeVM(actionDriverID, name), tr('toastResumed', { name }))
|
||||
case 'discardSuspend': return setDiscardSuspendTarget(key)
|
||||
case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e))
|
||||
case 'focus': return api.FocusVMWindow(actionDriverID, name).catch((e) => fail(tr('failFocus'), e))
|
||||
case 'fullscreen':
|
||||
return runVMAction(key, action, async () => {
|
||||
const isFullscreen = await api.ToggleVMFullscreenWithDriver(actionDriverID, name)
|
||||
refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen })
|
||||
const isFullscreen = await api.ToggleVMFullscreen(actionDriverID, name)
|
||||
refreshVMStats(actionDriverID, name, { window_fullscreen: isFullscreen })
|
||||
})
|
||||
case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied'))
|
||||
case 'stop': return runVMAction(key, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(key, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(key, action, () => api.RestartVMWithDriver(actionDriverID, name))
|
||||
case 'eject': return runVMAction(key, action, () => api.EjectInstallerWithDriver(actionDriverID, name), tr('toastEjected'))
|
||||
case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshot(actionDriverID, name), tr('toastScreenshotCopied'))
|
||||
case 'stop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, true), tr('toastStopped', { name }))
|
||||
case 'restart': return runVMAction(key, action, () => api.RestartVM(actionDriverID, name))
|
||||
case 'eject': return runVMAction(key, action, () => api.EjectInstaller(actionDriverID, name), tr('toastEjected'))
|
||||
case 'finishInstall': return runVMAction(key, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
|
||||
case 'enterRecovery': return runVMAction(key, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery'))
|
||||
case 'attachInstaller': return attachInstaller(key, name, isRunning)
|
||||
@@ -966,11 +772,11 @@ export const App: React.FC = () => {
|
||||
case 'upgradeNVMe':
|
||||
return runVMAction(key, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady'))
|
||||
case 'exportDiagnostics':
|
||||
return runVMAction(key, action, async () => { await api.ExportDiagnosticsWithDriver(actionDriverID, name) }, tr('toastDiagExported'))
|
||||
return runVMAction(key, action, async () => { await api.ExportDiagnostics(actionDriverID, name) }, tr('toastDiagExported'))
|
||||
case 'cloneVM':
|
||||
if (!features.clone) return
|
||||
return setCloneSource({ name, driverID: actionDriverID })
|
||||
case 'type': return typeInto(key, () => api.TypeClipboardWithDriver(actionDriverID, name))
|
||||
case 'type': return typeInto(key, () => api.TypeClipboard(actionDriverID, name))
|
||||
case 'sendText': return setSendTextTarget(key)
|
||||
case 'openFolder':
|
||||
return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e))
|
||||
@@ -1004,7 +810,7 @@ export const App: React.FC = () => {
|
||||
const vm = findVM(name)
|
||||
if (!vm) return
|
||||
const key = vmRefKey(vm)
|
||||
if (activeVMBusy(key)) return
|
||||
if (vmBusy.current(key)) return
|
||||
const st = state?.transitions[key] ?? vm.state
|
||||
if (st === 'stopped') onVMActionFor(key, 'start', false)
|
||||
else if (st === 'suspended') onVMActionFor(key, 'resume', false)
|
||||
@@ -1018,7 +824,7 @@ export const App: React.FC = () => {
|
||||
const name = targetVM?.name ?? target
|
||||
const driverID = targetVM?.driver_id ?? ''
|
||||
const key = targetVM ? vmRefKey(targetVM) : (name ?? '')
|
||||
if (name) runVMAction(key, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name }))
|
||||
if (name) runVMAction(key, 'delete', () => api.DeleteVM(driverID, name, keepFiles), tr('toastDeleted', { name }))
|
||||
}
|
||||
|
||||
const confirmDiscardSuspend = () => {
|
||||
@@ -1028,7 +834,7 @@ export const App: React.FC = () => {
|
||||
const name = targetVM?.name ?? target
|
||||
const driverID = targetVM?.driver_id ?? ''
|
||||
const key = targetVM ? vmRefKey(targetVM) : (name ?? '')
|
||||
if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { name }))
|
||||
if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspend(driverID, name), tr('toastDiscardSuspend', { name }))
|
||||
}
|
||||
|
||||
const confirmOnlineRecovery = () => {
|
||||
@@ -1045,7 +851,7 @@ export const App: React.FC = () => {
|
||||
setCloneSource(null)
|
||||
if (!src) return
|
||||
runVMAction(vmRefKey({ name: src.name, driver_id: src.driverID }), 'cloneVM', async () => {
|
||||
await api.CloneVMCoWWithDriver(src.driverID, src.name, cloneName)
|
||||
await api.CloneVMCoW(src.driverID, src.name, cloneName)
|
||||
setSelected(vmRefKey({ name: cloneName, driver_id: src.driverID }))
|
||||
}, tr('toastCloned', { name: cloneName }))
|
||||
}
|
||||
@@ -1119,17 +925,10 @@ export const App: React.FC = () => {
|
||||
})
|
||||
.catch((e) => {
|
||||
void refresh()
|
||||
const parsed = parseAppError(e)
|
||||
if (parsed.code === 'E_NETWORK_CREATE_BRIDGE_PENDING') {
|
||||
if (parseAppError(e).code === 'E_NETWORK_CREATE_BRIDGE_PENDING') {
|
||||
setSelected(name)
|
||||
toasts.push({
|
||||
kind: 'error',
|
||||
title: tr('toastCreated', { name }),
|
||||
description: parsed.summary,
|
||||
errorCode: parsed.code,
|
||||
rawDetail: parsed.rawDetail,
|
||||
detailsLabel: tr('errRawDetailsToggle'),
|
||||
copyDetailsLabel: tr('errCopyDetails'),
|
||||
...errorToast(locale, tr('toastCreated', { name }), e),
|
||||
action: { label: tr('settings'), onClick: () => {
|
||||
api.GetVMDetail(name).then((d) => { setDetail(d); setSelected(name); setShowSettings(true) }).catch((err) => fail(tr('failGeneric'), err))
|
||||
} },
|
||||
@@ -1146,13 +945,7 @@ export const App: React.FC = () => {
|
||||
return
|
||||
}
|
||||
toasts.push({
|
||||
kind: 'error',
|
||||
title: tr('failCreate', { name }),
|
||||
description: parsed.summary,
|
||||
errorCode: parsed.code,
|
||||
rawDetail: parsed.rawDetail,
|
||||
detailsLabel: tr('errRawDetailsToggle'),
|
||||
copyDetailsLabel: tr('errCopyDetails'),
|
||||
...errorToast(locale, tr('failCreate', { name }), e),
|
||||
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
|
||||
})
|
||||
})
|
||||
@@ -1175,7 +968,7 @@ export const App: React.FC = () => {
|
||||
// Global shortcuts (see docs/design-guidelines.md). Dialogs own the keyboard while open.
|
||||
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
||||
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
|
||||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate || closeDownloadsOpen || elevationQueue.length > 0
|
||||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || update.confirming || closeDownloadsOpen || elevationQueue.length > 0
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
if (appDialogOpen) return
|
||||
@@ -1218,46 +1011,17 @@ export const App: React.FC = () => {
|
||||
return () => { offRequest(); offResolved() }
|
||||
}, [])
|
||||
|
||||
// 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()
|
||||
}
|
||||
}, [])
|
||||
// Files dropped on the window go to the selected VM's shared folder.
|
||||
const dropping = useFileDrop(!!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode, (paths) => {
|
||||
if (!selectedVM) return
|
||||
api.DeliverPathsToGuest(selectedVM.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))
|
||||
})
|
||||
|
||||
return (
|
||||
<ThemeVisualsProvider payload={activeThemePayload}>
|
||||
@@ -1277,7 +1041,7 @@ export const App: React.FC = () => {
|
||||
onToggleSidebar={toggleSidebar}
|
||||
logsOpen={logsOpen}
|
||||
onToggleLogs={toggleLogs}
|
||||
themeMode={effectiveThemeMode}
|
||||
themeMode={themeMode}
|
||||
canLight={canLight}
|
||||
canDark={canDark}
|
||||
onThemeMode={setThemeMode}
|
||||
@@ -1285,7 +1049,7 @@ export const App: React.FC = () => {
|
||||
name: selectedVM.name,
|
||||
driver_id: selectedVM.driver_id,
|
||||
state: effectiveState,
|
||||
busy: Object.prototype.hasOwnProperty.call(busy, vmRefKey(selectedVM)),
|
||||
busy: vmRefKey(selectedVM) in vmBusy.busy,
|
||||
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
|
||||
canSuspend: canSuspendVM(selectedVM),
|
||||
features: selectedFeatures,
|
||||
@@ -1308,7 +1072,7 @@ export const App: React.FC = () => {
|
||||
type="button"
|
||||
className="theme-toggle"
|
||||
aria-label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}
|
||||
onClick={toggleTheme}
|
||||
onClick={() => setThemeMode(theme === 'light' ? 'dark' : 'light')}
|
||||
>
|
||||
{theme === 'light' ? <Moon size={14} aria-hidden="true" /> : <Sun size={14} aria-hidden="true" />}
|
||||
</button>
|
||||
@@ -1365,7 +1129,7 @@ export const App: React.FC = () => {
|
||||
locale={locale}
|
||||
vms={vms}
|
||||
transitions={state?.transitions ?? {}}
|
||||
busyActions={busy}
|
||||
busyActions={vmBusy.busy}
|
||||
selected={sidebarSelected}
|
||||
hostReady={hostReady}
|
||||
canSuspend={canSuspend}
|
||||
@@ -1387,19 +1151,19 @@ export const App: React.FC = () => {
|
||||
onVMContextAction={onSidebarContextAction}
|
||||
downloading={Object.values(taskMap).some(isActiveInstallerTask)}
|
||||
safeMode={state?.safe_mode}
|
||||
updateDot={!!appUpdate?.has_update}
|
||||
updateDot={!!update.info?.has_update}
|
||||
pluginViews={sidebarPluginViews}
|
||||
updateCard={showUpdateCard ? (
|
||||
updateCard={update.shown ? (
|
||||
<UpdateCapsule
|
||||
locale={locale}
|
||||
phase={installingUpdate ? 'ready' : updatePhase}
|
||||
latest={appUpdate?.latest ?? ''}
|
||||
task={updateTask}
|
||||
phase={update.installing ? 'ready' : update.phase}
|
||||
latest={update.info?.latest ?? ''}
|
||||
task={update.task}
|
||||
onOpen={() => setSelected(ABOUT_ID)}
|
||||
onDownload={downloadUpdate}
|
||||
onCancel={() => { if (updateTask) cancelTask(updateTask.id) }}
|
||||
onInstall={installUpdate}
|
||||
onDismiss={dismissUpdate}
|
||||
onDownload={update.download}
|
||||
onCancel={() => { if (update.task) cancelTask(update.task.id) }}
|
||||
onInstall={update.install}
|
||||
onDismiss={update.dismiss}
|
||||
/>
|
||||
) : null}
|
||||
/>
|
||||
@@ -1472,7 +1236,7 @@ export const App: React.FC = () => {
|
||||
vmInfo={vmInfo}
|
||||
host={state.host}
|
||||
pending={pending}
|
||||
busyAction={Object.prototype.hasOwnProperty.call(busy, vmRefKey(selectedVM)) ? busy[vmRefKey(selectedVM)] : undefined}
|
||||
busyAction={vmBusy.busy[vmRefKey(selectedVM)]}
|
||||
onAction={onVMAction}
|
||||
onPluginCommand={(pluginID, command, title) => {
|
||||
const name = selectedVM.name
|
||||
@@ -1486,15 +1250,7 @@ export const App: React.FC = () => {
|
||||
onDelete={() => setDeleteTarget(vmRefKey(selectedVM))}
|
||||
onViewLogs={() => { openLogs('serial'); loadSerial() }}
|
||||
onCopy={copy}
|
||||
onTypeText={(text) => typeInto(vmRefKey(selectedVM), () => api.TypeTextWithDriver(selectedVM.driver_id ?? '', selectedVM.name, text))}
|
||||
onToggleBorderless={(enabled) => {
|
||||
api.ToggleBorderless(selectedVM.name, enabled)
|
||||
.then(() => {
|
||||
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastBorderlessNextStart' : 'toastBorderlessUpdated') })
|
||||
return refresh()
|
||||
})
|
||||
.catch((e) => fail(tr('failGeneric'), e))
|
||||
}}
|
||||
onTypeText={(text) => typeInto(vmRefKey(selectedVM), () => api.TypeText(selectedVM.driver_id ?? '', selectedVM.name, text))}
|
||||
onTogglePreventSleep={(enabled) => {
|
||||
api.SetGuestPreventSleep(selectedVM.name, enabled)
|
||||
.then(() => {
|
||||
@@ -1523,7 +1279,7 @@ export const App: React.FC = () => {
|
||||
locale={locale}
|
||||
locales={pluginUI?.locales}
|
||||
tasks={Object.values(taskMap)}
|
||||
themeMode={effectiveThemeMode}
|
||||
themeMode={themeMode}
|
||||
canLight={canLight}
|
||||
canDark={canDark}
|
||||
pluginViews={settingsPluginViews}
|
||||
@@ -1539,14 +1295,14 @@ export const App: React.FC = () => {
|
||||
appVersion={state.app_version}
|
||||
appUpdateChannel={appUpdateChannel}
|
||||
onAppUpdateChannel={setAppUpdateChannel}
|
||||
appUpdate={appUpdate}
|
||||
onAppUpdate={setAppUpdate}
|
||||
updatePhase={updatePhase}
|
||||
updateTask={updateTask}
|
||||
installing={installingUpdate}
|
||||
onDownloadUpdate={downloadUpdate}
|
||||
onCancelUpdate={() => { if (updateTask) cancelTask(updateTask.id) }}
|
||||
onInstallUpdate={installUpdate}
|
||||
appUpdate={update.info}
|
||||
onAppUpdate={update.setInfo}
|
||||
updatePhase={update.phase}
|
||||
updateTask={update.task}
|
||||
installing={update.installing}
|
||||
onDownloadUpdate={update.download}
|
||||
onCancelUpdate={() => { if (update.task) cancelTask(update.task.id) }}
|
||||
onInstallUpdate={update.install}
|
||||
onCopy={copy}
|
||||
onError={fail}
|
||||
/>
|
||||
@@ -1616,7 +1372,7 @@ export const App: React.FC = () => {
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
driverID={selectedVM?.driver_id ?? ''}
|
||||
stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)}
|
||||
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)}
|
||||
host={state.host}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
optimizations={state.optimizations}
|
||||
@@ -1664,11 +1420,11 @@ export const App: React.FC = () => {
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{confirmUpdate && (
|
||||
{update.confirming && (
|
||||
<Modal
|
||||
title={tr('updateConfirmTitle', { v: appUpdate?.latest ?? '' })}
|
||||
title={tr('updateConfirmTitle', { v: update.info?.latest ?? '' })}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setConfirmUpdate(false)}
|
||||
onClose={() => update.cancelInstall()}
|
||||
>
|
||||
<div className="stack-2" style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
|
||||
<p style={{ margin: 0 }}>{tr('updateConfirmBody', { n: runningVMCount })}</p>
|
||||
@@ -1677,8 +1433,8 @@ export const App: React.FC = () => {
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setConfirmUpdate(false)}>{tr('cancel')}</Button>
|
||||
<Button variant="primary" onClick={runInstallUpdate}>{tr('updateRestart')}</Button>
|
||||
<Button variant="ghost" onClick={() => update.cancelInstall()}>{tr('cancel')}</Button>
|
||||
<Button variant="primary" onClick={update.confirmInstall}>{tr('updateRestart')}</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -1753,12 +1509,12 @@ export const App: React.FC = () => {
|
||||
<SendTextDialog
|
||||
locale={locale}
|
||||
vmName={sendName}
|
||||
guestToolsConnected={Boolean(latestVMStatsWithDriver(sendVM?.driver_id ?? '', sendName)?.guest_tools_connected ?? (selectedIsMacOS ? detail?.guest_tools_connected : false))}
|
||||
guestToolsConnected={Boolean(latestVMStats(sendVM?.driver_id ?? '', sendName)?.guest_tools_connected ?? (selectedIsMacOS ? detail?.guest_tools_connected : false))}
|
||||
onCancel={() => setSendTextTarget(null)}
|
||||
onConfirm={(text) => {
|
||||
const target = sendTextTarget
|
||||
setSendTextTarget(null)
|
||||
typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeTextWithDriver(sendVM?.driver_id ?? '', sendName, text))
|
||||
typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeText(sendVM?.driver_id ?? '', sendName, text))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -9,13 +9,13 @@ import { Modal } from '../ui/dialog'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { REPO_URL, siteURL } from './TitleMenus'
|
||||
import type { UpdatePhase } from './UpdateCapsule'
|
||||
import type { UpdatePhase } from '../lib/useAppUpdate'
|
||||
import { BrandMark } from '../ui/themeVisuals'
|
||||
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
|
||||
const QQ_GROUP_ID = '1136042744'
|
||||
|
||||
export type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
|
||||
type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
|
||||
@@ -100,7 +100,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
let live = true
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
api.GetVMAffinityWithDriver(driverID, vmName)
|
||||
api.GetVMAffinity(driverID, vmName)
|
||||
.then((st) => {
|
||||
if (!live) return
|
||||
setStatus(st)
|
||||
@@ -206,7 +206,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
setSaving(true)
|
||||
setErr('')
|
||||
try {
|
||||
const updated = await api.SetVMAffinityWithDriver(driverID, vmName, {
|
||||
const updated = await api.SetVMAffinity(driverID, vmName, {
|
||||
mode,
|
||||
cpus: mode === 'custom' ? selected : [],
|
||||
disable_eco_qos: disableEcoQoS,
|
||||
|
||||
@@ -10,13 +10,13 @@ import {
|
||||
splitFullscreenHotkey,
|
||||
} from '../lib/fullscreenHotkey'
|
||||
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import type { ThemeMode } from '../lib/useAppearance'
|
||||
import { AppState, Locale, ResolvedLocalePack, Task } from '../types'
|
||||
import { Button, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { PopupSelect, Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||
|
||||
type HostDNSMode = 'system' | 'doh'
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import '../i18n/domains/wizard.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, locText, parseAppError, t } from '../i18n'
|
||||
import {
|
||||
GUEST_LANG_PRESETS,
|
||||
guestLangOptions,
|
||||
MEMORY_MARKS,
|
||||
controllerLabel,
|
||||
@@ -32,7 +31,6 @@ import {
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
shortGPUName,
|
||||
splitLangLabel,
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
|
||||
|
||||
@@ -13,7 +13,7 @@ export const hasGuestArt = (family: GuestFamily): boolean => ART_FAMILIES.includ
|
||||
* names. macOS keeps its version artwork (VersionArt), so this returns null
|
||||
* for it and for an unknown family and the caller falls back to that artwork.
|
||||
*/
|
||||
export const GuestIcon: React.FC<{ family: GuestFamily; size?: number }> = ({ family, size = 15 }) => {
|
||||
const GuestIcon: React.FC<{ family: GuestFamily; size?: number }> = ({ family, size = 15 }) => {
|
||||
switch (family) {
|
||||
case 'linux':
|
||||
return <HostIcon name="guest-linux"><Terminal size={size} aria-hidden="true" /></HostIcon>
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { Disc3, Puzzle, RefreshCw } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import { ImageSourceContribution, Locale, PluginUIContributions } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { locText } from './SchemaForm'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
|
||||
export interface NativeImageSourceRenderOpts {
|
||||
interface NativeImageSourceRenderOpts {
|
||||
refreshSignal: number
|
||||
onBusyChange: (busy: boolean) => void
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from 'react'
|
||||
import { t } from '../i18n'
|
||||
import type { ParsedAppError } from '../i18n'
|
||||
import type { Locale } from '../types'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react'
|
||||
import { useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { parseAppError, t } from '../i18n'
|
||||
import type { ParsedAppError } from '../i18n'
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo, ScanReport } from '../types'
|
||||
import { Button, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api, events, MarketInstallProgress } from '../wails'
|
||||
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { locText } from './SchemaForm'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
|
||||
// Cards are revealed in pages as the feed scrolls into view.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
|
||||
import { getPluginMessageBundle, localeDir, locText, parseAppError, t } from '../i18n'
|
||||
import { Locale, PanelContribution, ViewContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { ConfirmDialog } from '../ui/dialog'
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from '../lib/pluginViewActions'
|
||||
import { buildSafePluginAssetURL } from '../lib/pluginAssets'
|
||||
import { subscribePluginHostEvents } from '../lib/pluginViewEvents'
|
||||
import { locText, SchemaForm } from './SchemaForm'
|
||||
import { SchemaForm } from './SchemaForm'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import React from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { locText, t } from '../i18n'
|
||||
import { Locale, ViewContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { locText } from './SchemaForm'
|
||||
|
||||
interface Props {
|
||||
view: ViewContribution
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import {
|
||||
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport, ViewContribution,
|
||||
} from '../types'
|
||||
@@ -16,7 +16,7 @@ import { api } from '../wails'
|
||||
import { PluginMarket } from './PluginMarket'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge } from './PluginParts'
|
||||
import { SchemaForm, locText } from './SchemaForm'
|
||||
import { SchemaForm } from './SchemaForm'
|
||||
|
||||
// Search only earns its space once the list is long enough to scan.
|
||||
const SEARCH_THRESHOLD = 12
|
||||
|
||||
@@ -5,8 +5,6 @@ import { locText, t } from '../i18n'
|
||||
import { Locale, SettingProperty, SettingsSchema } from '../types'
|
||||
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
|
||||
export { locText }
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
schema: SettingsSchema
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,14 +3,13 @@ import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { guestFamilyOf, vmFeatures } from '../lib/endpoints'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { Locale, VMAction, VMBusyAction, VMListItem } from '../types'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
import { BrandMark, HostIcon } from '../ui/themeVisuals'
|
||||
import { GuestArt, hasGuestArt } from './GuestIcon'
|
||||
import type { VMAction, VMBusyAction } from './VMPage'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
export const INSTALLERS_ID = '__installers__'
|
||||
|
||||
@@ -5,11 +5,10 @@ import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { VMFeatures, vmFeatures } from '../lib/endpoints'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { Locale } from '../types'
|
||||
import { Locale, VMAction } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
import type { ThemeMode } from './AppSettingsPage'
|
||||
import type { ThemeMode } from '../lib/useAppearance'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID } from './Sidebar'
|
||||
import { VMAction } from './VMPage'
|
||||
|
||||
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { ArrowDownToLine, RotateCw, X } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import type { UpdatePhase } from '../lib/useAppUpdate'
|
||||
import { Locale, Task } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
|
||||
/** Where an available update is: offered, downloading, verified and ready, or failed. */
|
||||
export type UpdatePhase = 'none' | 'available' | 'downloading' | 'ready' | 'failed'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { parseAppError, t } from '../i18n'
|
||||
import type { I18nKey, ParsedAppError } from '../i18n'
|
||||
|
||||
+164
-1474
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,158 @@
|
||||
import { Activity, Copy, Disc, FolderOpen, Keyboard, Upload } from 'lucide-react'
|
||||
import React, { useId } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { Locale, PendingChange, VMAction, VMBusyAction, VMDetail, VMStats } from '../../types'
|
||||
import { Button, IconButton, Tip } from '../../ui/controls'
|
||||
import { Switch } from '../../ui/settings'
|
||||
import { HostDNSRows, useHostDNS } from './hostDNS'
|
||||
import { SSHRow, useSSHAccess } from './ssh'
|
||||
|
||||
const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
vmKey: string
|
||||
state: string
|
||||
detail: VMDetail
|
||||
stats: VMStats | null
|
||||
pending: PendingChange[]
|
||||
currentAgentVersion: number
|
||||
/** macOS is still being installed, so it has no Guest Tools yet. */
|
||||
installing: boolean
|
||||
guestToolsLocked: boolean
|
||||
canUseHostDNS: boolean
|
||||
ssh: ReturnType<typeof useSSHAccess>
|
||||
hostDNS: ReturnType<typeof useHostDNS>
|
||||
busyAction?: VMBusyAction
|
||||
onAction: (action: VMAction) => void
|
||||
onCopy: (text: string) => void
|
||||
onTypeText: (text: string) => void
|
||||
onTogglePreventSleep: (enabled: boolean) => void
|
||||
onDeliverFile: () => void
|
||||
}
|
||||
|
||||
/** How Windows and a macOS VM reach each other: SSH, Guest Tools, shared files and DNS. */
|
||||
export const ConnectionSection: React.FC<Props> = ({
|
||||
locale, vmKey, state, detail, stats, pending, currentAgentVersion, installing, guestToolsLocked, canUseHostDNS, ssh, hostDNS,
|
||||
busyAction, onAction, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
const running = state === 'running'
|
||||
const suspended = state === 'suspended'
|
||||
const guestToolsHintId = useId()
|
||||
const tools = !installing
|
||||
if (!tools && detail.ssh_port <= 0) return null
|
||||
const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
|
||||
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
|
||||
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
|
||||
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
|
||||
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < currentAgentVersion
|
||||
const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached')
|
||||
// Plugin switched off: show the state and hide controls that would only fail.
|
||||
const gtOff = !!detail.guest_tools_disabled
|
||||
const gtAttached = detail.guest_tools_attached
|
||||
const showToolsAction = !gtOff && (gtAttached || !gtConnected || needsUpgrade)
|
||||
const toolsAction = gtAttached ? 'detachGuestTools' : 'attachGuestTools'
|
||||
const toolsActionLabel = gtAttached ? 'detachGuestTools' : needsUpgrade ? 'gtUpdate' : 'gtInstall'
|
||||
|
||||
// One status word per state; how files are shared goes in the tooltip.
|
||||
let gtTone: 'ok' | 'warn' | 'idle' = 'idle'
|
||||
let gtStatus: string
|
||||
let gtTip: string
|
||||
if (gtOff) {
|
||||
gtStatus = tr('gtStatusOff'); gtTip = tr('gtStatusOffTip')
|
||||
} else if (needsUpgrade) {
|
||||
gtTone = 'warn'; gtStatus = tr('gtStatusUpgrade'); gtTip = tr('guestToolsUpgradeHint')
|
||||
} else if (gtConnected) {
|
||||
gtTone = 'ok'; gtStatus = tr('gtStatusConnected')
|
||||
gtTip = gtMountMode === 'webdav' ? tr('guestToolsModeWebDAV') : gtMountMode === 'sync' ? tr('guestToolsModeSync') : tr('gtStatusConnected')
|
||||
} else if (detail.guest_tools_configured) {
|
||||
gtStatus = running ? tr('gtStatusWaiting') : tr('gtStatusEnabled')
|
||||
gtTip = tr('gtStatusWaitingTip')
|
||||
} else {
|
||||
gtStatus = tr('gtStatusNone'); gtTip = tr('gtNotInstalledDesc')
|
||||
}
|
||||
const showInstallCmd = !gtOff && detail.guest_tools_attached && !gtAttachPending && (!gtConnected || needsUpgrade)
|
||||
|
||||
return (
|
||||
<section className="section" aria-labelledby="conn-title">
|
||||
<h2 className="section-title" id="conn-title">{tr('connGroup')}</h2>
|
||||
<div className="conn-list">
|
||||
{detail.ssh_port > 0 && <SSHRow locale={locale} vmKey={vmKey} port={detail.ssh_port} state={ssh} onCopy={onCopy} />}
|
||||
{tools && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsTitle')}</span>
|
||||
<Tip label={gtTip}>
|
||||
<span className={`conn-status is-${gtTone}`} tabIndex={0}>
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{gtStatus}
|
||||
</span>
|
||||
</Tip>
|
||||
</div>
|
||||
{suspended && showToolsAction && (
|
||||
<span id={guestToolsHintId} className="hint">{tr('suspendedGuestToolsHint')}</span>
|
||||
)}
|
||||
<div className="conn-ctrl">
|
||||
{showToolsAction && (
|
||||
<Button
|
||||
variant={gtAttached || detail.guest_tools_configured || guestToolsLocked ? 'secondary' : 'primary'}
|
||||
icon={gtAttached ? undefined : <Disc size={13} aria-hidden="true" />}
|
||||
busy={busyAction === toolsAction}
|
||||
disabled={busy || guestToolsLocked}
|
||||
aria-describedby={suspended ? guestToolsHintId : undefined}
|
||||
onClick={() => onAction(toolsAction)}
|
||||
>
|
||||
{tr(toolsActionLabel)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && showInstallCmd && (
|
||||
<div className="conn-row conn-sub">
|
||||
<div className="conn-main">
|
||||
<span className="conn-meta">{tr('gtInstallSub')}</span>
|
||||
</div>
|
||||
<div className="conn-ctrl conn-ctrl-grow">
|
||||
<div className="ssh-pill">
|
||||
<code title={GUEST_TOOLS_INSTALL_CMD}>{GUEST_TOOLS_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(GUEST_TOOLS_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(GUEST_TOOLS_INSTALL_CMD)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && !gtOff && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('sharedFolder')}</span>
|
||||
<span className="conn-meta mono" title="~/Desktop/ReimsShare">~/Desktop/ReimsShare</span>
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Button icon={<Upload size={13} aria-hidden="true" />} disabled={busy} onClick={onDeliverFile}>{tr('deliverFileShort')}</Button>
|
||||
<Button icon={<FolderOpen size={13} aria-hidden="true" />} disabled={busy} onClick={() => onAction('openSharedFolder')}>{tr('openShort')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && !gtOff && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsPreventSleep')}</span>
|
||||
{gtSleepActive && (
|
||||
<span className="conn-meta ok-text"><Activity size={12} aria-hidden="true" /> {tr('guestToolsSleepActive')}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Switch label={tr('guestToolsPreventSleep')} checked={!!detail.guest_tools_prevent_sleep} onChange={onTogglePreventSleep} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{canUseHostDNS && <HostDNSRows locale={locale} detail={detail} running={running} busyAction={busyAction} state={hostDNS} onCopy={onCopy} onTypeText={onTypeText} />}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { Code2, Copy, MonitorPlay, Pencil, Terminal } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { EndpointAction, endpointActions, endpointKey, orderEndpoints, secondaryEndpointActions } from '../../lib/endpoints'
|
||||
import { Locale, VMEndpoint } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { Button } from '../../ui/controls'
|
||||
import { HostIcon } from '../../ui/themeVisuals'
|
||||
|
||||
/** The built-in icon of an endpoint kind; each is themeable by name. */
|
||||
export function endpointIcon(kind: string, size: number): React.ReactNode {
|
||||
return kind === 'vmconnect' || kind === 'rdp'
|
||||
? <HostIcon name="remote-desktop"><MonitorPlay size={size} aria-hidden="true" /></HostIcon>
|
||||
: <HostIcon name="terminal"><Terminal size={size} aria-hidden="true" /></HostIcon>
|
||||
}
|
||||
|
||||
/** A short, user-facing description of where an endpoint points. */
|
||||
function endpointDetail(ep: VMEndpoint): string {
|
||||
switch (ep.kind) {
|
||||
case 'ssh': return `${ep.user ? `${ep.user}@` : ''}${ep.host || '127.0.0.1'}${ep.port ? `:${ep.port}` : ''}`
|
||||
case 'wsl': return ep.distro ?? ''
|
||||
case 'rdp': return `${ep.host ?? ''}${ep.port ? `:${ep.port}` : ''}`
|
||||
case 'vmconnect': return ep.vm ?? ''
|
||||
case 'adb': return ep.serial ?? ''
|
||||
default: return ''
|
||||
}
|
||||
}
|
||||
|
||||
interface Options {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
name: string
|
||||
onCopy: (text: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** Runs the actions of a VM's endpoints, one at a time per endpoint. */
|
||||
export function useEndpointActions({ locale, driverID, name, onCopy, onError }: Options) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [endpointBusy, setEndpointBusy] = useState('')
|
||||
useEffect(() => { setEndpointBusy('') }, [driverID, name])
|
||||
|
||||
const runEndpointAction = (ep: VMEndpoint, action: EndpointAction | '') => {
|
||||
const busyKey = `${endpointKey(ep)}:${action}`
|
||||
setEndpointBusy(busyKey)
|
||||
const done = () => setEndpointBusy((cur) => (cur === busyKey ? '' : cur))
|
||||
if (action === 'copy') {
|
||||
api.GetVMEndpointCommand(driverID, name, ep.kind)
|
||||
.then((cmd) => onCopy(cmd))
|
||||
.catch((e) => onError(tr('failEndpointCommand'), e))
|
||||
.finally(done)
|
||||
return
|
||||
}
|
||||
api.OpenVMEndpoint(driverID, name, ep.kind, action)
|
||||
.catch((e) => onError(tr('failEndpointOpen'), e))
|
||||
.finally(done)
|
||||
}
|
||||
const endpointActionLabel = (kind: string, action: EndpointAction): string => {
|
||||
switch (action) {
|
||||
case 'terminal': return tr('endpointOpenTerminal')
|
||||
case 'vscode': return tr('endpointOpenVSCode')
|
||||
case 'config': return tr('sshWriteConfig')
|
||||
case 'edit': return tr('endpointEditConnection')
|
||||
case 'shell': return tr('endpointOpenADBShell')
|
||||
case 'copy': return tr('endpointCopyADB')
|
||||
case 'open': return tr(kind === 'vmconnect' ? 'endpointOpenVMConnect' : 'endpointOpenRDP')
|
||||
}
|
||||
}
|
||||
const endpointKindLabel = (kind: string): string => {
|
||||
switch (kind) {
|
||||
case 'ssh': return tr('endpointKindSSH')
|
||||
case 'wsl': return tr('endpointKindWSL')
|
||||
case 'rdp': return tr('endpointKindRDP')
|
||||
case 'vmconnect': return tr('endpointKindVMConnect')
|
||||
case 'adb': return tr('endpointKindADB')
|
||||
default: return kind
|
||||
}
|
||||
}
|
||||
|
||||
return { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel }
|
||||
}
|
||||
|
||||
interface SectionProps {
|
||||
locale: Locale
|
||||
endpoints: VMEndpoint[] | undefined
|
||||
/** The endpoint already offered as the page's primary action. */
|
||||
promotedEndpoint: VMEndpoint | undefined
|
||||
state: ReturnType<typeof useEndpointActions>
|
||||
}
|
||||
|
||||
export const EndpointSection: React.FC<SectionProps> = ({ locale, endpoints, promotedEndpoint, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel } = state
|
||||
// One flat list. The endpoint promoted to the header keeps only its secondary actions here, so the
|
||||
// primary action is never offered twice; every other endpoint lists all of its actions.
|
||||
const rows = orderEndpoints(endpoints).flatMap((ep) => {
|
||||
const promoted = promotedEndpoint === ep || (!!promotedEndpoint && endpointKey(promotedEndpoint) === endpointKey(ep))
|
||||
const actions = promoted ? secondaryEndpointActions(ep.kind) : endpointActions(ep.kind)
|
||||
return promoted && actions.length === 0 ? [] : [{ ep, actions }]
|
||||
})
|
||||
if (rows.length === 0) return null
|
||||
return (
|
||||
<section className="section" aria-labelledby="endpoints-title">
|
||||
<h2 className="section-title" id="endpoints-title">{tr('endpointsTitle')}</h2>
|
||||
<div className="conn-list">
|
||||
{rows.map(({ ep, actions }) => (
|
||||
<div className="conn-row" key={endpointKey(ep)}>
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{endpointKindLabel(ep.kind)}</span>
|
||||
<span className="conn-meta mono" title={endpointDetail(ep)}>{endpointDetail(ep)}</span>
|
||||
{!ep.ready && (
|
||||
<span className="conn-status">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('endpointNotReady')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{ep.ready && actions.length > 0 && (
|
||||
<div className="conn-ctrl">
|
||||
{actions.map((action) => (
|
||||
<Button
|
||||
key={action}
|
||||
icon={action === 'vscode' ? <Code2 size={13} aria-hidden="true" /> : action === 'copy' ? <Copy size={13} aria-hidden="true" /> : action === 'edit' || action === 'config' ? <Pencil size={13} aria-hidden="true" /> : endpointIcon(ep.kind, 13)}
|
||||
busy={endpointBusy === `${endpointKey(ep)}:${action}`}
|
||||
onClick={() => runEndpointAction(ep, action)}
|
||||
>
|
||||
{endpointActionLabel(ep.kind, action)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import { Copy, Keyboard } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { Locale, VMBusyAction, VMDetail } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { IconButton } from '../../ui/controls'
|
||||
import { Switch } from '../../ui/settings'
|
||||
|
||||
const HOST_DNS_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Host-DNS.command'
|
||||
const HOST_DNS_DISABLE_CMD = 'sh /Volumes/REIMSTOOLS/Disable-Host-DNS.command'
|
||||
|
||||
interface Options {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
name: string
|
||||
state: string
|
||||
detail: VMDetail | null
|
||||
/** Whether the VM can use the host's DNS at all. */
|
||||
available: boolean
|
||||
/** Guest Tools settings cannot change in the VM's current state. */
|
||||
locked: boolean
|
||||
onToast: (title: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** Per-VM host DNS proxy state (host_dns_flow.go). */
|
||||
export function useHostDNS({ locale, driverID, name, state, detail, available, locked, onToast, onError }: Options) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const running = state === 'running'
|
||||
const [hostDNS, setHostDNS] = useState<{
|
||||
host_dns_enabled: boolean
|
||||
host_dns_active: boolean
|
||||
host_dns_config_stale: boolean
|
||||
host_dns_reported: boolean
|
||||
} | null>(null)
|
||||
const [hostDNSLoadErr, setHostDNSLoadErr] = useState('')
|
||||
const [hostDNSBusy, setHostDNSBusy] = useState(false)
|
||||
const hostDNSWriteSeq = useRef(0)
|
||||
useEffect(() => {
|
||||
hostDNSWriteSeq.current += 1
|
||||
setHostDNS(null)
|
||||
setHostDNSLoadErr('')
|
||||
setHostDNSBusy(false)
|
||||
}, [driverID, name])
|
||||
useEffect(() => {
|
||||
if (!available) {
|
||||
setHostDNS(null)
|
||||
setHostDNSLoadErr('')
|
||||
return
|
||||
}
|
||||
let live = true
|
||||
const pull = (force = false) => {
|
||||
if (!force && document.hidden) return
|
||||
const seq = hostDNSWriteSeq.current
|
||||
api.GetGuestToolsHostDNS(name)
|
||||
.then((s) => {
|
||||
if (live && seq === hostDNSWriteSeq.current) {
|
||||
setHostDNS(s)
|
||||
setHostDNSLoadErr('')
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
console.warn('[vm] GetGuestToolsHostDNS failed:', e)
|
||||
if (live && seq === hostDNSWriteSeq.current) {
|
||||
setHostDNSLoadErr(parseAppError(e).summary)
|
||||
}
|
||||
})
|
||||
}
|
||||
pull(true)
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) pull(true)
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisible)
|
||||
const timer = running ? window.setInterval(() => pull(false), 5000) : undefined
|
||||
return () => {
|
||||
live = false
|
||||
document.removeEventListener('visibilitychange', onVisible)
|
||||
if (timer) window.clearInterval(timer)
|
||||
}
|
||||
}, [driverID, name, available, running, state, detail?.guest_tools_connected, detail?.guest_tools_attached])
|
||||
|
||||
const handleToggleHostDNS = async (enabled: boolean) => {
|
||||
if (hostDNSBusy || locked || !available || hostDNS === null) return
|
||||
const writeSeq = ++hostDNSWriteSeq.current
|
||||
setHostDNSBusy(true)
|
||||
try {
|
||||
await api.SetGuestToolsHostDNS(name, enabled)
|
||||
onToast(tr(enabled ? 'toastHostDNSOn' : 'toastHostDNSOff'))
|
||||
try {
|
||||
const next = await api.GetGuestToolsHostDNS(name)
|
||||
if (writeSeq === hostDNSWriteSeq.current) {
|
||||
setHostDNS(next)
|
||||
setHostDNSLoadErr('')
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[vm] GetGuestToolsHostDNS after toggle failed:', e)
|
||||
if (writeSeq === hostDNSWriteSeq.current) {
|
||||
setHostDNS((prev) => ({
|
||||
host_dns_enabled: enabled,
|
||||
host_dns_active: prev?.host_dns_active ?? false,
|
||||
host_dns_config_stale: prev?.host_dns_config_stale ?? false,
|
||||
host_dns_reported: prev?.host_dns_reported ?? false,
|
||||
}))
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
onError(tr('failGuestTools'), e)
|
||||
} finally {
|
||||
if (writeSeq === hostDNSWriteSeq.current) setHostDNSBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return { hostDNS, hostDNSLoadErr, hostDNSBusy, handleToggleHostDNS, locked }
|
||||
}
|
||||
|
||||
interface RowsProps {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
running: boolean
|
||||
busyAction?: VMBusyAction
|
||||
state: ReturnType<typeof useHostDNS>
|
||||
onCopy: (text: string) => void
|
||||
onTypeText: (text: string) => void
|
||||
}
|
||||
|
||||
export const HostDNSRows: React.FC<RowsProps> = ({ locale, detail, running, busyAction, state, onCopy, onTypeText }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { hostDNS, hostDNSLoadErr, hostDNSBusy, handleToggleHostDNS, locked } = state
|
||||
const busy = busyAction !== undefined
|
||||
const dnsEnabled = hostDNS?.host_dns_enabled ?? false
|
||||
const dnsActive = hostDNS?.host_dns_active ?? false
|
||||
const dnsStale = hostDNS?.host_dns_config_stale ?? false
|
||||
const dnsReported = hostDNS?.host_dns_reported ?? false
|
||||
const toolsAttached = !!detail.guest_tools_attached
|
||||
const disableCmd = toolsAttached
|
||||
? HOST_DNS_DISABLE_CMD
|
||||
: 'sh /private/etc/reims-host-dns/Disable-Host-DNS.command'
|
||||
const showApplySub = dnsEnabled && (dnsStale || !dnsActive)
|
||||
const showDisableSub = dnsActive || dnsStale || (dnsEnabled && running && !dnsReported)
|
||||
|
||||
let dnsStatus: React.ReactNode
|
||||
if (hostDNSLoadErr && hostDNS === null) {
|
||||
dnsStatus = <span className="conn-meta danger-text">{hostDNSLoadErr}</span>
|
||||
} else if (dnsEnabled && dnsReported && dnsStale) {
|
||||
dnsStatus = (
|
||||
<span className="conn-status is-warn">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('hostDNSStatusStale')}
|
||||
</span>
|
||||
)
|
||||
} else if (dnsEnabled && dnsReported && dnsActive) {
|
||||
dnsStatus = (
|
||||
<span className="conn-status is-ok">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('hostDNSStatusActive')}
|
||||
</span>
|
||||
)
|
||||
} else if (dnsEnabled) {
|
||||
dnsStatus = (
|
||||
<span className="conn-status">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('hostDNSStatusPending')}
|
||||
</span>
|
||||
)
|
||||
} else if (dnsReported && (dnsActive || dnsStale)) {
|
||||
dnsStatus = (
|
||||
<span className="conn-status is-warn">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('hostDNSStatusStillActive')}
|
||||
</span>
|
||||
)
|
||||
} else {
|
||||
dnsStatus = (
|
||||
<span className="conn-meta" title={tr('hostDNSOffHint')}>
|
||||
{tr('hostDNSOffHint')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsHostDNS')}</span>
|
||||
{dnsStatus}
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Switch
|
||||
label={tr('guestToolsHostDNS')}
|
||||
checked={dnsEnabled}
|
||||
disabled={busy || locked || hostDNSBusy || hostDNS === null || (dnsEnabled && (dnsActive || dnsStale))}
|
||||
onChange={(checked) => void handleToggleHostDNS(checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{showApplySub && (
|
||||
<div className="conn-row conn-sub">
|
||||
<div className="conn-main">
|
||||
<span className="conn-meta">
|
||||
{tr(!toolsAttached ? 'hostDNSAttachHint' : dnsStale ? 'hostDNSStaleHint' : 'hostDNSApplyHint')}
|
||||
</span>
|
||||
</div>
|
||||
{toolsAttached && (
|
||||
<div className="conn-ctrl conn-ctrl-grow">
|
||||
<div className="ssh-pill">
|
||||
<code title={HOST_DNS_APPLY_CMD}>{HOST_DNS_APPLY_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(HOST_DNS_APPLY_CMD)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(HOST_DNS_APPLY_CMD)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{showDisableSub && (
|
||||
<div className="conn-row conn-sub">
|
||||
<div className="conn-main">
|
||||
<span className="conn-meta">{tr('hostDNSDisableCmdHint')}</span>
|
||||
</div>
|
||||
<div className="conn-ctrl conn-ctrl-grow">
|
||||
<div className="ssh-pill">
|
||||
<code title={disableCmd}>{disableCmd}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(disableCmd)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(disableCmd)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { Check, Copy, Disc, Keyboard } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { Locale, VMAction, VMBusyAction, VMDetail } from '../../types'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
|
||||
// Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing
|
||||
// macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`.
|
||||
const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
name: string
|
||||
detail: VMDetail
|
||||
running: boolean
|
||||
/** Whether the VM window shows the install guide, so the card only says how to start. */
|
||||
installGuideEnabled: boolean
|
||||
busyAction?: VMBusyAction
|
||||
onAction: (action: VMAction) => void
|
||||
onCopy: (text: string) => void
|
||||
onTypeText: (text: string) => void
|
||||
}
|
||||
|
||||
/** How to finish installing macOS. Its step checkboxes are kept per VM in localStorage. */
|
||||
export const InstallCard: React.FC<Props> = ({ locale, name, detail, running, installGuideEnabled, busyAction, onAction, onCopy, onTypeText }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
const guideKey = `reims-go-guide:${name}`
|
||||
const [doneSteps, setDoneSteps] = useState<number[]>(() => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(guideKey) ?? '[]')
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
})
|
||||
const toggleGuideStep = (step: number) => {
|
||||
setDoneSteps((prev) => {
|
||||
const next = prev.includes(step) ? prev.filter((x) => x !== step) : [...prev, step]
|
||||
try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch (e) { console.warn('[vm] persist guide progress failed:', e) }
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const hasInstaller = detail.has_installer
|
||||
const isOffline = hasInstaller && /offline-installer/i.test(detail.installer_path ?? '')
|
||||
const badgeKey: I18nKey = !hasInstaller
|
||||
? 'guideKindBuiltIn'
|
||||
: isOffline
|
||||
? 'guideKindOffline'
|
||||
: 'guideKindOnline'
|
||||
if (installGuideEnabled) {
|
||||
return (
|
||||
<section className="card rg-p-card" aria-labelledby="guide-title">
|
||||
<h2 className="card-title" id="guide-title">
|
||||
{tr('guideTitle')}{' '}
|
||||
<span className="badge rg-p-badge">{tr(badgeKey)}</span>
|
||||
</h2>
|
||||
<p className="card-desc">{tr('guideStartHint')}</p>
|
||||
<div className="card-foot">
|
||||
{!hasInstaller && (
|
||||
<Button
|
||||
icon={<Disc size={14} aria-hidden="true" />}
|
||||
busy={busyAction === 'attachInstaller'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('attachInstaller')}
|
||||
>
|
||||
{tr('attachInstaller')}
|
||||
</Button>
|
||||
)}
|
||||
<Button busy={busyAction === 'finishInstall'} disabled={busy} onClick={() => onAction('finishInstall')}>
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
const finish = (
|
||||
<Button
|
||||
variant={running ? 'primary' : 'secondary'}
|
||||
busy={busyAction === 'finishInstall'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('finishInstall')}
|
||||
>
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
)
|
||||
// Each step's number is a checkbox the user ticks off (kept per VM).
|
||||
const step = (n: number, body: React.ReactNode) => {
|
||||
const done = doneSteps.includes(n)
|
||||
return (
|
||||
<li className={`guide-step${done ? ' is-done' : ''}`}>
|
||||
<button
|
||||
type="button"
|
||||
className={`guide-step-btn${done ? ' done' : ''}`}
|
||||
aria-pressed={done}
|
||||
onClick={() => toggleGuideStep(n)}
|
||||
>
|
||||
{done ? <Check size={12} aria-hidden="true" /> : n}
|
||||
</button>
|
||||
<span className="guide-step-body">{body}</span>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section className="card rg-p-card" aria-labelledby="guide-title">
|
||||
<h2 className="card-title" id="guide-title">
|
||||
{tr('guideTitle')}{' '}
|
||||
<span className={`badge rg-p-badge ${isOffline ? 'badge-ok' : ''}`}>{tr(badgeKey)}</span>
|
||||
</h2>
|
||||
{!hasInstaller ? (
|
||||
<>
|
||||
<ol className="guide-steps">
|
||||
{step(1, tr('guideBuiltIn1'))}
|
||||
{step(2, tr('guideBuiltIn2'))}
|
||||
{step(3, tr('guideBuiltIn3'))}
|
||||
</ol>
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
icon={<Disc size={14} aria-hidden="true" />}
|
||||
busy={busyAction === 'attachInstaller'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('attachInstaller')}
|
||||
>
|
||||
{tr('attachInstaller')}
|
||||
</Button>
|
||||
{finish}
|
||||
</div>
|
||||
</>
|
||||
) : isOffline ? (
|
||||
<>
|
||||
<ol className="guide-steps">
|
||||
{step(1, tr('guideOffline1'))}
|
||||
{step(2, (
|
||||
<>
|
||||
{tr('guideOffline2')}
|
||||
<div className="cmd-line guide-cmd">
|
||||
<code>{OFFLINE_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(OFFLINE_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={14} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(OFFLINE_INSTALL_CMD)} />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
))}
|
||||
{step(3, tr('guideOffline3'))}
|
||||
</ol>
|
||||
<div className="card-foot">{finish}</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ol className="guide-steps">
|
||||
{step(1, tr('guideStep1'))}
|
||||
{step(2, tr('guideStep2'))}
|
||||
{step(3, tr('guideStep3'))}
|
||||
</ol>
|
||||
<div className="card-foot">{finish}</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { AlertTriangle, Info, Pause } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { formatBytes, formatMemory, formatShortTime, pendingChangeText } from '../../lib/format'
|
||||
import { HostReport, Locale, PendingChange, VMAction, VMBusyAction, VMDetail, VMStats } from '../../types'
|
||||
import { Button } from '../../ui/controls'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
state: string
|
||||
canSuspend: boolean
|
||||
/** Id the disabled Resume button is described by. */
|
||||
resumeHintId: string
|
||||
detail: VMDetail | null
|
||||
stats: VMStats | null
|
||||
host: HostReport
|
||||
pending: PendingChange[]
|
||||
busyAction?: VMBusyAction
|
||||
onAction: (action: VMAction) => void
|
||||
}
|
||||
|
||||
/** What needs attention on the VM or its host. */
|
||||
export const VMNotices: React.FC<Props> = ({ locale, state, canSuspend, resumeHintId, detail, stats, host, pending, busyAction, onAction }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
const running = state === 'running'
|
||||
const suspended = state === 'suspended'
|
||||
return (
|
||||
<>
|
||||
{state === 'broken' && (
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('brokenHint')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{suspended && (() => {
|
||||
const suspTime = formatShortTime(Date.parse(detail?.suspend_info?.created_at ?? ''), locale)
|
||||
const suspSize = detail?.suspend_info?.vmstate_size
|
||||
? formatBytes(detail.suspend_info.vmstate_size, locale)
|
||||
: (detail?.memory ? formatMemory(detail.memory, locale) : '—')
|
||||
return (
|
||||
<div className="notice notice-info">
|
||||
<span className="notice-main">
|
||||
<Pause size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span className="notice-text">
|
||||
<span className="notice-title">{tr('suspendedNoticeTitle')}</span>
|
||||
<span className="notice-sub">
|
||||
{suspTime
|
||||
? tr('suspendedNoticeDescWithTime', { time: suspTime, size: suspSize })
|
||||
: tr('suspendedNoticeDesc', { size: suspSize })}
|
||||
</span>
|
||||
{!canSuspend && <span id={resumeHintId} className="notice-sub">{tr('resumeUnavailable')}</span>}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
|
||||
{pending.length > 0 && (
|
||||
<div className="notice notice-info">
|
||||
<span className="notice-main">
|
||||
<Info size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span className="notice-text">
|
||||
<span className="notice-title">{running ? tr('pendingRestartHint') : tr('pendingTitle')}</span>
|
||||
<span className="notice-sub">{pending.map((p) => pendingChangeText(locale, p, host)).join(' · ')}</span>
|
||||
</span>
|
||||
</span>
|
||||
{running && (
|
||||
<Button busy={busyAction === 'restart'} disabled={busy} onClick={() => onAction('restart')}>
|
||||
{tr('restartToApply')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(host.data_root_drive_type === 'usb' || host.data_root_drive_type === 'removable' || host.data_root_drive_type === 'network') && (
|
||||
<div className="notice">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagExternalDriveWarn', { dir: host.data_root })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stats && (stats.disk_backing_depth_warn || (stats.disk_backing_depth ?? 0) >= 2 || stats.disk_backing_broken) && (
|
||||
<div className="notice">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>
|
||||
{stats.disk_backing_broken
|
||||
? tr('diagBackingChainBroken', { depth: stats.disk_backing_depth ?? 1 })
|
||||
: tr('diagBackingChainWarn', { depth: stats.disk_backing_depth ?? 2 })}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(host.memory_load_pct ?? 0) >= 85 && (
|
||||
<div className="notice">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail && !detail.has_installer && detail.disk_controller === 'ahci' && (
|
||||
<div className="notice notice-info">
|
||||
<span className="notice-main">
|
||||
<Info size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagAhciUpgradeHint')}</span>
|
||||
</span>
|
||||
<Button busy={busyAction === 'upgradeNVMe'} disabled={busy} onClick={() => onAction('upgradeNVMe')}>
|
||||
{tr('upgradeToNVMe')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { AppWindow, Camera, Play } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { VMThumbnail } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { Tip } from '../../ui/controls'
|
||||
|
||||
/**
|
||||
* Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
|
||||
* runs, otherwise the last frame saved. Skipped while this window is hidden;
|
||||
* the backend also skips it while the VM's own window is in front.
|
||||
*/
|
||||
export function useVMThumbnail(driverID: string, name: string, running: boolean, thumbnails: boolean): VMThumbnail | null {
|
||||
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
|
||||
useEffect(() => { setThumb(null) }, [driverID, name])
|
||||
useEffect(() => {
|
||||
if (!thumbnails) return
|
||||
let live = true
|
||||
const pull = () => {
|
||||
if (document.hidden) return
|
||||
api.GetVMThumbnail(driverID, name)
|
||||
.then((t) => { if (live && t?.data_url) setThumb(t) })
|
||||
.catch((e) => console.warn('[vm] GetVMThumbnail failed:', e))
|
||||
}
|
||||
pull()
|
||||
const timer = running ? window.setInterval(pull, 15000) : undefined
|
||||
return () => { live = false; if (timer) window.clearInterval(timer) }
|
||||
}, [driverID, name, running, thumbnails])
|
||||
return thumb
|
||||
}
|
||||
|
||||
/**
|
||||
* The VM's own screen as its picture (as UTM and Parallels do): live while it
|
||||
* runs (click to bring its window forward; a camera button copies a
|
||||
* screenshot), the last frame dimmed while it is stopped (hover shows a start
|
||||
* button), and its macOS version artwork until a frame exists. Each new frame
|
||||
* fades in over the previous one.
|
||||
*/
|
||||
export const VMScreen: React.FC<{
|
||||
thumb: VMThumbnail | null
|
||||
art: React.ReactNode
|
||||
running: boolean
|
||||
startLabel: string
|
||||
showLabel: string
|
||||
shotLabel: string
|
||||
onStart?: () => void
|
||||
onShow?: () => void
|
||||
onScreenshot?: () => void
|
||||
}> = ({ thumb, art, running, startLabel, showLabel, shotLabel, onStart, onShow, onScreenshot }) => {
|
||||
const prev = useRef<string>('')
|
||||
const shown = thumb?.data_url ?? ''
|
||||
const under = prev.current !== shown ? prev.current : ''
|
||||
useEffect(() => { prev.current = shown }, [shown])
|
||||
|
||||
// The page's own buttons are the keyboard path; the screen is a pointer shortcut.
|
||||
const act = onShow ?? onStart
|
||||
const overlay = onShow ? (
|
||||
<span className="vm-screen-chip" aria-hidden="true"><AppWindow size={13} /> {showLabel}</span>
|
||||
) : onStart ? (
|
||||
<span className="vm-screen-play" aria-hidden="true"><Play size={18} fill="currentColor" /></span>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`vm-display-unit${act ? ' is-actionable' : ''}`}
|
||||
onClick={act}
|
||||
title={onShow ? showLabel : onStart ? startLabel : undefined}
|
||||
>
|
||||
<div
|
||||
className={`vm-screen${running ? ' is-live' : ' is-idle'}`}
|
||||
style={shown && under ? { backgroundImage: `url(${under})` } : undefined}
|
||||
>
|
||||
{shown ? <img key={thumb?.captured_at} className="vm-screen-img" src={shown} alt="" draggable={false} /> : art}
|
||||
{running && <span className="vm-screen-live" aria-hidden="true" />}
|
||||
{running && shown && onScreenshot && (
|
||||
<Tip label={shotLabel} side="left">
|
||||
<button
|
||||
type="button"
|
||||
className="vm-screen-shot"
|
||||
aria-label={shotLabel}
|
||||
onClick={(e) => { e.stopPropagation(); onScreenshot() }}
|
||||
>
|
||||
<Camera size={14} aria-hidden="true" />
|
||||
</button>
|
||||
</Tip>
|
||||
)}
|
||||
{overlay}
|
||||
</div>
|
||||
<div className="vm-display-stand" aria-hidden="true" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import { History, Plus, RotateCcw, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { formatShortTime } from '../../lib/format'
|
||||
import { DiskSnapshot, Locale } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { Button, IconButton, Tip } from '../../ui/controls'
|
||||
import { HostIcon } from '../../ui/themeVisuals'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
name: string
|
||||
state: string
|
||||
/** False while the VM has no restore points to manage. */
|
||||
shown: boolean
|
||||
/** Restore points only change while the VM is stopped. */
|
||||
locked: boolean
|
||||
onToast: (title: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** The VM's offline restore points (snapshot_flow.go). */
|
||||
export const SnapshotSection: React.FC<Props> = ({ locale, driverID, name, state, shown, locked, onToast, onError }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [snapshots, setSnapshots] = useState<DiskSnapshot[]>([])
|
||||
const [creatingSnap, setCreatingSnap] = useState(false)
|
||||
const [snapDraft, setSnapDraft] = useState('')
|
||||
const [snapBusy, setSnapBusy] = useState('')
|
||||
const [restoreTarget, setRestoreTarget] = useState<string | null>(null)
|
||||
|
||||
const loadSnapshots = () => {
|
||||
if (!shown) { setSnapshots([]); return }
|
||||
api.ListSnapshots(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
|
||||
}
|
||||
useEffect(() => {
|
||||
setCreatingSnap(false)
|
||||
setSnapDraft('')
|
||||
setRestoreTarget(null)
|
||||
loadSnapshots()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [driverID, name, shown, state])
|
||||
|
||||
const handleCreateSnapshot = async () => {
|
||||
const label = snapDraft.trim()
|
||||
if (!label) return
|
||||
setSnapBusy('create')
|
||||
try {
|
||||
await api.CreateSnapshot(driverID, name, label)
|
||||
setSnapDraft('')
|
||||
setCreatingSnap(false)
|
||||
onToast(tr('toastSnapshotCreated', { name: label }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
const handleRestoreSnapshot = async (snapName: string) => {
|
||||
setRestoreTarget(null)
|
||||
setSnapBusy(`restore:${snapName}`)
|
||||
try {
|
||||
await api.RestoreSnapshot(driverID, name, snapName)
|
||||
onToast(tr('toastSnapshotRestored', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
const handleDeleteSnapshot = async (snapName: string) => {
|
||||
setSnapBusy(`delete:${snapName}`)
|
||||
try {
|
||||
await api.DeleteSnapshot(driverID, name, snapName)
|
||||
onToast(tr('toastSnapshotDeleted', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
if (!shown) return null
|
||||
return (
|
||||
<>
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span className="hstack">
|
||||
<HostIcon name="snapshot"><History size={14} aria-hidden="true" /></HostIcon>
|
||||
<span>{tr('snapshotsTitle')}</span>
|
||||
<span className="snap-meta-hint">· {tr('snapshotHint')}</span>
|
||||
</span>
|
||||
<Tip label={locked ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
|
||||
<span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<Plus size={13} aria-hidden="true" />}
|
||||
disabled={locked || !!snapBusy}
|
||||
onClick={() => setCreatingSnap((v) => !v)}
|
||||
>
|
||||
{tr('snapshotCreate')}
|
||||
</Button>
|
||||
</span>
|
||||
</Tip>
|
||||
</div>
|
||||
<div className="conn-list">
|
||||
{creatingSnap && (
|
||||
<div className="snap-create-bar">
|
||||
<input
|
||||
className="input rg-p-input"
|
||||
value={snapDraft}
|
||||
maxLength={64}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={tr('snapshotNamePlaceholder')}
|
||||
autoFocus
|
||||
onChange={(e) => setSnapDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && snapDraft.trim()) { e.preventDefault(); void handleCreateSnapshot() }
|
||||
if (e.key === 'Escape') { e.preventDefault(); setCreatingSnap(false) }
|
||||
}}
|
||||
/>
|
||||
<Button variant="primary" busy={snapBusy === 'create'} disabled={!snapDraft.trim() || !!snapBusy} onClick={() => void handleCreateSnapshot()}>
|
||||
{tr('save')}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => setCreatingSnap(false)}>{tr('cancel')}</Button>
|
||||
</div>
|
||||
)}
|
||||
{snapshots.length === 0 ? (
|
||||
<div className="conn-row">
|
||||
<span className="conn-meta">{tr('snapshotEmpty')}</span>
|
||||
</div>
|
||||
) : (
|
||||
snapshots.map((s) => (
|
||||
<div className="conn-row" key={s.id || s.name}>
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{s.name}</span>
|
||||
{s.created_at > 0 && <span className="conn-meta tnum">{formatShortTime(s.created_at * 1000, locale)}</span>}
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Button
|
||||
icon={<RotateCcw size={13} aria-hidden="true" />}
|
||||
busy={snapBusy === `restore:${s.name}`}
|
||||
disabled={locked || !!snapBusy}
|
||||
onClick={() => setRestoreTarget(s.name)}
|
||||
>
|
||||
{tr('snapshotRestore')}
|
||||
</Button>
|
||||
<IconButton
|
||||
small
|
||||
label={tr('snapshotDelete')}
|
||||
icon={<Trash size={14} />}
|
||||
busy={snapBusy === `delete:${s.name}`}
|
||||
disabled={locked || !!snapBusy}
|
||||
onClick={() => void handleDeleteSnapshot(s.name)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{restoreTarget && (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setRestoreTarget(null) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="danger">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{tr('snapshotRestoreTitle', { name: restoreTarget })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">{tr('snapshotRestoreDesc')}</Alert.Description>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn rg-p-button btn-danger" onClick={() => void handleRestoreSnapshot(restoreTarget)}>
|
||||
{tr('snapshotRestore')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Code2, Copy, FileCode2, Terminal, UserRound } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { sshCommand } from '../../lib/format'
|
||||
import { Locale } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
import { ActionMenu } from '../../ui/menu'
|
||||
|
||||
interface Options {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
name: string
|
||||
/** The remembered user belongs to the macOS connection row; other drivers keep theirs in their endpoints. */
|
||||
enabled: boolean
|
||||
onToast: (title: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** The SSH user remembered for the VM (.reims-go-ssh-user) and the actions that use it. */
|
||||
export function useSSHAccess({ locale, driverID, name, enabled, onToast, onError }: Options) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [sshUser, setSshUser] = useState('')
|
||||
const [sshUserDialog, setSshUserDialog] = useState(false)
|
||||
const [sshUserDraft, setSshUserDraft] = useState('')
|
||||
useEffect(() => { setSshUserDialog(false) }, [driverID, name])
|
||||
useEffect(() => {
|
||||
if (!enabled) { setSshUser(''); return }
|
||||
let live = true
|
||||
api.GetVMSSHUser(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
|
||||
return () => { live = false }
|
||||
}, [driverID, name, enabled])
|
||||
|
||||
const openSSHTerminal = () => {
|
||||
api.OpenSSHTerminal(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const writeSSHConfig = () => {
|
||||
api.WriteSSHConfig(driverID, name, sshUser)
|
||||
.then((alias) => onToast(tr('toastSSHConfigWritten', { alias })))
|
||||
.catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const openVSCodeSSH = () => {
|
||||
api.OpenVSCodeSSH(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const saveSSHUser = async () => {
|
||||
const next = sshUserDraft.trim()
|
||||
setSshUserDialog(false)
|
||||
try {
|
||||
await api.SetVMSSHUser(driverID, name, next)
|
||||
setSshUser(next)
|
||||
onToast(tr('toastSSHUserSaved'))
|
||||
} catch (e) {
|
||||
onError(tr('failSSH'), e)
|
||||
}
|
||||
}
|
||||
|
||||
return { sshUser, sshUserDialog, setSshUserDialog, sshUserDraft, setSshUserDraft, openSSHTerminal, writeSSHConfig, openVSCodeSSH, saveSSHUser }
|
||||
}
|
||||
|
||||
type SSHAccess = ReturnType<typeof useSSHAccess>
|
||||
|
||||
export const SSHRow: React.FC<{ locale: Locale; vmKey: string; port: number; state: SSHAccess; onCopy: (text: string) => void }> = ({ locale, vmKey, port, state, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { sshUser, openSSHTerminal, writeSSHConfig, openVSCodeSSH, setSshUserDraft, setSshUserDialog } = state
|
||||
const sshText = sshUser ? `ssh -p ${port} ${sshUser}@127.0.0.1` : sshCommand(port)
|
||||
return (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">SSH</span>
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<div className="ssh-pill">
|
||||
<code>{sshText}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(sshText)} />
|
||||
</div>
|
||||
<Button icon={<Terminal size={13} aria-hidden="true" />} onClick={openSSHTerminal}>
|
||||
{tr('sshOpenTerminal')}
|
||||
</Button>
|
||||
<ActionMenu key={vmKey} locale={locale} label={tr('sshMore')} small>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={writeSSHConfig}>
|
||||
<FileCode2 size={14} /> {tr('sshWriteConfig')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={openVSCodeSSH}>
|
||||
<Code2 size={14} /> {tr('sshOpenVSCode')}
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => { setSshUserDraft(sshUser); setSshUserDialog(true) }}>
|
||||
<UserRound size={14} /> {tr('sshSetUser')}
|
||||
</Menu.Item>
|
||||
</ActionMenu>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Asks for the user name the SSH actions sign in with. */
|
||||
export const SSHUserDialog: React.FC<{ locale: Locale; state: SSHAccess }> = ({ locale, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { sshUserDialog, setSshUserDialog, sshUserDraft, setSshUserDraft, saveSSHUser } = state
|
||||
if (!sshUserDialog) return null
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setSshUserDialog(false) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{tr('sshUserTitle')}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">{tr('sshUserDesc')}</Alert.Description>
|
||||
<div className="field field-spaced">
|
||||
<input
|
||||
className="input rg-p-input mono"
|
||||
value={sshUserDraft}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={tr('sshUserPlaceholder')}
|
||||
autoFocus
|
||||
onChange={(e) => setSshUserDraft(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); void saveSSHUser() } }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn rg-p-button btn-primary" onClick={() => void saveSSHUser()}>{tr('save')}</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { Cpu, Globe, HardDrive, MemoryStick, Monitor, Network } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, graphicsLabel, parseMemoryGB, resolveGuestLang } from '../../lib/format'
|
||||
import { HostReport, Locale, VMDetail, VMInfo, VMStats } from '../../types'
|
||||
import { Tip } from '../../ui/controls'
|
||||
|
||||
const GUEST_FAMILY_LABEL: Record<string, string> = { macos: 'macOS', linux: 'Linux', windows: 'Windows', android: 'Android' }
|
||||
|
||||
type Tone = '' | ' warn' | ' high'
|
||||
const meterTone = (pct: number, warn = 75, high = 90): Tone => (pct >= high ? ' high' : pct >= warn ? ' warn' : '')
|
||||
const clampPct = (v: number) => Math.min(100, Math.max(0, v))
|
||||
|
||||
interface Spec {
|
||||
key: string
|
||||
/** Shown only in the wide, single-column layout. */
|
||||
label: string
|
||||
icon: React.ReactNode
|
||||
value: string
|
||||
tip: string
|
||||
/** Cells in the first row reserve a meter slot so the row keeps its height. */
|
||||
meter?: { pct: number; tone: Tone; idle: boolean }
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
running: boolean
|
||||
detail: VMDetail | null
|
||||
/** Non-macOS VMs: the cross-driver model. */
|
||||
vmInfo?: VMInfo | null
|
||||
isMacOSDriver: boolean
|
||||
guestFamily: string
|
||||
host: HostReport
|
||||
stats: VMStats | null
|
||||
}
|
||||
|
||||
// Summary presents each fact once in user-facing words; raw upstream values stay in "Technical details".
|
||||
function vmSpecs({ locale, running, detail, vmInfo, isMacOSDriver, guestFamily, host, stats }: Props): Spec[] {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const specs: Spec[] = []
|
||||
if (detail) {
|
||||
const live = running && !!stats
|
||||
const cpuPct = live ? clampPct(stats!.cpu_percent || 0) : 0
|
||||
const memGB = parseMemoryGB(detail.memory) ?? 0
|
||||
const rss = live ? stats!.memory_rss_bytes : 0
|
||||
const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0
|
||||
const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
|
||||
const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0
|
||||
const mem = formatMemory(detail.memory, locale)
|
||||
|
||||
specs.push(
|
||||
{
|
||||
key: 'cpu', label: tr('factCPU'), icon: <Cpu size={15} aria-hidden="true" />, value: tr('cores', { n: detail.cpus }),
|
||||
tip: live ? tr('specCPULiveTip', { n: detail.cpus, pct: Math.round(cpuPct) }) : tr('specCPUTip', { n: detail.cpus }),
|
||||
meter: { pct: cpuPct, tone: meterTone(cpuPct), idle: !live },
|
||||
},
|
||||
{
|
||||
key: 'mem', label: tr('factMemory'), icon: <MemoryStick size={15} aria-hidden="true" />, value: mem,
|
||||
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss, locale) }) : tr('specMemTip', { mem }),
|
||||
meter: { pct: memPct, tone: '', idle: !live },
|
||||
},
|
||||
{
|
||||
key: 'disk', label: tr('factDisk'), icon: <HardDrive size={15} aria-hidden="true" />,
|
||||
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes, locale) : controllerLabel(detail.disk_controller),
|
||||
tip: diskKnown
|
||||
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats!.disk_actual_bytes, locale), max: formatBytes(stats!.disk_virtual_bytes, locale) })
|
||||
: tr('specDiskTip', { ctl: controllerLabel(detail.disk_controller) }),
|
||||
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
|
||||
},
|
||||
{
|
||||
key: 'gfx', label: tr('factGraphics'), icon: <Monitor size={15} aria-hidden="true" />,
|
||||
value: graphicsLabel(locale, detail, host),
|
||||
tip: tr('specGraphicsTip', { gfx: graphicsLabel(locale, detail, host) }),
|
||||
},
|
||||
{
|
||||
key: 'net', label: tr('fieldNetwork'), icon: <Network size={15} aria-hidden="true" />,
|
||||
value: detail.network_mode === 'bridge' ? tr('netBridge') : detail.network_mode === 'custom' ? tr('netCustom') : detail.network ? tr('netShared') : tr('netOff'),
|
||||
tip: detail.network_mode === 'bridge' ? tr('specNetBridgeTip') : !detail.network ? tr('specNetOffTip') : detail.ssh_port > 0 ? tr('specNetSSHTip', { port: detail.ssh_port }) : tr('specNetTip'),
|
||||
},
|
||||
)
|
||||
if (detail.guest_lang) {
|
||||
const lang = resolveGuestLang(locale, detail.guest_lang)
|
||||
specs.push({
|
||||
key: 'lang', label: tr('specLang'), icon: <Globe size={15} aria-hidden="true" />, value: lang.label,
|
||||
tip: lang.detail
|
||||
? tr('specLangTipDetail', { label: lang.label, detail: lang.detail })
|
||||
: tr('specLangTip', { label: lang.label }),
|
||||
})
|
||||
}
|
||||
} else if (vmInfo && !isMacOSDriver) {
|
||||
// Other drivers describe a VM through the cross-driver model only.
|
||||
const live = running && !!stats
|
||||
const guestOS = vmInfo.guest_os
|
||||
const osName = [guestOS?.distro || GUEST_FAMILY_LABEL[guestFamily] || '', guestOS?.version ?? ''].filter(Boolean).join(' ')
|
||||
if (osName) {
|
||||
specs.push({
|
||||
key: 'os', label: tr('factGuestOS'), icon: <Monitor size={15} aria-hidden="true" />, value: osName,
|
||||
tip: guestOS?.arch ? `${osName} · ${guestOS.arch}` : osName,
|
||||
})
|
||||
}
|
||||
if ((vmInfo.cpus ?? 0) > 0) {
|
||||
const cpus = vmInfo.cpus ?? 0
|
||||
const cpuPct = live ? clampPct(stats!.cpu_percent || 0) : 0
|
||||
specs.push({
|
||||
key: 'cpu', label: tr('factCPU'), icon: <Cpu size={15} aria-hidden="true" />, value: tr('cores', { n: cpus }),
|
||||
tip: live ? tr('specCPULiveTip', { n: cpus, pct: Math.round(cpuPct) }) : tr('specCPUTip', { n: cpus }),
|
||||
meter: { pct: cpuPct, tone: meterTone(cpuPct), idle: !live },
|
||||
})
|
||||
}
|
||||
if (vmInfo.memory) {
|
||||
const memGB = parseMemoryGB(vmInfo.memory) ?? 0
|
||||
const rss = live ? stats!.memory_rss_bytes : 0
|
||||
const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0
|
||||
const mem = formatMemory(vmInfo.memory, locale)
|
||||
specs.push({
|
||||
key: 'mem', label: tr('factMemory'), icon: <MemoryStick size={15} aria-hidden="true" />, value: mem,
|
||||
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss, locale) }) : tr('specMemTip', { mem }),
|
||||
meter: { pct: memPct, tone: '', idle: !live },
|
||||
})
|
||||
}
|
||||
if (vmInfo.disk_summary) {
|
||||
const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
|
||||
const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0
|
||||
specs.push({
|
||||
key: 'disk', label: tr('factDisk'), icon: <HardDrive size={15} aria-hidden="true" />,
|
||||
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes, locale) : vmInfo.disk_summary,
|
||||
tip: vmInfo.disk_summary,
|
||||
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
|
||||
})
|
||||
}
|
||||
}
|
||||
return specs
|
||||
}
|
||||
|
||||
export const VMSummary: React.FC<Props> = (props) => {
|
||||
const specs = vmSpecs(props)
|
||||
if (specs.length === 0) return null
|
||||
return (
|
||||
<div className={`vm-spec-card rg-p-vm-summary${props.running ? ' is-live' : ''}`} role="list" data-rg-slot="vm.card">
|
||||
{specs.map((s) => (
|
||||
<Tip key={s.key} label={s.tip}>
|
||||
<div className="vm-spec-cell" role="listitem" tabIndex={0}>
|
||||
<span className="vm-spec-icon">{s.icon}</span>
|
||||
<span className="vm-spec-label">{s.label}</span>
|
||||
<span className="vm-spec-val">{s.value}</span>
|
||||
{s.meter && (
|
||||
<span className="vm-spec-meter" data-idle={s.meter.idle || undefined} aria-hidden="true">
|
||||
<span className={`meter-fill${s.meter.tone}`} style={{ transform: `scaleX(${s.meter.idle ? 0 : s.meter.pct / 100})` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Tip>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { ChevronRight, Copy } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { Locale, VMDetail, VMInfo } from '../../types'
|
||||
import { IconButton } from '../../ui/controls'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
name: string
|
||||
driverID: string
|
||||
detail: VMDetail | null
|
||||
vmInfo?: VMInfo | null
|
||||
onCopy: (text: string) => void
|
||||
}
|
||||
|
||||
/** The raw values upstream tools use for the VM, folded by default. */
|
||||
export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmInfo, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const copyTechSummary = () => {
|
||||
if (!detail) {
|
||||
if (!vmInfo) return
|
||||
onCopy([
|
||||
`${tr('fieldVMName')}: ${name}`,
|
||||
`${tr('fieldDriver')}: ${vmInfo.driver_name || driverID}`,
|
||||
...(vmInfo.disk_path ? [`${tr('fieldDisk')}: ${vmInfo.disk_path}`] : []),
|
||||
...(vmInfo.directory ? [`${tr('fieldDir')}: ${vmInfo.directory}`] : []),
|
||||
].join('\n'))
|
||||
return
|
||||
}
|
||||
const rows = [
|
||||
`${tr('fieldKind')}: ${detail.kind || '—'}`,
|
||||
`${tr('fieldCPUModel')}: ${detail.cpu_model || 'auto'}`,
|
||||
`${tr('fieldGraphicsBackend')}: ${detail.graphics}`,
|
||||
...(detail.gpu && detail.gpu !== 'auto' ? [`${tr('fieldICD')}: ${detail.gpu}`] : []),
|
||||
`${tr('resolution')}: ${detail.displays} × ${detail.resolution}`,
|
||||
`${tr('fieldController')}: ${detail.disk_controller}`,
|
||||
`${tr('fieldDisk')}: ${detail.disk}`,
|
||||
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`,
|
||||
`${tr('fieldAudio')}: ${detail.audio_raw || tr('off')}`,
|
||||
...(detail.guest_lang ? [`${tr('guestLang')}: ${detail.guest_lang}`] : []),
|
||||
`${tr('fieldDir')}: ${detail.directory}`,
|
||||
]
|
||||
onCopy(rows.join('\n'))
|
||||
}
|
||||
|
||||
if (!detail) {
|
||||
if (!vmInfo) return null
|
||||
return (
|
||||
<details key="driver" className="tech">
|
||||
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
|
||||
<div className="tech-body">
|
||||
<IconButton small className="tech-copy" label={tr('copyTechInfo')} icon={<Copy size={14} />} onClick={copyTechSummary} />
|
||||
<dl className="kv-list">
|
||||
<dt>{tr('fieldVMName')}</dt><dd className="mono">{name}</dd>
|
||||
<dt>{tr('fieldDriver')}</dt><dd>{vmInfo.driver_name || driverID}</dd>
|
||||
{vmInfo.disk_path && (<><dt>{tr('fieldDisk')}</dt><dd className="mono">{vmInfo.disk_path}</dd></>)}
|
||||
{vmInfo.directory && (<><dt>{tr('fieldDir')}</dt><dd className="mono">{vmInfo.directory}</dd></>)}
|
||||
</dl>
|
||||
</div>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<details className="tech">
|
||||
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
|
||||
<div className="tech-body">
|
||||
<IconButton small className="tech-copy" label={tr('copyTechInfo')} icon={<Copy size={14} />} onClick={copyTechSummary} />
|
||||
<dl className="kv-list">
|
||||
<dt>{tr('fieldVMName')}</dt><dd className="mono">{name}</dd>
|
||||
<dt>{tr('fieldKind')}</dt><dd>{detail.kind || '—'}</dd>
|
||||
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
|
||||
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
|
||||
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</dd></>)}
|
||||
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {detail.resolution}</dd>
|
||||
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</dd>
|
||||
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
|
||||
<dt>{tr('fieldNetwork')}</dt><dd className="mono">{detail.network_summary || tr('off')}</dd>
|
||||
<dt>{tr('fieldAudio')}</dt><dd>{detail.audio_raw || tr('off')}</dd>
|
||||
{detail.guest_lang && (<><dt>{tr('guestLang')}</dt><dd className="mono">{detail.guest_lang}</dd></>)}
|
||||
<dt>{tr('fieldDir')}</dt><dd className="mono">{detail.directory}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { Copy } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { formatBytes } from '../../lib/format'
|
||||
import { DiskCompactResult, DiskResizeResult, Locale, VMStats } from '../../types'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
import { SetRow } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
interface DiskOptions {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
vm: string
|
||||
running: boolean
|
||||
stats?: VMStats | null
|
||||
onError: (message: string) => void
|
||||
onDiskChanged?: () => void
|
||||
}
|
||||
|
||||
/** Resizing, compacting and optimizing the VM's disk, one at a time. */
|
||||
export function useDiskMaintenance({ locale, driverID, vm, running, stats, onError, onDiskChanged }: DiskOptions) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
const [resizeInput, setResizeInput] = useState('+64G')
|
||||
const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | 'optimize' | ''>('')
|
||||
const [resizeResult, setResizeResult] = useState<DiskResizeResult | null>(null)
|
||||
const [compactResult, setCompactResult] = useState<DiskCompactResult | null>(null)
|
||||
const [optimizeResult, setOptimizeResult] = useState<DiskCompactResult | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
setResizeResult(null)
|
||||
setCompactResult(null)
|
||||
setOptimizeResult(null)
|
||||
}, [driverID, vm])
|
||||
|
||||
const handleResizeDisk = async () => {
|
||||
if (running || diskOpBusy || !resizeInput.trim()) return
|
||||
onError('')
|
||||
setDiskOpBusy('resize')
|
||||
try {
|
||||
const res = await api.ResizeVMDisk(driverID, vm, resizeInput.trim())
|
||||
if (activeVMNameRef.current === vm) {
|
||||
setResizeResult(res)
|
||||
}
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vm) {
|
||||
onError(parseAppError(e).summary)
|
||||
}
|
||||
} finally {
|
||||
setDiskOpBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2'
|
||||
const diskRewriteBaseReason = running ? tr('stopBeforeDiskOp')
|
||||
: (stats?.disk_snapshot_count ?? 0) > 0 ? tr('diskRewriteSnapshots')
|
||||
: (stats?.disk_backing_depth ?? 0) > 0 ? tr('diskRewriteOverlay')
|
||||
: !isQcow2 ? tr('diskCompactQcow2Only')
|
||||
: undefined
|
||||
const compactRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'compact' ? tr('diskRewriteBusy') : undefined)
|
||||
const optimizeRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'optimize' ? tr('diskRewriteBusy') : undefined)
|
||||
|
||||
const handleCompactDisk = async (optimize: boolean) => {
|
||||
if (diskRewriteBaseReason || diskOpBusy) return
|
||||
onError('')
|
||||
setDiskOpBusy(optimize ? 'optimize' : 'compact')
|
||||
try {
|
||||
if (optimize) {
|
||||
const res = await api.OptimizeVMDisk(driverID, vm)
|
||||
if (activeVMNameRef.current === vm) {
|
||||
setOptimizeResult(res)
|
||||
setCompactResult(null)
|
||||
}
|
||||
} else {
|
||||
const res = await api.CompactVMDisk(driverID, vm)
|
||||
if (activeVMNameRef.current === vm) {
|
||||
setCompactResult(res)
|
||||
}
|
||||
}
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vm) {
|
||||
onError(parseAppError(e).summary)
|
||||
}
|
||||
} finally {
|
||||
setDiskOpBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const extendedL2 = stats?.disk_extended_l2 || optimizeResult?.extended_l2_enabled
|
||||
|
||||
return {
|
||||
resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2,
|
||||
compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
|
||||
}
|
||||
}
|
||||
|
||||
interface RowsProps {
|
||||
locale: Locale
|
||||
running: boolean
|
||||
state: ReturnType<typeof useDiskMaintenance>
|
||||
onCopy?: (text: string) => void
|
||||
}
|
||||
|
||||
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, state, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state
|
||||
return (
|
||||
<>
|
||||
<SetRow
|
||||
title={tr('diskResizeTitle')}
|
||||
desc={tr('diskResizeDesc')}
|
||||
disabled={running}
|
||||
reason={tr('stopBeforeDiskOp')}
|
||||
block={
|
||||
<div className="stack-2">
|
||||
<div className="hstack">
|
||||
<div className="presets">
|
||||
{['+32G', '+64G', '+128G', '256G', '512G'].map((v) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
className="preset"
|
||||
aria-pressed={resizeInput === v}
|
||||
disabled={running || !!diskOpBusy}
|
||||
onClick={() => setResizeInput(v)}
|
||||
>
|
||||
{v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<input
|
||||
className="input rg-p-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"
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
busy={diskOpBusy === 'resize'}
|
||||
disabled={running || !!diskOpBusy || !resizeInput.trim()}
|
||||
onClick={handleResizeDisk}
|
||||
>
|
||||
{tr('diskResizeAction')}
|
||||
</Button>
|
||||
</div>
|
||||
{resizeResult && (
|
||||
<div className="notice">
|
||||
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}</div>
|
||||
<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)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('diskCompactTitle')}
|
||||
desc={compactResult
|
||||
? compactResult.reclaimed_bytes > 0
|
||||
? tr('diskCompactDone', {
|
||||
before: formatBytes(compactResult.before_bytes, locale),
|
||||
after: formatBytes(compactResult.after_bytes, locale),
|
||||
reclaimed: formatBytes(compactResult.reclaimed_bytes, locale),
|
||||
})
|
||||
: tr('diskCompactNoGain')
|
||||
: tr('diskCompactDesc')}
|
||||
disabled={!!compactRowReason}
|
||||
reason={compactRowReason}
|
||||
control={
|
||||
<Button
|
||||
variant="secondary"
|
||||
busy={diskOpBusy === 'compact'}
|
||||
disabled={!!compactRowReason || !!diskOpBusy}
|
||||
onClick={() => handleCompactDisk(false)}
|
||||
>
|
||||
{tr('diskCompactAction')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('diskOptimizeTitle')}
|
||||
desc={optimizeResult ? tr('diskOptimizeDone', {
|
||||
before: formatBytes(optimizeResult.before_bytes, locale),
|
||||
after: formatBytes(optimizeResult.after_bytes, locale),
|
||||
reclaimed: formatBytes(optimizeResult.reclaimed_bytes, locale),
|
||||
status: tr(extendedL2 ? 'diskOptimizeEnabled' : 'diskOptimizeInactive'),
|
||||
}) : tr(extendedL2 ? 'diskOptimizeEnabled' : 'diskOptimizeDesc')}
|
||||
disabled={!extendedL2 && !!optimizeRowReason}
|
||||
reason={extendedL2 ? undefined : optimizeRowReason}
|
||||
control={extendedL2 ? undefined : (
|
||||
<Button variant="secondary" busy={diskOpBusy === 'optimize'} disabled={!!optimizeRowReason || !!diskOpBusy} onClick={() => handleCompactDisk(true)}>
|
||||
{tr('diskOptimizeAction')}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface DefenderProps {
|
||||
locale: Locale
|
||||
dataRoot: string
|
||||
onCopy?: (text: string) => void
|
||||
onError: (message: string) => void
|
||||
}
|
||||
|
||||
export const DefenderExclusionRow: React.FC<DefenderProps> = ({ locale, dataRoot, onCopy, onError }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const handleDefender = async (copy: boolean) => {
|
||||
onError('')
|
||||
try {
|
||||
if (copy) {
|
||||
const command = await api.GetDefenderExclusionCommand()
|
||||
if (command) onCopy?.(command)
|
||||
} else {
|
||||
await api.OpenWindowsSecurityExclusions()
|
||||
}
|
||||
} catch (e) {
|
||||
onError(parseAppError(e).summary)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<SetRow
|
||||
title={tr('defenderExclusionTitle')}
|
||||
desc={tr('defenderExclusionDesc', { path: dataRoot })}
|
||||
control={
|
||||
<div className="hstack">
|
||||
<Button variant="secondary" onClick={() => handleDefender(false)}>{tr('defenderOpenSecurity')}</Button>
|
||||
{onCopy && <Button variant="secondary" onClick={() => handleDefender(true)}>{tr('defenderCopyCommand')}</Button>}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { createKeymapRequests, keymapPresetUpdate, keymapUpdate, type KeymapState } from '../../lib/vmKeymap'
|
||||
import { Locale, VMKeymapGuestModifier, VMKeymapHostModifier, VMKeymapPreset } from '../../types'
|
||||
import { PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
/** The VM's modifier key mapping, refreshed while shown. */
|
||||
export function useKeymap(vm: string, running: boolean, shown: boolean) {
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
const [{ keymap, error: keymapErr, busy: keymapBusy }, setKeymapState] = useState<KeymapState>({ keymap: null, error: '', busy: false })
|
||||
const [keymapRequests] = useState(() => createKeymapRequests(api, () => activeVMNameRef.current,
|
||||
(patch) => setKeymapState((state) => ({ ...state, ...patch }))))
|
||||
|
||||
useEffect(() => {
|
||||
setKeymapState(keymapRequests.initial(vm))
|
||||
}, [vm, keymapRequests])
|
||||
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const { refresh, stop } = keymapRequests.watch(vm)
|
||||
void refresh()
|
||||
const timer = window.setInterval(refresh, 3000)
|
||||
return () => { stop(); window.clearInterval(timer) }
|
||||
}, [shown, vm, running, keymapRequests])
|
||||
|
||||
return { keymap, keymapErr, keymapBusy, write: keymapRequests.write }
|
||||
}
|
||||
|
||||
export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType<typeof useKeymap> }> = ({ locale, vm, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { keymap, keymapErr, keymapBusy, write } = state
|
||||
return (
|
||||
<SetGroup title={tr('keymapGroupTitle')} note={tr('keymapGroupNote')}>
|
||||
{keymapErr && <div className="notice notice-error" role="alert">{keymapErr}</div>}
|
||||
{keymap && <>
|
||||
<SetRow title={tr('keymapPresetTitle')} disabled={keymapBusy}
|
||||
desc={keymap.preset === 'off' && !keymap.capture_host_shortcuts ? undefined
|
||||
: !keymap.input_service_available ? tr('keymapInputServiceRequired')
|
||||
: !keymap.running ? tr('keymapStopped')
|
||||
: keymap.needs_guest_tools && !keymap.guest_connected ? tr('keymapWaiting')
|
||||
: keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version
|
||||
? tr('keymapUpgrade', { version: keymap.required_agent_version })
|
||||
: keymap.needs_guest_tools && !keymap.guest_keymap_active ? tr('keymapPending')
|
||||
: tr(keymap.hook_active ? 'keymapRunning' : 'keymapInactive')}
|
||||
control={<Segmented<VMKeymapPreset> label={tr('keymapPresetTitle')} value={keymap.preset}
|
||||
options={[{ value: 'off', label: tr('keymapPresetOff') }, { value: 'win_to_cmd', label: tr('keymapPresetWinToCmd') }, { value: 'swap_alt_win', label: tr('keymapPresetSwapAltWin') }, { value: 'custom', label: tr('keymapPresetCustom') }]}
|
||||
onChange={(preset) => {
|
||||
const request = keymapPresetUpdate(keymap, preset)
|
||||
if (request) void write(vm, request)
|
||||
}} />}
|
||||
/>
|
||||
<SetRow title={tr('keymapCaptureHostShortcutsTitle')} desc={tr('keymapCaptureHostShortcutsDesc')} disabled={keymapBusy}
|
||||
control={<Switch label={tr('keymapCaptureHostShortcutsTitle')} checked={keymap.capture_host_shortcuts}
|
||||
onChange={(capture_host_shortcuts) => { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />}
|
||||
/>
|
||||
{keymap.preset === 'custom' && ([
|
||||
['lwin', 'keymapHostLwin'],
|
||||
['rwin', 'keymapHostRwin'],
|
||||
['lalt', 'keymapHostLalt'],
|
||||
['ralt', 'keymapHostRalt'],
|
||||
['lctrl', 'keymapHostLctrl'],
|
||||
['rctrl', 'keymapHostRctrl'],
|
||||
['capslock', 'keymapHostCapslock'],
|
||||
] as const satisfies readonly (readonly [VMKeymapHostModifier, I18nKey])[]).map(([modifier, label]) => (
|
||||
<SetRow key={modifier} title={tr(label)} disabled={keymapBusy}
|
||||
control={<PopupSelect<VMKeymapGuestModifier> label={tr(label)} value={keymap.bindings[modifier] ?? 'default'}
|
||||
options={[
|
||||
{ value: 'default', label: tr('keymapGuestDefault') },
|
||||
{ value: 'lcmd', label: tr('keymapGuestLcmd') },
|
||||
{ value: 'rcmd', label: tr('keymapGuestRcmd') },
|
||||
{ value: 'lopt', label: tr('keymapGuestLopt') },
|
||||
{ value: 'ropt', label: tr('keymapGuestRopt') },
|
||||
{ value: 'lctrl', label: tr('keymapGuestLctrl') },
|
||||
{ value: 'rctrl', label: tr('keymapGuestRctrl') },
|
||||
{ value: 'esc', label: tr('keymapGuestEsc') },
|
||||
{ value: 'disabled', label: tr('keymapGuestDisabled') },
|
||||
]}
|
||||
onChange={(target) => { void write(vm, keymapUpdate(keymap, { bindings: { [modifier]: target } })) }} />}
|
||||
/>
|
||||
))}
|
||||
</>}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import React, { Suspense, lazy, useEffect, useRef, useState } from 'react'
|
||||
import { parseAppError } from '../../i18n'
|
||||
import { Locale, PluginInfo } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
|
||||
const SchemaForm = lazy(() => import('../SchemaForm').then((m) => ({ default: m.SchemaForm })))
|
||||
|
||||
/** Per-VM settings of the active plugins. Changes save at once, in order. */
|
||||
export function useVMPluginSettings(vmKey: string, onError: (message: string) => void) {
|
||||
const [vmPlugins, setVmPlugins] = useState<PluginInfo[]>([])
|
||||
const [vmPluginVals, setVmPluginVals] = useState<Record<string, Record<string, unknown>>>({})
|
||||
const vmPluginSettingsSaveQueues = useRef(new Map<string, Promise<void>>())
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(vmKey)])
|
||||
.then(([list, vals]) => {
|
||||
if (!live) return
|
||||
const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings)
|
||||
setVmPlugins(activeWithVM)
|
||||
setVmPluginVals((vals ?? {}) as Record<string, Record<string, unknown>>)
|
||||
})
|
||||
.catch((e) => console.warn('[settings] load VM plugin settings failed:', e))
|
||||
return () => { live = false }
|
||||
}, [vmKey])
|
||||
|
||||
const updateVMPluginSetting = (pluginID: string, patch: Record<string, unknown>) => {
|
||||
setVmPluginVals((prev) => ({ ...prev, [pluginID]: { ...prev[pluginID], ...patch } }))
|
||||
const queueKey = JSON.stringify([pluginID, vmKey])
|
||||
const previous = vmPluginSettingsSaveQueues.current.get(queueKey) ?? Promise.resolve()
|
||||
const save = previous.catch((error) => {
|
||||
console.warn('[settings] previous plugin save failed:', error)
|
||||
}).then(() => api.SetPluginSettings(pluginID, vmKey, patch))
|
||||
vmPluginSettingsSaveQueues.current.set(queueKey, save)
|
||||
void save.catch((e) => onError(parseAppError(e).summary)).finally(() => {
|
||||
if (vmPluginSettingsSaveQueues.current.get(queueKey) === save) {
|
||||
vmPluginSettingsSaveQueues.current.delete(queueKey)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return { vmPlugins, vmPluginVals, updateVMPluginSetting }
|
||||
}
|
||||
|
||||
export const VMPluginGroup: React.FC<{ locale: Locale; group: string; state: ReturnType<typeof useVMPluginSettings> }> = ({ locale, group, state }) => {
|
||||
const { vmPlugins, vmPluginVals, updateVMPluginSetting } = state
|
||||
const matched = vmPlugins.filter((p) => p.settings && (p.settings['x-group'] === group || Object.values(p.settings.properties ?? {}).some((prop) => prop['x-group'] === group)))
|
||||
if (matched.length === 0) return null
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
{matched.map((p) => (
|
||||
<SchemaForm
|
||||
key={p.id}
|
||||
locale={locale}
|
||||
schema={p.settings!}
|
||||
values={vmPluginVals[p.id] ?? {}}
|
||||
scopeFilter="vm"
|
||||
groupFilter={group}
|
||||
onChange={(_, patch) => updateVMPluginSetting(p.id, patch)}
|
||||
/>
|
||||
))}
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import { FolderPlus, Trash2 } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { DriveShareSettings, Locale, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, VMDetail } from '../../types'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
import { Segmented, SetGroup, SetRow, SetValue, Switch } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
/** Windows drives shared with the VM. */
|
||||
export function useDriveShares(vm: string) {
|
||||
const [driveSettings, setDriveSettings] = useState<DriveShareSettings | null>(null)
|
||||
const [driveBusy, setDriveBusy] = useState(false)
|
||||
const driveBusyRef = useRef(false)
|
||||
const [driveErr, setDriveErr] = useState('')
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setDriveSettings(null)
|
||||
setDriveErr('')
|
||||
api.GetVMDriveShareSettings(vm)
|
||||
.then((settings) => { if (active) setDriveSettings(settings) })
|
||||
.catch((e) => { if (active) setDriveErr(parseAppError(e).summary) })
|
||||
return () => { active = false }
|
||||
}, [vm])
|
||||
|
||||
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
|
||||
if (driveBusyRef.current || !driveSettings) return
|
||||
driveBusyRef.current = true
|
||||
setDriveBusy(true)
|
||||
setDriveErr('')
|
||||
try {
|
||||
const next = await api.SetVMDriveShareSettings(vm, enabled, selected)
|
||||
if (activeVMNameRef.current === vm) setDriveSettings(next)
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vm) setDriveErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
driveBusyRef.current = false
|
||||
setDriveBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive)
|
||||
|
||||
return { driveSettings, driveBusy, driveErr, updateDriveShares, selectedDrives }
|
||||
}
|
||||
|
||||
/** Single folders shared with the VM. */
|
||||
export function useSharedFolders(vm: string, locale: Locale) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [folderSettings, setFolderSettings] = useState<SharedFolderSettings | null>(null)
|
||||
const [folderBusy, setFolderBusy] = useState(false)
|
||||
const folderBusyRef = useRef(false)
|
||||
const folderOpSeqRef = useRef(0)
|
||||
const [folderErr, setFolderErr] = useState('')
|
||||
const [confirmRWFolder, setConfirmRWFolder] = useState<SharedFolderInfo | null>(null)
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
folderOpSeqRef.current += 1
|
||||
folderBusyRef.current = false
|
||||
setFolderBusy(false)
|
||||
setFolderSettings(null)
|
||||
setFolderErr('')
|
||||
setConfirmRWFolder(null)
|
||||
api.GetVMSharedFolderSettings(vm)
|
||||
.then((settings) => { if (active) setFolderSettings(settings) })
|
||||
.catch((e) => { if (active) setFolderErr(formatFolderError(e)) })
|
||||
return () => { active = false }
|
||||
}, [vm])
|
||||
|
||||
const formatFolderIssue = (issue?: string) => {
|
||||
switch (issue) {
|
||||
case 'missing': return tr('folderShareIssueMissing')
|
||||
case 'volume_mismatch': return tr('folderShareIssueVolumeMismatch')
|
||||
case 'path_changed': return tr('folderShareIssuePathChanged')
|
||||
case 'overlap': return tr('folderShareIssueOverlap')
|
||||
case 'blocked': return tr('folderShareIssueBlocked')
|
||||
case 'not_found': return tr('folderShareIssueNotFound')
|
||||
case 'invalid_mode': return tr('folderShareIssueInvalidMode')
|
||||
case 'corrupt_config': return tr('folderShareIssueCorruptConfig')
|
||||
default: return ''
|
||||
}
|
||||
}
|
||||
|
||||
const formatFolderError = (e: unknown) => {
|
||||
const summary = parseAppError(e).summary
|
||||
const match = summary.match(/shared folder:\s*(missing|volume_mismatch|path_changed|overlap|blocked|not_found|invalid_mode|corrupt_config)\b/i)
|
||||
if (match) return formatFolderIssue(match[1].toLowerCase())
|
||||
return summary
|
||||
}
|
||||
|
||||
const runFolderOp = async (op: (vm: string) => Promise<SharedFolderSettings | null>) => {
|
||||
if (folderBusyRef.current || !folderSettings) return
|
||||
const opSeq = ++folderOpSeqRef.current
|
||||
folderBusyRef.current = true
|
||||
setFolderBusy(true)
|
||||
setFolderErr('')
|
||||
try {
|
||||
const next = await op(vm)
|
||||
if (next && activeVMNameRef.current === vm && folderOpSeqRef.current === opSeq) {
|
||||
setFolderSettings(next)
|
||||
}
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vm && folderOpSeqRef.current === opSeq) {
|
||||
setFolderErr(formatFolderError(e))
|
||||
}
|
||||
} finally {
|
||||
if (folderOpSeqRef.current === opSeq) {
|
||||
folderBusyRef.current = false
|
||||
setFolderBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleAddFolder = () => runFolderOp(async (vm) => {
|
||||
const picked = await api.PickDirectory(tr('folderSharePickTitle'))
|
||||
if (!picked || activeVMNameRef.current !== vm) return null
|
||||
return api.AddVMSharedFolder(vm, picked)
|
||||
})
|
||||
|
||||
const updateFolderMode = (folderID: string, mode: SharedFolderMode) =>
|
||||
runFolderOp((vm) => api.SetVMSharedFolderMode(vm, folderID, mode))
|
||||
|
||||
const handleRemoveFolder = (folderID: string) =>
|
||||
runFolderOp((vm) => api.RemoveVMSharedFolder(vm, folderID))
|
||||
|
||||
return {
|
||||
folderSettings, folderBusy, folderErr, confirmRWFolder, setConfirmRWFolder, formatFolderIssue,
|
||||
handleAddFolder, updateFolderMode, handleRemoveFolder,
|
||||
}
|
||||
}
|
||||
|
||||
interface SectionProps<State> {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
state: State
|
||||
/** Version of the connected Guest Tools agent, 0 when none is connected. */
|
||||
toolsVersion: number
|
||||
}
|
||||
|
||||
export const DriveShareSection: React.FC<SectionProps<ReturnType<typeof useDriveShares>>> = ({ locale, detail, state, toolsVersion }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { driveSettings, driveBusy, driveErr, updateDriveShares, selectedDrives } = state
|
||||
return (
|
||||
<SetGroup title={tr('driveShareTitle')} note={tr('driveShareReadOnly')}>
|
||||
<SetRow
|
||||
title={tr('driveShareMaster')}
|
||||
desc={tr('driveShareMasterDesc')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('driveShareMaster')}
|
||||
checked={!!driveSettings?.enabled}
|
||||
disabled={!driveSettings || driveBusy || !!detail.guest_tools_disabled}
|
||||
onChange={(enabled) => void updateDriveShares(enabled, selectedDrives())}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{detail.guest_tools_disabled && <div className="notice">{tr('gtStatusOffTip')}</div>}
|
||||
{driveErr && <div className="notice" role="alert">{driveErr}</div>}
|
||||
{driveSettings?.enabled && selectedDrives().length > 0 &&
|
||||
toolsVersion > 0 &&
|
||||
toolsVersion < driveSettings.required_agent_version && (
|
||||
<div className="notice">{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}</div>
|
||||
)}
|
||||
{/* Drives are only worth choosing once sharing is on. */}
|
||||
{driveSettings?.enabled && driveSettings.drives.map((drive) => {
|
||||
const title = `Windows (${drive.drive}:)`
|
||||
return (
|
||||
<SetRow
|
||||
key={drive.drive}
|
||||
title={title}
|
||||
desc={drive.system ? <span className="warn-text">{tr('driveShareSystem')}</span> : undefined}
|
||||
disabled={driveBusy || !!detail.guest_tools_disabled}
|
||||
control={
|
||||
<Switch
|
||||
label={title}
|
||||
checked={drive.selected}
|
||||
disabled={driveBusy}
|
||||
onChange={(enabled) => {
|
||||
const next = selectedDrives().filter((letter) => letter !== drive.drive)
|
||||
if (enabled) next.push(drive.drive)
|
||||
void updateDriveShares(driveSettings?.enabled ?? false, next)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
{driveSettings && driveSettings.drives.length === 0 && (
|
||||
<SetValue title={tr('driveShareTitle')} value={tr('driveShareNoDrives')} />
|
||||
)}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export const SharedFolderSection: React.FC<SectionProps<ReturnType<typeof useSharedFolders>>> = ({ locale, detail, state, toolsVersion }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { folderSettings, folderBusy, folderErr, setConfirmRWFolder, formatFolderIssue, handleAddFolder, updateFolderMode, handleRemoveFolder } = state
|
||||
return (
|
||||
<SetGroup title={tr('folderShareTitle')} note={tr('folderShareNote')}>
|
||||
<SetRow
|
||||
title={tr('folderShareAddTitle')}
|
||||
desc={tr('folderShareDesc')}
|
||||
disabled={folderBusy || !!detail.guest_tools_disabled}
|
||||
control={
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<FolderPlus size={14} aria-hidden="true" />}
|
||||
busy={folderBusy}
|
||||
disabled={!folderSettings || folderBusy || !!detail.guest_tools_disabled}
|
||||
onClick={() => void handleAddFolder()}
|
||||
>
|
||||
{tr('folderShareAdd')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{folderErr && <div className="notice" role="alert">{folderErr}</div>}
|
||||
{folderSettings &&
|
||||
folderSettings.folders.some((f) => f.enabled && f.available) &&
|
||||
toolsVersion > 0 &&
|
||||
toolsVersion < folderSettings.required_agent_version && (
|
||||
<div className="notice">{tr('folderShareNeedsTools', { version: folderSettings.required_agent_version })}</div>
|
||||
)}
|
||||
{folderSettings && folderSettings.folders.length === 0 && (
|
||||
<SetValue title={tr('folderShareListTitle')} value={tr('folderShareEmpty')} />
|
||||
)}
|
||||
{folderSettings?.folders.map((folder) => {
|
||||
const mode: SharedFolderMode = !folder.enabled ? 'disabled' : folder.writable ? 'rw' : 'ro'
|
||||
const activeMode: SharedFolderMode | undefined = folder.available ? mode : (!folder.enabled ? 'disabled' : undefined)
|
||||
const issueText = !folder.available ? formatFolderIssue(folder.issue) : ''
|
||||
return (
|
||||
<SetRow
|
||||
key={folder.id}
|
||||
title={folder.name}
|
||||
desc={
|
||||
<>
|
||||
<code className="inline-code folder-path" title={folder.host_path}>{folder.host_path}</code>
|
||||
{issueText && <div className="warn-text">{issueText}</div>}
|
||||
{!issueText && folder.enabled && folder.writable && (
|
||||
<div className="warn-text">{tr('folderShareWritableWarn')}</div>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
disabled={folderBusy || !!detail.guest_tools_disabled}
|
||||
control={
|
||||
<div className="hstack">
|
||||
<Segmented<SharedFolderMode>
|
||||
label={folder.name}
|
||||
value={activeMode}
|
||||
options={[
|
||||
{ value: 'disabled', label: tr('folderShareModeDisabled') },
|
||||
{ value: 'ro', label: tr('folderShareModeRO'), disabled: !folder.available },
|
||||
{ value: 'rw', label: tr('folderShareModeRW'), disabled: !folder.available },
|
||||
]}
|
||||
onChange={(nextMode) => {
|
||||
if (nextMode === activeMode) return
|
||||
if (nextMode === 'rw') {
|
||||
setConfirmRWFolder(folder)
|
||||
return
|
||||
}
|
||||
void updateFolderMode(folder.id, nextMode)
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
small
|
||||
label={tr('folderShareRemove')}
|
||||
icon={<Trash2 size={13} />}
|
||||
disabled={folderBusy || !!detail.guest_tools_disabled}
|
||||
onClick={() => void handleRemoveFolder(folder.id)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
|
||||
/** Asks before the VM may change files in a shared folder. */
|
||||
export const WritableFolderDialog: React.FC<{ locale: Locale; state: ReturnType<typeof useSharedFolders> }> = ({ locale, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { confirmRWFolder, setConfirmRWFolder, updateFolderMode } = state
|
||||
if (!confirmRWFolder) return null
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setConfirmRWFolder(null) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{tr('folderShareConfirmRWTitle')}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
{tr('folderShareConfirmRWDesc', { name: confirmRWFolder.name, path: confirmRWFolder.host_path })}
|
||||
</Alert.Description>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn rg-p-button">{tr('cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="btn rg-p-button btn-primary"
|
||||
onClick={() => {
|
||||
const target = confirmRWFolder
|
||||
setConfirmRWFolder(null)
|
||||
void updateFolderMode(target.id, 'rw')
|
||||
}}
|
||||
>
|
||||
{tr('folderShareConfirmRWAction')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import { Copy, Eye, EyeOff, Shuffle } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { Locale, SMBIOSIdentity, VMDetail } from '../../types'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
import { Modal } from '../../ui/dialog'
|
||||
import { SetGroup, SetRow, SetValue } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
function maskIdentity(v: string | undefined, head = 4, tail = 4): string {
|
||||
const s = (v ?? '').trim()
|
||||
if (!s) return '—'
|
||||
if (s.length <= head + tail) return '•'.repeat(s.length)
|
||||
return `${s.slice(0, head)}••••${s.slice(-tail)}`
|
||||
}
|
||||
|
||||
/** The VM's SMBIOS identity and the dialog that replaces it. */
|
||||
export function useSMBIOS(detail: VMDetail, running: boolean) {
|
||||
const [smbios, setSmbios] = useState<SMBIOSIdentity | null>(null)
|
||||
const [smbiosErr, setSmbiosErr] = useState('')
|
||||
const [smbiosReveal, setSmbiosReveal] = useState(false)
|
||||
const [smbiosOpen, setSmbiosOpen] = useState(false)
|
||||
const [smbiosDraft, setSmbiosDraft] = useState<SMBIOSIdentity | null>(null)
|
||||
const [smbiosBusy, setSmbiosBusy] = useState<'' | 'generate' | 'apply'>('')
|
||||
const [smbiosModalErr, setSmbiosModalErr] = useState('')
|
||||
const [smbiosApplied, setSmbiosApplied] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setSmbios(null)
|
||||
setSmbiosErr('')
|
||||
setSmbiosReveal(false)
|
||||
setSmbiosApplied(false)
|
||||
if (!detail.has_opencore) return () => { active = false }
|
||||
api.GetVMSMBIOS(detail.name)
|
||||
.then((id) => { if (active) setSmbios(id) })
|
||||
.catch((e) => { if (active) setSmbiosErr(parseAppError(e).summary) })
|
||||
return () => { active = false }
|
||||
}, [detail.name, detail.has_opencore])
|
||||
|
||||
const smbiosLocked = running || detail.state === 'suspended' || !!detail.suspend_info
|
||||
|
||||
const handleGenerateSmbios = async (modelOverride?: string) => {
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosBusy('generate')
|
||||
try {
|
||||
const generated = await api.GenerateVMSMBIOS(modelOverride ?? smbios?.model ?? '')
|
||||
setSmbiosDraft({
|
||||
model: smbios?.model || generated.model,
|
||||
serial: generated.serial,
|
||||
mlb: generated.mlb,
|
||||
uuid: generated.uuid,
|
||||
rom: smbios?.rom || '',
|
||||
})
|
||||
} catch (e) {
|
||||
setSmbiosModalErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setSmbiosBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const openSmbiosRotate = () => {
|
||||
if (smbiosLocked) return
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosApplied(false)
|
||||
setSmbiosOpen(true)
|
||||
void handleGenerateSmbios(smbios?.model ?? '')
|
||||
}
|
||||
|
||||
const handleApplySmbios = async () => {
|
||||
if (smbiosLocked || smbiosBusy || !smbiosDraft) return
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosBusy('apply')
|
||||
try {
|
||||
const updated = await api.ApplyVMSMBIOS(detail.name, {
|
||||
model: smbios?.model || smbiosDraft.model || '',
|
||||
serial: smbiosDraft.serial,
|
||||
mlb: smbiosDraft.mlb,
|
||||
uuid: smbiosDraft.uuid,
|
||||
rom: smbios?.rom || '',
|
||||
})
|
||||
setSmbios(updated)
|
||||
setSmbiosOpen(false)
|
||||
setSmbiosApplied(true)
|
||||
} catch (e) {
|
||||
setSmbiosModalErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setSmbiosBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
smbios, smbiosErr, smbiosReveal, setSmbiosReveal, smbiosOpen, setSmbiosOpen, smbiosDraft,
|
||||
setSmbiosDraft, smbiosBusy, smbiosModalErr, smbiosApplied, smbiosLocked, openSmbiosRotate,
|
||||
handleGenerateSmbios, handleApplySmbios,
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
state: ReturnType<typeof useSMBIOS>
|
||||
onCopy?: (text: string) => void
|
||||
}
|
||||
|
||||
export const SMBIOSSection: React.FC<Props> = ({ locale, state, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { smbios, smbiosErr, smbiosReveal, setSmbiosReveal, smbiosApplied, smbiosLocked, openSmbiosRotate } = state
|
||||
return (
|
||||
<SetGroup title={tr('smbiosTitle')} note={tr('smbiosCheckHint')}>
|
||||
<SetRow
|
||||
title={tr('smbiosTitle')}
|
||||
desc={tr('smbiosDesc')}
|
||||
disabled={smbiosLocked}
|
||||
reason={tr('smbiosStopRequired')}
|
||||
control={
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<Shuffle size={13} aria-hidden="true" />}
|
||||
disabled={smbiosLocked || !smbios}
|
||||
onClick={openSmbiosRotate}
|
||||
>
|
||||
{tr('smbiosRotateBtn')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{smbiosErr && <div className="notice notice-error" role="alert">{tr('smbiosLoadFailed')}: {smbiosErr}</div>}
|
||||
{smbiosApplied && <div className="notice" role="status">{tr('smbiosApplied')}</div>}
|
||||
{smbios && (
|
||||
<>
|
||||
<SetValue title={tr('smbiosModel')} value={smbios.model || '—'} mono />
|
||||
<SetValue
|
||||
title={tr('smbiosSerial')}
|
||||
mono
|
||||
value={
|
||||
<span className="hstack">
|
||||
<span>{smbiosReveal ? smbios.serial : maskIdentity(smbios.serial, 4, 4)}</span>
|
||||
<IconButton
|
||||
small
|
||||
label={smbiosReveal ? tr('smbiosHide') : tr('smbiosShow')}
|
||||
icon={smbiosReveal ? <EyeOff size={13} /> : <Eye size={13} />}
|
||||
onClick={() => setSmbiosReveal((v) => !v)}
|
||||
/>
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('smbiosCopySerial')}
|
||||
icon={<Copy size={13} />}
|
||||
onClick={() => onCopy(smbios.serial)}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<SetValue title={tr('smbiosMLB')} value={smbiosReveal ? smbios.mlb : maskIdentity(smbios.mlb, 4, 4)} mono />
|
||||
<SetValue title={tr('smbiosUUID')} value={smbiosReveal ? smbios.uuid : maskIdentity(smbios.uuid, 4, 4)} mono />
|
||||
{smbios.rom && <SetValue title={tr('smbiosROM')} value={smbiosReveal ? smbios.rom : maskIdentity(smbios.rom, 5, 5)} mono />}
|
||||
</>
|
||||
)}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export const SMBIOSDialog: React.FC<Props> = ({ locale, state, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { smbios, setSmbiosOpen, smbiosDraft, setSmbiosDraft, smbiosBusy, smbiosModalErr, smbiosLocked, handleGenerateSmbios, handleApplySmbios } = state
|
||||
return (
|
||||
<Modal
|
||||
title={tr('smbiosDialogTitle')}
|
||||
subtitle={tr('smbiosDialogSub')}
|
||||
closeLabel={tr('close')}
|
||||
dismissable={smbiosBusy !== 'apply'}
|
||||
onClose={() => setSmbiosOpen(false)}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<div className="notice">
|
||||
<span className="warn-text">{tr('smbiosWarning')}</span>
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<Shuffle size={13} aria-hidden="true" />}
|
||||
busy={smbiosBusy === 'generate'}
|
||||
disabled={smbiosBusy === 'apply'}
|
||||
onClick={() => void handleGenerateSmbios(smbios?.model ?? '')}
|
||||
>
|
||||
{tr('smbiosGenerate')}
|
||||
</Button>
|
||||
{onCopy && smbiosDraft?.serial && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<Copy size={13} aria-hidden="true" />}
|
||||
disabled={!!smbiosBusy}
|
||||
onClick={() => onCopy(smbiosDraft.serial)}
|
||||
>
|
||||
{tr('smbiosCopySerial')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosSerial')}</span>
|
||||
<input
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={12}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.serial ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: e.target.value.toUpperCase(),
|
||||
mlb: prev?.mlb ?? '',
|
||||
uuid: prev?.uuid ?? '',
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosMLB')}</span>
|
||||
<input
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={17}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.mlb ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: prev?.serial ?? '',
|
||||
mlb: e.target.value.toUpperCase(),
|
||||
uuid: prev?.uuid ?? '',
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosUUID')}</span>
|
||||
<input
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={36}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.uuid ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: prev?.serial ?? '',
|
||||
mlb: prev?.mlb ?? '',
|
||||
uuid: e.target.value.toUpperCase(),
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
{smbios?.rom && (
|
||||
<div className="srow-desc">
|
||||
{tr('smbiosROM')}: <code className="inline-code">{smbios.rom}</code>
|
||||
</div>
|
||||
)}
|
||||
<div className="srow-desc">{tr('smbiosCheckHint')}</div>
|
||||
{smbiosModalErr && <div className="notice notice-error" role="alert">{smbiosModalErr}</div>}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" disabled={smbiosBusy === 'apply'} onClick={() => setSmbiosOpen(false)}>
|
||||
{tr('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={smbiosBusy === 'apply'}
|
||||
disabled={smbiosLocked || smbiosBusy === 'generate' || !smbiosDraft?.serial.trim() || !smbiosDraft?.mlb.trim() || !smbiosDraft?.uuid.trim()}
|
||||
onClick={() => void handleApplySmbios()}
|
||||
>
|
||||
{tr('smbiosApply')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { app as WailsApp } from '../../../wailsjs/go/models'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { humanDisplayFallbackName, humanDisplayMeta, humanDisplayTitle, sortDisplaysForPicker } from '../../lib/format'
|
||||
import { DisplayInfo, HostReport, Locale } from '../../types'
|
||||
import { PopupSelect, SetRow } from '../../ui/settings'
|
||||
import { errorToast, type ToastInput } from '../../ui/toast'
|
||||
import { api } from '../../wails'
|
||||
|
||||
const PRIMARY_DISPLAY_OPT = '__primary'
|
||||
|
||||
interface Options {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
vm: string
|
||||
running: boolean
|
||||
host: HostReport
|
||||
shown: boolean
|
||||
isBlocked: () => boolean
|
||||
onToast: (toast: ToastInput) => void
|
||||
}
|
||||
|
||||
/** The host display the VM window opens on. A change applies at once. */
|
||||
export function useTargetDisplay({ locale, driverID, vm, running, host, shown, isBlocked, onToast }: Options) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
const [displayStatus, setDisplayStatus] = useState<WailsApp.VMDisplayStatus | null>(null)
|
||||
const [displayBusy, setDisplayBusy] = useState(false)
|
||||
const [displayErr, setDisplayErr] = useState('')
|
||||
const displayBusyRef = useRef(false)
|
||||
const displayReqSeqRef = useRef(0)
|
||||
|
||||
const connectedDisplays = useMemo<DisplayInfo[]>(
|
||||
() => sortDisplaysForPicker(displayStatus?.displays ?? host.displays ?? []),
|
||||
[displayStatus, host.displays],
|
||||
)
|
||||
const activeTargetDisplay = displayStatus
|
||||
? connectedDisplays.find((d) => d.name === displayStatus.effective_display)
|
||||
: host.primary_display
|
||||
const displayProfile = useMemo(() => displayStatus ? {
|
||||
...host,
|
||||
primary_display: activeTargetDisplay,
|
||||
display_presets: displayStatus.display_presets,
|
||||
fullscreen_hidpi: displayStatus.fullscreen_hidpi,
|
||||
hidpi_advice: displayStatus.hidpi_advice,
|
||||
recommended_resolution: undefined,
|
||||
} : host, [host, displayStatus, activeTargetDisplay])
|
||||
|
||||
const hostDisplaysSig = (host.displays ?? [])
|
||||
.map((d) => `${d.name ?? ''}:${d.friendly_name ?? ''}:${d.width}x${d.height}@${d.scale_pct}:${d.refresh_hz ?? 0}:${d.work_width ?? 0}x${d.work_height ?? 0}:${d.primary ? 1 : 0}`)
|
||||
.join('|')
|
||||
|
||||
useEffect(() => {
|
||||
displayReqSeqRef.current += 1
|
||||
displayBusyRef.current = false
|
||||
setDisplayStatus(null)
|
||||
setDisplayBusy(false)
|
||||
setDisplayErr('')
|
||||
}, [driverID, vm])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
const reqSeq = displayReqSeqRef.current
|
||||
if (displayBusyRef.current) return () => { active = false }
|
||||
api.GetVMDisplay(driverID, vm)
|
||||
.then((st) => {
|
||||
if (active && displayReqSeqRef.current === reqSeq) {
|
||||
setDisplayStatus(st)
|
||||
setDisplayErr('')
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (active && displayReqSeqRef.current === reqSeq) {
|
||||
setDisplayErr(parseAppError(e).summary)
|
||||
}
|
||||
})
|
||||
return () => { active = false }
|
||||
}, [driverID, vm, running, hostDisplaysSig, shown])
|
||||
|
||||
const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n })
|
||||
|
||||
const displayOptions = useMemo(() => {
|
||||
const opts: Array<{ value: string; label: string; detail?: string }> = [
|
||||
{
|
||||
value: PRIMARY_DISPLAY_OPT,
|
||||
label: tr('targetDisplayPrimaryDefault'),
|
||||
},
|
||||
...connectedDisplays
|
||||
.filter((d): d is DisplayInfo & { name: string } => Boolean(d.name?.trim()))
|
||||
.map((d, idx) => ({
|
||||
value: d.name,
|
||||
label: humanDisplayTitle(d, idx + 1, numberedDisplay),
|
||||
detail: humanDisplayMeta(d, d.primary ? tr('hostDisplayPrimary') : undefined),
|
||||
})),
|
||||
]
|
||||
const savedTarget = displayStatus?.target_display?.trim()
|
||||
if (savedTarget && displayStatus?.fallback_to_primary) {
|
||||
if (!opts.some((o) => o.value.toLowerCase() === savedTarget.toLowerCase())) {
|
||||
opts.push({
|
||||
value: savedTarget,
|
||||
label: humanDisplayFallbackName(savedTarget, numberedDisplay),
|
||||
detail: tr('targetDisplayDisconnectedOption'),
|
||||
})
|
||||
}
|
||||
}
|
||||
return opts
|
||||
}, [connectedDisplays, displayStatus?.fallback_to_primary, displayStatus?.target_display, locale])
|
||||
const selectedDisplayValue = useMemo(() => {
|
||||
const saved = displayStatus?.target_display?.trim()
|
||||
if (!saved) return PRIMARY_DISPLAY_OPT
|
||||
return displayOptions.find((o) => o.value.toLowerCase() === saved.toLowerCase())?.value ?? saved
|
||||
}, [displayOptions, displayStatus?.target_display])
|
||||
const activeTargetDisplayTitle = useMemo(() => {
|
||||
if (!activeTargetDisplay) return ''
|
||||
const idx = connectedDisplays.findIndex((d) => d === activeTargetDisplay || (d.name && activeTargetDisplay.name && d.name.toLowerCase() === activeTargetDisplay.name.toLowerCase()))
|
||||
return humanDisplayTitle(activeTargetDisplay, idx >= 0 ? idx + 1 : 1, numberedDisplay)
|
||||
}, [activeTargetDisplay, connectedDisplays, locale])
|
||||
const handleTargetDisplayChange = async (nextValue: string) => {
|
||||
if (isBlocked() || displayBusyRef.current || displayStatus === null) return
|
||||
const nextTarget = nextValue === PRIMARY_DISPLAY_OPT ? '' : nextValue
|
||||
const currentTarget = displayStatus.target_display ?? ''
|
||||
if (nextTarget.toLowerCase() === currentTarget.toLowerCase()) return
|
||||
|
||||
const opSeq = ++displayReqSeqRef.current
|
||||
displayBusyRef.current = true
|
||||
setDisplayBusy(true)
|
||||
setDisplayErr('')
|
||||
try {
|
||||
const next = await api.SetVMDisplay(driverID, vm, nextTarget)
|
||||
if (activeVMNameRef.current !== vm || displayReqSeqRef.current !== opSeq) return
|
||||
setDisplayStatus(next)
|
||||
const chosenLabel = displayOptions.find((o) => o.value === nextValue)?.label
|
||||
?? humanDisplayFallbackName(next.target_display, numberedDisplay)
|
||||
if (next.move_error) {
|
||||
onToast(errorToast(locale, tr('targetDisplayToastSaved', { display: chosenLabel }), next.move_error))
|
||||
} else {
|
||||
onToast({
|
||||
kind: 'ok',
|
||||
title: next.applied_live
|
||||
? tr('targetDisplayToastMoved', { display: chosenLabel })
|
||||
: tr('targetDisplayToastSaved', { display: chosenLabel }),
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current !== vm || displayReqSeqRef.current !== opSeq) return
|
||||
onToast(errorToast(locale, tr('targetDisplaySaveFailed'), e))
|
||||
} finally {
|
||||
if (displayReqSeqRef.current === opSeq) {
|
||||
displayBusyRef.current = false
|
||||
setDisplayBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
displayStatus, displayBusy, displayErr, connectedDisplays, activeTargetDisplay,
|
||||
activeTargetDisplayTitle, displayProfile, displayOptions, selectedDisplayValue, handleTargetDisplayChange,
|
||||
/** Whether a change is being saved right now, ahead of the next render. */
|
||||
isBusy: () => displayBusyRef.current,
|
||||
}
|
||||
}
|
||||
|
||||
interface RowProps {
|
||||
locale: Locale
|
||||
running: boolean
|
||||
disabled: boolean
|
||||
state: ReturnType<typeof useTargetDisplay>
|
||||
}
|
||||
|
||||
export const TargetDisplayRow: React.FC<RowProps> = ({ locale, running, disabled, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { displayStatus, displayBusy, displayErr, connectedDisplays, displayOptions, selectedDisplayValue, handleTargetDisplayChange } = state
|
||||
const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n })
|
||||
const targetDisplayDesc = displayStatus?.fallback_to_primary && displayStatus.target_display
|
||||
? (
|
||||
<span className="warn-text">
|
||||
{tr('targetDisplayFallbackHint', {
|
||||
name: humanDisplayFallbackName(displayStatus.target_display, numberedDisplay),
|
||||
})}
|
||||
</span>
|
||||
)
|
||||
: connectedDisplays.length === 0
|
||||
? tr('targetDisplayNoneHint')
|
||||
: connectedDisplays.length === 1
|
||||
? tr('targetDisplaySingleHint')
|
||||
: tr(running ? 'targetDisplayRunningHint' : 'targetDisplayStoppedHint')
|
||||
return (
|
||||
<SetRow
|
||||
title={tr('targetDisplayTitle')}
|
||||
desc={targetDisplayDesc}
|
||||
error={displayErr || undefined}
|
||||
disabled={disabled || displayBusy || displayStatus === null || (connectedDisplays.length === 0 && !displayStatus.target_display)}
|
||||
control={
|
||||
<PopupSelect
|
||||
label={tr('targetDisplayTitle')}
|
||||
value={selectedDisplayValue}
|
||||
onChange={(v) => void handleTargetDisplayChange(v)}
|
||||
options={displayOptions}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { Check, Copy } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { createVMSettingRequests, type VMSettingState } from '../../lib/vmSettingRequests'
|
||||
import { Locale, VMDetail } from '../../types'
|
||||
import { IconButton } from '../../ui/controls'
|
||||
import { PopupSelect, SetRow } from '../../ui/settings'
|
||||
import type { ToastInput } from '../../ui/toast'
|
||||
import { api } from '../../wails'
|
||||
|
||||
type VMTimezoneStatus = Awaited<ReturnType<typeof api.GetVMTimezone>>
|
||||
|
||||
const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command'
|
||||
const GUEST_TIMEZONE_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Timezone.command'
|
||||
|
||||
const GUEST_TIMEZONE_PRESETS: ReadonlyArray<{ value: string; labelKey: I18nKey; detail?: string }> = [
|
||||
{ value: 'Asia/Shanghai', labelKey: 'guestTimezoneShanghai', detail: 'Asia/Shanghai' },
|
||||
{ value: 'Asia/Hong_Kong', labelKey: 'guestTimezoneHongKong', detail: 'Asia/Hong_Kong' },
|
||||
{ value: 'Asia/Taipei', labelKey: 'guestTimezoneTaipei', detail: 'Asia/Taipei' },
|
||||
{ value: 'Asia/Tokyo', labelKey: 'guestTimezoneTokyo', detail: 'Asia/Tokyo' },
|
||||
{ value: 'Asia/Seoul', labelKey: 'guestTimezoneSeoul', detail: 'Asia/Seoul' },
|
||||
{ value: 'Asia/Singapore', labelKey: 'guestTimezoneSingapore', detail: 'Asia/Singapore' },
|
||||
{ value: 'Europe/London', labelKey: 'guestTimezoneLondon', detail: 'Europe/London' },
|
||||
{ value: 'Europe/Berlin', labelKey: 'guestTimezoneBerlin', detail: 'Europe/Berlin' },
|
||||
{ value: 'America/Los_Angeles', labelKey: 'guestTimezoneLosAngeles', detail: 'America/Los_Angeles' },
|
||||
{ value: 'America/New_York', labelKey: 'guestTimezoneNewYork', detail: 'America/New_York' },
|
||||
{ value: 'Australia/Sydney', labelKey: 'guestTimezoneSydney', detail: 'Australia/Sydney' },
|
||||
{ value: 'UTC', labelKey: 'guestTimezoneUTC' },
|
||||
]
|
||||
|
||||
/** The time zone the VM follows, refreshed while shown. */
|
||||
export function useGuestTimezone(driverID: string, vm: string, running: boolean, shown: boolean) {
|
||||
const vmSettingsKey = `${driverID}:${vm}`
|
||||
const activeVMKeyRef = useRef(vmSettingsKey)
|
||||
activeVMKeyRef.current = vmSettingsKey
|
||||
const [{ value: tzStatus, error: tzErr, busy: tzBusy }, setTzState] = useState<VMSettingState<VMTimezoneStatus>>({ value: null, error: '', busy: false })
|
||||
const [tzRequests] = useState(() => createVMSettingRequests<VMTimezoneStatus>(() => activeVMKeyRef.current,
|
||||
(patch) => setTzState((state) => ({ ...state, ...patch }))))
|
||||
|
||||
useEffect(() => {
|
||||
setTzState({ value: null, error: '', busy: tzRequests.isWriting(vmSettingsKey) })
|
||||
}, [vmSettingsKey, tzRequests])
|
||||
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const { refresh, stop } = tzRequests.watch(vmSettingsKey, () => api.GetVMTimezone(driverID, vm))
|
||||
void refresh()
|
||||
const timer = window.setInterval(refresh, 3000)
|
||||
return () => { stop(); window.clearInterval(timer) }
|
||||
}, [shown, driverID, vm, running, vmSettingsKey, tzRequests])
|
||||
|
||||
return {
|
||||
tzStatus,
|
||||
tzErr,
|
||||
tzBusy,
|
||||
/** Whether a change is being saved right now, ahead of the next render. */
|
||||
isWriting: () => tzRequests.isWriting(vmSettingsKey),
|
||||
write: (setting: string) => tzRequests.write(vmSettingsKey, () => api.SetVMTimezone(driverID, vm, setting)),
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
hostTimezone?: string
|
||||
state: ReturnType<typeof useGuestTimezone>
|
||||
disabled: boolean
|
||||
isBlocked: () => boolean
|
||||
onToast: (toast: ToastInput) => void
|
||||
onCopy?: (text: string) => void
|
||||
}
|
||||
|
||||
export const GuestTimezoneRow: React.FC<Props> = ({ locale, detail, hostTimezone, state, disabled, isBlocked, onToast, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { tzStatus, tzErr, tzBusy, write } = state
|
||||
|
||||
const updateTimezone = async (nextSetting: string) => {
|
||||
if (isBlocked() || !tzStatus) return
|
||||
const currentSetting = tzStatus.mode === 'off' ? 'off' : tzStatus.mode === 'custom' ? tzStatus.timezone : 'host'
|
||||
if (nextSetting === currentSetting) return
|
||||
if (await write(nextSetting)) {
|
||||
onToast({ kind: 'ok', title: tr('guestTimezoneSaved') })
|
||||
}
|
||||
}
|
||||
|
||||
const detectedHostTZ = tzStatus?.host_timezone || hostTimezone || ''
|
||||
const tzSelectedValue = tzStatus?.mode === 'custom' ? tzStatus.timezone : tzStatus?.mode
|
||||
const tzOptions = [
|
||||
{ value: 'host', label: tr('guestTimezoneHost'), detail: detectedHostTZ || undefined },
|
||||
...GUEST_TIMEZONE_PRESETS.map((p) => ({
|
||||
value: p.value,
|
||||
label: tr(p.labelKey),
|
||||
detail: p.detail,
|
||||
})),
|
||||
...(tzStatus?.mode === 'custom' && tzStatus.timezone && !GUEST_TIMEZONE_PRESETS.some((p) => p.value === tzStatus.timezone)
|
||||
? [{ value: tzStatus.timezone, label: tzStatus.timezone }]
|
||||
: []),
|
||||
{ value: 'off', label: tr('guestTimezoneOff') },
|
||||
]
|
||||
let tzDesc: React.ReactNode = tr('guestTimezoneDesc')
|
||||
let tzCommand = ''
|
||||
if (tzStatus) {
|
||||
const tzEffective = tzStatus.effective_timezone
|
||||
if (tzStatus.mode === 'off') {
|
||||
tzDesc = tr('guestTimezoneOffDesc')
|
||||
} else if (detail.guest_tools_disabled) {
|
||||
tzDesc = <span className="warn-text">{tr('gtStatusOffTip')}</span>
|
||||
} else if (!tzEffective) {
|
||||
tzDesc = <span className="warn-text">{tr('guestTimezoneHostUnknown')}</span>
|
||||
} else if (tzStatus.running && tzStatus.guest_connected) {
|
||||
const tzFailure = tzStatus.timezone_error
|
||||
? <span className="warn-text">{tr('guestTimezoneApplyFailed', { tz: tzEffective })}</span>
|
||||
: null
|
||||
if (tzStatus.guest_agent_version < tzStatus.required_agent_version) {
|
||||
tzDesc = <span className="warn-text">{tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzStatus.required_agent_version })}</span>
|
||||
if (detail.guest_tools_attached) tzCommand = GUEST_TOOLS_INSTALL_CMD
|
||||
} else if (!tzStatus.helper_ready) {
|
||||
const hint = tr(detail.guest_tools_attached ? 'guestTimezoneApplyHint' : 'guestTimezoneApplyAttachHint')
|
||||
tzDesc = tzFailure ? <div className="stack-1">{tzFailure}<span>{hint}</span></div> : hint
|
||||
if (detail.guest_tools_attached) tzCommand = GUEST_TIMEZONE_APPLY_CMD
|
||||
} else if (tzFailure) {
|
||||
tzDesc = tzFailure
|
||||
} else if (tzStatus.guest_applied === tzEffective) {
|
||||
tzDesc = <span className="ok-text"><Check size={12} aria-hidden="true" />{tr('guestTimezoneSynced', { tz: tzEffective })}</span>
|
||||
} else {
|
||||
tzDesc = tr('guestTimezoneSyncing', { tz: tzEffective })
|
||||
}
|
||||
} else if (detail.guest_tools_attached) {
|
||||
tzCommand = GUEST_TOOLS_INSTALL_CMD
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SetRow
|
||||
title={tr('guestTimezoneTitle')}
|
||||
desc={tzDesc}
|
||||
disabled={!tzStatus || tzBusy || disabled}
|
||||
error={tzErr || undefined}
|
||||
control={
|
||||
<PopupSelect
|
||||
label={tr('guestTimezoneTitle')}
|
||||
value={tzSelectedValue}
|
||||
placeholder={tr('guestTimezoneLoading')}
|
||||
onChange={updateTimezone}
|
||||
options={tzOptions}
|
||||
/>
|
||||
}
|
||||
block={tzCommand ? (
|
||||
<div className="cmd-line">
|
||||
<code>{tzCommand}</code>
|
||||
{onCopy && (
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(tzCommand)} />
|
||||
)}
|
||||
</div>
|
||||
) : undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { builtinDict, registerBuiltinDomain } from './i18n/runtime'
|
||||
export type { I18nKey }
|
||||
export { registerBuiltinDomain }
|
||||
|
||||
export interface LocaleOption {
|
||||
interface LocaleOption {
|
||||
value: Locale
|
||||
label: string
|
||||
detail?: string
|
||||
@@ -65,11 +65,11 @@ function primarySubtag(tag: string): string {
|
||||
return idx >= 0 ? s.slice(0, idx) : s
|
||||
}
|
||||
|
||||
export function isZhLocale(locale: Locale): boolean {
|
||||
function isZhLocale(locale: Locale): boolean {
|
||||
return primarySubtag(locale) === 'zh'
|
||||
}
|
||||
|
||||
export function isCJKLocale(locale: Locale): boolean {
|
||||
function isCJKLocale(locale: Locale): boolean {
|
||||
const p = primarySubtag(locale)
|
||||
return p === 'zh' || p === 'ja' || p === 'ko'
|
||||
}
|
||||
@@ -87,7 +87,7 @@ function isBuiltinLocale(locale: string): locale is BuiltinLocale {
|
||||
return locale === 'zh-CN' || locale === 'en-US'
|
||||
}
|
||||
|
||||
export function canonicalizeTag(raw: string | undefined): string {
|
||||
function canonicalizeTag(raw: string | undefined): string {
|
||||
if (!raw) return ''
|
||||
const clean = raw.trim().split(/[.@]/)[0].replaceAll('_', '-')
|
||||
const low = clean.toLowerCase()
|
||||
|
||||
@@ -177,8 +177,6 @@ export const coreZh: Record<string, string> = {
|
||||
"themeSystem": "跟随系统",
|
||||
"toastAffinityApplied": "处理器相关性已应用({count} 个逻辑处理器 · {mask})",
|
||||
"toastAffinitySaved": "处理器相关性已保存,下次启动时生效",
|
||||
"toastBorderlessNextStart": "已保存全屏启动偏好,重启虚拟机后生效",
|
||||
"toastBorderlessUpdated": "已保存全屏启动偏好",
|
||||
"toastCopied": "已复制",
|
||||
"toastCreateCanceled": "已取消创建 {name}",
|
||||
"toastCreateCanceledPartial": "已下载部分已保留,可继续下载或返回修改",
|
||||
@@ -390,8 +388,6 @@ export const coreEn: Record<string, string> = {
|
||||
"themeSystem": "System",
|
||||
"toastAffinityApplied": "Processor affinity applied ({count} logical CPUs · {mask})",
|
||||
"toastAffinitySaved": "Processor affinity saved for next start",
|
||||
"toastBorderlessNextStart": "Fullscreen launch saved — applies on next restart",
|
||||
"toastBorderlessUpdated": "Fullscreen launch preference saved",
|
||||
"toastCopied": "Copied",
|
||||
"toastCreateCanceled": "Canceled creating {name}",
|
||||
"toastCreateCanceledPartial": "Downloaded progress is kept; resume anytime or edit and retry",
|
||||
|
||||
@@ -14,7 +14,6 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginBuiltinSection": "内置插件",
|
||||
"pluginClearSecret": "清除",
|
||||
"pluginColorSchemes": "配色方案",
|
||||
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
|
||||
"pluginDeleteScheme": "删除方案",
|
||||
"pluginDisable": "停用",
|
||||
"pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件和挂起状态都会保留,重新启用即可恢复。运行中的虚拟机需要先停止或挂起。",
|
||||
@@ -70,7 +69,6 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
|
||||
"pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引",
|
||||
"pluginMarketSyncing": "正在同步插件市场",
|
||||
"pluginMarketUpdate": "更新至 v{version}",
|
||||
"pluginMarketUpdateShort": "更新",
|
||||
"pluginMarketVersionTip": "已安装 v{installed},可更新至 v{version}",
|
||||
"pluginMarketWithdrawn": "已撤回",
|
||||
@@ -98,7 +96,6 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginScanHardSection": "硬性拦截项(禁止安装)",
|
||||
"pluginScanInspect": "安全扫描",
|
||||
"pluginScanInstallConfirm": "确认导入安装",
|
||||
"pluginScanLoading": "正在扫描插件包…",
|
||||
"pluginScanModalTitle": "插件静态安全报告",
|
||||
"pluginScanMoreItems": "另有 {count} 项已折叠",
|
||||
"pluginSchemeDefault": "默认",
|
||||
@@ -139,7 +136,6 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginBuiltinSection": "Built-in plugins",
|
||||
"pluginClearSecret": "Clear",
|
||||
"pluginColorSchemes": "Color schemes",
|
||||
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
|
||||
"pluginDeleteScheme": "Delete scheme",
|
||||
"pluginDisable": "Disable",
|
||||
"pluginDisableInUseBody": "Its VMs will show as “Driver unavailable” and can’t be started or changed. Their files and any suspended state are kept; turning the plugin back on restores them. Stop or suspend any running VM first.",
|
||||
@@ -195,7 +191,6 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
|
||||
"pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data",
|
||||
"pluginMarketSyncing": "Syncing the plugin market",
|
||||
"pluginMarketUpdate": "Update to v{version}",
|
||||
"pluginMarketUpdateShort": "Update",
|
||||
"pluginMarketVersionTip": "v{installed} installed, v{version} available",
|
||||
"pluginMarketWithdrawn": "Withdrawn",
|
||||
@@ -223,7 +218,6 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginScanHardSection": "Hard blockers (install refused)",
|
||||
"pluginScanInspect": "Security scan",
|
||||
"pluginScanInstallConfirm": "Proceed with install",
|
||||
"pluginScanLoading": "Scanning plugin package…",
|
||||
"pluginScanModalTitle": "Plugin security report",
|
||||
"pluginScanMoreItems": "...and {count} more",
|
||||
"pluginSchemeDefault": "Default",
|
||||
|
||||
@@ -59,7 +59,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})",
|
||||
"affinityTitle": "处理器核心",
|
||||
"appCheckUpdate": "检查更新",
|
||||
"appDownloadUpdate": "前往下载",
|
||||
"appUpToDate": "已是最新",
|
||||
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
|
||||
"appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)",
|
||||
@@ -169,11 +168,9 @@ export const settingsZh: Record<string, string> = {
|
||||
"effectNextStart": "下次启动生效",
|
||||
"enableAudio": "音频",
|
||||
"enableLogs": "记录图形与串口日志",
|
||||
"enableNetwork": "网络(NAT)",
|
||||
"enableWHPX": "启用",
|
||||
"extraArgs": "额外 QEMU 参数",
|
||||
"extraArgsDesc": "原样追加到 QEMU 命令行",
|
||||
"failAffinity": "设置处理器相关性失败",
|
||||
"folderShareAdd": "添加目录…",
|
||||
"folderShareAddTitle": "宿主机目录",
|
||||
"folderShareConfirmRWAction": "改为读写",
|
||||
@@ -199,9 +196,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"folderShareRemove": "移除目录",
|
||||
"folderShareTitle": "自定义共享目录",
|
||||
"folderShareWritableWarn": "读写模式:macOS 中的修改和删除会直接作用于宿主机原目录",
|
||||
"footerDisk": "磁盘可用 {gb} GB",
|
||||
"footerMem": "内存 {pct}%",
|
||||
"footerMemAvail": "可用 {avail} GB",
|
||||
"forceQuitAppButton": "强制退出",
|
||||
"forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。",
|
||||
"forceQuitAppTitle": "强制退出 Reims-Go",
|
||||
@@ -247,7 +241,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"groupMacOS": "macOS",
|
||||
"groupPerformance": "性能",
|
||||
"groupQemu": "QEMU",
|
||||
"gtInstallCmd": "安装命令",
|
||||
"guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错",
|
||||
"guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言",
|
||||
"guestLangShort": "系统语言",
|
||||
@@ -279,9 +272,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"guestTimezoneUTC": "UTC(协调世界时)",
|
||||
"guestTimezoneUpgradeAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看升级到版本 {version} 的命令",
|
||||
"guestTimezoneUpgradeHint": "在 macOS 终端运行以下命令,将 Guest Tools 升级到版本 {version}",
|
||||
"guestToolsConnected": "已连接",
|
||||
"guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效",
|
||||
"guestToolsReady": "已配置",
|
||||
"hidpiPresetBadge": "HiDPI",
|
||||
"hostAudioInput": "Windows 麦克风",
|
||||
"hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音",
|
||||
@@ -356,7 +346,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"installersDownloaded": "已下载",
|
||||
"installersDownloadingForVM": "为 {vm} 下载中",
|
||||
"installersDownloadingPct": "下载中 {p}%",
|
||||
"installersEmpty": "还没有下载任何镜像",
|
||||
"installersHint": "下载好的镜像可以重复用来新建虚拟机",
|
||||
"installersKindOffline": "离线完整包",
|
||||
"installersKindOnline": "在线恢复镜像",
|
||||
@@ -422,10 +411,8 @@ export const settingsZh: Record<string, string> = {
|
||||
"navHasIssue": "这一页有需要修改的项",
|
||||
"nestedVirtDesc": "允许 macOS 运行自己的虚拟机,完全关机后再次启动时生效。",
|
||||
"nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。",
|
||||
"nestedVirtLabel": "嵌套虚拟化",
|
||||
"nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。",
|
||||
"networkBridge": "桥接",
|
||||
"networkDesc": "通过 Windows 的网络连接上网",
|
||||
"networkNAT": "NAT",
|
||||
"networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网",
|
||||
"networkTitle": "网络",
|
||||
@@ -436,7 +423,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"npcapInstalling": "正在准备 Npcap,在弹出的官方安装向导中完成安装后将自动重新检查",
|
||||
"npcapMissing": "未检测到完整安装;应用网络时自动从官网下载,也可提前安装。许可与 UAC 在官方向导确认",
|
||||
"npcapStopFirst": "安装驱动前需先关闭全部虚拟机",
|
||||
"offlineListFailed": "无法读取 Apple 的版本列表",
|
||||
"opencore": "OpenCore",
|
||||
"optAuto": "已自动开启",
|
||||
"optAvailable": "可用",
|
||||
@@ -449,11 +435,9 @@ export const settingsZh: Record<string, string> = {
|
||||
"optPCoreSub": "仅调度到性能核({detail}),减少卡顿",
|
||||
"optPCoreUnavailable": "当前处理器无大小核架构,无需开启",
|
||||
"optRecommended": "推荐",
|
||||
"optSchedBackground": "后台服务",
|
||||
"optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)",
|
||||
"optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)",
|
||||
"optSchedOpen": "更改…",
|
||||
"optSchedPrograms": "程序优先",
|
||||
"optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)",
|
||||
"optSchedTitle": "Windows 处理器调度",
|
||||
"optUnavailable": "不可用",
|
||||
@@ -462,7 +446,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"recommendedBadge": "推荐",
|
||||
"resCustom": "自定义",
|
||||
"resCustomSub": "宽 × 高",
|
||||
"resFullscreen": "全屏",
|
||||
"resInvalid": "格式为 宽x高,例如 2560x1600",
|
||||
"resNativeBadge": "原生",
|
||||
"resScaleToFitWindow": "缩放以适应窗口",
|
||||
@@ -504,11 +487,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"sshOffDesc": "从 Windows 用 SSH 登录 macOS",
|
||||
"sshPort": "SSH 转发端口",
|
||||
"startAfterCreate": "创建后立即启动",
|
||||
"statsCPU": "QEMU CPU",
|
||||
"statsDisk": "磁盘占用",
|
||||
"statsDiskSub": "实际 {actual} / 上限 {virtual}",
|
||||
"statsMemory": "宿主机内存",
|
||||
"statsUptime": "运行时长",
|
||||
"stopBeforeDiskOp": "关机后才能操作",
|
||||
"stopTimeout": "关机等待时间",
|
||||
"stopTimeoutHint": "0 表示一直等待",
|
||||
@@ -547,7 +525,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"vcpus": "虚拟处理器",
|
||||
"vmDir": "存放目录",
|
||||
"vmName": "名称",
|
||||
"welcomeCheckHost": "先完成内核环境配置 →",
|
||||
"welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置",
|
||||
"welcomeTitle": "创建第一台 macOS 虚拟机",
|
||||
"whpxHvOff": "Hypervisor 启动已关闭,启用后重启 Windows",
|
||||
@@ -624,7 +601,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"affinitySummaryPCores": "P-Cores ({count}T · {mask})",
|
||||
"affinityTitle": "CPU cores",
|
||||
"appCheckUpdate": "Check for updates",
|
||||
"appDownloadUpdate": "Download",
|
||||
"appUpToDate": "Up to date",
|
||||
"appUpdateAvailable": "New stable release {v} available",
|
||||
"appUpdateAvailableAlpha": "New alpha release {v} available",
|
||||
@@ -734,11 +710,9 @@ export const settingsEn: Record<string, string> = {
|
||||
"effectNextStart": "Next start",
|
||||
"enableAudio": "Audio",
|
||||
"enableLogs": "Keep graphics and serial logs",
|
||||
"enableNetwork": "Network (NAT)",
|
||||
"enableWHPX": "Enable",
|
||||
"extraArgs": "Extra QEMU arguments",
|
||||
"extraArgsDesc": "Appended to the QEMU command line as is",
|
||||
"failAffinity": "Could not update processor affinity",
|
||||
"folderShareAdd": "Add folder…",
|
||||
"folderShareAddTitle": "Host folders",
|
||||
"folderShareConfirmRWAction": "Enable read-write",
|
||||
@@ -764,9 +738,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"folderShareRemove": "Remove folder",
|
||||
"folderShareTitle": "Custom shared folders",
|
||||
"folderShareWritableWarn": "Read-write: changes and deletions in macOS modify the host folder directly",
|
||||
"footerDisk": "Disk {gb} GB free",
|
||||
"footerMem": "Memory {pct}%",
|
||||
"footerMemAvail": "{avail} GB free",
|
||||
"forceQuitAppButton": "Force quit",
|
||||
"forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.",
|
||||
"forceQuitAppTitle": "Force quit Reims-Go",
|
||||
@@ -812,7 +783,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"groupMacOS": "macOS",
|
||||
"groupPerformance": "Performance",
|
||||
"groupQemu": "QEMU",
|
||||
"gtInstallCmd": "Install command",
|
||||
"guestLangHint": "Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable",
|
||||
"guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window",
|
||||
"guestLangShort": "System language",
|
||||
@@ -844,9 +814,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"guestTimezoneUTC": "UTC",
|
||||
"guestTimezoneUpgradeAttachHint": "Attach the Guest Tools image on the VM details page to see the command for updating to version {version}",
|
||||
"guestTimezoneUpgradeHint": "Run the command below in macOS Terminal to update Guest Tools to version {version}",
|
||||
"guestToolsConnected": "Connected",
|
||||
"guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately",
|
||||
"guestToolsReady": "Configured",
|
||||
"hidpiPresetBadge": "HiDPI",
|
||||
"hostAudioInput": "Windows microphone",
|
||||
"hostAudioMissingIn": "No microphone found; macOS will record silence",
|
||||
@@ -921,7 +888,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"installersDownloaded": "Downloaded",
|
||||
"installersDownloadingForVM": "Downloading for {vm}",
|
||||
"installersDownloadingPct": "Downloading {p}%",
|
||||
"installersEmpty": "No images downloaded yet",
|
||||
"installersHint": "Downloaded images can be reused for new VMs",
|
||||
"installersKindOffline": "Offline installer",
|
||||
"installersKindOnline": "Online recovery",
|
||||
@@ -987,10 +953,8 @@ export const settingsEn: Record<string, string> = {
|
||||
"navHasIssue": "This page has settings to fix",
|
||||
"nestedVirtDesc": "Lets macOS run its own virtual machines. Applies on a full restart.",
|
||||
"nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.",
|
||||
"nestedVirtLabel": "Nested virtualization",
|
||||
"nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.",
|
||||
"networkBridge": "Bridged",
|
||||
"networkDesc": "Uses the Windows network connection",
|
||||
"networkNAT": "NAT",
|
||||
"networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking",
|
||||
"networkTitle": "Network",
|
||||
@@ -1001,7 +965,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"npcapInstalling": "Preparing Npcap. Complete the official installer; availability will be checked afterwards",
|
||||
"npcapMissing": "A complete installation was not detected. Downloaded from the official website when applying, or install now. Confirm the license and UAC in the official wizard",
|
||||
"npcapStopFirst": "Shut down all VMs before installing the driver",
|
||||
"offlineListFailed": "Couldn’t read Apple’s release list",
|
||||
"opencore": "OpenCore",
|
||||
"optAuto": "Automatic",
|
||||
"optAvailable": "Available",
|
||||
@@ -1014,11 +977,9 @@ export const settingsEn: Record<string, string> = {
|
||||
"optPCoreSub": "Schedule QEMU on performance cores only ({detail})",
|
||||
"optPCoreUnavailable": "CPU has no hybrid P/E cores",
|
||||
"optRecommended": "Recommended",
|
||||
"optSchedBackground": "Background services",
|
||||
"optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)",
|
||||
"optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)",
|
||||
"optSchedOpen": "Change…",
|
||||
"optSchedPrograms": "Programs",
|
||||
"optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)",
|
||||
"optSchedTitle": "Windows processor scheduling",
|
||||
"optUnavailable": "Unavailable",
|
||||
@@ -1027,7 +988,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"recommendedBadge": "Recommended",
|
||||
"resCustom": "Custom",
|
||||
"resCustomSub": "Width × height",
|
||||
"resFullscreen": "Full screen",
|
||||
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
|
||||
"resNativeBadge": "Native",
|
||||
"resScaleToFitWindow": "Scale to fit window",
|
||||
@@ -1069,11 +1029,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"sshOffDesc": "Log in to macOS over SSH from Windows",
|
||||
"sshPort": "SSH forward port",
|
||||
"startAfterCreate": "Start after creating",
|
||||
"statsCPU": "QEMU CPU",
|
||||
"statsDisk": "Disk usage",
|
||||
"statsDiskSub": "{actual} actual / {virtual} max",
|
||||
"statsMemory": "Host RAM",
|
||||
"statsUptime": "Uptime",
|
||||
"stopBeforeDiskOp": "Shut down the VM first",
|
||||
"stopTimeout": "Shutdown timeout",
|
||||
"stopTimeoutHint": "0 waits indefinitely",
|
||||
@@ -1112,7 +1067,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"vcpus": "Virtual CPUs",
|
||||
"vmDir": "Folder",
|
||||
"vmName": "Name",
|
||||
"welcomeCheckHost": "Set up Engine first →",
|
||||
"welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes",
|
||||
"welcomeTitle": "Create your first macOS VM",
|
||||
"whpxHvOff": "Hypervisor launch is off — enable and restart Windows",
|
||||
|
||||
@@ -139,6 +139,7 @@ export const vmZh: Record<string, string> = {
|
||||
"hostDNSStatusPending": "待应用",
|
||||
"hostDNSStatusStale": "配置已过期",
|
||||
"hostDNSStatusStillActive": "macOS 代理未移除",
|
||||
"nestedVirtLabel": "嵌套虚拟化",
|
||||
"netBridge": "桥接网络",
|
||||
"netCustom": "自定义网络",
|
||||
"netOff": "无网络",
|
||||
@@ -394,6 +395,7 @@ export const vmEn: Record<string, string> = {
|
||||
"hostDNSStatusPending": "Not applied",
|
||||
"hostDNSStatusStale": "Config outdated",
|
||||
"hostDNSStatusStillActive": "Still active in macOS",
|
||||
"nestedVirtLabel": "Nested virtualization",
|
||||
"netBridge": "Bridged network",
|
||||
"netCustom": "Custom network",
|
||||
"netOff": "No network",
|
||||
|
||||
@@ -51,7 +51,7 @@ export function formatLocaleNumber(locale: string, value: number, precision = -1
|
||||
const MAX_ICU_DEPTH = 16
|
||||
const MAX_ICU_TEMPLATE_LEN = 16384
|
||||
|
||||
export function parseICU(tmpl: string): ICUNode[] | null {
|
||||
function parseICU(tmpl: string): ICUNode[] | null {
|
||||
if (tmpl.length > MAX_ICU_TEMPLATE_LEN) return null
|
||||
if (astCache.has(tmpl)) {
|
||||
return astCache.get(tmpl) ?? null
|
||||
|
||||
@@ -59,7 +59,6 @@ export type I18nKey =
|
||||
| "affinitySummaryPCores"
|
||||
| "affinityTitle"
|
||||
| "appCheckUpdate"
|
||||
| "appDownloadUpdate"
|
||||
| "appUpToDate"
|
||||
| "appUpdateAvailable"
|
||||
| "appUpdateAvailableAlpha"
|
||||
@@ -245,7 +244,6 @@ export type I18nKey =
|
||||
| "emptyVMs"
|
||||
| "enableAudio"
|
||||
| "enableLogs"
|
||||
| "enableNetwork"
|
||||
| "enableWHPX"
|
||||
| "endpointCopyADB"
|
||||
| "endpointEditConnection"
|
||||
@@ -278,7 +276,6 @@ export type I18nKey =
|
||||
| "factGraphics"
|
||||
| "factGuestOS"
|
||||
| "factMemory"
|
||||
| "failAffinity"
|
||||
| "failAttachInstaller"
|
||||
| "failCloneVM"
|
||||
| "failCreate"
|
||||
@@ -346,14 +343,11 @@ export type I18nKey =
|
||||
| "folderShareTitle"
|
||||
| "folderShareWritableWarn"
|
||||
| "fontMissingFoDHint"
|
||||
| "footerDisk"
|
||||
| "footerDiskLabel"
|
||||
| "footerDiskTip"
|
||||
| "footerDiskValue"
|
||||
| "footerHostIssue"
|
||||
| "footerHostIssueTip"
|
||||
| "footerMem"
|
||||
| "footerMemAvail"
|
||||
| "footerMemLabel"
|
||||
| "footerMemTip"
|
||||
| "footerMemValue"
|
||||
@@ -412,7 +406,6 @@ export type I18nKey =
|
||||
| "groupPerformance"
|
||||
| "groupQemu"
|
||||
| "gtInstall"
|
||||
| "gtInstallCmd"
|
||||
| "gtInstallSub"
|
||||
| "gtNotInstalledDesc"
|
||||
| "gtStatusConnected"
|
||||
@@ -464,13 +457,10 @@ export type I18nKey =
|
||||
| "guestTimezoneUTC"
|
||||
| "guestTimezoneUpgradeAttachHint"
|
||||
| "guestTimezoneUpgradeHint"
|
||||
| "guestToolsConnected"
|
||||
| "guestToolsHostDNS"
|
||||
| "guestToolsModeSync"
|
||||
| "guestToolsModeWebDAV"
|
||||
| "guestToolsPreventSleep"
|
||||
| "guestToolsPreventSleepSub"
|
||||
| "guestToolsReady"
|
||||
| "guestToolsSleepActive"
|
||||
| "guestToolsTitle"
|
||||
| "guestToolsUpgradeHint"
|
||||
@@ -588,7 +578,6 @@ export type I18nKey =
|
||||
| "installersDownloading"
|
||||
| "installersDownloadingForVM"
|
||||
| "installersDownloadingPct"
|
||||
| "installersEmpty"
|
||||
| "installersHint"
|
||||
| "installersKindOffline"
|
||||
| "installersKindOnline"
|
||||
@@ -694,7 +683,6 @@ export type I18nKey =
|
||||
| "netOff"
|
||||
| "netShared"
|
||||
| "networkBridge"
|
||||
| "networkDesc"
|
||||
| "networkNAT"
|
||||
| "networkOfflineHint"
|
||||
| "networkTitle"
|
||||
@@ -712,7 +700,6 @@ export type I18nKey =
|
||||
| "offlineCached"
|
||||
| "offlineDownloading"
|
||||
| "offlineHint"
|
||||
| "offlineListFailed"
|
||||
| "offlineListFailedDetail"
|
||||
| "offlineLoading"
|
||||
| "offlineQueued"
|
||||
@@ -737,11 +724,9 @@ export type I18nKey =
|
||||
| "optPCoreSub"
|
||||
| "optPCoreUnavailable"
|
||||
| "optRecommended"
|
||||
| "optSchedBackground"
|
||||
| "optSchedNowBackground"
|
||||
| "optSchedNowPrograms"
|
||||
| "optSchedOpen"
|
||||
| "optSchedPrograms"
|
||||
| "optSchedSub"
|
||||
| "optSchedTitle"
|
||||
| "optUnavailable"
|
||||
@@ -767,7 +752,6 @@ export type I18nKey =
|
||||
| "pluginBuiltinSection"
|
||||
| "pluginClearSecret"
|
||||
| "pluginColorSchemes"
|
||||
| "pluginColorSchemesHint"
|
||||
| "pluginDeleteScheme"
|
||||
| "pluginDisable"
|
||||
| "pluginDisableInUseBody"
|
||||
@@ -823,7 +807,6 @@ export type I18nKey =
|
||||
| "pluginMarketSearchPlaceholder"
|
||||
| "pluginMarketStaleBanner"
|
||||
| "pluginMarketSyncing"
|
||||
| "pluginMarketUpdate"
|
||||
| "pluginMarketUpdateShort"
|
||||
| "pluginMarketVersionTip"
|
||||
| "pluginMarketWithdrawn"
|
||||
@@ -852,7 +835,6 @@ export type I18nKey =
|
||||
| "pluginScanHardSection"
|
||||
| "pluginScanInspect"
|
||||
| "pluginScanInstallConfirm"
|
||||
| "pluginScanLoading"
|
||||
| "pluginScanModalTitle"
|
||||
| "pluginScanMoreItems"
|
||||
| "pluginSchemeDefault"
|
||||
@@ -884,7 +866,6 @@ export type I18nKey =
|
||||
| "refresh"
|
||||
| "resCustom"
|
||||
| "resCustomSub"
|
||||
| "resFullscreen"
|
||||
| "resInvalid"
|
||||
| "resLooksLike"
|
||||
| "resNativeBadge"
|
||||
@@ -1051,11 +1032,6 @@ export type I18nKey =
|
||||
| "state_stopping"
|
||||
| "state_suspended"
|
||||
| "state_suspending"
|
||||
| "statsCPU"
|
||||
| "statsDisk"
|
||||
| "statsDiskSub"
|
||||
| "statsMemory"
|
||||
| "statsUptime"
|
||||
| "step1"
|
||||
| "step2"
|
||||
| "step3"
|
||||
@@ -1121,8 +1097,6 @@ export type I18nKey =
|
||||
| "themeSystem"
|
||||
| "toastAffinityApplied"
|
||||
| "toastAffinitySaved"
|
||||
| "toastBorderlessNextStart"
|
||||
| "toastBorderlessUpdated"
|
||||
| "toastCloned"
|
||||
| "toastCopied"
|
||||
| "toastCreateCanceled"
|
||||
@@ -1208,7 +1182,6 @@ export type I18nKey =
|
||||
| "vmDir"
|
||||
| "vmName"
|
||||
| "vulkanProbeFailed"
|
||||
| "welcomeCheckHost"
|
||||
| "welcomeSub"
|
||||
| "welcomeTitle"
|
||||
| "whpxHvOff"
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
// visibility:hidden/collapse, [hidden], [inert], aria-hidden="true",
|
||||
// data-state="closed") must not block global shortcuts or menu focus return.
|
||||
|
||||
export interface DialogLikeElement {
|
||||
interface DialogLikeElement {
|
||||
getAttribute(name: string): string | null
|
||||
closest?(selector: string): unknown
|
||||
parentElement?: DialogLikeElement | null
|
||||
}
|
||||
|
||||
export interface ComputedVisibility {
|
||||
interface ComputedVisibility {
|
||||
display: string
|
||||
visibility: string
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { VMEndpoint, VMInfo, VMListItem } from '../types'
|
||||
// Guest family, driver capabilities and endpoint ordering for non-macOS guests.
|
||||
// Everything here is pure so node:test can load it (scripts/test-endpoints.mjs).
|
||||
|
||||
export const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
|
||||
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
|
||||
|
||||
export type GuestFamily = 'macos' | 'linux' | 'windows' | 'android' | ''
|
||||
|
||||
@@ -85,7 +85,7 @@ export function vmFeatures(vm?: { driver_id?: string; capabilities?: readonly st
|
||||
/** Highest priority first: the first ready endpoint in this order is the primary hosted action. */
|
||||
export const ENDPOINT_PRIORITY = ['vmconnect', 'rdp', 'wsl', 'ssh', 'adb'] as const
|
||||
|
||||
export type EndpointKind = (typeof ENDPOINT_PRIORITY)[number]
|
||||
type EndpointKind = (typeof ENDPOINT_PRIORITY)[number]
|
||||
|
||||
export type EndpointAction = 'open' | 'terminal' | 'vscode' | 'config' | 'edit' | 'shell' | 'copy'
|
||||
|
||||
@@ -102,7 +102,7 @@ function rank(kind: string): number {
|
||||
return i < 0 ? ENDPOINT_PRIORITY.length : i
|
||||
}
|
||||
|
||||
export function isEndpointKind(kind: string): kind is EndpointKind {
|
||||
function isEndpointKind(kind: string): kind is EndpointKind {
|
||||
return rank(kind) < ENDPOINT_PRIORITY.length
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ export function secondaryEndpointActions(kind: string): EndpointAction[] {
|
||||
return endpointActions(kind).slice(1)
|
||||
}
|
||||
|
||||
export interface EndpointSplit {
|
||||
interface EndpointSplit {
|
||||
/** The highest-priority ready endpoint; absent when none is ready. */
|
||||
primary?: VMEndpoint
|
||||
/** All other endpoints in priority order, never the primary one. */
|
||||
|
||||
+13
-15
@@ -10,10 +10,6 @@ function currentDocLocale(): string {
|
||||
// Human-readable values for the main view (see docs/design-guidelines.md).
|
||||
// Raw values stay available under "Technical details".
|
||||
|
||||
export function formatNameList(locale: Locale, names: string[]): string {
|
||||
return new Intl.ListFormat(locale === 'auto' ? currentDocLocale() : locale, { style: 'long', type: 'conjunction' }).format(names)
|
||||
}
|
||||
|
||||
const MEMORY_CHOICES = [4, 6, 8, 12, 16, 24, 32, 48, 64]
|
||||
|
||||
/**
|
||||
@@ -143,7 +139,7 @@ export function shortGPUName(name: string): string {
|
||||
}
|
||||
|
||||
/** "1920x1080" → "1080p"; non-16:9 sizes keep "W×H". */
|
||||
export function resolutionLabel(raw: string): string {
|
||||
function resolutionLabel(raw: string): string {
|
||||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(raw ?? '')
|
||||
if (!m) return raw
|
||||
const w = Number(m[1]), h = Number(m[2])
|
||||
@@ -171,6 +167,17 @@ export function sshCommand(port: number): string {
|
||||
return `ssh -p ${port} 127.0.0.1`
|
||||
}
|
||||
|
||||
/** A point in time as a short date and time of day; empty when it is unknown. */
|
||||
export function formatShortTime(ms: number, locale: Locale): string {
|
||||
if (!ms) return ''
|
||||
try {
|
||||
const loc = locale === 'en-XA' ? 'en-US' : locale
|
||||
return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(ms))
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number, locale?: Locale): string {
|
||||
if (!bytes || bytes <= 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
@@ -426,7 +433,7 @@ export function recommendedResolution(host: HostReport): string {
|
||||
return rec?.resolution ?? '1920x1080'
|
||||
}
|
||||
|
||||
export interface GuestLangPreset {
|
||||
interface GuestLangPreset {
|
||||
value: string
|
||||
labelKey: I18nKey
|
||||
detailKey?: I18nKey
|
||||
@@ -472,15 +479,6 @@ export function guestLangLabel(locale: Locale, code: string | undefined): string
|
||||
return detail ? `${label} (${detail})` : label
|
||||
}
|
||||
|
||||
/**
|
||||
* Split "简体中文(美式键盘,推荐)" / "Simplified Chinese (US Keyboard)" into a
|
||||
* pop-up label and its grey detail, so the menu reads like macOS.
|
||||
*/
|
||||
export function splitLangLabel(value: string, text: string): { value: string; label: string; detail?: string } {
|
||||
const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text)
|
||||
return m ? { value, label: m[1], detail: m[2] } : { value, label: text }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
export const DEFAULT_FULLSCREEN_HOTKEY = 'Ctrl+Shift+F'
|
||||
|
||||
export interface HotkeyModifiers {
|
||||
interface HotkeyModifiers {
|
||||
ctrl: boolean
|
||||
shift: boolean
|
||||
alt: boolean
|
||||
win: boolean
|
||||
}
|
||||
|
||||
export interface HotkeyKeyEventLike {
|
||||
interface HotkeyKeyEventLike {
|
||||
code?: string
|
||||
key?: string
|
||||
ctrlKey?: boolean
|
||||
@@ -17,15 +17,15 @@ export interface HotkeyKeyEventLike {
|
||||
repeat?: boolean
|
||||
}
|
||||
|
||||
export type FullscreenHotkeyErrorReason = 'unsupported' | 'needs_modifier' | 'reserved'
|
||||
type FullscreenHotkeyErrorReason = 'unsupported' | 'needs_modifier' | 'reserved'
|
||||
|
||||
export type FullscreenHotkeyCaptureResult =
|
||||
type FullscreenHotkeyCaptureResult =
|
||||
| { kind: 'cancel' }
|
||||
| { kind: 'ignore' }
|
||||
| { kind: 'ok'; hotkey: string }
|
||||
| { kind: 'error'; reason: FullscreenHotkeyErrorReason; hotkey?: string }
|
||||
|
||||
export type FullscreenHotkeyParseResult =
|
||||
type FullscreenHotkeyParseResult =
|
||||
| { ok: true; hotkey: string }
|
||||
| { ok: false; reason: FullscreenHotkeyErrorReason | 'invalid'; hotkey?: string }
|
||||
|
||||
@@ -100,11 +100,11 @@ const CODE_TO_KEY: Record<string, string> = {
|
||||
ArrowRight: 'Right',
|
||||
}
|
||||
|
||||
export function isFunctionKey(key: string): boolean {
|
||||
function isFunctionKey(key: string): boolean {
|
||||
return /^F(?:[1-9]|1[0-2])$/.test(key)
|
||||
}
|
||||
|
||||
export function isReservedFullscreenHotkey(mods: HotkeyModifiers, key: string): boolean {
|
||||
function isReservedFullscreenHotkey(mods: HotkeyModifiers, key: string): boolean {
|
||||
return (
|
||||
(mods.ctrl && mods.alt && key === 'Delete') ||
|
||||
(mods.alt && (key === 'F4' || key === 'Tab')) ||
|
||||
@@ -158,7 +158,7 @@ function mapEventPrimaryKey(e: HotkeyKeyEventLike): string | null {
|
||||
return normalizePrimaryToken(key, EVENT_KEY_ALIASES)
|
||||
}
|
||||
|
||||
export function parseFullscreenHotkey(raw: string): FullscreenHotkeyParseResult {
|
||||
function parseFullscreenHotkey(raw: string): FullscreenHotkeyParseResult {
|
||||
const input = trimGoSpace(raw) || DEFAULT_FULLSCREEN_HOTKEY
|
||||
const mods: HotkeyModifiers = { ctrl: false, shift: false, alt: false, win: false }
|
||||
let primary = ''
|
||||
|
||||
@@ -3,7 +3,7 @@ import { I18nKey, t } from '../i18n'
|
||||
import { vmRefKey } from './vmRef'
|
||||
import type { Config, HostReport, Locale, Task, VMListItem } from '../types'
|
||||
|
||||
export interface HypervisorSettingsView {
|
||||
interface HypervisorSettingsView {
|
||||
supported: boolean
|
||||
gateEnabled: boolean
|
||||
expanded: boolean
|
||||
@@ -18,7 +18,7 @@ export interface HypervisorSettingsView {
|
||||
showHVCINotice: boolean
|
||||
}
|
||||
|
||||
export interface HostWHPXSummary {
|
||||
interface HostWHPXSummary {
|
||||
short: string
|
||||
hint: string
|
||||
tone: 'ok' | 'warn'
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { LogEntry } from '../types'
|
||||
|
||||
export type LogLevel = 'info' | 'warn' | 'error'
|
||||
type LogLevel = 'info' | 'warn' | 'error'
|
||||
|
||||
export interface LogLine extends LogEntry {
|
||||
id: number
|
||||
level: LogLevel
|
||||
}
|
||||
|
||||
export const MAX_LOG_LINES = 2000
|
||||
const MAX_LOG_LINES = 2000
|
||||
|
||||
// Progress no longer reaches the log: the backend turns it into tasks
|
||||
// (tasks.go, "reims:task"). Levels are still guessed from the text until the
|
||||
@@ -17,7 +17,7 @@ const WARN_RE = /\bwarn(ing)?\b/i
|
||||
|
||||
let nextId = 1
|
||||
|
||||
export function classify(entry: LogEntry): LogLine {
|
||||
function classify(entry: LogEntry): LogLine {
|
||||
const ts = typeof entry?.ts === 'string' ? entry.ts : ''
|
||||
const source = typeof entry?.source === 'string' ? entry.source : ''
|
||||
const line = typeof entry?.line === 'string' ? entry.line : String(entry?.line ?? '')
|
||||
|
||||
@@ -2,7 +2,7 @@ import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, Optimization, OptimizationStatus } from '../types'
|
||||
|
||||
export type KernelIrqchipMode = 'auto' | 'on' | 'off'
|
||||
type KernelIrqchipMode = 'auto' | 'on' | 'off'
|
||||
|
||||
export function findOptimization(list: Optimization[] | undefined, id: string): Optimization | undefined {
|
||||
return (list ?? []).find((o) => o.id === id)
|
||||
|
||||
@@ -19,7 +19,7 @@ export interface PluginFormResult {
|
||||
values?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface PluginViewActionHandlers {
|
||||
interface PluginViewActionHandlers {
|
||||
invoke(method: string, params: Record<string, unknown>): Promise<unknown>
|
||||
confirm(request: PluginConfirmRequest): Promise<boolean>
|
||||
showForm(request: PluginFormRequest): Promise<PluginFormResult>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export type PluginHostEvent = 'vm.stateChanged' | 'task.updated'
|
||||
export type PluginHostEventListener = (event: PluginHostEvent, data: unknown) => void
|
||||
type PluginHostEvent = 'vm.stateChanged' | 'task.updated'
|
||||
type PluginHostEventListener = (event: PluginHostEvent, data: unknown) => void
|
||||
|
||||
const listeners = new Set<PluginHostEventListener>()
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type PluginViewLocation = 'sidebar' | 'vm.tab' | 'settings' | 'dialog'
|
||||
type PluginViewLocation = 'sidebar' | 'vm.tab' | 'settings' | 'dialog'
|
||||
|
||||
export interface PluginViewRoute {
|
||||
pluginId: string
|
||||
|
||||
@@ -93,14 +93,14 @@ export function taskInstallerKey(task: Task): string {
|
||||
return `${kind}:${v}`
|
||||
}
|
||||
|
||||
export function matchesOnlineInstallerTitle(title: string | undefined, target: string): boolean {
|
||||
function matchesOnlineInstallerTitle(title: string | undefined, target: string): boolean {
|
||||
const want = target.trim().toLowerCase()
|
||||
if (!want) return false
|
||||
const norm = (title ?? '').trim().toLowerCase().replace(/^macos\s+/, '')
|
||||
return norm === want || norm.replace(/\s+/g, '-') === want
|
||||
}
|
||||
|
||||
export function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean {
|
||||
function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean {
|
||||
if (!isActiveInstallerTask(task)) return false
|
||||
const kind = taskInstallerKind(task)
|
||||
if (!kind || kind !== item.kind) return false
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import { UI_CONTRACT_LAYOUT_OPTIONS, UI_CONTRACT_TOKENS, type UIContractSDKEvent } from '../styles/ui-contract'
|
||||
import type { ActiveThemePayload, ThemeDecoration, ThemeDecorationState, TokenDeriveRule } from '../types'
|
||||
import type { ThemeSDKHostActions, UIStateSnapshot } from './uiSdk'
|
||||
|
||||
const LEGACY_CACHE_KEY = 'reims-go-theme-tokens-v1'
|
||||
const THEME_CACHE_KEY = 'reims-go-theme-tokens-v2'
|
||||
@@ -26,27 +27,6 @@ interface ThemeTokenCache {
|
||||
dark?: Record<string, string>
|
||||
}
|
||||
|
||||
export interface UIStateSnapshot {
|
||||
appearance: 'light' | 'dark'
|
||||
motion: 'full' | 'reduced'
|
||||
locale: string
|
||||
dir: 'ltr' | 'rtl'
|
||||
view: string
|
||||
vmName: string
|
||||
vmState: string
|
||||
busy: boolean
|
||||
hasError: boolean
|
||||
sidebarCollapsed: boolean
|
||||
safeMode: boolean
|
||||
vms: Array<{ name: string; state: string }>
|
||||
}
|
||||
|
||||
export interface ThemeSDKHostActions {
|
||||
toggleSidebar: () => void
|
||||
openSettings: () => void
|
||||
focusVMWindow: (name: string) => void
|
||||
}
|
||||
|
||||
let activeUIScriptCleanup: (() => void) | null = null
|
||||
let activeUIScriptNotifier: ((snap: UIStateSnapshot) => void) | null = null
|
||||
let activeUIScriptURL = ''
|
||||
@@ -86,7 +66,7 @@ function decodeCSSEscapes(s: string): string {
|
||||
}
|
||||
|
||||
/** Validates a token key+value against the UI Contract whitelist and CSS injection rules. */
|
||||
export function sanitizeTokenValue(key: string, value: string): string | null {
|
||||
function sanitizeTokenValue(key: string, value: string): string | null {
|
||||
if (!ALLOWED_CONTRACT_TOKENS.has(key)) return null
|
||||
if (typeof value !== 'string') return null
|
||||
const trimmed = value.trim()
|
||||
@@ -133,7 +113,7 @@ const LAYOUT_ATTRS: Record<string, string> = {
|
||||
const ALLOWED_LAYOUT = new Set<string>(UI_CONTRACT_LAYOUT_OPTIONS)
|
||||
|
||||
/** Writes the active theme's layout options as data-layout-* attributes; null clears them. */
|
||||
export function applyThemeLayout(layout: Record<string, unknown> | null | undefined): void {
|
||||
function applyThemeLayout(layout: Record<string, unknown> | null | undefined): void {
|
||||
const el = document.documentElement
|
||||
for (const [option, attr] of Object.entries(LAYOUT_ATTRS)) {
|
||||
const value = layout?.[option]
|
||||
@@ -143,7 +123,7 @@ export function applyThemeLayout(layout: Record<string, unknown> | null | undefi
|
||||
}
|
||||
|
||||
/** Verifies stylesheet has balanced braces and no unclosed strings/comments so it cannot escape `@layer theme`. */
|
||||
export function isBalancedThemeCSS(css: string): boolean {
|
||||
function isBalancedThemeCSS(css: string): boolean {
|
||||
if (css.toLowerCase().includes('</style')) return false
|
||||
let depth = 0
|
||||
const n = css.length
|
||||
@@ -655,18 +635,3 @@ export function disposeActiveThemeAndLocaleFonts(): void {
|
||||
export function notifyInteractiveThemeState(snap: UIStateSnapshot): void {
|
||||
activeUIScriptNotifier?.(snap)
|
||||
}
|
||||
|
||||
/** Plays a theme-configured sound for an event if present (fail-silent). */
|
||||
export function playThemeSound(payload: ActiveThemePayload | null, eventName: string): void {
|
||||
const file = payload?.theme?.sounds?.[eventName]
|
||||
if (!file || !payload?.asset_base_url) return
|
||||
const safe = sanitizeRelativeAssetPath(file)
|
||||
if (!safe) return
|
||||
try {
|
||||
const audio = new Audio(payload.asset_base_url + safe)
|
||||
audio.volume = 0.35
|
||||
void audio.play().catch((e) => console.warn('[theme] sound playback failed:', eventName, e))
|
||||
} catch (e) {
|
||||
console.warn('[theme] sound init failed:', eventName, e)
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,29 @@ import {
|
||||
type UIContractLayer, type UIContractPart, type UIContractSDKEvent, type UIContractSlot,
|
||||
} from '../styles/ui-contract'
|
||||
import { hideWailsGlobals } from '../wails'
|
||||
import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine'
|
||||
|
||||
export interface ReimsUISDK {
|
||||
export interface UIStateSnapshot {
|
||||
appearance: 'light' | 'dark'
|
||||
motion: 'full' | 'reduced'
|
||||
locale: string
|
||||
dir: 'ltr' | 'rtl'
|
||||
view: string
|
||||
vmName: string
|
||||
vmState: string
|
||||
busy: boolean
|
||||
hasError: boolean
|
||||
sidebarCollapsed: boolean
|
||||
safeMode: boolean
|
||||
vms: Array<{ name: string; state: string }>
|
||||
}
|
||||
|
||||
export interface ThemeSDKHostActions {
|
||||
toggleSidebar: () => void
|
||||
openSettings: () => void
|
||||
focusVMWindow: (name: string) => void
|
||||
}
|
||||
|
||||
interface ReimsUISDK {
|
||||
readonly uiApi: string
|
||||
/** Stable host features (e.g. `slot.sidebar.footer`); feature-detect instead of comparing versions. */
|
||||
readonly features: readonly string[]
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { AppUpdateInfo, Task } from '../types'
|
||||
import { api } from '../wails'
|
||||
|
||||
export type UpdatePhase = 'none' | 'available' | 'downloading' | 'ready' | 'failed'
|
||||
|
||||
const CHECK_EVERY_MS = 6 * 60 * 60 * 1000
|
||||
const DISMISSED_KEY = 'reims-go-update-dismissed'
|
||||
|
||||
interface Options {
|
||||
/** Checks start once the app is up. */
|
||||
ready: boolean
|
||||
tasks: Record<string, Task>
|
||||
runningVMCount: number
|
||||
onError: (e: unknown) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-app update: one task per release, whose state drives the sidebar
|
||||
* capsule and the About page alike.
|
||||
*/
|
||||
export function useAppUpdate({ ready, tasks, runningVMCount, onError }: Options) {
|
||||
const [info, setInfo] = useState<AppUpdateInfo | null>(null)
|
||||
const [dismissed, setDismissed] = useState<string>(() => {
|
||||
try { return localStorage.getItem(DISMISSED_KEY) ?? '' } catch { return '' }
|
||||
})
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const [installing, setInstalling] = useState(false)
|
||||
|
||||
// Check once the app is up, then every 6 hours, so the sidebar's update
|
||||
// button shows up without opening the About page.
|
||||
useEffect(() => {
|
||||
if (!ready) return
|
||||
const check = () => { api.CheckAppUpdate(false).then(setInfo).catch((e) => console.warn('[app] CheckAppUpdate failed:', e)) }
|
||||
check()
|
||||
const id = window.setInterval(check, CHECK_EVERY_MS)
|
||||
return () => window.clearInterval(id)
|
||||
}, [ready])
|
||||
|
||||
const task = info?.has_update
|
||||
? Object.values(tasks)
|
||||
.filter((x) => x.kind === 'app-update' && x.subject === info.latest)
|
||||
.sort((a, b) => b.updated_at - a.updated_at)[0] ?? null
|
||||
: null
|
||||
const phase: UpdatePhase = !info?.has_update ? 'none'
|
||||
: task?.status === 'running' ? 'downloading'
|
||||
: task?.status === 'done' ? 'ready'
|
||||
: task?.status === 'failed' ? 'failed'
|
||||
: 'available'
|
||||
|
||||
const dismiss = () => {
|
||||
if (!info) return
|
||||
setDismissed(info.latest)
|
||||
try { localStorage.setItem(DISMISSED_KEY, info.latest) } catch (e) { console.warn('[app] persist dismissed update failed:', e) }
|
||||
}
|
||||
|
||||
/** Forgets a dismissed release and asks again, e.g. after the update channel changed. */
|
||||
const recheck = async () => {
|
||||
setDismissed('')
|
||||
try { localStorage.removeItem(DISMISSED_KEY) } catch (e) { console.warn('[app] clear dismissed update failed:', e) }
|
||||
try {
|
||||
setInfo(await api.CheckAppUpdate(true))
|
||||
} catch (e) {
|
||||
setInfo(null)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
const download = () => { api.DownloadAppUpdate().catch(onError) }
|
||||
const confirmInstall = () => {
|
||||
setConfirming(false)
|
||||
setInstalling(true)
|
||||
api.InstallAppUpdate().catch((e) => {
|
||||
setInstalling(false)
|
||||
onError(e)
|
||||
})
|
||||
}
|
||||
// Restarting leaves VMs running but pauses the host-guest bridges: say so first.
|
||||
const install = () => { if (runningVMCount > 0) setConfirming(true); else confirmInstall() }
|
||||
|
||||
return {
|
||||
info, setInfo, task, phase, installing, confirming,
|
||||
shown: phase !== 'none' && !(phase === 'available' && dismissed === info?.latest),
|
||||
dismiss, recheck, download, install, confirmInstall, cancelInstall: () => setConfirming(false),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { events } from '../wails'
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||
|
||||
function useMediaQuery(query: string): boolean {
|
||||
const [matches, setMatches] = useState(() => !!window.matchMedia?.(query).matches)
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia?.(query)
|
||||
if (!mq) return
|
||||
const onChange = (e: MediaQueryListEvent) => setMatches(e.matches)
|
||||
mq.addEventListener('change', onChange)
|
||||
return () => mq.removeEventListener('change', onChange)
|
||||
}, [query])
|
||||
return matches
|
||||
}
|
||||
|
||||
/**
|
||||
* Light or dark, from the user's choice, Windows and what the active theme
|
||||
* supports. The choice is remembered per user.
|
||||
*/
|
||||
export function useAppearance(supported: 'light' | 'dark' | 'both') {
|
||||
const [mode, setMode] = useState<ThemeMode>(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem('reims-go-theme')
|
||||
if (saved === 'dark' || saved === 'light') return saved
|
||||
} catch (e) {
|
||||
console.warn('[app] read theme preference failed:', e)
|
||||
}
|
||||
return 'system'
|
||||
})
|
||||
const sysDark = useMediaQuery('(prefers-color-scheme: dark)')
|
||||
const reducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)')
|
||||
|
||||
const canLight = supported !== 'dark'
|
||||
const canDark = supported !== 'light'
|
||||
const themeMode: ThemeMode = !canDark ? 'light' : !canLight ? 'dark' : mode
|
||||
const theme: 'light' | 'dark' = themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme
|
||||
events.emitTheme(theme)
|
||||
}, [theme])
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full'
|
||||
}, [reducedMotion])
|
||||
|
||||
const setThemeMode = (next: ThemeMode) => {
|
||||
setMode(next)
|
||||
try {
|
||||
if (next === 'system') localStorage.removeItem('reims-go-theme')
|
||||
else localStorage.setItem('reims-go-theme', next)
|
||||
} catch (e) {
|
||||
console.warn('[app] persist theme preference failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
return { theme, themeMode, canLight, canDark, setThemeMode, reducedMotion }
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { OnFileDrop, OnFileDropOff } from '../wails'
|
||||
|
||||
/**
|
||||
* Native Wails file drag-and-drop. Returns whether files are being dragged
|
||||
* over the window while it accepts them.
|
||||
*/
|
||||
export function useFileDrop(accepts: boolean, onDrop: (paths: string[]) => void): boolean {
|
||||
const [dropping, setDropping] = useState(false)
|
||||
const latest = useRef({ accepts, onDrop })
|
||||
latest.current = { accepts, onDrop }
|
||||
|
||||
useEffect(() => {
|
||||
let depth = 0
|
||||
const onEnter = (e: DragEvent) => {
|
||||
if (!latest.current.accepts) return
|
||||
if (e.dataTransfer?.types?.includes('Files')) { depth++; setDropping(true) }
|
||||
}
|
||||
const onLeave = () => {
|
||||
depth = Math.max(0, depth - 1)
|
||||
if (depth === 0) setDropping(false)
|
||||
}
|
||||
const onEnd = () => { depth = 0; setDropping(false) }
|
||||
window.addEventListener('dragenter', onEnter)
|
||||
window.addEventListener('dragleave', onLeave)
|
||||
window.addEventListener('drop', onEnd)
|
||||
OnFileDrop((_x, _y, paths) => {
|
||||
onEnd()
|
||||
if (latest.current.accepts && paths?.length) latest.current.onDrop(paths)
|
||||
}, true)
|
||||
return () => {
|
||||
window.removeEventListener('dragenter', onEnter)
|
||||
window.removeEventListener('dragleave', onLeave)
|
||||
window.removeEventListener('drop', onEnd)
|
||||
OnFileDropOff()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return dropping
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { Task, VMListItem } from '../types'
|
||||
import { publishPluginHostEvent } from './pluginViewEvents'
|
||||
import { emitThemeEvent } from './themeEngine'
|
||||
import { vmRefKey } from './vmRef'
|
||||
|
||||
interface Options {
|
||||
view: string
|
||||
selectedVM: string
|
||||
vms: VMListItem[]
|
||||
transitions: Record<string, string> | undefined
|
||||
tasks: Record<string, Task>
|
||||
}
|
||||
|
||||
/**
|
||||
* UI SDK event stream (ui-contract UI_CONTRACT_SDK_EVENTS). emitThemeEvent is
|
||||
* a no-op unless an interactive theme is loaded; payloads carry no paths.
|
||||
*/
|
||||
export function useThemeEvents({ view, selectedVM, vms, transitions, tasks }: Options) {
|
||||
useEffect(() => {
|
||||
emitThemeEvent('view.changed', { view, vm: selectedVM })
|
||||
}, [view, selectedVM])
|
||||
|
||||
const vmStatesRef = useRef<Record<string, string> | null>(null)
|
||||
useEffect(() => {
|
||||
const next: Record<string, string> = {}
|
||||
for (const v of vms) next[vmRefKey(v)] = transitions?.[vmRefKey(v)] ?? v.state
|
||||
const prev = vmStatesRef.current
|
||||
vmStatesRef.current = next
|
||||
if (!prev) return
|
||||
for (const v of vms) {
|
||||
const key = vmRefKey(v)
|
||||
if (prev[key] !== undefined && prev[key] !== next[key]) {
|
||||
const payload = { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] }
|
||||
emitThemeEvent('vm.stateChanged', payload)
|
||||
publishPluginHostEvent('vm.stateChanged', payload)
|
||||
}
|
||||
}
|
||||
}, [vms, transitions])
|
||||
const taskStatesRef = useRef<Record<string, { status: string; percent: number }> | null>(null)
|
||||
useEffect(() => {
|
||||
const prev = taskStatesRef.current
|
||||
const next: Record<string, { status: string; percent: number }> = {}
|
||||
for (const t of Object.values(tasks)) next[t.id] = { status: t.status, percent: t.percent }
|
||||
taskStatesRef.current = next
|
||||
if (!prev) return
|
||||
for (const t of Object.values(tasks)) {
|
||||
const was = prev[t.id]
|
||||
const info = { id: t.id, kind: t.kind, vm: t.vm ?? '', percent: t.percent }
|
||||
if (!was && t.status === 'running') emitThemeEvent('task.started', info)
|
||||
else if (was?.status === 'running' && t.status === 'running' && was.percent !== t.percent) emitThemeEvent('task.progress', info)
|
||||
if ((!was || was.status === 'running') && t.status !== 'running') emitThemeEvent('task.finished', { ...info, status: t.status })
|
||||
}
|
||||
}, [tasks])
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import type { VMBusyAction } from '../types'
|
||||
|
||||
/**
|
||||
* The actions running on each VM, keyed by VM reference (driver and name) so
|
||||
* same-name VMs of different drivers never block each other. A VM runs one
|
||||
* action at a time; only a force stop may join another one.
|
||||
*/
|
||||
export function useVMBusy() {
|
||||
const [busy, setBusy] = useState<Record<string, VMBusyAction>>(() => Object.create(null))
|
||||
const running = useRef(new Map<string, Map<number, VMBusyAction>>())
|
||||
const nextToken = useRef(0)
|
||||
|
||||
/** The VM's latest action, also ahead of the next render. */
|
||||
const current = (key: string): VMBusyAction | undefined => [...(running.current.get(key)?.values() ?? [])].at(-1)
|
||||
|
||||
const sync = () => {
|
||||
const next: Record<string, VMBusyAction> = Object.create(null)
|
||||
for (const key of running.current.keys()) {
|
||||
const action = current(key)
|
||||
if (action) next[key] = action
|
||||
}
|
||||
setBusy(next)
|
||||
}
|
||||
|
||||
/** Marks the VM busy; returns a token for `end`, or null when the action has to wait. */
|
||||
const begin = (key: string, action: VMBusyAction): number | null => {
|
||||
const ops = running.current.get(key) ?? new Map<number, VMBusyAction>()
|
||||
if (ops.size > 0 && (action !== 'forceStop' || [...ops.values()].includes('forceStop'))) return null
|
||||
const token = ++nextToken.current
|
||||
ops.set(token, action)
|
||||
running.current.set(key, ops)
|
||||
sync()
|
||||
return token
|
||||
}
|
||||
|
||||
const end = (key: string, token: number) => {
|
||||
const ops = running.current.get(key)
|
||||
if (!ops?.delete(token)) return
|
||||
if (ops.size === 0) running.current.delete(key)
|
||||
sync()
|
||||
}
|
||||
|
||||
return { busy, current, begin, end }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export interface VMRefLike {
|
||||
interface VMRefLike {
|
||||
name: string
|
||||
driver_id?: string
|
||||
}
|
||||
|
||||
@@ -21,14 +21,14 @@ const statsKey = (driverID: string, name: string) => `${driverID}:${name}`
|
||||
function sample(key: string, driverID: string, name: string, entryRef: Entry) {
|
||||
if (entries.get(key) !== entryRef) return
|
||||
const reqSeq = ++entryRef.seq
|
||||
api.GetVMStatsWithDriver(driverID, name)
|
||||
api.GetVMStats(driverID, name)
|
||||
.then((s) => {
|
||||
if (entries.get(key) !== entryRef || reqSeq <= entryRef.appliedSeq) return
|
||||
entryRef.appliedSeq = reqSeq
|
||||
entryRef.last = s
|
||||
entryRef.subs.forEach((f) => f(s))
|
||||
})
|
||||
.catch((e) => console.warn('[vmStats] GetVMStatsWithDriver failed:', key, e))
|
||||
.catch((e) => console.warn('[vmStats] GetVMStats failed:', key, e))
|
||||
}
|
||||
|
||||
function schedule(key: string, driverID: string, name: string, e: Entry) {
|
||||
@@ -51,13 +51,12 @@ if (typeof document !== 'undefined') {
|
||||
}
|
||||
|
||||
/** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */
|
||||
export function latestVMStatsWithDriver(driverID: string, name: string | undefined | null): VMStats | null {
|
||||
export function latestVMStats(driverID: string, name: string | undefined | null): VMStats | null {
|
||||
return name ? entries.get(statsKey(driverID, name))?.last ?? null : null
|
||||
}
|
||||
export function latestVMStats(name: string | undefined | null): VMStats | null { return latestVMStatsWithDriver('', name) }
|
||||
|
||||
/** Immediately patch cached stats (if any) and re-sample a VM's stats. */
|
||||
export function refreshVMStatsWithDriver(driverID: string, name: string, patch?: Partial<VMStats>) {
|
||||
export function refreshVMStats(driverID: string, name: string, patch?: Partial<VMStats>) {
|
||||
const key = statsKey(driverID, name)
|
||||
const e = entries.get(key)
|
||||
if (!e) return
|
||||
@@ -68,7 +67,6 @@ export function refreshVMStatsWithDriver(driverID: string, name: string, patch?:
|
||||
}
|
||||
sample(key, driverID, name, e)
|
||||
}
|
||||
export function refreshVMStats(name: string, patch?: Partial<VMStats>) { refreshVMStatsWithDriver('', name, patch) }
|
||||
|
||||
/** Re-sample all currently subscribed VMs (e.g. after a tray-triggered state change). */
|
||||
export function refreshSubscribedVMStats() {
|
||||
@@ -82,7 +80,7 @@ export function refreshSubscribedVMStats() {
|
||||
|
||||
/** Live stats for one VM; `running` picks the sampling rate. Null name: none. */
|
||||
export function useVMStats(driverID: string, name: string | null, running: boolean): VMStats | null {
|
||||
const [stats, setStats] = useState<VMStats | null>(() => latestVMStatsWithDriver(driverID, name))
|
||||
const [stats, setStats] = useState<VMStats | null>(() => latestVMStats(driverID, name))
|
||||
useEffect(() => {
|
||||
if (!name) { setStats(null); return }
|
||||
const key = statsKey(driverID, name)
|
||||
|
||||
@@ -22,7 +22,7 @@ html, body, #root {
|
||||
html:lang(ja) { line-break: strict; }
|
||||
html:lang(ko) { word-break: keep-all; }
|
||||
:is(:lang(zh), :lang(ja), :lang(ko)) :is(em, i) { font-style: normal; font-weight: var(--fw-medium); }
|
||||
:is(:lang(zh), :lang(ja), :lang(ko)) :is(.brand, .sidebar-head, .sidebar-section-label, .sidebar-brand-name, .about-hero-text h1) {
|
||||
:is(:lang(zh), :lang(ja), :lang(ko)) :is(.brand, .sidebar-head, .sidebar-brand-name, .about-hero-text h1) {
|
||||
letter-spacing: var(--heading-tracking, 0em);
|
||||
}
|
||||
|
||||
@@ -166,12 +166,6 @@ h1, h2, h3, p { margin: 0; }
|
||||
font-size: var(--fs-13); font-weight: var(--fw-strong); letter-spacing: -0.01em;
|
||||
color: var(--text);
|
||||
}
|
||||
.sidebar-section-label {
|
||||
padding: 4px 10px 4px;
|
||||
font-size: var(--fs-13); font-weight: var(--fw-strong); letter-spacing: -0.01em;
|
||||
color: var(--text);
|
||||
}
|
||||
.sidebar-sep { height: 1px; background: var(--border); margin: 8px 10px 6px; }
|
||||
.sidebar-brand {
|
||||
display: flex; align-items: center; gap: 9px;
|
||||
padding: 2px 4px 12px 8px; min-height: 34px;
|
||||
@@ -321,7 +315,6 @@ h1, h2, h3, p { margin: 0; }
|
||||
.page-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 34px; }
|
||||
.page-title { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||
.page-title h1 { font-size: 18px; font-weight: var(--fw-strong); letter-spacing: -0.015em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.state-text { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-12); color: var(--text-2); white-space: nowrap; }
|
||||
.actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
|
||||
|
||||
/* ── macOS Tahoe "About This Mac" Hero ─────────────────── */
|
||||
@@ -499,24 +492,6 @@ h1, h2, h3, p { margin: 0; }
|
||||
display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); min-height: 26px;
|
||||
}
|
||||
|
||||
.tahoe-group {
|
||||
background: var(--surface-1);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--r-lg);
|
||||
overflow: hidden;
|
||||
}
|
||||
.tahoe-row {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 16px;
|
||||
min-height: 40px; padding: 9px 16px;
|
||||
position: relative; font-size: 13.5px;
|
||||
}
|
||||
.tahoe-row + .tahoe-row::before {
|
||||
content: ""; position: absolute; top: 0; left: 16px; right: 16px;
|
||||
height: 1px; background: var(--border);
|
||||
}
|
||||
.tahoe-label { color: var(--text); font-weight: var(--fw-regular); display: inline-flex; align-items: center; gap: 10px; flex-shrink: 0; }
|
||||
.tahoe-value { color: var(--text-2); text-align: right; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: text; }
|
||||
|
||||
/* ── Buttons ───────────────────────────────────────────── */
|
||||
.btn {
|
||||
height: 31px; padding: 0 13px;
|
||||
@@ -605,12 +580,6 @@ h1, h2, h3, p { margin: 0; }
|
||||
display: flex; align-items: flex-start; gap: 12px;
|
||||
font-size: var(--fs-13); color: var(--text-2); line-height: 1.55;
|
||||
}
|
||||
.guide-step-num {
|
||||
width: 22px; height: 22px; border-radius: 50%; flex-shrink: 0; margin-top: 1px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--accent-soft); color: var(--accent-soft-text);
|
||||
font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.guide-step-body { flex: 1; min-width: 0; }
|
||||
.steps { margin: 0; padding-left: var(--sp-6); display: flex; flex-direction: column; gap: var(--sp-1); color: var(--text-2); font-size: var(--fs-13); }
|
||||
|
||||
@@ -623,8 +592,6 @@ h1, h2, h3, p { margin: 0; }
|
||||
.cmd-line > svg { color: var(--text-3); flex-shrink: 0; }
|
||||
.cmd-line code { flex: 1; min-width: 0; font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); user-select: text; overflow-wrap: anywhere; }
|
||||
.cmd-line-spaced { margin-top: 6px; }
|
||||
|
||||
.tech-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); }
|
||||
.tech > summary {
|
||||
list-style: none; cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1);
|
||||
padding: 4px 6px; margin-left: -6px;
|
||||
@@ -897,8 +864,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.status-metric.high { color: var(--danger-text); }
|
||||
.status-metric.high > svg { color: var(--danger-text); }
|
||||
.status-metric.ok { color: var(--ok-text); }
|
||||
.status-metric-dim { color: var(--text-3); }
|
||||
.status-sep { color: var(--border-strong); flex-shrink: 0; }
|
||||
.status-mini-bar {
|
||||
display: inline-block; width: 34px; height: 4px; border-radius: 999px;
|
||||
background: var(--surface-active); overflow: hidden; flex-shrink: 0;
|
||||
@@ -1065,7 +1030,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.field { display: flex; flex-direction: column; gap: 6px; }
|
||||
.field-spaced { margin-top: 10px; }
|
||||
.field-label { font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text-2); }
|
||||
.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
|
||||
.input, .select {
|
||||
width: 100%; height: 32px; padding: 0 10px;
|
||||
border-radius: var(--r-md); border: 1px solid var(--border-strong);
|
||||
@@ -1377,12 +1341,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.guide-cmd { margin-top: var(--sp-2); }
|
||||
|
||||
/* ── Telemetry meter (GPU compositor scaleX) ───────────── */
|
||||
.resource-meter {
|
||||
height: 5px;
|
||||
border-radius: 999px;
|
||||
background: var(--surface-active);
|
||||
overflow: hidden;
|
||||
}
|
||||
.meter-fill {
|
||||
display: block;
|
||||
width: 100%;
|
||||
@@ -2072,7 +2030,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.source-cards, .field-row, .review-groups { grid-template-columns: 1fr; }
|
||||
.source-cards, .review-groups { grid-template-columns: 1fr; }
|
||||
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr; }
|
||||
.vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; }
|
||||
.affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
|
||||
@@ -238,31 +238,6 @@ export const UI_CONTRACT_TOKENS = [
|
||||
'--titlebar-h', '--logbar-h', '--sidebar-w', '--page-max',
|
||||
] as const
|
||||
|
||||
export const UI_CONTRACT = {
|
||||
uiApi: UI_API_VERSION,
|
||||
parts: [...UI_CONTRACT_PARTS],
|
||||
stateAttrs: [...UI_CONTRACT_STATE_ATTRS],
|
||||
itemStates: [...UI_CONTRACT_ITEM_STATES],
|
||||
slots: [...UI_CONTRACT_SLOTS],
|
||||
layers: [...UI_CONTRACT_LAYERS],
|
||||
layoutOptions: [...UI_CONTRACT_LAYOUT_OPTIONS],
|
||||
icons: [...UI_CONTRACT_ICONS],
|
||||
viewLocations: [...UI_CONTRACT_VIEW_LOCATIONS],
|
||||
sdkEvents: [...UI_CONTRACT_SDK_EVENTS],
|
||||
tokens: [...UI_CONTRACT_TOKENS],
|
||||
experimental: {
|
||||
parts: [...UI_CONTRACT_PARTS_EXPERIMENTAL],
|
||||
stateAttrs: [...UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL],
|
||||
itemStates: [...UI_CONTRACT_ITEM_STATES_EXPERIMENTAL],
|
||||
slots: [...UI_CONTRACT_SLOTS_EXPERIMENTAL],
|
||||
layers: [...UI_CONTRACT_LAYERS_EXPERIMENTAL],
|
||||
layoutOptions: [...UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL],
|
||||
icons: [...UI_CONTRACT_ICONS_EXPERIMENTAL],
|
||||
viewLocations: [...UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL],
|
||||
sdkEvents: [...UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL],
|
||||
},
|
||||
}
|
||||
|
||||
// Stable host features advertised to themes through the UI SDK.
|
||||
export const UI_CONTRACT_FEATURES: readonly string[] = [
|
||||
...UI_CONTRACT_SLOTS.map((s) => `slot.${s}`),
|
||||
|
||||
+34
-23
@@ -16,11 +16,9 @@ export type Config = Model<config.Config> & {
|
||||
|
||||
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 GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown'
|
||||
type GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown'
|
||||
|
||||
export type GPUInfo = Omit<Model<host.GPUInfo>, 'compat'> & {
|
||||
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
|
||||
@@ -41,16 +39,15 @@ export type HostReport = Omit<Model<host.Report>, 'gpus' | 'recommended_gpu'> &
|
||||
recommended_gpu?: GPUInfo
|
||||
}
|
||||
|
||||
export type RuntimeManifest = Model<runtime.Manifest>
|
||||
export type InstalledRuntime = Model<runtime.Installed>
|
||||
|
||||
export type RemoteRuntime = Model<runtime.Remote> & {
|
||||
channel: 'stable' | 'alpha'
|
||||
}
|
||||
|
||||
export type VMState = 'running' | 'stopped' | 'suspended' | 'broken' | 'driver_unavailable'
|
||||
export type VMPhase = 'normal' | 'installer' | 'recovery'
|
||||
export type GuestOSInfo = Model<driver.GuestOSInfo>
|
||||
type VMState = 'running' | 'stopped' | 'suspended' | 'broken' | 'driver_unavailable'
|
||||
type VMPhase = 'normal' | 'installer' | 'recovery'
|
||||
type GuestOSInfo = Model<driver.GuestOSInfo>
|
||||
export type VMEndpoint = Model<driver.VMEndpoint> & {
|
||||
kind: 'ssh' | 'wsl' | 'rdp' | 'vmconnect' | 'adb' | (string & {})
|
||||
}
|
||||
@@ -83,7 +80,6 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
|
||||
}
|
||||
|
||||
export type AppUpdateInfo = version.UpdateInfo
|
||||
export type SuspendInfo = reims.SuspendInfo
|
||||
export type VMDetail = reims.VMDetail
|
||||
export type SMBIOSIdentity = opencore.SMBIOSIdentity
|
||||
export type VMStats = app.VMStats
|
||||
@@ -126,7 +122,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
displays: number
|
||||
}
|
||||
|
||||
export type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
|
||||
type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
|
||||
|
||||
export type InstallerKind = 'offline' | 'online'
|
||||
export type InstallerPhase = 'queued' | 'downloading'
|
||||
@@ -155,23 +151,15 @@ export type PermissionSpec = plugin.PermissionSpec
|
||||
export type SettingProperty = plugin.SettingProperty
|
||||
export type SettingsSchema = plugin.SettingsSchema
|
||||
export type PluginInfo = plugin.PluginInfo
|
||||
export type DoctorFinding = plugin.DoctorFinding
|
||||
export type ScanFinding = plugin.ScanFinding
|
||||
export type ExecutableFile = plugin.ExecutableFile
|
||||
export type CapabilityItem = plugin.CapabilityItem
|
||||
export type ScanReport = plugin.ScanReport
|
||||
export type MarketEntry = plugin.MarketEntry
|
||||
export type MarketWithdrawal = plugin.MarketWithdrawal
|
||||
export type MarketCatalogItem = plugin.MarketCatalogItem
|
||||
export type MarketBrowseResult = plugin.MarketBrowseResult
|
||||
export type TokenDeriveRule = plugin.TokenDeriveRule
|
||||
export type ThemeScheme = plugin.ThemeScheme
|
||||
export type ThemeDecoration = plugin.ThemeDecoration
|
||||
export type ThemeDecorationState = plugin.ThemeDecorationState
|
||||
export type ThemeContribution = plugin.ThemeContribution
|
||||
export type CustomThemeScheme = plugin.CustomThemeScheme
|
||||
export type ActiveThemePayload = plugin.ActiveThemePayload
|
||||
export interface ResolvedLocaleFont {
|
||||
interface ResolvedLocaleFont {
|
||||
family: string
|
||||
url: string
|
||||
weight?: string
|
||||
@@ -184,18 +172,41 @@ export type ResolvedLocalePack = Model<plugin.ResolvedLocalePack> & {
|
||||
plugin_messages?: Record<string, Record<string, string>>
|
||||
fonts?: ResolvedLocaleFont[]
|
||||
}
|
||||
export type MenuContribution = plugin.MenuContribution
|
||||
export type VMCardContribution = plugin.VMCardContribution
|
||||
export type PanelContribution = plugin.PanelContribution
|
||||
export type ViewContribution = plugin.ViewContribution
|
||||
export type ImageSourceContribution = plugin.ImageSourceContribution
|
||||
export type StatusItemContribution = plugin.StatusItemContribution
|
||||
export type PluginUIContributions = app.PluginUIContributions
|
||||
export type DriverSummary = driver.DriverSummary
|
||||
export type DriverCreateRequest = driver.CreateRequest
|
||||
export type RuntimeKindSpec = runtime.KindSpec
|
||||
|
||||
/** A "reims:log" event (internal/app/app.go emitLog); not a Go struct, so not generated. */
|
||||
export type VMAction =
|
||||
| 'start'
|
||||
| 'suspend'
|
||||
| 'resume'
|
||||
| 'discardSuspend'
|
||||
| 'stop'
|
||||
| 'forceStop'
|
||||
| 'restart'
|
||||
| 'focus'
|
||||
| 'fullscreen'
|
||||
| 'screenshot'
|
||||
| 'eject'
|
||||
| 'finishInstall'
|
||||
| 'enterRecovery'
|
||||
| 'attachInstaller'
|
||||
| 'attachGuestTools'
|
||||
| 'detachGuestTools'
|
||||
| 'openSharedFolder'
|
||||
| 'upgradeNVMe'
|
||||
| 'exportDiagnostics'
|
||||
| 'cloneVM'
|
||||
| 'type'
|
||||
| 'sendText'
|
||||
| 'delete'
|
||||
| 'openFolder'
|
||||
|
||||
export type VMBusyAction = VMAction | 'pluginCommand'
|
||||
|
||||
export interface LogEntry {
|
||||
ts: string
|
||||
source: string
|
||||
|
||||
@@ -92,7 +92,7 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||
)
|
||||
IconButton.displayName = 'IconButton'
|
||||
|
||||
export type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn'
|
||||
type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn'
|
||||
|
||||
export function statusKind(state: string): StatusKind {
|
||||
if (state === 'running') return 'running'
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Ellipsis } from 'lucide-react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { localeDir } from '../i18n'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import type { Locale } from '../types'
|
||||
import { Tip } from './controls'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
label: string
|
||||
small?: boolean
|
||||
/** Runs when the menu closes; returns true after moving focus itself. */
|
||||
onCloseFocus?: () => boolean
|
||||
/** The menu's items. */
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* An ellipsis button with a menu. Focus returns to the button only after
|
||||
* keyboard use: after a click it would pop the button's tooltip, and an item
|
||||
* that opened a dialog needs the focus there.
|
||||
*/
|
||||
export const ActionMenu: React.FC<Props> = ({ locale, label, small, onCloseFocus, children }) => {
|
||||
const [open, setOpen] = useState(false)
|
||||
const openedByPointer = useRef(false)
|
||||
const closedByPointer = useRef(false)
|
||||
|
||||
return (
|
||||
<Menu.Root
|
||||
dir={localeDir(locale)}
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (next) closedByPointer.current = false
|
||||
setOpen(next)
|
||||
}}
|
||||
>
|
||||
<Tip label={label} disabled={open}>
|
||||
<Menu.Trigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className={`icon-btn rg-p-icon-button${small ? ' sm' : ''}`}
|
||||
aria-label={label}
|
||||
onPointerDown={() => { openedByPointer.current = true }}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') openedByPointer.current = false
|
||||
}}
|
||||
>
|
||||
<Ellipsis size={small ? 14 : 15} />
|
||||
</button>
|
||||
</Menu.Trigger>
|
||||
</Tip>
|
||||
<Menu.Portal>
|
||||
<Menu.Content
|
||||
className="menu rg-p-menu"
|
||||
align="end"
|
||||
sideOffset={4}
|
||||
collisionPadding={8}
|
||||
onPointerDownCapture={(e) => {
|
||||
if (!(e.target as HTMLElement | null)?.closest('[data-disabled]')) closedByPointer.current = true
|
||||
}}
|
||||
onKeyDownCapture={() => { closedByPointer.current = false }}
|
||||
onPointerDownOutside={() => { closedByPointer.current = true }}
|
||||
onCloseAutoFocus={(e) => {
|
||||
if (onCloseFocus?.() || openedByPointer.current || closedByPointer.current || hasVisibleDialog()) e.preventDefault()
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
)
|
||||
}
|
||||
@@ -89,7 +89,7 @@ export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void
|
||||
</label>
|
||||
)
|
||||
|
||||
export interface SegOption<V> {
|
||||
interface SegOption<V> {
|
||||
value: V
|
||||
label: string
|
||||
disabled?: boolean
|
||||
@@ -108,18 +108,20 @@ export function Segmented<V extends string | number>({ options, value, onChange,
|
||||
wide?: boolean
|
||||
}) {
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const [thumb, setThumb] = useState<{ x: number; w: number } | null>(null)
|
||||
const [thumb, setThumb] = useState<{ x: number; w: number; value: V } | null>(null)
|
||||
|
||||
const measure = () => {
|
||||
const el = box.current?.querySelector<HTMLElement>('[aria-checked="true"]')
|
||||
const next = el ? { x: el.offsetLeft, w: el.offsetWidth } : null
|
||||
setThumb((prev) => {
|
||||
if (!prev && !next) return prev
|
||||
if (prev && next && prev.x === next.x && prev.w === next.w) return prev
|
||||
return next
|
||||
// Options disabled while something is saving keep the highlight in place.
|
||||
if (!el || value === undefined) return prev?.value === value ? prev : null
|
||||
if (prev?.value === value && prev.x === el.offsetLeft && prev.w === el.offsetWidth) return prev
|
||||
return { x: el.offsetLeft, w: el.offsetWidth, value }
|
||||
})
|
||||
}
|
||||
const optionsSig = options.map((o) => `${String(o.value)}\x1f${o.label}`).join('\x1e')
|
||||
const latestMeasure = useRef(measure)
|
||||
latestMeasure.current = measure
|
||||
const optionsSig = options.map((o) => `${String(o.value)}\x1f${o.label}\x1f${!!o.disabled}`).join('\x1e')
|
||||
const docDir = typeof document !== 'undefined' ? document.documentElement.dir : ''
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useLayoutEffect(measure, [value, optionsSig, wide, docDir])
|
||||
@@ -130,7 +132,7 @@ export function Segmented<V extends string | number>({ options, value, onChange,
|
||||
if (raf) cancelAnimationFrame(raf)
|
||||
raf = requestAnimationFrame(() => {
|
||||
raf = 0
|
||||
measure()
|
||||
latestMeasure.current()
|
||||
})
|
||||
})
|
||||
ro.observe(box.current)
|
||||
@@ -138,7 +140,6 @@ export function Segmented<V extends string | number>({ options, value, onChange,
|
||||
if (raf) cancelAnimationFrame(raf)
|
||||
ro.disconnect()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
@@ -247,7 +248,7 @@ function thinMarks(marks: RangeMark[], min: number, max: number, gap = 9): Range
|
||||
return out
|
||||
}
|
||||
|
||||
export interface RangeMark {
|
||||
interface RangeMark {
|
||||
value: number
|
||||
label: string
|
||||
}
|
||||
@@ -326,7 +327,7 @@ export const RangeField: React.FC<RangeProps> = ({ value, min, max, step = 1, un
|
||||
)
|
||||
}
|
||||
|
||||
export interface CardOption<V> {
|
||||
interface CardOption<V> {
|
||||
value: V
|
||||
title: string
|
||||
sub?: string
|
||||
@@ -362,7 +363,7 @@ export function OptionCards<V extends string>({ options, value, onChange, label,
|
||||
)
|
||||
}
|
||||
|
||||
export interface PopupOption<V> {
|
||||
interface PopupOption<V> {
|
||||
value: V
|
||||
label: string
|
||||
/** Secondary text drawn after the label in grey, e.g. a build number. */
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { locText } from '../i18n'
|
||||
import { matchDecorationState, themeAssetURL, type UIStateSnapshot } from '../lib/themeEngine'
|
||||
import { matchDecorationState, themeAssetURL } from '../lib/themeEngine'
|
||||
import type { UIStateSnapshot } from '../lib/uiSdk'
|
||||
import { UI_CONTRACT_ICONS, UI_CONTRACT_LAYERS, UI_CONTRACT_SLOTS, type UIContractIcon } from '../styles/ui-contract'
|
||||
import type { ActiveThemePayload, Locale, ThemeDecoration } from '../types'
|
||||
|
||||
@@ -13,7 +14,7 @@ const DEFAULT_BRAND_MARK = '/logo.svg'
|
||||
const KNOWN_ICONS = new Set<string>(UI_CONTRACT_ICONS)
|
||||
const KNOWN_TARGETS = new Set<string>([...UI_CONTRACT_SLOTS, ...UI_CONTRACT_LAYERS])
|
||||
|
||||
export interface ThemeVisuals {
|
||||
interface ThemeVisuals {
|
||||
brandMarkURL: string
|
||||
icons: Partial<Record<UIContractIcon, string>>
|
||||
}
|
||||
@@ -25,7 +26,7 @@ function isBuiltin(payload: ActiveThemePayload | null): boolean {
|
||||
return !payload?.theme || payload.theme_id === 'builtin.theme.default'
|
||||
}
|
||||
|
||||
export function resolveThemeVisuals(payload: ActiveThemePayload | null): ThemeVisuals {
|
||||
function resolveThemeVisuals(payload: ActiveThemePayload | null): ThemeVisuals {
|
||||
if (isBuiltin(payload)) return EMPTY
|
||||
const th = payload!.theme!
|
||||
const icons: Partial<Record<UIContractIcon, string>> = {}
|
||||
@@ -41,7 +42,7 @@ export const ThemeVisualsProvider: React.FC<{ payload: ActiveThemePayload | null
|
||||
return <ThemeVisualsContext.Provider value={value}>{children}</ThemeVisualsContext.Provider>
|
||||
}
|
||||
|
||||
export function useThemeVisuals(): ThemeVisuals {
|
||||
function useThemeVisuals(): ThemeVisuals {
|
||||
return useContext(ThemeVisualsContext)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import { Check, CircleCheck, CircleX, X } from 'lucide-react'
|
||||
import { HostIcon } from './themeVisuals'
|
||||
import { emitThemeEvent } from '../lib/themeEngine'
|
||||
import React, { useCallback, useState } from 'react'
|
||||
import { parseAppError, t } from '../i18n'
|
||||
import type { Locale } from '../types'
|
||||
import { IconButton } from './controls'
|
||||
|
||||
export interface ToastInput {
|
||||
@@ -16,7 +18,21 @@ export interface ToastInput {
|
||||
action?: { label: string; onClick: () => void }
|
||||
}
|
||||
|
||||
export interface ToastItem extends ToastInput {
|
||||
/** An error toast: the message, with the raw details folded for bug reports. */
|
||||
export function errorToast(locale: Locale, title: string, e: unknown): ToastInput {
|
||||
const parsed = parseAppError(e)
|
||||
return {
|
||||
kind: 'error',
|
||||
title,
|
||||
description: parsed.summary,
|
||||
errorCode: parsed.code,
|
||||
rawDetail: parsed.rawDetail,
|
||||
detailsLabel: t(locale, 'errRawDetailsToggle'),
|
||||
copyDetailsLabel: t(locale, 'errCopyDetails'),
|
||||
}
|
||||
}
|
||||
|
||||
interface ToastItem extends ToastInput {
|
||||
id: number
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
import type {
|
||||
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
|
||||
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
|
||||
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate,
|
||||
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate,
|
||||
} from './types'
|
||||
|
||||
type AnyFn = (...args: never[]) => unknown
|
||||
@@ -155,10 +155,8 @@ export const api = {
|
||||
InstallNpcap: boundGo.InstallNpcap as () => Promise<void>,
|
||||
GetState: boundGo.GetState as () => Promise<AppState>,
|
||||
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
|
||||
GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
GetVMAffinityWithDriver: boundGo.GetVMAffinityWithDriver as (driverID: string, name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinityWithDriver: boundGo.SetVMAffinityWithDriver as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise<VMAffinityStatus>,
|
||||
SetVMAffinity: boundGo.SetVMAffinity as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
|
||||
GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise<VMKeymapStatus>,
|
||||
GetVMInfo: boundGo.GetVMInfo as (driverID: string, name: string) => Promise<VMInfo>,
|
||||
SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise<VMKeymapStatus>,
|
||||
@@ -174,7 +172,6 @@ export const api = {
|
||||
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
|
||||
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
|
||||
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
|
||||
ListRuntimeKinds: boundGo.ListRuntimeKinds as () => Promise<RuntimeKindSpec[] | null>,
|
||||
}
|
||||
|
||||
export interface MarketInstallProgress {
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Vendored
+42
-122
@@ -34,23 +34,15 @@ export function CheckAppUpdate(arg1:boolean):Promise<version.UpdateInfo>;
|
||||
|
||||
export function CheckDataRoot(arg1:string):Promise<app.DataRootCheck>;
|
||||
|
||||
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
|
||||
export function CloneVMCoW(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function CloneVMCoWWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function CompactVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
|
||||
|
||||
export function CompactVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
|
||||
export function CompactVMDisk(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
|
||||
|
||||
export function CompleteSetup(arg1:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshot(arg1:string):Promise<void>;
|
||||
export function CopyVMScreenshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CopyVMScreenshotWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function CreateSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
export function CreateSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
|
||||
|
||||
@@ -60,13 +52,9 @@ export function DeleteCustomThemeScheme(arg1:string):Promise<void>;
|
||||
|
||||
export function DeleteInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
export function DeleteSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function DeleteSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function DeleteVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
export function DeleteVM(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
|
||||
export function DeliverFileToGuest(arg1:string):Promise<string>;
|
||||
|
||||
@@ -76,13 +64,7 @@ export function DetachGuestTools(arg1:string):Promise<void>;
|
||||
|
||||
export function DisablePlugin(arg1:string):Promise<void>;
|
||||
|
||||
export function DiscardSuspend(arg1:string):Promise<void>;
|
||||
|
||||
export function DiscardSuspendWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DismissTask(arg1:string):Promise<void>;
|
||||
|
||||
export function DoctorPlugin(arg1:string):Promise<Array<plugin.DoctorFinding>>;
|
||||
export function DiscardSuspend(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
@@ -90,25 +72,17 @@ export function DownloadAppUpdate():Promise<string>;
|
||||
|
||||
export function DownloadInstaller(arg1:string):Promise<string>;
|
||||
|
||||
export function EjectInstaller(arg1:string):Promise<void>;
|
||||
|
||||
export function EjectInstallerWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
export function EjectInstaller(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function EnableWHPX():Promise<void>;
|
||||
|
||||
export function EnterRecovery(arg1:string):Promise<void>;
|
||||
|
||||
export function ExportDiagnostics(arg1:string):Promise<string>;
|
||||
|
||||
export function ExportDiagnosticsWithDriver(arg1:string,arg2:string):Promise<string>;
|
||||
export function ExportDiagnostics(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function FinishInstall(arg1:string):Promise<void>;
|
||||
|
||||
export function FocusVMWindow(arg1:string):Promise<void>;
|
||||
|
||||
export function FocusVMWindowWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
export function FocusVMWindow(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function ForceQuitApp():Promise<void>;
|
||||
|
||||
@@ -136,17 +110,16 @@ export function GetStorageBreakdown():Promise<app.StorageBreakdown>;
|
||||
|
||||
export function GetTasks():Promise<Array<app.Task>>;
|
||||
|
||||
export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise<app.VMAffinityStatus>;
|
||||
export function GetVMAffinity(arg1:string,arg2:string):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
|
||||
|
||||
export function GetVMDisplayWithDriver(arg1:string,arg2:string):Promise<app.VMDisplayStatus>;
|
||||
export function GetVMDisplay(arg1:string,arg2:string):Promise<app.VMDisplayStatus>;
|
||||
|
||||
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function GetVMEndpointCommandWithDriver(arg1:string,arg2:string,arg3:string):Promise<string>;
|
||||
export function GetVMEndpointCommand(arg1:string,arg2:string,arg3:string):Promise<string>;
|
||||
|
||||
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
|
||||
|
||||
export function GetVMKeymap(arg1:string):Promise<app.VMKeymapStatus>;
|
||||
@@ -157,30 +130,21 @@ export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise<ap
|
||||
|
||||
export function GetVMNetworkSettings(arg1:string):Promise<app.VMNetworkSettings>;
|
||||
|
||||
export function GetVMNote(arg1:string):Promise<string>;
|
||||
export function GetVMNoteWithDriver(arg1:string,arg2:string):Promise<string>;
|
||||
export function GetVMNote(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function GetVMPluginSettings(arg1:string):Promise<Record<string, Record<string, any>>>;
|
||||
|
||||
export function GetVMSMBIOS(arg1:string):Promise<opencore.SMBIOSIdentity>;
|
||||
|
||||
export function GetVMSSHUser(arg1:string):Promise<string>;
|
||||
|
||||
export function GetVMSSHUserWithDriver(arg1:string,arg2:string):Promise<string>;
|
||||
export function GetVMSSHUser(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function GetVMSharedFolderSettings(arg1:string):Promise<app.SharedFolderSettings>;
|
||||
|
||||
export function GetVMStats(arg1:string):Promise<app.VMStats>;
|
||||
export function GetVMStats(arg1:string,arg2:string):Promise<app.VMStats>;
|
||||
|
||||
export function GetVMStatsWithDriver(arg1:string,arg2:string):Promise<app.VMStats>;
|
||||
export function GetVMThumbnail(arg1:string,arg2:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function GetVMThumbnailWithDriver(arg1:string,arg2:string):Promise<app.VMThumbnail>;
|
||||
|
||||
export function GetVMTimezone(arg1:string):Promise<app.VMTimezoneStatus>;
|
||||
|
||||
export function GetVMTimezoneWithDriver(arg1:string,arg2:string):Promise<app.VMTimezoneStatus>;
|
||||
export function GetVMTimezone(arg1:string,arg2:string):Promise<app.VMTimezoneStatus>;
|
||||
|
||||
export function InspectPluginArchive(arg1:string):Promise<plugin.ScanReport>;
|
||||
|
||||
@@ -212,38 +176,29 @@ export function ListPlugins():Promise<Array<plugin.PluginInfo>>;
|
||||
|
||||
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
|
||||
|
||||
export function ListRuntimeKinds():Promise<Array<runtime.KindSpec>>;
|
||||
|
||||
export function ListSnapshots(arg1:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
|
||||
export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
export function ListSnapshots(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
|
||||
|
||||
export function OpenProcessorScheduling():Promise<void>;
|
||||
|
||||
export function OpenQQGroup():Promise<void>;
|
||||
|
||||
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenSSHTerminalWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
export function OpenSSHTerminal(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function OpenSharedFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenURL(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVMEndpointWithDriver(arg1:string,arg2:string,arg3:string,arg4:string):Promise<void>;
|
||||
export function OpenVMEndpoint(arg1:string,arg2:string,arg3:string,arg4:string):Promise<void>;
|
||||
|
||||
export function OpenVMFolder(arg1:string):Promise<void>;
|
||||
|
||||
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
export function OpenVSCodeSSH(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function OpenWindowsCoreIsolation():Promise<void>;
|
||||
|
||||
export function OpenWindowsSecurityExclusions():Promise<void>;
|
||||
|
||||
export function OptimizeVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
|
||||
|
||||
export function OptimizeVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
|
||||
export function OptimizeVMDisk(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
|
||||
|
||||
export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
|
||||
|
||||
@@ -261,9 +216,7 @@ export function QuitApp():Promise<void>;
|
||||
|
||||
export function ReadPluginLog(arg1:string):Promise<string>;
|
||||
|
||||
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
|
||||
|
||||
export function ReadVMLogsWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<string>;
|
||||
export function ReadVMLogs(arg1:string,arg2:string,arg3:boolean):Promise<string>;
|
||||
|
||||
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
@@ -275,23 +228,15 @@ export function ReopenDataRoot(arg1:boolean):Promise<dataroot.Status>;
|
||||
|
||||
export function RequestClose():Promise<void>;
|
||||
|
||||
export function ResizeVMDisk(arg1:string,arg2:string):Promise<driver.DiskResizeResult>;
|
||||
|
||||
export function ResizeVMDiskWithDriver(arg1:string,arg2:string,arg3:string):Promise<driver.DiskResizeResult>;
|
||||
export function ResizeVMDisk(arg1:string,arg2:string,arg3:string):Promise<driver.DiskResizeResult>;
|
||||
|
||||
export function ResolveElevationRequest(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function RestartVM(arg1:string):Promise<void>;
|
||||
export function RestartVM(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function RestartVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
export function RestoreSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function RestoreSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function ResumeVM(arg1:string):Promise<void>;
|
||||
|
||||
export function ResumeVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
export function ResumeVM(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
|
||||
|
||||
@@ -327,62 +272,39 @@ export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
export function SetVMAffinity(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMDisplayWithDriver(arg1:string,arg2:string,arg3:string):Promise<app.VMDisplayStatus>;
|
||||
export function SetVMDisplay(arg1:string,arg2:string,arg3:string):Promise<app.VMDisplayStatus>;
|
||||
|
||||
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
|
||||
|
||||
export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise<app.VMKeymapStatus>;
|
||||
|
||||
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
|
||||
export function SetVMNoteWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
export function SetVMNote(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function SetVMSSHUserWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
export function SetVMSSHUser(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
export function SetVMSharedFolderMode(arg1:string,arg2:string,arg3:string):Promise<app.SharedFolderSettings>;
|
||||
|
||||
export function SetVMTimezone(arg1:string,arg2:string):Promise<app.VMTimezoneStatus>;
|
||||
export function SetVMTimezone(arg1:string,arg2:string,arg3:string):Promise<app.VMTimezoneStatus>;
|
||||
|
||||
export function SetVMTimezoneWithDriver(arg1:string,arg2:string,arg3:string):Promise<app.VMTimezoneStatus>;
|
||||
export function StartVM(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function ShowMainWindow():Promise<void>;
|
||||
|
||||
export function StartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function StartVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function StopVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
export function StopVM(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
|
||||
export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
|
||||
|
||||
export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
|
||||
|
||||
export function SuspendVM(arg1:string):Promise<void>;
|
||||
|
||||
export function SuspendVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
export function SuspendVM(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise<guesttools.HostDNSTestResult>;
|
||||
|
||||
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
|
||||
export function ToggleVMFullscreen(arg1:string,arg2:string):Promise<boolean>;
|
||||
|
||||
export function ToggleVMFullscreen(arg1:string):Promise<boolean>;
|
||||
export function TypeClipboard(arg1:string,arg2:string):Promise<number>;
|
||||
|
||||
export function ToggleVMFullscreenWithDriver(arg1:string,arg2:string):Promise<boolean>;
|
||||
|
||||
export function TypeClipboard(arg1:string):Promise<number>;
|
||||
|
||||
export function TypeClipboardWithDriver(arg1:string,arg2:string):Promise<number>;
|
||||
|
||||
export function TypeText(arg1:string,arg2:string):Promise<number>;
|
||||
|
||||
export function TypeTextWithDriver(arg1:string,arg2:string,arg3:string):Promise<number>;
|
||||
export function TypeText(arg1:string,arg2:string,arg3:string):Promise<number>;
|
||||
|
||||
export function UpgradeDiskToNVMe(arg1:string):Promise<void>;
|
||||
|
||||
@@ -392,6 +314,4 @@ export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.Valida
|
||||
|
||||
export function ValidateSet(arg1:reims.SetOpts):Promise<Array<reims.ValidationIssue>>;
|
||||
|
||||
export function WriteSSHConfig(arg1:string,arg2:string):Promise<string>;
|
||||
|
||||
export function WriteSSHConfigWithDriver(arg1:string,arg2:string,arg3:string):Promise<string>;
|
||||
export function WriteSSHConfig(arg1:string,arg2:string,arg3:string):Promise<string>;
|
||||
+80
-248
@@ -46,40 +46,24 @@ 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 CloneVMCoW(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['CloneVMCoW'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function CloneVMCoWWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['CloneVMCoWWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function CompactVMDisk(arg1) {
|
||||
return window['go']['app']['App']['CompactVMDisk'](arg1);
|
||||
}
|
||||
|
||||
export function CompactVMDiskWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['CompactVMDiskWithDriver'](arg1, arg2);
|
||||
export function CompactVMDisk(arg1, arg2) {
|
||||
return window['go']['app']['App']['CompactVMDisk'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CompleteSetup(arg1) {
|
||||
return window['go']['app']['App']['CompleteSetup'](arg1);
|
||||
}
|
||||
|
||||
export function CopyVMScreenshot(arg1) {
|
||||
return window['go']['app']['App']['CopyVMScreenshot'](arg1);
|
||||
export function CopyVMScreenshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['CopyVMScreenshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CopyVMScreenshotWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['CopyVMScreenshotWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CreateSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['CreateSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function CreateSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['CreateSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
export function CreateSnapshot(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['CreateSnapshot'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function CreateVM(arg1) {
|
||||
@@ -98,20 +82,12 @@ 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 DeleteSnapshot(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['DeleteSnapshot'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function DeleteSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['DeleteSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function DeleteVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['DeleteVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DeleteVMWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['DeleteVMWithDriver'](arg1, arg2, arg3);
|
||||
export function DeleteVM(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['DeleteVM'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function DeliverFileToGuest(arg1) {
|
||||
@@ -130,20 +106,8 @@ export function DisablePlugin(arg1) {
|
||||
return window['go']['app']['App']['DisablePlugin'](arg1);
|
||||
}
|
||||
|
||||
export function DiscardSuspend(arg1) {
|
||||
return window['go']['app']['App']['DiscardSuspend'](arg1);
|
||||
}
|
||||
|
||||
export function DiscardSuspendWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['DiscardSuspendWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DismissTask(arg1) {
|
||||
return window['go']['app']['App']['DismissTask'](arg1);
|
||||
}
|
||||
|
||||
export function DoctorPlugin(arg1) {
|
||||
return window['go']['app']['App']['DoctorPlugin'](arg1);
|
||||
export function DiscardSuspend(arg1, arg2) {
|
||||
return window['go']['app']['App']['DiscardSuspend'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DownloadAndAttachOnlineRecovery(arg1, arg2) {
|
||||
@@ -158,44 +122,28 @@ export function DownloadInstaller(arg1) {
|
||||
return window['go']['app']['App']['DownloadInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstaller(arg1) {
|
||||
return window['go']['app']['App']['EjectInstaller'](arg1);
|
||||
}
|
||||
|
||||
export function EjectInstallerWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['EjectInstallerWithDriver'](arg1, arg2);
|
||||
export function EjectInstaller(arg1, arg2) {
|
||||
return window['go']['app']['App']['EjectInstaller'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function EnablePlugin(arg1, arg2) {
|
||||
return window['go']['app']['App']['EnablePlugin'](arg1, arg2);
|
||||
}
|
||||
|
||||
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 ExportDiagnosticsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ExportDiagnosticsWithDriver'](arg1, arg2);
|
||||
export function ExportDiagnostics(arg1, arg2) {
|
||||
return window['go']['app']['App']['ExportDiagnostics'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function FinishInstall(arg1) {
|
||||
return window['go']['app']['App']['FinishInstall'](arg1);
|
||||
}
|
||||
|
||||
export function FocusVMWindow(arg1) {
|
||||
return window['go']['app']['App']['FocusVMWindow'](arg1);
|
||||
}
|
||||
|
||||
export function FocusVMWindowWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['FocusVMWindowWithDriver'](arg1, arg2);
|
||||
export function FocusVMWindow(arg1, arg2) {
|
||||
return window['go']['app']['App']['FocusVMWindow'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ForceQuitApp() {
|
||||
@@ -250,28 +198,24 @@ export function GetTasks() {
|
||||
return window['go']['app']['App']['GetTasks']();
|
||||
}
|
||||
|
||||
export function GetVMAffinity(arg1) {
|
||||
return window['go']['app']['App']['GetVMAffinity'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMAffinityWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMAffinityWithDriver'](arg1, arg2);
|
||||
export function GetVMAffinity(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMAffinity'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMDetail(arg1) {
|
||||
return window['go']['app']['App']['GetVMDetail'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMDisplayWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMDisplayWithDriver'](arg1, arg2);
|
||||
export function GetVMDisplay(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMDisplay'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMDriveShareSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMEndpointCommandWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['GetVMEndpointCommandWithDriver'](arg1, arg2, arg3);
|
||||
export function GetVMEndpointCommand(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['GetVMEndpointCommand'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function GetVMInfo(arg1, arg2) {
|
||||
@@ -294,8 +238,8 @@ export function GetVMNetworkSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMNetworkSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMNote(arg1) {
|
||||
return window['go']['app']['App']['GetVMNote'](arg1);
|
||||
export function GetVMNote(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMNote'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMPluginSettings(arg1) {
|
||||
@@ -306,44 +250,24 @@ export function GetVMSMBIOS(arg1) {
|
||||
return window['go']['app']['App']['GetVMSMBIOS'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMNoteWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMNoteWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMSSHUser(arg1) {
|
||||
return window['go']['app']['App']['GetVMSSHUser'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMSSHUserWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMSSHUserWithDriver'](arg1, arg2);
|
||||
export function GetVMSSHUser(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMSSHUser'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMSharedFolderSettings(arg1) {
|
||||
return window['go']['app']['App']['GetVMSharedFolderSettings'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMStats(arg1) {
|
||||
return window['go']['app']['App']['GetVMStats'](arg1);
|
||||
export function GetVMStats(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMStats'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMStatsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMStatsWithDriver'](arg1, arg2);
|
||||
export function GetVMThumbnail(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMThumbnail'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMThumbnail(arg1) {
|
||||
return window['go']['app']['App']['GetVMThumbnail'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMThumbnailWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMThumbnailWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function GetVMTimezone(arg1) {
|
||||
return window['go']['app']['App']['GetVMTimezone'](arg1);
|
||||
}
|
||||
|
||||
export function GetVMTimezoneWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMTimezoneWithDriver'](arg1, arg2);
|
||||
export function GetVMTimezone(arg1, arg2) {
|
||||
return window['go']['app']['App']['GetVMTimezone'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function InspectPluginArchive(arg1) {
|
||||
@@ -406,16 +330,8 @@ export function ListRemoteRuntimes() {
|
||||
return window['go']['app']['App']['ListRemoteRuntimes']();
|
||||
}
|
||||
|
||||
export function ListRuntimeKinds() {
|
||||
return window['go']['app']['App']['ListRuntimeKinds']();
|
||||
}
|
||||
|
||||
export function ListSnapshots(arg1) {
|
||||
return window['go']['app']['App']['ListSnapshots'](arg1);
|
||||
}
|
||||
|
||||
export function ListSnapshotsWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ListSnapshotsWithDriver'](arg1, arg2);
|
||||
export function ListSnapshots(arg1, arg2) {
|
||||
return window['go']['app']['App']['ListSnapshots'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenProcessorScheduling() {
|
||||
@@ -426,12 +342,8 @@ export function OpenQQGroup() {
|
||||
return window['go']['app']['App']['OpenQQGroup']();
|
||||
}
|
||||
|
||||
export function OpenSSHTerminal(arg1, arg2) {
|
||||
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function OpenSSHTerminalWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['OpenSSHTerminalWithDriver'](arg1, arg2, arg3);
|
||||
export function OpenSSHTerminal(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['OpenSSHTerminal'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function OpenSharedFolder(arg1) {
|
||||
@@ -442,20 +354,16 @@ export function OpenURL(arg1) {
|
||||
return window['go']['app']['App']['OpenURL'](arg1);
|
||||
}
|
||||
|
||||
export function OpenVMEndpointWithDriver(arg1, arg2, arg3, arg4) {
|
||||
return window['go']['app']['App']['OpenVMEndpointWithDriver'](arg1, arg2, arg3, arg4);
|
||||
export function OpenVMEndpoint(arg1, arg2, arg3, arg4) {
|
||||
return window['go']['app']['App']['OpenVMEndpoint'](arg1, arg2, arg3, arg4);
|
||||
}
|
||||
|
||||
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 OpenVSCodeSSHWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['OpenVSCodeSSHWithDriver'](arg1, arg2, arg3);
|
||||
export function OpenVSCodeSSH(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function OpenWindowsCoreIsolation() {
|
||||
@@ -466,12 +374,8 @@ export function OpenWindowsSecurityExclusions() {
|
||||
return window['go']['app']['App']['OpenWindowsSecurityExclusions']();
|
||||
}
|
||||
|
||||
export function OptimizeVMDisk(arg1) {
|
||||
return window['go']['app']['App']['OptimizeVMDisk'](arg1);
|
||||
}
|
||||
|
||||
export function OptimizeVMDiskWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['OptimizeVMDiskWithDriver'](arg1, arg2);
|
||||
export function OptimizeVMDisk(arg1, arg2) {
|
||||
return window['go']['app']['App']['OptimizeVMDisk'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function PanelBridgeCall(arg1, arg2, arg3) {
|
||||
@@ -506,12 +410,8 @@ export function ReadPluginLog(arg1) {
|
||||
return window['go']['app']['App']['ReadPluginLog'](arg1);
|
||||
}
|
||||
|
||||
export function ReadVMLogs(arg1, arg2) {
|
||||
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ReadVMLogsWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ReadVMLogsWithDriver'](arg1, arg2, arg3);
|
||||
export function ReadVMLogs(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function RemovePlugin(arg1, arg2) {
|
||||
@@ -534,40 +434,24 @@ export function RequestClose() {
|
||||
return window['go']['app']['App']['RequestClose']();
|
||||
}
|
||||
|
||||
export function ResizeVMDisk(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ResizeVMDiskWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ResizeVMDiskWithDriver'](arg1, arg2, arg3);
|
||||
export function ResizeVMDisk(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ResizeVMDisk'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ResolveElevationRequest(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResolveElevationRequest'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestartVM(arg1) {
|
||||
return window['go']['app']['App']['RestartVM'](arg1);
|
||||
export function RestartVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestartVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestartVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestartVMWithDriver'](arg1, arg2);
|
||||
export function RestoreSnapshot(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function RestoreSnapshot(arg1, arg2) {
|
||||
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function RestoreSnapshotWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['RestoreSnapshotWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function ResumeVM(arg1) {
|
||||
return window['go']['app']['App']['ResumeVM'](arg1);
|
||||
}
|
||||
|
||||
export function ResumeVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResumeVMWithDriver'](arg1, arg2);
|
||||
export function ResumeVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['ResumeVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SaveCustomThemeScheme(arg1) {
|
||||
@@ -638,16 +522,12 @@ export function SetSyncHostMemorySMBIOS(arg1) {
|
||||
return window['go']['app']['App']['SetSyncHostMemorySMBIOS'](arg1);
|
||||
}
|
||||
|
||||
export function SetVMAffinity(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2);
|
||||
export function SetVMAffinity(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMAffinityWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMAffinityWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMDisplayWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMDisplayWithDriver'](arg1, arg2, arg3);
|
||||
export function SetVMDisplay(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMDisplay'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
|
||||
@@ -658,52 +538,28 @@ export function SetVMKeymap(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMKeymap'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMNote(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMNote'](arg1, arg2);
|
||||
export function SetVMNote(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMNote'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMNoteWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMNoteWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMSSHUser(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SetVMSSHUserWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMSSHUserWithDriver'](arg1, arg2, arg3);
|
||||
export function SetVMSSHUser(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMSSHUser'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMSharedFolderMode(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMSharedFolderMode'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMTimezone(arg1, arg2) {
|
||||
return window['go']['app']['App']['SetVMTimezone'](arg1, arg2);
|
||||
export function SetVMTimezone(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMTimezone'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SetVMTimezoneWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMTimezoneWithDriver'](arg1, arg2, arg3);
|
||||
export function StartVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['StartVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ShowMainWindow() {
|
||||
return window['go']['app']['App']['ShowMainWindow']();
|
||||
}
|
||||
|
||||
export function StartVM(arg1) {
|
||||
return window['go']['app']['App']['StartVM'](arg1);
|
||||
}
|
||||
|
||||
export function StartVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['StartVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StopVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StopVMWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['StopVMWithDriver'](arg1, arg2, arg3);
|
||||
export function StopVM(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['StopVM'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function SuggestDataRoots() {
|
||||
@@ -714,44 +570,24 @@ export function SuggestLanguagePack() {
|
||||
return window['go']['app']['App']['SuggestLanguagePack']();
|
||||
}
|
||||
|
||||
export function SuspendVM(arg1) {
|
||||
return window['go']['app']['App']['SuspendVM'](arg1);
|
||||
}
|
||||
|
||||
export function SuspendVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['SuspendVMWithDriver'](arg1, arg2);
|
||||
export function SuspendVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['SuspendVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function TestHostDNS(arg1) {
|
||||
return window['go']['app']['App']['TestHostDNS'](arg1);
|
||||
}
|
||||
|
||||
export function ToggleBorderless(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleBorderless'](arg1, arg2);
|
||||
export function ToggleVMFullscreen(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleVMFullscreen'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ToggleVMFullscreen(arg1) {
|
||||
return window['go']['app']['App']['ToggleVMFullscreen'](arg1);
|
||||
export function TypeClipboard(arg1, arg2) {
|
||||
return window['go']['app']['App']['TypeClipboard'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function ToggleVMFullscreenWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['ToggleVMFullscreenWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function TypeClipboard(arg1) {
|
||||
return window['go']['app']['App']['TypeClipboard'](arg1);
|
||||
}
|
||||
|
||||
export function TypeClipboardWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['TypeClipboardWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function TypeText(arg1, arg2) {
|
||||
return window['go']['app']['App']['TypeText'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function TypeTextWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['TypeTextWithDriver'](arg1, arg2, arg3);
|
||||
export function TypeText(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['TypeText'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function UpgradeDiskToNVMe(arg1) {
|
||||
@@ -770,10 +606,6 @@ export function ValidateSet(arg1) {
|
||||
return window['go']['app']['App']['ValidateSet'](arg1);
|
||||
}
|
||||
|
||||
export function WriteSSHConfig(arg1, arg2) {
|
||||
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function WriteSSHConfigWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['WriteSSHConfigWithDriver'](arg1, arg2, arg3);
|
||||
export function WriteSSHConfig(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['WriteSSHConfig'](arg1, arg2, arg3);
|
||||
}
|
||||
@@ -958,6 +958,7 @@ export namespace driver {
|
||||
console_endpoint?: string;
|
||||
paste_combo?: string;
|
||||
keymap?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DriverSummary(source);
|
||||
}
|
||||
@@ -1000,11 +1001,11 @@ export namespace driver {
|
||||
distro?: string;
|
||||
version?: string;
|
||||
arch?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new GuestOSInfo(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.family = source["family"];
|
||||
@@ -1022,11 +1023,11 @@ export namespace driver {
|
||||
vm?: string;
|
||||
serial?: string;
|
||||
ready: boolean;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMEndpoint(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.kind = source["kind"];
|
||||
@@ -1059,6 +1060,7 @@ export namespace driver {
|
||||
phase?: string;
|
||||
ready?: boolean;
|
||||
endpoints?: VMEndpoint[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMInfo(source);
|
||||
}
|
||||
@@ -1085,7 +1087,7 @@ export namespace driver {
|
||||
this.ready = source["ready"];
|
||||
this.endpoints = this.convertValues(source["endpoints"], VMEndpoint);
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -1115,6 +1117,7 @@ export namespace driver {
|
||||
phase?: string;
|
||||
ready?: boolean;
|
||||
endpoints?: VMEndpoint[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new VMListItem(source);
|
||||
}
|
||||
@@ -1132,7 +1135,7 @@ export namespace driver {
|
||||
this.ready = source["ready"];
|
||||
this.endpoints = this.convertValues(source["endpoints"], VMEndpoint);
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -1796,7 +1799,6 @@ export namespace plugin {
|
||||
icons?: Record<string, string>;
|
||||
brandMark?: string;
|
||||
background?: string;
|
||||
sounds?: Record<string, string>;
|
||||
stylesheet?: string;
|
||||
decorations?: ThemeDecoration[];
|
||||
uiScript?: string;
|
||||
@@ -1822,7 +1824,6 @@ export namespace plugin {
|
||||
this.icons = source["icons"];
|
||||
this.brandMark = source["brandMark"];
|
||||
this.background = source["background"];
|
||||
this.sounds = source["sounds"];
|
||||
this.stylesheet = source["stylesheet"];
|
||||
this.decorations = this.convertValues(source["decorations"], ThemeDecoration);
|
||||
this.uiScript = source["uiScript"];
|
||||
@@ -1935,22 +1936,6 @@ export namespace plugin {
|
||||
}
|
||||
}
|
||||
|
||||
export class DoctorFinding {
|
||||
severity: string;
|
||||
check: string;
|
||||
message: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new DoctorFinding(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.severity = source["severity"];
|
||||
this.check = source["check"];
|
||||
this.message = source["message"];
|
||||
}
|
||||
}
|
||||
export class Engines {
|
||||
"reims-go"?: string;
|
||||
pluginApi?: string;
|
||||
@@ -2330,52 +2315,6 @@ export namespace plugin {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class ViewContribution {
|
||||
id: string;
|
||||
title: LocalizedText;
|
||||
icon?: string;
|
||||
location: string;
|
||||
entry: string;
|
||||
order?: number;
|
||||
when?: string;
|
||||
minWidth?: number;
|
||||
pluginId?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ViewContribution(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.title = this.convertValues(source["title"], LocalizedText);
|
||||
this.icon = source["icon"];
|
||||
this.location = source["location"];
|
||||
this.entry = source["entry"];
|
||||
this.order = source["order"];
|
||||
this.when = source["when"];
|
||||
this.minWidth = source["minWidth"];
|
||||
this.pluginId = source["pluginId"];
|
||||
}
|
||||
|
||||
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 PermissionSpec {
|
||||
name: string;
|
||||
level: string;
|
||||
@@ -2946,6 +2885,52 @@ export namespace plugin {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class ViewContribution {
|
||||
id: string;
|
||||
title: LocalizedText;
|
||||
icon?: string;
|
||||
location: string;
|
||||
entry: string;
|
||||
order?: number;
|
||||
when?: string;
|
||||
minWidth?: number;
|
||||
pluginId?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ViewContribution(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.title = this.convertValues(source["title"], LocalizedText);
|
||||
this.icon = source["icon"];
|
||||
this.location = source["location"];
|
||||
this.entry = source["entry"];
|
||||
this.order = source["order"];
|
||||
this.when = source["when"];
|
||||
this.minWidth = source["minWidth"];
|
||||
this.pluginId = source["pluginId"];
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// VMAffinityUpdate is the payload passed from the UI to save and live-apply a
|
||||
@@ -39,22 +38,10 @@ type VMAffinityStatus struct {
|
||||
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
|
||||
return runningPIDByName(vms, name)
|
||||
}
|
||||
}
|
||||
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
|
||||
return a.cachedVMPID(name)
|
||||
}
|
||||
|
||||
func buildVMAffinityStatus(detail driver.VMInfo, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus {
|
||||
@@ -97,10 +84,7 @@ func buildVMAffinityStatus(detail driver.VMInfo, rep host.Report, globalAutoPin
|
||||
|
||||
// GetVMAffinity returns the per-VM processor affinity configuration, resolved
|
||||
// effective CPU set, and live QEMU process affinity mask when running.
|
||||
func (a *App) GetVMAffinity(name string) (VMAffinityStatus, error) {
|
||||
return a.GetVMAffinityWithDriver("", name)
|
||||
}
|
||||
func (a *App) GetVMAffinityWithDriver(driverID, name string) (VMAffinityStatus, error) {
|
||||
func (a *App) GetVMAffinity(driverID, name string) (VMAffinityStatus, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
@@ -128,10 +112,7 @@ func (a *App) GetVMAffinityWithDriver(driverID, name string) (VMAffinityStatus,
|
||||
|
||||
// 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) {
|
||||
return a.SetVMAffinityWithDriver("", name, req)
|
||||
}
|
||||
func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
|
||||
func (a *App) SetVMAffinity(driverID, name string, req VMAffinityUpdate) (VMAffinityStatus, error) {
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
@@ -140,7 +121,7 @@ func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdat
|
||||
if err != nil {
|
||||
return VMAffinityStatus{}, err
|
||||
}
|
||||
if driver.IsHosted(vm.Capabilities) || (len(vm.Capabilities) > 0 && !driver.HasCapability(vm.Capabilities, driver.CapAffinity)) {
|
||||
if driver.IsHosted(vm.Capabilities) || !driver.SupportsCapability(vm.Capabilities, driver.CapAffinity) {
|
||||
return VMAffinityStatus{}, fmt.Errorf("CPU affinity is not available for %s", name)
|
||||
}
|
||||
if detail.Directory == "" {
|
||||
@@ -180,8 +161,6 @@ func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdat
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr
|
||||
}
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitStateChanged()
|
||||
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
|
||||
}
|
||||
+23
-477
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -284,7 +283,7 @@ func (a *App) beforeClose(ctx context.Context) bool {
|
||||
if tasks.hasRunningDownload() {
|
||||
// Closing now would abort a download: ask first. The window's
|
||||
// confirmation calls QuitApp, which lets the next close through.
|
||||
wailsRuntime.EventsEmit(ctx, "reims:confirm-close-downloads", true)
|
||||
a.emit("reims:confirm-close-downloads", true)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -333,446 +332,6 @@ func (a *App) shutdown(ctx context.Context) {
|
||||
releaseVMTyping("")
|
||||
}
|
||||
|
||||
// pollVMs refreshes the VM list every pollBusy while a VM is starting or
|
||||
// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`.
|
||||
// Start, stop and delete call wakePoll so their result shows up at once.
|
||||
const (
|
||||
pollBusy = 2 * time.Second
|
||||
// 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
|
||||
)
|
||||
|
||||
func (a *App) pollVMs(ctx context.Context) {
|
||||
timer := time.NewTimer(pollBusy)
|
||||
defer timer.Stop()
|
||||
// Cache static hybrid P-core mask once instead of querying host every tick.
|
||||
a.mu.Lock()
|
||||
initRoot := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
cachedHost := host.Inspect(initRoot)
|
||||
var lastSig string
|
||||
pinnedPIDs := make(map[int]bool)
|
||||
guideCheckedPIDs := make(map[int]bool)
|
||||
lastGuideMgr := a.getInstallGuideManager()
|
||||
exitWatched := make(map[int]bool)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
case <-a.pollWake:
|
||||
}
|
||||
a.mu.Lock()
|
||||
next := pollSteady
|
||||
if len(a.transitions) > 0 {
|
||||
next = pollBusy
|
||||
}
|
||||
a.mu.Unlock()
|
||||
timer.Reset(next)
|
||||
// reims-ctl keeps its state in the data folder; leave it alone until
|
||||
// setup has chosen one, and while it is open read-only.
|
||||
if !a.dataRootUsable() {
|
||||
continue
|
||||
}
|
||||
vms, err := a.listVMsInternal(ctx)
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
changed := a.lastVMListErr == nil || a.lastVMListErr.Error() != err.Error()
|
||||
a.lastVMListErr = err
|
||||
if a.lastVMsAt.IsZero() && a.lastVMs == nil {
|
||||
a.lastVMs = vms
|
||||
}
|
||||
a.lastVMsAt = time.Now()
|
||||
a.mu.Unlock()
|
||||
if changed {
|
||||
a.emitLifecycleStateChanged()
|
||||
}
|
||||
continue
|
||||
}
|
||||
a.syncComputerUseOwnership(vms)
|
||||
// Only VMs whose process the host neither spawned (the broker watches
|
||||
// those through their job) nor leaves to the driver (hosted) need a
|
||||
// per-PID exit watcher.
|
||||
procVMs := make([]driver.VMListItem, 0, len(vms))
|
||||
for _, vm := range vms {
|
||||
if !driver.IsHosted(vm.Capabilities) && !a.brokerRunsVM(vm.DriverID, vm.Name) {
|
||||
procVMs = append(procVMs, vm)
|
||||
}
|
||||
}
|
||||
watchExits(ctx, procVMs, exitWatched, a.wakePoll)
|
||||
type pinCandidate struct {
|
||||
driverID string
|
||||
name string
|
||||
dir string
|
||||
pid int
|
||||
}
|
||||
var toPin []pinCandidate
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
autoPin := a.cfg.AutoPinPCores
|
||||
tm := a.trayMgr
|
||||
runningCount := 0
|
||||
var b strings.Builder
|
||||
var imeTargets []host.IMETarget
|
||||
for _, vm := range vms {
|
||||
key := vmKeyForDriver(vm.DriverID, vm.Name)
|
||||
if vm.State == "running" {
|
||||
runningCount++
|
||||
// The remote IME bridge types through the macOS guest's tools.
|
||||
if vm.PID != nil && *vm.PID > 0 && (driver.HasCapability(vm.Capabilities, driver.CapGuestTools) || len(vm.Capabilities) == 0) {
|
||||
imeTargets = append(imeTargets, host.IMETarget{
|
||||
VMName: vm.Name,
|
||||
VMDir: vm.Dir,
|
||||
PID: uint32(*vm.PID),
|
||||
})
|
||||
}
|
||||
}
|
||||
if tr, ok := a.transitions[key]; ok {
|
||||
if (tr == "starting" && vm.State == "running") ||
|
||||
(tr == "stopping" && vm.State == "stopped") ||
|
||||
(tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) ||
|
||||
(tr == "resuming" && vm.State == "running") {
|
||||
delete(a.transitions, key)
|
||||
if vm.State == "stopped" {
|
||||
delete(a.pendingChanges, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
if vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] &&
|
||||
!driver.IsHosted(vm.Capabilities) && (driver.HasCapability(vm.Capabilities, driver.CapAffinity) || len(vm.Capabilities) == 0) {
|
||||
pinnedPIDs[*vm.PID] = true
|
||||
toPin = append(toPin, pinCandidate{driverID: vm.DriverID, name: vm.Name, dir: vm.Dir, pid: *vm.PID})
|
||||
}
|
||||
fmt.Fprintf(&b, "%s:%s:%s:%s:%s:%s;", key, vm.State, a.transitions[key], vm.Phase, readyToken(vm.Ready), endpointSignature(vm.Endpoints))
|
||||
}
|
||||
sig := b.String()
|
||||
ib := a.imeBridge
|
||||
liveVMs := make(map[string]struct{}, len(vms))
|
||||
for _, vm := range vms {
|
||||
liveVMs[vmKeyForDriver(vm.DriverID, vm.Name)] = struct{}{}
|
||||
}
|
||||
removedVMs := make(map[string]struct{})
|
||||
for _, vm := range a.lastVMs {
|
||||
key := vmKeyForDriver(vm.DriverID, vm.Name)
|
||||
if _, ok := liveVMs[key]; !ok {
|
||||
removedVMs[key] = 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
|
||||
})
|
||||
var stoppedBridges []string
|
||||
for _, prev := range a.lastVMs {
|
||||
if prev.State != "running" || prev.DriverID != driver.BuiltinReimsMacOSDriverID {
|
||||
continue
|
||||
}
|
||||
key := vmKeyForDriver(prev.DriverID, prev.Name)
|
||||
tr := a.transitions[key]
|
||||
if tr == "starting" || tr == "resuming" {
|
||||
continue
|
||||
}
|
||||
for _, cur := range vms {
|
||||
if cur.DriverID == prev.DriverID && cur.Name == prev.Name && cur.State != "running" {
|
||||
stoppedBridges = append(stoppedBridges, cur.Name)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
gt := a.guestTools
|
||||
a.lastVMs = append([]driver.VMListItem(nil), vms...)
|
||||
a.lastVMsAt = time.Now()
|
||||
listRecovered := a.lastVMListErr != nil
|
||||
a.lastVMListErr = nil
|
||||
a.mu.Unlock()
|
||||
for _, vmName := range stoppedBridges {
|
||||
a.stopPacketBridge(vmName)
|
||||
if gt != nil {
|
||||
gt.StopManagementNetwork(vmName)
|
||||
}
|
||||
}
|
||||
prunePinnedPIDs(pinnedPIDs, vms)
|
||||
prunePinnedPIDs(guideCheckedPIDs, vms)
|
||||
guideMgr := a.getInstallGuideManager()
|
||||
if guideMgr != lastGuideMgr {
|
||||
clear(guideCheckedPIDs)
|
||||
lastGuideMgr = guideMgr
|
||||
}
|
||||
runningPIDs := make(map[int]bool, len(vms))
|
||||
for _, vm := range vms {
|
||||
if vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
runningPIDs[*vm.PID] = true
|
||||
}
|
||||
}
|
||||
guidesChanged := false
|
||||
if guideMgr != nil {
|
||||
guidesChanged = guideMgr.CancelStopped(runningPIDs)
|
||||
}
|
||||
for key := range removedVMs {
|
||||
name := vmNameFromKey(key)
|
||||
if ref, ok := driver.ParseVMRef(key); ok && ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.stopPacketBridge(name)
|
||||
}
|
||||
a.forgetComputerUseOwnedVM(key)
|
||||
ref, parsed := driver.ParseVMRef(key)
|
||||
// A disabled driver's VMs may leave the list without being deleted.
|
||||
if parsed && a.driverFor(driver.VMInfo{DriverID: ref.DriverID}) != nil {
|
||||
a.discardMaterializedSecretsForVM(key)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
if !parsed || ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
// These helpers are keyed by bare name and belong to macOS VMs only.
|
||||
stopVMMonitor(name)
|
||||
releaseVMTyping(name)
|
||||
releaseVMThumbnail(name)
|
||||
} else {
|
||||
releaseVMTypingForDriver(ref.DriverID, ref.Name)
|
||||
releaseVMThumbnailForDriver(ref.DriverID, ref.Name)
|
||||
}
|
||||
if parsed {
|
||||
a.stateTable().Delete(ref)
|
||||
}
|
||||
a.cancelRebootWatcherKey(key)
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(key)
|
||||
}
|
||||
}
|
||||
if ib != nil {
|
||||
ib.SetTargets(imeTargets)
|
||||
}
|
||||
a.syncKeymapRules()
|
||||
a.syncFullscreenHotkeyTargets()
|
||||
if tm != nil {
|
||||
effLoc := i18n.EffectiveLocale(loc)
|
||||
if runningCount >= 1 {
|
||||
tm.UpdateTooltip(i18n.M(effLoc, "tray.running", i18n.Vars{"count": runningCount}))
|
||||
} else {
|
||||
tm.UpdateTooltip("Reims-Go")
|
||||
}
|
||||
}
|
||||
shownDetails := make(map[string]driver.VMInfo, len(toPin))
|
||||
for _, cand := range toPin {
|
||||
det, err := a.resolveVMInfo(cand.driverID, cand.name)
|
||||
if err != nil {
|
||||
// Retry boot discovery if the runtime was still starting.
|
||||
delete(pinnedPIDs, cand.pid)
|
||||
continue
|
||||
}
|
||||
vmDir := cand.dir
|
||||
if vmDir == "" {
|
||||
vmDir = det.Directory
|
||||
}
|
||||
if det.Directory == "" {
|
||||
det.Directory = vmDir
|
||||
}
|
||||
shownDetails[vmKeyForDriver(cand.driverID, cand.name)] = det
|
||||
if line, _ := a.applyVMAffinity(loc, cachedHost, driver.NewVMRef(cand.driverID, cand.name), vmDir, autoPin, cand.pid, det.CPUs, false); line != "" {
|
||||
if driver.NewVMRef(cand.driverID, cand.name).DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.emitLog(cand.name, line)
|
||||
} else {
|
||||
a.emitVMLogForDriver(cand.driverID, cand.name, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
if guideMgr != nil {
|
||||
for _, vm := range vms {
|
||||
if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
|
||||
continue
|
||||
}
|
||||
// The install guide belongs to the macOS installer flow.
|
||||
if len(vm.Capabilities) > 0 && !driver.HasCapability(vm.Capabilities, driver.CapOpenCore) {
|
||||
continue
|
||||
}
|
||||
pid := *vm.PID
|
||||
if guideCheckedPIDs[pid] {
|
||||
continue
|
||||
}
|
||||
det, ok := shownDetails[vmKeyForDriver(vm.DriverID, vm.Name)]
|
||||
if !ok {
|
||||
d, err := a.resolveVMInfo(vm.DriverID, vm.Name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if d.Directory == "" {
|
||||
d.Directory = vm.Dir
|
||||
}
|
||||
det = d
|
||||
}
|
||||
guideCheckedPIDs[pid] = true
|
||||
if a.maybeStartInstallGuide(ctx, guideMgr, vm.Name, pid, det, loc) {
|
||||
guidesChanged = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if sig != lastSig || guidesChanged || listRecovered {
|
||||
lastSig = sig
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) listVMsInternal(ctx context.Context) ([]driver.VMListItem, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc != nil {
|
||||
vms, err := svc.List(ctx)
|
||||
out := make([]driver.VMListItem, 0, len(vms))
|
||||
for _, vm := range vms {
|
||||
out = append(out, driver.VMListItem{
|
||||
Name: vm.Name, DriverID: vm.DriverID, Dir: vm.Directory, PID: vm.PID, State: vm.State,
|
||||
Capabilities: vm.Capabilities, GuestOS: vm.GuestOS, Phase: vm.Phase, Ready: vm.Ready, Endpoints: vm.Endpoints,
|
||||
})
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vms, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range vms {
|
||||
vms[i].DriverID = driver.BuiltinReimsMacOSDriverID
|
||||
}
|
||||
enrichMacOSVMListStates(vms)
|
||||
return vms, nil
|
||||
}
|
||||
|
||||
// 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 []driver.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 []driver.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.
|
||||
func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) {
|
||||
a.mu.Lock()
|
||||
if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge {
|
||||
vms := append([]driver.VMListItem(nil), a.lastVMs...)
|
||||
err := a.lastVMListErr
|
||||
a.mu.Unlock()
|
||||
return vms, err
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return a.listVMsInternal(ctx)
|
||||
}
|
||||
|
||||
// polledVM looks name up in polledVMs.
|
||||
func (a *App) polledVM(name string) (driver.VMListItem, bool) {
|
||||
vms, err := a.polledVMs(context.Background())
|
||||
if err != nil {
|
||||
return driver.VMListItem{}, false
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name {
|
||||
return vm, true
|
||||
}
|
||||
}
|
||||
return driver.VMListItem{}, false
|
||||
}
|
||||
|
||||
func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) {
|
||||
vms, err := a.polledVMs(context.Background())
|
||||
if err != nil {
|
||||
return driver.VMListItem{}, false
|
||||
}
|
||||
driverID = driver.CanonicalDriverID(driverID)
|
||||
if driverID == "" {
|
||||
driverID = driver.BuiltinReimsMacOSDriverID
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID {
|
||||
return vm, true
|
||||
}
|
||||
}
|
||||
return driver.VMListItem{}, false
|
||||
}
|
||||
|
||||
// wakePoll marks the polled list stale and runs pollVMs now. Call it after
|
||||
// anything that changes which VMs exist or run.
|
||||
func (a *App) wakePoll() {
|
||||
a.mu.Lock()
|
||||
a.lastVMsAt = time.Time{}
|
||||
a.mu.Unlock()
|
||||
select {
|
||||
case a.pollWake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// cachedDiskPath is one VM's disk path from `reims-ctl show`, kept for
|
||||
// diskPathTTL so GetVMStats doesn't run `show` every few seconds.
|
||||
type cachedDiskPath struct {
|
||||
@@ -797,7 +356,7 @@ func (a *App) emitLog(source, line string) {
|
||||
if a.ctx == nil {
|
||||
return
|
||||
}
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{
|
||||
a.emit("reims:log", map[string]string{
|
||||
"ts": ts,
|
||||
"source": source,
|
||||
"line": redacted,
|
||||
@@ -897,9 +456,7 @@ func (a *App) SetLocale(raw string) error {
|
||||
if mgr != nil {
|
||||
mgr.NotifyLocaleChanged(eff)
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitStateChanged()
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -926,8 +483,8 @@ func (a *App) SetSyncHostMemorySMBIOS(enabled bool) error {
|
||||
return a.saveConfigLocked()
|
||||
}
|
||||
|
||||
// ShowMainWindow restores and focuses the Wails window from the system tray.
|
||||
func (a *App) ShowMainWindow() {
|
||||
// showMainWindow restores and focuses the Wails window from the system tray.
|
||||
func (a *App) showMainWindow() {
|
||||
if a.ctx == nil {
|
||||
return
|
||||
}
|
||||
@@ -948,13 +505,11 @@ func (a *App) RequestClose() {
|
||||
func (a *App) startTray() {
|
||||
mgr, err := tray.Start(a.trayIcon, "Reims-Go", tray.Callbacks{
|
||||
OnShow: func() {
|
||||
a.ShowMainWindow()
|
||||
a.showMainWindow()
|
||||
},
|
||||
OnNewVM: func() {
|
||||
a.ShowMainWindow()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:tray-new-vm")
|
||||
}
|
||||
a.showMainWindow()
|
||||
a.emit("reims:tray-new-vm")
|
||||
},
|
||||
OnVMAction: a.trayVMAction,
|
||||
OnQuit: a.QuitApp,
|
||||
@@ -1025,39 +580,35 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) {
|
||||
var failTitle string
|
||||
switch act {
|
||||
case tray.ActStart:
|
||||
err, failTitle = a.StartVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.start_fail", vars)
|
||||
err, failTitle = a.StartVM(driverID, name), i18n.M(loc, "tray.notify.start_fail", vars)
|
||||
case tray.ActSuspend:
|
||||
err, failTitle = a.SuspendVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.suspend_fail", vars)
|
||||
err, failTitle = a.SuspendVM(driverID, name), i18n.M(loc, "tray.notify.suspend_fail", vars)
|
||||
case tray.ActResume:
|
||||
err, failTitle = a.ResumeVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.resume_fail", vars)
|
||||
err, failTitle = a.ResumeVM(driverID, name), i18n.M(loc, "tray.notify.resume_fail", vars)
|
||||
case tray.ActDiscardSuspend:
|
||||
a.ShowMainWindow()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:tray-discard-suspend", name)
|
||||
}
|
||||
a.showMainWindow()
|
||||
a.emit("reims:tray-discard-suspend", name)
|
||||
case tray.ActStop:
|
||||
err, failTitle = a.StopVMWithDriver(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
|
||||
err, failTitle = a.StopVM(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
|
||||
case tray.ActForceStop:
|
||||
err, failTitle = a.StopVMWithDriver(driverID, name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars)
|
||||
err, failTitle = a.StopVM(driverID, name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars)
|
||||
case tray.ActRestart:
|
||||
err, failTitle = a.RestartVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.restart_fail", vars)
|
||||
err, failTitle = a.RestartVM(driverID, name), i18n.M(loc, "tray.notify.restart_fail", vars)
|
||||
case tray.ActShowWindow:
|
||||
err, failTitle = a.FocusVMWindowWithDriver(driverID, name), i18n.M(loc, "tray.notify.focus_fail", vars)
|
||||
err, failTitle = a.FocusVMWindow(driverID, name), i18n.M(loc, "tray.notify.focus_fail", vars)
|
||||
case tray.ActToggleFullscreen:
|
||||
_, err = a.ToggleVMFullscreenWithDriver(driverID, name)
|
||||
_, err = a.ToggleVMFullscreen(driverID, name)
|
||||
failTitle = i18n.M(loc, "tray.notify.fullscreen_fail", vars)
|
||||
case tray.ActScreenshot:
|
||||
if err = a.CopyVMScreenshotWithDriver(driverID, name); err == nil && tm != nil {
|
||||
if err = a.CopyVMScreenshot(driverID, name); err == nil && tm != nil {
|
||||
tm.Notify(i18n.T(loc, "tray.notify.screenshot_ok"), name, false)
|
||||
}
|
||||
failTitle = i18n.M(loc, "tray.notify.screenshot_fail", vars)
|
||||
case tray.ActSharedFolder:
|
||||
err, failTitle = a.OpenSharedFolder(name), i18n.T(loc, "tray.notify.shared_fail")
|
||||
case tray.ActOpenInApp:
|
||||
a.ShowMainWindow()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:tray-select-vm", name)
|
||||
}
|
||||
a.showMainWindow()
|
||||
a.emit("reims:tray-select-vm", name)
|
||||
}
|
||||
if err != nil {
|
||||
a.emitVMLog(name, failTitle+": "+err.Error())
|
||||
@@ -1178,9 +729,7 @@ func (a *App) SetDataRoot(dir string) error {
|
||||
if rootChanged {
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitStateChanged()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1245,7 +794,6 @@ func (a *App) RemoveRuntime(commit string) error {
|
||||
a.mu.Lock()
|
||||
cfg := a.cfg
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
ctx := a.ctx
|
||||
a.mu.Unlock()
|
||||
|
||||
inst, err := rt.Remove(cfg, commit)
|
||||
@@ -1262,9 +810,7 @@ func (a *App) RemoveRuntime(commit string) error {
|
||||
}
|
||||
}
|
||||
a.emitLog("runtime", fmt.Sprintf("Removed runtime %s (%s)", inst.Commit, inst.Dir))
|
||||
if ctx != nil {
|
||||
wailsRuntime.EventsEmit(ctx, "reims:state-changed", true)
|
||||
}
|
||||
a.emitStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,13 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"runtime"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
)
|
||||
|
||||
@@ -140,3 +143,39 @@ func TestCachedVMPID(t *testing.T) {
|
||||
t.Fatalf("cachedVMPID(missing-vm) = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordVMListReportsWhatChanged(t *testing.T) {
|
||||
mac := driver.BuiltinReimsMacOSDriverID
|
||||
item := func(name, state string) driver.VMListItem {
|
||||
return driver.VMListItem{DriverID: mac, Name: name, State: state}
|
||||
}
|
||||
key := func(name string) string { return vmKeyForDriver(mac, name) }
|
||||
a := &App{
|
||||
lastVMs: []driver.VMListItem{item("gone", "running"), item("crashed", "running"), item("rebooting", "running"), item("kept", "running")},
|
||||
lastVMListErr: errors.New("reims-ctl failed"),
|
||||
transitions: map[string]string{key("rebooting"): "starting", key("new"): "starting"},
|
||||
pendingChanges: map[string][]PendingChange{},
|
||||
diskPaths: map[string]cachedDiskPath{key("old-disk"): {}, key("kept"): {}},
|
||||
}
|
||||
change := a.recordVMList([]driver.VMListItem{item("crashed", "stopped"), item("rebooting", "stopped"), item("kept", "running"), item("new", "running")})
|
||||
|
||||
if !change.recovered || a.lastVMListErr != nil {
|
||||
t.Error("a good listing after a failed one must count as recovered")
|
||||
}
|
||||
if len(change.removed) != 2 {
|
||||
t.Errorf("removed = %v, want gone and old-disk", change.removed)
|
||||
}
|
||||
if _, ok := a.diskPaths[key("old-disk")]; ok || len(a.diskPaths) != 1 {
|
||||
t.Errorf("diskPaths = %v, want only kept", a.diskPaths)
|
||||
}
|
||||
// "rebooting" is down only because it is being started again.
|
||||
if !slices.Equal(change.stoppedBridges, []string{"crashed"}) {
|
||||
t.Errorf("stoppedBridges = %v, want crashed", change.stoppedBridges)
|
||||
}
|
||||
if _, ok := a.transitions[key("new")]; ok {
|
||||
t.Error("a running VM must not stay in the starting transition")
|
||||
}
|
||||
if a.transitions[key("rebooting")] != "starting" {
|
||||
t.Error("an unfinished transition must be kept")
|
||||
}
|
||||
}
|
||||
@@ -175,7 +175,7 @@ func (a *App) InstallAppUpdate() error {
|
||||
}
|
||||
a.mu.Unlock()
|
||||
target := selfupdate.Target(exe, filepath.Base(path))
|
||||
if err := selfupdate.SwapWithOptions(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil {
|
||||
if err := selfupdate.Swap(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil {
|
||||
return err
|
||||
}
|
||||
a.emitLog("app", fmt.Sprintf("Installed update %s at %s; restarting", ver, target))
|
||||
|
||||
@@ -8,16 +8,12 @@ import (
|
||||
)
|
||||
|
||||
// CloneVMCoW derives a VM through the source VM's owning driver.
|
||||
func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
return a.CloneVMCoWWithDriver("", sourceName, cloneName)
|
||||
}
|
||||
|
||||
func (a *App) CloneVMCoWWithDriver(driverID, sourceName, cloneName string) error {
|
||||
_, err := a.cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName)
|
||||
func (a *App) CloneVMCoW(driverID, sourceName, cloneName string) error {
|
||||
_, err := a.cloneVM(driverID, sourceName, cloneName)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName string) (driver.VMInfo, error) {
|
||||
func (a *App) cloneVM(driverID, sourceName, cloneName string) (driver.VMInfo, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
@@ -31,6 +27,6 @@ func (a *App) cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName string) (
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
a.emitStateChanged()
|
||||
return cloned, nil
|
||||
}
|
||||
@@ -46,8 +46,8 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[
|
||||
"host/vm.get": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.get", a.handleComputerUseVMGet),
|
||||
"host/vm.start": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.start", a.handleComputerUseVMStart),
|
||||
"host/vm.shutdown": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
||||
"host/vm.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVMWithDriver)),
|
||||
"host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVMWithDriver)),
|
||||
"host/vm.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVM)),
|
||||
"host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVM)),
|
||||
"host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone),
|
||||
"host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete),
|
||||
"host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
@@ -175,7 +175,7 @@ func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID
|
||||
view["capabilities"] = append([]string(nil), vm.Capabilities...)
|
||||
}
|
||||
if accessEnabled {
|
||||
username := a.GetVMSSHUserWithDriver(vm.DriverID, vm.Name)
|
||||
username := a.GetVMSSHUser(vm.DriverID, vm.Name)
|
||||
if mgr != nil {
|
||||
settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false)
|
||||
if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" {
|
||||
@@ -200,7 +200,7 @@ func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, m
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.StartVMWithDriver(vm.DriverID, vm.Name); err != nil {
|
||||
if err := a.StartVM(vm.DriverID, vm.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
@@ -217,7 +217,7 @@ func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.StopVMWithDriver(vm.DriverID, vm.Name, false); err != nil {
|
||||
if err := a.StopVM(vm.DriverID, vm.Name, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
@@ -273,14 +273,14 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
|
||||
}) {
|
||||
return nil, fmt.Errorf("VM name %q is already taken", cloneName)
|
||||
}
|
||||
cloned, err := a.cloneVMCoWWithDriverInfo(vm.DriverID, vm.Name, cloneName)
|
||||
cloned, err := a.cloneVM(vm.DriverID, vm.Name, cloneName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cloneRef := cloned.Ref()
|
||||
err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key())
|
||||
if err != nil {
|
||||
if cleanupErr := a.DeleteVMWithDriver(vm.DriverID, cloneName, false); cleanupErr != nil {
|
||||
if cleanupErr := a.DeleteVM(vm.DriverID, cloneName, false); cleanupErr != nil {
|
||||
return nil, errors.Join(err, fmt.Errorf("clean up unregistered clone %q: %w", cloneName, cleanupErr))
|
||||
}
|
||||
return nil, err
|
||||
@@ -307,13 +307,13 @@ func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage
|
||||
return nil, a.computerUseHostError("not_authorized", "err.computer_use.not_owned", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
if vm.State == "running" {
|
||||
if err := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, false); err != nil {
|
||||
if forceErr := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, true); forceErr != nil {
|
||||
if err := a.stopVM(ctx, vm.DriverID, vm.Name, false); err != nil {
|
||||
if forceErr := a.stopVM(ctx, vm.DriverID, vm.Name, true); forceErr != nil {
|
||||
return nil, errors.Join(err, fmt.Errorf("force stop temporary VM %q: %w", vm.Name, forceErr))
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := a.DeleteVMWithDriver(vm.DriverID, vm.Name, false); err != nil {
|
||||
if err := a.DeleteVM(vm.DriverID, vm.Name, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
removeComputerUseOwnership(vm.Directory)
|
||||
@@ -332,7 +332,7 @@ func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawM
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
snapshots, err := a.ListSnapshotsWithDriver(vm.DriverID, vm.Name)
|
||||
snapshots, err := a.ListSnapshots(vm.DriverID, vm.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -351,7 +351,7 @@ func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawM
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.CreateSnapshotWithDriver(vm.DriverID, vm.Name, req.Name); err != nil {
|
||||
if err := a.CreateSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
|
||||
@@ -372,7 +372,7 @@ func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.Raw
|
||||
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
|
||||
return nil, a.computerUseHostError("confirmation_required", "err.computer_use.restore_confirmation", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
if err := a.RestoreSnapshotWithDriver(vm.DriverID, vm.Name, req.Name); err != nil {
|
||||
if err := a.RestoreSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
|
||||
@@ -588,11 +588,11 @@ func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error {
|
||||
}
|
||||
if item.State == "running" {
|
||||
stopCtx, stopCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
err := a.stopVMWithDriverCtx(stopCtx, item.DriverID, item.Name, false)
|
||||
err := a.stopVM(stopCtx, item.DriverID, item.Name, false)
|
||||
stopCancel()
|
||||
if err != nil {
|
||||
forceCtx, forceCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
forceErr := a.stopVMWithDriverCtx(forceCtx, item.DriverID, item.Name, true)
|
||||
forceErr := a.stopVM(forceCtx, item.DriverID, item.Name, true)
|
||||
forceCancel()
|
||||
if forceErr != nil {
|
||||
cleanupErrors = append(cleanupErrors, errors.Join(
|
||||
@@ -603,7 +603,7 @@ func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := a.DeleteVMWithDriver(item.DriverID, item.Name, false); err != nil {
|
||||
if err := a.DeleteVM(item.DriverID, item.Name, false); err != nil {
|
||||
cleanupErrors = append(cleanupErrors, fmt.Errorf("delete orphaned temporary VM %q: %w", item.Name, err))
|
||||
continue
|
||||
}
|
||||
|
||||
Loaded 100 of 312 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user