Merge upstream v0.2.11 and preserve Npcap launch integration
This commit is contained in:
commit
f73520d70f
95 files changed
+2956
-968
No files matched your search
@@ -55,6 +55,7 @@
|
||||
6. **默认用户只拿 `stable` 通道**:CI 产物先入 `alpha`,经真实宿主冒烟并人工确认后才升为 `stable`(见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。
|
||||
7. **配置写入只走 `reims-ctl set`**:不直接改写 `vm.toml`,保证上游校验与 OpenCore 重建生效(见 [`docs/design-guidelines.md`](docs/design-guidelines.md))。
|
||||
8. **文档维护纪律**:`docs/` 只存放当前生效的长期文档,使用单一事实来源;不写私人本机路径、日期补丁式叙事、易过时的伪代码/ASCII 草图;一次性排查、审视与排期记录留在 Issue 或 PR 中。
|
||||
9. **禁止空 `catch` 吞错**:严禁编写带有空代码块(含仅注释或空语句)的 `catch` 语句或空回调(如 `catch {}`、`catch (e) {}`、`.catch(() => {})`、`.then(..., () => {})`)把失败静默包装成成功;捕获异常后必须执行明确的错误处理(上报/展示错误、记录诊断告警、分类过滤预期错误并重抛其余异常,或显式回退状态)。该约束由 [`frontend/scripts/test-no-empty-catch.mjs`](frontend/scripts/test-no-empty-catch.mjs) 在 `pnpm --dir frontend test` 中强制校验。
|
||||
|
||||
## 开源合规边界
|
||||
|
||||
|
||||
@@ -2,6 +2,30 @@
|
||||
|
||||
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
|
||||
|
||||
## v0.2.11 — 2026-12-01
|
||||
|
||||
### 新功能
|
||||
|
||||
- **Intel 虚拟机挂起与瞬间恢复**([#37](https://github.com/Nwflower/Reims-Go/pull/37)):支持在虚拟机运行中挂起保存内存与图形状态并在下次启动秒级恢复,采用事务化状态保存、异常回滚与多通道直接 I/O 优化。
|
||||
- **自定义共享文件夹与 WebDAV 路径隔离**([#38](https://github.com/Nwflower/Reims-Go/pull/38)、[#39](https://github.com/Nwflower/Reims-Go/pull/39)):Guest Tools 升级至 v8,支持按虚拟机配置自定义宿主机共享文件夹(含卷校验与设置页管理),并统一基于 `os.Root` 收紧 WebDAV 与回退文件同步的路径边界。
|
||||
- **内置并行下载器插件与可扩展下载器接口**([#24](https://github.com/Nwflower/Reims-Go/pull/24)、[#52](https://github.com/Nwflower/Reims-Go/pull/52)):离线安装包与镜像下载支持多线程分片并行加速,并开放 `downloaders` 插件扩展点。
|
||||
- **可插拔「镜像」页面与内置 macOS 镜像源**:将原安装包页升级为支持多插件镜像源切换的「镜像」页(`images.source` 扩展点),内置 macOS 镜像插件并接入品牌描边加载动画与服务可用性提示。
|
||||
- **插件 UI / 桥接契约锁定与主题能力升级(uiApi 2.0 / bridgeApi 1.0)**:冻结插件契约,新增主题插槽(slots)、全窗装饰层(layers)、布局选项(侧栏位置/模式、界面紧凑度、标题栏高度)以及图标与品牌标志覆写。
|
||||
- **虚拟机硬件、显示与交互增强**:
|
||||
- 支持按虚拟机配置 Windows 修饰键重映射及 `Win` 键映射为 macOS `Command`([#53](https://github.com/Nwflower/Reims-Go/pull/53))。
|
||||
- 支持一键轮换 OpenCore SMBIOS 硬件标识([#47](https://github.com/Nwflower/Reims-Go/pull/47))及可选同步宿主机 SMBIOS Type 17 内存规格([#44](https://github.com/Nwflower/Reims-Go/pull/44))。
|
||||
- 支持 `qcow2` `extended_l2` 磁盘性能优化、快照改写保护与 Windows Defender 排除项引导([#56](https://github.com/Nwflower/Reims-Go/pull/56))。
|
||||
- 全屏模式与客体分辨率解耦以支持 1.5x HiDPI 缩放([#22](https://github.com/Nwflower/Reims-Go/pull/22));新增关机模式选择与一键强制退出([#51](https://github.com/Nwflower/Reims-Go/pull/51))、虚拟机关闭确认弹窗及「关于」页 Discord 社区入口([#57](https://github.com/Nwflower/Reims-Go/pull/57))。
|
||||
- 支持停用内置 macOS 客体插件并按驱动隔离虚拟机生命周期路由。
|
||||
|
||||
### 优化与修复
|
||||
|
||||
- **统一插件前端组件与视觉样式**:合并已安装列表、插件市场与首次向导中的插件图标块、信任徽标、胶囊筛选按钮与搜索框(补齐语言包图标识别与 RTL 逻辑属性),将插件危险确认弹窗、表单、复选框、错误提示条与加载骨架屏收敛至全局基础组件。
|
||||
- **修复 Apple 在线恢复镜像鉴权与离线路径展开**([#34](https://github.com/Nwflower/Reims-Go/pull/34)):修复恢复镜像下载鉴权、分区 chunklist 校验及 `reims-ctl show` 主目录路径展开问题。
|
||||
- **修复剪贴板互通与文件同步可靠性**([#28](https://github.com/Nwflower/Reims-Go/pull/28)、[#33](https://github.com/Nwflower/Reims-Go/pull/33)):加固 Windows 剪贴板锁与 DIB/PNG 回声抑制,修复回退同步删除传播、Windows 驱动器挂载认证及 CLI 直接启动时保留 Guest Tools 的问题。
|
||||
- **修复 Vulkan 诊断与 GPU 驱动发现**([#21](https://github.com/Nwflower/Reims-Go/pull/21)、[#46](https://github.com/Nwflower/Reims-Go/pull/46)):清理失效的 GPU 驱动缓存文件,从活动显示驱动包中发现缺失的 Vulkan ICD 并在向导与 `doctor` 中展示探测诊断。
|
||||
- **界面性能与工程健壮性加固**([#57](https://github.com/Nwflower/Reims-Go/pull/57)):消除软件合成模式下的弹窗卡顿,修复插件状态判定、列表错误上报与休眠虚拟机停用驱动插件问题,全面禁止空 `catch` 吞错并加入静态门禁测试;运行时发布源切换至独立的 Reims vGPU / QEMU fork 通道。
|
||||
|
||||
## v0.2.10 — 2026-11-30
|
||||
|
||||
### 新功能
|
||||
|
||||
@@ -13,6 +13,32 @@ packages, `klauspost/compress`, and `ulikunitz/xz`) under permissive licenses
|
||||
(MIT, BSD, ISC, and SIL OFL 1.1); see `go.mod` and `frontend/package.json` for
|
||||
the complete dependency list.
|
||||
|
||||
### go-toml v2
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2021 - 2023 Thomas Pelletier
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## Portable runtime
|
||||
|
||||
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
|
||||
precompiled binaries built from the following upstream open-source projects.
|
||||
Each runtime release ships the matching source package, `NOTICE.md`, and
|
||||
|
||||
@@ -211,7 +211,8 @@ UI 槽位采用「声明即占有」:插件只能向宿主槽位目录(§5.1
|
||||
- 只读状态订阅:非敏感的 VM 摘要、任务进度、当前视图、外观;不提供原始路径与敏感字段。
|
||||
- 事件流:VM 状态变化(含过渡态)、任务开始/进度/结束、提示条出现、视图切换,供主题做转场动画,不必轮询状态。
|
||||
- 宿主提供的页面观察总线、帧读写管线与按部件查询:主题不自建节点观察者,也不整页查询文档。
|
||||
- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。
|
||||
- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。按 VM 重复的槽位(`nav.item.trailing`)以 VM 引用为键挂载;全窗口图层另有专用挂载;按部件查询可取回重复部件的全部实例。
|
||||
- 声明式装饰与 SDK 挂载共用同一批槽位与图层;重复槽位里的装饰按所在 VM 自身的状态匹配。
|
||||
- 受限动作:仅开放非破坏性界面动作(折叠侧栏、打开设置、前置 VM 窗口等);启停、删除、配置写入不在 SDK 中。
|
||||
- 主题设置:由 `settings` Schema 定义,宿主渲染设置页。
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "reims-go-frontend",
|
||||
"private": true,
|
||||
"version": "0.2.10",
|
||||
"version": "0.2.11",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"test": "node --test scripts/test-i18n.mjs scripts/test-macos-boundary.mjs",
|
||||
"test": "node --test scripts/test-i18n.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
|
||||
"build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
|
||||
@@ -1 +1 @@
|
||||
963b18fba33337becedb9d93549f159f
|
||||
d5f2fdb982362b7c1d77e7244b0a024f
|
||||
@@ -15,6 +15,7 @@ const srcDir = path.join(rootDir, 'src')
|
||||
const contractSrc = fs.readFileSync(path.join(srcDir, 'styles', 'ui-contract.ts'), 'utf8')
|
||||
const bridgeSrc = fs.readFileSync(path.join(srcDir, 'lib', 'bridgeContract.ts'), 'utf8')
|
||||
const tokensCss = fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
|
||||
const appCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8')
|
||||
|
||||
function extractArray(src, name) {
|
||||
const re = new RegExp(`export const ${name} = \\[([\\s\\S]*?)\\] as const`)
|
||||
@@ -33,8 +34,13 @@ const uiApi = extractVersion(contractSrc, 'UI_API_VERSION')
|
||||
const stable = {
|
||||
parts: extractArray(contractSrc, 'UI_CONTRACT_PARTS'),
|
||||
stateAttrs: extractArray(contractSrc, 'UI_CONTRACT_STATE_ATTRS'),
|
||||
itemStates: extractArray(contractSrc, 'UI_CONTRACT_ITEM_STATES'),
|
||||
slots: extractArray(contractSrc, 'UI_CONTRACT_SLOTS'),
|
||||
layers: extractArray(contractSrc, 'UI_CONTRACT_LAYERS'),
|
||||
layoutOptions: extractArray(contractSrc, 'UI_CONTRACT_LAYOUT_OPTIONS'),
|
||||
icons: extractArray(contractSrc, 'UI_CONTRACT_ICONS'),
|
||||
viewLocations: extractArray(contractSrc, 'UI_CONTRACT_VIEW_LOCATIONS'),
|
||||
sdkEvents: extractArray(contractSrc, 'UI_CONTRACT_SDK_EVENTS'),
|
||||
tokens: extractArray(contractSrc, 'UI_CONTRACT_TOKENS'),
|
||||
}
|
||||
const experimental = {
|
||||
@@ -70,6 +76,16 @@ function readSources(dir, exts) {
|
||||
}
|
||||
const allTsx = readSources(srcDir, ['.tsx'])
|
||||
const allCode = readSources(srcDir, ['.ts', '.tsx'])
|
||||
// Per-file sources, for checks that need two things in the same component.
|
||||
function sourceFiles(dir, out = []) {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) sourceFiles(full, out)
|
||||
else if (entry.name.endsWith('.tsx')) out.push(fs.readFileSync(full, 'utf8'))
|
||||
}
|
||||
return out
|
||||
}
|
||||
const tsxFiles = sourceFiles(srcDir)
|
||||
|
||||
const hasClass = (p) => new RegExp(`(?<![a-zA-Z0-9_-])${esc(p)}(?![a-zA-Z0-9_-])`).test(allTsx)
|
||||
const camel = (attr) => attr.replace(/^data-/, '').replace(/-([a-z])/g, (_, c) => c.toUpperCase())
|
||||
@@ -85,6 +101,26 @@ fail('stable state attributes never set', stable.stateAttrs.filter((a) => !hasAt
|
||||
fail('stable slots without a data-rg-slot anchor', stable.slots.filter((s) => !hasSlot(s)))
|
||||
fail('stable layers without a data-rg-layer element', stable.layers.filter((l) => !hasLayer(l)))
|
||||
fail('stable tokens missing in tokens.css', stable.tokens.filter((tk) => !tokensCss.includes(`${tk}:`)))
|
||||
// An item state counts as emitted when one component carries both the part and the attribute.
|
||||
fail('stable item states not emitted together with their part', stable.itemStates.filter((s) => {
|
||||
const [part, attr] = s.split(':')
|
||||
return !tsxFiles.some((src) => new RegExp(`(?<![a-zA-Z0-9_-])${esc(part)}(?![a-zA-Z0-9_-])`).test(src) && src.includes(`${attr}=`))
|
||||
}))
|
||||
// Layout values other than the defaults need CSS that implements them.
|
||||
const LAYOUT_ATTR = { sidebarPosition: 'data-layout-sidebar', sidebarMode: 'data-layout-sidebar-mode', density: 'data-layout-density', titlebar: 'data-layout-titlebar' }
|
||||
const LAYOUT_DEFAULTS = ['sidebarPosition=left', 'sidebarMode=full', 'density=regular', 'titlebar=standard']
|
||||
fail('stable layout options without CSS in app.css', stable.layoutOptions.filter((o) => {
|
||||
if (LAYOUT_DEFAULTS.includes(o)) return false
|
||||
const [opt, val] = o.split('=')
|
||||
return !LAYOUT_ATTR[opt] || !appCss.includes(`[${LAYOUT_ATTR[opt]}="${val}"]`)
|
||||
}))
|
||||
fail('layout options with an unknown option name', [...stable.layoutOptions, ...experimental.layoutOptions].filter((o) => !LAYOUT_ATTR[o.split('=')[0]]))
|
||||
// Every stable icon name is rendered through <HostIcon name="..."> (or the status-shape map).
|
||||
const controlsSrc = fs.readFileSync(path.join(srcDir, 'ui', 'controls.tsx'), 'utf8')
|
||||
fail('stable icon names never rendered through HostIcon', stable.icons.filter((n) =>
|
||||
!allTsx.includes(`HostIcon name="${n}"`) && !(n.startsWith('vm.state.') && controlsSrc.includes(`'${n}'`))))
|
||||
// Every stable SDK event has an emitter.
|
||||
fail('stable SDK events never emitted', stable.sdkEvents.filter((e) => !allCode.includes(`emitThemeEvent('${e}'`)))
|
||||
|
||||
fail('experimental parts already emitted (promote them to UI_CONTRACT_PARTS)', experimental.parts.filter(hasClass))
|
||||
fail('experimental slots already anchored (promote them to UI_CONTRACT_SLOTS)', experimental.slots.filter(hasSlot))
|
||||
@@ -95,11 +131,16 @@ fail('entries listed as both stable and experimental (parts)', overlap(stable.pa
|
||||
fail('entries listed as both stable and experimental (state attributes)', overlap(stable.stateAttrs, experimental.stateAttrs))
|
||||
fail('entries listed as both stable and experimental (slots)', overlap(stable.slots, experimental.slots))
|
||||
fail('entries listed as both stable and experimental (layers)', overlap(stable.layers, experimental.layers))
|
||||
fail('entries listed as both stable and experimental (item states)', overlap(stable.itemStates, experimental.itemStates))
|
||||
fail('entries listed as both stable and experimental (layout options)', overlap(stable.layoutOptions, experimental.layoutOptions))
|
||||
fail('entries listed as both stable and experimental (icons)', overlap(stable.icons, experimental.icons))
|
||||
fail('entries listed as both stable and experimental (view locations)', overlap(stable.viewLocations, experimental.viewLocations))
|
||||
fail('entries listed as both stable and experimental (SDK events)', overlap(stable.sdkEvents, experimental.sdkEvents))
|
||||
fail('bridge methods listed as both stable and experimental', overlap(bridge.methods, bridge.experimentalMethods))
|
||||
fail('bridge events listed as both stable and experimental', overlap(bridge.events, bridge.experimentalEvents))
|
||||
|
||||
const knownParts = [...stable.parts, ...experimental.parts]
|
||||
fail('item states on unknown parts', experimental.itemStates.filter((s) => !knownParts.includes(s.split(':')[0])))
|
||||
fail('item states on unknown parts', [...stable.itemStates, ...experimental.itemStates].filter((s) => !knownParts.includes(s.split(':')[0])))
|
||||
for (const [name, list] of Object.entries({ ...stable, ...experimental, ...bridge })) {
|
||||
const dupes = list.filter((x, i) => list.indexOf(x) !== i)
|
||||
fail(`duplicate entries in ${name}`, dupes)
|
||||
@@ -125,6 +166,7 @@ write('bridge-contract.json', {
|
||||
})
|
||||
console.log(
|
||||
`[ui-contract] OK (uiApi=${uiApi}, parts=${stable.parts.length}+${experimental.parts.length}x, ` +
|
||||
`tokens=${stable.tokens.length}, slots=${stable.slots.length}+${experimental.slots.length}x, ` +
|
||||
`tokens=${stable.tokens.length}, slots=${stable.slots.length}+${experimental.slots.length}x, layers=${stable.layers.length}, ` +
|
||||
`icons=${stable.icons.length}, sdkEvents=${stable.sdkEvents.length}, ` +
|
||||
`bridgeApi=${bridgeApi}, methods=${bridge.methods.length}+${bridge.experimentalMethods.length}x)`,
|
||||
)
|
||||
@@ -67,9 +67,11 @@ test('Static Guard (CRITICAL-1): lazy i18n domain keys are always backed by doma
|
||||
'Setup.tsx',
|
||||
'RuntimeOnline.tsx',
|
||||
'HostView.tsx',
|
||||
'ImagesPage.tsx',
|
||||
'InstallersPage.tsx',
|
||||
'PluginsPage.tsx',
|
||||
'PluginMarket.tsx',
|
||||
'PluginParts.tsx',
|
||||
'AppSettingsPage.tsx',
|
||||
'AboutPage.tsx',
|
||||
'PluginPanelFrame.tsx',
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
// Guards the AGENTS.md rule forbidding empty catch blocks that silently turn
|
||||
// failures into successes. Covers JS/TS/JSX/TSX/MJS/CJS via the TypeScript AST
|
||||
// and PowerShell (.ps1/.psm1/.psd1) via a comment- and string-aware lexer.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import ts from 'typescript'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const repoRoot = path.resolve(__dirname, '..', '..')
|
||||
|
||||
const JS_TS_EXTS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'])
|
||||
const PS_EXTS = new Set(['.ps1', '.psm1', '.psd1'])
|
||||
const SKIP_DIRS = new Set(['.git', '.debug', 'node_modules', 'dist', 'build', 'wailsjs'])
|
||||
|
||||
function scriptKindFor(filePath) {
|
||||
switch (path.extname(filePath).toLowerCase()) {
|
||||
case '.tsx': return ts.ScriptKind.TSX
|
||||
case '.ts':
|
||||
case '.mts':
|
||||
case '.cts': return ts.ScriptKind.TS
|
||||
case '.jsx': return ts.ScriptKind.JSX
|
||||
default: return ts.ScriptKind.JS
|
||||
}
|
||||
}
|
||||
|
||||
function isEmptyBlock(block) {
|
||||
return ts.isBlock(block) && block.statements.every((stmt) => ts.isEmptyStatement(stmt))
|
||||
}
|
||||
|
||||
function isEmptyFunctionBody(expr) {
|
||||
let current = expr
|
||||
while (ts.isParenthesizedExpression(current)) current = current.expression
|
||||
if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) {
|
||||
return isEmptyBlock(current.body)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function getCalleeMethodName(callee) {
|
||||
if (ts.isPropertyAccessExpression(callee)) return callee.name.text
|
||||
if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
|
||||
return callee.argumentExpression.text
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds empty `catch` clauses and empty Promise `.catch(...)` / `.then(_, ...)`
|
||||
* rejection callbacks in a JS/TS source string using the TypeScript AST.
|
||||
*/
|
||||
export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') {
|
||||
const sf = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true, scriptKindFor(filePath))
|
||||
const findings = []
|
||||
|
||||
const record = (node, kind) => {
|
||||
const pos = sf.getLineAndCharacterOfPosition(node.getStart(sf))
|
||||
findings.push({
|
||||
file: filePath,
|
||||
line: pos.line + 1,
|
||||
column: pos.character + 1,
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
function visit(node) {
|
||||
if (ts.isCatchClause(node) && isEmptyBlock(node.block)) {
|
||||
record(node, 'empty-catch-clause')
|
||||
} else if (ts.isCallExpression(node)) {
|
||||
const method = getCalleeMethodName(node.expression)
|
||||
if (method === 'catch' && node.arguments.length >= 1 && isEmptyFunctionBody(node.arguments[0])) {
|
||||
record(node.arguments[0], 'empty-promise-catch')
|
||||
} else if (method === 'then' && node.arguments.length >= 2 && isEmptyFunctionBody(node.arguments[1])) {
|
||||
record(node.arguments[1], 'empty-promise-then-reject')
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
|
||||
visit(sf)
|
||||
return findings
|
||||
}
|
||||
|
||||
function tokenizePowerShell(sourceText) {
|
||||
const tokens = []
|
||||
let i = 0
|
||||
let line = 1
|
||||
let col = 1
|
||||
const len = sourceText.length
|
||||
|
||||
const advance = () => {
|
||||
const ch = sourceText[i++]
|
||||
if (ch === '\n') {
|
||||
line += 1
|
||||
col = 1
|
||||
} else {
|
||||
col += 1
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
const atHereStringEnd = (quote) => {
|
||||
if (sourceText[i] !== quote || sourceText[i + 1] !== '@') return false
|
||||
return i === 0 || sourceText[i - 1] === '\n'
|
||||
}
|
||||
|
||||
while (i < len) {
|
||||
const ch = sourceText[i]
|
||||
const next = sourceText[i + 1]
|
||||
|
||||
// Whitespace
|
||||
if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
|
||||
advance()
|
||||
continue
|
||||
}
|
||||
|
||||
// Block comment <# ... #>
|
||||
if (ch === '<' && next === '#') {
|
||||
advance()
|
||||
advance()
|
||||
while (i < len && !(sourceText[i] === '#' && sourceText[i + 1] === '>')) advance()
|
||||
if (i < len) {
|
||||
advance()
|
||||
advance()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Line comment # ...
|
||||
if (ch === '#') {
|
||||
while (i < len && sourceText[i] !== '\n') advance()
|
||||
continue
|
||||
}
|
||||
|
||||
// Here-strings @' ... '@ and @" ... "@
|
||||
if (ch === '@' && (next === "'" || next === '"')) {
|
||||
const quote = next
|
||||
let look = i + 2
|
||||
while (look < len && (sourceText[look] === ' ' || sourceText[look] === '\t' || sourceText[look] === '\r')) look++
|
||||
if (look < len && sourceText[look] === '\n') {
|
||||
const startLine = line
|
||||
const startCol = col
|
||||
while (i <= look) advance()
|
||||
while (i < len && !atHereStringEnd(quote)) advance()
|
||||
if (i < len) {
|
||||
advance()
|
||||
advance()
|
||||
}
|
||||
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Single-quoted string ('' escapes ')
|
||||
if (ch === "'") {
|
||||
const startLine = line
|
||||
const startCol = col
|
||||
advance()
|
||||
while (i < len) {
|
||||
if (sourceText[i] === "'") {
|
||||
advance()
|
||||
if (sourceText[i] === "'") {
|
||||
advance()
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
advance()
|
||||
}
|
||||
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Double-quoted string (` escapes next char, "" escapes ")
|
||||
if (ch === '"') {
|
||||
const startLine = line
|
||||
const startCol = col
|
||||
advance()
|
||||
while (i < len) {
|
||||
if (sourceText[i] === '`') {
|
||||
advance()
|
||||
if (i < len) advance()
|
||||
continue
|
||||
}
|
||||
if (sourceText[i] === '"') {
|
||||
advance()
|
||||
if (sourceText[i] === '"') {
|
||||
advance()
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
advance()
|
||||
}
|
||||
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Backtick escape outside strings
|
||||
if (ch === '`') {
|
||||
advance()
|
||||
if (i < len) advance()
|
||||
continue
|
||||
}
|
||||
|
||||
const startLine = line
|
||||
const startCol = col
|
||||
|
||||
// :: operator
|
||||
if (ch === ':' && next === ':') {
|
||||
advance()
|
||||
advance()
|
||||
tokens.push({ type: 'punct', value: '::', line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Punctuation relevant to catch syntax
|
||||
if ('{}[];,.'.includes(ch)) {
|
||||
advance()
|
||||
tokens.push({ type: 'punct', value: ch, line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Word / identifier / parameter (e.g. -catch, catch)
|
||||
if (/[A-Za-z_-]/.test(ch)) {
|
||||
let word = ''
|
||||
while (i < len && /[A-Za-z0-9_-]/.test(sourceText[i])) word += advance()
|
||||
tokens.push({ type: 'word', value: word, line: startLine, column: startCol })
|
||||
continue
|
||||
}
|
||||
|
||||
// Any other token
|
||||
advance()
|
||||
tokens.push({ type: 'other', value: ch, line: startLine, column: startCol })
|
||||
}
|
||||
|
||||
return tokens
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds empty `catch` blocks (including comment-only and semicolon-only blocks,
|
||||
* with or without `[Type]` exception filters) in a PowerShell script.
|
||||
*/
|
||||
export function findEmptyCatchesInPowerShell(sourceText, filePath = 'sample.ps1') {
|
||||
const tokens = tokenizePowerShell(sourceText)
|
||||
const findings = []
|
||||
|
||||
for (let idx = 0; idx < tokens.length; idx++) {
|
||||
const tok = tokens[idx]
|
||||
if (tok.type !== 'word' || tok.value.toLowerCase() !== 'catch') continue
|
||||
const prev = tokens[idx - 1]
|
||||
if (prev && (prev.value === '.' || prev.value === '::')) continue
|
||||
|
||||
// Skip optional comma-separated type filters: catch [TypeA], [TypeB] { ... }
|
||||
let cursor = idx + 1
|
||||
while (cursor < tokens.length && tokens[cursor].value === '[') {
|
||||
let depth = 0
|
||||
while (cursor < tokens.length) {
|
||||
if (tokens[cursor].value === '[') depth++
|
||||
else if (tokens[cursor].value === ']') {
|
||||
depth--
|
||||
if (depth === 0) {
|
||||
cursor++
|
||||
break
|
||||
}
|
||||
}
|
||||
cursor++
|
||||
}
|
||||
if (cursor < tokens.length && tokens[cursor].value === ',') cursor++
|
||||
else break
|
||||
}
|
||||
|
||||
if (cursor >= tokens.length || tokens[cursor].value !== '{') continue
|
||||
|
||||
// Scan block body until matching '}'
|
||||
let bodyCursor = cursor + 1
|
||||
let empty = true
|
||||
while (bodyCursor < tokens.length && tokens[bodyCursor].value !== '}') {
|
||||
if (tokens[bodyCursor].value !== ';') {
|
||||
empty = false
|
||||
break
|
||||
}
|
||||
bodyCursor++
|
||||
}
|
||||
if (empty && bodyCursor < tokens.length && tokens[bodyCursor].value === '}') {
|
||||
findings.push({
|
||||
file: filePath,
|
||||
line: tok.line,
|
||||
column: tok.column,
|
||||
kind: 'empty-ps-catch',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return findings
|
||||
}
|
||||
|
||||
function walkFiles(dir, out = []) {
|
||||
if (!fs.existsSync(dir)) return out
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) walkFiles(full, out)
|
||||
else out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
test('detector self-test: catches all empty JS/TS catch forms and allows handled catches', () => {
|
||||
const bad = [
|
||||
'try { a() } catch {}',
|
||||
'try { a() } catch (e) {}',
|
||||
'try { a() } catch { /* comment only */ }',
|
||||
'try { a() } catch (e) {\n // comment only\n}',
|
||||
'try { a() } catch { ; ; }',
|
||||
'p.catch(() => {})',
|
||||
'p?.catch((e) => { /* noop */ })',
|
||||
'p["catch"](function () {})',
|
||||
'p.catch(async () => { ; })',
|
||||
'p.then(ok, () => {})',
|
||||
'p.then(ok, (err) => { // noop\n})',
|
||||
].join('\n')
|
||||
|
||||
const badFindings = findEmptyCatchesInJS(bad, 'bad.ts')
|
||||
assert.equal(badFindings.length, 11, `expected 11 findings, got ${JSON.stringify(badFindings)}`)
|
||||
|
||||
const good = [
|
||||
'const text = "try { a() } catch {} .catch(() => {})"',
|
||||
'// try { a() } catch {}',
|
||||
'try { a() } catch (e) { console.warn(e) }',
|
||||
'try { a() } catch { return fallback }',
|
||||
'p.catch((e) => console.warn(e))',
|
||||
'p.catch(() => null)',
|
||||
'p.then(ok, (e) => handle(e))',
|
||||
].join('\n')
|
||||
|
||||
assert.deepEqual(findEmptyCatchesInJS(good, 'good.ts'), [])
|
||||
})
|
||||
|
||||
test('detector self-test: catches empty PowerShell catch blocks and ignores strings/comments', () => {
|
||||
const bad = [
|
||||
'try { foo } catch {}',
|
||||
'try { foo } Catch { # comment only\n}',
|
||||
'try { foo } catch { <# block comment #> ; }',
|
||||
'try { foo } catch [System.IO.IOException], [System.Exception] {}',
|
||||
].join('\n')
|
||||
|
||||
const badFindings = findEmptyCatchesInPowerShell(bad, 'bad.ps1')
|
||||
assert.equal(badFindings.length, 4, `expected 4 findings, got ${JSON.stringify(badFindings)}`)
|
||||
|
||||
const good = [
|
||||
'# try { foo } catch {}',
|
||||
'<# try { foo } catch {} #>',
|
||||
'$s1 = "try { foo } catch {}"',
|
||||
"$s2 = 'try { foo } catch {}'",
|
||||
'$here = @"\ntry { foo } catch {}\n"@',
|
||||
'$obj.catch { }',
|
||||
'try { foo } catch { Write-Warning $_ }',
|
||||
'try { foo } catch [System.Exception] { throw }',
|
||||
].join('\n')
|
||||
|
||||
assert.deepEqual(findEmptyCatchesInPowerShell(good, 'good.ps1'), [])
|
||||
})
|
||||
|
||||
test('repository has zero empty catch blocks across frontend/ and scripts/', () => {
|
||||
const roots = [path.join(repoRoot, 'frontend'), path.join(repoRoot, 'scripts')]
|
||||
const violations = []
|
||||
let scannedJS = 0
|
||||
let scannedPS = 0
|
||||
|
||||
for (const root of roots) {
|
||||
for (const file of walkFiles(root)) {
|
||||
const ext = path.extname(file).toLowerCase()
|
||||
const rel = path.relative(repoRoot, file).split(path.sep).join('/')
|
||||
if (JS_TS_EXTS.has(ext)) {
|
||||
scannedJS += 1
|
||||
const text = fs.readFileSync(file, 'utf8')
|
||||
violations.push(...findEmptyCatchesInJS(text, rel))
|
||||
} else if (PS_EXTS.has(ext)) {
|
||||
scannedPS += 1
|
||||
const text = fs.readFileSync(file, 'utf8')
|
||||
violations.push(...findEmptyCatchesInPowerShell(text, rel))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert.ok(scannedJS > 0, 'expected to scan at least one JS/TS file')
|
||||
assert.ok(scannedPS > 0, 'expected to scan at least one PowerShell file')
|
||||
assert.deepEqual(
|
||||
violations.map((v) => `${v.file}:${v.line}:${v.column} (${v.kind})`),
|
||||
[],
|
||||
`Empty catch blocks found (forbidden by AGENTS.md):\n${violations.map((v) => ` - ${v.file}:${v.line}:${v.column} (${v.kind})`).join('\n')}`,
|
||||
)
|
||||
})
|
||||
+89
-23
@@ -17,13 +17,14 @@ import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './
|
||||
import { LogLine, appendLog } from './lib/logs'
|
||||
import { macOSMajor } from './macos/macosRelease'
|
||||
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
|
||||
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
|
||||
import { vmRefKey } from './lib/vmRef'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
|
||||
import { Button, Tip, TooltipProvider } from './ui/controls'
|
||||
import { ConfirmDialog, Modal } from './ui/dialog'
|
||||
import { Toaster, useToasts } from './ui/toast'
|
||||
import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals'
|
||||
import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails'
|
||||
|
||||
// Opened on demand, so each is its own chunk and stays out of the startup
|
||||
@@ -34,6 +35,7 @@ const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) =
|
||||
const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog })))
|
||||
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
|
||||
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
|
||||
const 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 AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
|
||||
@@ -77,7 +79,7 @@ export const App: React.FC = () => {
|
||||
const stateReady = !!state
|
||||
useEffect(() => {
|
||||
if (!stateReady) return
|
||||
const check = () => { api.CheckAppUpdate(false).then(setAppUpdate).catch(() => {}) }
|
||||
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)
|
||||
@@ -103,7 +105,9 @@ export const App: React.FC = () => {
|
||||
try {
|
||||
const saved = localStorage.getItem('reims-go-theme')
|
||||
if (saved === 'dark' || saved === 'light') return saved
|
||||
} catch {}
|
||||
} catch (e) {
|
||||
console.warn('[app] read theme preference failed:', e)
|
||||
}
|
||||
return 'system'
|
||||
})
|
||||
const [sysDark, setSysDark] = useState<boolean>(() =>
|
||||
@@ -160,7 +164,9 @@ export const App: React.FC = () => {
|
||||
try {
|
||||
if (mode === 'system') localStorage.removeItem('reims-go-theme')
|
||||
else localStorage.setItem('reims-go-theme', mode)
|
||||
} catch {}
|
||||
} catch (e) {
|
||||
console.warn('[app] persist theme preference failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleTheme = () => {
|
||||
@@ -173,7 +179,7 @@ export const App: React.FC = () => {
|
||||
try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true }
|
||||
})
|
||||
const toggleSidebar = () => setSidebarOpen((open) => {
|
||||
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch {}
|
||||
try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch (e) { console.warn('[app] persist sidebar state failed:', e) }
|
||||
return !open
|
||||
})
|
||||
|
||||
@@ -236,11 +242,11 @@ export const App: React.FC = () => {
|
||||
}
|
||||
setLogLines((prev) => appendLog(prev, entry))
|
||||
})
|
||||
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
|
||||
api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
|
||||
// Tasks: seed from the backend, then follow events.
|
||||
api.GetTasks().then((list) => {
|
||||
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
|
||||
}).catch(() => {})
|
||||
}).catch((e) => console.warn('[app] GetTasks failed:', e))
|
||||
const offTask = events.onTask((task) => onTaskRef.current(task))
|
||||
const onVisibility = () => {
|
||||
if (!document.hidden) {
|
||||
@@ -288,7 +294,7 @@ export const App: React.FC = () => {
|
||||
for (const vm of vms) {
|
||||
api.GetVMNote(vm.name)
|
||||
.then((n) => { if (live) setDisplayNames((m) => ({ ...m, [vm.name]: (n ?? '').trim() })) })
|
||||
.catch(() => {})
|
||||
.catch((e) => console.warn('[app] GetVMNote failed:', vm.name, e))
|
||||
}
|
||||
return () => { live = false }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -302,7 +308,7 @@ export const App: React.FC = () => {
|
||||
for (const vm of vms) {
|
||||
api.GetVMMacOS(vm.name)
|
||||
.then((r) => { if (live) setReleases((m) => ({ ...m, [vm.name]: (r ?? '').trim() })) })
|
||||
.catch(() => {})
|
||||
.catch((e) => console.warn('[app] GetVMMacOS failed:', vm.name, e))
|
||||
}
|
||||
return () => { live = false }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -381,7 +387,7 @@ export const App: React.FC = () => {
|
||||
const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => {
|
||||
await api.SetAppUpdateChannel(ch)
|
||||
setDismissedUpdate('')
|
||||
try { localStorage.removeItem('reims-go-update-dismissed') } catch {}
|
||||
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))
|
||||
@@ -410,7 +416,7 @@ export const App: React.FC = () => {
|
||||
const dismissUpdate = () => {
|
||||
if (!appUpdate) return
|
||||
setDismissedUpdate(appUpdate.latest)
|
||||
try { localStorage.setItem('reims-go-update-dismissed', appUpdate.latest) } catch {}
|
||||
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)
|
||||
@@ -435,7 +441,9 @@ export const App: React.FC = () => {
|
||||
const last = localStorage.getItem('reims-go-last-version')
|
||||
if (last && last !== v) toasts.push({ kind: 'ok', title: tr('updateDoneToast', { v }) })
|
||||
localStorage.setItem('reims-go-last-version', v)
|
||||
} catch {}
|
||||
} catch (e) {
|
||||
console.warn('[app] track last app version failed:', e)
|
||||
}
|
||||
}, [state?.app_version, pluginUI !== null])
|
||||
const importRuntime = async () => {
|
||||
try {
|
||||
@@ -500,10 +508,46 @@ export const App: React.FC = () => {
|
||||
notifyInteractiveThemeState(uiStateRef.current)
|
||||
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme])
|
||||
|
||||
// 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]) {
|
||||
emitThemeEvent('vm.stateChanged', { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] })
|
||||
}
|
||||
}
|
||||
}, [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])
|
||||
|
||||
// Apply active theme pack (zero extra CSS for builtin default theme, §5.1 & §8.1).
|
||||
useEffect(() => {
|
||||
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
|
||||
api.GetPluginUIContributions().then(setPluginUI).catch(() => {})
|
||||
api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
|
||||
api.GetPluginUIContributions().then(setPluginUI).catch((e) => console.warn('[app] GetPluginUIContributions failed:', e))
|
||||
}, [themeRevision, state?.safe_mode])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -514,7 +558,7 @@ export const App: React.FC = () => {
|
||||
{
|
||||
toggleSidebar,
|
||||
openSettings: () => setSelected(SETTINGS_ID),
|
||||
focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch(() => {}) },
|
||||
focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch((e) => console.warn('[theme] FocusVMWindow failed:', vmName, e)) },
|
||||
},
|
||||
)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -982,12 +1026,14 @@ export const App: React.FC = () => {
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<ThemeVisualsProvider payload={activeThemePayload}>
|
||||
<TooltipProvider>
|
||||
<div className="app-shell rg-p-shell">
|
||||
<div className="rg-layer rg-layer-background" data-rg-layer="layer.background" aria-hidden="true" />
|
||||
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
|
||||
{showSetup || showReadOnly || !state ? (
|
||||
<div className="brand rg-p-brand">
|
||||
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
<BrandMark className="brand-mark" />
|
||||
Reims-Go
|
||||
</div>
|
||||
) : (
|
||||
@@ -1018,6 +1064,7 @@ export const App: React.FC = () => {
|
||||
appVersion={state.app_version}
|
||||
/>
|
||||
)}
|
||||
<div className="rg-slot-anchor titlebar-center" data-rg-slot="titlebar.center" />
|
||||
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
|
||||
{canLight && canDark && (
|
||||
<Tip label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}>
|
||||
@@ -1117,19 +1164,34 @@ export const App: React.FC = () => {
|
||||
|
||||
<main className="main rg-p-main">
|
||||
<div className="scroll">
|
||||
{state?.vm_list_error && <div className="notice notice-error" role="alert">{state.vm_list_error}</div>}
|
||||
<Suspense fallback={null}>
|
||||
{!state ? (
|
||||
<div className="page">
|
||||
{loadError ? <div className="notice notice-error">{loadError}</div> : <span className="muted">…</span>}
|
||||
</div>
|
||||
) : selected === INSTALLERS_ID ? (
|
||||
<InstallersPage
|
||||
<ImagesPage
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
tasks={Object.values(taskMap)}
|
||||
onCreateWithInstaller={openWizardWithInstaller}
|
||||
onError={fail}
|
||||
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
||||
appearance={theme}
|
||||
pluginUI={pluginUI}
|
||||
onOpenPlugins={() => setSelected(PLUGINS_ID)}
|
||||
renderNativeSource={(nativeId, opts) => (
|
||||
nativeId === 'macos' ? (
|
||||
<Suspense fallback={null}>
|
||||
<InstallersPage
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
tasks={Object.values(taskMap)}
|
||||
refreshSignal={opts.refreshSignal}
|
||||
onBusyChange={opts.onBusyChange}
|
||||
onCreateWithInstaller={openWizardWithInstaller}
|
||||
onError={fail}
|
||||
onToast={(title) => toasts.push({ kind: 'ok', title })}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null
|
||||
)}
|
||||
/>
|
||||
) : selected === PLUGINS_ID ? (
|
||||
<PluginsPage
|
||||
@@ -1405,8 +1467,12 @@ export const App: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
|
||||
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} dir={dir} />
|
||||
<div className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
|
||||
</div>
|
||||
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */}
|
||||
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} dir={dir} />
|
||||
<ThemeDecorations payload={activeThemePayload} snap={uiStateRef.current} locale={locale} />
|
||||
</TooltipProvider>
|
||||
</ThemeVisualsProvider>
|
||||
)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Segmented } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { REPO_URL } from './TitleMenus'
|
||||
import type { UpdatePhase } from './UpdateCapsule'
|
||||
import { BrandMark } from '../ui/themeVisuals'
|
||||
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
|
||||
const QQ_GROUP_ID = '1136042744'
|
||||
@@ -152,7 +153,7 @@ export const AboutPage: React.FC<Props> = ({
|
||||
updateSub = (
|
||||
<>
|
||||
<div className="row-sub">{tr('updateDownloadingSub', { v: appUpdate?.latest ?? '' })}{updateTask && taskDetail(updateTask) ? ` · ${taskDetail(updateTask)}` : ''}</div>
|
||||
<span className="progress about-update-progress" aria-hidden="true">
|
||||
<span className="progress rg-p-progress about-update-progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${(pct ?? 0) / 100})` }} />
|
||||
</span>
|
||||
</>
|
||||
@@ -183,7 +184,7 @@ export const AboutPage: React.FC<Props> = ({
|
||||
return (
|
||||
<div className="page about-page">
|
||||
<header className="about-hero">
|
||||
<img className="about-hero-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
<BrandMark className="about-hero-mark" />
|
||||
<div className="about-hero-text">
|
||||
<h1>Reims-Go</h1>
|
||||
<p>{tr('aboutTagline')}</p>
|
||||
@@ -197,7 +198,7 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row-title">
|
||||
{tr('appVersionTitle')} <span className="mono">{version}</span>
|
||||
{appUpdate && !appUpdate.has_update && (
|
||||
<span className="badge badge-ok">{tr('appUpToDate')}</span>
|
||||
<span className="badge rg-p-badge badge-ok">{tr('appUpToDate')}</span>
|
||||
)}
|
||||
</div>
|
||||
{updateSub}
|
||||
@@ -301,7 +302,7 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row-title">
|
||||
{tr('aboutQQGroup')} <span className="mono">{QQ_GROUP_ID}</span>
|
||||
{qqInstalled === false && (
|
||||
<span className="badge">{tr('aboutQQNotInstalled')}</span>
|
||||
<span className="badge rg-p-badge">{tr('aboutQQNotInstalled')}</span>
|
||||
)}
|
||||
</div>
|
||||
{qqInstalled === false ? (
|
||||
|
||||
@@ -78,7 +78,7 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('autoPinPCores')}
|
||||
<span className={`badge ${optBadgeClass(pcoreOpt?.status)}`}>
|
||||
<span className={`badge rg-p-badge ${optBadgeClass(pcoreOpt?.status)}`}>
|
||||
{optStatusLabel(locale, pcoreOpt?.status)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -18,7 +18,7 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{t(locale, 'cloneTitle', { name: sourceName })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
@@ -28,7 +28,7 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
|
||||
<label className="field-label" htmlFor="clone-name">{t(locale, 'cloneNameLabel')}</label>
|
||||
<input
|
||||
id="clone-name"
|
||||
className="input mono"
|
||||
className="input rg-p-input mono"
|
||||
value={cloneName}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
@@ -40,10 +40,10 @@ export const CloneDialog: React.FC<Props> = ({ locale, sourceName, defaultCloneN
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
<button type="button" className="btn rg-p-button">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" disabled={!trimmed} onClick={() => onConfirm(trimmed)}>
|
||||
<button type="button" className="btn rg-p-button btn-primary" disabled={!trimmed} onClick={() => onConfirm(trimmed)}>
|
||||
{t(locale, 'cloneConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
|
||||
@@ -98,7 +98,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch(() => {})
|
||||
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e))
|
||||
return () => { live = false }
|
||||
}, [])
|
||||
const activeDriver = drivers.find((d) => d.id === driverID)
|
||||
@@ -183,7 +183,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
|
||||
useEffect(() => {
|
||||
if (opts.source_mode !== 'offline' || releases) return
|
||||
let live = true
|
||||
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch(() => {})
|
||||
api.ListInstallers().then((l) => { if (live) setCached(l ?? []) }).catch((e) => console.warn('[wizard] ListInstallers failed:', e))
|
||||
api.ListOfflineReleases()
|
||||
.then((list) => {
|
||||
if (!live) return
|
||||
@@ -299,7 +299,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
|
||||
<SetGroup title={tr('wizardBasics')}>
|
||||
<SetRow
|
||||
title={tr('vmName')}
|
||||
control={<input className="input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
|
||||
control={<input className="input rg-p-input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
{activeDriver.create_schema && (
|
||||
@@ -334,13 +334,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
|
||||
<span className={`source-icon source-icon-${s.mode}`} aria-hidden="true"><Icon size={20} /></span>
|
||||
<span className="source-title">
|
||||
{tr(s.title)}
|
||||
{s.mode === 'offline' && <span className="badge badge-accent">{tr('recommendedBadge')}</span>}
|
||||
{s.mode === 'offline' && <span className="badge rg-p-badge badge-accent">{tr('recommendedBadge')}</span>}
|
||||
</span>
|
||||
<span className="source-sub">{tr(s.sub)}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="rg-slot-anchor" data-rg-slot="create.source" />
|
||||
|
||||
<SetGroup>
|
||||
{opts.source_mode === 'apple' && (
|
||||
@@ -832,7 +833,10 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
|
||||
await navigator.clipboard.writeText(command)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1500)
|
||||
} catch { /* clipboard unavailable; the text stays selectable */ }
|
||||
} catch (e) {
|
||||
// clipboard unavailable; the text stays selectable
|
||||
console.warn('[wizard] clipboard write failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -841,7 +845,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
|
||||
<SetRow
|
||||
title={tr('vmName')}
|
||||
error={nameIssue}
|
||||
control={<input className="input name-input" aria-label={tr('vmName')} value={opts.name} onChange={(e) => onName(e.target.value)} spellCheck={false} />}
|
||||
control={<input className="input rg-p-input name-input" aria-label={tr('vmName')} value={opts.name} onChange={(e) => onName(e.target.value)} spellCheck={false} />}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('vmDir')}
|
||||
|
||||
@@ -44,7 +44,7 @@ export class ErrorBoundary extends React.Component<{ children: React.ReactNode }
|
||||
<div className="error-boundary-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
className="btn rg-p-button btn-primary"
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
{t(loc, 'errorBoundaryReload')}
|
||||
|
||||
@@ -33,7 +33,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
api.GetStorageBreakdown().then((s) => { if (live) setStorage(s) }).catch(() => {})
|
||||
api.GetStorageBreakdown().then((s) => { if (live) setStorage(s) }).catch((e) => console.warn('[host] GetStorageBreakdown failed:', e))
|
||||
return () => { live = false }
|
||||
}, [state.config.data_root, state.vms?.length, state.runtimes?.length])
|
||||
|
||||
@@ -157,7 +157,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
const instPct = (storage.installers_bytes / tot) * 100
|
||||
const rtPct = (storage.runtimes_bytes / tot) * 100
|
||||
return (
|
||||
<section className="card">
|
||||
<section className="card rg-p-card">
|
||||
<div className="card-title">
|
||||
<span>{tr('storageBreakdownTitle')}</span>
|
||||
<span className="spacer" />
|
||||
@@ -253,10 +253,10 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
<div className="row-main">
|
||||
<div className="row-title" title={g.vulkan_icd}>
|
||||
{g.name}
|
||||
<span className={`badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
|
||||
{g.compat === 'unsupported' && <span className="badge badge-warn">{tr('gpuCompatUnsupported')}</span>}
|
||||
{g.compat === 'warn' && <span className="badge badge-warn">{tr('gpuCompatWarn')}</span>}
|
||||
{isRec && g.compat !== 'warn' && g.compat !== 'unsupported' && <span className="badge badge-ok">{tr('gpuRecommended')}</span>}
|
||||
<span className={`badge rg-p-badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
|
||||
{g.compat === 'unsupported' && <span className="badge rg-p-badge badge-warn">{tr('gpuCompatUnsupported')}</span>}
|
||||
{g.compat === 'warn' && <span className="badge rg-p-badge badge-warn">{tr('gpuCompatWarn')}</span>}
|
||||
{isRec && g.compat !== 'warn' && g.compat !== 'unsupported' && <span className="badge rg-p-badge badge-ok">{tr('gpuRecommended')}</span>}
|
||||
</div>
|
||||
{meta && <div className="row-sub">{meta}</div>}
|
||||
{hint && <div className="row-sub warn-text">{hint}</div>}
|
||||
@@ -277,8 +277,8 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
<div className="row-title">
|
||||
{d.width} × {d.height}
|
||||
{d.refresh_hz ? ` @ ${d.refresh_hz}Hz` : ''}
|
||||
<span className="badge">{d.scale_pct || 100}%</span>
|
||||
{d.primary && <span className="badge badge-ok">{tr('hostDisplayPrimary')}</span>}
|
||||
<span className="badge rg-p-badge">{d.scale_pct || 100}%</span>
|
||||
{d.primary && <span className="badge rg-p-badge badge-ok">{tr('hostDisplayPrimary')}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
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 { 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 {
|
||||
refreshSignal: number
|
||||
onBusyChange: (busy: boolean) => void
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
appearance: 'light' | 'dark'
|
||||
pluginUI: PluginUIContributions | null
|
||||
renderNativeSource?: (nativeId: string, opts: NativeImageSourceRenderOpts) => React.ReactNode
|
||||
onOpenPlugins: () => void
|
||||
}
|
||||
|
||||
function sourceKey(src: ImageSourceContribution): string {
|
||||
return `${src.pluginId ?? ''}:${src.id}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level Images page: hosts plugin-registered image source tabs via a top
|
||||
* Segmented control. Built-in plugins (such as macOS Images) mount native host
|
||||
* views; external plugins render in a sandboxed L4 iframe.
|
||||
*/
|
||||
export const ImagesPage: React.FC<Props> = ({
|
||||
locale,
|
||||
appearance,
|
||||
pluginUI,
|
||||
renderNativeSource,
|
||||
onOpenPlugins,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const sources = useMemo(() => pluginUI?.image_sources ?? [], [pluginUI?.image_sources])
|
||||
const [selectedKey, setSelectedKey] = useState('')
|
||||
const [refreshSignals, setRefreshSignals] = useState<Record<string, number>>({})
|
||||
const [busyByKey, setBusyByKey] = useState<Record<string, boolean>>({})
|
||||
|
||||
const activeSource = useMemo(() => {
|
||||
if (sources.length === 0) return null
|
||||
return sources.find((s) => sourceKey(s) === selectedKey) ?? sources[0]
|
||||
}, [sources, selectedKey])
|
||||
|
||||
const activeKey = activeSource ? sourceKey(activeSource) : ''
|
||||
|
||||
useEffect(() => {
|
||||
if (activeKey && activeKey !== selectedKey) {
|
||||
setSelectedKey(activeKey)
|
||||
}
|
||||
}, [activeKey, selectedKey])
|
||||
|
||||
const activeBusy = activeKey ? !!busyByKey[activeKey] : false
|
||||
|
||||
const handleActiveBusyChange = useCallback((busy: boolean) => {
|
||||
if (!activeKey) return
|
||||
setBusyByKey((prev) => (prev[activeKey] === busy ? prev : { ...prev, [activeKey]: busy }))
|
||||
}, [activeKey])
|
||||
|
||||
const triggerRefresh = () => {
|
||||
if (!activeKey) return
|
||||
setRefreshSignals((prev) => ({ ...prev, [activeKey]: (prev[activeKey] ?? 0) + 1 }))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page installers-page">
|
||||
<header className="page-head">
|
||||
<div className="page-title installers-page-title">
|
||||
<h1>{tr('installersTitle')}</h1>
|
||||
<span>{tr('installersHint')}</span>
|
||||
</div>
|
||||
{activeSource && (
|
||||
<div className="actions">
|
||||
<IconButton
|
||||
label={tr('refresh')}
|
||||
icon={<RefreshCw size={16} className={activeBusy ? 'spin' : undefined} />}
|
||||
disabled={activeBusy}
|
||||
onClick={triggerRefresh}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
|
||||
{sources.length > 0 && (
|
||||
<div className="images-switch">
|
||||
<Segmented
|
||||
label={tr('imagesSourcesLabel')}
|
||||
value={activeKey}
|
||||
onChange={setSelectedKey}
|
||||
options={sources.map((src) => ({
|
||||
value: sourceKey(src),
|
||||
label: locText(src.title, locale, src.id),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pluginUI === null ? (
|
||||
<WordmarkLoader className="installers-loader" />
|
||||
) : !activeSource ? (
|
||||
<div className="empty-panel images-empty">
|
||||
<Disc3 size={28} aria-hidden="true" />
|
||||
<div className="images-empty-title">{tr('imagesNoSourcesTitle')}</div>
|
||||
<div className="images-empty-desc">{tr('imagesNoSourcesDesc')}</div>
|
||||
<Button variant="primary" icon={<Puzzle size={14} aria-hidden="true" />} onClick={onOpenPlugins}>
|
||||
{tr('imagesOpenPlugins')}
|
||||
</Button>
|
||||
</div>
|
||||
) : activeSource.native ? (
|
||||
renderNativeSource?.(activeSource.native, {
|
||||
refreshSignal: refreshSignals[activeKey] ?? 0,
|
||||
onBusyChange: handleActiveBusyChange,
|
||||
})
|
||||
) : (
|
||||
<PluginPanelFrame
|
||||
key={activeKey}
|
||||
locale={locale}
|
||||
panel={{
|
||||
id: activeSource.id,
|
||||
slot: 'images.source',
|
||||
title: activeSource.title,
|
||||
entry: activeSource.entry || 'index.html',
|
||||
height: activeSource.height || 560,
|
||||
pluginId: activeSource.pluginId,
|
||||
}}
|
||||
assetToken={pluginUI.asset_token ?? ''}
|
||||
appearance={appearance}
|
||||
headless
|
||||
maxHeight={1200}
|
||||
refreshSignal={refreshSignals[activeKey] ?? 0}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { LogLine } from '../lib/logs'
|
||||
import { taskDetail, taskInstallerPhase, taskStopAction, taskTitle } from '../lib/tasks'
|
||||
import { HostReport, Locale, Task } from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
import { HostIcon } from '../ui/themeVisuals'
|
||||
|
||||
export type LogTab = 'app' | 'serial' | 'qemu'
|
||||
|
||||
@@ -127,9 +128,18 @@ export const LogPanel: React.FC<Props> = ({
|
||||
try {
|
||||
const saved = Number(localStorage.getItem(LOG_HEIGHT_KEY))
|
||||
if (Number.isFinite(saved) && saved >= MIN_LOG_HEIGHT && saved <= MAX_LOG_HEIGHT) return saved
|
||||
} catch {}
|
||||
} catch (e) {
|
||||
console.warn('[logPanel] read persisted height failed:', e)
|
||||
}
|
||||
return DEFAULT_LOG_HEIGHT
|
||||
})
|
||||
const persistHeight = (value: number) => {
|
||||
try {
|
||||
localStorage.setItem(LOG_HEIGHT_KEY, String(value))
|
||||
} catch (e) {
|
||||
console.warn('[logPanel] persist height failed:', e)
|
||||
}
|
||||
}
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const dragRef = useRef<{ startY: number; startH: number } | null>(null)
|
||||
|
||||
@@ -149,7 +159,7 @@ export const LogPanel: React.FC<Props> = ({
|
||||
dragRef.current = null
|
||||
setDragging(false)
|
||||
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(height)) } catch {}
|
||||
persistHeight(height)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -175,17 +185,18 @@ export const LogPanel: React.FC<Props> = ({
|
||||
const delta = e.key === 'ArrowUp' ? 24 : -24
|
||||
const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, height + delta))
|
||||
setHeight(next)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(next)) } catch {}
|
||||
persistHeight(next)
|
||||
}}
|
||||
onDoubleClick={() => {
|
||||
setHeight(DEFAULT_LOG_HEIGHT)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(DEFAULT_LOG_HEIGHT)) } catch {}
|
||||
persistHeight(DEFAULT_LOG_HEIGHT)
|
||||
}}
|
||||
>
|
||||
<span className="log-resize-pill" aria-hidden="true" />
|
||||
</div>
|
||||
)}
|
||||
<div className="logbar rg-p-statusbar">
|
||||
<span className="rg-slot-inline" data-rg-slot="statusbar.left" />
|
||||
{task ? (
|
||||
<>
|
||||
<Tip
|
||||
@@ -202,7 +213,7 @@ export const LogPanel: React.FC<Props> = ({
|
||||
</span>
|
||||
{task.percent >= 0 && (
|
||||
<>
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress rg-p-progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
<span className="task-pct">{Math.floor(task.percent)}%</span>
|
||||
@@ -231,7 +242,7 @@ export const LogPanel: React.FC<Props> = ({
|
||||
{!hostReady && onOpenHost && (
|
||||
<Tip side="top" label={tr('footerHostIssueTip')}>
|
||||
<button type="button" className="status-metric status-issue" onClick={onOpenHost}>
|
||||
<AlertTriangle size={12} aria-hidden="true" />
|
||||
<HostIcon name="warning"><AlertTriangle size={12} aria-hidden="true" /></HostIcon>
|
||||
<span>{tr('footerHostIssue')}</span>
|
||||
</button>
|
||||
</Tip>
|
||||
@@ -293,7 +304,7 @@ export const LogPanel: React.FC<Props> = ({
|
||||
</button>
|
||||
)}
|
||||
<div
|
||||
className="tabs"
|
||||
className="tabs rg-p-tabs"
|
||||
role="tablist"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
|
||||
@@ -308,15 +319,15 @@ export const LogPanel: React.FC<Props> = ({
|
||||
btns[order.indexOf(next)]?.focus()
|
||||
}}
|
||||
>
|
||||
<button type="button" role="tab" className="tab" tabIndex={tab === 'app' ? 0 : -1} aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'app' ? 0 : -1} aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
{tr('logActivity')}
|
||||
</button>
|
||||
{showSerial && (
|
||||
<>
|
||||
<button type="button" role="tab" className="tab" tabIndex={tab === 'serial' ? 0 : -1} aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'serial' ? 0 : -1} aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab" tabIndex={tab === 'qemu' ? 0 : -1} aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
<button type="button" role="tab" className="tab rg-p-tab" tabIndex={tab === 'qemu' ? 0 : -1} aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
{tr('logQemu')}
|
||||
</button>
|
||||
</>
|
||||
@@ -337,7 +348,7 @@ export const LogPanel: React.FC<Props> = ({
|
||||
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshQemu} />
|
||||
)}
|
||||
<span className="rg-slot-inline" data-rg-slot="statusbar.right" />
|
||||
{!open && unseenErrors > 0 && <span className="badge badge-error" aria-hidden="true">{unseenErrors}</span>}
|
||||
{!open && unseenErrors > 0 && <span className="badge rg-p-badge badge-error" aria-hidden="true">{unseenErrors}</span>}
|
||||
<Tip label={open ? tr('collapseLogs') : tr('expandLogs')} shortcut="Ctrl+L" side="top">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
Boxes, Clipboard, Compass, Cpu, Disc3, Globe, Keyboard,
|
||||
Layers, Monitor, Palette, Puzzle, RotateCcw,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { PermissionSpec } from '../types'
|
||||
|
||||
export interface PluginVisualSource {
|
||||
id?: string
|
||||
kind?: string
|
||||
system?: boolean
|
||||
tier?: string
|
||||
locales?: string[]
|
||||
permissions?: Array<PermissionSpec | string>
|
||||
}
|
||||
|
||||
export interface PluginVisual {
|
||||
tone: string
|
||||
icon: React.ReactNode
|
||||
}
|
||||
|
||||
const ICON_SIZES = { sm: 16, md: 18, lg: 20 } as const
|
||||
|
||||
/**
|
||||
* Single visual resolver for both installed plugins (PluginInfo) and market
|
||||
* entries (MarketEntry), so a plugin keeps the same icon and colour across
|
||||
* Market, Installed and first-run setup.
|
||||
*/
|
||||
export function resolvePluginVisual(src: PluginVisualSource, iconSize = 20): PluginVisual {
|
||||
if (src.system) return { tone: 'indigo', icon: <Boxes size={iconSize} aria-hidden="true" /> }
|
||||
switch (src.kind) {
|
||||
case 'theme': return { tone: 'purple', icon: <Palette size={iconSize} aria-hidden="true" /> }
|
||||
case 'locale': return { tone: 'sky', icon: <Globe size={iconSize} aria-hidden="true" /> }
|
||||
case 'driver':
|
||||
case 'runtime': return { tone: 'indigo', icon: <Monitor size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
const id = (src.id ?? '').toLowerCase()
|
||||
const perms = new Set((src.permissions ?? []).map((x) => (typeof x === 'string' ? x : x.name)))
|
||||
if ((src.locales?.length ?? 0) > 0 || id.includes('lang') || id.includes('locale')) {
|
||||
return { tone: 'sky', icon: <Globe size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('theme') || perms.has('ui:script')) {
|
||||
return { tone: 'purple', icon: <Palette size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('driver') || perms.has('driver:vm') || perms.has('runtime:provider')) {
|
||||
return { tone: 'indigo', icon: <Monitor size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('clipboard') || perms.has('host:clipboard')) {
|
||||
return { tone: 'sky', icon: <Clipboard size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('ime') || id.includes('input') || id.includes('wheel') || perms.has('input:filter')) {
|
||||
return { tone: 'rose', icon: <Keyboard size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('reboot')) {
|
||||
return { tone: 'amber', icon: <RotateCcw size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('whpx') || id.includes('irq')) {
|
||||
return { tone: 'emerald', icon: <Cpu size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('guide')) {
|
||||
return { tone: 'teal', icon: <Compass size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('offline') || id.includes('installer') || id.includes('helper') || id.includes('image')) {
|
||||
return { tone: 'teal', icon: <Disc3 size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (src.tier === 'L3') {
|
||||
return { tone: 'slate', icon: <Layers size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
return { tone: 'teal', icon: <Puzzle size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
|
||||
/** App Store-inspired squircle icon tile shared by Market, Installed and Setup. */
|
||||
export const PluginAppIcon: React.FC<{
|
||||
plugin?: PluginVisualSource
|
||||
kind?: string
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
}> = ({ plugin, kind, size = 'lg' }) => {
|
||||
const vis = resolvePluginVisual(plugin ?? { kind }, ICON_SIZES[size])
|
||||
const sizeCls = size === 'lg' ? '' : ` is-${size}`
|
||||
return <div className={`plugin-app-icon tone-${vis.tone}${sizeCls}`}>{vis.icon}</div>
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
Activity, AlertTriangle, BadgeCheck, Binary, Check, Clipboard, Code2, Download, Files, Globe,
|
||||
Keyboard, Monitor, PanelsTopLeft, Palette, Puzzle, Search, ShieldAlert, ShieldCheck, Users,
|
||||
} from 'lucide-react'
|
||||
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'
|
||||
@@ -9,6 +6,7 @@ import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo } from '../ty
|
||||
import { Button, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api, events, MarketInstallProgress } from '../wails'
|
||||
import { PluginAppIcon, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { locText } from './SchemaForm'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
|
||||
@@ -28,43 +26,6 @@ const KIND_LABELS: Record<string, I18nKey> = {
|
||||
runtime: 'pluginMarketKindRuntime',
|
||||
}
|
||||
|
||||
const RISKS: Record<string, { key: I18nKey; icon: React.ReactNode; high: boolean }> = {
|
||||
native: { key: 'pluginRiskNative', icon: <Binary size={15} aria-hidden="true" />, high: true },
|
||||
background: { key: 'pluginRiskBackground', icon: <Activity size={15} aria-hidden="true" />, high: true },
|
||||
network: { key: 'pluginRiskNetwork', icon: <Globe size={15} aria-hidden="true" />, high: true },
|
||||
files: { key: 'pluginRiskFiles', icon: <Files size={15} aria-hidden="true" />, high: true },
|
||||
vm: { key: 'pluginRiskVm', icon: <Monitor size={15} aria-hidden="true" />, high: true },
|
||||
clipboard: { key: 'pluginRiskClipboard', icon: <Clipboard size={15} aria-hidden="true" />, high: true },
|
||||
input: { key: 'pluginRiskInput', icon: <Keyboard size={15} aria-hidden="true" />, high: false },
|
||||
ui: { key: 'pluginRiskUi', icon: <PanelsTopLeft size={15} aria-hidden="true" />, high: false },
|
||||
}
|
||||
|
||||
/** Plain-language list of what a plugin can do (backend risk categories). */
|
||||
export const RiskList: React.FC<{ locale: Locale; risks?: string[] }> = ({ locale, risks }) => {
|
||||
const known = (risks ?? []).filter((r) => RISKS[r])
|
||||
if (known.length === 0) return null
|
||||
return (
|
||||
<ul className="plugin-risk-list">
|
||||
{known.map((r) => (
|
||||
<li key={r} className={`plugin-risk${RISKS[r].high ? ' is-high' : ''}`}>
|
||||
<span className="plugin-risk-icon">{RISKS[r].icon}</span>
|
||||
<span>{t(locale, RISKS[r].key)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function kindVisual(kind?: string): { tone: string; icon: React.ReactNode } {
|
||||
switch (kind) {
|
||||
case 'theme': return { tone: 'purple', icon: <Palette size={20} aria-hidden="true" /> }
|
||||
case 'locale': return { tone: 'sky', icon: <Globe size={20} aria-hidden="true" /> }
|
||||
case 'driver':
|
||||
case 'runtime': return { tone: 'indigo', icon: <Monitor size={20} aria-hidden="true" /> }
|
||||
default: return { tone: 'teal', icon: <Puzzle size={20} aria-hidden="true" /> }
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
safeMode?: boolean
|
||||
@@ -145,8 +106,9 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
}
|
||||
return res
|
||||
})
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// the network load reports errors
|
||||
console.warn('[market] PeekPluginMarket failed:', e)
|
||||
}
|
||||
}, [])
|
||||
|
||||
@@ -239,24 +201,6 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
}, [result, kind])
|
||||
const kindLabel = (k: string) => KIND_LABELS[k] ? tr(KIND_LABELS[k]) : k.charAt(0).toUpperCase() + k.slice(1)
|
||||
|
||||
const publisherMark = (trust: string, publisher: string) => {
|
||||
const meta = trust === 'official'
|
||||
? { cls: 'is-official', icon: <BadgeCheck size={13} aria-hidden="true" />, label: tr('pluginTrustOfficial') }
|
||||
: trust === 'verified'
|
||||
? { cls: 'is-verified', icon: <ShieldCheck size={13} aria-hidden="true" />, label: tr('pluginTrustVerified') }
|
||||
: trust === 'dev'
|
||||
? { cls: 'is-dev', icon: <Code2 size={13} aria-hidden="true" />, label: tr('pluginTrustDev') }
|
||||
: { cls: 'is-community', icon: <Users size={13} aria-hidden="true" />, label: tr('pluginTrustCommunity') }
|
||||
return (
|
||||
<Tip label={meta.label}>
|
||||
<span className={`market-publisher ${meta.cls}`} tabIndex={0}>
|
||||
{meta.icon}
|
||||
<span className="market-publisher-name">{publisher || meta.label}</span>
|
||||
</span>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
|
||||
const action = (item: MarketCatalogItem) => {
|
||||
const e = item.entry
|
||||
const p = progress[e.id]
|
||||
@@ -265,14 +209,14 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
const text = p.phase === 'install' ? tr('pluginMarketInstalling') : pct === null ? tr('pluginMarketDownloading') : `${pct}%`
|
||||
return (
|
||||
<div
|
||||
className={`market-progress${pct === null ? ' is-indeterminate' : ''}`}
|
||||
className={`market-progress rg-p-progress${pct === null ? ' is-indeterminate' : ''}`}
|
||||
role="progressbar"
|
||||
aria-label={tr('pluginMarketDownloading')}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={pct ?? undefined}
|
||||
>
|
||||
<span className="market-progress-fill" style={pct === null ? undefined : { width: `${pct}%` }} />
|
||||
<span className="market-progress-fill" style={pct === null ? undefined : { transform: `scaleX(${pct / 100})` }} />
|
||||
<span className="market-progress-text">{text}</span>
|
||||
</div>
|
||||
)
|
||||
@@ -314,17 +258,12 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
return (
|
||||
<section className="section plugin-market">
|
||||
<div className="market-toolbar">
|
||||
<div className="plugins-search-wrap market-search-wrap">
|
||||
<Search size={13} className="plugins-search-icon" aria-hidden="true" />
|
||||
<input
|
||||
type="search"
|
||||
className="input market-search"
|
||||
aria-label={tr('pluginMarketSearchPlaceholder')}
|
||||
placeholder={tr('pluginMarketSearchPlaceholder')}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<PluginSearchInput
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tr('pluginMarketSearchPlaceholder')}
|
||||
wide
|
||||
/>
|
||||
{facets.length > 1 && (
|
||||
<div className="market-kinds" role="radiogroup" aria-label={tr('pluginMarketKindAll')}>
|
||||
{[{ kind: '', count: 0 }, ...facets].map((f) => (
|
||||
@@ -333,11 +272,11 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={kind === f.kind}
|
||||
className={`market-kind${kind === f.kind ? ' is-active' : ''}`}
|
||||
className={`plugin-pill${kind === f.kind ? ' is-active' : ''}`}
|
||||
onClick={() => setKind(f.kind)}
|
||||
>
|
||||
{f.kind ? kindLabel(f.kind) : tr('pluginMarketKindAll')}
|
||||
{f.kind && f.count > 0 && <span className="market-kind-count">{f.count}</span>}
|
||||
{f.kind && f.count > 0 && <span className="plugin-pill-count">{f.count}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -374,21 +313,20 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
<div className="market-grid">
|
||||
{shown.map((item, i) => {
|
||||
const e = item.entry
|
||||
const vis = kindVisual(e.kind)
|
||||
const desc = locText(e.description, locale, '')
|
||||
const muted = !!item.withdrawn || !item.compatible
|
||||
return (
|
||||
<article
|
||||
className={`market-card${muted ? ' is-muted' : ''}`}
|
||||
className={`market-card rg-p-card${muted ? ' is-muted' : ''}`}
|
||||
key={e.id}
|
||||
style={{ '--i': i % PAGE_SIZE } as React.CSSProperties}
|
||||
>
|
||||
<div className="market-card-head">
|
||||
<div className={`plugin-app-icon tone-${vis.tone}`}>{vis.icon}</div>
|
||||
<PluginAppIcon plugin={e} size="lg" />
|
||||
<div className="market-card-titles">
|
||||
<h3 className="market-card-name" title={locText(e.name, locale, e.id)}>{locText(e.name, locale, e.id)}</h3>
|
||||
<div className="market-card-byline">
|
||||
{publisherMark(e.trust, e.publisher)}
|
||||
<PluginTrustBadge locale={locale} trust={e.trust} publisher={e.publisher} />
|
||||
<span className="market-card-dot" aria-hidden="true">·</span>
|
||||
<span className="market-card-version">v{e.version}</span>
|
||||
</div>
|
||||
@@ -413,7 +351,7 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { if (!enabling) setPrompt(null) }}
|
||||
>
|
||||
<div className="stack-3 plugin-enable-body">
|
||||
<div className="dialog-body">
|
||||
{(prompt.risks?.length ?? 0) > 0 ? (
|
||||
<>
|
||||
<p className="plugin-enable-lead">{tr('pluginEnablePromptBody')}</p>
|
||||
@@ -423,7 +361,7 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
<p className="plugin-enable-lead">{tr('pluginEnablePromptNoRisk')}</p>
|
||||
)}
|
||||
{prompt.needs_approval && (
|
||||
<label className="hstack plugin-enable-ack">
|
||||
<label className="choice">
|
||||
<input type="checkbox" checked={promptChecked} onChange={(e) => setPromptChecked(e.target.checked)} />
|
||||
<span>{tr('pluginApproveCheckbox')}</span>
|
||||
</label>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
|
||||
import { Locale, PanelContribution } from '../types'
|
||||
@@ -7,9 +8,15 @@ import { locText } from './SchemaForm'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
panel: PanelContribution
|
||||
panel: Omit<PanelContribution, 'convertValues'>
|
||||
assetToken: string
|
||||
appearance: 'light' | 'dark'
|
||||
/** Omit the panel title bar (e.g. when hosted inside a tab/segmented view). */
|
||||
headless?: boolean
|
||||
/** Upper bound for the iframe height in px (defaults to 480 for inline panels). */
|
||||
maxHeight?: number
|
||||
/** Incrementing this reloads the iframe cleanly. */
|
||||
refreshSignal?: number
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,13 +44,22 @@ function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, ent
|
||||
return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}`
|
||||
}
|
||||
|
||||
export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, appearance }) => {
|
||||
export const PluginPanelFrame: React.FC<Props> = ({
|
||||
locale, panel, assetToken, appearance, headless, maxHeight = 480, refreshSignal = 0,
|
||||
}) => {
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
const localeRef = useRef<Locale>(locale)
|
||||
localeRef.current = locale
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [nonce, setNonce] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (refreshSignal > 0) {
|
||||
setFailed(false)
|
||||
setNonce((n) => n + 1)
|
||||
}
|
||||
}, [refreshSignal])
|
||||
|
||||
const src = buildSafePanelSrc(assetToken, panel.pluginId, panel.entry)
|
||||
|
||||
const syncTheme = () => {
|
||||
@@ -113,8 +129,11 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
|
||||
|
||||
if (failed || !src) {
|
||||
return (
|
||||
<div className="plugin-panel-error">
|
||||
<span>{t(locale, 'panelLoadFailed')}</span>
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{t(locale, 'panelLoadFailed')}</span>
|
||||
</span>
|
||||
{src && (
|
||||
<Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>
|
||||
{t(locale, 'installersRetry')}
|
||||
@@ -125,8 +144,8 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="plugin-panel-wrap">
|
||||
<div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>
|
||||
<div className={`plugin-panel-wrap rg-p-plugin-view${headless ? ' is-headless' : ''}`} data-plugin={panel.pluginId}>
|
||||
{!headless && <div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>}
|
||||
<iframe
|
||||
key={nonce}
|
||||
ref={iframeRef}
|
||||
@@ -135,7 +154,7 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
|
||||
src={src}
|
||||
sandbox="allow-scripts"
|
||||
referrerPolicy="no-referrer"
|
||||
style={{ height: Math.max(120, Math.min(480, panel.height || 220)) }}
|
||||
style={{ height: Math.max(120, Math.min(maxHeight, panel.height || 220)) }}
|
||||
onLoad={syncTheme}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
Activity, BadgeCheck, Binary, Clipboard, Code2, Files, Globe,
|
||||
Keyboard, Monitor, PanelsTopLeft, Search, ShieldCheck, Users,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
|
||||
export { PluginAppIcon, resolvePluginVisual, type PluginVisual, type PluginVisualSource } from './PluginAppIcon'
|
||||
|
||||
/** Publisher + trust-tier mark shared by Installed rows and Market cards. */
|
||||
export const PluginTrustBadge: React.FC<{
|
||||
locale: Locale
|
||||
trust: string
|
||||
publisher?: string
|
||||
}> = ({ locale, trust, publisher }) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const meta = trust === 'official'
|
||||
? { cls: 'is-official', icon: <BadgeCheck size={13} aria-hidden="true" />, label: tr('pluginTrustOfficial') }
|
||||
: trust === 'verified'
|
||||
? { cls: 'is-verified', icon: <ShieldCheck size={13} aria-hidden="true" />, label: tr('pluginTrustVerified') }
|
||||
: trust === 'dev'
|
||||
? { cls: 'is-dev', icon: <Code2 size={13} aria-hidden="true" />, label: tr('pluginTrustDev') }
|
||||
: { cls: 'is-community', icon: <Users size={13} aria-hidden="true" />, label: tr('pluginTrustCommunity') }
|
||||
return (
|
||||
<Tip label={meta.label}>
|
||||
<span className={`plugin-trust ${meta.cls}`} tabIndex={0}>
|
||||
{meta.icon}
|
||||
<span className="plugin-trust-name">{publisher || meta.label}</span>
|
||||
</span>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
|
||||
/** Search input with leading magnifying glass, shared by Installed and Market. */
|
||||
export const PluginSearchInput: React.FC<{
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder: string
|
||||
wide?: boolean
|
||||
}> = ({ value, onChange, placeholder, wide }) => (
|
||||
<div className={`plugin-search-wrap${wide ? ' is-wide' : ''}`}>
|
||||
<Search size={13} className="plugin-search-icon" aria-hidden="true" />
|
||||
<input
|
||||
type="search"
|
||||
className="input rg-p-input plugin-search"
|
||||
aria-label={placeholder}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
const RISKS: Record<string, { key: I18nKey; icon: React.ReactNode; high: boolean }> = {
|
||||
native: { key: 'pluginRiskNative', icon: <Binary size={15} aria-hidden="true" />, high: true },
|
||||
background: { key: 'pluginRiskBackground', icon: <Activity size={15} aria-hidden="true" />, high: true },
|
||||
network: { key: 'pluginRiskNetwork', icon: <Globe size={15} aria-hidden="true" />, high: true },
|
||||
files: { key: 'pluginRiskFiles', icon: <Files size={15} aria-hidden="true" />, high: true },
|
||||
vm: { key: 'pluginRiskVm', icon: <Monitor size={15} aria-hidden="true" />, high: true },
|
||||
clipboard: { key: 'pluginRiskClipboard', icon: <Clipboard size={15} aria-hidden="true" />, high: true },
|
||||
input: { key: 'pluginRiskInput', icon: <Keyboard size={15} aria-hidden="true" />, high: false },
|
||||
ui: { key: 'pluginRiskUi', icon: <PanelsTopLeft size={15} aria-hidden="true" />, high: false },
|
||||
}
|
||||
|
||||
/** Plain-language list of what a plugin can do (backend risk categories). */
|
||||
export const RiskList: React.FC<{ locale: Locale; risks?: string[] }> = ({ locale, risks }) => {
|
||||
const known = (risks ?? []).filter((r) => RISKS[r])
|
||||
if (known.length === 0) return null
|
||||
return (
|
||||
<ul className="plugin-risk-list">
|
||||
{known.map((r) => (
|
||||
<li key={r} className={`plugin-risk${RISKS[r].high ? ' is-high' : ''}`}>
|
||||
<span className="plugin-risk-icon">{RISKS[r].icon}</span>
|
||||
<span>{t(locale, RISKS[r].key)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
AlertTriangle, BadgeCheck, Boxes, CheckCircle2, Clipboard, Code2, Compass, Cpu, Disc3,
|
||||
FolderOpen, Keyboard, Layers, Monitor, PackagePlus, Palette, Puzzle, RefreshCw, RotateCcw,
|
||||
Search, Settings2, Shield, ShieldAlert, ShieldCheck, Sparkles, Terminal, Trash2,
|
||||
AlertTriangle, CheckCircle2, FolderOpen, PackagePlus, Palette,
|
||||
RefreshCw, Settings2, Shield, ShieldAlert, Sparkles, Terminal, Trash2,
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
@@ -11,11 +10,12 @@ import {
|
||||
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport,
|
||||
} from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { ConfirmDialog, Modal } from '../ui/dialog'
|
||||
import { PopupSelect, Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { PluginMarket, RiskList } from './PluginMarket'
|
||||
import { PluginMarket } from './PluginMarket'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { PluginAppIcon, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { SchemaForm, locText } from './SchemaForm'
|
||||
|
||||
// Search only earns its space once the list is long enough to scan.
|
||||
@@ -34,45 +34,6 @@ interface Props {
|
||||
onLocaleSwitch?: (l: Locale) => void
|
||||
}
|
||||
|
||||
interface PluginVisual {
|
||||
tone: string
|
||||
icon: React.ReactNode
|
||||
}
|
||||
|
||||
function resolvePluginVisual(p: PluginInfo): PluginVisual {
|
||||
if (p.system) return { tone: 'indigo', icon: <Boxes size={19} aria-hidden="true" /> }
|
||||
const id = p.id.toLowerCase()
|
||||
const perms = new Set((p.permissions ?? []).map((x) => x.name))
|
||||
if (id.includes('theme') || perms.has('ui:script')) {
|
||||
return { tone: 'purple', icon: <Palette size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('driver') || perms.has('driver:vm') || perms.has('runtime:provider')) {
|
||||
return { tone: 'indigo', icon: <Monitor size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('clipboard') || perms.has('host:clipboard')) {
|
||||
return { tone: 'sky', icon: <Clipboard size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('ime') || id.includes('input') || id.includes('wheel') || perms.has('input:filter')) {
|
||||
return { tone: 'rose', icon: <Keyboard size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('reboot')) {
|
||||
return { tone: 'amber', icon: <RotateCcw size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('whpx') || id.includes('irq')) {
|
||||
return { tone: 'emerald', icon: <Cpu size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('guide')) {
|
||||
return { tone: 'teal', icon: <Compass size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('offline') || id.includes('installer') || id.includes('helper')) {
|
||||
return { tone: 'teal', icon: <Disc3 size={19} aria-hidden="true" /> }
|
||||
}
|
||||
if (p.tier === 'L3') {
|
||||
return { tone: 'slate', icon: <Layers size={19} aria-hidden="true" /> }
|
||||
}
|
||||
return { tone: 'purple', icon: <Puzzle size={19} aria-hidden="true" /> }
|
||||
}
|
||||
|
||||
// The plugin settings dialog shows app-scope fields only; per-VM fields live in
|
||||
// each VM's settings. Same scope rule as SchemaForm.
|
||||
function hasAppSettings(p: PluginInfo): boolean {
|
||||
@@ -182,7 +143,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
setApproveChecked(false)
|
||||
setApproveReport(null)
|
||||
setApproveTarget(p)
|
||||
void api.ScanInstalledPlugin(p.id).then(setApproveReport).catch(() => {})
|
||||
void api.ScanInstalledPlugin(p.id).then(setApproveReport).catch((e) => console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e))
|
||||
return
|
||||
}
|
||||
setBusyID(p.id)
|
||||
@@ -394,25 +355,16 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
return base
|
||||
}, [activeTheme, customSchemes, presetSchemes])
|
||||
|
||||
const trustMeta = (trLevel: string) => {
|
||||
if (trLevel === 'official') return { label: tr('pluginTrustOfficial'), cls: 'is-official', icon: <BadgeCheck size={12} aria-hidden="true" /> }
|
||||
if (trLevel === 'verified') return { label: tr('pluginTrustVerified'), cls: 'is-verified', icon: <ShieldCheck size={12} aria-hidden="true" /> }
|
||||
if (trLevel === 'dev') return { label: tr('pluginTrustDev'), cls: 'is-dev', icon: <Code2 size={12} aria-hidden="true" /> }
|
||||
return { label: tr('pluginTrustCommunity'), cls: 'is-community', icon: <Shield size={12} aria-hidden="true" /> }
|
||||
}
|
||||
|
||||
// The switch already says on/off, so only surface states that need attention.
|
||||
const stateBadge = (p: PluginInfo) => {
|
||||
if (p.state === 'degraded') return <span className="badge badge-warn">{tr('pluginStateDegraded')}</span>
|
||||
if (p.state === 'failed') return <span className="badge badge-warn">{tr('pluginStateFailed')}</span>
|
||||
if (p.state === 'pending' && p.enabled) return <span className="badge">{tr('pluginStatePending')}</span>
|
||||
if (p.state === 'degraded') return <span className="badge rg-p-badge badge-warn">{tr('pluginStateDegraded')}</span>
|
||||
if (p.state === 'failed') return <span className="badge rg-p-badge badge-warn">{tr('pluginStateFailed')}</span>
|
||||
if (p.state === 'pending' && p.enabled) return <span className="badge rg-p-badge">{tr('pluginStatePending')}</span>
|
||||
return null
|
||||
}
|
||||
|
||||
const renderRow = (p: PluginInfo) => {
|
||||
const visual = resolvePluginVisual(p)
|
||||
const isBuiltin = p.source === 'builtin'
|
||||
const trust = trustMeta(p.trust)
|
||||
const perms = p.permissions ?? []
|
||||
const highPerms = perms.filter((x) => x.level === 'high')
|
||||
const desc = locText(p.description, locale, '')
|
||||
@@ -421,7 +373,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
|
||||
return (
|
||||
<div className={`row plugin-row${p.enabled ? ' is-enabled' : ''}`} key={p.id}>
|
||||
<div className={`plugin-app-icon tone-${visual.tone}`}>{visual.icon}</div>
|
||||
<PluginAppIcon plugin={p} size="md" />
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="plugin-row-name">{locText(p.name, locale, p.id)}</span>
|
||||
@@ -430,7 +382,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
{desc && <div className="row-sub plugin-row-desc" title={desc}>{desc}</div>}
|
||||
{!isBuiltin && (
|
||||
<div className="row-sub plugin-row-meta">
|
||||
<span className={`plugin-trust ${trust.cls}`}>{trust.icon}{p.publisher || trust.label}</span>
|
||||
<PluginTrustBadge locale={locale} trust={p.trust} publisher={p.publisher} />
|
||||
<span className="mono">v{p.version}</span>
|
||||
{perms.length > 0 && (
|
||||
<Tip label={tr('pluginPermissionsLabel', { list: perms.map((x) => x.name).join(', ') })}>
|
||||
@@ -520,7 +472,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<div className="row" key={`${f.check}-${idx}`}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="badge badge-danger">{f.check}</span>
|
||||
<span className="badge rg-p-badge badge-danger">{f.check}</span>
|
||||
{f.target && <span className="mono">{f.target}</span>}
|
||||
</div>
|
||||
<div className="row-sub">{locText(f.localized, locale, f.message)}</div>
|
||||
@@ -539,7 +491,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<div className="row" key={c.id}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className={`badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
|
||||
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
|
||||
<span>{locText(c.title, locale, c.id)}</span>
|
||||
<span className="mono muted" style={{ fontSize: 'var(--fs-11)' }}>{c.id}</span>
|
||||
</div>
|
||||
@@ -567,7 +519,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<div className="row" key={`pend-${f.check}-${idx}`}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="badge">{f.check}</span>
|
||||
<span className="badge rg-p-badge">{f.check}</span>
|
||||
{f.target && <span className="mono">{f.target}</span>}
|
||||
</div>
|
||||
<div className="row-sub">{locText(f.localized, locale, f.message)}</div>
|
||||
@@ -578,7 +530,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<div className="row" key={ex.path}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className={`badge${ex.declared ? '' : ' badge-danger'}`}>{ex.declared ? 'EXE' : 'UNLISTED'}</span>
|
||||
<span className={`badge rg-p-badge${ex.declared ? '' : ' badge-danger'}`}>{ex.declared ? 'EXE' : 'UNLISTED'}</span>
|
||||
<span className="mono">{ex.path}</span>
|
||||
</div>
|
||||
<div className="row-sub mono selectable">SHA-256: {ex.sha256}</div>
|
||||
@@ -608,17 +560,11 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
</div>
|
||||
<div className="actions">
|
||||
{activeTab === 'installed' && showSearch && (
|
||||
<div className="plugins-search-wrap">
|
||||
<Search size={13} className="plugins-search-icon" aria-hidden="true" />
|
||||
<input
|
||||
type="search"
|
||||
className="input plugins-search"
|
||||
aria-label={tr('pluginSearchPlaceholder')}
|
||||
placeholder={tr('pluginSearchPlaceholder')}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<PluginSearchInput
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tr('pluginSearchPlaceholder')}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
label={activeTab === 'market' ? tr('pluginMarketRefresh') : tr('refresh')}
|
||||
@@ -719,10 +665,12 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' ? (
|
||||
<div className="theme-scheme-strip">
|
||||
<span className="muted" style={{ fontSize: 'var(--fs-12)' }}>{tr('pluginColorSchemes')}</span>
|
||||
<div className="theme-scheme-chips">
|
||||
<div className="theme-scheme-chips" role="radiogroup" aria-label={tr('pluginColorSchemes')}>
|
||||
<button
|
||||
type="button"
|
||||
className={`plugin-cat-pill${!activeTheme.active_scheme ? ' is-active' : ''}`}
|
||||
role="radio"
|
||||
aria-checked={!activeTheme.active_scheme}
|
||||
className={`plugin-pill${!activeTheme.active_scheme ? ' is-active' : ''}`}
|
||||
onClick={() => void selectTheme(activeTheme.theme_id, '')}
|
||||
>
|
||||
{tr('pluginSchemeDefault')}
|
||||
@@ -731,7 +679,9 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<button
|
||||
key={s.id}
|
||||
type="button"
|
||||
className={`plugin-cat-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
|
||||
role="radio"
|
||||
aria-checked={activeTheme.active_scheme === s.id}
|
||||
className={`plugin-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
|
||||
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
|
||||
>
|
||||
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
|
||||
@@ -742,7 +692,9 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<span className="hstack" style={{ gap: 2 }} key={s.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={`plugin-cat-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
|
||||
role="radio"
|
||||
aria-checked={activeTheme.active_scheme === s.id}
|
||||
className={`plugin-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
|
||||
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
|
||||
>
|
||||
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
|
||||
@@ -780,7 +732,17 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
{!loading && <span className="section-count">{filteredBuiltins.length}</span>}
|
||||
</div>
|
||||
{loading ? (
|
||||
<div className="list"><div className="row plugin-row"><span className="muted">…</span></div></div>
|
||||
<div className="skeleton-list" role="status" aria-label={tr('sidebarPlugins')}>
|
||||
{[0, 1, 2].map((i) => (
|
||||
<div className="skeleton-row" key={i} aria-hidden="true">
|
||||
<div className="skeleton-stack">
|
||||
<div className="skeleton-bar w-title" />
|
||||
<div className="skeleton-bar w-sub" />
|
||||
</div>
|
||||
<div className="skeleton-bar w-btn" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="list">{filteredBuiltins.map(renderRow)}</div>
|
||||
)}
|
||||
@@ -813,7 +775,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { if (!scanBusy) setScanModal(null) }}
|
||||
>
|
||||
<div style={{ padding: 'var(--sp-4)', maxHeight: 440, overflow: 'auto' }}>
|
||||
<div className="dialog-body">
|
||||
{renderScanReportBody(scanModal.report)}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
@@ -847,7 +809,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { setApproveTarget(null); setApproveReport(null) }}
|
||||
>
|
||||
<div className="stack-3" style={{ padding: 'var(--sp-4)', maxHeight: 440, overflow: 'auto' }}>
|
||||
<div className="dialog-body">
|
||||
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
|
||||
<div className="notice notice-warn">
|
||||
<span className="notice-main">
|
||||
@@ -875,7 +837,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<div className="row" key={c.id}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className={`badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
|
||||
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
|
||||
<span>{locText(c.title, locale, c.id)}</span>
|
||||
</div>
|
||||
<div className="row-sub">{locText(c.summary, locale, '')}</div>
|
||||
@@ -885,7 +847,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<label className="hstack" style={{ cursor: 'pointer' }}>
|
||||
<label className="choice">
|
||||
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
|
||||
<span>{tr('pluginApproveCheckbox')}</span>
|
||||
</label>
|
||||
@@ -909,7 +871,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setSettingsTarget(null)}
|
||||
>
|
||||
<div style={{ padding: 'var(--sp-4)' }}>
|
||||
<div className="dialog-body">
|
||||
<SchemaForm
|
||||
locale={locale}
|
||||
schema={settingsTarget.settings}
|
||||
@@ -926,87 +888,52 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
)}
|
||||
|
||||
{disableTarget && (
|
||||
<Modal
|
||||
<ConfirmDialog
|
||||
title={tr('pluginDisableInUseTitle')}
|
||||
subtitle={locText(disableTarget.name, locale, disableTarget.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setDisableTarget(null)}
|
||||
description={tr('pluginDisableInUseBody')}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('pluginDisable')}
|
||||
onCancel={() => setDisableTarget(null)}
|
||||
onConfirm={() => {
|
||||
const target = disableTarget
|
||||
setDisableTarget(null)
|
||||
void togglePlugin(target, false, true)
|
||||
}}
|
||||
>
|
||||
<div style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
|
||||
{tr('pluginDisableInUseBody')}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setDisableTarget(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
const target = disableTarget
|
||||
setDisableTarget(null)
|
||||
void togglePlugin(target, false, true)
|
||||
}}
|
||||
>
|
||||
{tr('pluginDisable')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
<div className="row-sub">{locText(disableTarget.name, locale, disableTarget.id)}</div>
|
||||
</ConfirmDialog>
|
||||
)}
|
||||
|
||||
{removeTarget && (
|
||||
<Modal
|
||||
<ConfirmDialog
|
||||
title={tr('pluginRemove')}
|
||||
subtitle={locText(removeTarget.name, locale, removeTarget.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setRemoveTarget(null)}
|
||||
description={locText(removeTarget.name, locale, removeTarget.id)}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('pluginRemove')}
|
||||
onCancel={() => setRemoveTarget(null)}
|
||||
onConfirm={() => {
|
||||
const target = removeTarget
|
||||
setRemoveTarget(null)
|
||||
void removePlugin(target)
|
||||
}}
|
||||
>
|
||||
<div style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
|
||||
<span className="mono">{removeTarget.id}@{removeTarget.version}</span>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setRemoveTarget(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
const target = removeTarget
|
||||
setRemoveTarget(null)
|
||||
void removePlugin(target)
|
||||
}}
|
||||
>
|
||||
{tr('pluginRemove')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
<div className="row-sub mono">{removeTarget.id}@{removeTarget.version}</div>
|
||||
</ConfirmDialog>
|
||||
)}
|
||||
|
||||
{deleteSchemeTarget && (
|
||||
<Modal
|
||||
<ConfirmDialog
|
||||
title={tr('pluginDeleteScheme')}
|
||||
subtitle={deleteSchemeTarget.name}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setDeleteSchemeTarget(null)}
|
||||
>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setDeleteSchemeTarget(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
const target = deleteSchemeTarget
|
||||
setDeleteSchemeTarget(null)
|
||||
void deleteScheme(target.id)
|
||||
}}
|
||||
>
|
||||
{tr('pluginDeleteScheme')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
description={deleteSchemeTarget.name}
|
||||
cancelLabel={tr('cancel')}
|
||||
confirmLabel={tr('pluginDeleteScheme')}
|
||||
onCancel={() => setDeleteSchemeTarget(null)}
|
||||
onConfirm={() => {
|
||||
const target = deleteSchemeTarget
|
||||
setDeleteSchemeTarget(null)
|
||||
void deleteScheme(target.id)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{logTarget && (
|
||||
@@ -1015,9 +942,9 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setLogTarget(null)}
|
||||
>
|
||||
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
|
||||
{logTarget.text}
|
||||
</pre>
|
||||
<div className="dialog-body">
|
||||
<pre className="plugin-log-pre mono selectable">{logTarget.text}</pre>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
@@ -1027,19 +954,19 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setSchemeEditorOpen(false)}
|
||||
>
|
||||
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
|
||||
<label className="stack-1">
|
||||
<span>{tr('pluginSchemeName')}</span>
|
||||
<input className="input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
|
||||
<div className="dialog-body">
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('pluginSchemeName')}</span>
|
||||
<input className="input rg-p-input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
|
||||
</label>
|
||||
<label className="hstack">
|
||||
<span>{tr('pluginAccentSeed')}</span>
|
||||
<span className="field-label">{tr('pluginAccentSeed')}</span>
|
||||
<input type="color" value={seedAccent} onChange={(e) => setSeedAccent(e.target.value)} />
|
||||
<span className="mono">{seedAccent}</span>
|
||||
</label>
|
||||
<label className="stack-1">
|
||||
<span>{tr('pluginSurfaceSeed')}</span>
|
||||
<input className="input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('pluginSurfaceSeed')}</span>
|
||||
<input className="input rg-p-input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
|
||||
</label>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
|
||||
@@ -60,7 +60,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
<div className="row-sub task-inline">
|
||||
<LoaderCircle size={14} className="spin" aria-hidden="true" />
|
||||
{task.percent >= 0 && (
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress rg-p-progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
)}
|
||||
@@ -108,7 +108,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
|
||||
</Button>
|
||||
) : !running && active && remote ? (
|
||||
<span className="badge badge-ok">{tr('runtimeUpToDate')}</span>
|
||||
<span className="badge rg-p-badge badge-ok">{tr('runtimeUpToDate')}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -53,7 +53,7 @@ export const SchemaForm: React.FC<Props> = ({
|
||||
const eff = prop['x-effect']
|
||||
if (!eff) return null
|
||||
const label = t(locale, eff === 'immediate' ? 'effectImmediate' : 'effectNextStart')
|
||||
return <span className={`badge ${eff === 'immediate' ? 'badge-ok' : ''}`}>{label}</span>
|
||||
return <span className={`badge rg-p-badge ${eff === 'immediate' ? 'badge-ok' : ''}`}>{label}</span>
|
||||
}
|
||||
|
||||
const renderControl = (k: string, prop: SettingProperty) => {
|
||||
@@ -114,7 +114,7 @@ export const SchemaForm: React.FC<Props> = ({
|
||||
return (
|
||||
<input
|
||||
type="password"
|
||||
className="input"
|
||||
className="input rg-p-input"
|
||||
aria-label={label}
|
||||
autoComplete="new-password"
|
||||
placeholder={isMasked ? SECRET_MASK : undefined}
|
||||
@@ -127,7 +127,7 @@ export const SchemaForm: React.FC<Props> = ({
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
className="input rg-p-input"
|
||||
aria-label={label}
|
||||
value={String(cur ?? '')}
|
||||
onChange={(e) => setKey(k, e.target.value)}
|
||||
|
||||
@@ -19,7 +19,7 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{t(locale, 'sendTextTitle', { name: vmName })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
@@ -27,7 +27,7 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
|
||||
</Alert.Description>
|
||||
<div className="field field-spaced">
|
||||
<textarea
|
||||
className="input textarea"
|
||||
className="input rg-p-input textarea"
|
||||
rows={4}
|
||||
placeholder={t(locale, 'sendTextPlaceholder')}
|
||||
value={text}
|
||||
@@ -44,10 +44,10 @@ export const SendTextDialog: React.FC<Props> = ({ locale, vmName, guestToolsConn
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
<button type="button" className="btn rg-p-button">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" disabled={!canSend} onClick={() => onConfirm(text)}>
|
||||
<button type="button" className="btn rg-p-button btn-primary" disabled={!canSend} onClick={() => onConfirm(text)}>
|
||||
{t(locale, 'sendTextConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
|
||||
@@ -211,7 +211,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
setVmPlugins(activeWithVM)
|
||||
setVmPluginVals((vals ?? {}) as Record<string, Record<string, unknown>>)
|
||||
})
|
||||
.catch(() => {})
|
||||
.catch((e) => console.warn('[settings] load VM plugin settings failed:', e))
|
||||
return () => { live = false }
|
||||
}, [driverID, detail.name])
|
||||
|
||||
@@ -325,7 +325,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
let active = true
|
||||
api.GetVMAffinityWithDriver(driverID, detail.name)
|
||||
.then((st) => { if (active) setAffinityStatus(st) })
|
||||
.catch(() => {})
|
||||
.catch((e) => console.warn('[settings] GetVMAffinityWithDriver failed:', e))
|
||||
return () => { active = false }
|
||||
}, [detail.name, running, affinityVersion])
|
||||
|
||||
@@ -894,7 +894,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
/>
|
||||
{customRes && (
|
||||
<input
|
||||
className="input mono res-input"
|
||||
className="input rg-p-input mono res-input"
|
||||
aria-label={tr('resolution')}
|
||||
placeholder={form.borderless ? '5120x2880' : '2560x1600'}
|
||||
autoFocus
|
||||
@@ -1070,7 +1070,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<input
|
||||
className="input mono input-compact"
|
||||
className="input rg-p-input mono input-compact"
|
||||
aria-label={tr('diskResizeTitle')}
|
||||
value={resizeInput}
|
||||
spellCheck={false}
|
||||
@@ -1440,7 +1440,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
/>
|
||||
{customLog && (
|
||||
<input
|
||||
className="input mono"
|
||||
className="input rg-p-input mono"
|
||||
aria-label={tr('logLevel')}
|
||||
placeholder="info,reims=debug"
|
||||
value={form.log_level ?? ''}
|
||||
@@ -1462,7 +1462,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
{...rowProps('extra_args')}
|
||||
title={tr('extraArgs')}
|
||||
desc={tr('extraArgsDesc')}
|
||||
block={<input className="input mono" aria-label={tr('extraArgs')} value={form.extra_args ?? ''} onChange={(e) => set({ extra_args: e.target.value })} />}
|
||||
block={<input className="input rg-p-input mono" aria-label={tr('extraArgs')} value={form.extra_args ?? ''} onChange={(e) => set({ extra_args: e.target.value })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
</>
|
||||
@@ -1490,7 +1490,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
className="nav-item"
|
||||
className="nav-item rg-p-nav-item"
|
||||
aria-current={cat === c.id ? 'page' : undefined}
|
||||
onClick={() => setCat(c.id)}
|
||||
>
|
||||
@@ -1568,7 +1568,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosSerial')}</span>
|
||||
<input
|
||||
className="input mono"
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={12}
|
||||
@@ -1586,7 +1586,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosMLB')}</span>
|
||||
<input
|
||||
className="input mono"
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={17}
|
||||
@@ -1604,7 +1604,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosUUID')}</span>
|
||||
<input
|
||||
className="input mono"
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={36}
|
||||
@@ -1650,7 +1650,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setConfirmRWFolder(null) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<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">
|
||||
@@ -1659,12 +1659,12 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{tr('cancel')}</button>
|
||||
<button type="button" className="btn rg-p-button">{tr('cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
className="btn rg-p-button btn-primary"
|
||||
onClick={() => {
|
||||
const target = confirmRWFolder
|
||||
setConfirmRWFolder(null)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FolderOpen, Globe, HardDrive } from 'lucide-react'
|
||||
import { FolderOpen, HardDrive } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
@@ -8,6 +8,7 @@ import { Button } from '../ui/controls'
|
||||
import { PopupSelect } from '../ui/settings'
|
||||
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
|
||||
import { api } from '../wails'
|
||||
import { PluginAppIcon } from './PluginAppIcon'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
|
||||
interface Props {
|
||||
@@ -62,13 +63,18 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
|
||||
const rec = l.find((c) => c.recommended) ?? l[0]
|
||||
if (rec) setSelected(rec.path)
|
||||
}).catch((e) => onError(tr('failGeneric'), e))
|
||||
api.SuggestLanguagePack().then((p) => { if (p?.entry) setLangPack(p) }).catch(() => {})
|
||||
api.SuggestLanguagePack().then((p) => { if (p?.entry) setLangPack(p) }).catch((e) => console.warn('[setup] SuggestLanguagePack failed:', e))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) { setCheck(null); return }
|
||||
let live = true
|
||||
api.CheckDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {})
|
||||
api.CheckDataRoot(selected)
|
||||
.then((c) => { if (live) setCheck(c) })
|
||||
.catch((e) => {
|
||||
if (live) setCheck(null)
|
||||
console.warn('[setup] CheckDataRoot failed:', e)
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [selected])
|
||||
|
||||
@@ -133,15 +139,15 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
|
||||
{choices.map((c) => option(c.path, (
|
||||
<>
|
||||
{tr('setupFree', { n: c.free_gb.toFixed(0) })}
|
||||
{c.recommended && <span className="badge badge-accent">{tr('setupRecommended')}</span>}
|
||||
{c.system && <span className="badge">{tr('setupSystem')}</span>}
|
||||
{c.external && <span className="badge badge-warn">{tr('setupExternal')}</span>}
|
||||
{c.recommended && <span className="badge rg-p-badge badge-accent">{tr('setupRecommended')}</span>}
|
||||
{c.system && <span className="badge rg-p-badge">{tr('setupSystem')}</span>}
|
||||
{c.external && <span className="badge rg-p-badge badge-warn">{tr('setupExternal')}</span>}
|
||||
</>
|
||||
)))}
|
||||
{customMode ? (
|
||||
<div className="input-group">
|
||||
<input
|
||||
className="input mono"
|
||||
className="input rg-p-input mono"
|
||||
aria-label={tr('setupOther')}
|
||||
value={custom}
|
||||
placeholder="D:\VMs\reims-go"
|
||||
@@ -167,7 +173,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
|
||||
{langPack && (
|
||||
<label className="setup-langpack">
|
||||
<input type="checkbox" checked={langPackOn} disabled={busy} onChange={(e) => setLangPackOn(e.target.checked)} />
|
||||
<span className="setup-langpack-icon"><Globe size={16} aria-hidden="true" /></span>
|
||||
<PluginAppIcon kind="locale" size="sm" />
|
||||
<span className="setup-langpack-main">
|
||||
{/* The pack's name and blurb in the OS language: that is who it is for. */}
|
||||
<span className="setup-langpack-title">
|
||||
@@ -227,7 +233,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
{host.whpx === 'missing' ? (
|
||||
<Button variant="primary" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
|
||||
) : (
|
||||
<span className={`badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
<span className={`badge rg-p-badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
{tr(whpxOK ? 'whpxReady' : host.whpx === 'no_hypervisor' ? 'whpxNoHvShort' : 'whpxUnsupportedShort')}
|
||||
</span>
|
||||
)}
|
||||
@@ -243,7 +249,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
{gpuHint && <div className="row-sub warn-text">{gpuHint}</div>}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
<span className={`badge rg-p-badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
|
||||
{tr(
|
||||
gpuOK
|
||||
? 'whpxReady'
|
||||
@@ -266,7 +272,7 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<span className={`badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
|
||||
<span className={`badge rg-p-badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Locale, VMListItem } from '../types'
|
||||
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 { VMAction } from './VMPage'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
@@ -78,13 +79,18 @@ export const Sidebar: React.FC<Props> = ({
|
||||
kind: ReturnType<typeof statusKind> | null,
|
||||
onDoubleClick?: () => void,
|
||||
dot?: boolean,
|
||||
vm?: { state: string; driver: string; busy: boolean },
|
||||
) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
role="option"
|
||||
data-id={id}
|
||||
className="nav-item"
|
||||
className="nav-item rg-p-nav-item"
|
||||
data-selected={selected === id ? 'true' : 'false'}
|
||||
data-vm-state={vm?.state}
|
||||
data-driver={vm?.driver}
|
||||
data-busy={vm ? (vm.busy ? 'true' : 'false') : undefined}
|
||||
aria-selected={selected === id}
|
||||
aria-label={stateLabel ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
|
||||
tabIndex={selected === id || (!hasSelectedInList && id === ids[0]) ? 0 : -1}
|
||||
@@ -99,6 +105,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
</Tip>
|
||||
)}
|
||||
{vm && <span className="rg-slot-anchor nav-item-trailing" data-rg-slot="nav.item.trailing" data-rg-key={id} aria-hidden="true" />}
|
||||
</button>
|
||||
)
|
||||
|
||||
@@ -106,16 +113,17 @@ export const Sidebar: React.FC<Props> = ({
|
||||
<div className="sidebar-wrap">
|
||||
<aside className="sidebar rg-p-sidebar">
|
||||
<div className="sidebar-brand">
|
||||
<img className="sidebar-brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
<BrandMark className="sidebar-brand-mark" />
|
||||
<span className="sidebar-brand-name">Reims-Go</span>
|
||||
</div>
|
||||
<div className="rg-slot-anchor" data-rg-slot="sidebar.header" />
|
||||
{updateCard}
|
||||
<div className="sidebar-head rg-p-sidebar-head">
|
||||
<span>{tr('sidebarVMs')}</span>
|
||||
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
|
||||
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<HostIcon name="new-vm"><Plus size={15} /></HostIcon>} onClick={onNew} tipSide="right" />
|
||||
</div>
|
||||
<div className="nav rg-p-nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
<div className="nav-group nav-vms" role="group" aria-label={tr('sidebarVMs')}>
|
||||
<div className="nav-group rg-p-nav-group nav-vms" role="group" aria-label={tr('sidebarVMs')}>
|
||||
{vms.length === 0 && <div className="nav-empty rg-p-empty" data-rg-slot="empty.state">{tr('emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const st = transitions[vmRefKey(vm)] ?? vm.state
|
||||
@@ -134,6 +142,8 @@ export const Sidebar: React.FC<Props> = ({
|
||||
t(locale, `state_${st}` as I18nKey),
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(vmRefKey(vm)) : undefined,
|
||||
undefined,
|
||||
{ state: st, driver: vm.driver_id ?? '', busy: vmBusy || transitioning },
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
@@ -148,7 +158,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
</Ctx.Trigger>
|
||||
<Ctx.Portal>
|
||||
<Ctx.Content
|
||||
className="menu"
|
||||
className="menu rg-p-menu"
|
||||
onCloseAutoFocus={(e) => {
|
||||
if (
|
||||
ctxOpenedByPointerRef.current
|
||||
@@ -159,68 +169,68 @@ export const Sidebar: React.FC<Props> = ({
|
||||
}}
|
||||
>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'start')}>
|
||||
<Play size={14} /> {tr('start')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'start')}>
|
||||
<HostIcon name="start"><Play size={14} /></HostIcon> {tr('start')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
{suspended && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vmRefKey(vm), 'resume')}>
|
||||
<Play size={14} /> {tr('resume')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vmRefKey(vm), 'resume')}>
|
||||
<HostIcon name="resume"><Play size={14} /></HostIcon> {tr('resume')}
|
||||
</Ctx.Item>
|
||||
{!canSuspend && <Ctx.Label className="menu-group-label">{tr('resumeUnavailable')}</Ctx.Label>}
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'discardSuspend')}>
|
||||
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'discardSuspend')}>
|
||||
<Power size={14} /> {tr('discardSuspend')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{running && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'focus')}>
|
||||
<AppWindow size={14} /> {tr('showWindow')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'focus')}>
|
||||
<HostIcon name="window"><AppWindow size={14} /></HostIcon> {tr('showWindow')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'fullscreen')}>
|
||||
<Maximize2 size={14} /> {tr('toggleFullscreen')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'fullscreen')}>
|
||||
<HostIcon name="fullscreen"><Maximize2 size={14} /></HostIcon> {tr('toggleFullscreen')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'screenshot')}>
|
||||
<HostIcon name="screenshot"><Camera size={14} /></HostIcon> {tr('copyScreenshot')}
|
||||
</Ctx.Item>
|
||||
{canSuspend && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'suspend')}>
|
||||
<Pause size={14} /> {tr('suspend')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'suspend')}>
|
||||
<HostIcon name="suspend"><Pause size={14} /></HostIcon> {tr('suspend')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'stop')}>
|
||||
<Square size={14} /> {tr('stop')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'stop')}>
|
||||
<HostIcon name="stop"><Square size={14} /></HostIcon> {tr('stop')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'restart')}>
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'restart')}>
|
||||
<HostIcon name="restart"><RotateCw size={14} /></HostIcon> {tr('restart')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Ctx.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vmRefKey(vm), 'forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vmRefKey(vm), 'forceStop')}>
|
||||
<HostIcon name="force-stop"><Power size={14} /></HostIcon> {tr('forceStop')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
|
||||
<Settings size={14} /> {tr('settingsEllipsis')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
|
||||
<HostIcon name="settings"><Settings size={14} /></HostIcon> {tr('settingsEllipsis')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openSharedFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openSharedFolder')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openSharedFolder')}>
|
||||
<HostIcon name="folder"><FolderOpen size={14} /></HostIcon> {tr('openSharedFolder')}
|
||||
</Ctx.Item>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'cloneVM')}>
|
||||
<HostIcon name="clone"><CopyPlus size={14} /></HostIcon> {tr('cloneVM')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openFolder')}>
|
||||
<HostIcon name="folder"><FolderOpen size={14} /></HostIcon> {tr('openFolder')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
<Ctx.Item className="menu-item rg-p-menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
|
||||
<HostIcon name="delete"><Trash size={14} /></HostIcon> {tr('delete')}
|
||||
</Ctx.Item>
|
||||
</Ctx.Content>
|
||||
</Ctx.Portal>
|
||||
@@ -228,7 +238,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="nav-group nav-system" role="group" aria-label={tr('sidebarSystem')}>
|
||||
<div className="nav-group rg-p-nav-group nav-system" role="group" aria-label={tr('sidebarSystem')}>
|
||||
{navBtn(
|
||||
INSTALLERS_ID,
|
||||
tr('sidebarInstallers'),
|
||||
@@ -240,7 +250,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
{navBtn(
|
||||
PLUGINS_ID,
|
||||
tr('sidebarPlugins'),
|
||||
<Puzzle size={13} />,
|
||||
<HostIcon name="plugin"><Puzzle size={13} /></HostIcon>,
|
||||
'nav-icon-plugins',
|
||||
safeMode ? tr('pluginSafeModeShort') : '',
|
||||
safeMode ? 'warn' : null,
|
||||
@@ -256,7 +266,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
{navBtn(
|
||||
SETTINGS_ID,
|
||||
tr('sidebarSettings'),
|
||||
<Settings size={13} />,
|
||||
<HostIcon name="settings"><Settings size={13} /></HostIcon>,
|
||||
'nav-icon-settings',
|
||||
'',
|
||||
null,
|
||||
@@ -264,7 +274,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
{navBtn(
|
||||
ABOUT_ID,
|
||||
tr('settingsAbout'),
|
||||
<Info size={13} />,
|
||||
<HostIcon name="info"><Info size={13} /></HostIcon>,
|
||||
'nav-icon-about',
|
||||
'',
|
||||
null,
|
||||
|
||||
@@ -74,13 +74,13 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
: tr('enterFullscreen')
|
||||
|
||||
const item = (label: string, onSelect: () => void, opts: { shortcut?: string; disabled?: boolean; danger?: boolean } = {}) => (
|
||||
<Menu.Item className={`menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
|
||||
<Menu.Item className={`menu-item rg-p-menu-item${opts.danger ? ' danger' : ''}`} disabled={opts.disabled} onSelect={onSelect}>
|
||||
<span className="menu-label">{label}</span>
|
||||
{opts.shortcut && <kbd className="menu-shortcut">{opts.shortcut}</kbd>}
|
||||
</Menu.Item>
|
||||
)
|
||||
const check = (label: string, checked: boolean, onSelect: () => void, shortcut?: string) => (
|
||||
<Menu.CheckboxItem className="menu-item menu-item-check" checked={checked} onSelect={onSelect}>
|
||||
<Menu.CheckboxItem className="menu-item rg-p-menu-item menu-item-check" checked={checked} onSelect={onSelect}>
|
||||
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
<span className="menu-label">{label}</span>
|
||||
{shortcut && <kbd className="menu-shortcut">{shortcut}</kbd>}
|
||||
@@ -146,7 +146,7 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content
|
||||
className={`menu titlebar-menu-content${indented ? ' menu-indented' : ''}`}
|
||||
className={`menu rg-p-menu titlebar-menu-content${indented ? ' menu-indented' : ''}`}
|
||||
data-menubar-switch={menuState.switched ? 'true' : undefined}
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
@@ -250,7 +250,7 @@ export const TitleMenus: React.FC<Props> = ({
|
||||
{(['light', 'dark', 'system'] as const).map((m) => (
|
||||
<Menu.RadioItem
|
||||
key={m}
|
||||
className="menu-item menu-item-check"
|
||||
className="menu-item rg-p-menu-item menu-item-check"
|
||||
value={m}
|
||||
disabled={(m === 'light' && !canLight) || (m === 'dark' && !canDark) || (m === 'system' && (!canLight || !canDark))}
|
||||
>
|
||||
|
||||
@@ -59,7 +59,11 @@ export function VMNetworkSettings({ name, locale, running, disabled, stagedDirty
|
||||
} catch (err) {
|
||||
setError(parseAppError(err))
|
||||
// 失败后读取实际状态;回滚未完成时保留修复入口。
|
||||
try { setState(await api.GetVMNetworkSettings(name)) } catch { /* 保留首个错误 */ }
|
||||
try {
|
||||
setState(await api.GetVMNetworkSettings(name))
|
||||
} catch (refreshError) {
|
||||
console.warn('[network] refresh settings after apply failure:', refreshError)
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
onBusy(false)
|
||||
|
||||
@@ -53,6 +53,7 @@ import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions,
|
||||
import { api } from '../wails'
|
||||
import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { Switch } from '../ui/settings'
|
||||
import { HostIcon } from '../ui/themeVisuals'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
|
||||
export type VMAction =
|
||||
@@ -146,10 +147,10 @@ function ShutdownButton({ locale, busyAction, onAction }: Pick<Props, 'locale' |
|
||||
</Button>
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content className="menu" align="end" sideOffset={4} collisionPadding={8}>
|
||||
<Menu.Content className="menu rg-p-menu" align="end" sideOffset={4} collisionPadding={8}>
|
||||
<Menu.RadioGroup value={mode} onValueChange={(v) => setMode(v === 'forceStop' ? 'forceStop' : 'stop')}>
|
||||
{(['stop', 'forceStop'] as const).map((action) => (
|
||||
<Menu.RadioItem key={action} value={action} className={`menu-item menu-item-check${action === 'forceStop' ? ' danger' : ''}`}>
|
||||
<Menu.RadioItem key={action} value={action} className={`menu-item rg-p-menu-item menu-item-check${action === 'forceStop' ? ' danger' : ''}`}>
|
||||
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
{t(locale, action)}
|
||||
</Menu.RadioItem>
|
||||
@@ -197,7 +198,9 @@ export const VMPage: React.FC<Props> = ({
|
||||
let live = true
|
||||
const pull = () => {
|
||||
if (document.hidden) return
|
||||
api.GetVMThumbnailWithDriver(driverID, name).then((t) => { if (live && t?.data_url) setThumb(t) }).catch(() => {})
|
||||
api.GetVMThumbnailWithDriver(driverID, name)
|
||||
.then((t) => { if (live && t?.data_url) setThumb(t) })
|
||||
.catch((e) => console.warn('[vm] GetVMThumbnailWithDriver failed:', e))
|
||||
}
|
||||
pull()
|
||||
const timer = running ? window.setInterval(pull, 15000) : undefined
|
||||
@@ -286,7 +289,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
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 {}
|
||||
try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch (e) { console.warn('[vm] persist guide progress failed:', e) }
|
||||
return next
|
||||
})
|
||||
}
|
||||
@@ -435,7 +438,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
<Menu.Trigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
className="icon-btn rg-p-icon-button"
|
||||
aria-label={tr('more')}
|
||||
onPointerDown={() => { moreOpenedByPointer.current = true }}
|
||||
onKeyDown={(e) => {
|
||||
@@ -450,7 +453,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
</Tip>
|
||||
<Menu.Portal>
|
||||
<Menu.Content
|
||||
className="menu"
|
||||
className="menu rg-p-menu"
|
||||
align="end"
|
||||
sideOffset={4}
|
||||
collisionPadding={8}
|
||||
@@ -480,23 +483,23 @@ export const VMPage: React.FC<Props> = ({
|
||||
{running && (
|
||||
<>
|
||||
{detail?.graphics !== 'vmware-svga' && (
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('fullscreen')}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('fullscreen')}>
|
||||
{stats?.window_fullscreen
|
||||
? <><Minimize2 size={14} /> {tr('exitFullscreen')}</>
|
||||
: <><Maximize2 size={14} /> {tr('enterFullscreen')}</>}
|
||||
</Menu.Item>
|
||||
)}
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('restart')}>
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('restart')}>
|
||||
<HostIcon name="restart"><RotateCw size={14} /></HostIcon> {tr('restart')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('sendText')}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('sendText')}>
|
||||
<Keyboard size={14} /> {tr('sendText')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('type')}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('type')}>
|
||||
<Keyboard size={14} /> {tr('typeClipboard')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('screenshot')}>
|
||||
<HostIcon name="screenshot"><Camera size={14} /></HostIcon> {tr('copyScreenshot')}
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
</>
|
||||
@@ -504,35 +507,35 @@ export const VMPage: React.FC<Props> = ({
|
||||
{detail && (
|
||||
<>
|
||||
{installing ? (
|
||||
<Menu.Item className="menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('finishInstall')}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('finishInstall')}>
|
||||
<LifeBuoy size={14} /> {tr('finishInstall')}
|
||||
</Menu.Item>
|
||||
) : (
|
||||
<>
|
||||
<Menu.Item className="menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('enterRecovery')}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('enterRecovery')}>
|
||||
<LifeBuoy size={14} /> {tr('enterRecovery')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" disabled={running || suspended || transitioning || busy} onSelect={() => onAction('cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={running || suspended || transitioning || busy} onSelect={() => onAction('cloneVM')}>
|
||||
<HostIcon name="clone"><CopyPlus size={14} /></HostIcon> {tr('cloneVM')}
|
||||
</Menu.Item>
|
||||
</>
|
||||
)}
|
||||
<Menu.Item className="menu-item" onSelect={onOpenAffinity}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={onOpenAffinity}>
|
||||
<Cpu size={14} /> {tr('affinityMenu')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" onSelect={() => { renameFromMenu.current = true; startRename() }}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => { renameFromMenu.current = true; startRename() }}>
|
||||
<Pencil size={14} /> {tr('displayNameEditEllipsis')}
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
</>
|
||||
)}
|
||||
<Menu.Item className="menu-item" onSelect={() => onAction('openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => onAction('openFolder')}>
|
||||
<HostIcon name="folder"><FolderOpen size={14} /></HostIcon> {tr('openFolder')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" onSelect={onViewLogs}>
|
||||
<Terminal size={14} /> {tr('viewLogs')}
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={onViewLogs}>
|
||||
<HostIcon name="logs"><Terminal size={14} /></HostIcon> {tr('viewLogs')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
|
||||
<Archive size={14} /> {tr('exportDiagnostics')}
|
||||
</Menu.Item>
|
||||
{(pluginUI?.menus ?? [])
|
||||
@@ -540,7 +543,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
.map((m) => (
|
||||
<Menu.Item
|
||||
key={`${m.pluginId}:${m.id}`}
|
||||
className="menu-item"
|
||||
className="menu-item rg-p-menu-item"
|
||||
onSelect={() => {
|
||||
void api.InvokePluginCommand(m.pluginId ?? '', m.command, { vm: name })
|
||||
.then(() => onToast(locText(m.title, locale, m.id)))
|
||||
@@ -552,17 +555,17 @@ export const VMPage: React.FC<Props> = ({
|
||||
))}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{suspended && (
|
||||
<Menu.Item className="menu-item danger" disabled={busy} onSelect={() => onAction('discardSuspend')}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item danger" disabled={busy} onSelect={() => onAction('discardSuspend')}>
|
||||
<Power size={14} /> {tr('discardSuspend')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Menu.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
<Menu.Item className="menu-item rg-p-menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
|
||||
<HostIcon name="force-stop"><Power size={14} /></HostIcon> {tr('forceStop')}
|
||||
</Menu.Item>
|
||||
)}
|
||||
<Menu.Item className="menu-item danger" disabled={running || suspended || transitioning || busy} onSelect={onDelete}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
<Menu.Item className="menu-item rg-p-menu-item danger" disabled={running || suspended || transitioning || busy} onSelect={onDelete}>
|
||||
<HostIcon name="delete"><Trash size={14} /></HostIcon> {tr('delete')}
|
||||
</Menu.Item>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
@@ -659,7 +662,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page vm-page vm-page-drop rg-p-vm-page" style={dropStyle}>
|
||||
<div className="page vm-page vm-page-drop rg-p-vm-page" data-vm-state={state} data-driver={driverID} style={dropStyle}>
|
||||
{dropping && (
|
||||
<div className="drop-banner" role="status" aria-live="polite">
|
||||
<Upload size={16} aria-hidden="true" />
|
||||
@@ -718,7 +721,8 @@ export const VMPage: React.FC<Props> = ({
|
||||
<span>{tr(`state_${state}` as I18nKey)}</span>
|
||||
{running && stats && stats.uptime_seconds > 0 && <span className="vm-hero-uptime">· {formatUptime(stats.uptime_seconds, locale)}</span>}
|
||||
</div>
|
||||
<div className="vm-hero-actions">
|
||||
<span className="rg-slot-anchor" data-rg-slot="vm.header.trailing" />
|
||||
<div className="vm-hero-actions rg-p-vm-actions">
|
||||
{primary}
|
||||
{secondary}
|
||||
<Tip label={suspended ? tr('suspendedSettingsHint') : tr('settings')} shortcut={suspended ? undefined : 'Ctrl+,'}>
|
||||
@@ -727,6 +731,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
</span>
|
||||
</Tip>
|
||||
{menu}
|
||||
<span className="rg-slot-anchor" data-rg-slot="vm.toolbar" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -852,10 +857,10 @@ export const VMPage: React.FC<Props> = ({
|
||||
: 'guideKindOnline'
|
||||
if (installGuideEnabled) {
|
||||
return (
|
||||
<section className="card" aria-labelledby="guide-title">
|
||||
<section className="card rg-p-card" aria-labelledby="guide-title">
|
||||
<h2 className="card-title" id="guide-title">
|
||||
{tr('guideTitle')}{' '}
|
||||
<span className="badge">{tr(badgeKey)}</span>
|
||||
<span className="badge rg-p-badge">{tr(badgeKey)}</span>
|
||||
</h2>
|
||||
<p className="card-desc">{tr('guideStartHint')}</p>
|
||||
<div className="card-foot">
|
||||
@@ -904,10 +909,10 @@ export const VMPage: React.FC<Props> = ({
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section className="card" aria-labelledby="guide-title">
|
||||
<section className="card rg-p-card" aria-labelledby="guide-title">
|
||||
<h2 className="card-title" id="guide-title">
|
||||
{tr('guideTitle')}{' '}
|
||||
<span className={`badge ${isOffline ? 'badge-ok' : ''}`}>{tr(badgeKey)}</span>
|
||||
<span className={`badge rg-p-badge ${isOffline ? 'badge-ok' : ''}`}>{tr(badgeKey)}</span>
|
||||
</h2>
|
||||
{!hasInstaller ? (
|
||||
<>
|
||||
@@ -1027,7 +1032,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
<Menu.Trigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn sm"
|
||||
className="icon-btn rg-p-icon-button sm"
|
||||
aria-label={tr('sshMore')}
|
||||
onPointerDown={() => { sshOpenedByPointer.current = true }}
|
||||
onKeyDown={(e) => {
|
||||
@@ -1042,7 +1047,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
</Tip>
|
||||
<Menu.Portal>
|
||||
<Menu.Content
|
||||
className="menu"
|
||||
className="menu rg-p-menu"
|
||||
align="end"
|
||||
sideOffset={4}
|
||||
collisionPadding={8}
|
||||
@@ -1063,14 +1068,14 @@ export const VMPage: React.FC<Props> = ({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Menu.Item className="menu-item" onSelect={writeSSHConfig}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={writeSSHConfig}>
|
||||
<FileCode2 size={14} /> {tr('sshWriteConfig')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item" onSelect={openVSCodeSSH}>
|
||||
<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" onSelect={() => { setSshUserDraft(sshUser); setSshUserDialog(true) }}>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => { setSshUserDraft(sshUser); setSshUserDialog(true) }}>
|
||||
<UserRound size={14} /> {tr('sshSetUser')}
|
||||
</Menu.Item>
|
||||
</Menu.Content>
|
||||
@@ -1159,7 +1164,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span className="hstack">
|
||||
<History size={14} aria-hidden="true" />
|
||||
<HostIcon name="snapshot"><History size={14} aria-hidden="true" /></HostIcon>
|
||||
<span>{tr('snapshotsTitle')}</span>
|
||||
<span className="snap-meta-hint">· {tr('snapshotHint')}</span>
|
||||
</span>
|
||||
@@ -1180,7 +1185,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
{creatingSnap && (
|
||||
<div className="snap-create-bar">
|
||||
<input
|
||||
className="input"
|
||||
className="input rg-p-input"
|
||||
value={snapDraft}
|
||||
maxLength={64}
|
||||
spellCheck={false}
|
||||
@@ -1275,13 +1280,13 @@ export const VMPage: React.FC<Props> = ({
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setSshUserDialog(false) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<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 mono"
|
||||
className="input rg-p-input mono"
|
||||
value={sshUserDraft}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
@@ -1293,9 +1298,9 @@ export const VMPage: React.FC<Props> = ({
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><button type="button" className="btn">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" onClick={() => void saveSSHUser()}>{tr('save')}</button>
|
||||
<button type="button" className="btn rg-p-button btn-primary" onClick={() => void saveSSHUser()}>{tr('save')}</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
@@ -1307,15 +1312,15 @@ export const VMPage: React.FC<Props> = ({
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setRestoreTarget(null) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<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">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-danger" onClick={() => void handleRestoreSnapshot(restoreTarget)}>
|
||||
<button type="button" className="btn rg-p-button btn-danger" onClick={() => void handleRestoreSnapshot(restoreTarget)}>
|
||||
{tr('snapshotRestore')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
|
||||
@@ -133,7 +133,7 @@ export const coreZh: Record<string, string> = {
|
||||
"showSidebar": "显示侧边栏",
|
||||
"shutdownMode": "关机方式",
|
||||
"sidebarHost": "内核",
|
||||
"sidebarInstallers": "安装包",
|
||||
"sidebarInstallers": "镜像",
|
||||
"sidebarItemAria": "{label},{state}",
|
||||
"sidebarLabel": "侧边栏",
|
||||
"sidebarPlugins": "插件",
|
||||
@@ -325,7 +325,7 @@ export const coreEn: Record<string, string> = {
|
||||
"showSidebar": "Show sidebar",
|
||||
"shutdownMode": "Shutdown mode",
|
||||
"sidebarHost": "Engine",
|
||||
"sidebarInstallers": "Installers",
|
||||
"sidebarInstallers": "Images",
|
||||
"sidebarItemAria": "{label}, {state}",
|
||||
"sidebarLabel": "Sidebar",
|
||||
"sidebarPlugins": "Plugins",
|
||||
|
||||
@@ -260,6 +260,10 @@ export const settingsZh: Record<string, string> = {
|
||||
"hostRAMTotal": "共 {n} GB",
|
||||
"hostRuntime": "运行时",
|
||||
"hostWHPX": "Windows 虚拟机监控程序平台",
|
||||
"imagesNoSourcesDesc": "请在「插件」页面启用至少一个镜像源插件(例如 macOS 镜像源)以浏览和下载系统镜像。",
|
||||
"imagesNoSourcesTitle": "未启用镜像源插件",
|
||||
"imagesOpenPlugins": "前往插件",
|
||||
"imagesSourcesLabel": "镜像来源",
|
||||
"installersAvailable": "Apple 提供的版本",
|
||||
"installersCreateVM": "新建虚拟机",
|
||||
"installersDelete": "删除",
|
||||
@@ -268,8 +272,8 @@ export const settingsZh: Record<string, string> = {
|
||||
"installersDownloaded": "已下载",
|
||||
"installersDownloadingForVM": "为 {vm} 下载中",
|
||||
"installersDownloadingPct": "下载中 {p}%",
|
||||
"installersEmpty": "还没有下载任何安装包",
|
||||
"installersHint": "下载好的安装包可以重复用来新建虚拟机",
|
||||
"installersEmpty": "还没有下载任何镜像",
|
||||
"installersHint": "下载好的镜像可以重复用来新建虚拟机",
|
||||
"installersKindOffline": "离线完整包",
|
||||
"installersKindOnline": "在线恢复镜像",
|
||||
"installersLatest": "最新",
|
||||
@@ -279,7 +283,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"installersQueued": "排队中",
|
||||
"installersQueuedForVM": "为 {vm} 排队中",
|
||||
"installersResume": "继续下载",
|
||||
"installersTitle": "安装包",
|
||||
"installersTitle": "镜像",
|
||||
"installersWaitingVM": "{vm} 等待使用",
|
||||
"kernelIrqchipAuto": "自动",
|
||||
"kernelIrqchipLabel": "中断加速",
|
||||
@@ -320,6 +324,8 @@ export const settingsZh: Record<string, string> = {
|
||||
"logLevel": "日志级别",
|
||||
"logLevelCustom": "自定义",
|
||||
"logLevelDesc": "排查问题时再调高",
|
||||
"macosSlaButton": "查看许可协议",
|
||||
"macosSlaNotice": "使用此软件必须接受软件附带的原始许可协议。",
|
||||
"macosVersion": "macOS 版本",
|
||||
"memCommitHint": "Windows 还能分配 {avail} GB · 推荐 {rec} GB",
|
||||
"memOverHint": "超过推荐值,启动时可能分配失败",
|
||||
@@ -415,7 +421,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"stopTimeout": "关机等待时间",
|
||||
"stopTimeoutHint": "0 表示一直等待",
|
||||
"storageBreakdownTitle": "空间分布",
|
||||
"storageInstallers": "安装包",
|
||||
"storageInstallers": "镜像",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "虚拟机文件",
|
||||
"syncHostMemorySMBIOS": "同步宿主机内存规格",
|
||||
@@ -705,6 +711,10 @@ export const settingsEn: Record<string, string> = {
|
||||
"hostRAMTotal": "{n} GB total",
|
||||
"hostRuntime": "Runtime",
|
||||
"hostWHPX": "Windows Hypervisor Platform",
|
||||
"imagesNoSourcesDesc": "Enable at least one image source plugin (such as macOS Images) in Plugins to browse and download system images.",
|
||||
"imagesNoSourcesTitle": "No image source plugins enabled",
|
||||
"imagesOpenPlugins": "Open Plugins",
|
||||
"imagesSourcesLabel": "Image sources",
|
||||
"installersAvailable": "Releases from Apple",
|
||||
"installersCreateVM": "Create VM",
|
||||
"installersDelete": "Delete",
|
||||
@@ -713,8 +723,8 @@ export const settingsEn: Record<string, string> = {
|
||||
"installersDownloaded": "Downloaded",
|
||||
"installersDownloadingForVM": "Downloading for {vm}",
|
||||
"installersDownloadingPct": "Downloading {p}%",
|
||||
"installersEmpty": "No installers downloaded yet",
|
||||
"installersHint": "Downloaded installers can be reused for new VMs",
|
||||
"installersEmpty": "No images downloaded yet",
|
||||
"installersHint": "Downloaded images can be reused for new VMs",
|
||||
"installersKindOffline": "Offline installer",
|
||||
"installersKindOnline": "Online recovery",
|
||||
"installersLatest": "Latest",
|
||||
@@ -724,7 +734,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"installersQueued": "Queued",
|
||||
"installersQueuedForVM": "Queued for {vm}",
|
||||
"installersResume": "Resume",
|
||||
"installersTitle": "Installers",
|
||||
"installersTitle": "Images",
|
||||
"installersWaitingVM": "{vm} waiting",
|
||||
"kernelIrqchipAuto": "Auto",
|
||||
"kernelIrqchipLabel": "Interrupt acceleration",
|
||||
@@ -765,6 +775,8 @@ export const settingsEn: Record<string, string> = {
|
||||
"logLevel": "Log level",
|
||||
"logLevelCustom": "Custom",
|
||||
"logLevelDesc": "Raise only when troubleshooting",
|
||||
"macosSlaButton": "View SLA",
|
||||
"macosSlaNotice": "Use of this software requires acceptance of the original license agreement included with the software.",
|
||||
"macosVersion": "macOS version",
|
||||
"memCommitHint": "Windows can allocate {avail} GB more · {rec} GB recommended",
|
||||
"memOverHint": "Above the recommendation; the VM may fail to start",
|
||||
@@ -860,7 +872,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"stopTimeout": "Shutdown timeout",
|
||||
"stopTimeoutHint": "0 waits indefinitely",
|
||||
"storageBreakdownTitle": "Storage breakdown",
|
||||
"storageInstallers": "Installers",
|
||||
"storageInstallers": "Images",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "VM files",
|
||||
"syncHostMemorySMBIOS": "Sync host memory specs",
|
||||
|
||||
@@ -441,6 +441,10 @@ export type I18nKey =
|
||||
| "hostReady"
|
||||
| "hostRuntime"
|
||||
| "hostWHPX"
|
||||
| "imagesNoSourcesDesc"
|
||||
| "imagesNoSourcesTitle"
|
||||
| "imagesOpenPlugins"
|
||||
| "imagesSourcesLabel"
|
||||
| "importRuntime"
|
||||
| "installersAvailable"
|
||||
| "installersCreateVM"
|
||||
@@ -529,6 +533,8 @@ export type I18nKey =
|
||||
| "macos.showAllDevices"
|
||||
| "macos.utilitiesTerminal"
|
||||
| "macos.volume"
|
||||
| "macosSlaButton"
|
||||
| "macosSlaNotice"
|
||||
| "macosVersion"
|
||||
| "maximize"
|
||||
| "memCommitHint"
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// declarative state-driven slot decorations.
|
||||
// - Tier 3 (Interactive theme): lazy-loads `./uiSdk` only when a trusted `ui_script_url` is active.
|
||||
|
||||
import { UI_CONTRACT_TOKENS } from '../styles/ui-contract'
|
||||
import { UI_CONTRACT_LAYOUT_OPTIONS, UI_CONTRACT_TOKENS, type UIContractSDKEvent } from '../styles/ui-contract'
|
||||
import type { ActiveThemePayload, ThemeDecoration, ThemeDecorationState, TokenDeriveRule } from '../types'
|
||||
|
||||
const LEGACY_CACHE_KEY = 'reims-go-theme-tokens-v1'
|
||||
@@ -55,6 +55,16 @@ export interface ThemeSDKHostActions {
|
||||
let activeUIScriptCleanup: (() => void) | null = null
|
||||
let activeUIScriptNotifier: ((snap: UIStateSnapshot) => void) | null = null
|
||||
let activeUIScriptURL = ''
|
||||
let activeUIScriptEventSink: ((event: string, data: unknown) => void) | null = null
|
||||
|
||||
/**
|
||||
* Forwards a host event to the interactive theme's `sdk.on` handlers. A no-op
|
||||
* unless an interactive theme is loaded; payloads carry no paths or secrets.
|
||||
*/
|
||||
export function emitThemeEvent(event: UIContractSDKEvent, data: unknown): void {
|
||||
if (!activeUIScriptEventSink) return
|
||||
try { activeUIScriptEventSink(event, data) } catch (e) { console.warn('[theme] UI script event handler failed:', event, e) }
|
||||
}
|
||||
let applyGeneration = 0
|
||||
|
||||
function decodeCSSEscapes(s: string): string {
|
||||
@@ -109,6 +119,34 @@ function sanitizeRelativeAssetPath(rel: string): string | null {
|
||||
return cleaned
|
||||
}
|
||||
|
||||
/** Resolves a theme package asset to its served URL, or null when unsafe. */
|
||||
export function themeAssetURL(payload: ActiveThemePayload | null, rel: string | undefined): string | null {
|
||||
if (!payload || !rel) return null
|
||||
const rawBaseURL = payload.asset_base_url ?? ''
|
||||
if (!RE_ASSET_BASE_URL.test(rawBaseURL) || rawBaseURL.includes('..')) return null
|
||||
const safe = sanitizeRelativeAssetPath(rel)
|
||||
return safe ? rawBaseURL + safe : null
|
||||
}
|
||||
|
||||
// Theme `layout` option → <html> attribute (ui-contract UI_CONTRACT_LAYOUT_OPTIONS).
|
||||
const LAYOUT_ATTRS: Record<string, string> = {
|
||||
sidebarPosition: 'data-layout-sidebar',
|
||||
sidebarMode: 'data-layout-sidebar-mode',
|
||||
density: 'data-layout-density',
|
||||
titlebar: 'data-layout-titlebar',
|
||||
}
|
||||
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 {
|
||||
const el = document.documentElement
|
||||
for (const [option, attr] of Object.entries(LAYOUT_ATTRS)) {
|
||||
const value = layout?.[option]
|
||||
if (typeof value === 'string' && ALLOWED_LAYOUT.has(`${option}=${value}`)) el.setAttribute(attr, value)
|
||||
else el.removeAttribute(attr)
|
||||
}
|
||||
}
|
||||
|
||||
/** Verifies stylesheet has balanced braces and no unclosed strings/comments so it cannot escape `@layer theme` (B5). */
|
||||
export function isBalancedThemeCSS(css: string): boolean {
|
||||
if (css.toLowerCase().includes('</style')) return false
|
||||
@@ -162,8 +200,8 @@ function resolveInitialAppearance(): 'light' | 'dark' {
|
||||
try {
|
||||
const saved = localStorage.getItem('reims-go-theme')
|
||||
if (saved === 'dark' || saved === 'light') return saved
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
} catch (e) {
|
||||
console.warn('[theme] read theme preference failed:', e)
|
||||
}
|
||||
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||
}
|
||||
@@ -180,8 +218,8 @@ function clearLegacyInlineCache(): void {
|
||||
}
|
||||
localStorage.removeItem(LEGACY_CACHE_KEY)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} catch (e) {
|
||||
console.warn('[theme] clear legacy inline cache failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,8 +255,8 @@ export function applyCachedThemeTokensSync(): void {
|
||||
document.head.appendChild(el)
|
||||
}
|
||||
el.textContent = `@layer theme {\n:root {\n${varLines}\n}\n}`
|
||||
} catch {
|
||||
// ignore corrupt cache
|
||||
} catch (e) {
|
||||
console.warn('[theme] apply cached theme tokens failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,8 +267,8 @@ function clearDynamicThemeStyles(): void {
|
||||
clearLegacyInlineCache()
|
||||
try {
|
||||
localStorage.removeItem(THEME_CACHE_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
} catch (e) {
|
||||
console.warn('[theme] clear theme token cache failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,7 +474,7 @@ export async function applyActiveTheme(
|
||||
// Always tear down previous interactive theme script if URL changed or disabled.
|
||||
const nextScriptURL = payload?.ui_script_url ?? ''
|
||||
if (activeUIScriptCleanup && activeUIScriptURL !== nextScriptURL) {
|
||||
try { activeUIScriptCleanup() } catch {}
|
||||
try { activeUIScriptCleanup() } catch (e) { console.warn('[theme] UI script cleanup failed:', e) }
|
||||
activeUIScriptCleanup = null
|
||||
activeUIScriptURL = ''
|
||||
}
|
||||
@@ -444,10 +482,12 @@ export async function applyActiveTheme(
|
||||
// Builtin default theme (or safe mode) -> zero extra CSS injected (§8.1).
|
||||
if (!payload || !payload.theme || payload.theme_id === 'builtin.theme.default') {
|
||||
clearDynamicThemeStyles()
|
||||
applyThemeLayout(null)
|
||||
return
|
||||
}
|
||||
|
||||
const th = payload.theme
|
||||
applyThemeLayout(th.layout as Record<string, unknown> | undefined)
|
||||
const rawBaseURL = payload.asset_base_url ?? ''
|
||||
const baseURL = RE_ASSET_BASE_URL.test(rawBaseURL) && !rawBaseURL.includes('..') ? rawBaseURL : ''
|
||||
|
||||
@@ -532,25 +572,27 @@ export async function applyActiveTheme(
|
||||
}
|
||||
nextCache[appearance] = sanitizedTokens
|
||||
localStorage.setItem(THEME_CACHE_KEY, JSON.stringify(nextCache))
|
||||
} catch {
|
||||
// ignore storage quota
|
||||
} catch (e) {
|
||||
console.warn('[theme] persist theme token cache failed:', e)
|
||||
}
|
||||
|
||||
// 5. Tier 3: lazy-load UI SDK ONLY when an approved interactive theme script is present (§8.1).
|
||||
if (nextScriptURL && nextScriptURL !== activeUIScriptURL) {
|
||||
try {
|
||||
const { mountInteractiveThemeScript, notifyThemeSDKState } = await import('./uiSdk')
|
||||
const { mountInteractiveThemeScript, notifyThemeSDKState, emitThemeSDKEvent } = await import('./uiSdk')
|
||||
if (gen !== applyGeneration) return
|
||||
const cleanup = await mountInteractiveThemeScript(nextScriptURL, getState, actions)
|
||||
if (gen !== applyGeneration) {
|
||||
try { cleanup() } catch {}
|
||||
try { cleanup() } catch (e) { console.warn('[theme] stale UI script cleanup failed:', e) }
|
||||
return
|
||||
}
|
||||
activeUIScriptCleanup = () => {
|
||||
activeUIScriptNotifier = null
|
||||
activeUIScriptEventSink = null
|
||||
cleanup()
|
||||
}
|
||||
activeUIScriptNotifier = notifyThemeSDKState
|
||||
activeUIScriptEventSink = emitThemeSDKEvent
|
||||
activeUIScriptURL = nextScriptURL
|
||||
} catch {
|
||||
if (gen === applyGeneration) {
|
||||
@@ -610,7 +652,7 @@ export function applyActiveLocaleFonts(
|
||||
/** Tears down injected theme/locale style nodes and active UI scripts on unmount. */
|
||||
export function disposeActiveThemeAndLocaleFonts(): void {
|
||||
if (activeUIScriptCleanup) {
|
||||
try { activeUIScriptCleanup() } catch {}
|
||||
try { activeUIScriptCleanup() } catch (e) { console.warn('[theme] dispose UI script cleanup failed:', e) }
|
||||
activeUIScriptCleanup = null
|
||||
activeUIScriptNotifier = null
|
||||
activeUIScriptURL = ''
|
||||
@@ -632,8 +674,8 @@ export function playThemeSound(payload: ActiveThemePayload | null, eventName: st
|
||||
try {
|
||||
const audio = new Audio(payload.asset_base_url + safe)
|
||||
audio.volume = 0.35
|
||||
void audio.play().catch(() => {})
|
||||
} catch {
|
||||
// ignore audio decode/autoplay errors
|
||||
void audio.play().catch((e) => console.warn('[theme] sound playback failed:', eventName, e))
|
||||
} catch (e) {
|
||||
console.warn('[theme] sound init failed:', eventName, e)
|
||||
}
|
||||
}
|
||||
+74
-15
@@ -1,7 +1,10 @@
|
||||
// Lazy-loaded Tier-3 Interactive Theme UI SDK (docs/plugin-architecture.md §5.1).
|
||||
// Loaded ONLY when a trusted interactive theme with `ui:script` is enabled (§8.1).
|
||||
|
||||
import { UI_API_VERSION, UI_CONTRACT_FEATURES, UI_CONTRACT_PARTS, UI_CONTRACT_SLOTS, type UIContractPart, type UIContractSlot } from '../styles/ui-contract'
|
||||
import {
|
||||
UI_API_VERSION, UI_CONTRACT_FEATURES, UI_CONTRACT_LAYERS, UI_CONTRACT_PARTS, UI_CONTRACT_SDK_EVENTS, UI_CONTRACT_SLOTS,
|
||||
type UIContractLayer, type UIContractPart, type UIContractSDKEvent, type UIContractSlot,
|
||||
} from '../styles/ui-contract'
|
||||
import { hideWailsGlobals } from '../wails'
|
||||
import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine'
|
||||
|
||||
@@ -18,23 +21,44 @@ export interface ReimsUISDK {
|
||||
subscribeState: (cb: (snap: UIStateSnapshot) => void) => () => void
|
||||
/** Queries elements strictly by contract part class (`rg-p-*`). */
|
||||
queryPart: (part: UIContractPart) => HTMLElement | null
|
||||
/** All elements of a repeated part (e.g. `rg-p-nav-item`), in document order. */
|
||||
queryParts: (part: UIContractPart) => HTMLElement[]
|
||||
/** Shared MutationObserver bus scoped to a contract part. */
|
||||
observePart: (part: UIContractPart, cb: () => void) => () => void
|
||||
/** Shared RAF read/write batch pipeline to avoid layout thrashing. */
|
||||
scheduleRead: (fn: () => void) => void
|
||||
scheduleWrite: (fn: () => void) => void
|
||||
/** Framework-agnostic DOM mounting into a declared slot anchor. */
|
||||
mountSlot: (slot: UIContractSlot, node: HTMLElement) => () => void
|
||||
/**
|
||||
* Framework-agnostic DOM mounting into a declared slot anchor. Repeated slots
|
||||
* (`nav.item.trailing`) take the item key from `slotKeys`.
|
||||
*/
|
||||
mountSlot: (slot: UIContractSlot, node: HTMLElement, key?: string) => () => void
|
||||
/** Keys of the currently rendered instances of a repeated slot (VM references). */
|
||||
slotKeys: (slot: UIContractSlot) => string[]
|
||||
/** Mounts into a full-window layer (`layer.background` / `layer.overlay`). */
|
||||
mountLayer: (layer: UIContractLayer, node: HTMLElement) => () => void
|
||||
/** Subscribes to a host event (VM state, tasks, toasts, view changes). */
|
||||
on: (event: UIContractSDKEvent, cb: (data: unknown) => void) => () => void
|
||||
/** Restricted non-destructive UI actions only (no start/stop/delete/config write). */
|
||||
actions: ThemeSDKHostActions
|
||||
}
|
||||
|
||||
const stateListeners = new Set<(snap: UIStateSnapshot) => void>()
|
||||
const eventListeners = new Map<string, Set<(data: unknown) => void>>()
|
||||
|
||||
/** Delivers a host event to subscribed theme handlers (themeEngine.emitThemeEvent). */
|
||||
export function emitThemeSDKEvent(event: string, data: unknown): void {
|
||||
const set = eventListeners.get(event)
|
||||
if (!set) return
|
||||
for (const cb of set) {
|
||||
try { cb(data) } catch (e) { console.warn('[uiSdk] event listener failed:', event, e) }
|
||||
}
|
||||
}
|
||||
|
||||
export function notifyThemeSDKState(snap: UIStateSnapshot): void {
|
||||
if (stateListeners.size === 0) return
|
||||
for (const cb of stateListeners) {
|
||||
try { cb(snap) } catch {}
|
||||
try { cb(snap) } catch (e) { console.warn('[uiSdk] state listener failed:', e) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,8 +73,8 @@ function flushFrame() {
|
||||
const writes = writeQueue
|
||||
readQueue = []
|
||||
writeQueue = []
|
||||
for (const r of reads) { try { r() } catch {} }
|
||||
for (const w of writes) { try { w() } catch {} }
|
||||
for (const r of reads) { try { r() } catch (e) { console.warn('[uiSdk] scheduled read failed:', e) } }
|
||||
for (const w of writes) { try { w() } catch (e) { console.warn('[uiSdk] scheduled write failed:', e) } }
|
||||
}
|
||||
|
||||
function scheduleRAF() {
|
||||
@@ -71,19 +95,32 @@ export async function mountInteractiveThemeScript(
|
||||
const disposers = new Set<() => void>()
|
||||
const partSet = new Set<string>(UI_CONTRACT_PARTS)
|
||||
const slotSet = new Set<string>(UI_CONTRACT_SLOTS)
|
||||
const layerSet = new Set<string>(UI_CONTRACT_LAYERS)
|
||||
const eventSet = new Set<string>(UI_CONTRACT_SDK_EVENTS)
|
||||
|
||||
const addDisposer = (fn: () => void) => {
|
||||
if (disposed) return
|
||||
disposers.add(fn)
|
||||
}
|
||||
|
||||
const mountInto = (host: HTMLElement | null, node: HTMLElement) => {
|
||||
if (disposed || !host) return () => {}
|
||||
host.appendChild(node)
|
||||
const off = () => {
|
||||
node.remove()
|
||||
disposers.delete(off)
|
||||
}
|
||||
addDisposer(off)
|
||||
return off
|
||||
}
|
||||
|
||||
const disposeAll = () => {
|
||||
if (disposed) return
|
||||
disposed = true
|
||||
const list = Array.from(disposers).reverse()
|
||||
disposers.clear()
|
||||
for (const fn of list) {
|
||||
try { fn() } catch {}
|
||||
try { fn() } catch (e) { console.warn('[uiSdk] disposer failed:', e) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +133,7 @@ export async function mountInteractiveThemeScript(
|
||||
const localDisposers: Array<() => void> = []
|
||||
const localDispose = () => {
|
||||
while (localDisposers.length > 0) {
|
||||
try { localDisposers.pop()?.() } catch {}
|
||||
try { localDisposers.pop()?.() } catch (e) { console.warn('[uiSdk] feature disposer failed:', e) }
|
||||
}
|
||||
}
|
||||
addDisposer(localDispose)
|
||||
@@ -125,13 +162,17 @@ export async function mountInteractiveThemeScript(
|
||||
if (disposed || !partSet.has(part)) return null
|
||||
return document.querySelector<HTMLElement>(`.${part}`)
|
||||
},
|
||||
queryParts: (part) => {
|
||||
if (disposed || !partSet.has(part)) return []
|
||||
return Array.from(document.querySelectorAll<HTMLElement>(`.${part}`))
|
||||
},
|
||||
observePart: (part, cb) => {
|
||||
if (disposed || !partSet.has(part)) return () => {}
|
||||
const target = document.querySelector<HTMLElement>(`.${part}`)
|
||||
if (!target) return () => {}
|
||||
const obs = new MutationObserver(() => {
|
||||
if (disposed) return
|
||||
try { cb() } catch {}
|
||||
try { cb() } catch (e) { console.warn('[uiSdk] part observer failed:', part, e) }
|
||||
})
|
||||
obs.observe(target, { attributes: true, childList: true, subtree: false })
|
||||
const off = () => {
|
||||
@@ -151,13 +192,31 @@ export async function mountInteractiveThemeScript(
|
||||
writeQueue.push(() => { if (!disposed) fn() })
|
||||
scheduleRAF()
|
||||
},
|
||||
mountSlot: (slot, node) => {
|
||||
if (disposed || !slotSet.has(slot)) return () => {}
|
||||
const host = document.querySelector<HTMLElement>(`[data-rg-slot="${CSS.escape(slot)}"]`)
|
||||
if (!host) return () => {}
|
||||
host.appendChild(node)
|
||||
mountSlot: (slot, node, key) => {
|
||||
if (!slotSet.has(slot)) return () => {}
|
||||
const sel = `[data-rg-slot="${CSS.escape(slot)}"]` + (key ? `[data-rg-key="${CSS.escape(key)}"]` : '')
|
||||
return mountInto(document.querySelector<HTMLElement>(sel), node)
|
||||
},
|
||||
slotKeys: (slot) => {
|
||||
if (disposed || !slotSet.has(slot)) return []
|
||||
return Array.from(document.querySelectorAll<HTMLElement>(`[data-rg-slot="${CSS.escape(slot)}"][data-rg-key]`))
|
||||
.map((el) => el.dataset.rgKey ?? '')
|
||||
.filter(Boolean)
|
||||
},
|
||||
mountLayer: (layer, node) => {
|
||||
if (!layerSet.has(layer)) return () => {}
|
||||
return mountInto(document.querySelector<HTMLElement>(`[data-rg-layer="${CSS.escape(layer)}"]`), node)
|
||||
},
|
||||
on: (event, cb) => {
|
||||
if (disposed || !eventSet.has(event)) return () => {}
|
||||
let set = eventListeners.get(event)
|
||||
if (!set) {
|
||||
set = new Set()
|
||||
eventListeners.set(event, set)
|
||||
}
|
||||
set.add(cb)
|
||||
const off = () => {
|
||||
node.remove()
|
||||
eventListeners.get(event)?.delete(cb)
|
||||
disposers.delete(off)
|
||||
}
|
||||
addDisposer(off)
|
||||
|
||||
@@ -28,7 +28,7 @@ function sample(key: string, driverID: string, name: string, entryRef: Entry) {
|
||||
entryRef.last = s
|
||||
entryRef.subs.forEach((f) => f(s))
|
||||
})
|
||||
.catch(() => {})
|
||||
.catch((e) => console.warn('[vmStats] GetVMStatsWithDriver failed:', key, e))
|
||||
}
|
||||
|
||||
function schedule(key: string, driverID: string, name: string, e: Entry) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { AlertTriangle, Check, ChevronDown, Clock, Download, LoaderCircle, Pause, Plus, RefreshCw, Trash, X } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { AlertTriangle, Check, ChevronDown, Clock, Download, ExternalLink, Info, LoaderCircle, Pause, Plus, Trash, X } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { WordmarkLoader } from '../components/WordmarkLoader'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { macOSMajor } from './macosRelease'
|
||||
import {
|
||||
@@ -23,10 +24,14 @@ import { Button, IconButton } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
import { VersionArt } from './VersionArt'
|
||||
|
||||
const APPLE_SLA_URL = 'https://www.apple.com/legal/sla'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
tasks: Task[]
|
||||
refreshSignal?: number
|
||||
onBusyChange?: (busy: boolean) => void
|
||||
onCreateWithInstaller: (item: CachedInstaller) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
onToast: (title: string) => void
|
||||
@@ -71,13 +76,18 @@ function formatOnlineTitle(version: string): string {
|
||||
return `macOS ${words.join(' ')}`
|
||||
}
|
||||
|
||||
/** Offline installers (roadmap M2.2): what is downloaded, and Apple's releases to download. */
|
||||
export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateWithInstaller, onError, onToast }) => {
|
||||
/** macOS image source view provided by the built-in `builtin.images.macos` plugin. */
|
||||
export const InstallersPage: React.FC<Props> = ({
|
||||
locale, host, tasks, refreshSignal = 0, onBusyChange, onCreateWithInstaller, onError, onToast,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [cached, setCached] = useState<CachedInstaller[] | null>(null)
|
||||
const [releases, setReleases] = useState<Release[] | null>(null)
|
||||
const [releasesErr, setReleasesErr] = useState('')
|
||||
const [confirmDelete, setConfirmDelete] = useState('')
|
||||
const lastRefreshRef = useRef(refreshSignal)
|
||||
const onBusyChangeRef = useRef(onBusyChange)
|
||||
onBusyChangeRef.current = onBusyChange
|
||||
|
||||
const installerTasks = tasks.filter(isInstallerTask)
|
||||
const activeInstallerTasks = installerTasks.filter(isActiveInstallerTask)
|
||||
@@ -95,12 +105,28 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
.catch((e) => setReleasesErr(String(e).replace(/^Error:\s*/, '')))
|
||||
}
|
||||
useEffect(() => { loadReleases() }, [])
|
||||
useEffect(() => {
|
||||
if (refreshSignal !== lastRefreshRef.current) {
|
||||
lastRefreshRef.current = refreshSignal
|
||||
loadCached()
|
||||
loadReleases()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [refreshSignal])
|
||||
useEffect(() => {
|
||||
onBusyChangeRef.current?.(releases === null && !releasesErr)
|
||||
}, [releases, releasesErr])
|
||||
useEffect(() => () => { onBusyChangeRef.current?.(false) }, [])
|
||||
// Refresh the downloaded list whenever an installer download starts, shifts phase, or ends.
|
||||
useEffect(() => {
|
||||
setConfirmDelete('')
|
||||
loadCached()
|
||||
}, [installerTasksSig])
|
||||
|
||||
const openSLA = () => {
|
||||
api.OpenURL(APPLE_SLA_URL).catch((e) => onError(tr('failGeneric'), e))
|
||||
}
|
||||
|
||||
const downloaded = (version: string) => (cached ?? []).find((c) => c.kind === 'offline' && !c.partial && c.version === version)
|
||||
const partial = (version: string) => (cached ?? []).some((c) => c.kind === 'offline' && c.partial && c.version === version)
|
||||
const activeForRelease = (version: string) => findActiveOfflineTask(activeInstallerTasks, version)
|
||||
@@ -138,7 +164,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
<span className="task-inline row-sub">
|
||||
<LoaderCircle size={14} className="spin" aria-hidden="true" />
|
||||
{task.percent >= 0 && (
|
||||
<span className="progress" aria-hidden="true">
|
||||
<span className="progress rg-p-progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
|
||||
</span>
|
||||
)}
|
||||
@@ -147,20 +173,6 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
)
|
||||
}
|
||||
|
||||
const skeleton = (rows: number, label?: string) => (
|
||||
<div className="skeleton-list" role="status" aria-label={label}>
|
||||
{Array.from({ length: rows }).map((_, i) => (
|
||||
<div className="skeleton-row" key={i} aria-hidden="true">
|
||||
<div className="skeleton-stack">
|
||||
<div className="skeleton-bar w-title" />
|
||||
<div className="skeleton-bar w-sub" />
|
||||
</div>
|
||||
<div className="skeleton-bar w-btn" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
const spaceShort = (r: Release) => !downloaded(r.version) && !activeForRelease(r.version) && host.free_disk_gb > 0 && host.free_disk_gb * 1e9 < needBytes(r)
|
||||
|
||||
const releaseAction = (r: Release) => {
|
||||
@@ -169,10 +181,10 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
const task = active.primary
|
||||
const queued = taskInstallerPhase(task) === 'queued'
|
||||
if (queued) {
|
||||
return <span className="badge" role="status">{tr('installersQueued')}</span>
|
||||
return <span className="badge rg-p-badge" role="status">{tr('installersQueued')}</span>
|
||||
}
|
||||
return (
|
||||
<span className="badge badge-accent installer-active-status" role="status">
|
||||
<span className="badge rg-p-badge badge-accent installer-active-status" role="status">
|
||||
<LoaderCircle size={12} className="spin" aria-hidden="true" />
|
||||
<span>
|
||||
{task.percent >= 0
|
||||
@@ -250,30 +262,27 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
const downloadedRows = [...virtualRows, ...cachedRows].sort((a, b) => rowPriority(a) - rowPriority(b))
|
||||
|
||||
const groups = groupReleases(releases ?? [])
|
||||
const showDownloaded = cached === null || downloadedRows.length > 0
|
||||
const showDownloaded = downloadedRows.length > 0
|
||||
|
||||
return (
|
||||
<div className="page installers-page">
|
||||
<header className="page-head">
|
||||
<div className="page-title installers-page-title">
|
||||
<h1>{tr('installersTitle')}</h1>
|
||||
<span>{tr('installersHint')}</span>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => { loadCached(); loadReleases() }} />
|
||||
</div>
|
||||
</header>
|
||||
<div className="macos-images-view">
|
||||
<div className="notice notice-info macos-sla-notice" role="note">
|
||||
<span className="notice-main">
|
||||
<Info size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('macosSlaNotice')}</span>
|
||||
</span>
|
||||
<Button icon={<ExternalLink size={13} aria-hidden="true" />} onClick={openSLA}>
|
||||
{tr('macosSlaButton')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showDownloaded && (
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span>{tr('installersDownloaded')}</span>
|
||||
{downloadedRows.length > 0 && <span className="section-count">{downloadedRows.length}</span>}
|
||||
<span className="section-count">{downloadedRows.length}</span>
|
||||
</div>
|
||||
{cached === null && downloadedRows.length === 0 ? (
|
||||
skeleton(1, tr('installersDownloaded'))
|
||||
) : (
|
||||
<div className="list installer-list">
|
||||
<div className="list installer-list">
|
||||
{downloadedRows.map((row) => {
|
||||
const c = row.cached
|
||||
const active = row.active
|
||||
@@ -292,23 +301,23 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span>{row.title}{row.version ? ` ${row.version}` : ''}</span>
|
||||
{!task && c?.kind === 'offline' && !c.partial && <span className="badge badge-ok">{tr('installersKindOffline')}</span>}
|
||||
{!task && c?.kind === 'offline' && !c.partial && <span className="badge rg-p-badge badge-ok">{tr('installersKindOffline')}</span>}
|
||||
{(!task && c?.kind === 'online' && !c.partial) || (task && row.kind === 'online')
|
||||
? <span className="badge">{tr('installersKindOnline')}</span>
|
||||
? <span className="badge rg-p-badge">{tr('installersKindOnline')}</span>
|
||||
: null}
|
||||
{c?.partial && !task && <span className="badge badge-warn">{tr('installersPartial')}</span>}
|
||||
{c?.partial && !task && <span className="badge rg-p-badge badge-warn">{tr('installersPartial')}</span>}
|
||||
{task && vmName && (
|
||||
<span className={`badge ${queued ? '' : 'badge-accent'}`}>
|
||||
<span className={`badge rg-p-badge ${queued ? '' : 'badge-accent'}`}>
|
||||
{tr(queued ? 'installersQueuedForVM' : 'installersDownloadingForVM', { vm: vmName })}
|
||||
</span>
|
||||
)}
|
||||
{task && !vmName && waitingVMs.length > 0 && (
|
||||
<span className="badge badge-accent">
|
||||
<span className="badge rg-p-badge badge-accent">
|
||||
{tr('installersWaitingVM', { vm: waitingVMs.join(', ') })}
|
||||
</span>
|
||||
)}
|
||||
{task && !vmName && queued && (
|
||||
<span className="badge">{tr('installersQueued')}</span>
|
||||
<span className="badge rg-p-badge">{tr('installersQueued')}</span>
|
||||
)}
|
||||
</div>
|
||||
{task ? progress(task) : c ? (
|
||||
@@ -344,7 +353,6 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -359,10 +367,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
<Button onClick={loadReleases}>{tr('installersRetry')}</Button>
|
||||
</div>
|
||||
) : releases === null ? (
|
||||
<>
|
||||
{skeleton(2, tr('offlineLoading'))}
|
||||
<span className="hint">{tr('offlineLoading')}</span>
|
||||
</>
|
||||
<WordmarkLoader className="installers-loader" label={tr('offlineLoading')} />
|
||||
) : (
|
||||
<div className="release-list">
|
||||
{groups.map((group, groupIndex) => {
|
||||
@@ -377,7 +382,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
<div className="row-title release-title">
|
||||
<span>{latest.title}</span>
|
||||
<strong>{latest.version}</strong>
|
||||
{groupIndex === 0 && <span className="badge badge-accent">{tr('installersLatest')}</span>}
|
||||
{groupIndex === 0 && <span className="badge rg-p-badge badge-accent">{tr('installersLatest')}</span>}
|
||||
{downloaded(latest.version) && <Check size={15} className="ok-text" aria-label={tr('offlineCached')} />}
|
||||
</div>
|
||||
{releaseMeta(latest)}
|
||||
@@ -397,7 +402,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
|
||||
<div className="row-title">
|
||||
<span>{r.version}</span>
|
||||
<span className="muted">{r.build}</span>
|
||||
{downloaded(r.version) && <span className="badge badge-ok">{tr('offlineCached')}</span>}
|
||||
{downloaded(r.version) && <span className="badge rg-p-badge badge-ok">{tr('offlineCached')}</span>}
|
||||
</div>
|
||||
{releaseMeta(r)}
|
||||
</div>
|
||||
|
||||
@@ -14,7 +14,7 @@ export const OnlineRecoveryDialog: React.FC<Props> = ({ locale, name, onCancel,
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog sm">
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{t(locale, 'onlineRecoveryTitle')}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
@@ -23,10 +23,10 @@ export const OnlineRecoveryDialog: React.FC<Props> = ({ locale, name, onCancel,
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn">{t(locale, 'cancel')}</button>
|
||||
<button type="button" className="btn rg-p-button">{t(locale, 'cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn btn-primary" onClick={onConfirm}>
|
||||
<button type="button" className="btn rg-p-button btn-primary" onClick={onConfirm}>
|
||||
{t(locale, 'onlineRecoveryConfirm')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
|
||||
+108
-60
@@ -712,11 +712,18 @@ h1, h2, h3, p { margin: 0; }
|
||||
}
|
||||
.empty-panel > svg { opacity: 0.6; }
|
||||
|
||||
/* Installers: one major-version card per system, older point releases folded away. */
|
||||
/* Images: segmented plugin sources, macOS SLA notice, one major-version card per system. */
|
||||
.installers-page { max-width: 780px; }
|
||||
.installers-page .page-head { align-items: flex-start; }
|
||||
.installers-page-title { flex-direction: column; align-items: flex-start; gap: 1px; }
|
||||
.installers-page-title > span { color: var(--text-3); font-size: var(--fs-12); line-height: 1.45; }
|
||||
.images-switch { display: flex; }
|
||||
.macos-images-view { display: flex; flex-direction: column; gap: 16px; }
|
||||
.macos-sla-notice { align-items: center; }
|
||||
.installers-loader { padding: 48px 0 40px; }
|
||||
.images-empty { gap: 8px; padding: 36px 24px; text-align: center; }
|
||||
.images-empty-title { font-size: var(--fs-14); font-weight: var(--fw-medium); color: var(--text); }
|
||||
.images-empty-desc { max-width: 420px; font-size: var(--fs-12); color: var(--text-3); line-height: 1.5; margin-bottom: 6px; }
|
||||
|
||||
/* About: brand header, then the update row and community links. */
|
||||
.about-page { max-width: 680px; }
|
||||
@@ -861,7 +868,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
:root[dir="rtl"] .status-mini-fill,
|
||||
:root[dir="rtl"] .progress-fill,
|
||||
:root[dir="rtl"] .meter-fill {
|
||||
:root[dir="rtl"] .meter-fill,
|
||||
:root[dir="rtl"] .market-progress-fill {
|
||||
transform-origin: right center;
|
||||
}
|
||||
.status-mini-fill.warn { background: var(--status-busy); }
|
||||
@@ -1296,12 +1304,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
cursor: pointer;
|
||||
}
|
||||
.setup-langpack:has(input:disabled) { cursor: default; opacity: 0.7; }
|
||||
.setup-langpack > input { flex-shrink: 0; margin: 0; }
|
||||
.setup-langpack-icon {
|
||||
width: 30px; height: 30px; border-radius: 8px; flex-shrink: 0;
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); color: #fff;
|
||||
}
|
||||
.setup-langpack > input { flex-shrink: 0; margin: 0; accent-color: var(--accent); }
|
||||
.setup-langpack-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.setup-langpack-title { font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text); }
|
||||
.setup-langpack-sub { font-size: var(--fs-12); color: var(--text-2); line-height: 1.45; }
|
||||
@@ -1670,6 +1673,65 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.rg-slot-inline { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.rg-slot-inline:empty { display: none; }
|
||||
.rg-preview-anchor { position: absolute; z-index: 2; pointer-events: none; }
|
||||
.titlebar-center {
|
||||
position: absolute; left: 50%; top: 0; height: 100%; transform: translateX(-50%);
|
||||
display: flex; align-items: center; gap: 6px; --wails-draggable: no-drag;
|
||||
}
|
||||
.nav-item-trailing { display: inline-flex; align-items: center; flex-shrink: 0; }
|
||||
|
||||
/* uiApi 2.0 full-window layers (ui-contract.ts): fixed to the window, never
|
||||
take pointer input or focus, and freeze animations under reduced motion.
|
||||
The shell is its own stacking context: the background layer (z -1) paints
|
||||
over the shell's own background and under all of its content (themes make
|
||||
the shell surfaces translucent to reveal it); the overlay layer (z 30) sits
|
||||
above the titlebar and status bar (z 10). Dialogs, menus and tooltips are
|
||||
portaled to body and the toaster sits outside the shell, so they stay on top. */
|
||||
.app-shell { position: relative; isolation: isolate; }
|
||||
.rg-layer { position: fixed; inset: 0; pointer-events: none; overflow: hidden; }
|
||||
.rg-layer:empty { display: none; }
|
||||
.rg-layer-background { z-index: -1; }
|
||||
.rg-layer-overlay { z-index: 30; }
|
||||
[data-motion="reduced"] .rg-layer *,
|
||||
[data-motion="reduced"] .rg-layer *::before,
|
||||
[data-motion="reduced"] .rg-layer *::after { animation-play-state: paused !important; transition: none !important; }
|
||||
|
||||
/* Theme decorations (ui-contract): images placed into slot anchors and layers. */
|
||||
.rg-decoration { display: block; max-width: 100%; object-fit: contain; pointer-events: none; user-select: none; }
|
||||
.rg-layer > .rg-decoration { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
|
||||
|
||||
/* Theme icon override: a packaged monochrome SVG tinted with currentColor. */
|
||||
.rg-icon {
|
||||
display: inline-block; flex-shrink: 0; background-color: currentColor;
|
||||
-webkit-mask: var(--rg-icon) center / contain no-repeat; mask: var(--rg-icon) center / contain no-repeat;
|
||||
}
|
||||
|
||||
/* Theme layout options (ui-contract; set from the active theme's `layout` as
|
||||
data-layout-* on <html>). They move and size regions only. */
|
||||
:root[data-layout-titlebar="compact"] { --titlebar-h: 34px; }
|
||||
:root[data-layout-density="compact"] {
|
||||
--sp-1: 3px; --sp-2: 6px; --sp-3: 9px; --sp-4: 12px; --sp-5: 16px; --sp-6: 20px; --sp-8: 26px;
|
||||
}
|
||||
:root[data-layout-density="compact"] .nav-item { height: 30px; }
|
||||
:root[data-layout-density="comfortable"] {
|
||||
--sp-1: 5px; --sp-2: 10px; --sp-3: 14px; --sp-4: 20px; --sp-5: 24px; --sp-6: 30px; --sp-8: 40px;
|
||||
}
|
||||
:root[data-layout-density="comfortable"] .nav-item { height: 42px; }
|
||||
:root[data-layout-sidebar="right"] .workspace { flex-direction: row-reverse; }
|
||||
:root[data-layout-sidebar="right"] .sidebar-wrap { border-inline-end: 0; border-inline-start: 1px solid var(--border); }
|
||||
:root[data-layout-sidebar-mode="floating"] .sidebar-wrap { background: transparent; border-color: transparent; }
|
||||
:root[data-layout-sidebar-mode="floating"] .sidebar { box-shadow: var(--shadow-overlay); }
|
||||
/* Rail: icons only. Labels stay as accessible names and tooltips. */
|
||||
:root[data-layout-sidebar-mode="rail"] { --sidebar-w: 76px; }
|
||||
:root[data-layout-sidebar-mode="rail"] .sidebar-brand-name,
|
||||
:root[data-layout-sidebar-mode="rail"] .sidebar-head > span,
|
||||
:root[data-layout-sidebar-mode="rail"] .nav-label,
|
||||
:root[data-layout-sidebar-mode="rail"] .update-capsule-title,
|
||||
:root[data-layout-sidebar-mode="rail"] .update-capsule-btn { display: none; }
|
||||
:root[data-layout-sidebar-mode="rail"] .sidebar-brand,
|
||||
:root[data-layout-sidebar-mode="rail"] .sidebar-head { justify-content: center; padding-inline: 0; }
|
||||
:root[data-layout-sidebar-mode="rail"] .nav-item { justify-content: center; padding: 0; position: relative; }
|
||||
:root[data-layout-sidebar-mode="rail"] .nav-item .status { position: absolute; top: 4px; inset-inline-end: 6px; }
|
||||
:root[data-layout-sidebar-mode="rail"] .nav-item .nav-dot { position: absolute; top: 4px; inset-inline-start: 6px; }
|
||||
.rg-preview-anchor:empty { display: none; }
|
||||
.rg-preview-anchor.tl { top: 6px; left: 6px; }
|
||||
.rg-preview-anchor.tr { top: 6px; right: 6px; }
|
||||
@@ -1680,37 +1742,35 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
overflow: hidden; background: var(--surface-1); margin-bottom: var(--sp-3);
|
||||
}
|
||||
.plugin-panel-wrap.is-headless { margin-bottom: 0; }
|
||||
.plugin-panel-head {
|
||||
padding: 8px 12px; font-size: var(--fs-12); font-weight: var(--fw-medium);
|
||||
color: var(--text-2); border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.plugin-panel-frame { display: block; width: 100%; border: 0; background: transparent; }
|
||||
.plugin-panel-error {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 12px 14px; border: 1px solid var(--danger-border); border-radius: var(--r-md);
|
||||
background: var(--danger-soft); color: var(--danger-text); font-size: var(--fs-12);
|
||||
.plugin-search-wrap { position: relative; display: flex; align-items: center; }
|
||||
.plugin-search-wrap.is-wide { width: 100%; }
|
||||
.plugin-search-icon {
|
||||
position: absolute; inset-inline-start: 10px; color: var(--text-3); pointer-events: none;
|
||||
}
|
||||
.plugins-search-wrap { position: relative; display: flex; align-items: center; }
|
||||
.plugins-search-icon {
|
||||
position: absolute; left: 10px; color: var(--text-3); pointer-events: none;
|
||||
}
|
||||
.plugins-search { width: 210px; padding-left: 30px; }
|
||||
.plugin-search { width: 210px; padding-inline-start: 30px; }
|
||||
.plugin-search-wrap.is-wide .plugin-search { width: 100%; }
|
||||
.plugins-scheme-dot {
|
||||
width: 9px; height: 9px; border-radius: 50%; flex-shrink: 0;
|
||||
border: 1px solid var(--border-strong); display: inline-block;
|
||||
}
|
||||
|
||||
.plugin-cat-pill {
|
||||
.plugin-pill {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
height: 26px; padding: 0 11px; border-radius: 999px;
|
||||
border: 1px solid var(--border); background: var(--surface-1);
|
||||
color: var(--text-2); font-size: var(--fs-12); font-weight: var(--fw-medium);
|
||||
cursor: pointer; transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease;
|
||||
}
|
||||
.plugin-cat-pill:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.plugin-cat-pill.is-active {
|
||||
background: var(--accent-soft); border-color: var(--accent); color: var(--accent-soft-text);
|
||||
border: 1px solid transparent; background: transparent;
|
||||
color: var(--text-2); font: inherit; font-size: var(--fs-12); font-weight: var(--fw-medium);
|
||||
cursor: pointer; transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.plugin-pill:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.plugin-pill.is-active { background: var(--accent-soft); color: var(--accent-soft-text); }
|
||||
.plugin-pill-count { color: var(--text-3); font-variant-numeric: tabular-nums; }
|
||||
.plugin-pill.is-active .plugin-pill-count { color: inherit; opacity: 0.7; }
|
||||
|
||||
/* iOS/macOS App Store–inspired squircle icon tiles */
|
||||
.plugin-app-icon {
|
||||
@@ -1718,6 +1778,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
color: #fff; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.28), 0 1px 2px rgba(0, 0, 0, 0.14);
|
||||
}
|
||||
.plugin-app-icon.is-md { width: 34px; height: 34px; border-radius: 9px; }
|
||||
.plugin-app-icon.is-sm { width: 30px; height: 30px; border-radius: 8px; }
|
||||
.plugin-app-icon.tone-indigo { background: linear-gradient(145deg, #6e7cf0 0%, #4d5be0 100%); }
|
||||
.plugin-app-icon.tone-purple { background: linear-gradient(145deg, #bf5af2 0%, #8944ab 100%); }
|
||||
.plugin-app-icon.tone-sky { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
|
||||
@@ -1732,8 +1794,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.plugins-page-title { flex-direction: column; align-items: flex-start; gap: 1px; }
|
||||
.plugins-page-title > span { color: var(--text-3); font-size: var(--fs-12); line-height: 1.45; }
|
||||
.plugin-row { gap: 12px; min-height: 60px; }
|
||||
.plugin-row .plugin-app-icon { width: 34px; height: 34px; border-radius: 9px; }
|
||||
.plugin-row .plugin-app-icon svg { width: 18px; height: 18px; }
|
||||
.plugin-row-name { font-weight: var(--fw-medium); }
|
||||
.plugin-row-desc {
|
||||
color: var(--text-2); line-height: 1.45;
|
||||
@@ -1743,30 +1803,23 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.plugin-row-alert { display: flex; align-items: center; gap: 5px; color: var(--warn-text); }
|
||||
.plugin-row-locked { display: inline-flex; border-radius: 999px; }
|
||||
.plugin-row-locked .switch { pointer-events: none; }
|
||||
.plugin-trust { display: inline-flex; align-items: center; gap: 3px; font-weight: var(--fw-medium); }
|
||||
.plugin-trust.is-official, .plugin-trust.is-verified { color: var(--ok-text); }
|
||||
.plugin-trust.is-dev { color: var(--accent-soft-text); }
|
||||
.plugin-trust.is-community { color: var(--text-2); }
|
||||
.plugin-trust {
|
||||
display: inline-flex; align-items: center; gap: 4px; min-width: 0;
|
||||
color: var(--text-2); border-radius: var(--r-sm); outline-offset: 2px;
|
||||
}
|
||||
.plugin-trust svg { flex-shrink: 0; }
|
||||
.plugin-trust-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.plugin-trust.is-official svg { color: var(--accent); }
|
||||
.plugin-trust.is-verified svg { color: var(--ok-text); }
|
||||
.plugin-trust.is-dev svg { color: var(--accent-soft-text); }
|
||||
.plugin-trust.is-community svg { color: var(--text-3); }
|
||||
.plugins-empty { padding: 24px 4px; text-align: center; color: var(--text-3); font-size: var(--fs-13); }
|
||||
.plugins-switch { display: flex; }
|
||||
|
||||
/* Plugin market: cache-first feed of cards in as many columns as fit */
|
||||
.plugin-market { gap: 12px; }
|
||||
.market-toolbar { display: flex; flex-direction: column; gap: 10px; }
|
||||
.market-search-wrap { width: 100%; }
|
||||
.market-search { width: 100%; padding-left: 30px; }
|
||||
.market-kinds { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.market-kind {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
height: 26px; padding: 0 11px; border-radius: 999px;
|
||||
border: 1px solid transparent; background: transparent;
|
||||
color: var(--text-2); font: inherit; font-size: var(--fs-12); font-weight: var(--fw-medium);
|
||||
cursor: pointer; transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.market-kind:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.market-kind.is-active { background: var(--accent-soft); color: var(--accent-soft-text); }
|
||||
.market-kind-count { color: var(--text-3); font-variant-numeric: tabular-nums; }
|
||||
.market-kind.is-active .market-kind-count { color: inherit; opacity: 0.7; }
|
||||
|
||||
.market-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }
|
||||
.market-card {
|
||||
@@ -1792,16 +1845,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.market-card-dot { flex-shrink: 0; }
|
||||
.market-card-version { flex-shrink: 0; font-variant-numeric: tabular-nums; }
|
||||
.market-publisher {
|
||||
display: inline-flex; align-items: center; gap: 4px; min-width: 0;
|
||||
color: var(--text-2); border-radius: var(--r-sm); outline-offset: 2px;
|
||||
}
|
||||
.market-publisher svg { flex-shrink: 0; }
|
||||
.market-publisher-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.market-publisher.is-official svg { color: var(--accent); }
|
||||
.market-publisher.is-verified svg { color: var(--ok-text); }
|
||||
.market-publisher.is-dev svg { color: var(--accent-soft-text); }
|
||||
.market-publisher.is-community svg { color: var(--text-3); }
|
||||
.market-card-action { flex-shrink: 0; }
|
||||
.market-card-action .btn.market-btn { height: 28px; padding: 0 12px; font-size: var(--fs-12); }
|
||||
.market-card-desc {
|
||||
@@ -1817,11 +1860,12 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.market-progress-fill {
|
||||
position: absolute; inset: 0 auto 0 0; z-index: -1; width: 0;
|
||||
background: var(--accent-soft); transition: width 160ms linear;
|
||||
position: absolute; inset: 0; z-index: -1; width: 100%;
|
||||
background: var(--accent-soft); transform-origin: left center;
|
||||
transition: transform 160ms linear;
|
||||
}
|
||||
.market-progress.is-indeterminate .market-progress-fill {
|
||||
width: 40%; animation: market-progress-sweep 1.1s var(--ease-in-out) infinite;
|
||||
inset: 0 auto 0 0; width: 40%; animation: market-progress-sweep 1.1s var(--ease-in-out) infinite;
|
||||
}
|
||||
@keyframes market-progress-sweep { from { transform: translateX(-100%); } to { transform: translateX(250%); } }
|
||||
.market-progress-text {
|
||||
@@ -1847,9 +1891,11 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
@keyframes wordmark-pulse { from { opacity: 0.35; } to { opacity: 1; } }
|
||||
|
||||
/* What a plugin can do, shown before enabling it */
|
||||
.plugin-enable-body { padding: var(--sp-4); }
|
||||
.plugin-enable-lead { margin: 0; font-size: var(--fs-13); color: var(--text-2); }
|
||||
.plugin-enable-ack { cursor: pointer; font-size: var(--fs-13); }
|
||||
.plugin-log-pre {
|
||||
margin: 0; font-size: var(--fs-12); line-height: 1.55;
|
||||
white-space: pre-wrap; word-break: break-word;
|
||||
}
|
||||
.plugin-risk-list {
|
||||
margin: 0; padding: 4px 0; list-style: none;
|
||||
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
@@ -1982,7 +2028,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); }
|
||||
.row-main, .srow-text { flex: 1 1 220px; }
|
||||
.conn-ctrl, .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; }
|
||||
.plugins-search { width: 100%; }
|
||||
.plugin-search-wrap, .plugin-search { width: 100%; }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1993,6 +2039,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.rg-p-titlebar { --wails-draggable: drag !important; }
|
||||
:focus-visible:not(.dialog):not(.menu) { box-shadow: var(--focus-ring) !important; }
|
||||
.icon-btn, .win-btn { min-width: 28px !important; min-height: 28px !important; }
|
||||
/* Layers and decorations never take input, whatever a theme says. */
|
||||
.rg-layer, .rg-layer *, .rg-decoration { pointer-events: none !important; }
|
||||
}
|
||||
|
||||
.bridge-adapters { display: grid; gap: var(--space-3, 12px); }
|
||||
|
||||
@@ -30,12 +30,7 @@ export const UI_CONTRACT_PARTS = [
|
||||
'rg-p-logpanel',
|
||||
'rg-p-settings',
|
||||
'rg-p-empty',
|
||||
] as const
|
||||
|
||||
export type UIContractPart = (typeof UI_CONTRACT_PARTS)[number]
|
||||
|
||||
// Control-level parts (§5.1). Experimental until each one is emitted.
|
||||
export const UI_CONTRACT_PARTS_EXPERIMENTAL = [
|
||||
// Control-level parts.
|
||||
'rg-p-nav-group',
|
||||
'rg-p-nav-item',
|
||||
'rg-p-button',
|
||||
@@ -56,6 +51,10 @@ export const UI_CONTRACT_PARTS_EXPERIMENTAL = [
|
||||
'rg-p-plugin-view',
|
||||
] as const
|
||||
|
||||
export type UIContractPart = (typeof UI_CONTRACT_PARTS)[number]
|
||||
|
||||
export const UI_CONTRACT_PARTS_EXPERIMENTAL = [] as const
|
||||
|
||||
export const UI_CONTRACT_STATE_ATTRS = [
|
||||
'data-theme',
|
||||
'data-motion',
|
||||
@@ -66,18 +65,17 @@ export const UI_CONTRACT_STATE_ATTRS = [
|
||||
'data-has-error',
|
||||
'data-sidebar-collapsed',
|
||||
'data-safe-mode',
|
||||
] as const
|
||||
|
||||
// Document-level layout attributes, set from the active theme's `layout`.
|
||||
export const UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL = [
|
||||
// Set from the active theme layout options; absent with the built-in theme.
|
||||
'data-layout-sidebar',
|
||||
'data-layout-sidebar-mode',
|
||||
'data-layout-density',
|
||||
'data-layout-titlebar',
|
||||
] as const
|
||||
|
||||
export const UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL = [] as const
|
||||
|
||||
// Per-item state attributes, written as `<part>:<attribute>`.
|
||||
export const UI_CONTRACT_ITEM_STATES_EXPERIMENTAL = [
|
||||
export const UI_CONTRACT_ITEM_STATES = [
|
||||
'rg-p-nav-item:data-vm-state',
|
||||
'rg-p-nav-item:data-driver',
|
||||
'rg-p-nav-item:data-selected',
|
||||
@@ -86,48 +84,56 @@ export const UI_CONTRACT_ITEM_STATES_EXPERIMENTAL = [
|
||||
'rg-p-vm-page:data-driver',
|
||||
'rg-p-button:data-variant',
|
||||
'rg-p-button:data-busy',
|
||||
'rg-p-icon-button:data-busy',
|
||||
'rg-p-dialog:data-tone',
|
||||
'rg-p-toast:data-tone',
|
||||
] as const
|
||||
|
||||
export const UI_CONTRACT_ITEM_STATES_EXPERIMENTAL = [] as const
|
||||
|
||||
// Slot anchors (`data-rg-slot`) that decorations and UI SDK mounts can target.
|
||||
// Which plugin contributions a slot accepts is declared on the Go side.
|
||||
// `nav.item.trailing` repeats once per VM entry, keyed by `data-rg-key`
|
||||
// (the VM reference). Which plugin contributions a slot accepts is declared
|
||||
// on the Go side.
|
||||
export const UI_CONTRACT_SLOTS = [
|
||||
'titlebar.center',
|
||||
'sidebar.header',
|
||||
'sidebar.footer',
|
||||
'statusbar.right',
|
||||
'nav.item.trailing',
|
||||
'vm.header.trailing',
|
||||
'vm.toolbar',
|
||||
'vm.card',
|
||||
'settings.plugin',
|
||||
'vm.preview.tl',
|
||||
'vm.preview.tr',
|
||||
'vm.preview.bl',
|
||||
'vm.preview.br',
|
||||
'statusbar.left',
|
||||
'statusbar.right',
|
||||
'empty.state',
|
||||
'create.source',
|
||||
'settings.plugin',
|
||||
] as const
|
||||
|
||||
export type UIContractSlot = (typeof UI_CONTRACT_SLOTS)[number]
|
||||
|
||||
export const UI_CONTRACT_SLOTS_EXPERIMENTAL = [
|
||||
'titlebar.center',
|
||||
'sidebar.header',
|
||||
'nav.item.trailing',
|
||||
'vm.header.trailing',
|
||||
'vm.toolbar',
|
||||
'statusbar.left',
|
||||
'create.source',
|
||||
] as const
|
||||
export const UI_CONTRACT_SLOTS_EXPERIMENTAL = [] as const
|
||||
|
||||
// Full-window layers: never take pointer input or focus; animations stop
|
||||
// under reduced motion.
|
||||
export const UI_CONTRACT_LAYERS = [] as const
|
||||
|
||||
export const UI_CONTRACT_LAYERS_EXPERIMENTAL = [
|
||||
// Full-window layers (`data-rg-layer`): never take pointer input or focus;
|
||||
// animations freeze under reduced motion. Decorations and UI SDK mounts can
|
||||
// target them like slots.
|
||||
export const UI_CONTRACT_LAYERS = [
|
||||
'layer.background',
|
||||
'layer.overlay',
|
||||
] as const
|
||||
|
||||
// Theme `layout` options, written as `<option>=<value>`. They move and size
|
||||
// regions only; operation entries always stay reachable.
|
||||
export const UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL = [
|
||||
export type UIContractLayer = (typeof UI_CONTRACT_LAYERS)[number]
|
||||
|
||||
export const UI_CONTRACT_LAYERS_EXPERIMENTAL = [] as const
|
||||
|
||||
// Theme `layout` options, written as `<option>=<value>`; each becomes a
|
||||
// data-layout-* attribute on <html>. They move and size regions only;
|
||||
// operation entries always stay reachable.
|
||||
export const UI_CONTRACT_LAYOUT_OPTIONS = [
|
||||
'sidebarPosition=left',
|
||||
'sidebarPosition=right',
|
||||
'sidebarMode=full',
|
||||
@@ -140,8 +146,11 @@ export const UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL = [
|
||||
'titlebar=compact',
|
||||
] as const
|
||||
|
||||
export const UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL = [] as const
|
||||
|
||||
// Icon names a theme can map to a packaged monochrome SVG via `icons`.
|
||||
export const UI_CONTRACT_ICONS_EXPERIMENTAL = [
|
||||
// Every name is rendered through <HostIcon> somewhere in the host.
|
||||
export const UI_CONTRACT_ICONS = [
|
||||
'start',
|
||||
'stop',
|
||||
'force-stop',
|
||||
@@ -169,7 +178,13 @@ export const UI_CONTRACT_ICONS_EXPERIMENTAL = [
|
||||
'vm.state.error',
|
||||
] as const
|
||||
|
||||
export type UIContractIcon = (typeof UI_CONTRACT_ICONS)[number]
|
||||
|
||||
export const UI_CONTRACT_ICONS_EXPERIMENTAL = [] as const
|
||||
|
||||
// Where plugin `views` can appear (§5.6).
|
||||
export const UI_CONTRACT_VIEW_LOCATIONS = [] as const
|
||||
|
||||
export const UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL = [
|
||||
'sidebar',
|
||||
'vm.tab',
|
||||
@@ -177,8 +192,8 @@ export const UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL = [
|
||||
'dialog',
|
||||
] as const
|
||||
|
||||
// UI SDK event stream for interactive themes.
|
||||
export const UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL = [
|
||||
// UI SDK event stream for interactive themes (`sdk.on(event, cb)`).
|
||||
export const UI_CONTRACT_SDK_EVENTS = [
|
||||
'vm.stateChanged',
|
||||
'task.started',
|
||||
'task.progress',
|
||||
@@ -187,6 +202,10 @@ export const UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL = [
|
||||
'view.changed',
|
||||
] as const
|
||||
|
||||
export type UIContractSDKEvent = (typeof UI_CONTRACT_SDK_EVENTS)[number]
|
||||
|
||||
export const UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL = [] as const
|
||||
|
||||
export const UI_CONTRACT_TOKENS = [
|
||||
'--font-sans', '--font-cjk', '--font-mono',
|
||||
'--body-lh', '--heading-tracking',
|
||||
@@ -216,8 +235,13 @@ 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],
|
||||
@@ -235,5 +259,10 @@ export const UI_CONTRACT = {
|
||||
// Stable host features advertised to themes through the UI SDK (§6.3).
|
||||
export const UI_CONTRACT_FEATURES: readonly string[] = [
|
||||
...UI_CONTRACT_SLOTS.map((s) => `slot.${s}`),
|
||||
...(UI_CONTRACT_LAYERS as readonly string[]).map((l) => l),
|
||||
...UI_CONTRACT_LAYERS,
|
||||
'theme.layout',
|
||||
'theme.icons',
|
||||
'theme.brandMark',
|
||||
'theme.decorations',
|
||||
...UI_CONTRACT_SDK_EVENTS.map((e) => `sdk.event.${e}`),
|
||||
]
|
||||
@@ -49,7 +49,7 @@ export type RemoteRuntime = Model<runtime.Remote> & {
|
||||
|
||||
export type VMListItem = Model<driver.VMListItem> & {
|
||||
driver_id?: string
|
||||
state: 'running' | 'stopped' | 'suspended' | 'broken'
|
||||
state: 'running' | 'stopped' | 'suspended' | 'broken' | 'driver_unavailable'
|
||||
}
|
||||
|
||||
export type PendingChange = app.PendingChange
|
||||
@@ -61,6 +61,7 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
|
||||
runtimes: InstalledRuntime[] | null
|
||||
active_runtime?: InstalledRuntime
|
||||
vms: VMListItem[] | null
|
||||
vm_list_error?: string
|
||||
}
|
||||
|
||||
export type AppUpdateInfo = version.UpdateInfo
|
||||
@@ -168,6 +169,7 @@ export type ResolvedLocalePack = Model<plugin.ResolvedLocalePack> & {
|
||||
export type MenuContribution = plugin.MenuContribution
|
||||
export type VMCardContribution = plugin.VMCardContribution
|
||||
export type PanelContribution = plugin.PanelContribution
|
||||
export type ImageSourceContribution = plugin.ImageSourceContribution
|
||||
export type StatusItemContribution = plugin.StatusItemContribution
|
||||
export type PluginUIContributions = app.PluginUIContributions
|
||||
export type DriverSummary = driver.DriverSummary
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import * as RTooltip from '@radix-ui/react-tooltip'
|
||||
import { LoaderCircle } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import type { UIContractIcon } from '../styles/ui-contract'
|
||||
import { HostIcon } from './themeVisuals'
|
||||
|
||||
export const TooltipProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => (
|
||||
<RTooltip.Provider delayDuration={400} skipDelayDuration={200}>{children}</RTooltip.Provider>
|
||||
@@ -24,7 +26,7 @@ export const Tip: React.FC<TipProps> = ({ label, shortcut, side = 'bottom', disa
|
||||
<RTooltip.Root open={disabled ? false : open} onOpenChange={(next) => setOpen(disabled ? false : next)}>
|
||||
<RTooltip.Trigger asChild>{children}</RTooltip.Trigger>
|
||||
<RTooltip.Portal>
|
||||
<RTooltip.Content className="tooltip" side={side} sideOffset={6} collisionPadding={8}>
|
||||
<RTooltip.Content className="tooltip rg-p-tooltip" side={side} sideOffset={6} collisionPadding={8}>
|
||||
{label}
|
||||
{shortcut && <kbd>{shortcut}</kbd>}
|
||||
</RTooltip.Content>
|
||||
@@ -46,7 +48,9 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
<button
|
||||
ref={ref}
|
||||
type="button"
|
||||
className={`btn${variant === 'secondary' ? '' : ` btn-${variant}`}${className ? ` ${className}` : ''}`}
|
||||
className={`btn rg-p-button${variant === 'secondary' ? '' : ` btn-${variant}`}${className ? ` ${className}` : ''}`}
|
||||
data-variant={variant}
|
||||
data-busy={busy ? 'true' : undefined}
|
||||
disabled={disabled || busy}
|
||||
aria-busy={busy || undefined}
|
||||
{...rest}
|
||||
@@ -75,7 +79,8 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||
ref={ref}
|
||||
type="button"
|
||||
aria-label={label}
|
||||
className={`icon-btn${small ? ' sm' : ''}${className ? ` ${className}` : ''}`}
|
||||
className={`icon-btn rg-p-icon-button${small ? ' sm' : ''}${className ? ` ${className}` : ''}`}
|
||||
data-busy={busy ? 'true' : undefined}
|
||||
disabled={disabled || busy}
|
||||
aria-busy={busy || undefined}
|
||||
{...rest}
|
||||
@@ -98,7 +103,18 @@ export function statusKind(state: string): StatusKind {
|
||||
return 'stopped'
|
||||
}
|
||||
|
||||
/** Status shape: differs by shape as well as colour. */
|
||||
const STATUS_ICON: Record<StatusKind, UIContractIcon> = {
|
||||
running: 'vm.state.running',
|
||||
stopped: 'vm.state.stopped',
|
||||
suspended: 'vm.state.suspended',
|
||||
busy: 'vm.state.busy',
|
||||
broken: 'vm.state.error',
|
||||
warn: 'vm.state.error',
|
||||
}
|
||||
|
||||
/** Status shape: differs by shape as well as colour; themes may replace it by icon name. */
|
||||
export const StatusShape: React.FC<{ kind: StatusKind }> = ({ kind }) => (
|
||||
<span className={`status status-${kind}`} aria-hidden="true" />
|
||||
<HostIcon name={STATUS_ICON[kind]} size={10}>
|
||||
<span className={`status status-${kind}`} aria-hidden="true" />
|
||||
</HostIcon>
|
||||
)
|
||||
@@ -25,7 +25,8 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content
|
||||
className="dialog sm"
|
||||
className="dialog rg-p-dialog sm"
|
||||
data-tone="danger"
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
const prev = prevFocusRef.current
|
||||
@@ -56,11 +57,13 @@ interface Props {
|
||||
onClose: () => void
|
||||
/** Extra class on the dialog box, e.g. a wider variant. */
|
||||
className?: string
|
||||
/** Exposed as data-tone for themes (ui-contract). */
|
||||
tone?: 'neutral' | 'danger' | 'warn'
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
/** Modal frame: head with title and ✕; children supply body/steps/foot sections. */
|
||||
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => {
|
||||
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, tone = 'neutral', children }) => {
|
||||
const prevFocusRef = React.useRef<HTMLElement | null>(
|
||||
typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
@@ -71,7 +74,8 @@ export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissabl
|
||||
<RDialog.Portal>
|
||||
<RDialog.Overlay className="overlay" />
|
||||
<RDialog.Content
|
||||
className={className ? `dialog ${className}` : 'dialog'}
|
||||
className={className ? `dialog rg-p-dialog ${className}` : 'dialog rg-p-dialog'}
|
||||
data-tone={tone}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
// Focus the first enabled form field, or the dialog container itself when there is
|
||||
// none, so the top-right ✕ close button's tooltip never pops on open.
|
||||
|
||||
@@ -86,7 +86,7 @@ export const SetValue: React.FC<{ title: string; value: React.ReactNode; mono?:
|
||||
)
|
||||
|
||||
export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean }> = ({ checked, onChange, label, disabled }) => (
|
||||
<label className="switch">
|
||||
<label className="switch rg-p-switch">
|
||||
<input type="checkbox" role="switch" aria-label={label} checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
|
||||
<span className="slider" />
|
||||
</label>
|
||||
@@ -357,7 +357,7 @@ export function OptionCards<V extends string>({ options, value, onChange, label,
|
||||
<span className="opt-card-title" title={o.title}>{o.title}</span>
|
||||
{o.sub && <span className="opt-card-sub">{o.sub}</span>}
|
||||
{o.badges && o.badges.length > 0 && (
|
||||
<span className="opt-card-badges">{o.badges.map((b) => <span key={b} className="badge badge-accent">{b}</span>)}</span>
|
||||
<span className="opt-card-badges">{o.badges.map((b) => <span key={b} className="badge rg-p-badge badge-accent">{b}</span>)}</span>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
@@ -402,10 +402,10 @@ export function PopupSelect<V extends string>({ value, options, onChange, label,
|
||||
</button>
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content className="menu popup-menu" align="start" sideOffset={4} collisionPadding={8}>
|
||||
<Menu.Content className="menu rg-p-menu popup-menu" align="start" sideOffset={4} collisionPadding={8}>
|
||||
<Menu.RadioGroup value={value ?? ''} onValueChange={(v) => onChange(v as V)}>
|
||||
{options.map((o) => (
|
||||
<Menu.RadioItem key={o.value} value={o.value} disabled={o.disabled} className="menu-item popup-item">
|
||||
<Menu.RadioItem key={o.value} value={o.value} disabled={o.disabled} className="menu-item rg-p-menu-item popup-item">
|
||||
<Menu.ItemIndicator className="popup-check"><Check size={13} /></Menu.ItemIndicator>
|
||||
<span className="popup-item-label">{o.label}</span>
|
||||
{o.detail && <span className="popup-detail">{o.detail}</span>}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
// Theme visuals from uiApi 2.0 (docs/plugin-architecture.md §5.1): icon
|
||||
// overrides, the brand mark, and declarative decorations rendered into slot
|
||||
// anchors (`data-rg-slot`) and full-window layers (`data-rg-layer`).
|
||||
// With the built-in theme none of this injects anything.
|
||||
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 { UI_CONTRACT_ICONS, UI_CONTRACT_LAYERS, UI_CONTRACT_SLOTS, type UIContractIcon } from '../styles/ui-contract'
|
||||
import type { ActiveThemePayload, Locale, ThemeDecoration } from '../types'
|
||||
|
||||
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 {
|
||||
brandMarkURL: string
|
||||
icons: Partial<Record<UIContractIcon, string>>
|
||||
}
|
||||
|
||||
const EMPTY: ThemeVisuals = { brandMarkURL: DEFAULT_BRAND_MARK, icons: {} }
|
||||
const ThemeVisualsContext = createContext<ThemeVisuals>(EMPTY)
|
||||
|
||||
function isBuiltin(payload: ActiveThemePayload | null): boolean {
|
||||
return !payload?.theme || payload.theme_id === 'builtin.theme.default'
|
||||
}
|
||||
|
||||
export function resolveThemeVisuals(payload: ActiveThemePayload | null): ThemeVisuals {
|
||||
if (isBuiltin(payload)) return EMPTY
|
||||
const th = payload!.theme!
|
||||
const icons: Partial<Record<UIContractIcon, string>> = {}
|
||||
for (const [name, rel] of Object.entries(th.icons ?? {})) {
|
||||
const url = KNOWN_ICONS.has(name) ? themeAssetURL(payload, rel) : null
|
||||
if (url) icons[name as UIContractIcon] = url
|
||||
}
|
||||
return { brandMarkURL: themeAssetURL(payload, th.brandMark) ?? DEFAULT_BRAND_MARK, icons }
|
||||
}
|
||||
|
||||
export const ThemeVisualsProvider: React.FC<{ payload: ActiveThemePayload | null; children: React.ReactNode }> = ({ payload, children }) => {
|
||||
const value = useMemo(() => resolveThemeVisuals(payload), [payload])
|
||||
return <ThemeVisualsContext.Provider value={value}>{children}</ThemeVisualsContext.Provider>
|
||||
}
|
||||
|
||||
export function useThemeVisuals(): ThemeVisuals {
|
||||
return useContext(ThemeVisualsContext)
|
||||
}
|
||||
|
||||
type IconChild = React.ReactElement<{ size?: number | string; 'data-rg-icon'?: string }>
|
||||
|
||||
/**
|
||||
* A host icon a theme can replace by name (ui-contract UI_CONTRACT_ICONS).
|
||||
* The child is the built-in icon; both carry `data-rg-icon` for styling.
|
||||
*/
|
||||
export const HostIcon: React.FC<{ name: UIContractIcon; size?: number; children: IconChild }> = ({ name, size: sizeProp, children }) => {
|
||||
const { icons } = useThemeVisuals()
|
||||
const url = icons[name]
|
||||
if (!url) return React.cloneElement(children, { 'data-rg-icon': name })
|
||||
const size = sizeProp ?? Number(children.props.size ?? 16)
|
||||
return (
|
||||
<span
|
||||
className="rg-icon"
|
||||
data-rg-icon={name}
|
||||
aria-hidden="true"
|
||||
style={{ width: size, height: size, ['--rg-icon' as string]: `url("${url}")` }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** The product mark, replaceable by a theme's `brandMark`. */
|
||||
export const BrandMark: React.FC<{ className: string }> = ({ className }) => {
|
||||
const { brandMarkURL } = useThemeVisuals()
|
||||
return <img className={className} src={brandMarkURL} alt="" aria-hidden="true" />
|
||||
}
|
||||
|
||||
interface DecorationProps {
|
||||
urls: string[]
|
||||
fps: number
|
||||
reducedMotion: boolean
|
||||
width?: number
|
||||
height?: number
|
||||
alt: string
|
||||
}
|
||||
|
||||
const DecorationImage: React.FC<DecorationProps> = ({ urls, fps, reducedMotion, width, height, alt }) => {
|
||||
const [frame, setFrame] = useState(0)
|
||||
const animate = urls.length > 1 && !reducedMotion
|
||||
useEffect(() => {
|
||||
setFrame(0)
|
||||
if (!animate) return
|
||||
const id = window.setInterval(() => setFrame((f) => (f + 1) % urls.length), 1000 / Math.min(30, Math.max(1, fps || 8)))
|
||||
return () => window.clearInterval(id)
|
||||
}, [animate, fps, urls.join('|')])
|
||||
return (
|
||||
<img
|
||||
className="rg-decoration"
|
||||
src={urls[animate ? frame : 0]}
|
||||
width={width || undefined}
|
||||
height={height || undefined}
|
||||
alt={alt}
|
||||
aria-hidden={alt ? undefined : true}
|
||||
draggable={false}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const anchorSelector = (target: string) => `[data-rg-slot="${CSS.escape(target)}"], [data-rg-layer="${CSS.escape(target)}"]`
|
||||
|
||||
/**
|
||||
* Renders the active theme's decorations into every matching anchor. Anchors
|
||||
* that repeat per VM (`nav.item.trailing`) evaluate states against that VM.
|
||||
*/
|
||||
export const ThemeDecorations: React.FC<{ payload: ActiveThemePayload | null; snap: UIStateSnapshot; locale: Locale }> = ({ payload, snap, locale }) => {
|
||||
const decorations: ThemeDecoration[] = isBuiltin(payload)
|
||||
? []
|
||||
: (payload!.theme!.decorations ?? []).filter((d) => KNOWN_TARGETS.has(d.slot))
|
||||
const targets = useMemo(() => [...new Set(decorations.map((d) => d.slot))], [decorations.map((d) => d.slot).join('|')])
|
||||
const [anchors, setAnchors] = useState<Record<string, Element[]>>({})
|
||||
|
||||
// Anchors come and go with views; rescan once per frame after DOM changes.
|
||||
useEffect(() => {
|
||||
if (targets.length === 0) {
|
||||
setAnchors({})
|
||||
return
|
||||
}
|
||||
let raf = 0
|
||||
const scan = () => {
|
||||
raf = 0
|
||||
const next: Record<string, Element[]> = {}
|
||||
for (const target of targets) next[target] = Array.from(document.querySelectorAll(anchorSelector(target)))
|
||||
setAnchors((prev) => {
|
||||
const same = targets.every((tg) => (prev[tg]?.length ?? 0) === next[tg].length && next[tg].every((el, i) => prev[tg][i] === el))
|
||||
return same ? prev : next
|
||||
})
|
||||
}
|
||||
scan()
|
||||
const obs = new MutationObserver(() => {
|
||||
if (!raf) raf = requestAnimationFrame(scan)
|
||||
})
|
||||
obs.observe(document.body, { childList: true, subtree: true })
|
||||
return () => {
|
||||
obs.disconnect()
|
||||
if (raf) cancelAnimationFrame(raf)
|
||||
}
|
||||
}, [targets.join('|')])
|
||||
|
||||
if (decorations.length === 0) return null
|
||||
const reducedMotion = snap.motion === 'reduced'
|
||||
const portals: React.ReactNode[] = []
|
||||
for (const dec of decorations) {
|
||||
for (const [i, anchor] of (anchors[dec.slot] ?? []).entries()) {
|
||||
// Per-VM anchors read the VM's own state from the enclosing item.
|
||||
const item = (anchor as HTMLElement).closest<HTMLElement>('[data-vm-state]')
|
||||
const itemSnap = item && (anchor as HTMLElement).dataset.rgKey ? { ...snap, vmState: item.dataset.vmState ?? '', busy: item.dataset.busy === 'true' } : snap
|
||||
const st = matchDecorationState(dec, itemSnap)
|
||||
if (!st) continue
|
||||
const frames = (st.frames ?? []).map((f) => themeAssetURL(payload, f)).filter((u): u is string => !!u)
|
||||
const asset = themeAssetURL(payload, st.asset)
|
||||
const urls = frames.length > 0 ? frames : asset ? [asset] : []
|
||||
if (urls.length === 0) continue
|
||||
portals.push(createPortal(
|
||||
<DecorationImage
|
||||
urls={urls}
|
||||
fps={st.fps ?? 0}
|
||||
reducedMotion={reducedMotion}
|
||||
width={dec.width}
|
||||
height={dec.height}
|
||||
alt={dec.alt ? locText(dec.alt, locale, '') : ''}
|
||||
/>,
|
||||
anchor,
|
||||
`${dec.id}:${i}`,
|
||||
))
|
||||
}
|
||||
}
|
||||
return <>{portals}</>
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import * as RToast from '@radix-ui/react-toast'
|
||||
import { Check, CircleCheck, CircleX, X } from 'lucide-react'
|
||||
import { HostIcon } from './themeVisuals'
|
||||
import { emitThemeEvent } from '../lib/themeEngine'
|
||||
import React, { useCallback, useState } from 'react'
|
||||
import { IconButton } from './controls'
|
||||
|
||||
@@ -24,6 +26,7 @@ export function useToasts() {
|
||||
const [items, setItems] = useState<ToastItem[]>([])
|
||||
const push = useCallback((input: ToastInput) => {
|
||||
setItems((prev) => [...prev.slice(-3), { ...input, id: seq++ }])
|
||||
emitThemeEvent('toast.shown', { kind: input.kind, title: input.title })
|
||||
}, [])
|
||||
const remove = useCallback((id: number) => setItems((prev) => prev.filter((i) => i.id !== id)), [])
|
||||
return { items, push, remove }
|
||||
@@ -53,12 +56,13 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
|
||||
setCopied(true)
|
||||
window.setTimeout(() => setCopied(false), 1500)
|
||||
})
|
||||
.catch(() => {})
|
||||
.catch((e) => console.warn('[toast] clipboard write failed:', e))
|
||||
}
|
||||
|
||||
return (
|
||||
<RToast.Root
|
||||
className={`toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
|
||||
className={`toast rg-p-toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
|
||||
data-tone={item.kind}
|
||||
duration={expanded ? 600_000 : item.kind === 'error' ? 10_000 : item.action ? 8000 : 3000}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onRemove(item.id)
|
||||
@@ -68,7 +72,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
|
||||
{item.kind === 'ok' ? (
|
||||
<CircleCheck size={16} aria-hidden="true" />
|
||||
) : (
|
||||
<CircleX size={16} aria-hidden="true" />
|
||||
<HostIcon name="error"><CircleX size={16} aria-hidden="true" /></HostIcon>
|
||||
)}
|
||||
<div className="toast-text">
|
||||
<div className="toast-title-row">
|
||||
@@ -81,7 +85,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
|
||||
</div>
|
||||
{item.action && !item.rawDetail && (
|
||||
<RToast.Action asChild altText={item.action.label}>
|
||||
<button type="button" className="btn" onClick={item.action.onClick}>
|
||||
<button type="button" className="btn rg-p-button" onClick={item.action.onClick}>
|
||||
{item.action.label}
|
||||
</button>
|
||||
</RToast.Action>
|
||||
@@ -110,7 +114,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
|
||||
)}
|
||||
{item.action && (
|
||||
<RToast.Action asChild altText={item.action.label}>
|
||||
<button type="button" className="btn toast-action-btn" onClick={item.action.onClick}>
|
||||
<button type="button" className="btn rg-p-button toast-action-btn" onClick={item.action.onClick}>
|
||||
{item.action.label}
|
||||
</button>
|
||||
</RToast.Action>
|
||||
|
||||
@@ -57,8 +57,9 @@ export function hideWailsGlobals(): void {
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
})
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// non-configurable in some test environments
|
||||
console.warn('[wails] hide window.go failed:', e)
|
||||
}
|
||||
try {
|
||||
const minimalRuntime = typeof capturedRuntime.ResolveFilePaths === 'function'
|
||||
@@ -71,8 +72,9 @@ export function hideWailsGlobals(): void {
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
})
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// ignore if non-configurable
|
||||
console.warn('[wails] hide window.runtime failed:', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,8 +127,8 @@ function eventsOn<T>(eventName: string, cb: (data: T) => void): () => void {
|
||||
return () => {
|
||||
try {
|
||||
off()
|
||||
} catch {
|
||||
// ignore
|
||||
} catch (e) {
|
||||
console.warn('[wails] unsubscribe event failed:', eventName, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,8 +140,9 @@ function eventsEmit(eventName: string, ...args: unknown[]): void {
|
||||
return
|
||||
}
|
||||
;(RawEventsEmit as (name: string, ...data: unknown[]) => void)(eventName, ...args)
|
||||
} catch {
|
||||
// ignore if Wails runtime is unavailable (e.g. standalone preview)
|
||||
} catch (e) {
|
||||
// Wails runtime may be unavailable (e.g. standalone preview)
|
||||
console.warn('[wails] emit event failed:', eventName, e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+107
-104
@@ -16,7 +16,25 @@
|
||||
"rg-p-statusbar",
|
||||
"rg-p-logpanel",
|
||||
"rg-p-settings",
|
||||
"rg-p-empty"
|
||||
"rg-p-empty",
|
||||
"rg-p-nav-group",
|
||||
"rg-p-nav-item",
|
||||
"rg-p-button",
|
||||
"rg-p-icon-button",
|
||||
"rg-p-card",
|
||||
"rg-p-badge",
|
||||
"rg-p-tabs",
|
||||
"rg-p-tab",
|
||||
"rg-p-menu",
|
||||
"rg-p-menu-item",
|
||||
"rg-p-dialog",
|
||||
"rg-p-toast",
|
||||
"rg-p-tooltip",
|
||||
"rg-p-input",
|
||||
"rg-p-switch",
|
||||
"rg-p-progress",
|
||||
"rg-p-vm-actions",
|
||||
"rg-p-plugin-view"
|
||||
],
|
||||
"stateAttrs": [
|
||||
"data-theme",
|
||||
@@ -27,20 +45,95 @@
|
||||
"data-busy",
|
||||
"data-has-error",
|
||||
"data-sidebar-collapsed",
|
||||
"data-safe-mode"
|
||||
"data-safe-mode",
|
||||
"data-layout-sidebar",
|
||||
"data-layout-sidebar-mode",
|
||||
"data-layout-density",
|
||||
"data-layout-titlebar"
|
||||
],
|
||||
"itemStates": [
|
||||
"rg-p-nav-item:data-vm-state",
|
||||
"rg-p-nav-item:data-driver",
|
||||
"rg-p-nav-item:data-selected",
|
||||
"rg-p-nav-item:data-busy",
|
||||
"rg-p-vm-page:data-vm-state",
|
||||
"rg-p-vm-page:data-driver",
|
||||
"rg-p-button:data-variant",
|
||||
"rg-p-button:data-busy",
|
||||
"rg-p-icon-button:data-busy",
|
||||
"rg-p-dialog:data-tone",
|
||||
"rg-p-toast:data-tone"
|
||||
],
|
||||
"slots": [
|
||||
"titlebar.center",
|
||||
"sidebar.header",
|
||||
"sidebar.footer",
|
||||
"statusbar.right",
|
||||
"nav.item.trailing",
|
||||
"vm.header.trailing",
|
||||
"vm.toolbar",
|
||||
"vm.card",
|
||||
"settings.plugin",
|
||||
"vm.preview.tl",
|
||||
"vm.preview.tr",
|
||||
"vm.preview.bl",
|
||||
"vm.preview.br",
|
||||
"empty.state"
|
||||
"statusbar.left",
|
||||
"statusbar.right",
|
||||
"empty.state",
|
||||
"create.source",
|
||||
"settings.plugin"
|
||||
],
|
||||
"layers": [
|
||||
"layer.background",
|
||||
"layer.overlay"
|
||||
],
|
||||
"layoutOptions": [
|
||||
"sidebarPosition=left",
|
||||
"sidebarPosition=right",
|
||||
"sidebarMode=full",
|
||||
"sidebarMode=rail",
|
||||
"sidebarMode=floating",
|
||||
"density=compact",
|
||||
"density=regular",
|
||||
"density=comfortable",
|
||||
"titlebar=standard",
|
||||
"titlebar=compact"
|
||||
],
|
||||
"icons": [
|
||||
"start",
|
||||
"stop",
|
||||
"force-stop",
|
||||
"restart",
|
||||
"suspend",
|
||||
"resume",
|
||||
"new-vm",
|
||||
"settings",
|
||||
"plugin",
|
||||
"folder",
|
||||
"logs",
|
||||
"screenshot",
|
||||
"fullscreen",
|
||||
"window",
|
||||
"snapshot",
|
||||
"clone",
|
||||
"delete",
|
||||
"info",
|
||||
"warning",
|
||||
"error",
|
||||
"vm.state.running",
|
||||
"vm.state.stopped",
|
||||
"vm.state.suspended",
|
||||
"vm.state.busy",
|
||||
"vm.state.error"
|
||||
],
|
||||
"viewLocations": [],
|
||||
"sdkEvents": [
|
||||
"vm.stateChanged",
|
||||
"task.started",
|
||||
"task.progress",
|
||||
"task.finished",
|
||||
"toast.shown",
|
||||
"view.changed"
|
||||
],
|
||||
"layers": [],
|
||||
"tokens": [
|
||||
"--font-sans",
|
||||
"--font-cjk",
|
||||
@@ -131,109 +224,19 @@
|
||||
"--page-max"
|
||||
],
|
||||
"experimental": {
|
||||
"parts": [
|
||||
"rg-p-nav-group",
|
||||
"rg-p-nav-item",
|
||||
"rg-p-button",
|
||||
"rg-p-icon-button",
|
||||
"rg-p-card",
|
||||
"rg-p-badge",
|
||||
"rg-p-tabs",
|
||||
"rg-p-tab",
|
||||
"rg-p-menu",
|
||||
"rg-p-menu-item",
|
||||
"rg-p-dialog",
|
||||
"rg-p-toast",
|
||||
"rg-p-tooltip",
|
||||
"rg-p-input",
|
||||
"rg-p-switch",
|
||||
"rg-p-progress",
|
||||
"rg-p-vm-actions",
|
||||
"rg-p-plugin-view"
|
||||
],
|
||||
"stateAttrs": [
|
||||
"data-layout-sidebar",
|
||||
"data-layout-sidebar-mode",
|
||||
"data-layout-density",
|
||||
"data-layout-titlebar"
|
||||
],
|
||||
"itemStates": [
|
||||
"rg-p-nav-item:data-vm-state",
|
||||
"rg-p-nav-item:data-driver",
|
||||
"rg-p-nav-item:data-selected",
|
||||
"rg-p-nav-item:data-busy",
|
||||
"rg-p-vm-page:data-vm-state",
|
||||
"rg-p-vm-page:data-driver",
|
||||
"rg-p-button:data-variant",
|
||||
"rg-p-button:data-busy",
|
||||
"rg-p-dialog:data-tone",
|
||||
"rg-p-toast:data-tone"
|
||||
],
|
||||
"slots": [
|
||||
"titlebar.center",
|
||||
"sidebar.header",
|
||||
"nav.item.trailing",
|
||||
"vm.header.trailing",
|
||||
"vm.toolbar",
|
||||
"statusbar.left",
|
||||
"create.source"
|
||||
],
|
||||
"layers": [
|
||||
"layer.background",
|
||||
"layer.overlay"
|
||||
],
|
||||
"layoutOptions": [
|
||||
"sidebarPosition=left",
|
||||
"sidebarPosition=right",
|
||||
"sidebarMode=full",
|
||||
"sidebarMode=rail",
|
||||
"sidebarMode=floating",
|
||||
"density=compact",
|
||||
"density=regular",
|
||||
"density=comfortable",
|
||||
"titlebar=standard",
|
||||
"titlebar=compact"
|
||||
],
|
||||
"icons": [
|
||||
"start",
|
||||
"stop",
|
||||
"force-stop",
|
||||
"restart",
|
||||
"suspend",
|
||||
"resume",
|
||||
"new-vm",
|
||||
"settings",
|
||||
"plugin",
|
||||
"folder",
|
||||
"logs",
|
||||
"screenshot",
|
||||
"fullscreen",
|
||||
"window",
|
||||
"snapshot",
|
||||
"clone",
|
||||
"delete",
|
||||
"info",
|
||||
"warning",
|
||||
"error",
|
||||
"vm.state.running",
|
||||
"vm.state.stopped",
|
||||
"vm.state.suspended",
|
||||
"vm.state.busy",
|
||||
"vm.state.error"
|
||||
],
|
||||
"parts": [],
|
||||
"stateAttrs": [],
|
||||
"itemStates": [],
|
||||
"slots": [],
|
||||
"layers": [],
|
||||
"layoutOptions": [],
|
||||
"icons": [],
|
||||
"viewLocations": [
|
||||
"sidebar",
|
||||
"vm.tab",
|
||||
"settings",
|
||||
"dialog"
|
||||
],
|
||||
"sdkEvents": [
|
||||
"vm.stateChanged",
|
||||
"task.started",
|
||||
"task.progress",
|
||||
"task.finished",
|
||||
"toast.shown",
|
||||
"view.changed"
|
||||
]
|
||||
"sdkEvents": []
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,7 @@ export namespace app {
|
||||
active_runtime?: runtime.Installed;
|
||||
can_suspend: boolean;
|
||||
vms: driver.VMListItem[];
|
||||
vm_list_error?: string;
|
||||
transitions: Record<string, string>;
|
||||
pending_changes: Record<string, Array<PendingChange>>;
|
||||
active_guides?: string[];
|
||||
@@ -84,6 +85,7 @@ export namespace app {
|
||||
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
|
||||
this.can_suspend = source["can_suspend"];
|
||||
this.vms = this.convertValues(source["vms"], driver.VMListItem);
|
||||
this.vm_list_error = source["vm_list_error"];
|
||||
this.transitions = source["transitions"];
|
||||
this.pending_changes = this.convertValues(source["pending_changes"], Array<PendingChange>, true);
|
||||
this.active_guides = source["active_guides"];
|
||||
@@ -273,6 +275,7 @@ export namespace app {
|
||||
settings_pages?: plugin.SettingsPageContribution[];
|
||||
status_items?: plugin.StatusItemContribution[];
|
||||
panels?: plugin.PanelContribution[];
|
||||
image_sources?: plugin.ImageSourceContribution[];
|
||||
vm_templates?: plugin.VMTemplateContribution[];
|
||||
themes?: plugin.ThemeContribution[];
|
||||
locales?: plugin.ResolvedLocalePack[];
|
||||
@@ -294,6 +297,7 @@ export namespace app {
|
||||
this.settings_pages = this.convertValues(source["settings_pages"], plugin.SettingsPageContribution);
|
||||
this.status_items = this.convertValues(source["status_items"], plugin.StatusItemContribution);
|
||||
this.panels = this.convertValues(source["panels"], plugin.PanelContribution);
|
||||
this.image_sources = this.convertValues(source["image_sources"], plugin.ImageSourceContribution);
|
||||
this.vm_templates = this.convertValues(source["vm_templates"], plugin.VMTemplateContribution);
|
||||
this.themes = this.convertValues(source["themes"], plugin.ThemeContribution);
|
||||
this.locales = this.convertValues(source["locales"], plugin.ResolvedLocalePack);
|
||||
@@ -1307,24 +1311,6 @@ export namespace plugin {
|
||||
this.seeds = source["seeds"];
|
||||
}
|
||||
}
|
||||
export class ThemeLayout {
|
||||
sidebarPosition?: string;
|
||||
sidebarMode?: string;
|
||||
density?: string;
|
||||
titlebar?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ThemeLayout(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.sidebarPosition = source["sidebarPosition"];
|
||||
this.sidebarMode = source["sidebarMode"];
|
||||
this.density = source["density"];
|
||||
this.titlebar = source["titlebar"];
|
||||
}
|
||||
}
|
||||
export class ThemeDecorationState {
|
||||
when: string;
|
||||
asset?: string;
|
||||
@@ -1383,6 +1369,24 @@ export namespace plugin {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class ThemeLayout {
|
||||
sidebarPosition?: string;
|
||||
sidebarMode?: string;
|
||||
density?: string;
|
||||
titlebar?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ThemeLayout(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.sidebarPosition = source["sidebarPosition"];
|
||||
this.sidebarMode = source["sidebarMode"];
|
||||
this.density = source["density"];
|
||||
this.titlebar = source["titlebar"];
|
||||
}
|
||||
}
|
||||
export class ThemeFont {
|
||||
family: string;
|
||||
file: string;
|
||||
@@ -1497,7 +1501,7 @@ export namespace plugin {
|
||||
uiScript?: string;
|
||||
layout?: ThemeLayout;
|
||||
pluginId?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ThemeContribution(source);
|
||||
}
|
||||
@@ -1651,11 +1655,11 @@ export namespace plugin {
|
||||
pluginApi?: string;
|
||||
uiApi?: string;
|
||||
bridgeApi?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Engines(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this["reims-go"] = source["reims-go"];
|
||||
@@ -1981,6 +1985,50 @@ export namespace plugin {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class ImageSourceContribution {
|
||||
id: string;
|
||||
title: LocalizedText;
|
||||
description?: LocalizedText;
|
||||
order?: number;
|
||||
entry?: string;
|
||||
height?: number;
|
||||
native?: string;
|
||||
pluginId?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ImageSourceContribution(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.title = this.convertValues(source["title"], LocalizedText);
|
||||
this.description = this.convertValues(source["description"], LocalizedText);
|
||||
this.order = source["order"];
|
||||
this.entry = source["entry"];
|
||||
this.height = source["height"];
|
||||
this.native = source["native"];
|
||||
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;
|
||||
|
||||
@@ -5,6 +5,7 @@ go 1.26.0
|
||||
require (
|
||||
github.com/go-ole/go-ole v1.3.0
|
||||
github.com/klauspost/compress v1.20.5
|
||||
github.com/pelletier/go-toml/v2 v2.4.3
|
||||
github.com/ulikunitz/xz v0.5.17
|
||||
github.com/wailsapp/wails/v2 v2.17.1
|
||||
golang.org/x/net v0.60.0
|
||||
|
||||
@@ -39,6 +39,8 @@ github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy
|
||||
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
|
||||
+29
-3
@@ -56,6 +56,7 @@ type AppState struct {
|
||||
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
|
||||
CanSuspend bool `json:"can_suspend"`
|
||||
VMs []driver.VMListItem `json:"vms"`
|
||||
VMListError string `json:"vm_list_error,omitempty"`
|
||||
Transitions map[string]string `json:"transitions"`
|
||||
PendingChanges map[string][]PendingChange `json:"pending_changes"`
|
||||
ActiveGuides []string `json:"active_guides,omitempty"`
|
||||
@@ -114,6 +115,7 @@ type App struct {
|
||||
vmStarts sync.WaitGroup
|
||||
lastVMs []driver.VMListItem
|
||||
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
||||
lastVMListErr error
|
||||
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
|
||||
diskPaths map[string]cachedDiskPath
|
||||
procSamples map[string]host.ProcessSample
|
||||
@@ -335,6 +337,17 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
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
|
||||
}
|
||||
watchExits(ctx, vms, exitWatched, a.wakePoll)
|
||||
@@ -419,6 +432,8 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
gt := a.guestTools
|
||||
a.lastVMs = append([]driver.VMListItem(nil), vms...)
|
||||
a.lastVMsAt = time.Now()
|
||||
listRecovered := a.lastVMListErr != nil
|
||||
a.lastVMListErr = nil
|
||||
a.mu.Unlock()
|
||||
prunePinnedPIDs(pinnedPIDs, vms)
|
||||
prunePinnedPIDs(guideCheckedPIDs, vms)
|
||||
@@ -512,7 +527,7 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if sig != lastSig || guidesChanged {
|
||||
if sig != lastSig || guidesChanged || listRecovered {
|
||||
lastSig = sig
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -600,8 +615,9 @@ 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, nil
|
||||
return vms, err
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return a.listVMsInternal(ctx)
|
||||
@@ -702,7 +718,15 @@ func (a *App) GetState() AppState {
|
||||
active, _ := rt.ResolveActive(&cfgCopy)
|
||||
// The poller's list (≤ polledMaxAge old, and invalidated by wakePoll after
|
||||
// start/stop/delete) instead of another `reims-ctl list` per refresh.
|
||||
vms, _ := a.polledVMs(context.Background())
|
||||
var vms []driver.VMListItem
|
||||
var listError string
|
||||
if !needsSetup && !rootStatus.ReadOnly {
|
||||
var err error
|
||||
vms, err = a.polledVMs(context.Background())
|
||||
if err != nil {
|
||||
listError = host.RedactText(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
opts := a.evaluateOptimizations(rep)
|
||||
|
||||
@@ -735,6 +759,7 @@ func (a *App) GetState() AppState {
|
||||
ActiveRuntime: active,
|
||||
CanSuspend: active != nil && active.Manifest.HasCapability("vm-suspend"),
|
||||
VMs: vms,
|
||||
VMListError: listError,
|
||||
Transitions: trCopy,
|
||||
PendingChanges: pcCopy,
|
||||
ActiveGuides: activeGuides,
|
||||
@@ -935,6 +960,7 @@ func (a *App) resetDataRootCaches() {
|
||||
a.mu.Lock()
|
||||
a.lastVMs = nil
|
||||
a.lastVMsAt = time.Time{}
|
||||
a.lastVMListErr = nil
|
||||
a.diskPaths = make(map[string]cachedDiskPath)
|
||||
a.procSamples = make(map[string]host.ProcessSample)
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -2,6 +2,7 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
type appSecondDriver struct {
|
||||
id string
|
||||
vms []driver.VMInfo
|
||||
listErr error
|
||||
starts, stops, deletes, sets int
|
||||
actions []string
|
||||
actionResults map[string]any
|
||||
@@ -28,7 +30,7 @@ func (d *appSecondDriver) RuntimeAPIRange() string { retur
|
||||
func (d *appSecondDriver) Capabilities() []string { return nil }
|
||||
func (d *appSecondDriver) CreateSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *appSecondDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *appSecondDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, nil }
|
||||
func (d *appSecondDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, d.listErr }
|
||||
func (d *appSecondDriver) Show(_ context.Context, name string) (driver.VMInfo, error) {
|
||||
for _, vm := range d.vms {
|
||||
if vm.Name == name {
|
||||
@@ -113,6 +115,31 @@ func TestAppSecondDriverUserEntry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestForceQuitWithUnreachableVMDriver(t *testing.T) {
|
||||
const driverID = "test.driver.unreachable"
|
||||
listErr := errors.New("runtime unavailable")
|
||||
drv := &appSecondDriver{id: driverID, listErr: listErr}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := reg.Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{ID: "test.unreachable", Version: "1.0.0"},
|
||||
Source: plugin.SourceBuiltin, Desired: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
reg.RegisterGuestDriver(sc, driverID, drv)
|
||||
return nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(t.Context())
|
||||
a := &App{
|
||||
cfg: &config.Config{DataRoot: t.TempDir()},
|
||||
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
|
||||
}
|
||||
if err := a.ForceQuitApp(); !errors.Is(err, listErr) || a.allowQuit {
|
||||
t.Fatalf("force quit: err=%v, allowQuit=%v", err, a.allowQuit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppRecoveryActionsUseLifecycle(t *testing.T) {
|
||||
const driverID = driver.BuiltinReimsMacOSDriverID
|
||||
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "running"}}, actionResults: map[string]any{
|
||||
|
||||
@@ -41,6 +41,7 @@ type PluginUIContributions struct {
|
||||
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
|
||||
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
|
||||
Panels []plugin.PanelContribution `json:"panels,omitempty"`
|
||||
ImageSources []plugin.ImageSourceContribution `json:"image_sources,omitempty"`
|
||||
VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"`
|
||||
Themes []plugin.ThemeContribution `json:"themes,omitempty"`
|
||||
Locales []plugin.ResolvedLocalePack `json:"locales,omitempty"`
|
||||
@@ -96,7 +97,7 @@ func (a *App) initPlugins() {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.DataRoot
|
||||
})
|
||||
}, guest.VMInventory())
|
||||
|
||||
mgr.Registry().SetInUseChecker(drvRouter.PluginInUseChecker())
|
||||
mgr.Registry().SetBusyChecker(drvRouter.PluginBusyChecker())
|
||||
@@ -196,6 +197,7 @@ func (a *App) initPlugins() {
|
||||
a.syncKeymapRules()
|
||||
a.syncClipboardPolicies()
|
||||
a.syncLocales()
|
||||
a.wakePoll()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
@@ -727,6 +729,7 @@ func (a *App) GetPluginUIContributions() PluginUIContributions {
|
||||
SettingsPages: mgr.LocalizeSettingsPages(reg.SettingsPages()),
|
||||
StatusItems: mgr.LocalizeStatusItems(reg.StatusItems()),
|
||||
Panels: mgr.LocalizePanels(reg.Panels("")),
|
||||
ImageSources: mgr.LocalizeImageSources(reg.ImageSources()),
|
||||
VMTemplates: reg.VMTemplates(),
|
||||
Themes: reg.Themes(),
|
||||
Locales: uiLocales,
|
||||
|
||||
+4
-4
@@ -388,16 +388,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
vms, err := svc.List(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(vms) == 0 {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "vm.empty"))
|
||||
return nil
|
||||
}
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(vms)
|
||||
return errors.Join(enc.Encode(vms), err)
|
||||
case "create":
|
||||
fs := flag.NewFlagSet("vm create", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)")
|
||||
|
||||
@@ -2,6 +2,7 @@ package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -11,11 +12,13 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
)
|
||||
|
||||
@@ -49,6 +52,17 @@ func checkDirectMacOSNetwork(ctx context.Context, cfg *config.Config, name strin
|
||||
return nil
|
||||
}
|
||||
|
||||
func requireCLIMacOSEnabled(cfg *config.Config, loc i18n.Locale) error {
|
||||
st, err := plugin.NewStateStore(plugin.NewPluginsLayout(cfg.DataRoot).Root).Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry := st.Plugins[guest.ID]; entry != nil && !entry.Enabled {
|
||||
return errors.New(i18n.T(loc, "err.macos.disabled"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// macOSCreateOptions is the CLI-neutral input to the native macOS create flow.
|
||||
type macOSCreateOptions struct {
|
||||
Name, Dir, MacOS, Memory, DiskSize, GPU, GuestLang string
|
||||
@@ -57,6 +71,9 @@ type macOSCreateOptions struct {
|
||||
}
|
||||
|
||||
func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in macOSCreateOptions, startAfterCreate, viaWindow bool) error {
|
||||
if err := requireCLIMacOSEnabled(cfg, loc); err != nil {
|
||||
return err
|
||||
}
|
||||
prep, err := startprep.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -102,7 +119,7 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in
|
||||
}
|
||||
}
|
||||
if startAfterCreate {
|
||||
if err := startVM(ctx, cfg, in.Name, viaWindow); err != nil {
|
||||
if err := startVMWithDriver(ctx, cfg, driver.BuiltinReimsMacOSDriverID, in.Name, viaWindow); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -117,6 +134,9 @@ func typeMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, args
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm type <name> [text] (no text: read stdin)")
|
||||
}
|
||||
if err := requireCLIMacOSEnabled(cfg, loc); err != nil {
|
||||
return err
|
||||
}
|
||||
prep, err := startprep.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -48,8 +48,12 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
Log: func(source, line string) {
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
|
||||
},
|
||||
GetSetting: func(pluginID, vmName, key string) (any, bool) {
|
||||
value, ok := mgr.GetSettings(pluginID, vmName, false)[key]
|
||||
return value, ok
|
||||
},
|
||||
}
|
||||
router := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { return cfg.DataRoot })
|
||||
router := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory())
|
||||
mgr.Registry().SetInUseChecker(router.PluginInUseChecker())
|
||||
mgr.Registry().SetBusyChecker(router.PluginBusyChecker())
|
||||
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
||||
|
||||
@@ -1,11 +1,85 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
func TestMacOSPluginDisableAndVMInventory(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
args := []string{"--data-root", root, "--lang", "en-US"}
|
||||
runCLI := func(command ...string) error {
|
||||
_, err := run(append(args, command...))
|
||||
return err
|
||||
}
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", filepath.Join(root, "config", "reims-ctl"))
|
||||
if err := runCLI("plugin", "disable", "builtin.guest.macos"); err != nil {
|
||||
t.Fatalf("disable without a runtime or VMs: %v", err)
|
||||
}
|
||||
for _, cmd := range [][]string{{"vm", "create", "--start", "mac"}, {"vm", "type", "mac", "test"}} {
|
||||
if err := runCLI(cmd...); err == nil || err.Error() != i18n.T(i18n.EnUS, "err.macos.disabled") {
|
||||
t.Fatalf("%v while disabled: %v", cmd, err)
|
||||
}
|
||||
}
|
||||
|
||||
vmDir := filepath.Join(t.TempDir(), "folder-different-from-vm-name")
|
||||
cfg := &config.Config{DataRoot: root}
|
||||
registryDir := filepath.Join(cfg.XDGConfigDir(), "reims-ctl")
|
||||
if err := os.MkdirAll(registryDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := filepath.Join(registryDir, "vms.toml")
|
||||
content := fmt.Sprintf("[[vm]]\nname = %q\ndir = %q\n", "Mac Work", vmDir)
|
||||
if err := os.WriteFile(registry, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr, router, err := openCLIPluginManager(cfg, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
vms, err := router.ListAllVMs(t.Context())
|
||||
if err != nil || len(vms) != 1 || vms[0].Name != "Mac Work" || vms[0].Directory != vmDir ||
|
||||
vms[0].DriverID != driver.BuiltinReimsMacOSDriverID || !vms[0].DriverUnavailable {
|
||||
t.Fatalf("disabled list = %+v, %v", vms, err)
|
||||
}
|
||||
if _, vm, err := router.ResolveVM(t.Context(), "mac work"); err == nil || vm.Directory != vmDir || !vm.DriverUnavailable {
|
||||
t.Fatalf("disabled lookup = %+v, %v", vm, err)
|
||||
}
|
||||
|
||||
if err := runCLI("plugin", "enable", "builtin.guest.macos"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := runCLI("vm", "list"); !errors.Is(err, rt.ErrNoActiveRuntime) {
|
||||
t.Fatalf("list with registered VMs and no runtime = %v", err)
|
||||
}
|
||||
if err := runCLI("plugin", "disable", "builtin.guest.macos"); !errors.Is(err, rt.ErrNoActiveRuntime) {
|
||||
t.Fatalf("disabling with registered VMs and unknown state = %v", err)
|
||||
}
|
||||
|
||||
// An installed runtime with a missing control executable must also fail its
|
||||
// enumeration rather than show an empty VM list.
|
||||
runtimeDir := filepath.Join(cfg.RuntimesDir(), "test")
|
||||
if err := os.MkdirAll(runtimeDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte(`{"commit":"test"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := runCLI("vm", "list"); err == nil || !strings.Contains(err.Error(), "reims-ctl list") {
|
||||
t.Fatalf("list with an unusable runtime = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIPluginListEnableDisableAndDoctor(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
// `plugin list` should succeed and include builtins.
|
||||
|
||||
@@ -21,17 +21,13 @@ import (
|
||||
// report back. Preparation can rebuild the OpenCore image before QEMU starts.
|
||||
const startHandoffTimeout = 5 * time.Minute
|
||||
|
||||
// startVM checks the VM can start, then hands it to the desktop window: the
|
||||
// startVMWithDriver resolves the VM, then hands it to the desktop window: the
|
||||
// one already running, or a new one in the tray (`--background`). The window
|
||||
// runs the GUI's StartVM, so a VM started from the command line gets Guest
|
||||
// Tools and the Win10 cold-reboot watcher too; both need a process that stays
|
||||
// up after this command exits.
|
||||
//
|
||||
// 显式传入管理器当前数据目录仍交给管理器;其他目录的桥接禁止直接启动。
|
||||
func startVM(ctx context.Context, cfg *config.Config, name string, viaWindow bool) error {
|
||||
return startVMWithDriver(ctx, cfg, "", name, viaWindow)
|
||||
}
|
||||
|
||||
func startVMWithDriver(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error {
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
|
||||
@@ -5,6 +5,8 @@ package downloader
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
@@ -20,21 +22,35 @@ const (
|
||||
|
||||
// Request describes a single file or file-region download handed to a Provider.
|
||||
type Request struct {
|
||||
URL string `json:"url"`
|
||||
DestPath string `json:"dest_path"`
|
||||
DestOffset int64 `json:"dest_offset,omitempty"`
|
||||
ExpectedSize int64 `json:"expected_size,omitempty"`
|
||||
IntegrityURL string `json:"integrity_url,omitempty"`
|
||||
IntegrityBytes []byte `json:"integrity_bytes,omitempty"`
|
||||
ExpectedSHA256 string `json:"expected_sha256,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Resume bool `json:"resume"`
|
||||
DirectHint bool `json:"direct_hint,omitempty"`
|
||||
URL string `json:"url"`
|
||||
DestPath string `json:"dest_path"`
|
||||
DestOffset int64 `json:"dest_offset,omitempty"`
|
||||
ExpectedSize int64 `json:"expected_size,omitempty"`
|
||||
IntegrityURL string `json:"integrity_url,omitempty"`
|
||||
IntegrityBytes []byte `json:"integrity_bytes,omitempty"`
|
||||
ExpectedSHA256 string `json:"expected_sha256,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Resume bool `json:"resume"`
|
||||
DirectHint bool `json:"direct_hint,omitempty"`
|
||||
SameOriginRedirects bool `json:"same_origin_redirects,omitempty"`
|
||||
// RefreshHeaders optionally fetches fresh auth headers (such as a new Apple
|
||||
// osrecovery AssetToken cookie) when a range request returns HTTP 401/403.
|
||||
RefreshHeaders func(ctx context.Context) (map[string]string, error) `json:"-"`
|
||||
}
|
||||
|
||||
// CheckSameOriginRedirect limits redirects for downloads carrying origin-bound
|
||||
// credentials and preserves net/http's default redirect limit.
|
||||
func CheckSameOriginRedirect(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return fmt.Errorf("stopped after %d redirects", len(via))
|
||||
}
|
||||
origin := via[0].URL
|
||||
if req.URL.Scheme != origin.Scheme || !strings.EqualFold(req.URL.Host, origin.Host) || req.URL.User != nil {
|
||||
return fmt.Errorf("download redirected outside its origin")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Progress reports live download state back to the host UI/CLI.
|
||||
type Progress struct {
|
||||
Done int64 `json:"done"`
|
||||
|
||||
@@ -187,6 +187,9 @@ func (p *ParallelDownloader) Download(ctx context.Context, req Request, onProgre
|
||||
}
|
||||
opts := p.options()
|
||||
client := buildHTTPClient(opts, req.URL, req.DirectHint)
|
||||
if req.SameOriginRedirects {
|
||||
client.CheckRedirect = CheckSameOriginRedirect
|
||||
}
|
||||
defer client.CloseIdleConnections()
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(req.DestPath), 0o755); err != nil {
|
||||
|
||||
+83
-81
@@ -244,6 +244,13 @@ type Router struct {
|
||||
reg *plugin.Registry
|
||||
dataRootDir func() string // DataRoot for statically declared guest VM roots
|
||||
legacyVMRoot func() string // compatibility root for tests and older embedders
|
||||
inventories []VMInventory
|
||||
}
|
||||
|
||||
// VMInventory exposes persisted registrations without invoking a guest driver.
|
||||
type VMInventory struct {
|
||||
DriverID string
|
||||
List func(dataRoot string) ([]VMInfo, error)
|
||||
}
|
||||
|
||||
// NewRouter creates a driver Router backed by reg.
|
||||
@@ -251,9 +258,10 @@ func NewRouter(reg *plugin.Registry, vmRootDir func() string) *Router {
|
||||
return &Router{reg: reg, legacyVMRoot: vmRootDir}
|
||||
}
|
||||
|
||||
// NewRouterWithDataRoot scans only VM roots declared by registered drivers.
|
||||
func NewRouterWithDataRoot(reg *plugin.Registry, dataRootDir func() string) *Router {
|
||||
return &Router{reg: reg, dataRootDir: dataRootDir}
|
||||
// NewRouterWithDataRoot discovers unavailable VMs through driver inventories
|
||||
// or through ownership markers in declared roots.
|
||||
func NewRouterWithDataRoot(reg *plugin.Registry, dataRootDir func() string, inventories ...VMInventory) *Router {
|
||||
return &Router{reg: reg, dataRootDir: dataRootDir, inventories: inventories}
|
||||
}
|
||||
|
||||
func (rt *Router) vmRoots() []string {
|
||||
@@ -352,10 +360,11 @@ func (rt *Router) DriverByID(id string) (Driver, error) {
|
||||
func (rt *Router) ListAllVMs(ctx context.Context) ([]VMInfo, error) {
|
||||
seen := make(map[string]bool)
|
||||
var out []VMInfo
|
||||
var errs []error
|
||||
for _, d := range rt.Drivers() {
|
||||
vms, err := d.List(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
errs = append(errs, fmt.Errorf("list VMs for driver %q: %w", d.ID(), err))
|
||||
}
|
||||
for _, vm := range vms {
|
||||
vm.DriverID = d.ID()
|
||||
@@ -371,7 +380,51 @@ func (rt *Router) ListAllVMs(ctx context.Context) ([]VMInfo, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Declared roots retain VMs whose driver is disabled or missing.
|
||||
unavailable, err := rt.listUnavailableVMs("")
|
||||
out = append(out, unavailable...)
|
||||
errs = append(errs, err)
|
||||
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
ni, nj := strings.ToLower(out[i].Name), strings.ToLower(out[j].Name)
|
||||
if ni != nj {
|
||||
return ni < nj
|
||||
}
|
||||
return out[i].DriverID < out[j].DriverID
|
||||
})
|
||||
return out, errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (rt *Router) listUnavailableVMs(driverID string) ([]VMInfo, error) {
|
||||
var out []VMInfo
|
||||
var errs []error
|
||||
inventoried := make(map[string]bool)
|
||||
seen := make(map[string]bool)
|
||||
add := func(vm VMInfo) {
|
||||
key := foldedRefKey(vm.DriverID, vm.Name)
|
||||
if !seen[key] {
|
||||
vm.State, vm.DriverUnavailable = "driver_unavailable", true
|
||||
out = append(out, vm)
|
||||
seen[key] = true
|
||||
}
|
||||
}
|
||||
if rt.dataRootDir != nil {
|
||||
for _, inventory := range rt.inventories {
|
||||
id := CanonicalDriverID(inventory.DriverID)
|
||||
if _, active := rt.reg.GuestDriver(id); active || (driverID != "" && driverID != id) {
|
||||
continue
|
||||
}
|
||||
vms, err := inventory.List(rt.dataRootDir())
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("read VM registrations for driver %q: %w", id, err))
|
||||
continue
|
||||
}
|
||||
inventoried[id] = true
|
||||
for _, vm := range vms {
|
||||
vm.DriverID = id
|
||||
add(vm)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, root := range rt.vmRoots() {
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
@@ -386,92 +439,44 @@ func (rt *Router) ListAllVMs(ctx context.Context) ([]VMInfo, error) {
|
||||
continue
|
||||
}
|
||||
owner := ReadOwnerDriver(vmDir)
|
||||
key := foldedRefKey(owner, e.Name())
|
||||
if seen[key] {
|
||||
if _, active := rt.reg.GuestDriver(owner); active || inventoried[owner] || (driverID != "" && owner != driverID) {
|
||||
continue
|
||||
}
|
||||
if _, ok := rt.reg.GuestDriver(owner); ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
out = append(out, VMInfo{
|
||||
Name: e.Name(), DriverID: owner, State: "driver_unavailable",
|
||||
Directory: vmDir, DriverUnavailable: true,
|
||||
})
|
||||
add(VMInfo{Name: e.Name(), DriverID: owner, Directory: vmDir})
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
ni, nj := strings.ToLower(out[i].Name), strings.ToLower(out[j].Name)
|
||||
if ni != nj {
|
||||
return ni < nj
|
||||
}
|
||||
return out[i].DriverID < out[j].DriverID
|
||||
})
|
||||
return out, nil
|
||||
return out, errors.Join(errs...)
|
||||
}
|
||||
|
||||
// ResolveVM resolves a bare name only when exactly one driver owns it.
|
||||
func (rt *Router) ResolveVM(ctx context.Context, vmName string) (Driver, VMInfo, error) {
|
||||
type match struct {
|
||||
d Driver
|
||||
vm VMInfo
|
||||
vms, err := rt.ListAllVMs(ctx)
|
||||
if err != nil {
|
||||
return nil, VMInfo{}, err
|
||||
}
|
||||
byRef := map[string]match{}
|
||||
for _, d := range rt.Drivers() {
|
||||
vms, err := d.List(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if !strings.EqualFold(vm.Name, vmName) {
|
||||
continue
|
||||
}
|
||||
vm.DriverID = d.ID()
|
||||
byRef[foldedRefKey(vm.DriverID, vm.Name)] = match{d: d, vm: vm}
|
||||
var matches []VMInfo
|
||||
for _, vm := range vms {
|
||||
if strings.EqualFold(vm.Name, vmName) {
|
||||
matches = append(matches, vm)
|
||||
}
|
||||
}
|
||||
for _, root := range rt.vmRoots() {
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() || !strings.EqualFold(e.Name(), vmName) {
|
||||
continue
|
||||
}
|
||||
vmDir := filepath.Join(root, e.Name())
|
||||
if _, err := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); err != nil {
|
||||
continue
|
||||
}
|
||||
owner := ReadOwnerDriver(vmDir)
|
||||
if _, active := rt.reg.GuestDriver(owner); active {
|
||||
continue
|
||||
}
|
||||
byRef[foldedRefKey(owner, e.Name())] = match{vm: VMInfo{
|
||||
Name: e.Name(), DriverID: owner, State: "driver_unavailable",
|
||||
Directory: vmDir, DriverUnavailable: true,
|
||||
}}
|
||||
}
|
||||
}
|
||||
if len(byRef) == 0 {
|
||||
if len(matches) == 0 {
|
||||
return nil, VMInfo{}, fmt.Errorf("VM %q not found in any active driver", vmName)
|
||||
}
|
||||
if len(byRef) > 1 {
|
||||
ids := make([]string, 0, len(byRef))
|
||||
for _, m := range byRef {
|
||||
ids = append(ids, m.vm.DriverID)
|
||||
if len(matches) > 1 {
|
||||
ids := make([]string, 0, len(matches))
|
||||
for _, vm := range matches {
|
||||
ids = append(ids, vm.DriverID)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
return nil, VMInfo{}, &AmbiguousVMError{Name: vmName, DriverIDs: ids}
|
||||
}
|
||||
for _, m := range byRef {
|
||||
if m.d == nil {
|
||||
return nil, m.vm, fmt.Errorf("VM %q requires driver %q which is currently unavailable", vmName, m.vm.DriverID)
|
||||
}
|
||||
return m.d, m.vm, nil
|
||||
vm := matches[0]
|
||||
if vm.DriverUnavailable {
|
||||
return nil, vm, fmt.Errorf("VM %q requires driver %q which is currently unavailable", vmName, vm.DriverID)
|
||||
}
|
||||
panic("unreachable")
|
||||
d, err := rt.DriverByID(vm.DriverID)
|
||||
return d, vm, err
|
||||
}
|
||||
|
||||
// ResolveRef resolves a VM within an explicit owning driver.
|
||||
@@ -486,16 +491,13 @@ func (rt *Router) ResolveRef(ctx context.Context, ref VMRef) (Driver, VMInfo, er
|
||||
vm.DriverID = d.ID()
|
||||
return d, vm, nil
|
||||
}
|
||||
for _, root := range rt.vmRoots() {
|
||||
vmDir := filepath.Join(root, ref.Name)
|
||||
if _, statErr := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); statErr != nil {
|
||||
continue
|
||||
}
|
||||
if ReadOwnerDriver(vmDir) == ref.DriverID {
|
||||
return nil, VMInfo{Name: ref.Name, DriverID: ref.DriverID, State: "driver_unavailable", Directory: vmDir, DriverUnavailable: true}, err
|
||||
unavailable, inventoryErr := rt.listUnavailableVMs(ref.DriverID)
|
||||
for _, vm := range unavailable {
|
||||
if strings.EqualFold(vm.Name, ref.Name) {
|
||||
return nil, vm, err
|
||||
}
|
||||
}
|
||||
return nil, VMInfo{}, err
|
||||
return nil, VMInfo{}, errors.Join(err, inventoryErr)
|
||||
}
|
||||
|
||||
// PluginInUseChecker reports a plugin as in use while a guest driver it
|
||||
|
||||
@@ -511,7 +511,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"showSidebar": "显示侧边栏",
|
||||
"shutdownMode": "关机方式",
|
||||
"sidebarHost": "内核",
|
||||
"sidebarInstallers": "安装包",
|
||||
"sidebarInstallers": "镜像",
|
||||
"sidebarItemAria": "{label},{state}",
|
||||
"sidebarLabel": "侧边栏",
|
||||
"sidebarPlugins": "插件",
|
||||
@@ -1159,7 +1159,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"showSidebar": "Show sidebar",
|
||||
"shutdownMode": "Shutdown mode",
|
||||
"sidebarHost": "Engine",
|
||||
"sidebarInstallers": "Installers",
|
||||
"sidebarInstallers": "Images",
|
||||
"sidebarItemAria": "{label}, {state}",
|
||||
"sidebarLabel": "Sidebar",
|
||||
"sidebarPlugins": "Plugins",
|
||||
|
||||
@@ -142,6 +142,7 @@ func Definition(ver string, cb builtin.HostCallbacks, desired bool) plugin.Plugi
|
||||
Activate: func(ctx context.Context, sc *plugin.Scope) error {
|
||||
drv := macosdriver.NewReimsMacOSDriver(cb.GetConfig, macosdriver.Options{
|
||||
OwnerID: ID,
|
||||
ManagedByDesktop: cb.StartColdReboot != nil,
|
||||
WHPXFallbackEnabled: func() bool { return settingOn(cb, SettingWHPXFallback) },
|
||||
ColdRebootEnabled: func() bool { return settingOn(cb, SettingWin10ColdReboot) },
|
||||
MigrateLedger: func(l *plugin.ArgLedger) { MigrateLedger(l) },
|
||||
|
||||
@@ -188,3 +188,33 @@ func TestInstallGuideSettingAndPluginLifecycle(t *testing.T) {
|
||||
t.Fatal("setting off still provided guide")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuiltinMacOSImagesPluginLifecycle(t *testing.T) {
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := Register(reg, testCallbacks(t, nil), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
if !reg.IsActive(IDImages) {
|
||||
t.Fatal("macOS images plugin should default to active")
|
||||
}
|
||||
sources := reg.ImageSources()
|
||||
if len(sources) != 1 || sources[0].PluginID != IDImages || sources[0].Native != NativeImageSourceMacOS {
|
||||
t.Fatalf("unexpected image sources: %+v", sources)
|
||||
}
|
||||
if err := reg.SetDesired(context.Background(), IDImages, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reg.IsActive(IDImages) {
|
||||
t.Fatal("macOS images plugin did not disable")
|
||||
}
|
||||
if got := reg.ImageSources(); len(got) != 0 {
|
||||
t.Fatalf("expected zero image sources after disable, got %+v", got)
|
||||
}
|
||||
if err := reg.SetDesired(context.Background(), IDImages, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := reg.ImageSources(); len(got) != 1 || got[0].ID != NativeImageSourceMacOS {
|
||||
t.Fatalf("expected macOS image source restored after re-enable, got %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package guest
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/plugin"
|
||||
|
||||
// IDImages is the built-in optional plugin that provides the macOS image
|
||||
// catalog and local image management tab inside the Images page.
|
||||
const IDImages = "builtin.images.macos"
|
||||
|
||||
// NativeImageSourceMacOS identifies the host-mounted native macOS image view.
|
||||
const NativeImageSourceMacOS = "macos"
|
||||
|
||||
// ImagesDefinition describes the built-in macOS image source plugin.
|
||||
func ImagesDefinition(ver string, desired bool) plugin.PluginDef {
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDImages,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "macOS 镜像源", EnUS: "macOS Images"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "提供 Apple 官方 macOS 镜像目录浏览、下载与本地管理",
|
||||
EnUS: "Browse, download, and manage official macOS images from Apple",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Permissions: []string{"ui:slot"},
|
||||
DefaultEnabled: true,
|
||||
Contributes: plugin.Contributes{
|
||||
ImageSources: []plugin.ImageSourceContribution{{
|
||||
ID: NativeImageSourceMacOS,
|
||||
Title: plugin.LocalizedText{ZhCN: "macOS", EnUS: "macOS"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "Apple 提供的官方 macOS 镜像",
|
||||
EnUS: "Official macOS images from Apple",
|
||||
},
|
||||
Order: 0,
|
||||
Native: NativeImageSourceMacOS,
|
||||
}},
|
||||
},
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desired,
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,26 @@ package guest
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
// Register adds the optional built-in macOS guest plugin to reg.
|
||||
// VMInventory keeps registered VMs discoverable while macOS support is disabled.
|
||||
func VMInventory() driver.VMInventory {
|
||||
return driver.VMInventory{DriverID: IDDriver, List: reims.ListRegisteredVMs}
|
||||
}
|
||||
|
||||
// Register adds the optional built-in macOS plugins (guest driver + image source) to reg.
|
||||
func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) error {
|
||||
if desiredFn == nil {
|
||||
desiredFn = func(_ string, def bool) bool { return def }
|
||||
}
|
||||
ver := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
|
||||
return reg.Register(Definition(ver, cb, desiredFn(ID, true)))
|
||||
if err := reg.Register(Definition(ver, cb, desiredFn(ID, true))); err != nil {
|
||||
return err
|
||||
}
|
||||
return reg.Register(ImagesDefinition(ver, desiredFn(IDImages, true)))
|
||||
}
|
||||
@@ -231,14 +231,15 @@ func (c *Client) downloadOfflineAccelerated(ctx context.Context, version string,
|
||||
recStep := fmt.Sprintf("downloading %s recovery (%s)", onRel.Name, prov.ID())
|
||||
onUpdate(Update{Kind: KindStep, Message: recStep, Step: recStep, Percent: -1})
|
||||
rErr := prov.Download(ctx, downloader.Request{
|
||||
URL: asset.AssetURL,
|
||||
DestPath: partPath,
|
||||
DestOffset: rec.dmgOffset,
|
||||
ExpectedSize: rec.dmgSize,
|
||||
IntegrityBytes: rec.chunklist,
|
||||
Headers: recoveryHeaders(asset.AssetToken),
|
||||
Resume: true,
|
||||
DirectHint: true,
|
||||
URL: asset.AssetURL,
|
||||
DestPath: partPath,
|
||||
DestOffset: rec.dmgOffset,
|
||||
ExpectedSize: rec.dmgSize,
|
||||
IntegrityBytes: rec.chunklist,
|
||||
Headers: recoveryHeaders(asset.AssetToken),
|
||||
Resume: true,
|
||||
DirectHint: true,
|
||||
SameOriginRedirects: true,
|
||||
RefreshHeaders: func(rctx context.Context) (map[string]string, error) {
|
||||
fresh, ferr := fetchRecoveryAsset(rctx, httpClient, osRecoveryBaseURL, onRel.BoardID, osType)
|
||||
if ferr != nil {
|
||||
@@ -478,7 +479,7 @@ func inspectRecoveryPartition(imagePath string, verifyData bool) (*recoveryParti
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
cl, err := downloader.ParseCNKL(chuBytes)
|
||||
cl, err := parseSignedRecoveryChunklist(chuBytes)
|
||||
if err != nil || cl.TotalSize != int64(dmgEnt.size) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -20,7 +21,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
osRecoveryBaseURL = "http://osrecovery.apple.com"
|
||||
osRecoveryBaseURL = "https://osrecovery.apple.com"
|
||||
osRecoveryUserAgent = "InternetRecovery/1.0"
|
||||
)
|
||||
|
||||
@@ -119,7 +120,21 @@ func randUpperHex(nBytes int) string {
|
||||
func newDirectRecoveryHTTPClient() *http.Client {
|
||||
tr := http.DefaultTransport.(*http.Transport).Clone()
|
||||
tr.Proxy = nil // Direct connection to osrecovery.apple.com / oscdn.apple.com.
|
||||
return &http.Client{Transport: tr, Timeout: 25 * time.Second}
|
||||
return &http.Client{Transport: tr, Timeout: 25 * time.Second, CheckRedirect: downloader.CheckSameOriginRedirect}
|
||||
}
|
||||
|
||||
func appleRecoveryAssetURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.User != nil || u.Port() != "" {
|
||||
return false
|
||||
}
|
||||
host := strings.ToLower(u.Hostname())
|
||||
// Apple Internet Recovery still issues HTTP URLs on this CDN. Recovery
|
||||
// bytes are authenticated separately by Apple's signed chunklist.
|
||||
if host == "oscdn.apple.com" {
|
||||
return u.Scheme == "http" || u.Scheme == "https"
|
||||
}
|
||||
return u.Scheme == "https" && strings.HasSuffix(host, ".cdn-apple.com")
|
||||
}
|
||||
|
||||
// fetchRecoveryAsset performs Apple's 2-step osrecovery handshake to obtain
|
||||
@@ -222,6 +237,9 @@ func fetchRecoveryAssetOnce(ctx context.Context, client *http.Client, baseURL, b
|
||||
if kv["AU"] == "" {
|
||||
return nil, errors.New("osrecovery response missing asset URL (AU)")
|
||||
}
|
||||
if baseURL == osRecoveryBaseURL && (!appleRecoveryAssetURL(kv["AU"]) || !appleRecoveryAssetURL(kv["CU"])) {
|
||||
return nil, errors.New("osrecovery returned an untrusted recovery asset or chunklist URL")
|
||||
}
|
||||
return &recoveryAsset{
|
||||
AssetURL: kv["AU"],
|
||||
AssetToken: kv["AT"],
|
||||
@@ -352,9 +370,9 @@ func (c *Client) downloadOnlineAccelerated(ctx context.Context, version string,
|
||||
}
|
||||
return nil, false, nil
|
||||
}
|
||||
cl, err := downloader.ParseCNKL(clBytes)
|
||||
cl, err := parseSignedRecoveryChunklist(clBytes)
|
||||
if err != nil {
|
||||
return nil, false, nil
|
||||
return nil, true, err
|
||||
}
|
||||
|
||||
partPath := finalPath + ".part"
|
||||
@@ -362,13 +380,14 @@ func (c *Client) downloadOnlineAccelerated(ctx context.Context, version string,
|
||||
onUpdate(Update{Kind: KindStep, Message: dlStep, Step: dlStep, Percent: -1})
|
||||
|
||||
dlErr := prov.Download(ctx, downloader.Request{
|
||||
URL: asset.AssetURL,
|
||||
DestPath: partPath,
|
||||
ExpectedSize: cl.TotalSize,
|
||||
IntegrityBytes: clBytes,
|
||||
Headers: recoveryHeaders(asset.AssetToken),
|
||||
Resume: true,
|
||||
DirectHint: true,
|
||||
URL: asset.AssetURL,
|
||||
DestPath: partPath,
|
||||
ExpectedSize: cl.TotalSize,
|
||||
IntegrityBytes: clBytes,
|
||||
Headers: recoveryHeaders(asset.AssetToken),
|
||||
Resume: true,
|
||||
DirectHint: true,
|
||||
SameOriginRedirects: true,
|
||||
RefreshHeaders: func(rctx context.Context) (map[string]string, error) {
|
||||
fresh, rerr := fetchRecoveryAsset(rctx, httpClient, osRecoveryBaseURL, rel.BoardID, osType)
|
||||
if rerr != nil {
|
||||
@@ -393,6 +412,9 @@ func (c *Client) downloadOnlineAccelerated(ctx context.Context, version string,
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
if err := verifyRecoveryImage(ctx, partPath, cl); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
if err := os.Rename(partPath, finalPath); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"os"
|
||||
"slices"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/downloader"
|
||||
)
|
||||
|
||||
// Apple EFI ROM public key 1, as documented by OpenCorePkg's macrecovery
|
||||
// verifier and reims-util 7867384, src/chunklist.rs:24-31.
|
||||
var appleRecoveryKey = rsa.PublicKey{
|
||||
N: func() *big.Int {
|
||||
n, _ := new(big.Int).SetString(
|
||||
"C3E748CAD9CD384329E10E25A91E43E1A762FF529ADE578C935BDDF9B13F2179"+
|
||||
"D4855E6FC89E9E29CA12517D17DFA1EDCE0BEBF0EA7B461FFE61D94E2BDF72C196F89ACD3536B644064014DAE25A15DB"+
|
||||
"6BB0852ECBD120916318D1CCDEA3C84C92ED743FC176D0BACA920D3FCF3158AFF731F88CE0623182A8ED67E650515F7"+
|
||||
"5745909F07D415F55FC15A35654D118C55A462D37A3ACDA08612F3F3F6571761EFCCBCC299AEE99B3A4FD6212CCFFF5E"+
|
||||
"F37A2C334E871191F7E1C31960E010A54E86FA3F62E6D6905E1CD57732410A3EB0C6B4DEFDABE9F59BF1618758C751C"+
|
||||
"D56CEF851D1C0EAA1C558E37AC108DA9089863D20E2E7E4BF475EC66FE6B3EFDCF", 16)
|
||||
return n
|
||||
}(),
|
||||
E: 65537,
|
||||
}
|
||||
|
||||
func parseSignedRecoveryChunklist(data []byte) (*downloader.Chunklist, error) {
|
||||
return verifySignedRecoveryChunklist(data, &appleRecoveryKey)
|
||||
}
|
||||
|
||||
func verifySignedRecoveryChunklist(data []byte, key *rsa.PublicKey) (*downloader.Chunklist, error) {
|
||||
const headerSize, entrySize, rsaMethod = 36, 36, 1
|
||||
if len(data) < headerSize+key.Size() || data[10] != rsaMethod {
|
||||
return nil, fmt.Errorf("recovery chunklist is missing an Apple RSA signature")
|
||||
}
|
||||
end := len(data) - key.Size()
|
||||
if binary.LittleEndian.Uint32(data[4:8]) != headerSize ||
|
||||
binary.LittleEndian.Uint64(data[20:28]) != headerSize ||
|
||||
binary.LittleEndian.Uint64(data[28:36]) != uint64(end) ||
|
||||
(end-headerSize)%entrySize != 0 ||
|
||||
binary.LittleEndian.Uint64(data[12:20]) != uint64((end-headerSize)/entrySize) {
|
||||
return nil, fmt.Errorf("invalid signed recovery chunklist layout")
|
||||
}
|
||||
sig := bytes.Clone(data[end:])
|
||||
slices.Reverse(sig) // CNKL stores the RSA signature little-endian.
|
||||
sum := sha256.Sum256(data[:end])
|
||||
if err := rsa.VerifyPKCS1v15(key, crypto.SHA256, sum[:], sig); err != nil {
|
||||
return nil, fmt.Errorf("verify Apple recovery chunklist: %w", err)
|
||||
}
|
||||
return downloader.ParseCNKL(data)
|
||||
}
|
||||
|
||||
// Verify the actual file before publishing it, including bytes resumed from
|
||||
// disk and bytes written by an external download provider.
|
||||
func verifyRecoveryImage(ctx context.Context, path string, cl *downloader.Chunklist) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Size() != cl.TotalSize {
|
||||
return fmt.Errorf("recovery image size %d differs from signed size %d", info.Size(), cl.TotalSize)
|
||||
}
|
||||
hash := sha256.New()
|
||||
for _, chunk := range cl.Chunks {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
hash.Reset()
|
||||
if _, err := io.CopyN(hash, f, chunk.Size); err != nil {
|
||||
return fmt.Errorf("read recovery image chunk %d: %w", chunk.Index, err)
|
||||
}
|
||||
if !bytes.Equal(hash.Sum(nil), chunk.SHA256[:]) {
|
||||
return fmt.Errorf("recovery image chunk %d differs from its signed checksum", chunk.Index)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSignedRecoveryIntegrity(t *testing.T) {
|
||||
payload := []byte("synthetic recovery image")
|
||||
digestOnly := buildCNKLBytes(payload, 16)
|
||||
digest := sha256.Sum256(digestOnly)
|
||||
if _, err := parseSignedRecoveryChunklist(append(bytes.Clone(digestOnly), digest[:]...)); err == nil {
|
||||
t.Fatal("accepted chunklist without an Apple signature")
|
||||
}
|
||||
if appleRecoveryKey.N.BitLen() != 2048 {
|
||||
t.Fatal("unexpected Apple public key length")
|
||||
}
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signed := bytes.Clone(digestOnly)
|
||||
signed[10] = 1
|
||||
digest = sha256.Sum256(signed)
|
||||
sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
slices.Reverse(sig)
|
||||
signed = append(signed, sig...)
|
||||
cl, err := verifySignedRecoveryChunklist(signed, &key.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatalf("rejected valid signature: %v", err)
|
||||
}
|
||||
if _, err := parseSignedRecoveryChunklist(signed); err == nil {
|
||||
t.Fatal("accepted a recovery chunklist signed by a different key")
|
||||
}
|
||||
signed[45] ^= 1
|
||||
if _, err := verifySignedRecoveryChunklist(signed, &key.PublicKey); err == nil {
|
||||
t.Fatal("accepted modified signed chunklist")
|
||||
}
|
||||
|
||||
image := filepath.Join(t.TempDir(), "test.part")
|
||||
if err := os.WriteFile(image, payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := verifyRecoveryImage(t.Context(), image, cl); err != nil {
|
||||
t.Fatalf("valid image: %v", err)
|
||||
}
|
||||
payload[0] ^= 1
|
||||
if err := os.WriteFile(image, payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := verifyRecoveryImage(t.Context(), image, cl); err == nil {
|
||||
t.Fatal("accepted damaged image of the correct size")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppleRecoveryAssetURL(t *testing.T) {
|
||||
for raw, want := range map[string]bool{
|
||||
"http://oscdn.apple.com/recovery.dmg": true,
|
||||
"https://updates.cdn-apple.com/recovery.chunklist": true,
|
||||
"http://updates.cdn-apple.com/recovery.chunklist": false,
|
||||
"http://oscdn.apple.com.example/recovery.dmg": false,
|
||||
"http://oscdn.apple.com:8080/recovery.dmg": false,
|
||||
"http://user@oscdn.apple.com/recovery.dmg": false,
|
||||
} {
|
||||
if got := appleRecoveryAssetURL(raw); got != want {
|
||||
t.Errorf("appleRecoveryAssetURL(%q) = %v, want %v", raw, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package macosdriver
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
@@ -33,6 +34,7 @@ var ReimsMacOSCapabilities = []string{
|
||||
// as the compiled-in `builtin.driver.reims-macos` extension (§3.2, §5.3).
|
||||
type Options struct {
|
||||
OwnerID string
|
||||
ManagedByDesktop bool
|
||||
WHPXFallbackEnabled func() bool
|
||||
ColdRebootEnabled func() bool
|
||||
MigrateLedger func(*plugin.ArgLedger)
|
||||
@@ -96,6 +98,13 @@ func (d *ReimsMacOSDriver) startClient() (*reims.Client, rt.Installed, error) {
|
||||
func (d *ReimsMacOSDriver) List(ctx context.Context) ([]driver.VMInfo, error) {
|
||||
c, active, err := d.startClient()
|
||||
if err != nil {
|
||||
if errors.Is(err, rt.ErrNoActiveRuntime) {
|
||||
registered, registryErr := reims.ListRegisteredVMs(d.getConfig().DataRoot)
|
||||
if registryErr == nil && len(registered) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, errors.Join(err, registryErr)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items, err := c.List(ctx)
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
@@ -97,7 +98,7 @@ func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (
|
||||
if d.opts.MigrateLedger != nil {
|
||||
d.opts.MigrateLedger(ledger)
|
||||
}
|
||||
baseArgs := stripLegacyManagedExtraArgs(cur.ExtraArgs)
|
||||
baseArgs := startBaseArgs(cur.ExtraArgs, d.opts.ManagedByDesktop, req.ActivePlugins)
|
||||
userExtraArgs := plugin.UserExtraArgs(baseArgs, ledger)
|
||||
ownerIntent, err := d.prepareStart(ctx, cfg, c, active, ref.Name, cur, rep, userExtraArgs, stdout)
|
||||
if err != nil {
|
||||
@@ -113,7 +114,7 @@ func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (
|
||||
if active.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(cur.Borderless, cur.Resolution, rep.PrimaryDisplay) {
|
||||
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
}
|
||||
if active.Manifest.HasCapability("client-window-close") {
|
||||
if d.opts.ManagedByDesktop && active.Manifest.HasCapability("client-window-close") {
|
||||
c.Env = append(c.Env, vmstart.CloseRequestEnv(ref.Name)...)
|
||||
}
|
||||
if reconciled.Changed {
|
||||
@@ -222,7 +223,7 @@ func (d *ReimsMacOSDriver) prepareWHPXFallback(cfg config.Config, active rt.Inst
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) prepareColdReboot(cfg config.Config, name, vmDir string, rep host.Report, in *plugin.StartIntent) error {
|
||||
if !rep.NeedsColdRebootWorkaround || !optionEnabled(d.opts.ColdRebootEnabled) {
|
||||
if !d.opts.ManagedByDesktop || !rep.NeedsColdRebootWorkaround || !optionEnabled(d.opts.ColdRebootEnabled) {
|
||||
in.ClearKeys = append(in.ClearKeys, keyWin10ColdReboot)
|
||||
return nil
|
||||
}
|
||||
@@ -267,8 +268,13 @@ func (d *ReimsMacOSDriver) prepareHostMemorySMBIOS(cfg config.Config, rep host.R
|
||||
})
|
||||
}
|
||||
|
||||
func stripLegacyManagedExtraArgs(extraArgs string) string {
|
||||
s := reims.StripGuestToolsArgs(extraArgs)
|
||||
func startBaseArgs(extraArgs string, managedByDesktop bool, active map[string]bool) string {
|
||||
s := extraArgs
|
||||
// The CLI has no bridge callback to replace the disk it sees in the VM
|
||||
// configuration. Keep it attached if Guest Tools is still enabled.
|
||||
if managedByDesktop || (active != nil && !active[builtin.IDGuestTools]) {
|
||||
s = reims.StripGuestToolsArgs(s)
|
||||
}
|
||||
s = reims.StripGuestToolsNetworkArgs(s)
|
||||
s = reims.StripOfflineHelperArgs(s)
|
||||
s = qmp.StripLegacyWin10RebootArgs(s)
|
||||
|
||||
@@ -2,12 +2,15 @@ package macosdriver
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
@@ -19,9 +22,41 @@ func argKeys(in plugin.StartIntent) []string {
|
||||
return keys
|
||||
}
|
||||
|
||||
func TestDirectStartKeepsGuestToolsAndClearsDesktopReboot(t *testing.T) {
|
||||
const owner = "builtin.guest.macos"
|
||||
cfg := config.Config{DataRoot: t.TempDir()}
|
||||
rep := host.Report{NeedsColdRebootWorkaround: true}
|
||||
root := cfg.DataRoot
|
||||
tools := reims.MergeGuestToolsArgs("-cpu host", "tools.img")
|
||||
management, err := reims.GuestToolsNetworkArgs(root, 12001, 12002)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tools += " " + reims.JoinShellArgs(management)
|
||||
attached := qmp.MergeWin10RebootUnixArgs(tools, qmp.RebootSocketPath(root, cfg.TempDir(), "mac"))
|
||||
d := &ReimsMacOSDriver{opts: Options{OwnerID: owner}}
|
||||
intent := plugin.StartIntent{PluginID: owner}
|
||||
if err := d.prepareColdReboot(cfg, "mac", root, rep, &intent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(intent.PostStart) != 0 || !slices.Contains(intent.ClearKeys, keyWin10ColdReboot) {
|
||||
t.Fatalf("direct start cold-reboot intent = %+v", intent)
|
||||
}
|
||||
for _, enabled := range []bool{true, false} {
|
||||
active := map[string]bool{owner: true, builtin.IDGuestTools: enabled}
|
||||
base := startBaseArgs(attached, false, active)
|
||||
out := plugin.ReconcileStartIntentsForDriver(base, &plugin.ArgLedger{}, active, owner, []plugin.StartIntent{intent})
|
||||
if strings.Contains(out.ExtraArgs, "-no-reboot") || strings.Contains(out.ExtraArgs, "reimstools-net") ||
|
||||
!strings.Contains(out.ExtraArgs, "-cpu host") ||
|
||||
reims.HasGuestToolsArgs(out.ExtraArgs) != enabled {
|
||||
t.Fatalf("Guest Tools enabled=%v: unexpected launch args %q", enabled, out.ExtraArgs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareWorkaroundsHonourSettingsAndRuntime(t *testing.T) {
|
||||
whpx, cold := true, true
|
||||
d := &ReimsMacOSDriver{opts: Options{OwnerID: "test.macos",
|
||||
d := &ReimsMacOSDriver{opts: Options{OwnerID: "test.macos", ManagedByDesktop: true,
|
||||
WHPXFallbackEnabled: func() bool { return whpx }, ColdRebootEnabled: func() bool { return cold }}}
|
||||
rep := host.Report{WHPXCaps: host.WHPXCapabilities{KernelIrqchipAvailable: true, NestedVirtProperty: false}}
|
||||
var in plugin.StartIntent
|
||||
|
||||
@@ -105,7 +105,7 @@ func (d *ReimsMacOSDriver) resumeLocked(ctx context.Context, c *reims.Client, ac
|
||||
cfg := d.getConfig()
|
||||
rep := host.Inspect(cfg.DataRoot)
|
||||
var qmpAddr string
|
||||
if cur.State == "stopped" && reims.HasSuspendState(cur.Directory) && rep.NeedsColdRebootWorkaround {
|
||||
if d.opts.ManagedByDesktop && cur.State == "stopped" && reims.HasSuspendState(cur.Directory) && rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(cur.Directory, cfg.TempDir(), cur.Name)
|
||||
if qmp.HasWin10RebootUnixArgs(cur.ExtraArgs, sockPath) {
|
||||
if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) {
|
||||
@@ -120,7 +120,7 @@ func (d *ReimsMacOSDriver) resumeLocked(ctx context.Context, c *reims.Client, ac
|
||||
if active.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(cur.Borderless, cur.Resolution, rep.PrimaryDisplay) {
|
||||
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
}
|
||||
if active.Manifest.HasCapability("client-window-close") {
|
||||
if d.opts.ManagedByDesktop && active.Manifest.HasCapability("client-window-close") {
|
||||
c.Env = append(c.Env, vmstart.CloseRequestEnv(cur.Name)...)
|
||||
}
|
||||
prep, err := startprep.New(cfg, func(line string) { startLog(stdout, line) })
|
||||
@@ -128,7 +128,11 @@ func (d *ReimsMacOSDriver) resumeLocked(ctx context.Context, c *reims.Client, ac
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
prep.Client, prep.Runtime = c, active
|
||||
if err := prep.ResumeSnapshot(ctx, cur, rep, stdout, stderr); err != nil {
|
||||
launchArgs := cur.ExtraArgs
|
||||
if !d.opts.ManagedByDesktop {
|
||||
launchArgs = qmp.StripLegacyWin10RebootArgs(launchArgs)
|
||||
}
|
||||
if err := prep.ResumeSnapshot(ctx, cur, launchArgs, rep, stdout, stderr); err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
var res driver.StartResult
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
// ListRegisteredVMs reads the existing reims-ctl registry, including custom
|
||||
// directories, without loading a runtime or changing the registry.
|
||||
// Format: reims-vgpu 3731afd, crates/reims-ctl/src/vm.rs:974-1002.
|
||||
func ListRegisteredVMs(dataRoot string) ([]driver.VMInfo, error) {
|
||||
dir, overridden := os.LookupEnv("REIMS_CTL_CONFIG_DIR")
|
||||
if !overridden {
|
||||
dir = filepath.Join((&config.Config{DataRoot: dataRoot}).XDGConfigDir(), "reims-ctl")
|
||||
}
|
||||
path := filepath.Join(dir, "vms.toml")
|
||||
raw, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var registry struct {
|
||||
VMs []struct {
|
||||
Name string `toml:"name"`
|
||||
Dir string `toml:"dir"`
|
||||
} `toml:"vm"`
|
||||
}
|
||||
if err := toml.Unmarshal(raw, ®istry); err != nil {
|
||||
return nil, fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
vms := make([]driver.VMInfo, 0, len(registry.VMs))
|
||||
for _, entry := range registry.VMs {
|
||||
if entry.Name == "" || entry.Dir == "" {
|
||||
return nil, fmt.Errorf("incomplete VM registration in %s", path)
|
||||
}
|
||||
vms = append(vms, driver.VMInfo{
|
||||
Name: entry.Name,
|
||||
Directory: filepath.Clean(entry.Dir),
|
||||
})
|
||||
}
|
||||
return vms, nil
|
||||
}
|
||||
@@ -146,7 +146,7 @@ func cleanupSuspendAttempt(tmp string, err error) error {
|
||||
// ResumeSnapshot owns the incoming launch and snapshot consumption while
|
||||
// the caller holds LockVM. The original configuration must be restored
|
||||
// before guest execution can continue.
|
||||
func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, rep host.Report, out, stderr io.Writer) error {
|
||||
func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, launchArgs string, rep host.Report, out, stderr io.Writer) error {
|
||||
if err := p.checkSuspendRuntime(d); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -167,7 +167,7 @@ func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, rep host.Re
|
||||
return err
|
||||
}
|
||||
c := p.Client
|
||||
incoming := reims.MergeIncomingDeferArgs(d.ExtraArgs)
|
||||
incoming := reims.MergeIncomingDeferArgs(launchArgs)
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: d.Name, ExtraArgs: &incoming}, out, stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ func hasCap(caps []string, want string) bool {
|
||||
func appVersion() string {
|
||||
v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
|
||||
if v == "" || v == "dev" {
|
||||
return "0.2.10"
|
||||
return "0.2.11"
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
+54
-14
@@ -49,6 +49,7 @@ var ContributionCatalog = map[string]ContractStatus{
|
||||
"settingsPages": ContractExperimental,
|
||||
"statusItems": ContractExperimental,
|
||||
"panels": ContractStable,
|
||||
"imageSources": ContractStable,
|
||||
"views": ContractExperimental,
|
||||
"diagnostics": ContractExperimental,
|
||||
}
|
||||
@@ -56,9 +57,9 @@ var ContributionCatalog = map[string]ContractStatus{
|
||||
// ThemeFieldCatalog lists theme fields whose host support is still pending.
|
||||
// Fields not listed here are stable.
|
||||
var ThemeFieldCatalog = map[string]ContractStatus{
|
||||
"icons": ContractExperimental,
|
||||
"brandMark": ContractExperimental,
|
||||
"layout": ContractExperimental,
|
||||
"icons": ContractStable,
|
||||
"brandMark": ContractStable,
|
||||
"layout": ContractStable,
|
||||
}
|
||||
|
||||
// Slot content kinds.
|
||||
@@ -100,13 +101,13 @@ var UISlotCatalog = map[string]SlotSpec{
|
||||
"vm.preview.br": anchorSlot(ContractStable, 2, nil),
|
||||
"empty.state": anchorSlot(ContractStable, 2, nil),
|
||||
|
||||
"titlebar.center": anchorSlot(ContractExperimental, 1, nil),
|
||||
"sidebar.header": anchorSlot(ContractExperimental, 2, nil),
|
||||
"nav.item.trailing": anchorSlot(ContractExperimental, 2, nil),
|
||||
"vm.header.trailing": anchorSlot(ContractExperimental, 4, map[string]ContractStatus{SlotMenu: ContractExperimental}),
|
||||
"vm.toolbar": anchorSlot(ContractExperimental, 8, map[string]ContractStatus{SlotMenu: ContractStable}),
|
||||
"statusbar.left": anchorSlot(ContractExperimental, 4, map[string]ContractStatus{SlotStatusItem: ContractExperimental}),
|
||||
"create.source": anchorSlot(ContractExperimental, 4, map[string]ContractStatus{SlotPanel: ContractExperimental}),
|
||||
"titlebar.center": anchorSlot(ContractStable, 1, nil),
|
||||
"sidebar.header": anchorSlot(ContractStable, 2, nil),
|
||||
"nav.item.trailing": anchorSlot(ContractStable, 2, nil),
|
||||
"vm.header.trailing": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotMenu: ContractExperimental}),
|
||||
"vm.toolbar": anchorSlot(ContractStable, 8, map[string]ContractStatus{SlotMenu: ContractStable}),
|
||||
"statusbar.left": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotStatusItem: ContractExperimental}),
|
||||
"create.source": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotPanel: ContractExperimental}),
|
||||
}
|
||||
|
||||
// ViewLocationSpec describes one place a plugin view can appear.
|
||||
@@ -125,8 +126,8 @@ var ViewLocationCatalog = map[string]ViewLocationSpec{
|
||||
|
||||
// UILayerCatalog lists full-window layers.
|
||||
var UILayerCatalog = map[string]ContractStatus{
|
||||
"layer.background": ContractExperimental,
|
||||
"layer.overlay": ContractExperimental,
|
||||
"layer.background": ContractStable,
|
||||
"layer.overlay": ContractStable,
|
||||
}
|
||||
|
||||
// ThemeLayoutCatalog lists theme `layout` options and their allowed values.
|
||||
@@ -287,6 +288,31 @@ func validateUIContract(m Manifest) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
seenImageSources := map[string]bool{}
|
||||
for _, src := range m.Contributes.ImageSources {
|
||||
if !reContributionID.MatchString(src.ID) {
|
||||
return fmt.Errorf("invalid image source id %q", src.ID)
|
||||
}
|
||||
if seenImageSources[src.ID] {
|
||||
return fmt.Errorf("duplicate image source id %q", src.ID)
|
||||
}
|
||||
seenImageSources[src.ID] = true
|
||||
if !src.Title.HasAny() {
|
||||
return fmt.Errorf("image source %q is missing a localized title", src.ID)
|
||||
}
|
||||
if strings.TrimSpace(src.Native) == "" {
|
||||
if strings.TrimSpace(m.Entry.PanelDir) == "" {
|
||||
return fmt.Errorf("image source %q requires entry.panelDir", src.ID)
|
||||
}
|
||||
entry := strings.TrimSpace(src.Entry)
|
||||
if entry == "" {
|
||||
entry = "index.html"
|
||||
}
|
||||
if err := validateSafeManifestAsset(entry, ""); err != nil {
|
||||
return fmt.Errorf("invalid image source %q entry %q: %w", src.ID, src.Entry, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
perLocation := map[string]int{}
|
||||
seenViews := map[string]bool{}
|
||||
for _, v := range m.Contributes.Views {
|
||||
@@ -325,6 +351,13 @@ func validateUIContract(m Manifest) error {
|
||||
icons[n] = true
|
||||
}
|
||||
for _, th := range m.Contributes.Themes {
|
||||
for _, d := range th.Decorations {
|
||||
_, slot := UISlotCatalog[d.Slot]
|
||||
_, layer := UILayerCatalog[d.Slot]
|
||||
if !slot && !layer {
|
||||
return fmt.Errorf("theme %q decoration %q targets unknown slot or layer %q", th.ID, d.ID, d.Slot)
|
||||
}
|
||||
}
|
||||
for name := range th.Icons {
|
||||
if !icons[name] {
|
||||
return fmt.Errorf("theme %q overrides unknown icon %q", th.ID, name)
|
||||
@@ -412,13 +445,20 @@ func ContractFindings(m Manifest, raw []byte) []ScanFinding {
|
||||
}
|
||||
}
|
||||
|
||||
usesUI := len(m.Contributes.Themes) > 0 || len(m.Contributes.Panels) > 0 || len(m.Contributes.Views) > 0
|
||||
hasIframeImageSource := false
|
||||
for _, src := range m.Contributes.ImageSources {
|
||||
if strings.TrimSpace(src.Native) == "" {
|
||||
hasIframeImageSource = true
|
||||
break
|
||||
}
|
||||
}
|
||||
usesUI := len(m.Contributes.Themes) > 0 || len(m.Contributes.Panels) > 0 || hasIframeImageSource || len(m.Contributes.Views) > 0
|
||||
if usesUI && strings.TrimSpace(m.Engines.UIAPI) == "" {
|
||||
add("contract-engines", "engines.uiApi", "declare engines.uiApi so incompatible hosts refuse the plugin up front",
|
||||
"建议声明 engines.uiApi,让不兼容的宿主在安装前就拒绝",
|
||||
"Declare engines.uiApi so incompatible hosts refuse the plugin up front")
|
||||
}
|
||||
if (len(m.Contributes.Panels) > 0 || len(m.Contributes.Views) > 0) && strings.TrimSpace(m.Engines.BridgeAPI) == "" {
|
||||
if (len(m.Contributes.Panels) > 0 || hasIframeImageSource || len(m.Contributes.Views) > 0) && strings.TrimSpace(m.Engines.BridgeAPI) == "" {
|
||||
add("contract-engines", "engines.bridgeApi", "declare engines.bridgeApi for panels and views",
|
||||
"面板与视图建议声明 engines.bridgeApi",
|
||||
"Declare engines.bridgeApi for panels and views")
|
||||
|
||||
@@ -89,8 +89,8 @@ func TestContractCatalogsMatchFrontend(t *testing.T) {
|
||||
layout = append(layout, opt+"="+v)
|
||||
}
|
||||
}
|
||||
assertSameSet(t, "layout options", layout, tsArray(t, ui, "UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL"))
|
||||
assertSameSet(t, "icon names", ThemeIconNames, tsArray(t, ui, "UI_CONTRACT_ICONS_EXPERIMENTAL"))
|
||||
assertSameSet(t, "layout options", layout, tsArray(t, ui, "UI_CONTRACT_LAYOUT_OPTIONS"))
|
||||
assertSameSet(t, "icon names", ThemeIconNames, tsArray(t, ui, "UI_CONTRACT_ICONS"))
|
||||
|
||||
var locations []string
|
||||
for loc, spec := range ViewLocationCatalog {
|
||||
@@ -151,12 +151,12 @@ func TestHostFeaturesAreStableOnly(t *testing.T) {
|
||||
for _, f := range features {
|
||||
has[f] = true
|
||||
}
|
||||
for _, want := range []string{"bridge.hello", "bridge.vm.list", "event.theme.changed", "slot.sidebar.footer", "slot.settings.plugin.panel", "slot.vm.toolbar.menu", "contrib.themes"} {
|
||||
for _, want := range []string{"bridge.hello", "bridge.vm.list", "event.theme.changed", "slot.sidebar.footer", "slot.settings.plugin.panel", "slot.vm.toolbar.menu", "contrib.themes", "contrib.imageSources", "slot.vm.toolbar", "slot.nav.item.trailing", "layer.overlay", "layer.background", "theme.icons", "theme.layout", "theme.brandMark"} {
|
||||
if !has[want] {
|
||||
t.Errorf("missing stable feature %s", want)
|
||||
}
|
||||
}
|
||||
for _, unwanted := range []string{"bridge.file.pick", "contrib.views", "view.sidebar", "layer.overlay", "slot.vm.toolbar", "slot.sidebar.footer.panel", "theme.icons"} {
|
||||
for _, unwanted := range []string{"bridge.file.pick", "contrib.views", "view.sidebar", "slot.sidebar.footer.panel", "slot.vm.card.vmCard", "contrib.statusItems"} {
|
||||
if has[unwanted] {
|
||||
t.Errorf("experimental entry %s advertised as a feature", unwanted)
|
||||
}
|
||||
@@ -222,6 +222,27 @@ func TestValidateUIContract(t *testing.T) {
|
||||
m.Contributes.Themes = []ThemeContribution{{ID: "t", Name: LocalizedText{EnUS: "t"}, Icons: map[string]string{"rocket": "r.svg"}}}
|
||||
}, "unknown icon"},
|
||||
{"bridgeApi range", func(m *Manifest) { m.Engines.BridgeAPI = "^2.0.0" }, "incompatible bridgeApi"},
|
||||
{"decoration in layer", func(m *Manifest) {
|
||||
m.Contributes.Themes = []ThemeContribution{{ID: "t", Name: LocalizedText{EnUS: "t"},
|
||||
Decorations: []ThemeDecoration{{ID: "sky", Slot: "layer.background"}, {ID: "pet", Slot: "nav.item.trailing"}}}}
|
||||
}, ""},
|
||||
{"decoration in unknown slot", func(m *Manifest) {
|
||||
m.Contributes.Themes = []ThemeContribution{{ID: "t", Name: LocalizedText{EnUS: "t"},
|
||||
Decorations: []ThemeDecoration{{ID: "x", Slot: "sidebar.middle"}}}}
|
||||
}, "unknown slot or layer"},
|
||||
{"valid image source", func(m *Manifest) {
|
||||
m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Title: LocalizedText{EnUS: "Linux"}, Entry: "images.html"}}
|
||||
}, ""},
|
||||
{"image source without panelDir", func(m *Manifest) {
|
||||
m.Entry.PanelDir = ""
|
||||
m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Title: LocalizedText{EnUS: "Linux"}, Entry: "images.html"}}
|
||||
}, "requires entry.panelDir"},
|
||||
{"image source missing title", func(m *Manifest) {
|
||||
m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Entry: "images.html"}}
|
||||
}, "missing a localized title"},
|
||||
{"image source escaping entry", func(m *Manifest) {
|
||||
m.Contributes.ImageSources = []ImageSourceContribution{{ID: "linux", Title: LocalizedText{EnUS: "Linux"}, Entry: "../escape.html"}}
|
||||
}, "invalid image source"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -253,7 +274,7 @@ func TestContractFindings(t *testing.T) {
|
||||
checks[f.Check] = append(checks[f.Check], f.Target)
|
||||
}
|
||||
exp := strings.Join(checks["contract-experimental"], " ")
|
||||
for _, want := range []string{"contributes.views", "panel:card", "theme:t"} {
|
||||
for _, want := range []string{"contributes.views", "panel:card"} {
|
||||
if !strings.Contains(exp, want) {
|
||||
t.Errorf("experimental findings %q miss %s", exp, want)
|
||||
}
|
||||
|
||||
@@ -1571,6 +1571,32 @@ func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeImageSources applies active Language Pack manifest overrides onto ImageSourceContribution labels.
|
||||
func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
if len(ovs) == 0 || len(items) == 0 {
|
||||
return items
|
||||
}
|
||||
out := make([]ImageSourceContribution, len(items))
|
||||
for i, it := range items {
|
||||
cp := it
|
||||
if list := ovs[it.PluginID]; len(list) > 0 {
|
||||
cp.Title = cloneLocalizedText(it.Title)
|
||||
cp.Description = cloneLocalizedText(it.Description)
|
||||
for _, r := range list {
|
||||
if v := firstNonEmptyField(r.ov.Fields, "imageSource."+it.ID+".title"); v != "" {
|
||||
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
|
||||
}
|
||||
if v := firstNonEmptyField(r.ov.Fields, "imageSource."+it.ID+".description"); v != "" {
|
||||
applyLocalizedOverride(&cp.Description, r.locale, v, r.privileged)
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = cp
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeVMCards applies active Language Pack manifest overrides onto VMCardContribution labels.
|
||||
func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
|
||||
@@ -212,6 +212,16 @@ func ValidateManifest(m Manifest, hostVersion string, isBuiltinOrBundled bool) e
|
||||
if len(m.Contributes.Runtimes) > 0 && !permSet["runtime:provider"] {
|
||||
return errors.New("plugin declaring runtimes must request permission \"runtime:provider\"")
|
||||
}
|
||||
if len(m.Contributes.ImageSources) > 0 {
|
||||
if !permSet["ui:slot"] {
|
||||
return errors.New("plugin declaring imageSources must request permission \"ui:slot\"")
|
||||
}
|
||||
for _, src := range m.Contributes.ImageSources {
|
||||
if strings.TrimSpace(src.Native) != "" {
|
||||
return fmt.Errorf("external image source %q may not declare native renderer", src.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, d := range m.Contributes.GuestDrivers {
|
||||
for _, root := range d.VMRoots {
|
||||
|
||||
@@ -117,6 +117,7 @@ type Registry struct {
|
||||
settingsPages []SettingsPageContribution
|
||||
statusItems []StatusItemContribution
|
||||
panels []PanelContribution
|
||||
imageSources []ImageSourceContribution
|
||||
diagnostics []RegisteredDiagnostics
|
||||
}
|
||||
|
||||
@@ -606,6 +607,10 @@ func (r *Registry) registerManifestContributions(sc *Scope, m Manifest) {
|
||||
pnl.PluginID = pid
|
||||
r.RegisterPanel(sc, pnl)
|
||||
}
|
||||
for _, src := range m.Contributes.ImageSources {
|
||||
src.PluginID = pid
|
||||
r.RegisterImageSource(sc, src)
|
||||
}
|
||||
// Register L1 declarative rule hooks on the hook bus.
|
||||
if len(m.Contributes.RuleHooks) > 0 {
|
||||
rules := append([]RuleHook(nil), m.Contributes.RuleHooks...)
|
||||
@@ -1372,6 +1377,60 @@ func (r *Registry) Panels(slot string) []PanelContribution {
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterImageSource(sc *Scope, src ImageSourceContribution) {
|
||||
src.ID = strings.TrimSpace(src.ID)
|
||||
if src.ID == "" {
|
||||
return
|
||||
}
|
||||
src.PluginID = sc.PluginID()
|
||||
r.mu.Lock()
|
||||
replaced := false
|
||||
for i, existing := range r.imageSources {
|
||||
if existing.PluginID == src.PluginID && existing.ID == src.ID {
|
||||
r.imageSources[i] = src
|
||||
replaced = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !replaced {
|
||||
r.imageSources = append(r.imageSources, src)
|
||||
}
|
||||
r.mu.Unlock()
|
||||
sc.OnDispose(func() {
|
||||
r.mu.Lock()
|
||||
kept := r.imageSources[:0]
|
||||
for _, item := range r.imageSources {
|
||||
if !(item.PluginID == sc.PluginID() && item.ID == src.ID) {
|
||||
kept = append(kept, item)
|
||||
}
|
||||
}
|
||||
r.imageSources = kept
|
||||
r.mu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Registry) ImageSources() []ImageSourceContribution {
|
||||
r.mu.RLock()
|
||||
out := make([]ImageSourceContribution, len(r.imageSources))
|
||||
copy(out, r.imageSources)
|
||||
r.mu.RUnlock()
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if out[i].Order != out[j].Order {
|
||||
return out[i].Order < out[j].Order
|
||||
}
|
||||
ni := strings.TrimSpace(out[i].Native) != ""
|
||||
nj := strings.TrimSpace(out[j].Native) != ""
|
||||
if ni != nj {
|
||||
return ni
|
||||
}
|
||||
if out[i].PluginID != out[j].PluginID {
|
||||
return out[i].PluginID < out[j].PluginID
|
||||
}
|
||||
return out[i].ID < out[j].ID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterDiagnostics(sc *Scope, contrib DiagnosticsContribution, collector DiagnosticsCollector) {
|
||||
if collector == nil {
|
||||
return
|
||||
|
||||
@@ -292,7 +292,7 @@ func (m Manifest) InferTier(isBuiltin bool) Tier {
|
||||
if strings.TrimSpace(m.Entry.Script) != "" {
|
||||
return TierL2
|
||||
}
|
||||
if strings.TrimSpace(m.Entry.PanelDir) != "" || len(m.Contributes.Panels) > 0 {
|
||||
if strings.TrimSpace(m.Entry.PanelDir) != "" || len(m.Contributes.Panels) > 0 || len(m.Contributes.ImageSources) > 0 {
|
||||
return TierL4
|
||||
}
|
||||
if len(m.Contributes.Runtimes) > 0 {
|
||||
@@ -321,6 +321,7 @@ type Contributes struct {
|
||||
SettingsPages []SettingsPageContribution `json:"settingsPages,omitempty"`
|
||||
StatusItems []StatusItemContribution `json:"statusItems,omitempty"`
|
||||
Panels []PanelContribution `json:"panels,omitempty"`
|
||||
ImageSources []ImageSourceContribution `json:"imageSources,omitempty"`
|
||||
Views []ViewContribution `json:"views,omitempty"`
|
||||
Diagnostics []DiagnosticsContribution `json:"diagnostics,omitempty"`
|
||||
}
|
||||
@@ -601,6 +602,20 @@ type PanelContribution struct {
|
||||
PluginID string `json:"pluginId,omitempty"`
|
||||
}
|
||||
|
||||
// ImageSourceContribution registers a tab entry in the top-level Images page
|
||||
// segmented control. External plugins provide a sandboxed L4 iframe Entry under
|
||||
// entry.panelDir; compiled-in builtins may set Native to mount a host view.
|
||||
type ImageSourceContribution struct {
|
||||
ID string `json:"id"`
|
||||
Title LocalizedText `json:"title"`
|
||||
Description LocalizedText `json:"description,omitempty"`
|
||||
Order int `json:"order,omitempty"`
|
||||
Entry string `json:"entry,omitempty"`
|
||||
Height int `json:"height,omitempty"`
|
||||
Native string `json:"native,omitempty"`
|
||||
PluginID string `json:"pluginId,omitempty"`
|
||||
}
|
||||
|
||||
// ViewContribution declares a sandboxed iframe view with its own page, tab or
|
||||
// dialog (§5.6). Entry is relative to entry.panelDir; Location is one of
|
||||
// ViewLocationCatalog.
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
|
||||
var reRuntimeKind = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
|
||||
|
||||
var ErrNoActiveRuntime = errors.New("no active runtime installed")
|
||||
|
||||
const (
|
||||
// DefaultKind is the built-in macOS vGPU runtime kind.
|
||||
DefaultKind = "reims-vgpu"
|
||||
@@ -294,5 +296,5 @@ func ResolveForKind(cfg *config.Config, kind string) (*Installed, error) {
|
||||
if len(list) == 1 || (kind != DefaultKind && len(list) > 0) {
|
||||
return &list[0], nil
|
||||
}
|
||||
return nil, fmt.Errorf("no active %s runtime installed", kind)
|
||||
return nil, fmt.Errorf("%s: %w", kind, ErrNoActiveRuntime)
|
||||
}
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
// Version is the current Reims-Go release version. Release builds may override
|
||||
// it at link time with:
|
||||
//
|
||||
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.10"
|
||||
var Version = "v0.2.10"
|
||||
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.11"
|
||||
var Version = "v0.2.11"
|
||||
|
||||
const (
|
||||
DefaultReleasesRepo = "Nwflower/Reims-Go"
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"sidebarSettings": "Settings",
|
||||
"quitInProgress": "Quitting…",
|
||||
"quitFailed": "Quit canceled",
|
||||
"sidebarInstallers": "Installers",
|
||||
"sidebarInstallers": "Images",
|
||||
"installersRetry": "Retry",
|
||||
"emptyVMs": "No virtual machines",
|
||||
"hostReady": "Ready",
|
||||
|
||||
@@ -57,22 +57,28 @@
|
||||
"keymapGuestRctrl": "Right ⌃ Control",
|
||||
"keymapGuestEsc": "Esc",
|
||||
"keymapGuestDisabled": "Disabled",
|
||||
"installersTitle": "Installers",
|
||||
"installersTitle": "Images",
|
||||
"installersDownloaded": "Downloaded",
|
||||
"installersAvailable": "Releases from Apple",
|
||||
"installersLatest": "Latest",
|
||||
"installersOlder": {
|
||||
"message": "{count, plural, one {# older version} other {# older versions}}",
|
||||
"$comment": "安装包页面折叠的旧点版本计数按钮"
|
||||
"$comment": "镜像页面折叠的旧点版本计数按钮"
|
||||
},
|
||||
"installersEmpty": "No installers downloaded yet",
|
||||
"installersEmpty": "No images downloaded yet",
|
||||
"installersPartial": "Partly downloaded",
|
||||
"installersResume": "Resume",
|
||||
"installersDownload": "Download",
|
||||
"installersDelete": "Delete",
|
||||
"installersDeleteConfirm": "Confirm delete",
|
||||
"installersNoSpace": "Not enough space: needs about {need} GB, {free} GB free",
|
||||
"installersHint": "Downloaded installers can be reused for new VMs",
|
||||
"installersHint": "Downloaded images can be reused for new VMs",
|
||||
"imagesSourcesLabel": "Image sources",
|
||||
"imagesNoSourcesTitle": "No image source plugins enabled",
|
||||
"imagesNoSourcesDesc": "Enable at least one image source plugin (such as macOS Images) in Plugins to browse and download system images.",
|
||||
"imagesOpenPlugins": "Open Plugins",
|
||||
"macosSlaNotice": "Use of this software requires acceptance of the original license agreement included with the software.",
|
||||
"macosSlaButton": "View SLA",
|
||||
"installersCreateVM": "Create VM",
|
||||
"installersKindOffline": "Offline installer",
|
||||
"installersKindOnline": "Online recovery",
|
||||
@@ -104,7 +110,7 @@
|
||||
"themeLabel": "Appearance",
|
||||
"storageBreakdownTitle": "Storage breakdown",
|
||||
"storageVMs": "VM files",
|
||||
"storageInstallers": "Installers",
|
||||
"storageInstallers": "Images",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"welcomeTitle": "Create your first macOS VM",
|
||||
"welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"sidebarSettings": "设置",
|
||||
"quitInProgress": "正在退出…",
|
||||
"quitFailed": "已取消退出",
|
||||
"sidebarInstallers": "安装包",
|
||||
"sidebarInstallers": "镜像",
|
||||
"installersRetry": "重试",
|
||||
"emptyVMs": "还没有虚拟机",
|
||||
"hostReady": "就绪",
|
||||
|
||||
@@ -57,22 +57,28 @@
|
||||
"keymapGuestRctrl": "右 ⌃ Control",
|
||||
"keymapGuestEsc": "Esc",
|
||||
"keymapGuestDisabled": "禁用",
|
||||
"installersTitle": "安装包",
|
||||
"installersTitle": "镜像",
|
||||
"installersDownloaded": "已下载",
|
||||
"installersAvailable": "Apple 提供的版本",
|
||||
"installersLatest": "最新",
|
||||
"installersOlder": {
|
||||
"message": "{count, plural, other {# 个旧版本}}",
|
||||
"$comment": "安装包页面折叠的旧点版本计数按钮"
|
||||
"$comment": "镜像页面折叠的旧点版本计数按钮"
|
||||
},
|
||||
"installersEmpty": "还没有下载任何安装包",
|
||||
"installersEmpty": "还没有下载任何镜像",
|
||||
"installersPartial": "未下载完",
|
||||
"installersResume": "继续下载",
|
||||
"installersDownload": "下载",
|
||||
"installersDelete": "删除",
|
||||
"installersDeleteConfirm": "确认删除",
|
||||
"installersNoSpace": "空间不足:需要约 {need} GB,可用 {free} GB",
|
||||
"installersHint": "下载好的安装包可以重复用来新建虚拟机",
|
||||
"installersHint": "下载好的镜像可以重复用来新建虚拟机",
|
||||
"imagesSourcesLabel": "镜像来源",
|
||||
"imagesNoSourcesTitle": "未启用镜像源插件",
|
||||
"imagesNoSourcesDesc": "请在「插件」页面启用至少一个镜像源插件(例如 macOS 镜像源)以浏览和下载系统镜像。",
|
||||
"imagesOpenPlugins": "前往插件",
|
||||
"macosSlaNotice": "使用此软件必须接受软件附带的原始许可协议。",
|
||||
"macosSlaButton": "查看许可协议",
|
||||
"installersCreateVM": "新建虚拟机",
|
||||
"installersKindOffline": "离线完整包",
|
||||
"installersKindOnline": "在线恢复镜像",
|
||||
@@ -104,7 +110,7 @@
|
||||
"themeLabel": "外观",
|
||||
"storageBreakdownTitle": "空间分布",
|
||||
"storageVMs": "虚拟机文件",
|
||||
"storageInstallers": "安装包",
|
||||
"storageInstallers": "镜像",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"welcomeTitle": "创建第一台 macOS 虚拟机",
|
||||
"welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置",
|
||||
|
||||
@@ -27,11 +27,12 @@ export function resolveStorageRoot(root = REPO_ROOT) {
|
||||
['rev-parse', '--path-format=absolute', '--git-common-dir'],
|
||||
{ cwd: resolved, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
|
||||
).trim()
|
||||
if (common !== '') return path.dirname(path.resolve(resolved, common))
|
||||
} catch {
|
||||
return common !== '' ? path.dirname(path.resolve(resolved, common)) : resolved
|
||||
} catch (error) {
|
||||
// Non-git directories (e.g. synthetic test sandboxes) use the directory directly.
|
||||
if (error?.code === 'ENOENT' || error?.status === 128) return resolved
|
||||
throw error
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
export const debugPath = (root, ...parts) => path.join(root, '.debug', ...parts)
|
||||
|
||||
@@ -306,8 +306,9 @@ export function createWorkStore(storageRoot = resolveStorageRoot()) {
|
||||
if (error.code !== 'EEXIST') throw error
|
||||
try {
|
||||
if (Date.now() - fs.statSync(LOCK).mtimeMs > 10_000) fs.rmSync(LOCK, { force: true })
|
||||
} catch {
|
||||
} catch (statError) {
|
||||
// Holder released the lock between open and stat.
|
||||
if (statError?.code !== 'ENOENT') throw statError
|
||||
}
|
||||
if (Date.now() - started > 5_000) throw new Error('work: index lock is busy')
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50)
|
||||
|
||||
@@ -377,8 +377,8 @@ try {
|
||||
}
|
||||
} finally {
|
||||
Write-Host "[io-bench] Cleaning up guest temp files and clearing QMP histogram..."
|
||||
try { [void](Invoke-Ssh -RemoteCmd "rm -rf $remoteWorkDir $remoteBin" -AllowFailure) } catch {}
|
||||
try { [void](& $qmpBin histogram -vm-dir $VmDir -device $Device -clear) } catch {}
|
||||
try { [void](Invoke-Ssh -RemoteCmd "rm -rf $remoteWorkDir $remoteBin" -AllowFailure) } catch { Write-Warning "[io-bench] Failed to clean guest temp files: $_" }
|
||||
try { [void](& $qmpBin histogram -vm-dir $VmDir -device $Device -clear) } catch { Write-Warning "[io-bench] Failed to clear QMP histogram: $_" }
|
||||
}
|
||||
|
||||
# 5. Aggregate per workload
|
||||
|
||||
Reference in new issue
Block a user