Files
Reims-Go/frontend/src/components/SettingsModal.tsx
T
Dnyo666 ceeec602be feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI

# Conflicts:
#	frontend/src/i18n.ts
#	internal/cli/cli.go
#	internal/i18n/i18n.go
2026-11-30 14:56:19 +08:00

1047 lines
40 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { CircleAlert, Copy, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react'
import '../i18n/domains/settings.gen'
import { I18nKey, parseAppError, t } from '../i18n'
import {
GUEST_LANG_PRESETS,
guestLangOptions,
MEMORY_MARKS,
findGPU,
formatBytes,
gpuCompatHint,
gpuOptionValue,
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
hidpiLooksLike,
hostDisplayAdvice,
hostDisplayDesc,
recommendedDisplayPresets,
recommendedMemoryGB,
shortGPUName,
sshCommand,
} from '../lib/format'
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
import { api } from '../wails'
import { formatAffinitySummary } from './AffinityDialog'
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
// VM settings (docs/design-guidelines.md §2–3): edits are staged here and written in
// one `reims-ctl set` on Save, because upstream applies every change on the
// next start. Each row marks itself when it differs from the VM's current
// value and can be put back on its own.
type Cat = 'general' | 'compute' | 'display' | 'storage' | 'input' | 'advanced'
const CATS: { id: Cat; label: I18nKey; icon: LucideIcon }[] = [
{ id: 'general', label: 'catGeneral', icon: Info },
{ id: 'compute', label: 'catCompute', icon: Cpu },
{ id: 'display', label: 'catGraphics', icon: Monitor },
{ id: 'storage', label: 'catStorageNet', icon: HardDrive },
{ id: 'input', label: 'catInputAudio', icon: Keyboard },
{ id: 'advanced', label: 'catAdvanced', icon: Wrench },
]
type Field = Exclude<keyof SetOpts, 'name' | 'env'>
const FIELD_CAT: Record<Field, Cat> = {
guest_lang: 'general',
cpus: 'compute',
memory: 'compute',
graphics: 'display',
gpu: 'display',
resolution: 'display',
displays: 'display',
borderless: 'display',
disk_controller: 'storage',
network: 'storage',
ssh_port: 'storage',
capture: 'input',
audio: 'input',
audio_backend: 'input',
logs: 'advanced',
log_level: 'advanced',
stop_timeout: 'advanced',
extra_args: 'advanced',
}
const FIELDS = Object.keys(FIELD_CAT) as Field[]
const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
const CUSTOM = '__custom'
const FULLSCREEN = '__fullscreen'
const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i
const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase()
const normRes = (s: string | undefined) => (s ?? '').replace(/\s/g, '').replace(/×/g, 'x').toLowerCase()
/** Whether two values of a field mean the same thing to reims-ctl. */
function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean {
switch (field) {
case 'memory': return parseMemoryGB(a as string) === parseMemoryGB(b as string)
case 'gpu': return normPath(a as string) === normPath(b as string)
case 'resolution': return normRes(a as string) === normRes(b as string)
case 'log_level':
case 'extra_args':
case 'audio_backend':
case 'guest_lang': return String(a ?? '').trim() === String(b ?? '').trim()
default: return a === b
}
}
function baseline(detail: VMDetail, host: HostReport): SetOpts {
// Match the stored ICD path to the host's spelling so the GPU card lights up.
const icd = (host.gpus ?? []).find((g) => normPath(g.vulkan_icd) === normPath(detail.gpu))?.vulkan_icd
return {
name: detail.name,
cpus: detail.cpus,
memory: detail.memory,
graphics: detail.graphics,
displays: detail.displays || 1,
disk_controller: detail.disk_controller,
resolution: detail.resolution,
borderless: detail.borderless,
capture: detail.capture,
gpu: icd ?? (detail.gpu || 'auto'),
logs: detail.logs,
log_level: detail.log_level,
audio: detail.audio,
audio_backend: detail.audio_backend || 'auto',
network: detail.network,
ssh_port: detail.ssh_port,
stop_timeout: detail.stop_timeout,
extra_args: detail.extra_args,
guest_lang: detail.guest_lang || 'en-US:0',
}
}
interface Props {
locale: Locale
detail: VMDetail
stats?: VMStats | null
host: HostReport
optimizations?: Optimization[]
running: boolean
onCopy?: (text: string) => void
onDiskChanged?: () => void
onOpenAffinity?: () => void
affinityVersion?: number
/** Re-probe the host, e.g. after Windows' processor scheduling may have changed. */
onHostChanged?: () => void
onClose: () => void
onSaved: () => void
}
export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onClose, onSaved }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
const base = useMemo(() => baseline(detail, host), [detail, host])
const [cat, setCat] = useState<Cat>('compute')
const [busy, setBusy] = useState(false)
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [err, setErr] = useState('')
const [form, setForm] = useState<SetOpts>(base)
const [resizeInput, setResizeInput] = useState('+64G')
const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | ''>('')
const [resizeResult, setResizeResult] = useState<DiskResizeResult | null>(null)
const [compactResult, setCompactResult] = useState<DiskCompactResult | null>(null)
const [driveSettings, setDriveSettings] = useState<DriveShareSettings | null>(null)
const [driveBusy, setDriveBusy] = useState(false)
const driveBusyRef = useRef(false)
const activeVMNameRef = useRef(detail.name)
activeVMNameRef.current = detail.name
const [driveErr, setDriveErr] = useState('')
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
const [vmPlugins, setVmPlugins] = useState<PluginInfo[]>([])
const [vmPluginVals, setVmPluginVals] = useState<Record<string, Record<string, unknown>>>({})
const pane = useRef<HTMLDivElement>(null)
useEffect(() => {
let live = true
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(detail.name)])
.then(([list, vals]) => {
if (!live) return
const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings)
setVmPlugins(activeWithVM)
setVmPluginVals((vals ?? {}) as Record<string, Record<string, unknown>>)
})
.catch(() => {})
return () => { live = false }
}, [detail.name])
const updateVMPluginSetting = (pluginID: string, next: Record<string, unknown>) => {
setVmPluginVals((prev) => ({ ...prev, [pluginID]: next }))
void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(parseAppError(e).summary))
}
const renderVMPluginGroup = (group: string) => {
const matched = vmPlugins.filter((p) => p.settings && (p.settings['x-group'] === group || Object.values(p.settings.properties ?? {}).some((prop) => prop['x-group'] === group)))
if (matched.length === 0) return null
return (
<Suspense fallback={null}>
{matched.map((p) => (
<SchemaForm
key={p.id}
locale={locale}
schema={p.settings!}
values={vmPluginVals[p.id] ?? {}}
scopeFilter="vm"
groupFilter={group}
onChange={(next) => updateVMPluginSetting(p.id, next)}
/>
))}
</Suspense>
)
}
const presets = recommendedDisplayPresets(host)
const presetHit = presets.some((p) => same('resolution', p.resolution, form.resolution))
const [customRes, setCustomRes] = useState(!presetHit)
const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level))
// The detail the panel opened with can be a stale one (reopened right after
// a save, before the refreshed detail arrives): follow newer details until
// the person changes something.
const edited = useRef(false)
useEffect(() => {
if (edited.current) return
setForm(base)
setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}, [base]) // presets come from host, which base already follows
const set = (patch: Partial<SetOpts>) => {
edited.current = true
setForm((f) => ({ ...f, ...patch }))
const touched = Object.keys(patch)
setIssues((list) => list.filter((i) => !touched.includes(i.field)))
}
const dirty = (f: Field) => !same(f, form[f], base[f])
const reset = (f: Field) => () => {
set({ [f]: base[f] } as Partial<SetOpts>)
if (f === 'resolution') setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
if (f === 'log_level') setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
const changed = FIELDS.filter(dirty)
const changedIn = (c: Cat) => changed.filter((f) => FIELD_CAT[f] === c).length
const issueOf = (f: Field) => issues.find((i) => i.field === f)?.message
const issueIn = (c: Cat) => issues.some((i) => FIELD_CAT[i.field as Field] === c) || (c === 'display' && resBad)
const strayIssues = issues.filter((i) => !(i.field in FIELD_CAT))
// Inline checks the backend would also reject, so the row says it first.
const resBad = customRes && !RES_RE.test(form.resolution ?? '')
const sshOn = (form.ssh_port ?? 0) > 0
const localBlock = resBad
const rowProps = (f: Field) => ({
field: f,
dirty: dirty(f),
onReset: reset(f),
resetLabel: tr('resetField'),
error: issueOf(f),
})
// Scroll the first row with an error into view after switching to its page.
useEffect(() => {
if (issues.length === 0) return
const el = pane.current?.querySelector<HTMLElement>('[data-error]')
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}, [issues, cat])
useEffect(() => {
let active = true
setDriveSettings(null)
setDriveErr('')
api.GetVMDriveShareSettings(detail.name)
.then((settings) => { if (active) setDriveSettings(settings) })
.catch((e) => { if (active) setDriveErr(parseAppError(e).summary) })
return () => { active = false }
}, [detail.name])
useEffect(() => {
let active = true
api.GetVMAffinity(detail.name)
.then((st) => { if (active) setAffinityStatus(st) })
.catch(() => {})
return () => { active = false }
}, [detail.name, running, affinityVersion])
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
if (driveBusyRef.current || !driveSettings) return
driveBusyRef.current = true
const vmName = detail.name
setDriveBusy(true)
setDriveErr('')
try {
const next = await api.SetVMDriveShareSettings(vmName, enabled, selected)
if (activeVMNameRef.current === vmName) setDriveSettings(next)
} catch (e) {
if (activeVMNameRef.current === vmName) setDriveErr(parseAppError(e).summary)
} finally {
driveBusyRef.current = false
setDriveBusy(false)
}
}
const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive)
// Windows-wide, not staged with Save: one UAC prompt opens Windows' own
// Performance Options, and the new choice shows after the host refresh.
const [openingSched, setOpeningSched] = useState(false)
const openScheduling = async () => {
setOpeningSched(true)
try {
await api.OpenProcessorScheduling()
onHostChanged?.()
} catch (e) {
setErr(parseAppError(e).summary)
} finally {
setOpeningSched(false)
}
}
const handleSave = async () => {
if (busy || changed.length === 0 || localBlock) return
setErr('')
setIssues([])
setBusy(true)
try {
const diff: SetOpts = { name: detail.name }
for (const f of changed) (diff as unknown as Record<string, unknown>)[f] = form[f]
const iss = await api.ValidateSet(diff)
if (iss && iss.length > 0) {
setIssues(iss)
const first = iss.map((i) => FIELD_CAT[i.field as Field]).find(Boolean)
if (first) setCat(first)
return
}
await api.ApplyVMSettings(diff)
onSaved()
} catch (e) {
setErr(parseAppError(e).summary)
} finally {
setBusy(false)
}
}
const resetAll = () => {
edited.current = false
setForm(base)
setIssues([])
setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
const onKeyDown = (e: React.KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
e.preventDefault()
void handleSave()
}
}
const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual')
const threads = Math.max(host.logical_cpus || 0, 1)
const cpuRec = recommendedCPUs(host)
const memRec = recommendedMemoryGB(host)
const memSafe = memorySafeLimitGB(host)
const memMax = Math.max(Math.floor((host.total_ram_gb || 16) * 0.85), memRec, 4)
const memGB = Math.round(parseMemoryGB(form.memory) ?? memRec)
// ── Pages ────────────────────────────────────────────────
const general = (
<>
<SetGroup title={tr('groupMacOS')}>
<SetRow
{...rowProps('guest_lang')}
title={tr('guestLangShort')}
desc={tr('guestLangSettingsHint')}
control={
<PopupSelect
label={tr('guestLangShort')}
value={form.guest_lang || 'en-US:0'}
onChange={(guest_lang) => set({ guest_lang })}
options={[
...guestLangOptions(locale),
...(form.guest_lang && !GUEST_LANG_PRESETS.some((p) => p.value === form.guest_lang)
? [{ value: form.guest_lang, label: form.guest_lang }]
: []),
]}
/>
}
/>
</SetGroup>
<SetGroup note={tr('platformReadonly')}>
<SetValue title={tr('vmName')} value={detail.name} />
<SetValue title={tr('fieldKind')} value={detail.kind || '—'} />
<SetValue title={tr('fieldCPUModel')} value={detail.cpu_model || '—'} mono />
<SetValue title={tr('opencore')} value={detail.has_opencore ? tr('configured') : '—'} />
<SetValue title={tr('fieldDir')} value={detail.directory} mono />
</SetGroup>
{renderVMPluginGroup('collaboration')}
</>
)
const irqMode = parseKernelIrqchip(form.extra_args)
const cpuOver = (form.cpus ?? 0) > threads - 2 && threads > 2
const memOver = memGB > memSafe
const compute = (
<>
<SetGroup title={tr('factCPU')}>
<SetRow
{...rowProps('cpus')}
title={tr('vcpus')}
desc={cpuOver ? <span className="warn-text">{tr('cpuOverHint')}</span> : tr('cpuRecHint', { rec: cpuRec, n: threads })}
block={
<RangeField
label={tr('vcpus')}
value={form.cpus ?? cpuRec}
min={1}
max={threads}
unit={tr('coresUnit')}
onChange={(cpus) => set({ cpus })}
recommend={[Math.min(4, cpuRec), cpuRec]}
warnFrom={threads > 2 ? threads - 1 : undefined}
marks={[1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64].concat(threads).map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
{onOpenAffinity && (
<SetRow
title={tr('affinityTitle')}
desc={affinityStatus ? `${formatAffinitySummary(locale, affinityStatus)} · ${tr('affinityRowDesc')}` : tr('affinityRowDesc')}
control={
<Button variant="secondary" icon={<Cpu size={13} aria-hidden="true" />} onClick={onOpenAffinity}>
{tr('affinityConfigure')}
</Button>
}
/>
)}
</SetGroup>
<SetGroup title={tr('factMemory')}>
<SetRow
{...rowProps('memory')}
title={tr('guestMemory')}
desc={memOver
? <span className="warn-text">{tr('memOverHint')}</span>
: host.commit_avail_gb > 0
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: memRec })
: tr('memRecHint', { rec: memRec, n: host.total_ram_gb.toFixed(0) })}
block={
<RangeField
label={tr('guestMemory')}
value={memGB}
min={2}
max={memMax}
unit="GB"
onChange={(gb) => set({ memory: `${gb}G` })}
recommend={[Math.min(4, memRec), memRec]}
warnFrom={memSafe + 1}
marks={MEMORY_MARKS.concat(memMax).map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
</SetGroup>
<SetGroup title={tr('groupPerformance')}>
<SetRow
{...rowProps('extra_args')}
dirty={parseKernelIrqchip(form.extra_args) !== parseKernelIrqchip(base.extra_args)}
onReset={() => set({ extra_args: applyKernelIrqchip(form.extra_args, parseKernelIrqchip(base.extra_args)) })}
error={undefined}
field={undefined}
title={tr('kernelIrqchipLabel')}
desc={<span className={irqOpt?.detail?.startsWith('0x') ? 'warn-text' : undefined}>{kernelIrqchipHint(locale, irqOpt)}</span>}
control={
<Segmented
label={tr('kernelIrqchipLabel')}
value={irqMode}
onChange={(mode) => set({ extra_args: applyKernelIrqchip(form.extra_args, mode) })}
options={[
{ value: 'auto', label: tr('kernelIrqchipAuto') },
{ value: 'on', label: tr('kernelIrqchipOn'), disabled: !irqOpt?.supported },
{ value: 'off', label: tr('kernelIrqchipOff') },
]}
/>
}
/>
<SetRow
title={tr('optSchedTitle')}
desc={
host.processor_scheduling === 'background'
? tr('optSchedNowBackground')
: host.processor_scheduling
? <span className="warn-text">{tr('optSchedNowPrograms')}</span>
: tr('optSchedSub')
}
control={<Button variant="secondary" busy={openingSched} onClick={openScheduling}>{tr('optSchedOpen')}</Button>}
/>
</SetGroup>
</>
)
const gpuOptions = [
{
value: 'auto',
title: tr('gpuAutoTitle'),
sub: host.recommended_gpu ? tr('gpuAutoSub', { name: shortGPUName(host.recommended_gpu.name) }) : tr('gpuAutoOption'),
},
...realGPUs.map((g) => ({
value: gpuOptionValue(g, realGPUs),
title: shortGPUName(g.name),
sub: [
g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : '',
g.compat === 'unsupported' ? tr('gpuCompatUnsupported') : g.compat === 'warn' ? tr('gpuCompatWarn') : '',
]
.filter(Boolean)
.join(' · ') || undefined,
})),
]
if (form.gpu && form.gpu !== 'auto' && !gpuOptions.some((o) => normPath(o.value) === normPath(form.gpu))) {
gpuOptions.push({ value: form.gpu, title: form.gpu.split(/[\\/]/).pop() || form.gpu, sub: tr('gpuCustomIcd') })
}
const selectedGPU = findGPU(host, form.gpu)
const selectedGPUHint = gpuCompatHint(locale, selectedGPU)
const vgpu = form.graphics !== 'vmware-svga'
const pd = host.primary_display
const hidpiAdvice = hostDisplayAdvice(host, tr)
const resValue = form.borderless ? FULLSCREEN : customRes ? CUSTOM : presets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
const resArt = (r: string) => {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
return m ? <ScreenArt w={Number(m[1])} h={Number(m[2])} /> : <ScreenArt w={16} h={10} />
}
const display = (
<>
<SetGroup title={tr('groupGraphics')}>
<SetRow
{...rowProps('graphics')}
title={tr('graphicsBackend')}
desc={vgpu ? tr('graphicsReimsDesc') : tr('graphicsSvgaDesc')}
disabled={running}
reason={tr('graphicsRunningReason')}
control={
<Segmented
label={tr('graphicsBackend')}
value={form.graphics}
onChange={(graphics) => set({ graphics })}
options={[
{ value: 'reims-vgpu', label: tr('graphicsReimsShort') },
{ value: 'vmware-svga', label: tr('graphicsSvgaShort') },
]}
/>
}
/>
<SetRow
{...rowProps('gpu')}
title={tr('gpuSelect')}
desc={
realGPUs.length === 0 ? (
<span className="warn-text">{tr('gpuUnavailableHint')}</span>
) : selectedGPUHint ? (
<span className="warn-text">
{selectedGPUHint}
{!running && vgpu && (
<>
{' '}
<button
type="button"
className="link-btn"
onClick={() => set({ graphics: 'vmware-svga' })}
>
{tr('gpuSwitchSvga')}
</button>
</>
)}
</span>
) : undefined
}
disabled={!vgpu}
reason={tr('gpuSvgaReason')}
block={<OptionCards label={tr('gpuSelect')} value={gpuOptions.find((o) => normPath(o.value) === normPath(form.gpu))?.value} onChange={(gpu) => set({ gpu })} options={gpuOptions} />}
/>
</SetGroup>
<SetGroup title={tr('displayGroup')}>
<SetRow
{...rowProps('resolution')}
// Full screen is one of the sizes here, so the row also owns borderless.
dirty={dirty('resolution') || dirty('borderless')}
onReset={() => { reset('resolution')(); reset('borderless')() }}
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
title={tr('resolution')}
desc={hostDisplayDesc(host, tr)}
block={
<>
<OptionCards
label={tr('resolution')}
value={resValue}
onChange={(v) => {
if (v === FULLSCREEN) { setCustomRes(false); set({ borderless: true }); return }
if (v === CUSTOM) { setCustomRes(true); set({ borderless: false }); return }
setCustomRes(false)
set({ resolution: v, borderless: false })
}}
options={[
...presets.map((p) => ({
value: p.resolution,
title: p.label,
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
art: resArt(p.resolution),
badges: [p.hidpi ? tr('hidpiPresetBadge') : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean),
})),
{
value: FULLSCREEN,
title: tr('resFullscreen'),
sub: pd ? `${pd.width} × ${pd.height}` : undefined,
art: pd ? resArt(`${pd.width}x${pd.height}`) : resArt('16x10'),
badges: host.fullscreen_hidpi ? [tr('hidpiPresetBadge')] : [],
},
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> },
]}
/>
{customRes && !form.borderless && (
<input
className="input mono res-input"
aria-label={tr('resolution')}
placeholder="2560x1600"
autoFocus
value={form.resolution ?? ''}
onChange={(e) => set({ resolution: e.target.value })}
/>
)}
{hidpiAdvice && <div className="srow-desc res-advice">{hidpiAdvice}</div>}
</>
}
/>
<SetRow
{...rowProps('displays')}
title={tr('displays')}
desc={(host.displays?.length ?? 0) > 1 ? tr('multiDisplayHint', { n: host.displays?.length ?? 1 }) : undefined}
control={
<Segmented
label={tr('displays')}
value={form.displays ?? 1}
onChange={(displays) => set({ displays })}
options={[1, 2, 3, 4].map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
</SetGroup>
</>
)
const handleResizeDisk = async () => {
if (running || diskOpBusy || !resizeInput.trim()) return
setErr('')
setDiskOpBusy('resize')
try {
const res = await api.ResizeVMDisk(detail.name, resizeInput.trim())
setResizeResult(res)
onDiskChanged?.()
} catch (e) {
setErr(parseAppError(e).summary)
} finally {
setDiskOpBusy('')
}
}
const handleCompactDisk = async () => {
if (running || diskOpBusy) return
setErr('')
setDiskOpBusy('compact')
try {
const res = await api.CompactVMDisk(detail.name)
setCompactResult(res)
onDiskChanged?.()
} catch (e) {
setErr(parseAppError(e).summary)
} finally {
setDiskOpBusy('')
}
}
const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2'
const diskControllerDesc = detail.has_installer
? tr('diskControllerInstallHint')
: form.disk_controller === 'virtio'
? tr('diskControllerVirtioHint')
: form.disk_controller === 'nvme'
? tr('diskControllerNvmeReadyHint')
: tr('diskControllerNvmeHint')
const storage = (
<>
<SetGroup title={tr('catStorage')}>
<SetValue title={tr('fieldDisk')} value={detail.disk} mono />
{stats && stats.disk_virtual_bytes > 0 && (
<SetValue
title={tr('factDisk')}
value={tr('diskUsageSummary', {
actual: formatBytes(stats.disk_actual_bytes, locale),
virtual: formatBytes(stats.disk_virtual_bytes, locale),
})}
/>
)}
<SetRow
{...rowProps('disk_controller')}
title={tr('diskController')}
desc={diskControllerDesc}
disabled={detail.has_installer}
reason={tr('diskControllerWarn')}
control={
<Segmented
label={tr('diskController')}
value={form.disk_controller}
onChange={(disk_controller) => set({ disk_controller })}
options={[
{ value: 'ahci', label: 'SATA' },
{ value: 'nvme', label: 'NVMe' },
{ value: 'virtio', label: 'VirtIO' },
]}
/>
}
/>
<SetRow
title={tr('diskResizeTitle')}
desc={tr('diskResizeDesc')}
disabled={running}
reason={tr('stopBeforeDiskOp')}
block={
<div className="stack-2">
<div className="hstack">
<div className="presets">
{['+32G', '+64G', '+128G', '256G', '512G'].map((v) => (
<button
key={v}
type="button"
className="preset"
aria-pressed={resizeInput === v}
disabled={running || !!diskOpBusy}
onClick={() => setResizeInput(v)}
>
{v}
</button>
))}
</div>
</div>
<div className="hstack">
<input
className="input mono input-compact"
aria-label={tr('diskResizeTitle')}
value={resizeInput}
spellCheck={false}
autoComplete="off"
disabled={running || !!diskOpBusy}
onChange={(e) => setResizeInput(e.target.value)}
placeholder="+64G / 256G"
/>
<Button
variant="secondary"
busy={diskOpBusy === 'resize'}
disabled={running || !!diskOpBusy || !resizeInput.trim()}
onClick={handleResizeDisk}
>
{tr('diskResizeAction')}
</Button>
</div>
{resizeResult && (
<div className="notice">
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}</div>
<div className="cmd-line cmd-line-spaced">
<code>{resizeResult.guest_expand_cmd}</code>
{onCopy && (
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(resizeResult.guest_expand_cmd)} />
)}
</div>
</div>
)}
</div>
}
/>
<SetRow
title={tr('diskCompactTitle')}
desc={compactResult
? compactResult.reclaimed_bytes > 0
? tr('diskCompactDone', {
before: formatBytes(compactResult.before_bytes, locale),
after: formatBytes(compactResult.after_bytes, locale),
reclaimed: formatBytes(compactResult.reclaimed_bytes, locale),
})
: tr('diskCompactNoGain')
: tr('diskCompactDesc')}
disabled={running || !isQcow2}
reason={running ? tr('stopBeforeDiskOp') : tr('diskCompactQcow2Only')}
control={
<Button
variant="secondary"
busy={diskOpBusy === 'compact'}
disabled={running || !isQcow2 || !!diskOpBusy}
onClick={handleCompactDisk}
>
{tr('diskCompactAction')}
</Button>
}
/>
</SetGroup>
<SetGroup title={tr('driveShareTitle')} note={tr('driveShareReadOnly')}>
<SetRow
title={tr('driveShareMaster')}
desc={tr('driveShareMasterDesc')}
control={
<Switch
label={tr('driveShareMaster')}
checked={!!driveSettings?.enabled}
disabled={!driveSettings || driveBusy || !!detail.guest_tools_disabled}
onChange={(enabled) => void updateDriveShares(enabled, selectedDrives())}
/>
}
/>
{detail.guest_tools_disabled && <div className="notice">{tr('gtStatusOffTip')}</div>}
{driveErr && <div className="notice" role="alert">{driveErr}</div>}
{driveSettings?.enabled && selectedDrives().length > 0 &&
(detail.guest_tools_agent_version ?? 0) < driveSettings.required_agent_version && (
<div className="notice">{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}</div>
)}
{/* Drives are only worth choosing once sharing is on. */}
{driveSettings?.enabled && driveSettings.drives.map((drive) => {
const title = `Windows (${drive.drive}:)`
return (
<SetRow
key={drive.drive}
title={title}
desc={drive.system ? <span className="warn-text">{tr('driveShareSystem')}</span> : undefined}
disabled={driveBusy || !!detail.guest_tools_disabled}
control={
<Switch
label={title}
checked={drive.selected}
disabled={driveBusy}
onChange={(enabled) => {
const next = selectedDrives().filter((letter) => letter !== drive.drive)
if (enabled) next.push(drive.drive)
void updateDriveShares(driveSettings?.enabled ?? false, next)
}}
/>
}
/>
)
})}
{driveSettings && driveSettings.drives.length === 0 && (
<SetValue title={tr('driveShareTitle')} value={tr('driveShareNoDrives')} />
)}
</SetGroup>
<SetGroup title={tr('catNetwork')}>
<SetRow
{...rowProps('network')}
title={tr('networkTitle')}
desc={tr('networkDesc')}
control={<Switch label={tr('enableNetwork')} checked={!!form.network} onChange={(network) => set({ network })} />}
/>
<SetRow
{...rowProps('ssh_port')}
title={tr('sshForward')}
desc={sshOn ? <code className="inline-code">{sshCommand(form.ssh_port ?? 0)}</code> : tr('sshOffDesc')}
disabled={!form.network}
reason={tr('sshNeedsNetwork')}
control={
<div className="hstack">
{sshOn && (
<NumberField label={tr('sshPort')} value={form.ssh_port ?? 0} min={1} max={65535} onChange={(ssh_port) => set({ ssh_port })} />
)}
<Switch
label={tr('sshForward')}
checked={sshOn}
onChange={(on) => set({ ssh_port: on ? (base.ssh_port || 2222) : 0 })}
/>
</div>
}
/>
</SetGroup>
</>
)
const hostAudio = host.audio
const audioOutSummary = hostAudio
? hostAudio.output_count > 0
? `${hostAudio.output_count}${hostAudio.output_devices?.length ? ` · ${hostAudio.output_devices.slice(0, 2).join(', ')}` : ''}`
: tr('hostAudioMissingOut')
: '—'
const audioInSummary = hostAudio
? hostAudio.input_count > 0
? `${hostAudio.input_count}${hostAudio.input_devices?.length ? ` · ${hostAudio.input_devices.slice(0, 2).join(', ')}` : ''}`
: tr('hostAudioMissingIn')
: '—'
const input = (
<>
<SetGroup title={tr('catInput')}>
<SetRow
{...rowProps('capture')}
title={tr('captureInput')}
desc={tr('captureInputHint')}
control={<Switch label={tr('captureInput')} checked={!!form.capture} onChange={(capture) => set({ capture })} />}
/>
</SetGroup>
{renderVMPluginGroup('keyboard')}
<SetGroup title={tr('catAudio')} note={tr('audioTroubleshootNote')}>
<SetRow
{...rowProps('audio')}
title={tr('enableAudio')}
desc={tr('audioDesc')}
control={<Switch label={tr('enableAudio')} checked={!!form.audio} onChange={(audio) => set({ audio })} />}
/>
<SetRow
{...rowProps('audio_backend')}
title={tr('audioBackendTitle')}
desc={tr('audioBackendDesc')}
disabled={!form.audio}
reason={tr('audioDisabledReason')}
control={
<Segmented
label={tr('audioBackendTitle')}
value={form.audio_backend || 'auto'}
onChange={(audio_backend) => set({ audio_backend })}
options={[
{ value: 'auto', label: tr('audioBackendAuto') },
{ value: 'dsound', label: tr('audioBackendDsound') },
{ value: 'none', label: tr('audioBackendNone') },
// A backend set elsewhere (`reims-ctl set --audio-backend wav`) still shows as chosen.
...(['auto', 'dsound', 'none'].includes(form.audio_backend || 'auto') ? [] : [{ value: form.audio_backend as string, label: form.audio_backend as string }]),
]}
/>
}
/>
{hostAudio && (
<>
<SetValue title={tr('hostAudioOutput')} value={audioOutSummary} />
<SetValue title={tr('hostAudioInput')} value={audioInSummary} />
</>
)}
</SetGroup>
</>
)
const advanced = (
<>
<SetGroup title={tr('catLogs')}>
<SetRow
{...rowProps('logs')}
title={tr('enableLogs')}
control={<Switch label={tr('enableLogs')} checked={!!form.logs} onChange={(logs) => set({ logs })} />}
/>
<SetRow
{...rowProps('log_level')}
title={tr('logLevel')}
desc={tr('logLevelDesc')}
block={
<div className="stack-2">
<Segmented
label={tr('logLevel')}
value={customLog ? CUSTOM : (form.log_level || 'info')}
onChange={(v) => {
if (v === CUSTOM) { setCustomLog(true); return }
setCustomLog(false)
set({ log_level: v })
}}
options={[...LOG_LEVELS.map((l) => ({ value: l as string, label: l })), { value: CUSTOM, label: tr('logLevelCustom') }]}
/>
{customLog && (
<input
className="input mono"
aria-label={tr('logLevel')}
placeholder="info,reims=debug"
value={form.log_level ?? ''}
onChange={(e) => set({ log_level: e.target.value })}
/>
)}
</div>
}
/>
</SetGroup>
<SetGroup title={tr('groupQemu')}>
<SetRow
{...rowProps('stop_timeout')}
title={tr('stopTimeout')}
desc={tr('stopTimeoutHint')}
control={<NumberField label={tr('stopTimeout')} value={form.stop_timeout ?? 90} min={0} max={3600} unit={tr('secondsUnit')} onChange={(stop_timeout) => set({ stop_timeout })} />}
/>
<SetRow
{...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 })} />}
/>
</SetGroup>
</>
)
const pages: Record<Cat, React.ReactNode> = { general, compute, display, storage, input, advanced }
return (
<Modal
className="settings-dialog"
title={tr('settingsTitle', { name: detail.name })}
subtitle={`${tr(running ? 'state_running' : 'state_stopped')} · ${tr('appliesNextStart')}`}
closeLabel={tr('close')}
dismissable={!busy}
onClose={onClose}
>
<div className="settings-split" onKeyDown={onKeyDown}>
<nav className="settings-nav" aria-label={tr('settings')}>
{CATS.map((c) => {
const n = changedIn(c.id)
const bad = issueIn(c.id)
const Icon = c.icon
return (
<button
key={c.id}
type="button"
className="nav-item"
aria-current={cat === c.id ? 'page' : undefined}
onClick={() => setCat(c.id)}
>
<span className={`nav-icon-badge nav-icon-cat-${c.id}`} aria-hidden="true"><Icon size={14} /></span>
<span className="nav-label">{tr(c.label)}</span>
{bad
? <CircleAlert size={14} className="nav-issue" aria-label={tr('navHasIssue')} />
: n > 0 && <span className="nav-count" aria-label={tr('pendingChanges', { n })}>{n}</span>}
</button>
)
})}
</nav>
<div className="settings-pane" ref={pane}>
<h2 className="settings-pane-title">{tr(CATS.find((c) => c.id === cat)!.label)}</h2>
{err && <div className="notice notice-error">{err}</div>}
{strayIssues.length > 0 && (
<div className="notice notice-error">
<ul>{strayIssues.map((i) => <li key={i.field + i.code}>{i.message}</li>)}</ul>
</div>
)}
<div key={cat} className="pane-anim">{pages[cat]}</div>
</div>
</div>
<div className="dialog-foot">
<span className="foot-status" aria-live="polite">
{changed.length > 0
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changed.length })}</>
: <span className="muted">{tr('noChanges')}</span>}
{changed.length > 0 && (
<button type="button" className="link-btn" disabled={busy} onClick={resetAll}>{tr('resetAll')}</button>
)}
</span>
<span className="hstack">
<Button variant="ghost" disabled={busy} onClick={onClose}>{tr('cancel')}</Button>
<Button variant="primary" busy={busy} disabled={changed.length === 0 || localBlock} onClick={handleSave} title="Ctrl+S">
{tr('save')}
</Button>
</span>
</div>
</Modal>
)
}