Merge pull request #163 from Nwflower/refactor/entropy-convergence
架构降熵:合并重复实现、拆分过大的文件、删除不再使用的代码,并用测试守护这些规则。
This commit is contained in:
312 files changed
+8188
-9026
No files matched your search
@@ -9,13 +9,13 @@ import { Modal } from '../ui/dialog'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { REPO_URL, siteURL } from './TitleMenus'
|
||||
import type { UpdatePhase } from './UpdateCapsule'
|
||||
import type { UpdatePhase } from '../lib/useAppUpdate'
|
||||
import { BrandMark } from '../ui/themeVisuals'
|
||||
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
|
||||
const QQ_GROUP_ID = '1136042744'
|
||||
|
||||
export type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
|
||||
type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
|
||||
@@ -100,7 +100,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
let live = true
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
api.GetVMAffinityWithDriver(driverID, vmName)
|
||||
api.GetVMAffinity(driverID, vmName)
|
||||
.then((st) => {
|
||||
if (!live) return
|
||||
setStatus(st)
|
||||
@@ -206,7 +206,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
setSaving(true)
|
||||
setErr('')
|
||||
try {
|
||||
const updated = await api.SetVMAffinityWithDriver(driverID, vmName, {
|
||||
const updated = await api.SetVMAffinity(driverID, vmName, {
|
||||
mode,
|
||||
cpus: mode === 'custom' ? selected : [],
|
||||
disable_eco_qos: disableEcoQoS,
|
||||
|
||||
@@ -10,13 +10,13 @@ import {
|
||||
splitFullscreenHotkey,
|
||||
} from '../lib/fullscreenHotkey'
|
||||
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import type { ThemeMode } from '../lib/useAppearance'
|
||||
import { AppState, Locale, ResolvedLocalePack, Task } from '../types'
|
||||
import { Button, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { PopupSelect, Segmented, Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||
|
||||
type HostDNSMode = 'system' | 'doh'
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import '../i18n/domains/wizard.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, locText, parseAppError, t } from '../i18n'
|
||||
import {
|
||||
GUEST_LANG_PRESETS,
|
||||
guestLangOptions,
|
||||
MEMORY_MARKS,
|
||||
controllerLabel,
|
||||
@@ -32,7 +31,6 @@ import {
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
shortGPUName,
|
||||
splitLangLabel,
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
|
||||
|
||||
@@ -13,7 +13,7 @@ export const hasGuestArt = (family: GuestFamily): boolean => ART_FAMILIES.includ
|
||||
* names. macOS keeps its version artwork (VersionArt), so this returns null
|
||||
* for it and for an unknown family and the caller falls back to that artwork.
|
||||
*/
|
||||
export const GuestIcon: React.FC<{ family: GuestFamily; size?: number }> = ({ family, size = 15 }) => {
|
||||
const GuestIcon: React.FC<{ family: GuestFamily; size?: number }> = ({ family, size = 15 }) => {
|
||||
switch (family) {
|
||||
case 'linux':
|
||||
return <HostIcon name="guest-linux"><Terminal size={size} aria-hidden="true" /></HostIcon>
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { Disc3, Puzzle, RefreshCw } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import { ImageSourceContribution, Locale, PluginUIContributions } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Segmented } from '../ui/settings'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { locText } from './SchemaForm'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
|
||||
export interface NativeImageSourceRenderOpts {
|
||||
interface NativeImageSourceRenderOpts {
|
||||
refreshSignal: number
|
||||
onBusyChange: (busy: boolean) => void
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from 'react'
|
||||
import { t } from '../i18n'
|
||||
import type { ParsedAppError } from '../i18n'
|
||||
import type { Locale } from '../types'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react'
|
||||
import { useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { parseAppError, t } from '../i18n'
|
||||
import type { ParsedAppError } from '../i18n'
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo, ScanReport } from '../types'
|
||||
import { Button, Tip } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api, events, MarketInstallProgress } from '../wails'
|
||||
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { locText } from './SchemaForm'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
|
||||
// Cards are revealed in pages as the feed scrolls into view.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
|
||||
import { getPluginMessageBundle, localeDir, locText, parseAppError, t } from '../i18n'
|
||||
import { Locale, PanelContribution, ViewContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { ConfirmDialog } from '../ui/dialog'
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from '../lib/pluginViewActions'
|
||||
import { buildSafePluginAssetURL } from '../lib/pluginAssets'
|
||||
import { subscribePluginHostEvents } from '../lib/pluginViewEvents'
|
||||
import { locText, SchemaForm } from './SchemaForm'
|
||||
import { SchemaForm } from './SchemaForm'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import React from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { locText, t } from '../i18n'
|
||||
import { Locale, ViewContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { locText } from './SchemaForm'
|
||||
|
||||
interface Props {
|
||||
view: ViewContribution
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import {
|
||||
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport, ViewContribution,
|
||||
} from '../types'
|
||||
@@ -16,7 +16,7 @@ import { api } from '../wails'
|
||||
import { PluginMarket } from './PluginMarket'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge } from './PluginParts'
|
||||
import { SchemaForm, locText } from './SchemaForm'
|
||||
import { SchemaForm } from './SchemaForm'
|
||||
|
||||
// Search only earns its space once the list is long enough to scan.
|
||||
const SEARCH_THRESHOLD = 12
|
||||
|
||||
@@ -5,8 +5,6 @@ import { locText, t } from '../i18n'
|
||||
import { Locale, SettingProperty, SettingsSchema } from '../types'
|
||||
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
|
||||
export { locText }
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
schema: SettingsSchema
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,14 +3,13 @@ import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2
|
||||
import React, { useRef } from 'react'
|
||||
import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { guestFamilyOf, vmFeatures } from '../lib/endpoints'
|
||||
import { Locale, VMListItem } from '../types'
|
||||
import { Locale, VMAction, VMBusyAction, VMListItem } from '../types'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { vmRefKey } from '../lib/vmRef'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
import { BrandMark, HostIcon } from '../ui/themeVisuals'
|
||||
import { GuestArt, hasGuestArt } from './GuestIcon'
|
||||
import type { VMAction, VMBusyAction } from './VMPage'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
export const INSTALLERS_ID = '__installers__'
|
||||
|
||||
@@ -5,11 +5,10 @@ import { I18nKey, localeDir, t } from '../i18n'
|
||||
import { hasVisibleDialog } from '../lib/dialogState'
|
||||
import { VMFeatures, vmFeatures } from '../lib/endpoints'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { Locale } from '../types'
|
||||
import { Locale, VMAction } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
import type { ThemeMode } from './AppSettingsPage'
|
||||
import type { ThemeMode } from '../lib/useAppearance'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID } from './Sidebar'
|
||||
import { VMAction } from './VMPage'
|
||||
|
||||
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { ArrowDownToLine, RotateCw, X } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import type { UpdatePhase } from '../lib/useAppUpdate'
|
||||
import { Locale, Task } from '../types'
|
||||
import { Tip } from '../ui/controls'
|
||||
|
||||
/** Where an available update is: offered, downloading, verified and ready, or failed. */
|
||||
export type UpdatePhase = 'none' | 'available' | 'downloading' | 'ready' | 'failed'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { parseAppError, t } from '../i18n'
|
||||
import type { I18nKey, ParsedAppError } from '../i18n'
|
||||
|
||||
+164
-1474
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,158 @@
|
||||
import { Activity, Copy, Disc, FolderOpen, Keyboard, Upload } from 'lucide-react'
|
||||
import React, { useId } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { Locale, PendingChange, VMAction, VMBusyAction, VMDetail, VMStats } from '../../types'
|
||||
import { Button, IconButton, Tip } from '../../ui/controls'
|
||||
import { Switch } from '../../ui/settings'
|
||||
import { HostDNSRows, useHostDNS } from './hostDNS'
|
||||
import { SSHRow, useSSHAccess } from './ssh'
|
||||
|
||||
const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
vmKey: string
|
||||
state: string
|
||||
detail: VMDetail
|
||||
stats: VMStats | null
|
||||
pending: PendingChange[]
|
||||
currentAgentVersion: number
|
||||
/** macOS is still being installed, so it has no Guest Tools yet. */
|
||||
installing: boolean
|
||||
guestToolsLocked: boolean
|
||||
canUseHostDNS: boolean
|
||||
ssh: ReturnType<typeof useSSHAccess>
|
||||
hostDNS: ReturnType<typeof useHostDNS>
|
||||
busyAction?: VMBusyAction
|
||||
onAction: (action: VMAction) => void
|
||||
onCopy: (text: string) => void
|
||||
onTypeText: (text: string) => void
|
||||
onTogglePreventSleep: (enabled: boolean) => void
|
||||
onDeliverFile: () => void
|
||||
}
|
||||
|
||||
/** How Windows and a macOS VM reach each other: SSH, Guest Tools, shared files and DNS. */
|
||||
export const ConnectionSection: React.FC<Props> = ({
|
||||
locale, vmKey, state, detail, stats, pending, currentAgentVersion, installing, guestToolsLocked, canUseHostDNS, ssh, hostDNS,
|
||||
busyAction, onAction, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
const running = state === 'running'
|
||||
const suspended = state === 'suspended'
|
||||
const guestToolsHintId = useId()
|
||||
const tools = !installing
|
||||
if (!tools && detail.ssh_port <= 0) return null
|
||||
const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
|
||||
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
|
||||
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
|
||||
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
|
||||
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < currentAgentVersion
|
||||
const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached')
|
||||
// Plugin switched off: show the state and hide controls that would only fail.
|
||||
const gtOff = !!detail.guest_tools_disabled
|
||||
const gtAttached = detail.guest_tools_attached
|
||||
const showToolsAction = !gtOff && (gtAttached || !gtConnected || needsUpgrade)
|
||||
const toolsAction = gtAttached ? 'detachGuestTools' : 'attachGuestTools'
|
||||
const toolsActionLabel = gtAttached ? 'detachGuestTools' : needsUpgrade ? 'gtUpdate' : 'gtInstall'
|
||||
|
||||
// One status word per state; how files are shared goes in the tooltip.
|
||||
let gtTone: 'ok' | 'warn' | 'idle' = 'idle'
|
||||
let gtStatus: string
|
||||
let gtTip: string
|
||||
if (gtOff) {
|
||||
gtStatus = tr('gtStatusOff'); gtTip = tr('gtStatusOffTip')
|
||||
} else if (needsUpgrade) {
|
||||
gtTone = 'warn'; gtStatus = tr('gtStatusUpgrade'); gtTip = tr('guestToolsUpgradeHint')
|
||||
} else if (gtConnected) {
|
||||
gtTone = 'ok'; gtStatus = tr('gtStatusConnected')
|
||||
gtTip = gtMountMode === 'webdav' ? tr('guestToolsModeWebDAV') : gtMountMode === 'sync' ? tr('guestToolsModeSync') : tr('gtStatusConnected')
|
||||
} else if (detail.guest_tools_configured) {
|
||||
gtStatus = running ? tr('gtStatusWaiting') : tr('gtStatusEnabled')
|
||||
gtTip = tr('gtStatusWaitingTip')
|
||||
} else {
|
||||
gtStatus = tr('gtStatusNone'); gtTip = tr('gtNotInstalledDesc')
|
||||
}
|
||||
const showInstallCmd = !gtOff && detail.guest_tools_attached && !gtAttachPending && (!gtConnected || needsUpgrade)
|
||||
|
||||
return (
|
||||
<section className="section" aria-labelledby="conn-title">
|
||||
<h2 className="section-title" id="conn-title">{tr('connGroup')}</h2>
|
||||
<div className="conn-list">
|
||||
{detail.ssh_port > 0 && <SSHRow locale={locale} vmKey={vmKey} port={detail.ssh_port} state={ssh} onCopy={onCopy} />}
|
||||
{tools && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsTitle')}</span>
|
||||
<Tip label={gtTip}>
|
||||
<span className={`conn-status is-${gtTone}`} tabIndex={0}>
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{gtStatus}
|
||||
</span>
|
||||
</Tip>
|
||||
</div>
|
||||
{suspended && showToolsAction && (
|
||||
<span id={guestToolsHintId} className="hint">{tr('suspendedGuestToolsHint')}</span>
|
||||
)}
|
||||
<div className="conn-ctrl">
|
||||
{showToolsAction && (
|
||||
<Button
|
||||
variant={gtAttached || detail.guest_tools_configured || guestToolsLocked ? 'secondary' : 'primary'}
|
||||
icon={gtAttached ? undefined : <Disc size={13} aria-hidden="true" />}
|
||||
busy={busyAction === toolsAction}
|
||||
disabled={busy || guestToolsLocked}
|
||||
aria-describedby={suspended ? guestToolsHintId : undefined}
|
||||
onClick={() => onAction(toolsAction)}
|
||||
>
|
||||
{tr(toolsActionLabel)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && showInstallCmd && (
|
||||
<div className="conn-row conn-sub">
|
||||
<div className="conn-main">
|
||||
<span className="conn-meta">{tr('gtInstallSub')}</span>
|
||||
</div>
|
||||
<div className="conn-ctrl conn-ctrl-grow">
|
||||
<div className="ssh-pill">
|
||||
<code title={GUEST_TOOLS_INSTALL_CMD}>{GUEST_TOOLS_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(GUEST_TOOLS_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(GUEST_TOOLS_INSTALL_CMD)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && !gtOff && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('sharedFolder')}</span>
|
||||
<span className="conn-meta mono" title="~/Desktop/ReimsShare">~/Desktop/ReimsShare</span>
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Button icon={<Upload size={13} aria-hidden="true" />} disabled={busy} onClick={onDeliverFile}>{tr('deliverFileShort')}</Button>
|
||||
<Button icon={<FolderOpen size={13} aria-hidden="true" />} disabled={busy} onClick={() => onAction('openSharedFolder')}>{tr('openShort')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tools && !gtOff && (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsPreventSleep')}</span>
|
||||
{gtSleepActive && (
|
||||
<span className="conn-meta ok-text"><Activity size={12} aria-hidden="true" /> {tr('guestToolsSleepActive')}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Switch label={tr('guestToolsPreventSleep')} checked={!!detail.guest_tools_prevent_sleep} onChange={onTogglePreventSleep} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{canUseHostDNS && <HostDNSRows locale={locale} detail={detail} running={running} busyAction={busyAction} state={hostDNS} onCopy={onCopy} onTypeText={onTypeText} />}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { Code2, Copy, MonitorPlay, Pencil, Terminal } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { EndpointAction, endpointActions, endpointKey, orderEndpoints, secondaryEndpointActions } from '../../lib/endpoints'
|
||||
import { Locale, VMEndpoint } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { Button } from '../../ui/controls'
|
||||
import { HostIcon } from '../../ui/themeVisuals'
|
||||
|
||||
/** The built-in icon of an endpoint kind; each is themeable by name. */
|
||||
export function endpointIcon(kind: string, size: number): React.ReactNode {
|
||||
return kind === 'vmconnect' || kind === 'rdp'
|
||||
? <HostIcon name="remote-desktop"><MonitorPlay size={size} aria-hidden="true" /></HostIcon>
|
||||
: <HostIcon name="terminal"><Terminal size={size} aria-hidden="true" /></HostIcon>
|
||||
}
|
||||
|
||||
/** A short, user-facing description of where an endpoint points. */
|
||||
function endpointDetail(ep: VMEndpoint): string {
|
||||
switch (ep.kind) {
|
||||
case 'ssh': return `${ep.user ? `${ep.user}@` : ''}${ep.host || '127.0.0.1'}${ep.port ? `:${ep.port}` : ''}`
|
||||
case 'wsl': return ep.distro ?? ''
|
||||
case 'rdp': return `${ep.host ?? ''}${ep.port ? `:${ep.port}` : ''}`
|
||||
case 'vmconnect': return ep.vm ?? ''
|
||||
case 'adb': return ep.serial ?? ''
|
||||
default: return ''
|
||||
}
|
||||
}
|
||||
|
||||
interface Options {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
name: string
|
||||
onCopy: (text: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** Runs the actions of a VM's endpoints, one at a time per endpoint. */
|
||||
export function useEndpointActions({ locale, driverID, name, onCopy, onError }: Options) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [endpointBusy, setEndpointBusy] = useState('')
|
||||
useEffect(() => { setEndpointBusy('') }, [driverID, name])
|
||||
|
||||
const runEndpointAction = (ep: VMEndpoint, action: EndpointAction | '') => {
|
||||
const busyKey = `${endpointKey(ep)}:${action}`
|
||||
setEndpointBusy(busyKey)
|
||||
const done = () => setEndpointBusy((cur) => (cur === busyKey ? '' : cur))
|
||||
if (action === 'copy') {
|
||||
api.GetVMEndpointCommand(driverID, name, ep.kind)
|
||||
.then((cmd) => onCopy(cmd))
|
||||
.catch((e) => onError(tr('failEndpointCommand'), e))
|
||||
.finally(done)
|
||||
return
|
||||
}
|
||||
api.OpenVMEndpoint(driverID, name, ep.kind, action)
|
||||
.catch((e) => onError(tr('failEndpointOpen'), e))
|
||||
.finally(done)
|
||||
}
|
||||
const endpointActionLabel = (kind: string, action: EndpointAction): string => {
|
||||
switch (action) {
|
||||
case 'terminal': return tr('endpointOpenTerminal')
|
||||
case 'vscode': return tr('endpointOpenVSCode')
|
||||
case 'config': return tr('sshWriteConfig')
|
||||
case 'edit': return tr('endpointEditConnection')
|
||||
case 'shell': return tr('endpointOpenADBShell')
|
||||
case 'copy': return tr('endpointCopyADB')
|
||||
case 'open': return tr(kind === 'vmconnect' ? 'endpointOpenVMConnect' : 'endpointOpenRDP')
|
||||
}
|
||||
}
|
||||
const endpointKindLabel = (kind: string): string => {
|
||||
switch (kind) {
|
||||
case 'ssh': return tr('endpointKindSSH')
|
||||
case 'wsl': return tr('endpointKindWSL')
|
||||
case 'rdp': return tr('endpointKindRDP')
|
||||
case 'vmconnect': return tr('endpointKindVMConnect')
|
||||
case 'adb': return tr('endpointKindADB')
|
||||
default: return kind
|
||||
}
|
||||
}
|
||||
|
||||
return { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel }
|
||||
}
|
||||
|
||||
interface SectionProps {
|
||||
locale: Locale
|
||||
endpoints: VMEndpoint[] | undefined
|
||||
/** The endpoint already offered as the page's primary action. */
|
||||
promotedEndpoint: VMEndpoint | undefined
|
||||
state: ReturnType<typeof useEndpointActions>
|
||||
}
|
||||
|
||||
export const EndpointSection: React.FC<SectionProps> = ({ locale, endpoints, promotedEndpoint, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel } = state
|
||||
// One flat list. The endpoint promoted to the header keeps only its secondary actions here, so the
|
||||
// primary action is never offered twice; every other endpoint lists all of its actions.
|
||||
const rows = orderEndpoints(endpoints).flatMap((ep) => {
|
||||
const promoted = promotedEndpoint === ep || (!!promotedEndpoint && endpointKey(promotedEndpoint) === endpointKey(ep))
|
||||
const actions = promoted ? secondaryEndpointActions(ep.kind) : endpointActions(ep.kind)
|
||||
return promoted && actions.length === 0 ? [] : [{ ep, actions }]
|
||||
})
|
||||
if (rows.length === 0) return null
|
||||
return (
|
||||
<section className="section" aria-labelledby="endpoints-title">
|
||||
<h2 className="section-title" id="endpoints-title">{tr('endpointsTitle')}</h2>
|
||||
<div className="conn-list">
|
||||
{rows.map(({ ep, actions }) => (
|
||||
<div className="conn-row" key={endpointKey(ep)}>
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{endpointKindLabel(ep.kind)}</span>
|
||||
<span className="conn-meta mono" title={endpointDetail(ep)}>{endpointDetail(ep)}</span>
|
||||
{!ep.ready && (
|
||||
<span className="conn-status">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('endpointNotReady')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{ep.ready && actions.length > 0 && (
|
||||
<div className="conn-ctrl">
|
||||
{actions.map((action) => (
|
||||
<Button
|
||||
key={action}
|
||||
icon={action === 'vscode' ? <Code2 size={13} aria-hidden="true" /> : action === 'copy' ? <Copy size={13} aria-hidden="true" /> : action === 'edit' || action === 'config' ? <Pencil size={13} aria-hidden="true" /> : endpointIcon(ep.kind, 13)}
|
||||
busy={endpointBusy === `${endpointKey(ep)}:${action}`}
|
||||
onClick={() => runEndpointAction(ep, action)}
|
||||
>
|
||||
{endpointActionLabel(ep.kind, action)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import { Copy, Keyboard } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { Locale, VMBusyAction, VMDetail } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { IconButton } from '../../ui/controls'
|
||||
import { Switch } from '../../ui/settings'
|
||||
|
||||
const HOST_DNS_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Host-DNS.command'
|
||||
const HOST_DNS_DISABLE_CMD = 'sh /Volumes/REIMSTOOLS/Disable-Host-DNS.command'
|
||||
|
||||
interface Options {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
name: string
|
||||
state: string
|
||||
detail: VMDetail | null
|
||||
/** Whether the VM can use the host's DNS at all. */
|
||||
available: boolean
|
||||
/** Guest Tools settings cannot change in the VM's current state. */
|
||||
locked: boolean
|
||||
onToast: (title: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** Per-VM host DNS proxy state (host_dns_flow.go). */
|
||||
export function useHostDNS({ locale, driverID, name, state, detail, available, locked, onToast, onError }: Options) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const running = state === 'running'
|
||||
const [hostDNS, setHostDNS] = useState<{
|
||||
host_dns_enabled: boolean
|
||||
host_dns_active: boolean
|
||||
host_dns_config_stale: boolean
|
||||
host_dns_reported: boolean
|
||||
} | null>(null)
|
||||
const [hostDNSLoadErr, setHostDNSLoadErr] = useState('')
|
||||
const [hostDNSBusy, setHostDNSBusy] = useState(false)
|
||||
const hostDNSWriteSeq = useRef(0)
|
||||
useEffect(() => {
|
||||
hostDNSWriteSeq.current += 1
|
||||
setHostDNS(null)
|
||||
setHostDNSLoadErr('')
|
||||
setHostDNSBusy(false)
|
||||
}, [driverID, name])
|
||||
useEffect(() => {
|
||||
if (!available) {
|
||||
setHostDNS(null)
|
||||
setHostDNSLoadErr('')
|
||||
return
|
||||
}
|
||||
let live = true
|
||||
const pull = (force = false) => {
|
||||
if (!force && document.hidden) return
|
||||
const seq = hostDNSWriteSeq.current
|
||||
api.GetGuestToolsHostDNS(name)
|
||||
.then((s) => {
|
||||
if (live && seq === hostDNSWriteSeq.current) {
|
||||
setHostDNS(s)
|
||||
setHostDNSLoadErr('')
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
console.warn('[vm] GetGuestToolsHostDNS failed:', e)
|
||||
if (live && seq === hostDNSWriteSeq.current) {
|
||||
setHostDNSLoadErr(parseAppError(e).summary)
|
||||
}
|
||||
})
|
||||
}
|
||||
pull(true)
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) pull(true)
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisible)
|
||||
const timer = running ? window.setInterval(() => pull(false), 5000) : undefined
|
||||
return () => {
|
||||
live = false
|
||||
document.removeEventListener('visibilitychange', onVisible)
|
||||
if (timer) window.clearInterval(timer)
|
||||
}
|
||||
}, [driverID, name, available, running, state, detail?.guest_tools_connected, detail?.guest_tools_attached])
|
||||
|
||||
const handleToggleHostDNS = async (enabled: boolean) => {
|
||||
if (hostDNSBusy || locked || !available || hostDNS === null) return
|
||||
const writeSeq = ++hostDNSWriteSeq.current
|
||||
setHostDNSBusy(true)
|
||||
try {
|
||||
await api.SetGuestToolsHostDNS(name, enabled)
|
||||
onToast(tr(enabled ? 'toastHostDNSOn' : 'toastHostDNSOff'))
|
||||
try {
|
||||
const next = await api.GetGuestToolsHostDNS(name)
|
||||
if (writeSeq === hostDNSWriteSeq.current) {
|
||||
setHostDNS(next)
|
||||
setHostDNSLoadErr('')
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[vm] GetGuestToolsHostDNS after toggle failed:', e)
|
||||
if (writeSeq === hostDNSWriteSeq.current) {
|
||||
setHostDNS((prev) => ({
|
||||
host_dns_enabled: enabled,
|
||||
host_dns_active: prev?.host_dns_active ?? false,
|
||||
host_dns_config_stale: prev?.host_dns_config_stale ?? false,
|
||||
host_dns_reported: prev?.host_dns_reported ?? false,
|
||||
}))
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
onError(tr('failGuestTools'), e)
|
||||
} finally {
|
||||
if (writeSeq === hostDNSWriteSeq.current) setHostDNSBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return { hostDNS, hostDNSLoadErr, hostDNSBusy, handleToggleHostDNS, locked }
|
||||
}
|
||||
|
||||
interface RowsProps {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
running: boolean
|
||||
busyAction?: VMBusyAction
|
||||
state: ReturnType<typeof useHostDNS>
|
||||
onCopy: (text: string) => void
|
||||
onTypeText: (text: string) => void
|
||||
}
|
||||
|
||||
export const HostDNSRows: React.FC<RowsProps> = ({ locale, detail, running, busyAction, state, onCopy, onTypeText }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { hostDNS, hostDNSLoadErr, hostDNSBusy, handleToggleHostDNS, locked } = state
|
||||
const busy = busyAction !== undefined
|
||||
const dnsEnabled = hostDNS?.host_dns_enabled ?? false
|
||||
const dnsActive = hostDNS?.host_dns_active ?? false
|
||||
const dnsStale = hostDNS?.host_dns_config_stale ?? false
|
||||
const dnsReported = hostDNS?.host_dns_reported ?? false
|
||||
const toolsAttached = !!detail.guest_tools_attached
|
||||
const disableCmd = toolsAttached
|
||||
? HOST_DNS_DISABLE_CMD
|
||||
: 'sh /private/etc/reims-host-dns/Disable-Host-DNS.command'
|
||||
const showApplySub = dnsEnabled && (dnsStale || !dnsActive)
|
||||
const showDisableSub = dnsActive || dnsStale || (dnsEnabled && running && !dnsReported)
|
||||
|
||||
let dnsStatus: React.ReactNode
|
||||
if (hostDNSLoadErr && hostDNS === null) {
|
||||
dnsStatus = <span className="conn-meta danger-text">{hostDNSLoadErr}</span>
|
||||
} else if (dnsEnabled && dnsReported && dnsStale) {
|
||||
dnsStatus = (
|
||||
<span className="conn-status is-warn">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('hostDNSStatusStale')}
|
||||
</span>
|
||||
)
|
||||
} else if (dnsEnabled && dnsReported && dnsActive) {
|
||||
dnsStatus = (
|
||||
<span className="conn-status is-ok">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('hostDNSStatusActive')}
|
||||
</span>
|
||||
)
|
||||
} else if (dnsEnabled) {
|
||||
dnsStatus = (
|
||||
<span className="conn-status">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('hostDNSStatusPending')}
|
||||
</span>
|
||||
)
|
||||
} else if (dnsReported && (dnsActive || dnsStale)) {
|
||||
dnsStatus = (
|
||||
<span className="conn-status is-warn">
|
||||
<span className="conn-status-dot" aria-hidden="true" />
|
||||
{tr('hostDNSStatusStillActive')}
|
||||
</span>
|
||||
)
|
||||
} else {
|
||||
dnsStatus = (
|
||||
<span className="conn-meta" title={tr('hostDNSOffHint')}>
|
||||
{tr('hostDNSOffHint')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{tr('guestToolsHostDNS')}</span>
|
||||
{dnsStatus}
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Switch
|
||||
label={tr('guestToolsHostDNS')}
|
||||
checked={dnsEnabled}
|
||||
disabled={busy || locked || hostDNSBusy || hostDNS === null || (dnsEnabled && (dnsActive || dnsStale))}
|
||||
onChange={(checked) => void handleToggleHostDNS(checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{showApplySub && (
|
||||
<div className="conn-row conn-sub">
|
||||
<div className="conn-main">
|
||||
<span className="conn-meta">
|
||||
{tr(!toolsAttached ? 'hostDNSAttachHint' : dnsStale ? 'hostDNSStaleHint' : 'hostDNSApplyHint')}
|
||||
</span>
|
||||
</div>
|
||||
{toolsAttached && (
|
||||
<div className="conn-ctrl conn-ctrl-grow">
|
||||
<div className="ssh-pill">
|
||||
<code title={HOST_DNS_APPLY_CMD}>{HOST_DNS_APPLY_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(HOST_DNS_APPLY_CMD)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(HOST_DNS_APPLY_CMD)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{showDisableSub && (
|
||||
<div className="conn-row conn-sub">
|
||||
<div className="conn-main">
|
||||
<span className="conn-meta">{tr('hostDNSDisableCmdHint')}</span>
|
||||
</div>
|
||||
<div className="conn-ctrl conn-ctrl-grow">
|
||||
<div className="ssh-pill">
|
||||
<code title={disableCmd}>{disableCmd}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(disableCmd)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(disableCmd)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { Check, Copy, Disc, Keyboard } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { Locale, VMAction, VMBusyAction, VMDetail } from '../../types'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
|
||||
// Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing
|
||||
// macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`.
|
||||
const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
name: string
|
||||
detail: VMDetail
|
||||
running: boolean
|
||||
/** Whether the VM window shows the install guide, so the card only says how to start. */
|
||||
installGuideEnabled: boolean
|
||||
busyAction?: VMBusyAction
|
||||
onAction: (action: VMAction) => void
|
||||
onCopy: (text: string) => void
|
||||
onTypeText: (text: string) => void
|
||||
}
|
||||
|
||||
/** How to finish installing macOS. Its step checkboxes are kept per VM in localStorage. */
|
||||
export const InstallCard: React.FC<Props> = ({ locale, name, detail, running, installGuideEnabled, busyAction, onAction, onCopy, onTypeText }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
const guideKey = `reims-go-guide:${name}`
|
||||
const [doneSteps, setDoneSteps] = useState<number[]>(() => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(guideKey) ?? '[]')
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
})
|
||||
const toggleGuideStep = (step: number) => {
|
||||
setDoneSteps((prev) => {
|
||||
const next = prev.includes(step) ? prev.filter((x) => x !== step) : [...prev, step]
|
||||
try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch (e) { console.warn('[vm] persist guide progress failed:', e) }
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const hasInstaller = detail.has_installer
|
||||
const isOffline = hasInstaller && /offline-installer/i.test(detail.installer_path ?? '')
|
||||
const badgeKey: I18nKey = !hasInstaller
|
||||
? 'guideKindBuiltIn'
|
||||
: isOffline
|
||||
? 'guideKindOffline'
|
||||
: 'guideKindOnline'
|
||||
if (installGuideEnabled) {
|
||||
return (
|
||||
<section className="card rg-p-card" aria-labelledby="guide-title">
|
||||
<h2 className="card-title" id="guide-title">
|
||||
{tr('guideTitle')}{' '}
|
||||
<span className="badge rg-p-badge">{tr(badgeKey)}</span>
|
||||
</h2>
|
||||
<p className="card-desc">{tr('guideStartHint')}</p>
|
||||
<div className="card-foot">
|
||||
{!hasInstaller && (
|
||||
<Button
|
||||
icon={<Disc size={14} aria-hidden="true" />}
|
||||
busy={busyAction === 'attachInstaller'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('attachInstaller')}
|
||||
>
|
||||
{tr('attachInstaller')}
|
||||
</Button>
|
||||
)}
|
||||
<Button busy={busyAction === 'finishInstall'} disabled={busy} onClick={() => onAction('finishInstall')}>
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
const finish = (
|
||||
<Button
|
||||
variant={running ? 'primary' : 'secondary'}
|
||||
busy={busyAction === 'finishInstall'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('finishInstall')}
|
||||
>
|
||||
{tr('finishInstall')}
|
||||
</Button>
|
||||
)
|
||||
// Each step's number is a checkbox the user ticks off (kept per VM).
|
||||
const step = (n: number, body: React.ReactNode) => {
|
||||
const done = doneSteps.includes(n)
|
||||
return (
|
||||
<li className={`guide-step${done ? ' is-done' : ''}`}>
|
||||
<button
|
||||
type="button"
|
||||
className={`guide-step-btn${done ? ' done' : ''}`}
|
||||
aria-pressed={done}
|
||||
onClick={() => toggleGuideStep(n)}
|
||||
>
|
||||
{done ? <Check size={12} aria-hidden="true" /> : n}
|
||||
</button>
|
||||
<span className="guide-step-body">{body}</span>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section className="card rg-p-card" aria-labelledby="guide-title">
|
||||
<h2 className="card-title" id="guide-title">
|
||||
{tr('guideTitle')}{' '}
|
||||
<span className={`badge rg-p-badge ${isOffline ? 'badge-ok' : ''}`}>{tr(badgeKey)}</span>
|
||||
</h2>
|
||||
{!hasInstaller ? (
|
||||
<>
|
||||
<ol className="guide-steps">
|
||||
{step(1, tr('guideBuiltIn1'))}
|
||||
{step(2, tr('guideBuiltIn2'))}
|
||||
{step(3, tr('guideBuiltIn3'))}
|
||||
</ol>
|
||||
<div className="card-foot">
|
||||
<Button
|
||||
icon={<Disc size={14} aria-hidden="true" />}
|
||||
busy={busyAction === 'attachInstaller'}
|
||||
disabled={busy}
|
||||
onClick={() => onAction('attachInstaller')}
|
||||
>
|
||||
{tr('attachInstaller')}
|
||||
</Button>
|
||||
{finish}
|
||||
</div>
|
||||
</>
|
||||
) : isOffline ? (
|
||||
<>
|
||||
<ol className="guide-steps">
|
||||
{step(1, tr('guideOffline1'))}
|
||||
{step(2, (
|
||||
<>
|
||||
{tr('guideOffline2')}
|
||||
<div className="cmd-line guide-cmd">
|
||||
<code>{OFFLINE_INSTALL_CMD}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(OFFLINE_INSTALL_CMD)} />
|
||||
{running && (
|
||||
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={14} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(OFFLINE_INSTALL_CMD)} />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
))}
|
||||
{step(3, tr('guideOffline3'))}
|
||||
</ol>
|
||||
<div className="card-foot">{finish}</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ol className="guide-steps">
|
||||
{step(1, tr('guideStep1'))}
|
||||
{step(2, tr('guideStep2'))}
|
||||
{step(3, tr('guideStep3'))}
|
||||
</ol>
|
||||
<div className="card-foot">{finish}</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { AlertTriangle, Info, Pause } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { formatBytes, formatMemory, formatShortTime, pendingChangeText } from '../../lib/format'
|
||||
import { HostReport, Locale, PendingChange, VMAction, VMBusyAction, VMDetail, VMStats } from '../../types'
|
||||
import { Button } from '../../ui/controls'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
state: string
|
||||
canSuspend: boolean
|
||||
/** Id the disabled Resume button is described by. */
|
||||
resumeHintId: string
|
||||
detail: VMDetail | null
|
||||
stats: VMStats | null
|
||||
host: HostReport
|
||||
pending: PendingChange[]
|
||||
busyAction?: VMBusyAction
|
||||
onAction: (action: VMAction) => void
|
||||
}
|
||||
|
||||
/** What needs attention on the VM or its host. */
|
||||
export const VMNotices: React.FC<Props> = ({ locale, state, canSuspend, resumeHintId, detail, stats, host, pending, busyAction, onAction }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
const running = state === 'running'
|
||||
const suspended = state === 'suspended'
|
||||
return (
|
||||
<>
|
||||
{state === 'broken' && (
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('brokenHint')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{suspended && (() => {
|
||||
const suspTime = formatShortTime(Date.parse(detail?.suspend_info?.created_at ?? ''), locale)
|
||||
const suspSize = detail?.suspend_info?.vmstate_size
|
||||
? formatBytes(detail.suspend_info.vmstate_size, locale)
|
||||
: (detail?.memory ? formatMemory(detail.memory, locale) : '—')
|
||||
return (
|
||||
<div className="notice notice-info">
|
||||
<span className="notice-main">
|
||||
<Pause size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span className="notice-text">
|
||||
<span className="notice-title">{tr('suspendedNoticeTitle')}</span>
|
||||
<span className="notice-sub">
|
||||
{suspTime
|
||||
? tr('suspendedNoticeDescWithTime', { time: suspTime, size: suspSize })
|
||||
: tr('suspendedNoticeDesc', { size: suspSize })}
|
||||
</span>
|
||||
{!canSuspend && <span id={resumeHintId} className="notice-sub">{tr('resumeUnavailable')}</span>}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
|
||||
{pending.length > 0 && (
|
||||
<div className="notice notice-info">
|
||||
<span className="notice-main">
|
||||
<Info size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span className="notice-text">
|
||||
<span className="notice-title">{running ? tr('pendingRestartHint') : tr('pendingTitle')}</span>
|
||||
<span className="notice-sub">{pending.map((p) => pendingChangeText(locale, p, host)).join(' · ')}</span>
|
||||
</span>
|
||||
</span>
|
||||
{running && (
|
||||
<Button busy={busyAction === 'restart'} disabled={busy} onClick={() => onAction('restart')}>
|
||||
{tr('restartToApply')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(host.data_root_drive_type === 'usb' || host.data_root_drive_type === 'removable' || host.data_root_drive_type === 'network') && (
|
||||
<div className="notice">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagExternalDriveWarn', { dir: host.data_root })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stats && (stats.disk_backing_depth_warn || (stats.disk_backing_depth ?? 0) >= 2 || stats.disk_backing_broken) && (
|
||||
<div className="notice">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>
|
||||
{stats.disk_backing_broken
|
||||
? tr('diagBackingChainBroken', { depth: stats.disk_backing_depth ?? 1 })
|
||||
: tr('diagBackingChainWarn', { depth: stats.disk_backing_depth ?? 2 })}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(host.memory_load_pct ?? 0) >= 85 && (
|
||||
<div className="notice">
|
||||
<span className="notice-main">
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detail && !detail.has_installer && detail.disk_controller === 'ahci' && (
|
||||
<div className="notice notice-info">
|
||||
<span className="notice-main">
|
||||
<Info size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('diagAhciUpgradeHint')}</span>
|
||||
</span>
|
||||
<Button busy={busyAction === 'upgradeNVMe'} disabled={busy} onClick={() => onAction('upgradeNVMe')}>
|
||||
{tr('upgradeToNVMe')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { AppWindow, Camera, Play } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { VMThumbnail } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { Tip } from '../../ui/controls'
|
||||
|
||||
/**
|
||||
* Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
|
||||
* runs, otherwise the last frame saved. Skipped while this window is hidden;
|
||||
* the backend also skips it while the VM's own window is in front.
|
||||
*/
|
||||
export function useVMThumbnail(driverID: string, name: string, running: boolean, thumbnails: boolean): VMThumbnail | null {
|
||||
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
|
||||
useEffect(() => { setThumb(null) }, [driverID, name])
|
||||
useEffect(() => {
|
||||
if (!thumbnails) return
|
||||
let live = true
|
||||
const pull = () => {
|
||||
if (document.hidden) return
|
||||
api.GetVMThumbnail(driverID, name)
|
||||
.then((t) => { if (live && t?.data_url) setThumb(t) })
|
||||
.catch((e) => console.warn('[vm] GetVMThumbnail failed:', e))
|
||||
}
|
||||
pull()
|
||||
const timer = running ? window.setInterval(pull, 15000) : undefined
|
||||
return () => { live = false; if (timer) window.clearInterval(timer) }
|
||||
}, [driverID, name, running, thumbnails])
|
||||
return thumb
|
||||
}
|
||||
|
||||
/**
|
||||
* The VM's own screen as its picture (as UTM and Parallels do): live while it
|
||||
* runs (click to bring its window forward; a camera button copies a
|
||||
* screenshot), the last frame dimmed while it is stopped (hover shows a start
|
||||
* button), and its macOS version artwork until a frame exists. Each new frame
|
||||
* fades in over the previous one.
|
||||
*/
|
||||
export const VMScreen: React.FC<{
|
||||
thumb: VMThumbnail | null
|
||||
art: React.ReactNode
|
||||
running: boolean
|
||||
startLabel: string
|
||||
showLabel: string
|
||||
shotLabel: string
|
||||
onStart?: () => void
|
||||
onShow?: () => void
|
||||
onScreenshot?: () => void
|
||||
}> = ({ thumb, art, running, startLabel, showLabel, shotLabel, onStart, onShow, onScreenshot }) => {
|
||||
const prev = useRef<string>('')
|
||||
const shown = thumb?.data_url ?? ''
|
||||
const under = prev.current !== shown ? prev.current : ''
|
||||
useEffect(() => { prev.current = shown }, [shown])
|
||||
|
||||
// The page's own buttons are the keyboard path; the screen is a pointer shortcut.
|
||||
const act = onShow ?? onStart
|
||||
const overlay = onShow ? (
|
||||
<span className="vm-screen-chip" aria-hidden="true"><AppWindow size={13} /> {showLabel}</span>
|
||||
) : onStart ? (
|
||||
<span className="vm-screen-play" aria-hidden="true"><Play size={18} fill="currentColor" /></span>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`vm-display-unit${act ? ' is-actionable' : ''}`}
|
||||
onClick={act}
|
||||
title={onShow ? showLabel : onStart ? startLabel : undefined}
|
||||
>
|
||||
<div
|
||||
className={`vm-screen${running ? ' is-live' : ' is-idle'}`}
|
||||
style={shown && under ? { backgroundImage: `url(${under})` } : undefined}
|
||||
>
|
||||
{shown ? <img key={thumb?.captured_at} className="vm-screen-img" src={shown} alt="" draggable={false} /> : art}
|
||||
{running && <span className="vm-screen-live" aria-hidden="true" />}
|
||||
{running && shown && onScreenshot && (
|
||||
<Tip label={shotLabel} side="left">
|
||||
<button
|
||||
type="button"
|
||||
className="vm-screen-shot"
|
||||
aria-label={shotLabel}
|
||||
onClick={(e) => { e.stopPropagation(); onScreenshot() }}
|
||||
>
|
||||
<Camera size={14} aria-hidden="true" />
|
||||
</button>
|
||||
</Tip>
|
||||
)}
|
||||
{overlay}
|
||||
</div>
|
||||
<div className="vm-display-stand" aria-hidden="true" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import { History, Plus, RotateCcw, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { formatShortTime } from '../../lib/format'
|
||||
import { DiskSnapshot, Locale } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { Button, IconButton, Tip } from '../../ui/controls'
|
||||
import { HostIcon } from '../../ui/themeVisuals'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
name: string
|
||||
state: string
|
||||
/** False while the VM has no restore points to manage. */
|
||||
shown: boolean
|
||||
/** Restore points only change while the VM is stopped. */
|
||||
locked: boolean
|
||||
onToast: (title: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** The VM's offline restore points (snapshot_flow.go). */
|
||||
export const SnapshotSection: React.FC<Props> = ({ locale, driverID, name, state, shown, locked, onToast, onError }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [snapshots, setSnapshots] = useState<DiskSnapshot[]>([])
|
||||
const [creatingSnap, setCreatingSnap] = useState(false)
|
||||
const [snapDraft, setSnapDraft] = useState('')
|
||||
const [snapBusy, setSnapBusy] = useState('')
|
||||
const [restoreTarget, setRestoreTarget] = useState<string | null>(null)
|
||||
|
||||
const loadSnapshots = () => {
|
||||
if (!shown) { setSnapshots([]); return }
|
||||
api.ListSnapshots(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
|
||||
}
|
||||
useEffect(() => {
|
||||
setCreatingSnap(false)
|
||||
setSnapDraft('')
|
||||
setRestoreTarget(null)
|
||||
loadSnapshots()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [driverID, name, shown, state])
|
||||
|
||||
const handleCreateSnapshot = async () => {
|
||||
const label = snapDraft.trim()
|
||||
if (!label) return
|
||||
setSnapBusy('create')
|
||||
try {
|
||||
await api.CreateSnapshot(driverID, name, label)
|
||||
setSnapDraft('')
|
||||
setCreatingSnap(false)
|
||||
onToast(tr('toastSnapshotCreated', { name: label }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
const handleRestoreSnapshot = async (snapName: string) => {
|
||||
setRestoreTarget(null)
|
||||
setSnapBusy(`restore:${snapName}`)
|
||||
try {
|
||||
await api.RestoreSnapshot(driverID, name, snapName)
|
||||
onToast(tr('toastSnapshotRestored', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
const handleDeleteSnapshot = async (snapName: string) => {
|
||||
setSnapBusy(`delete:${snapName}`)
|
||||
try {
|
||||
await api.DeleteSnapshot(driverID, name, snapName)
|
||||
onToast(tr('toastSnapshotDeleted', { name: snapName }))
|
||||
loadSnapshots()
|
||||
} catch (e) {
|
||||
onError(tr('failSnapshot'), e)
|
||||
} finally {
|
||||
setSnapBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
if (!shown) return null
|
||||
return (
|
||||
<>
|
||||
<section className="section">
|
||||
<div className="section-title">
|
||||
<span className="hstack">
|
||||
<HostIcon name="snapshot"><History size={14} aria-hidden="true" /></HostIcon>
|
||||
<span>{tr('snapshotsTitle')}</span>
|
||||
<span className="snap-meta-hint">· {tr('snapshotHint')}</span>
|
||||
</span>
|
||||
<Tip label={locked ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
|
||||
<span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<Plus size={13} aria-hidden="true" />}
|
||||
disabled={locked || !!snapBusy}
|
||||
onClick={() => setCreatingSnap((v) => !v)}
|
||||
>
|
||||
{tr('snapshotCreate')}
|
||||
</Button>
|
||||
</span>
|
||||
</Tip>
|
||||
</div>
|
||||
<div className="conn-list">
|
||||
{creatingSnap && (
|
||||
<div className="snap-create-bar">
|
||||
<input
|
||||
className="input rg-p-input"
|
||||
value={snapDraft}
|
||||
maxLength={64}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={tr('snapshotNamePlaceholder')}
|
||||
autoFocus
|
||||
onChange={(e) => setSnapDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && snapDraft.trim()) { e.preventDefault(); void handleCreateSnapshot() }
|
||||
if (e.key === 'Escape') { e.preventDefault(); setCreatingSnap(false) }
|
||||
}}
|
||||
/>
|
||||
<Button variant="primary" busy={snapBusy === 'create'} disabled={!snapDraft.trim() || !!snapBusy} onClick={() => void handleCreateSnapshot()}>
|
||||
{tr('save')}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => setCreatingSnap(false)}>{tr('cancel')}</Button>
|
||||
</div>
|
||||
)}
|
||||
{snapshots.length === 0 ? (
|
||||
<div className="conn-row">
|
||||
<span className="conn-meta">{tr('snapshotEmpty')}</span>
|
||||
</div>
|
||||
) : (
|
||||
snapshots.map((s) => (
|
||||
<div className="conn-row" key={s.id || s.name}>
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">{s.name}</span>
|
||||
{s.created_at > 0 && <span className="conn-meta tnum">{formatShortTime(s.created_at * 1000, locale)}</span>}
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<Button
|
||||
icon={<RotateCcw size={13} aria-hidden="true" />}
|
||||
busy={snapBusy === `restore:${s.name}`}
|
||||
disabled={locked || !!snapBusy}
|
||||
onClick={() => setRestoreTarget(s.name)}
|
||||
>
|
||||
{tr('snapshotRestore')}
|
||||
</Button>
|
||||
<IconButton
|
||||
small
|
||||
label={tr('snapshotDelete')}
|
||||
icon={<Trash size={14} />}
|
||||
busy={snapBusy === `delete:${s.name}`}
|
||||
disabled={locked || !!snapBusy}
|
||||
onClick={() => void handleDeleteSnapshot(s.name)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{restoreTarget && (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setRestoreTarget(null) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="danger">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{tr('snapshotRestoreTitle', { name: restoreTarget })}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">{tr('snapshotRestoreDesc')}</Alert.Description>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn rg-p-button btn-danger" onClick={() => void handleRestoreSnapshot(restoreTarget)}>
|
||||
{tr('snapshotRestore')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import * as Menu from '@radix-ui/react-dropdown-menu'
|
||||
import { Code2, Copy, FileCode2, Terminal, UserRound } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { sshCommand } from '../../lib/format'
|
||||
import { Locale } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
import { ActionMenu } from '../../ui/menu'
|
||||
|
||||
interface Options {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
name: string
|
||||
/** The remembered user belongs to the macOS connection row; other drivers keep theirs in their endpoints. */
|
||||
enabled: boolean
|
||||
onToast: (title: string) => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/** The SSH user remembered for the VM (.reims-go-ssh-user) and the actions that use it. */
|
||||
export function useSSHAccess({ locale, driverID, name, enabled, onToast, onError }: Options) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [sshUser, setSshUser] = useState('')
|
||||
const [sshUserDialog, setSshUserDialog] = useState(false)
|
||||
const [sshUserDraft, setSshUserDraft] = useState('')
|
||||
useEffect(() => { setSshUserDialog(false) }, [driverID, name])
|
||||
useEffect(() => {
|
||||
if (!enabled) { setSshUser(''); return }
|
||||
let live = true
|
||||
api.GetVMSSHUser(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
|
||||
return () => { live = false }
|
||||
}, [driverID, name, enabled])
|
||||
|
||||
const openSSHTerminal = () => {
|
||||
api.OpenSSHTerminal(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const writeSSHConfig = () => {
|
||||
api.WriteSSHConfig(driverID, name, sshUser)
|
||||
.then((alias) => onToast(tr('toastSSHConfigWritten', { alias })))
|
||||
.catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const openVSCodeSSH = () => {
|
||||
api.OpenVSCodeSSH(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
|
||||
}
|
||||
const saveSSHUser = async () => {
|
||||
const next = sshUserDraft.trim()
|
||||
setSshUserDialog(false)
|
||||
try {
|
||||
await api.SetVMSSHUser(driverID, name, next)
|
||||
setSshUser(next)
|
||||
onToast(tr('toastSSHUserSaved'))
|
||||
} catch (e) {
|
||||
onError(tr('failSSH'), e)
|
||||
}
|
||||
}
|
||||
|
||||
return { sshUser, sshUserDialog, setSshUserDialog, sshUserDraft, setSshUserDraft, openSSHTerminal, writeSSHConfig, openVSCodeSSH, saveSSHUser }
|
||||
}
|
||||
|
||||
type SSHAccess = ReturnType<typeof useSSHAccess>
|
||||
|
||||
export const SSHRow: React.FC<{ locale: Locale; vmKey: string; port: number; state: SSHAccess; onCopy: (text: string) => void }> = ({ locale, vmKey, port, state, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { sshUser, openSSHTerminal, writeSSHConfig, openVSCodeSSH, setSshUserDraft, setSshUserDialog } = state
|
||||
const sshText = sshUser ? `ssh -p ${port} ${sshUser}@127.0.0.1` : sshCommand(port)
|
||||
return (
|
||||
<div className="conn-row">
|
||||
<div className="conn-main">
|
||||
<span className="conn-title">SSH</span>
|
||||
</div>
|
||||
<div className="conn-ctrl">
|
||||
<div className="ssh-pill">
|
||||
<code>{sshText}</code>
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(sshText)} />
|
||||
</div>
|
||||
<Button icon={<Terminal size={13} aria-hidden="true" />} onClick={openSSHTerminal}>
|
||||
{tr('sshOpenTerminal')}
|
||||
</Button>
|
||||
<ActionMenu key={vmKey} locale={locale} label={tr('sshMore')} small>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={writeSSHConfig}>
|
||||
<FileCode2 size={14} /> {tr('sshWriteConfig')}
|
||||
</Menu.Item>
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={openVSCodeSSH}>
|
||||
<Code2 size={14} /> {tr('sshOpenVSCode')}
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="menu-sep" />
|
||||
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => { setSshUserDraft(sshUser); setSshUserDialog(true) }}>
|
||||
<UserRound size={14} /> {tr('sshSetUser')}
|
||||
</Menu.Item>
|
||||
</ActionMenu>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Asks for the user name the SSH actions sign in with. */
|
||||
export const SSHUserDialog: React.FC<{ locale: Locale; state: SSHAccess }> = ({ locale, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { sshUserDialog, setSshUserDialog, sshUserDraft, setSshUserDraft, saveSSHUser } = state
|
||||
if (!sshUserDialog) return null
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setSshUserDialog(false) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{tr('sshUserTitle')}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">{tr('sshUserDesc')}</Alert.Description>
|
||||
<div className="field field-spaced">
|
||||
<input
|
||||
className="input rg-p-input mono"
|
||||
value={sshUserDraft}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={tr('sshUserPlaceholder')}
|
||||
autoFocus
|
||||
onChange={(e) => setSshUserDraft(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); void saveSSHUser() } }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button type="button" className="btn rg-p-button btn-primary" onClick={() => void saveSSHUser()}>{tr('save')}</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { Cpu, Globe, HardDrive, MemoryStick, Monitor, Network } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, graphicsLabel, parseMemoryGB, resolveGuestLang } from '../../lib/format'
|
||||
import { HostReport, Locale, VMDetail, VMInfo, VMStats } from '../../types'
|
||||
import { Tip } from '../../ui/controls'
|
||||
|
||||
const GUEST_FAMILY_LABEL: Record<string, string> = { macos: 'macOS', linux: 'Linux', windows: 'Windows', android: 'Android' }
|
||||
|
||||
type Tone = '' | ' warn' | ' high'
|
||||
const meterTone = (pct: number, warn = 75, high = 90): Tone => (pct >= high ? ' high' : pct >= warn ? ' warn' : '')
|
||||
const clampPct = (v: number) => Math.min(100, Math.max(0, v))
|
||||
|
||||
interface Spec {
|
||||
key: string
|
||||
/** Shown only in the wide, single-column layout. */
|
||||
label: string
|
||||
icon: React.ReactNode
|
||||
value: string
|
||||
tip: string
|
||||
/** Cells in the first row reserve a meter slot so the row keeps its height. */
|
||||
meter?: { pct: number; tone: Tone; idle: boolean }
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
running: boolean
|
||||
detail: VMDetail | null
|
||||
/** Non-macOS VMs: the cross-driver model. */
|
||||
vmInfo?: VMInfo | null
|
||||
isMacOSDriver: boolean
|
||||
guestFamily: string
|
||||
host: HostReport
|
||||
stats: VMStats | null
|
||||
}
|
||||
|
||||
// Summary presents each fact once in user-facing words; raw upstream values stay in "Technical details".
|
||||
function vmSpecs({ locale, running, detail, vmInfo, isMacOSDriver, guestFamily, host, stats }: Props): Spec[] {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const specs: Spec[] = []
|
||||
if (detail) {
|
||||
const live = running && !!stats
|
||||
const cpuPct = live ? clampPct(stats!.cpu_percent || 0) : 0
|
||||
const memGB = parseMemoryGB(detail.memory) ?? 0
|
||||
const rss = live ? stats!.memory_rss_bytes : 0
|
||||
const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0
|
||||
const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
|
||||
const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0
|
||||
const mem = formatMemory(detail.memory, locale)
|
||||
|
||||
specs.push(
|
||||
{
|
||||
key: 'cpu', label: tr('factCPU'), icon: <Cpu size={15} aria-hidden="true" />, value: tr('cores', { n: detail.cpus }),
|
||||
tip: live ? tr('specCPULiveTip', { n: detail.cpus, pct: Math.round(cpuPct) }) : tr('specCPUTip', { n: detail.cpus }),
|
||||
meter: { pct: cpuPct, tone: meterTone(cpuPct), idle: !live },
|
||||
},
|
||||
{
|
||||
key: 'mem', label: tr('factMemory'), icon: <MemoryStick size={15} aria-hidden="true" />, value: mem,
|
||||
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss, locale) }) : tr('specMemTip', { mem }),
|
||||
meter: { pct: memPct, tone: '', idle: !live },
|
||||
},
|
||||
{
|
||||
key: 'disk', label: tr('factDisk'), icon: <HardDrive size={15} aria-hidden="true" />,
|
||||
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes, locale) : controllerLabel(detail.disk_controller),
|
||||
tip: diskKnown
|
||||
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats!.disk_actual_bytes, locale), max: formatBytes(stats!.disk_virtual_bytes, locale) })
|
||||
: tr('specDiskTip', { ctl: controllerLabel(detail.disk_controller) }),
|
||||
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
|
||||
},
|
||||
{
|
||||
key: 'gfx', label: tr('factGraphics'), icon: <Monitor size={15} aria-hidden="true" />,
|
||||
value: graphicsLabel(locale, detail, host),
|
||||
tip: tr('specGraphicsTip', { gfx: graphicsLabel(locale, detail, host) }),
|
||||
},
|
||||
{
|
||||
key: 'net', label: tr('fieldNetwork'), icon: <Network size={15} aria-hidden="true" />,
|
||||
value: detail.network_mode === 'bridge' ? tr('netBridge') : detail.network_mode === 'custom' ? tr('netCustom') : detail.network ? tr('netShared') : tr('netOff'),
|
||||
tip: detail.network_mode === 'bridge' ? tr('specNetBridgeTip') : !detail.network ? tr('specNetOffTip') : detail.ssh_port > 0 ? tr('specNetSSHTip', { port: detail.ssh_port }) : tr('specNetTip'),
|
||||
},
|
||||
)
|
||||
if (detail.guest_lang) {
|
||||
const lang = resolveGuestLang(locale, detail.guest_lang)
|
||||
specs.push({
|
||||
key: 'lang', label: tr('specLang'), icon: <Globe size={15} aria-hidden="true" />, value: lang.label,
|
||||
tip: lang.detail
|
||||
? tr('specLangTipDetail', { label: lang.label, detail: lang.detail })
|
||||
: tr('specLangTip', { label: lang.label }),
|
||||
})
|
||||
}
|
||||
} else if (vmInfo && !isMacOSDriver) {
|
||||
// Other drivers describe a VM through the cross-driver model only.
|
||||
const live = running && !!stats
|
||||
const guestOS = vmInfo.guest_os
|
||||
const osName = [guestOS?.distro || GUEST_FAMILY_LABEL[guestFamily] || '', guestOS?.version ?? ''].filter(Boolean).join(' ')
|
||||
if (osName) {
|
||||
specs.push({
|
||||
key: 'os', label: tr('factGuestOS'), icon: <Monitor size={15} aria-hidden="true" />, value: osName,
|
||||
tip: guestOS?.arch ? `${osName} · ${guestOS.arch}` : osName,
|
||||
})
|
||||
}
|
||||
if ((vmInfo.cpus ?? 0) > 0) {
|
||||
const cpus = vmInfo.cpus ?? 0
|
||||
const cpuPct = live ? clampPct(stats!.cpu_percent || 0) : 0
|
||||
specs.push({
|
||||
key: 'cpu', label: tr('factCPU'), icon: <Cpu size={15} aria-hidden="true" />, value: tr('cores', { n: cpus }),
|
||||
tip: live ? tr('specCPULiveTip', { n: cpus, pct: Math.round(cpuPct) }) : tr('specCPUTip', { n: cpus }),
|
||||
meter: { pct: cpuPct, tone: meterTone(cpuPct), idle: !live },
|
||||
})
|
||||
}
|
||||
if (vmInfo.memory) {
|
||||
const memGB = parseMemoryGB(vmInfo.memory) ?? 0
|
||||
const rss = live ? stats!.memory_rss_bytes : 0
|
||||
const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0
|
||||
const mem = formatMemory(vmInfo.memory, locale)
|
||||
specs.push({
|
||||
key: 'mem', label: tr('factMemory'), icon: <MemoryStick size={15} aria-hidden="true" />, value: mem,
|
||||
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss, locale) }) : tr('specMemTip', { mem }),
|
||||
meter: { pct: memPct, tone: '', idle: !live },
|
||||
})
|
||||
}
|
||||
if (vmInfo.disk_summary) {
|
||||
const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
|
||||
const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0
|
||||
specs.push({
|
||||
key: 'disk', label: tr('factDisk'), icon: <HardDrive size={15} aria-hidden="true" />,
|
||||
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes, locale) : vmInfo.disk_summary,
|
||||
tip: vmInfo.disk_summary,
|
||||
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
|
||||
})
|
||||
}
|
||||
}
|
||||
return specs
|
||||
}
|
||||
|
||||
export const VMSummary: React.FC<Props> = (props) => {
|
||||
const specs = vmSpecs(props)
|
||||
if (specs.length === 0) return null
|
||||
return (
|
||||
<div className={`vm-spec-card rg-p-vm-summary${props.running ? ' is-live' : ''}`} role="list" data-rg-slot="vm.card">
|
||||
{specs.map((s) => (
|
||||
<Tip key={s.key} label={s.tip}>
|
||||
<div className="vm-spec-cell" role="listitem" tabIndex={0}>
|
||||
<span className="vm-spec-icon">{s.icon}</span>
|
||||
<span className="vm-spec-label">{s.label}</span>
|
||||
<span className="vm-spec-val">{s.value}</span>
|
||||
{s.meter && (
|
||||
<span className="vm-spec-meter" data-idle={s.meter.idle || undefined} aria-hidden="true">
|
||||
<span className={`meter-fill${s.meter.tone}`} style={{ transform: `scaleX(${s.meter.idle ? 0 : s.meter.pct / 100})` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Tip>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { ChevronRight, Copy } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { Locale, VMDetail, VMInfo } from '../../types'
|
||||
import { IconButton } from '../../ui/controls'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
name: string
|
||||
driverID: string
|
||||
detail: VMDetail | null
|
||||
vmInfo?: VMInfo | null
|
||||
onCopy: (text: string) => void
|
||||
}
|
||||
|
||||
/** The raw values upstream tools use for the VM, folded by default. */
|
||||
export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmInfo, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const copyTechSummary = () => {
|
||||
if (!detail) {
|
||||
if (!vmInfo) return
|
||||
onCopy([
|
||||
`${tr('fieldVMName')}: ${name}`,
|
||||
`${tr('fieldDriver')}: ${vmInfo.driver_name || driverID}`,
|
||||
...(vmInfo.disk_path ? [`${tr('fieldDisk')}: ${vmInfo.disk_path}`] : []),
|
||||
...(vmInfo.directory ? [`${tr('fieldDir')}: ${vmInfo.directory}`] : []),
|
||||
].join('\n'))
|
||||
return
|
||||
}
|
||||
const rows = [
|
||||
`${tr('fieldKind')}: ${detail.kind || '—'}`,
|
||||
`${tr('fieldCPUModel')}: ${detail.cpu_model || 'auto'}`,
|
||||
`${tr('fieldGraphicsBackend')}: ${detail.graphics}`,
|
||||
...(detail.gpu && detail.gpu !== 'auto' ? [`${tr('fieldICD')}: ${detail.gpu}`] : []),
|
||||
`${tr('resolution')}: ${detail.displays} × ${detail.resolution}`,
|
||||
`${tr('fieldController')}: ${detail.disk_controller}`,
|
||||
`${tr('fieldDisk')}: ${detail.disk}`,
|
||||
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`,
|
||||
`${tr('fieldAudio')}: ${detail.audio_raw || tr('off')}`,
|
||||
...(detail.guest_lang ? [`${tr('guestLang')}: ${detail.guest_lang}`] : []),
|
||||
`${tr('fieldDir')}: ${detail.directory}`,
|
||||
]
|
||||
onCopy(rows.join('\n'))
|
||||
}
|
||||
|
||||
if (!detail) {
|
||||
if (!vmInfo) return null
|
||||
return (
|
||||
<details key="driver" className="tech">
|
||||
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
|
||||
<div className="tech-body">
|
||||
<IconButton small className="tech-copy" label={tr('copyTechInfo')} icon={<Copy size={14} />} onClick={copyTechSummary} />
|
||||
<dl className="kv-list">
|
||||
<dt>{tr('fieldVMName')}</dt><dd className="mono">{name}</dd>
|
||||
<dt>{tr('fieldDriver')}</dt><dd>{vmInfo.driver_name || driverID}</dd>
|
||||
{vmInfo.disk_path && (<><dt>{tr('fieldDisk')}</dt><dd className="mono">{vmInfo.disk_path}</dd></>)}
|
||||
{vmInfo.directory && (<><dt>{tr('fieldDir')}</dt><dd className="mono">{vmInfo.directory}</dd></>)}
|
||||
</dl>
|
||||
</div>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<details className="tech">
|
||||
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
|
||||
<div className="tech-body">
|
||||
<IconButton small className="tech-copy" label={tr('copyTechInfo')} icon={<Copy size={14} />} onClick={copyTechSummary} />
|
||||
<dl className="kv-list">
|
||||
<dt>{tr('fieldVMName')}</dt><dd className="mono">{name}</dd>
|
||||
<dt>{tr('fieldKind')}</dt><dd>{detail.kind || '—'}</dd>
|
||||
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
|
||||
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
|
||||
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</dd></>)}
|
||||
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {detail.resolution}</dd>
|
||||
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</dd>
|
||||
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
|
||||
<dt>{tr('fieldNetwork')}</dt><dd className="mono">{detail.network_summary || tr('off')}</dd>
|
||||
<dt>{tr('fieldAudio')}</dt><dd>{detail.audio_raw || tr('off')}</dd>
|
||||
{detail.guest_lang && (<><dt>{tr('guestLang')}</dt><dd className="mono">{detail.guest_lang}</dd></>)}
|
||||
<dt>{tr('fieldDir')}</dt><dd className="mono">{detail.directory}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { Copy } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { formatBytes } from '../../lib/format'
|
||||
import { DiskCompactResult, DiskResizeResult, Locale, VMStats } from '../../types'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
import { SetRow } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
interface DiskOptions {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
vm: string
|
||||
running: boolean
|
||||
stats?: VMStats | null
|
||||
onError: (message: string) => void
|
||||
onDiskChanged?: () => void
|
||||
}
|
||||
|
||||
/** Resizing, compacting and optimizing the VM's disk, one at a time. */
|
||||
export function useDiskMaintenance({ locale, driverID, vm, running, stats, onError, onDiskChanged }: DiskOptions) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
const [resizeInput, setResizeInput] = useState('+64G')
|
||||
const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | 'optimize' | ''>('')
|
||||
const [resizeResult, setResizeResult] = useState<DiskResizeResult | null>(null)
|
||||
const [compactResult, setCompactResult] = useState<DiskCompactResult | null>(null)
|
||||
const [optimizeResult, setOptimizeResult] = useState<DiskCompactResult | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
setResizeResult(null)
|
||||
setCompactResult(null)
|
||||
setOptimizeResult(null)
|
||||
}, [driverID, vm])
|
||||
|
||||
const handleResizeDisk = async () => {
|
||||
if (running || diskOpBusy || !resizeInput.trim()) return
|
||||
onError('')
|
||||
setDiskOpBusy('resize')
|
||||
try {
|
||||
const res = await api.ResizeVMDisk(driverID, vm, resizeInput.trim())
|
||||
if (activeVMNameRef.current === vm) {
|
||||
setResizeResult(res)
|
||||
}
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vm) {
|
||||
onError(parseAppError(e).summary)
|
||||
}
|
||||
} finally {
|
||||
setDiskOpBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2'
|
||||
const diskRewriteBaseReason = running ? tr('stopBeforeDiskOp')
|
||||
: (stats?.disk_snapshot_count ?? 0) > 0 ? tr('diskRewriteSnapshots')
|
||||
: (stats?.disk_backing_depth ?? 0) > 0 ? tr('diskRewriteOverlay')
|
||||
: !isQcow2 ? tr('diskCompactQcow2Only')
|
||||
: undefined
|
||||
const compactRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'compact' ? tr('diskRewriteBusy') : undefined)
|
||||
const optimizeRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'optimize' ? tr('diskRewriteBusy') : undefined)
|
||||
|
||||
const handleCompactDisk = async (optimize: boolean) => {
|
||||
if (diskRewriteBaseReason || diskOpBusy) return
|
||||
onError('')
|
||||
setDiskOpBusy(optimize ? 'optimize' : 'compact')
|
||||
try {
|
||||
if (optimize) {
|
||||
const res = await api.OptimizeVMDisk(driverID, vm)
|
||||
if (activeVMNameRef.current === vm) {
|
||||
setOptimizeResult(res)
|
||||
setCompactResult(null)
|
||||
}
|
||||
} else {
|
||||
const res = await api.CompactVMDisk(driverID, vm)
|
||||
if (activeVMNameRef.current === vm) {
|
||||
setCompactResult(res)
|
||||
}
|
||||
}
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vm) {
|
||||
onError(parseAppError(e).summary)
|
||||
}
|
||||
} finally {
|
||||
setDiskOpBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const extendedL2 = stats?.disk_extended_l2 || optimizeResult?.extended_l2_enabled
|
||||
|
||||
return {
|
||||
resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2,
|
||||
compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
|
||||
}
|
||||
}
|
||||
|
||||
interface RowsProps {
|
||||
locale: Locale
|
||||
running: boolean
|
||||
state: ReturnType<typeof useDiskMaintenance>
|
||||
onCopy?: (text: string) => void
|
||||
}
|
||||
|
||||
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, state, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state
|
||||
return (
|
||||
<>
|
||||
<SetRow
|
||||
title={tr('diskResizeTitle')}
|
||||
desc={tr('diskResizeDesc')}
|
||||
disabled={running}
|
||||
reason={tr('stopBeforeDiskOp')}
|
||||
block={
|
||||
<div className="stack-2">
|
||||
<div className="hstack">
|
||||
<div className="presets">
|
||||
{['+32G', '+64G', '+128G', '256G', '512G'].map((v) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
className="preset"
|
||||
aria-pressed={resizeInput === v}
|
||||
disabled={running || !!diskOpBusy}
|
||||
onClick={() => setResizeInput(v)}
|
||||
>
|
||||
{v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<input
|
||||
className="input rg-p-input mono input-compact"
|
||||
aria-label={tr('diskResizeTitle')}
|
||||
value={resizeInput}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
disabled={running || !!diskOpBusy}
|
||||
onChange={(e) => setResizeInput(e.target.value)}
|
||||
placeholder="+64G / 256G"
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
busy={diskOpBusy === 'resize'}
|
||||
disabled={running || !!diskOpBusy || !resizeInput.trim()}
|
||||
onClick={handleResizeDisk}
|
||||
>
|
||||
{tr('diskResizeAction')}
|
||||
</Button>
|
||||
</div>
|
||||
{resizeResult && (
|
||||
<div className="notice">
|
||||
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}</div>
|
||||
<div className="cmd-line cmd-line-spaced">
|
||||
<code>{resizeResult.guest_expand_cmd}</code>
|
||||
{onCopy && (
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(resizeResult.guest_expand_cmd)} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('diskCompactTitle')}
|
||||
desc={compactResult
|
||||
? compactResult.reclaimed_bytes > 0
|
||||
? tr('diskCompactDone', {
|
||||
before: formatBytes(compactResult.before_bytes, locale),
|
||||
after: formatBytes(compactResult.after_bytes, locale),
|
||||
reclaimed: formatBytes(compactResult.reclaimed_bytes, locale),
|
||||
})
|
||||
: tr('diskCompactNoGain')
|
||||
: tr('diskCompactDesc')}
|
||||
disabled={!!compactRowReason}
|
||||
reason={compactRowReason}
|
||||
control={
|
||||
<Button
|
||||
variant="secondary"
|
||||
busy={diskOpBusy === 'compact'}
|
||||
disabled={!!compactRowReason || !!diskOpBusy}
|
||||
onClick={() => handleCompactDisk(false)}
|
||||
>
|
||||
{tr('diskCompactAction')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('diskOptimizeTitle')}
|
||||
desc={optimizeResult ? tr('diskOptimizeDone', {
|
||||
before: formatBytes(optimizeResult.before_bytes, locale),
|
||||
after: formatBytes(optimizeResult.after_bytes, locale),
|
||||
reclaimed: formatBytes(optimizeResult.reclaimed_bytes, locale),
|
||||
status: tr(extendedL2 ? 'diskOptimizeEnabled' : 'diskOptimizeInactive'),
|
||||
}) : tr(extendedL2 ? 'diskOptimizeEnabled' : 'diskOptimizeDesc')}
|
||||
disabled={!extendedL2 && !!optimizeRowReason}
|
||||
reason={extendedL2 ? undefined : optimizeRowReason}
|
||||
control={extendedL2 ? undefined : (
|
||||
<Button variant="secondary" busy={diskOpBusy === 'optimize'} disabled={!!optimizeRowReason || !!diskOpBusy} onClick={() => handleCompactDisk(true)}>
|
||||
{tr('diskOptimizeAction')}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface DefenderProps {
|
||||
locale: Locale
|
||||
dataRoot: string
|
||||
onCopy?: (text: string) => void
|
||||
onError: (message: string) => void
|
||||
}
|
||||
|
||||
export const DefenderExclusionRow: React.FC<DefenderProps> = ({ locale, dataRoot, onCopy, onError }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const handleDefender = async (copy: boolean) => {
|
||||
onError('')
|
||||
try {
|
||||
if (copy) {
|
||||
const command = await api.GetDefenderExclusionCommand()
|
||||
if (command) onCopy?.(command)
|
||||
} else {
|
||||
await api.OpenWindowsSecurityExclusions()
|
||||
}
|
||||
} catch (e) {
|
||||
onError(parseAppError(e).summary)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<SetRow
|
||||
title={tr('defenderExclusionTitle')}
|
||||
desc={tr('defenderExclusionDesc', { path: dataRoot })}
|
||||
control={
|
||||
<div className="hstack">
|
||||
<Button variant="secondary" onClick={() => handleDefender(false)}>{tr('defenderOpenSecurity')}</Button>
|
||||
{onCopy && <Button variant="secondary" onClick={() => handleDefender(true)}>{tr('defenderCopyCommand')}</Button>}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { createKeymapRequests, keymapPresetUpdate, keymapUpdate, type KeymapState } from '../../lib/vmKeymap'
|
||||
import { Locale, VMKeymapGuestModifier, VMKeymapHostModifier, VMKeymapPreset } from '../../types'
|
||||
import { PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
/** The VM's modifier key mapping, refreshed while shown. */
|
||||
export function useKeymap(vm: string, running: boolean, shown: boolean) {
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
const [{ keymap, error: keymapErr, busy: keymapBusy }, setKeymapState] = useState<KeymapState>({ keymap: null, error: '', busy: false })
|
||||
const [keymapRequests] = useState(() => createKeymapRequests(api, () => activeVMNameRef.current,
|
||||
(patch) => setKeymapState((state) => ({ ...state, ...patch }))))
|
||||
|
||||
useEffect(() => {
|
||||
setKeymapState(keymapRequests.initial(vm))
|
||||
}, [vm, keymapRequests])
|
||||
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const { refresh, stop } = keymapRequests.watch(vm)
|
||||
void refresh()
|
||||
const timer = window.setInterval(refresh, 3000)
|
||||
return () => { stop(); window.clearInterval(timer) }
|
||||
}, [shown, vm, running, keymapRequests])
|
||||
|
||||
return { keymap, keymapErr, keymapBusy, write: keymapRequests.write }
|
||||
}
|
||||
|
||||
export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType<typeof useKeymap> }> = ({ locale, vm, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { keymap, keymapErr, keymapBusy, write } = state
|
||||
return (
|
||||
<SetGroup title={tr('keymapGroupTitle')} note={tr('keymapGroupNote')}>
|
||||
{keymapErr && <div className="notice notice-error" role="alert">{keymapErr}</div>}
|
||||
{keymap && <>
|
||||
<SetRow title={tr('keymapPresetTitle')} disabled={keymapBusy}
|
||||
desc={keymap.preset === 'off' && !keymap.capture_host_shortcuts ? undefined
|
||||
: !keymap.input_service_available ? tr('keymapInputServiceRequired')
|
||||
: !keymap.running ? tr('keymapStopped')
|
||||
: keymap.needs_guest_tools && !keymap.guest_connected ? tr('keymapWaiting')
|
||||
: keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version
|
||||
? tr('keymapUpgrade', { version: keymap.required_agent_version })
|
||||
: keymap.needs_guest_tools && !keymap.guest_keymap_active ? tr('keymapPending')
|
||||
: tr(keymap.hook_active ? 'keymapRunning' : 'keymapInactive')}
|
||||
control={<Segmented<VMKeymapPreset> label={tr('keymapPresetTitle')} value={keymap.preset}
|
||||
options={[{ value: 'off', label: tr('keymapPresetOff') }, { value: 'win_to_cmd', label: tr('keymapPresetWinToCmd') }, { value: 'swap_alt_win', label: tr('keymapPresetSwapAltWin') }, { value: 'custom', label: tr('keymapPresetCustom') }]}
|
||||
onChange={(preset) => {
|
||||
const request = keymapPresetUpdate(keymap, preset)
|
||||
if (request) void write(vm, request)
|
||||
}} />}
|
||||
/>
|
||||
<SetRow title={tr('keymapCaptureHostShortcutsTitle')} desc={tr('keymapCaptureHostShortcutsDesc')} disabled={keymapBusy}
|
||||
control={<Switch label={tr('keymapCaptureHostShortcutsTitle')} checked={keymap.capture_host_shortcuts}
|
||||
onChange={(capture_host_shortcuts) => { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />}
|
||||
/>
|
||||
{keymap.preset === 'custom' && ([
|
||||
['lwin', 'keymapHostLwin'],
|
||||
['rwin', 'keymapHostRwin'],
|
||||
['lalt', 'keymapHostLalt'],
|
||||
['ralt', 'keymapHostRalt'],
|
||||
['lctrl', 'keymapHostLctrl'],
|
||||
['rctrl', 'keymapHostRctrl'],
|
||||
['capslock', 'keymapHostCapslock'],
|
||||
] as const satisfies readonly (readonly [VMKeymapHostModifier, I18nKey])[]).map(([modifier, label]) => (
|
||||
<SetRow key={modifier} title={tr(label)} disabled={keymapBusy}
|
||||
control={<PopupSelect<VMKeymapGuestModifier> label={tr(label)} value={keymap.bindings[modifier] ?? 'default'}
|
||||
options={[
|
||||
{ value: 'default', label: tr('keymapGuestDefault') },
|
||||
{ value: 'lcmd', label: tr('keymapGuestLcmd') },
|
||||
{ value: 'rcmd', label: tr('keymapGuestRcmd') },
|
||||
{ value: 'lopt', label: tr('keymapGuestLopt') },
|
||||
{ value: 'ropt', label: tr('keymapGuestRopt') },
|
||||
{ value: 'lctrl', label: tr('keymapGuestLctrl') },
|
||||
{ value: 'rctrl', label: tr('keymapGuestRctrl') },
|
||||
{ value: 'esc', label: tr('keymapGuestEsc') },
|
||||
{ value: 'disabled', label: tr('keymapGuestDisabled') },
|
||||
]}
|
||||
onChange={(target) => { void write(vm, keymapUpdate(keymap, { bindings: { [modifier]: target } })) }} />}
|
||||
/>
|
||||
))}
|
||||
</>}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import React, { Suspense, lazy, useEffect, useRef, useState } from 'react'
|
||||
import { parseAppError } from '../../i18n'
|
||||
import { Locale, PluginInfo } from '../../types'
|
||||
import { api } from '../../wails'
|
||||
|
||||
const SchemaForm = lazy(() => import('../SchemaForm').then((m) => ({ default: m.SchemaForm })))
|
||||
|
||||
/** Per-VM settings of the active plugins. Changes save at once, in order. */
|
||||
export function useVMPluginSettings(vmKey: string, onError: (message: string) => void) {
|
||||
const [vmPlugins, setVmPlugins] = useState<PluginInfo[]>([])
|
||||
const [vmPluginVals, setVmPluginVals] = useState<Record<string, Record<string, unknown>>>({})
|
||||
const vmPluginSettingsSaveQueues = useRef(new Map<string, Promise<void>>())
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(vmKey)])
|
||||
.then(([list, vals]) => {
|
||||
if (!live) return
|
||||
const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings)
|
||||
setVmPlugins(activeWithVM)
|
||||
setVmPluginVals((vals ?? {}) as Record<string, Record<string, unknown>>)
|
||||
})
|
||||
.catch((e) => console.warn('[settings] load VM plugin settings failed:', e))
|
||||
return () => { live = false }
|
||||
}, [vmKey])
|
||||
|
||||
const updateVMPluginSetting = (pluginID: string, patch: Record<string, unknown>) => {
|
||||
setVmPluginVals((prev) => ({ ...prev, [pluginID]: { ...prev[pluginID], ...patch } }))
|
||||
const queueKey = JSON.stringify([pluginID, vmKey])
|
||||
const previous = vmPluginSettingsSaveQueues.current.get(queueKey) ?? Promise.resolve()
|
||||
const save = previous.catch((error) => {
|
||||
console.warn('[settings] previous plugin save failed:', error)
|
||||
}).then(() => api.SetPluginSettings(pluginID, vmKey, patch))
|
||||
vmPluginSettingsSaveQueues.current.set(queueKey, save)
|
||||
void save.catch((e) => onError(parseAppError(e).summary)).finally(() => {
|
||||
if (vmPluginSettingsSaveQueues.current.get(queueKey) === save) {
|
||||
vmPluginSettingsSaveQueues.current.delete(queueKey)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return { vmPlugins, vmPluginVals, updateVMPluginSetting }
|
||||
}
|
||||
|
||||
export const VMPluginGroup: React.FC<{ locale: Locale; group: string; state: ReturnType<typeof useVMPluginSettings> }> = ({ locale, group, state }) => {
|
||||
const { vmPlugins, vmPluginVals, updateVMPluginSetting } = state
|
||||
const matched = vmPlugins.filter((p) => p.settings && (p.settings['x-group'] === group || Object.values(p.settings.properties ?? {}).some((prop) => prop['x-group'] === group)))
|
||||
if (matched.length === 0) return null
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
{matched.map((p) => (
|
||||
<SchemaForm
|
||||
key={p.id}
|
||||
locale={locale}
|
||||
schema={p.settings!}
|
||||
values={vmPluginVals[p.id] ?? {}}
|
||||
scopeFilter="vm"
|
||||
groupFilter={group}
|
||||
onChange={(_, patch) => updateVMPluginSetting(p.id, patch)}
|
||||
/>
|
||||
))}
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import * as Alert from '@radix-ui/react-alert-dialog'
|
||||
import { FolderPlus, Trash2 } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { DriveShareSettings, Locale, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, VMDetail } from '../../types'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
import { Segmented, SetGroup, SetRow, SetValue, Switch } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
/** Windows drives shared with the VM. */
|
||||
export function useDriveShares(vm: string) {
|
||||
const [driveSettings, setDriveSettings] = useState<DriveShareSettings | null>(null)
|
||||
const [driveBusy, setDriveBusy] = useState(false)
|
||||
const driveBusyRef = useRef(false)
|
||||
const [driveErr, setDriveErr] = useState('')
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setDriveSettings(null)
|
||||
setDriveErr('')
|
||||
api.GetVMDriveShareSettings(vm)
|
||||
.then((settings) => { if (active) setDriveSettings(settings) })
|
||||
.catch((e) => { if (active) setDriveErr(parseAppError(e).summary) })
|
||||
return () => { active = false }
|
||||
}, [vm])
|
||||
|
||||
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
|
||||
if (driveBusyRef.current || !driveSettings) return
|
||||
driveBusyRef.current = true
|
||||
setDriveBusy(true)
|
||||
setDriveErr('')
|
||||
try {
|
||||
const next = await api.SetVMDriveShareSettings(vm, enabled, selected)
|
||||
if (activeVMNameRef.current === vm) setDriveSettings(next)
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vm) setDriveErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
driveBusyRef.current = false
|
||||
setDriveBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive)
|
||||
|
||||
return { driveSettings, driveBusy, driveErr, updateDriveShares, selectedDrives }
|
||||
}
|
||||
|
||||
/** Single folders shared with the VM. */
|
||||
export function useSharedFolders(vm: string, locale: Locale) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [folderSettings, setFolderSettings] = useState<SharedFolderSettings | null>(null)
|
||||
const [folderBusy, setFolderBusy] = useState(false)
|
||||
const folderBusyRef = useRef(false)
|
||||
const folderOpSeqRef = useRef(0)
|
||||
const [folderErr, setFolderErr] = useState('')
|
||||
const [confirmRWFolder, setConfirmRWFolder] = useState<SharedFolderInfo | null>(null)
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
folderOpSeqRef.current += 1
|
||||
folderBusyRef.current = false
|
||||
setFolderBusy(false)
|
||||
setFolderSettings(null)
|
||||
setFolderErr('')
|
||||
setConfirmRWFolder(null)
|
||||
api.GetVMSharedFolderSettings(vm)
|
||||
.then((settings) => { if (active) setFolderSettings(settings) })
|
||||
.catch((e) => { if (active) setFolderErr(formatFolderError(e)) })
|
||||
return () => { active = false }
|
||||
}, [vm])
|
||||
|
||||
const formatFolderIssue = (issue?: string) => {
|
||||
switch (issue) {
|
||||
case 'missing': return tr('folderShareIssueMissing')
|
||||
case 'volume_mismatch': return tr('folderShareIssueVolumeMismatch')
|
||||
case 'path_changed': return tr('folderShareIssuePathChanged')
|
||||
case 'overlap': return tr('folderShareIssueOverlap')
|
||||
case 'blocked': return tr('folderShareIssueBlocked')
|
||||
case 'not_found': return tr('folderShareIssueNotFound')
|
||||
case 'invalid_mode': return tr('folderShareIssueInvalidMode')
|
||||
case 'corrupt_config': return tr('folderShareIssueCorruptConfig')
|
||||
default: return ''
|
||||
}
|
||||
}
|
||||
|
||||
const formatFolderError = (e: unknown) => {
|
||||
const summary = parseAppError(e).summary
|
||||
const match = summary.match(/shared folder:\s*(missing|volume_mismatch|path_changed|overlap|blocked|not_found|invalid_mode|corrupt_config)\b/i)
|
||||
if (match) return formatFolderIssue(match[1].toLowerCase())
|
||||
return summary
|
||||
}
|
||||
|
||||
const runFolderOp = async (op: (vm: string) => Promise<SharedFolderSettings | null>) => {
|
||||
if (folderBusyRef.current || !folderSettings) return
|
||||
const opSeq = ++folderOpSeqRef.current
|
||||
folderBusyRef.current = true
|
||||
setFolderBusy(true)
|
||||
setFolderErr('')
|
||||
try {
|
||||
const next = await op(vm)
|
||||
if (next && activeVMNameRef.current === vm && folderOpSeqRef.current === opSeq) {
|
||||
setFolderSettings(next)
|
||||
}
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vm && folderOpSeqRef.current === opSeq) {
|
||||
setFolderErr(formatFolderError(e))
|
||||
}
|
||||
} finally {
|
||||
if (folderOpSeqRef.current === opSeq) {
|
||||
folderBusyRef.current = false
|
||||
setFolderBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleAddFolder = () => runFolderOp(async (vm) => {
|
||||
const picked = await api.PickDirectory(tr('folderSharePickTitle'))
|
||||
if (!picked || activeVMNameRef.current !== vm) return null
|
||||
return api.AddVMSharedFolder(vm, picked)
|
||||
})
|
||||
|
||||
const updateFolderMode = (folderID: string, mode: SharedFolderMode) =>
|
||||
runFolderOp((vm) => api.SetVMSharedFolderMode(vm, folderID, mode))
|
||||
|
||||
const handleRemoveFolder = (folderID: string) =>
|
||||
runFolderOp((vm) => api.RemoveVMSharedFolder(vm, folderID))
|
||||
|
||||
return {
|
||||
folderSettings, folderBusy, folderErr, confirmRWFolder, setConfirmRWFolder, formatFolderIssue,
|
||||
handleAddFolder, updateFolderMode, handleRemoveFolder,
|
||||
}
|
||||
}
|
||||
|
||||
interface SectionProps<State> {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
state: State
|
||||
/** Version of the connected Guest Tools agent, 0 when none is connected. */
|
||||
toolsVersion: number
|
||||
}
|
||||
|
||||
export const DriveShareSection: React.FC<SectionProps<ReturnType<typeof useDriveShares>>> = ({ locale, detail, state, toolsVersion }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { driveSettings, driveBusy, driveErr, updateDriveShares, selectedDrives } = state
|
||||
return (
|
||||
<SetGroup title={tr('driveShareTitle')} note={tr('driveShareReadOnly')}>
|
||||
<SetRow
|
||||
title={tr('driveShareMaster')}
|
||||
desc={tr('driveShareMasterDesc')}
|
||||
control={
|
||||
<Switch
|
||||
label={tr('driveShareMaster')}
|
||||
checked={!!driveSettings?.enabled}
|
||||
disabled={!driveSettings || driveBusy || !!detail.guest_tools_disabled}
|
||||
onChange={(enabled) => void updateDriveShares(enabled, selectedDrives())}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{detail.guest_tools_disabled && <div className="notice">{tr('gtStatusOffTip')}</div>}
|
||||
{driveErr && <div className="notice" role="alert">{driveErr}</div>}
|
||||
{driveSettings?.enabled && selectedDrives().length > 0 &&
|
||||
toolsVersion > 0 &&
|
||||
toolsVersion < driveSettings.required_agent_version && (
|
||||
<div className="notice">{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}</div>
|
||||
)}
|
||||
{/* Drives are only worth choosing once sharing is on. */}
|
||||
{driveSettings?.enabled && driveSettings.drives.map((drive) => {
|
||||
const title = `Windows (${drive.drive}:)`
|
||||
return (
|
||||
<SetRow
|
||||
key={drive.drive}
|
||||
title={title}
|
||||
desc={drive.system ? <span className="warn-text">{tr('driveShareSystem')}</span> : undefined}
|
||||
disabled={driveBusy || !!detail.guest_tools_disabled}
|
||||
control={
|
||||
<Switch
|
||||
label={title}
|
||||
checked={drive.selected}
|
||||
disabled={driveBusy}
|
||||
onChange={(enabled) => {
|
||||
const next = selectedDrives().filter((letter) => letter !== drive.drive)
|
||||
if (enabled) next.push(drive.drive)
|
||||
void updateDriveShares(driveSettings?.enabled ?? false, next)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
{driveSettings && driveSettings.drives.length === 0 && (
|
||||
<SetValue title={tr('driveShareTitle')} value={tr('driveShareNoDrives')} />
|
||||
)}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export const SharedFolderSection: React.FC<SectionProps<ReturnType<typeof useSharedFolders>>> = ({ locale, detail, state, toolsVersion }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { folderSettings, folderBusy, folderErr, setConfirmRWFolder, formatFolderIssue, handleAddFolder, updateFolderMode, handleRemoveFolder } = state
|
||||
return (
|
||||
<SetGroup title={tr('folderShareTitle')} note={tr('folderShareNote')}>
|
||||
<SetRow
|
||||
title={tr('folderShareAddTitle')}
|
||||
desc={tr('folderShareDesc')}
|
||||
disabled={folderBusy || !!detail.guest_tools_disabled}
|
||||
control={
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<FolderPlus size={14} aria-hidden="true" />}
|
||||
busy={folderBusy}
|
||||
disabled={!folderSettings || folderBusy || !!detail.guest_tools_disabled}
|
||||
onClick={() => void handleAddFolder()}
|
||||
>
|
||||
{tr('folderShareAdd')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{folderErr && <div className="notice" role="alert">{folderErr}</div>}
|
||||
{folderSettings &&
|
||||
folderSettings.folders.some((f) => f.enabled && f.available) &&
|
||||
toolsVersion > 0 &&
|
||||
toolsVersion < folderSettings.required_agent_version && (
|
||||
<div className="notice">{tr('folderShareNeedsTools', { version: folderSettings.required_agent_version })}</div>
|
||||
)}
|
||||
{folderSettings && folderSettings.folders.length === 0 && (
|
||||
<SetValue title={tr('folderShareListTitle')} value={tr('folderShareEmpty')} />
|
||||
)}
|
||||
{folderSettings?.folders.map((folder) => {
|
||||
const mode: SharedFolderMode = !folder.enabled ? 'disabled' : folder.writable ? 'rw' : 'ro'
|
||||
const activeMode: SharedFolderMode | undefined = folder.available ? mode : (!folder.enabled ? 'disabled' : undefined)
|
||||
const issueText = !folder.available ? formatFolderIssue(folder.issue) : ''
|
||||
return (
|
||||
<SetRow
|
||||
key={folder.id}
|
||||
title={folder.name}
|
||||
desc={
|
||||
<>
|
||||
<code className="inline-code folder-path" title={folder.host_path}>{folder.host_path}</code>
|
||||
{issueText && <div className="warn-text">{issueText}</div>}
|
||||
{!issueText && folder.enabled && folder.writable && (
|
||||
<div className="warn-text">{tr('folderShareWritableWarn')}</div>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
disabled={folderBusy || !!detail.guest_tools_disabled}
|
||||
control={
|
||||
<div className="hstack">
|
||||
<Segmented<SharedFolderMode>
|
||||
label={folder.name}
|
||||
value={activeMode}
|
||||
options={[
|
||||
{ value: 'disabled', label: tr('folderShareModeDisabled') },
|
||||
{ value: 'ro', label: tr('folderShareModeRO'), disabled: !folder.available },
|
||||
{ value: 'rw', label: tr('folderShareModeRW'), disabled: !folder.available },
|
||||
]}
|
||||
onChange={(nextMode) => {
|
||||
if (nextMode === activeMode) return
|
||||
if (nextMode === 'rw') {
|
||||
setConfirmRWFolder(folder)
|
||||
return
|
||||
}
|
||||
void updateFolderMode(folder.id, nextMode)
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
small
|
||||
label={tr('folderShareRemove')}
|
||||
icon={<Trash2 size={13} />}
|
||||
disabled={folderBusy || !!detail.guest_tools_disabled}
|
||||
onClick={() => void handleRemoveFolder(folder.id)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
|
||||
/** Asks before the VM may change files in a shared folder. */
|
||||
export const WritableFolderDialog: React.FC<{ locale: Locale; state: ReturnType<typeof useSharedFolders> }> = ({ locale, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { confirmRWFolder, setConfirmRWFolder, updateFolderMode } = state
|
||||
if (!confirmRWFolder) return null
|
||||
return (
|
||||
<Alert.Root open onOpenChange={(open) => { if (!open) setConfirmRWFolder(null) }}>
|
||||
<Alert.Portal>
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
|
||||
<div className="dialog-body">
|
||||
<Alert.Title className="dialog-title">{tr('folderShareConfirmRWTitle')}</Alert.Title>
|
||||
<Alert.Description className="dialog-desc">
|
||||
{tr('folderShareConfirmRWDesc', { name: confirmRWFolder.name, path: confirmRWFolder.host_path })}
|
||||
</Alert.Description>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild>
|
||||
<button type="button" className="btn rg-p-button">{tr('cancel')}</button>
|
||||
</Alert.Cancel>
|
||||
<Alert.Action asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="btn rg-p-button btn-primary"
|
||||
onClick={() => {
|
||||
const target = confirmRWFolder
|
||||
setConfirmRWFolder(null)
|
||||
void updateFolderMode(target.id, 'rw')
|
||||
}}
|
||||
>
|
||||
{tr('folderShareConfirmRWAction')}
|
||||
</button>
|
||||
</Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
</Alert.Root>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import { Copy, Eye, EyeOff, Shuffle } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { Locale, SMBIOSIdentity, VMDetail } from '../../types'
|
||||
import { Button, IconButton } from '../../ui/controls'
|
||||
import { Modal } from '../../ui/dialog'
|
||||
import { SetGroup, SetRow, SetValue } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
function maskIdentity(v: string | undefined, head = 4, tail = 4): string {
|
||||
const s = (v ?? '').trim()
|
||||
if (!s) return '—'
|
||||
if (s.length <= head + tail) return '•'.repeat(s.length)
|
||||
return `${s.slice(0, head)}••••${s.slice(-tail)}`
|
||||
}
|
||||
|
||||
/** The VM's SMBIOS identity and the dialog that replaces it. */
|
||||
export function useSMBIOS(detail: VMDetail, running: boolean) {
|
||||
const [smbios, setSmbios] = useState<SMBIOSIdentity | null>(null)
|
||||
const [smbiosErr, setSmbiosErr] = useState('')
|
||||
const [smbiosReveal, setSmbiosReveal] = useState(false)
|
||||
const [smbiosOpen, setSmbiosOpen] = useState(false)
|
||||
const [smbiosDraft, setSmbiosDraft] = useState<SMBIOSIdentity | null>(null)
|
||||
const [smbiosBusy, setSmbiosBusy] = useState<'' | 'generate' | 'apply'>('')
|
||||
const [smbiosModalErr, setSmbiosModalErr] = useState('')
|
||||
const [smbiosApplied, setSmbiosApplied] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setSmbios(null)
|
||||
setSmbiosErr('')
|
||||
setSmbiosReveal(false)
|
||||
setSmbiosApplied(false)
|
||||
if (!detail.has_opencore) return () => { active = false }
|
||||
api.GetVMSMBIOS(detail.name)
|
||||
.then((id) => { if (active) setSmbios(id) })
|
||||
.catch((e) => { if (active) setSmbiosErr(parseAppError(e).summary) })
|
||||
return () => { active = false }
|
||||
}, [detail.name, detail.has_opencore])
|
||||
|
||||
const smbiosLocked = running || detail.state === 'suspended' || !!detail.suspend_info
|
||||
|
||||
const handleGenerateSmbios = async (modelOverride?: string) => {
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosBusy('generate')
|
||||
try {
|
||||
const generated = await api.GenerateVMSMBIOS(modelOverride ?? smbios?.model ?? '')
|
||||
setSmbiosDraft({
|
||||
model: smbios?.model || generated.model,
|
||||
serial: generated.serial,
|
||||
mlb: generated.mlb,
|
||||
uuid: generated.uuid,
|
||||
rom: smbios?.rom || '',
|
||||
})
|
||||
} catch (e) {
|
||||
setSmbiosModalErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setSmbiosBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const openSmbiosRotate = () => {
|
||||
if (smbiosLocked) return
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosApplied(false)
|
||||
setSmbiosOpen(true)
|
||||
void handleGenerateSmbios(smbios?.model ?? '')
|
||||
}
|
||||
|
||||
const handleApplySmbios = async () => {
|
||||
if (smbiosLocked || smbiosBusy || !smbiosDraft) return
|
||||
setSmbiosModalErr('')
|
||||
setSmbiosBusy('apply')
|
||||
try {
|
||||
const updated = await api.ApplyVMSMBIOS(detail.name, {
|
||||
model: smbios?.model || smbiosDraft.model || '',
|
||||
serial: smbiosDraft.serial,
|
||||
mlb: smbiosDraft.mlb,
|
||||
uuid: smbiosDraft.uuid,
|
||||
rom: smbios?.rom || '',
|
||||
})
|
||||
setSmbios(updated)
|
||||
setSmbiosOpen(false)
|
||||
setSmbiosApplied(true)
|
||||
} catch (e) {
|
||||
setSmbiosModalErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setSmbiosBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
smbios, smbiosErr, smbiosReveal, setSmbiosReveal, smbiosOpen, setSmbiosOpen, smbiosDraft,
|
||||
setSmbiosDraft, smbiosBusy, smbiosModalErr, smbiosApplied, smbiosLocked, openSmbiosRotate,
|
||||
handleGenerateSmbios, handleApplySmbios,
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
state: ReturnType<typeof useSMBIOS>
|
||||
onCopy?: (text: string) => void
|
||||
}
|
||||
|
||||
export const SMBIOSSection: React.FC<Props> = ({ locale, state, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { smbios, smbiosErr, smbiosReveal, setSmbiosReveal, smbiosApplied, smbiosLocked, openSmbiosRotate } = state
|
||||
return (
|
||||
<SetGroup title={tr('smbiosTitle')} note={tr('smbiosCheckHint')}>
|
||||
<SetRow
|
||||
title={tr('smbiosTitle')}
|
||||
desc={tr('smbiosDesc')}
|
||||
disabled={smbiosLocked}
|
||||
reason={tr('smbiosStopRequired')}
|
||||
control={
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<Shuffle size={13} aria-hidden="true" />}
|
||||
disabled={smbiosLocked || !smbios}
|
||||
onClick={openSmbiosRotate}
|
||||
>
|
||||
{tr('smbiosRotateBtn')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{smbiosErr && <div className="notice notice-error" role="alert">{tr('smbiosLoadFailed')}: {smbiosErr}</div>}
|
||||
{smbiosApplied && <div className="notice" role="status">{tr('smbiosApplied')}</div>}
|
||||
{smbios && (
|
||||
<>
|
||||
<SetValue title={tr('smbiosModel')} value={smbios.model || '—'} mono />
|
||||
<SetValue
|
||||
title={tr('smbiosSerial')}
|
||||
mono
|
||||
value={
|
||||
<span className="hstack">
|
||||
<span>{smbiosReveal ? smbios.serial : maskIdentity(smbios.serial, 4, 4)}</span>
|
||||
<IconButton
|
||||
small
|
||||
label={smbiosReveal ? tr('smbiosHide') : tr('smbiosShow')}
|
||||
icon={smbiosReveal ? <EyeOff size={13} /> : <Eye size={13} />}
|
||||
onClick={() => setSmbiosReveal((v) => !v)}
|
||||
/>
|
||||
{onCopy && (
|
||||
<IconButton
|
||||
small
|
||||
label={tr('smbiosCopySerial')}
|
||||
icon={<Copy size={13} />}
|
||||
onClick={() => onCopy(smbios.serial)}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<SetValue title={tr('smbiosMLB')} value={smbiosReveal ? smbios.mlb : maskIdentity(smbios.mlb, 4, 4)} mono />
|
||||
<SetValue title={tr('smbiosUUID')} value={smbiosReveal ? smbios.uuid : maskIdentity(smbios.uuid, 4, 4)} mono />
|
||||
{smbios.rom && <SetValue title={tr('smbiosROM')} value={smbiosReveal ? smbios.rom : maskIdentity(smbios.rom, 5, 5)} mono />}
|
||||
</>
|
||||
)}
|
||||
</SetGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export const SMBIOSDialog: React.FC<Props> = ({ locale, state, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { smbios, setSmbiosOpen, smbiosDraft, setSmbiosDraft, smbiosBusy, smbiosModalErr, smbiosLocked, handleGenerateSmbios, handleApplySmbios } = state
|
||||
return (
|
||||
<Modal
|
||||
title={tr('smbiosDialogTitle')}
|
||||
subtitle={tr('smbiosDialogSub')}
|
||||
closeLabel={tr('close')}
|
||||
dismissable={smbiosBusy !== 'apply'}
|
||||
onClose={() => setSmbiosOpen(false)}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<div className="notice">
|
||||
<span className="warn-text">{tr('smbiosWarning')}</span>
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<Shuffle size={13} aria-hidden="true" />}
|
||||
busy={smbiosBusy === 'generate'}
|
||||
disabled={smbiosBusy === 'apply'}
|
||||
onClick={() => void handleGenerateSmbios(smbios?.model ?? '')}
|
||||
>
|
||||
{tr('smbiosGenerate')}
|
||||
</Button>
|
||||
{onCopy && smbiosDraft?.serial && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<Copy size={13} aria-hidden="true" />}
|
||||
disabled={!!smbiosBusy}
|
||||
onClick={() => onCopy(smbiosDraft.serial)}
|
||||
>
|
||||
{tr('smbiosCopySerial')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosSerial')}</span>
|
||||
<input
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={12}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.serial ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: e.target.value.toUpperCase(),
|
||||
mlb: prev?.mlb ?? '',
|
||||
uuid: prev?.uuid ?? '',
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosMLB')}</span>
|
||||
<input
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={17}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.mlb ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: prev?.serial ?? '',
|
||||
mlb: e.target.value.toUpperCase(),
|
||||
uuid: prev?.uuid ?? '',
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">{tr('smbiosUUID')}</span>
|
||||
<input
|
||||
className="input rg-p-input mono"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
maxLength={36}
|
||||
disabled={!!smbiosBusy}
|
||||
value={smbiosDraft?.uuid ?? ''}
|
||||
onChange={(e) => setSmbiosDraft((prev) => ({
|
||||
model: prev?.model ?? smbios?.model ?? '',
|
||||
serial: prev?.serial ?? '',
|
||||
mlb: prev?.mlb ?? '',
|
||||
uuid: e.target.value.toUpperCase(),
|
||||
rom: prev?.rom ?? smbios?.rom ?? '',
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
{smbios?.rom && (
|
||||
<div className="srow-desc">
|
||||
{tr('smbiosROM')}: <code className="inline-code">{smbios.rom}</code>
|
||||
</div>
|
||||
)}
|
||||
<div className="srow-desc">{tr('smbiosCheckHint')}</div>
|
||||
{smbiosModalErr && <div className="notice notice-error" role="alert">{smbiosModalErr}</div>}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" disabled={smbiosBusy === 'apply'} onClick={() => setSmbiosOpen(false)}>
|
||||
{tr('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={smbiosBusy === 'apply'}
|
||||
disabled={smbiosLocked || smbiosBusy === 'generate' || !smbiosDraft?.serial.trim() || !smbiosDraft?.mlb.trim() || !smbiosDraft?.uuid.trim()}
|
||||
onClick={() => void handleApplySmbios()}
|
||||
>
|
||||
{tr('smbiosApply')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { app as WailsApp } from '../../../wailsjs/go/models'
|
||||
import { I18nKey, parseAppError, t } from '../../i18n'
|
||||
import { humanDisplayFallbackName, humanDisplayMeta, humanDisplayTitle, sortDisplaysForPicker } from '../../lib/format'
|
||||
import { DisplayInfo, HostReport, Locale } from '../../types'
|
||||
import { PopupSelect, SetRow } from '../../ui/settings'
|
||||
import { errorToast, type ToastInput } from '../../ui/toast'
|
||||
import { api } from '../../wails'
|
||||
|
||||
const PRIMARY_DISPLAY_OPT = '__primary'
|
||||
|
||||
interface Options {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
vm: string
|
||||
running: boolean
|
||||
host: HostReport
|
||||
shown: boolean
|
||||
isBlocked: () => boolean
|
||||
onToast: (toast: ToastInput) => void
|
||||
}
|
||||
|
||||
/** The host display the VM window opens on. A change applies at once. */
|
||||
export function useTargetDisplay({ locale, driverID, vm, running, host, shown, isBlocked, onToast }: Options) {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const activeVMNameRef = useRef(vm)
|
||||
activeVMNameRef.current = vm
|
||||
const [displayStatus, setDisplayStatus] = useState<WailsApp.VMDisplayStatus | null>(null)
|
||||
const [displayBusy, setDisplayBusy] = useState(false)
|
||||
const [displayErr, setDisplayErr] = useState('')
|
||||
const displayBusyRef = useRef(false)
|
||||
const displayReqSeqRef = useRef(0)
|
||||
|
||||
const connectedDisplays = useMemo<DisplayInfo[]>(
|
||||
() => sortDisplaysForPicker(displayStatus?.displays ?? host.displays ?? []),
|
||||
[displayStatus, host.displays],
|
||||
)
|
||||
const activeTargetDisplay = displayStatus
|
||||
? connectedDisplays.find((d) => d.name === displayStatus.effective_display)
|
||||
: host.primary_display
|
||||
const displayProfile = useMemo(() => displayStatus ? {
|
||||
...host,
|
||||
primary_display: activeTargetDisplay,
|
||||
display_presets: displayStatus.display_presets,
|
||||
fullscreen_hidpi: displayStatus.fullscreen_hidpi,
|
||||
hidpi_advice: displayStatus.hidpi_advice,
|
||||
recommended_resolution: undefined,
|
||||
} : host, [host, displayStatus, activeTargetDisplay])
|
||||
|
||||
const hostDisplaysSig = (host.displays ?? [])
|
||||
.map((d) => `${d.name ?? ''}:${d.friendly_name ?? ''}:${d.width}x${d.height}@${d.scale_pct}:${d.refresh_hz ?? 0}:${d.work_width ?? 0}x${d.work_height ?? 0}:${d.primary ? 1 : 0}`)
|
||||
.join('|')
|
||||
|
||||
useEffect(() => {
|
||||
displayReqSeqRef.current += 1
|
||||
displayBusyRef.current = false
|
||||
setDisplayStatus(null)
|
||||
setDisplayBusy(false)
|
||||
setDisplayErr('')
|
||||
}, [driverID, vm])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
const reqSeq = displayReqSeqRef.current
|
||||
if (displayBusyRef.current) return () => { active = false }
|
||||
api.GetVMDisplay(driverID, vm)
|
||||
.then((st) => {
|
||||
if (active && displayReqSeqRef.current === reqSeq) {
|
||||
setDisplayStatus(st)
|
||||
setDisplayErr('')
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (active && displayReqSeqRef.current === reqSeq) {
|
||||
setDisplayErr(parseAppError(e).summary)
|
||||
}
|
||||
})
|
||||
return () => { active = false }
|
||||
}, [driverID, vm, running, hostDisplaysSig, shown])
|
||||
|
||||
const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n })
|
||||
|
||||
const displayOptions = useMemo(() => {
|
||||
const opts: Array<{ value: string; label: string; detail?: string }> = [
|
||||
{
|
||||
value: PRIMARY_DISPLAY_OPT,
|
||||
label: tr('targetDisplayPrimaryDefault'),
|
||||
},
|
||||
...connectedDisplays
|
||||
.filter((d): d is DisplayInfo & { name: string } => Boolean(d.name?.trim()))
|
||||
.map((d, idx) => ({
|
||||
value: d.name,
|
||||
label: humanDisplayTitle(d, idx + 1, numberedDisplay),
|
||||
detail: humanDisplayMeta(d, d.primary ? tr('hostDisplayPrimary') : undefined),
|
||||
})),
|
||||
]
|
||||
const savedTarget = displayStatus?.target_display?.trim()
|
||||
if (savedTarget && displayStatus?.fallback_to_primary) {
|
||||
if (!opts.some((o) => o.value.toLowerCase() === savedTarget.toLowerCase())) {
|
||||
opts.push({
|
||||
value: savedTarget,
|
||||
label: humanDisplayFallbackName(savedTarget, numberedDisplay),
|
||||
detail: tr('targetDisplayDisconnectedOption'),
|
||||
})
|
||||
}
|
||||
}
|
||||
return opts
|
||||
}, [connectedDisplays, displayStatus?.fallback_to_primary, displayStatus?.target_display, locale])
|
||||
const selectedDisplayValue = useMemo(() => {
|
||||
const saved = displayStatus?.target_display?.trim()
|
||||
if (!saved) return PRIMARY_DISPLAY_OPT
|
||||
return displayOptions.find((o) => o.value.toLowerCase() === saved.toLowerCase())?.value ?? saved
|
||||
}, [displayOptions, displayStatus?.target_display])
|
||||
const activeTargetDisplayTitle = useMemo(() => {
|
||||
if (!activeTargetDisplay) return ''
|
||||
const idx = connectedDisplays.findIndex((d) => d === activeTargetDisplay || (d.name && activeTargetDisplay.name && d.name.toLowerCase() === activeTargetDisplay.name.toLowerCase()))
|
||||
return humanDisplayTitle(activeTargetDisplay, idx >= 0 ? idx + 1 : 1, numberedDisplay)
|
||||
}, [activeTargetDisplay, connectedDisplays, locale])
|
||||
const handleTargetDisplayChange = async (nextValue: string) => {
|
||||
if (isBlocked() || displayBusyRef.current || displayStatus === null) return
|
||||
const nextTarget = nextValue === PRIMARY_DISPLAY_OPT ? '' : nextValue
|
||||
const currentTarget = displayStatus.target_display ?? ''
|
||||
if (nextTarget.toLowerCase() === currentTarget.toLowerCase()) return
|
||||
|
||||
const opSeq = ++displayReqSeqRef.current
|
||||
displayBusyRef.current = true
|
||||
setDisplayBusy(true)
|
||||
setDisplayErr('')
|
||||
try {
|
||||
const next = await api.SetVMDisplay(driverID, vm, nextTarget)
|
||||
if (activeVMNameRef.current !== vm || displayReqSeqRef.current !== opSeq) return
|
||||
setDisplayStatus(next)
|
||||
const chosenLabel = displayOptions.find((o) => o.value === nextValue)?.label
|
||||
?? humanDisplayFallbackName(next.target_display, numberedDisplay)
|
||||
if (next.move_error) {
|
||||
onToast(errorToast(locale, tr('targetDisplayToastSaved', { display: chosenLabel }), next.move_error))
|
||||
} else {
|
||||
onToast({
|
||||
kind: 'ok',
|
||||
title: next.applied_live
|
||||
? tr('targetDisplayToastMoved', { display: chosenLabel })
|
||||
: tr('targetDisplayToastSaved', { display: chosenLabel }),
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current !== vm || displayReqSeqRef.current !== opSeq) return
|
||||
onToast(errorToast(locale, tr('targetDisplaySaveFailed'), e))
|
||||
} finally {
|
||||
if (displayReqSeqRef.current === opSeq) {
|
||||
displayBusyRef.current = false
|
||||
setDisplayBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
displayStatus, displayBusy, displayErr, connectedDisplays, activeTargetDisplay,
|
||||
activeTargetDisplayTitle, displayProfile, displayOptions, selectedDisplayValue, handleTargetDisplayChange,
|
||||
/** Whether a change is being saved right now, ahead of the next render. */
|
||||
isBusy: () => displayBusyRef.current,
|
||||
}
|
||||
}
|
||||
|
||||
interface RowProps {
|
||||
locale: Locale
|
||||
running: boolean
|
||||
disabled: boolean
|
||||
state: ReturnType<typeof useTargetDisplay>
|
||||
}
|
||||
|
||||
export const TargetDisplayRow: React.FC<RowProps> = ({ locale, running, disabled, state }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { displayStatus, displayBusy, displayErr, connectedDisplays, displayOptions, selectedDisplayValue, handleTargetDisplayChange } = state
|
||||
const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n })
|
||||
const targetDisplayDesc = displayStatus?.fallback_to_primary && displayStatus.target_display
|
||||
? (
|
||||
<span className="warn-text">
|
||||
{tr('targetDisplayFallbackHint', {
|
||||
name: humanDisplayFallbackName(displayStatus.target_display, numberedDisplay),
|
||||
})}
|
||||
</span>
|
||||
)
|
||||
: connectedDisplays.length === 0
|
||||
? tr('targetDisplayNoneHint')
|
||||
: connectedDisplays.length === 1
|
||||
? tr('targetDisplaySingleHint')
|
||||
: tr(running ? 'targetDisplayRunningHint' : 'targetDisplayStoppedHint')
|
||||
return (
|
||||
<SetRow
|
||||
title={tr('targetDisplayTitle')}
|
||||
desc={targetDisplayDesc}
|
||||
error={displayErr || undefined}
|
||||
disabled={disabled || displayBusy || displayStatus === null || (connectedDisplays.length === 0 && !displayStatus.target_display)}
|
||||
control={
|
||||
<PopupSelect
|
||||
label={tr('targetDisplayTitle')}
|
||||
value={selectedDisplayValue}
|
||||
onChange={(v) => void handleTargetDisplayChange(v)}
|
||||
options={displayOptions}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { Check, Copy } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { createVMSettingRequests, type VMSettingState } from '../../lib/vmSettingRequests'
|
||||
import { Locale, VMDetail } from '../../types'
|
||||
import { IconButton } from '../../ui/controls'
|
||||
import { PopupSelect, SetRow } from '../../ui/settings'
|
||||
import type { ToastInput } from '../../ui/toast'
|
||||
import { api } from '../../wails'
|
||||
|
||||
type VMTimezoneStatus = Awaited<ReturnType<typeof api.GetVMTimezone>>
|
||||
|
||||
const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command'
|
||||
const GUEST_TIMEZONE_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Timezone.command'
|
||||
|
||||
const GUEST_TIMEZONE_PRESETS: ReadonlyArray<{ value: string; labelKey: I18nKey; detail?: string }> = [
|
||||
{ value: 'Asia/Shanghai', labelKey: 'guestTimezoneShanghai', detail: 'Asia/Shanghai' },
|
||||
{ value: 'Asia/Hong_Kong', labelKey: 'guestTimezoneHongKong', detail: 'Asia/Hong_Kong' },
|
||||
{ value: 'Asia/Taipei', labelKey: 'guestTimezoneTaipei', detail: 'Asia/Taipei' },
|
||||
{ value: 'Asia/Tokyo', labelKey: 'guestTimezoneTokyo', detail: 'Asia/Tokyo' },
|
||||
{ value: 'Asia/Seoul', labelKey: 'guestTimezoneSeoul', detail: 'Asia/Seoul' },
|
||||
{ value: 'Asia/Singapore', labelKey: 'guestTimezoneSingapore', detail: 'Asia/Singapore' },
|
||||
{ value: 'Europe/London', labelKey: 'guestTimezoneLondon', detail: 'Europe/London' },
|
||||
{ value: 'Europe/Berlin', labelKey: 'guestTimezoneBerlin', detail: 'Europe/Berlin' },
|
||||
{ value: 'America/Los_Angeles', labelKey: 'guestTimezoneLosAngeles', detail: 'America/Los_Angeles' },
|
||||
{ value: 'America/New_York', labelKey: 'guestTimezoneNewYork', detail: 'America/New_York' },
|
||||
{ value: 'Australia/Sydney', labelKey: 'guestTimezoneSydney', detail: 'Australia/Sydney' },
|
||||
{ value: 'UTC', labelKey: 'guestTimezoneUTC' },
|
||||
]
|
||||
|
||||
/** The time zone the VM follows, refreshed while shown. */
|
||||
export function useGuestTimezone(driverID: string, vm: string, running: boolean, shown: boolean) {
|
||||
const vmSettingsKey = `${driverID}:${vm}`
|
||||
const activeVMKeyRef = useRef(vmSettingsKey)
|
||||
activeVMKeyRef.current = vmSettingsKey
|
||||
const [{ value: tzStatus, error: tzErr, busy: tzBusy }, setTzState] = useState<VMSettingState<VMTimezoneStatus>>({ value: null, error: '', busy: false })
|
||||
const [tzRequests] = useState(() => createVMSettingRequests<VMTimezoneStatus>(() => activeVMKeyRef.current,
|
||||
(patch) => setTzState((state) => ({ ...state, ...patch }))))
|
||||
|
||||
useEffect(() => {
|
||||
setTzState({ value: null, error: '', busy: tzRequests.isWriting(vmSettingsKey) })
|
||||
}, [vmSettingsKey, tzRequests])
|
||||
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const { refresh, stop } = tzRequests.watch(vmSettingsKey, () => api.GetVMTimezone(driverID, vm))
|
||||
void refresh()
|
||||
const timer = window.setInterval(refresh, 3000)
|
||||
return () => { stop(); window.clearInterval(timer) }
|
||||
}, [shown, driverID, vm, running, vmSettingsKey, tzRequests])
|
||||
|
||||
return {
|
||||
tzStatus,
|
||||
tzErr,
|
||||
tzBusy,
|
||||
/** Whether a change is being saved right now, ahead of the next render. */
|
||||
isWriting: () => tzRequests.isWriting(vmSettingsKey),
|
||||
write: (setting: string) => tzRequests.write(vmSettingsKey, () => api.SetVMTimezone(driverID, vm, setting)),
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
detail: VMDetail
|
||||
hostTimezone?: string
|
||||
state: ReturnType<typeof useGuestTimezone>
|
||||
disabled: boolean
|
||||
isBlocked: () => boolean
|
||||
onToast: (toast: ToastInput) => void
|
||||
onCopy?: (text: string) => void
|
||||
}
|
||||
|
||||
export const GuestTimezoneRow: React.FC<Props> = ({ locale, detail, hostTimezone, state, disabled, isBlocked, onToast, onCopy }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { tzStatus, tzErr, tzBusy, write } = state
|
||||
|
||||
const updateTimezone = async (nextSetting: string) => {
|
||||
if (isBlocked() || !tzStatus) return
|
||||
const currentSetting = tzStatus.mode === 'off' ? 'off' : tzStatus.mode === 'custom' ? tzStatus.timezone : 'host'
|
||||
if (nextSetting === currentSetting) return
|
||||
if (await write(nextSetting)) {
|
||||
onToast({ kind: 'ok', title: tr('guestTimezoneSaved') })
|
||||
}
|
||||
}
|
||||
|
||||
const detectedHostTZ = tzStatus?.host_timezone || hostTimezone || ''
|
||||
const tzSelectedValue = tzStatus?.mode === 'custom' ? tzStatus.timezone : tzStatus?.mode
|
||||
const tzOptions = [
|
||||
{ value: 'host', label: tr('guestTimezoneHost'), detail: detectedHostTZ || undefined },
|
||||
...GUEST_TIMEZONE_PRESETS.map((p) => ({
|
||||
value: p.value,
|
||||
label: tr(p.labelKey),
|
||||
detail: p.detail,
|
||||
})),
|
||||
...(tzStatus?.mode === 'custom' && tzStatus.timezone && !GUEST_TIMEZONE_PRESETS.some((p) => p.value === tzStatus.timezone)
|
||||
? [{ value: tzStatus.timezone, label: tzStatus.timezone }]
|
||||
: []),
|
||||
{ value: 'off', label: tr('guestTimezoneOff') },
|
||||
]
|
||||
let tzDesc: React.ReactNode = tr('guestTimezoneDesc')
|
||||
let tzCommand = ''
|
||||
if (tzStatus) {
|
||||
const tzEffective = tzStatus.effective_timezone
|
||||
if (tzStatus.mode === 'off') {
|
||||
tzDesc = tr('guestTimezoneOffDesc')
|
||||
} else if (detail.guest_tools_disabled) {
|
||||
tzDesc = <span className="warn-text">{tr('gtStatusOffTip')}</span>
|
||||
} else if (!tzEffective) {
|
||||
tzDesc = <span className="warn-text">{tr('guestTimezoneHostUnknown')}</span>
|
||||
} else if (tzStatus.running && tzStatus.guest_connected) {
|
||||
const tzFailure = tzStatus.timezone_error
|
||||
? <span className="warn-text">{tr('guestTimezoneApplyFailed', { tz: tzEffective })}</span>
|
||||
: null
|
||||
if (tzStatus.guest_agent_version < tzStatus.required_agent_version) {
|
||||
tzDesc = <span className="warn-text">{tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzStatus.required_agent_version })}</span>
|
||||
if (detail.guest_tools_attached) tzCommand = GUEST_TOOLS_INSTALL_CMD
|
||||
} else if (!tzStatus.helper_ready) {
|
||||
const hint = tr(detail.guest_tools_attached ? 'guestTimezoneApplyHint' : 'guestTimezoneApplyAttachHint')
|
||||
tzDesc = tzFailure ? <div className="stack-1">{tzFailure}<span>{hint}</span></div> : hint
|
||||
if (detail.guest_tools_attached) tzCommand = GUEST_TIMEZONE_APPLY_CMD
|
||||
} else if (tzFailure) {
|
||||
tzDesc = tzFailure
|
||||
} else if (tzStatus.guest_applied === tzEffective) {
|
||||
tzDesc = <span className="ok-text"><Check size={12} aria-hidden="true" />{tr('guestTimezoneSynced', { tz: tzEffective })}</span>
|
||||
} else {
|
||||
tzDesc = tr('guestTimezoneSyncing', { tz: tzEffective })
|
||||
}
|
||||
} else if (detail.guest_tools_attached) {
|
||||
tzCommand = GUEST_TOOLS_INSTALL_CMD
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SetRow
|
||||
title={tr('guestTimezoneTitle')}
|
||||
desc={tzDesc}
|
||||
disabled={!tzStatus || tzBusy || disabled}
|
||||
error={tzErr || undefined}
|
||||
control={
|
||||
<PopupSelect
|
||||
label={tr('guestTimezoneTitle')}
|
||||
value={tzSelectedValue}
|
||||
placeholder={tr('guestTimezoneLoading')}
|
||||
onChange={updateTimezone}
|
||||
options={tzOptions}
|
||||
/>
|
||||
}
|
||||
block={tzCommand ? (
|
||||
<div className="cmd-line">
|
||||
<code>{tzCommand}</code>
|
||||
{onCopy && (
|
||||
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(tzCommand)} />
|
||||
)}
|
||||
</div>
|
||||
) : undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user