Merge upstream target monitor selection and retain Npcap bindings

This commit is contained in:
root committed 2026-12-01 22:55:21 +08:00
commit af45f7f029
28 files changed
+1462 -99

No files matched your search

+1
View File
@@ -1358,6 +1358,7 @@ export const App: React.FC = () => {
onOpenAffinity={() => setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })}
affinityVersion={affinityVersion}
onHostChanged={refresh}
onToast={toasts.push}
onClose={() => setShowSettings(false)}
onSaved={() => {
setShowSettings(false)
+204 -25
View File
@@ -11,6 +11,9 @@ import {
formatBytes,
gpuCompatHint,
gpuOptionValue,
humanDisplayFallbackName,
humanDisplayMeta,
humanDisplayTitle,
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
@@ -23,15 +26,18 @@ import {
recommendedMemoryGB,
recommendedResolution,
shortGPUName,
sortDisplaysForPicker,
sshCommand,
} from '../lib/format'
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
import { useVMStats } from '../lib/vmStats'
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, SMBIOSIdentity, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
import { DiskCompactResult, DiskResizeResult, DisplayInfo, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, SMBIOSIdentity, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
import type { ToastInput } from '../ui/toast'
import { api } from '../wails'
import type { app as WailsApp } from '../../wailsjs/go/models'
import { formatAffinitySummary } from './AffinityDialog'
import { VMNetworkSettings } from './VMNetworkSettings'
import type { VMKeymapPreset, VMKeymapHostModifier, VMKeymapGuestModifier, VMKeymapStatus, VMKeymapUpdate } from '../types'
@@ -80,6 +86,7 @@ const FIELDS = Object.keys(FIELD_CAT) as Field[]
const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
const CUSTOM = '__custom'
const PRIMARY_DISPLAY_OPT = '__primary'
const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i
const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase()
@@ -146,11 +153,12 @@ interface Props {
affinityVersion?: number
/** Re-probe the host, e.g. after Windows' processor scheduling may have changed. */
onHostChanged?: () => void
onToast: (toast: ToastInput) => void
onClose: () => void
onSaved: () => void
}
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onClose, onSaved }) => {
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
const base = useMemo(() => baseline(detail, host), [detail, host])
@@ -181,6 +189,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const gtConnected = liveStats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
const gtAgentVersion = liveStats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
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 [keymap, setKeymap] = useState<VMKeymapStatus | null>(null)
const [keymapErr, setKeymapErr] = useState('')
const [keymapBusy, setKeymapBusy] = useState(false)
@@ -240,11 +253,27 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
)
}
const presets = recommendedDisplayPresets(host)
const fsPresets = fullscreenDisplayPresets(host)
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 presets = recommendedDisplayPresets(displayProfile)
const fsPresets = fullscreenDisplayPresets(displayProfile)
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
const presetHit = activePresets.some((p) => same('resolution', p.resolution, form.resolution))
const [customRes, setCustomRes] = useState(!presetHit)
const [forceCustomRes, setCustomRes] = useState(false)
const customRes = forceCustomRes || !presetHit
const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level))
// The detail the panel opened with can be a stale one (reopened right after
@@ -254,10 +283,9 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
useEffect(() => {
if (edited.current) return
setForm(base)
const list = base.borderless ? fsPresets : presets
setCustomRes(!list.some((p) => same('resolution', p.resolution, base.resolution)))
setCustomRes(false)
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}, [base]) // presets come from host, which base already follows
}, [base])
const set = (patch: Partial<SetOpts>) => {
edited.current = true
@@ -268,12 +296,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const dirty = (f: Field) => !same(f, form[f], base[f])
const reset = (f: Field) => () => {
set({ [f]: base[f] } as Partial<SetOpts>)
if (f === 'resolution' || f === 'borderless') {
const nextBorderless = f === 'borderless' ? base.borderless : form.borderless
const nextRes = f === 'resolution' ? base.resolution : form.resolution
const list = nextBorderless ? fsPresets : presets
setCustomRes(!list.some((p) => same('resolution', p.resolution, nextRes)))
}
if (f === 'resolution' || f === 'borderless') setCustomRes(false)
if (f === 'log_level') setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
const changed = FIELDS.filter(dirty)
@@ -329,6 +352,37 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
return () => { active = false }
}, [detail.name, running, affinityVersion])
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, detail.name])
useEffect(() => {
let active = true
const reqSeq = displayReqSeqRef.current
if (displayBusyRef.current) return () => { active = false }
api.GetVMDisplayWithDriver(driverID, detail.name)
.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, detail.name, running, hostDisplaysSig, cat === 'display'])
useEffect(() => {
let active = true
setSmbios(null)
@@ -516,6 +570,59 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const handleRemoveFolder = (folderID: string) =>
runFolderOp((vmName) => api.RemoveVMSharedFolder(vmName, folderID))
const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n })
const displayErrorToast = (title: string, error: unknown) => {
const parsed = parseAppError(error)
onToast({
kind: 'error',
title,
description: parsed.summary,
errorCode: parsed.code,
rawDetail: parsed.rawDetail,
detailsLabel: tr('errRawDetailsToggle'),
copyDetailsLabel: tr('errCopyDetails'),
})
}
const handleTargetDisplayChange = async (nextValue: string) => {
if (busy || displayBusyRef.current || displayStatus === null) return
const nextTarget = nextValue === PRIMARY_DISPLAY_OPT ? '' : nextValue
const currentTarget = displayStatus.target_display ?? ''
if (nextTarget.toLowerCase() === currentTarget.toLowerCase()) return
const vmName = detail.name
const opSeq = ++displayReqSeqRef.current
displayBusyRef.current = true
setDisplayBusy(true)
setDisplayErr('')
try {
const next = await api.SetVMDisplayWithDriver(driverID, vmName, nextTarget)
if (activeVMNameRef.current !== vmName || displayReqSeqRef.current !== opSeq) return
setDisplayStatus(next)
const chosenLabel = displayOptions.find((o) => o.value === nextValue)?.label
?? humanDisplayFallbackName(next.target_display, numberedDisplay)
if (next.move_error) {
displayErrorToast(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 !== vmName || displayReqSeqRef.current !== opSeq) return
displayErrorToast(tr('targetDisplaySaveFailed'), e)
} finally {
if (displayReqSeqRef.current === opSeq) {
displayBusyRef.current = false
setDisplayBusy(false)
}
}
}
// Windows-wide, not staged with Save: one UAC prompt opens Windows' own
// Performance Options, and the new choice shows after the host refresh.
const [openingSched, setOpeningSched] = useState(false)
@@ -532,7 +639,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
}
const handleSave = async () => {
if (busy || changed.length === 0 || localBlock) return
if (busy || displayBusyRef.current || changed.length === 0 || localBlock) return
setErr('')
setIssues([])
setBusy(true)
@@ -559,7 +666,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
edited.current = false
setForm(base)
setIssues([])
setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
setCustomRes(false)
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
@@ -786,20 +893,71 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const selectedGPU = findGPU(host, form.gpu)
const selectedGPUHint = gpuCompatHint(locale, selectedGPU)
const vgpu = form.graphics !== 'vmware-svga'
const pd = host.primary_display
const hidpiAdvice = hostDisplayAdvice(host, tr)
const targetDisp = activeTargetDisplay
const hidpiAdvice = hostDisplayAdvice(displayProfile, tr)
const resValue = customRes ? CUSTOM : activePresets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
const toggleBorderless = (borderless: boolean) => {
const targetPresets = borderless ? fsPresets : presets
if (!customRes && !targetPresets.some((p) => same('resolution', p.resolution, form.resolution))) {
const nextRes = borderless
? (pd ? `${pd.width}x${pd.height}` : targetPresets[0]?.resolution ?? form.resolution)
: recommendedResolution(host)
? (targetDisp && targetDisp.width > 0 && targetDisp.height > 0
? `${targetDisp.width}x${targetDisp.height}`
: targetPresets[0]?.resolution ?? form.resolution)
: recommendedResolution(displayProfile)
set({ borderless, resolution: nextRes })
return
}
set({ borderless })
}
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 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')
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 resArt = (r: string) => {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
return m ? <ScreenArt w={Number(m[1])} h={Number(m[2])} /> : <ScreenArt w={16} h={10} />
@@ -855,6 +1013,20 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
/>
</SetGroup>
<SetGroup title={tr('displayGroup')}>
<SetRow
title={tr('targetDisplayTitle')}
desc={targetDisplayDesc}
error={displayErr || undefined}
disabled={busy || displayBusy || displayStatus === null || (connectedDisplays.length === 0 && !displayStatus.target_display)}
control={
<PopupSelect
label={tr('targetDisplayTitle')}
value={selectedDisplayValue}
onChange={(v) => void handleTargetDisplayChange(v)}
options={displayOptions}
/>
}
/>
<SetRow
{...rowProps('borderless')}
title={tr('fullscreenLaunch')}
@@ -865,7 +1037,14 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
{...rowProps('resolution')}
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
title={tr('resolution')}
desc={hostDisplayDesc(host, tr)}
desc={hostDisplayDesc(host, tr, activeTargetDisplay, (d) =>
tr('targetDisplayHint', {
name: activeTargetDisplayTitle,
w: d.width,
h: d.height,
scale: d.scale_pct || 100,
}),
)}
block={
<>
<OptionCards
@@ -909,7 +1088,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
<SetRow
{...rowProps('displays')}
title={tr('displays')}
desc={(host.displays?.length ?? 0) > 1 ? tr('multiDisplayHint', { n: host.displays?.length ?? 1 }) : undefined}
desc={connectedDisplays.length > 1 ? tr('multiDisplayHint', { n: connectedDisplays.length }) : undefined}
control={
<Segmented
label={tr('displays')}
@@ -1477,7 +1656,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
title={tr('settingsTitle', { name: detail.name })}
subtitle={`${tr(running ? 'state_running' : 'state_stopped')} · ${tr('appliesNextStart')}`}
closeLabel={tr('close')}
dismissable={!busy && !confirmRWFolder}
dismissable={!busy && !displayBusy && !confirmRWFolder}
onClose={onClose}
>
<div className="settings-split" onKeyDown={onKeyDown}>
@@ -1526,8 +1705,8 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
)}
</span>
<span className="hstack">
<Button variant="ghost" disabled={busy} onClick={onClose}>{tr('cancel')}</Button>
<Button variant="primary" busy={busy} disabled={changed.length === 0 || localBlock} onClick={handleSave} title="Ctrl+S">
<Button variant="ghost" disabled={busy || displayBusy} onClick={onClose}>{tr('cancel')}</Button>
<Button variant="primary" busy={busy} disabled={displayBusy || changed.length === 0 || localBlock} onClick={handleSave} title="Ctrl+S">
{tr('save')}
</Button>
</span>
+26
View File
@@ -427,6 +427,19 @@ export const settingsZh: Record<string, string> = {
"syncHostMemorySMBIOS": "同步宿主机内存规格",
"syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效",
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4",
"targetDisplayDisconnectedOption": "已断开 · 回退至主显示器",
"targetDisplayFallbackHint": "已保存的「{name}」当前未连接,将回退至主显示器",
"targetDisplayHint": "目标显示器:{name}({w}×{h},{scale}% 缩放)",
"targetDisplayNoneHint": "未检测到物理显示器,将使用默认窗口位置",
"targetDisplayNumbered": "显示器 {n}",
"targetDisplayPrimaryDefault": "主显示器(默认)",
"targetDisplayRunningHint": "运行中切换会立即移动虚拟机窗口,并用于下次启动",
"targetDisplaySaveFailed": "无法更新启动显示器",
"targetDisplaySingleHint": "当前仅检测到 1 块显示器;接入更多显示器后可指定启动屏幕",
"targetDisplayStoppedHint": "选择虚拟机窗口打开的物理显示器,下次启动生效",
"targetDisplayTitle": "启动显示器",
"targetDisplayToastMoved": "已切换至「{display}」",
"targetDisplayToastSaved": "启动显示器已设为「{display}」,下次启动生效",
"themeLabel": "外观",
"themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用",
"themePluginLightDisabled": "当前主题仅支持深色外观",
@@ -878,6 +891,19 @@ export const settingsEn: Record<string, string> = {
"syncHostMemorySMBIOS": "Sync host memory specs",
"syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start",
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4",
"targetDisplayDisconnectedOption": "Disconnected · using primary",
"targetDisplayFallbackHint": "Saved {name} is disconnected; falling back to the primary display",
"targetDisplayHint": "Target display: {name} ({w}×{h} at {scale}%)",
"targetDisplayNoneHint": "No physical displays detected; uses the default window position",
"targetDisplayNumbered": "Display {n}",
"targetDisplayPrimaryDefault": "Primary display (default)",
"targetDisplayRunningHint": "Switching while running moves the VM window right away and applies on next start",
"targetDisplaySaveFailed": "Could not update launch display",
"targetDisplaySingleHint": "Only 1 display detected; connect another display to choose a launch screen",
"targetDisplayStoppedHint": "Choose which physical display opens the VM window; applies on next start",
"targetDisplayTitle": "Launch display",
"targetDisplayToastMoved": "Switched to {display}",
"targetDisplayToastSaved": "Launch display set to {display}; applies on next start",
"themeLabel": "Appearance",
"themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable",
"themePluginLightDisabled": "The active theme supports dark appearance only",
+13
View File
@@ -943,6 +943,19 @@ export type I18nKey =
| "syncHostMemorySMBIOS"
| "syncHostMemorySMBIOSSub"
| "syncHostMemorySMBIOSUnavailable"
| "targetDisplayDisconnectedOption"
| "targetDisplayFallbackHint"
| "targetDisplayHint"
| "targetDisplayNoneHint"
| "targetDisplayNumbered"
| "targetDisplayPrimaryDefault"
| "targetDisplayRunningHint"
| "targetDisplaySaveFailed"
| "targetDisplaySingleHint"
| "targetDisplayStoppedHint"
| "targetDisplayTitle"
| "targetDisplayToastMoved"
| "targetDisplayToastSaved"
| "taskAppUpdate"
| "taskCreate"
| "taskDownload"
+63 -6
View File
@@ -1,6 +1,6 @@
import { I18nKey, t } from '../i18n'
import { formatLocaleNumber } from '../i18n/icu'
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
import { DisplayInfo, DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
function currentDocLocale(): string {
if (typeof document === 'undefined') return 'en-US'
@@ -217,12 +217,68 @@ const DEFAULT_DISPLAY_PRESETS: DisplayPreset[] = [
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: false },
]
/** Extract 1-based monitor index from Windows device names like `\\.\DISPLAY2`. */
function displayNumber(name: string | undefined, fallbackIndex = 1): number {
const m = /display(\d+)$/i.exec((name ?? '').trim())
return m ? Number(m[1]) : fallbackIndex
}
const GENERIC_MONITOR_RE = /^(?:generic\s+(?:non-)?pnp\s+monitor|generic\s+monitor|通用(?:非)?即插即用监视器)$/i
function cleanDisplayModel(friendlyName: string | undefined): string {
const s = (friendlyName ?? '').trim()
if (!s || /^\\\\\.\\/i.test(s) || GENERIC_MONITOR_RE.test(s)) return ''
return s
}
/** Human-readable display title such as "Display 1 · DELL U2723QE" or "Display 2". */
export function humanDisplayTitle(
d: Pick<DisplayInfo, 'name' | 'friendly_name'>,
fallbackIndex: number,
numberedLabel: (n: number) => string,
): string {
const base = numberedLabel(displayNumber(d.name, fallbackIndex))
const model = cleanDisplayModel(d.friendly_name)
return model ? `${base} · ${model}` : base
}
/** Human-readable fallback title for a disconnected saved target display string. */
export function humanDisplayFallbackName(rawName: string, numberedLabel: (n: number) => string): string {
return numberedLabel(displayNumber(rawName))
}
/** Concise specs for a physical display option: "2560 × 1440 · 144 Hz · 150% · Primary". */
export function humanDisplayMeta(d: DisplayInfo, primaryLabel?: string): string {
const parts: string[] = []
if (d.width > 0 && d.height > 0) parts.push(`${d.width} × ${d.height}`)
if (d.refresh_hz && d.refresh_hz > 0) parts.push(`${d.refresh_hz} Hz`)
parts.push(`${d.scale_pct || 100}%`)
if (d.primary && primaryLabel) parts.push(primaryLabel)
return parts.join(' · ')
}
/** Sort physical monitors by display number so Display 1, Display 2… appear in order. */
export function sortDisplaysForPicker(displays: DisplayInfo[]): DisplayInfo[] {
return displays
.map((d, idx) => ({ d, idx, num: displayNumber(d.name, idx + 1) }))
.sort((a, b) => a.num - b.num || Number(b.d.primary) - Number(a.d.primary) || a.idx - b.idx)
.map((x) => x.d)
}
type Tr = (k: I18nKey, v?: Record<string, string | number>) => string
// The resolution row's description: the main display and its scaling.
export function hostDisplayDesc(host: HostReport, tr: Tr): string | undefined {
const d = host.primary_display
if (!d) return undefined
// The resolution row's description: the target display (or main display) and its scaling.
export function hostDisplayDesc(
host: HostReport,
tr: Tr,
targetDisplay?: DisplayInfo,
formatNonPrimary?: (d: DisplayInfo) => string,
): string | undefined {
const d = targetDisplay ?? host.primary_display
if (!d || d.width <= 0 || d.height <= 0) return undefined
if (targetDisplay && !targetDisplay.primary && formatNonPrimary) {
return formatNonPrimary(d)
}
return tr('hostDisplayHint', { w: d.width, h: d.height, scale: d.scale_pct || 100 })
}
@@ -234,7 +290,8 @@ export function hostDisplayAdvice(host: HostReport, tr: Tr): string | undefined
scale: 'hidpiTipScale',
unavailable: 'hidpiTipUnavailable',
}
const key = host.hidpi_advice ? tip[host.hidpi_advice] : undefined
const adviceCode = host.hidpi_advice
const key = adviceCode ? tip[adviceCode] : undefined
return key ? tr(key) : undefined
}
+4
View File
@@ -135,6 +135,8 @@ export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise<app.VMA
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
export function GetVMDisplayWithDriver(arg1:string,arg2:string):Promise<app.VMDisplayStatus>;
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
@@ -301,6 +303,8 @@ export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app
export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMDisplayWithDriver(arg1:string,arg2:string,arg3:string):Promise<app.VMDisplayStatus>;
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise<app.VMKeymapStatus>;
+8
View File
@@ -250,6 +250,10 @@ export function GetVMDetail(arg1) {
return window['go']['app']['App']['GetVMDetail'](arg1);
}
export function GetVMDisplayWithDriver(arg1, arg2) {
return window['go']['app']['App']['GetVMDisplayWithDriver'](arg1, arg2);
}
export function GetVMDriveShareSettings(arg1) {
return window['go']['app']['App']['GetVMDriveShareSettings'](arg1);
}
@@ -582,6 +586,10 @@ export function SetVMAffinityWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMAffinityWithDriver'](arg1, arg2, arg3);
}
export function SetVMDisplayWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMDisplayWithDriver'](arg1, arg2, arg3);
}
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
}
+34
View File
@@ -515,6 +515,38 @@ export namespace app {
this.live_read_error = source["live_read_error"];
}
}
export class VMDisplayStatus {
target_display: string;
effective_display: string;
fallback_to_primary: boolean;
connected: boolean;
displays: host.DisplayInfo[];
display_presets: host.DisplayPreset[];
fullscreen_hidpi: boolean;
hidpi_advice: string;
running: boolean;
applied_live: boolean;
move_error?: string;
static createFrom(source: Partial<VMDisplayStatus> | string = {}) {
return new VMDisplayStatus(source);
}
constructor(source: Partial<VMDisplayStatus> | string = {}) {
const status: Partial<VMDisplayStatus> = (typeof source === "string" ? JSON.parse(source) : source) || {};
this.target_display = status.target_display ?? "";
this.effective_display = status.effective_display ?? "";
this.fallback_to_primary = status.fallback_to_primary ?? false;
this.connected = status.connected ?? false;
this.displays = (status.displays || []).map(display => new host.DisplayInfo(display));
this.display_presets = (status.display_presets || []).map(preset => new host.DisplayPreset(preset));
this.fullscreen_hidpi = status.fullscreen_hidpi ?? false;
this.hidpi_advice = status.hidpi_advice ?? "";
this.running = status.running ?? false;
this.applied_live = status.applied_live ?? false;
this.move_error = status.move_error;
}
}
export class VMAffinityUpdate {
mode: string;
cpus?: number[];
@@ -946,6 +978,7 @@ export namespace host {
}
export class DisplayInfo {
name?: string;
friendly_name?: string;
width: number;
height: number;
scale_pct: number;
@@ -961,6 +994,7 @@ export namespace host {
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.friendly_name = source["friendly_name"];
this.width = source["width"];
this.height = source["height"];
this.scale_pct = source["scale_pct"];
+6
View File
@@ -103,12 +103,14 @@ type App struct {
pendingChanges map[string][]PendingChange
rebootWatchers map[string]rebootWatcherEntry
nextWatcherID uint64
stopPoll context.CancelFunc
guestTools *guesttools.Server
guestToolsConfigLocks sync.Map
vmDeleteEpochs map[string]uint64
resolveFolderVolume func(string) (host.DirectoryVolume, error)
imeBridge *host.IMEBridge
trayMgr *tray.Manager
allowQuit bool
quitMode string
@@ -133,6 +135,9 @@ type App struct {
uiHealth uiHealthState
themeMode string
vmClosePrompts sync.Map
displayHost vmDisplayHost
displayPlacements sync.Map
keymapMu sync.Mutex
keymapPIDs map[string]int
@@ -169,6 +174,7 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
diskPaths: make(map[string]cachedDiskPath),
procSamples: make(map[string]host.ProcessSample),
uiHealth: uiHealthState{windowHidden: launch.Background},
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
}
return a, Lifecycle{
OnStartup: a.startup,
+251
View File
@@ -0,0 +1,251 @@
package app
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
)
type VMDisplayStatus struct {
TargetDisplay string `json:"target_display"`
EffectiveDisplay string `json:"effective_display"`
FallbackToPrimary bool `json:"fallback_to_primary"`
Connected bool `json:"connected"`
Displays []host.DisplayInfo `json:"displays"`
DisplayPresets []host.DisplayPreset `json:"display_presets"`
FullscreenHiDPI bool `json:"fullscreen_hidpi"`
HiDPIAdvice string `json:"hidpi_advice"`
Running bool `json:"running"`
AppliedLive bool `json:"applied_live"`
MoveError string `json:"move_error,omitempty"`
}
type vmDisplayHost struct {
displays func() []host.DisplayInfo
move func(pid uint32, displayName string, borderless bool) (bool, error)
}
type vmDisplayPlacement struct {
sync.Mutex
moveEpoch uint64
}
func (a *App) vmDisplayPlacement(ref driver.VMRef) *vmDisplayPlacement {
placement, _ := a.displayPlacements.LoadOrStore(ref.Key(), &vmDisplayPlacement{})
return placement.(*vmDisplayPlacement)
}
func buildVMDisplayStatus(vm driver.VMInfo, cfg vmstart.VMDisplayConfig, displays []host.DisplayInfo) VMDisplayStatus {
target, fallback := vmstart.ResolveTargetDisplay(cfg, displays)
if displays == nil {
displays = []host.DisplayInfo{}
}
presets, _ := host.RecommendDisplayPresets(target)
status := VMDisplayStatus{
TargetDisplay: cfg.TargetDisplay,
FallbackToPrimary: fallback,
Connected: target != nil && !fallback,
Displays: displays,
DisplayPresets: presets,
FullscreenHiDPI: host.FullscreenStartsHiDPI(target),
HiDPIAdvice: host.HiDPIAdvice(target, presets),
Running: vm.State == "running",
}
if target != nil {
status.EffectiveDisplay = target.Name
}
return status
}
func (a *App) GetVMDisplayWithDriver(driverID, name string) (VMDisplayStatus, error) {
vm, err := a.resolveVMInfo(driverID, name)
if err != nil {
return VMDisplayStatus{}, err
}
return buildVMDisplayStatus(vm, vmstart.ReadVMDisplay(vm.Directory), a.displayHost.displays()), nil
}
func (a *App) SetVMDisplayWithDriver(driverID, name, targetDisplay string) (VMDisplayStatus, error) {
if err := a.requireWritableDataRoot(); err != nil {
return VMDisplayStatus{}, err
}
vm, err := a.resolveVMInfo(driverID, name)
if err != nil {
return VMDisplayStatus{}, err
}
placement := a.vmDisplayPlacement(vm.Ref())
placement.Lock()
defer placement.Unlock()
displays := a.displayHost.displays()
cfg := vmstart.VMDisplayConfig{TargetDisplay: vmstart.NormalizeTargetDisplay(targetDisplay)}
status := buildVMDisplayStatus(vm, cfg, displays)
if status.FallbackToPrimary && !strings.EqualFold(cfg.TargetDisplay, vmstart.ReadVMDisplay(vm.Directory).TargetDisplay) {
return VMDisplayStatus{}, fmt.Errorf("%w: %q is not connected", host.ErrDisplayNotFound, cfg.TargetDisplay)
}
if _, err := vmstart.SaveVMDisplay(vm.Directory, cfg); err != nil {
return VMDisplayStatus{}, err
}
defer a.emitLifecycleStateChanged()
if !status.Running || len(displays) == 0 {
return status, nil
}
if status.FallbackToPrimary {
a.emitVMLogForDriver(vm.DriverID, vm.Name, displayFallbackLog(cfg.TargetDisplay))
}
pid := 0
if vm.PID != nil {
pid = *vm.PID
}
if pid <= 0 {
ctx := a.baseCtx()
pid, err = a.displayVMPID(ctx, vm.Ref())
if err == nil && pid <= 0 {
pid, err = a.liveDisplayVMPID(ctx, vm.Ref())
}
if err != nil {
status.MoveError = "Could not find VM display process: " + err.Error()
a.emitVMLogForDriver(vm.DriverID, vm.Name, status.MoveError)
return status, nil
}
}
if pid <= 0 {
a.emitVMLogForDriver(vm.DriverID, vm.Name, "Display window not ready. The display selection will apply on next start.")
return status, nil
}
// Use the window's current mode, which the user may have toggled since startup.
moved, err := a.displayHost.move(uint32(pid), status.EffectiveDisplay, false)
switch {
case errors.Is(err, host.ErrDisplayWindowNotFound):
a.emitVMLogForDriver(vm.DriverID, vm.Name, "Display window not ready. The display selection will apply on next start.")
return status, nil
case err != nil:
status.MoveError = "Could not move VM display: " + err.Error()
a.emitVMLogForDriver(vm.DriverID, vm.Name, status.MoveError)
case moved:
status.AppliedLive = true
placement.moveEpoch++
a.emitVMLogForDriver(vm.DriverID, vm.Name, fmt.Sprintf("Moved VM window to display %q.", status.EffectiveDisplay))
}
return status, nil
}
func displayFallbackLog(target string) string {
return fmt.Sprintf("Display %q is disconnected. Using the primary display.", target)
}
func (a *App) displayVMPID(ctx context.Context, ref driver.VMRef) (int, error) {
vms, err := a.polledVMs(ctx)
if err != nil {
return 0, err
}
return runningDisplayPID(vms, ref), nil
}
func runningDisplayPID(vms []driver.VMListItem, ref driver.VMRef) int {
for _, vm := range vms {
if driver.NewVMRef(vm.DriverID, vm.Name) == ref && vm.State == "running" && vm.PID != nil {
return *vm.PID
}
}
return 0
}
func (a *App) liveDisplayVMPID(ctx context.Context, ref driver.VMRef) (int, error) {
a.mu.Lock()
router := a.driverRouter
a.mu.Unlock()
if router == nil {
vms, err := a.listVMsInternal(ctx)
return runningDisplayPID(vms, ref), err
}
d, err := router.DriverByID(ref.DriverID)
if err != nil {
return 0, err
}
vms, err := d.List(ctx)
if err != nil {
return 0, err
}
for _, vm := range vms {
if driver.NewVMRef(ref.DriverID, vm.Name) == ref && vm.State == "running" && vm.PID != nil {
return *vm.PID, nil
}
}
return 0, nil
}
func (a *App) positionVMDisplayOnStart(ctx context.Context, vm driver.VMInfo, ticks <-chan time.Time, probePID func(context.Context) (int, error)) {
placement := a.vmDisplayPlacement(vm.Ref())
placement.Lock()
epoch := placement.moveEpoch
placement.Unlock()
log := func(line string) { a.emitVMLogForDriver(vm.DriverID, vm.Name, line) }
cfg := vmstart.ReadVMDisplay(vm.Directory)
if cfg.TargetDisplay == "" {
return
}
borderless := vmInfoBool(vm, "borderless")
for {
select {
case <-ctx.Done():
return
case <-ticks:
if ctx.Err() != nil {
return
}
}
pid, err := probePID(ctx)
if ctx.Err() != nil {
return
}
if err != nil {
log("Could not find VM display process: " + err.Error())
return
}
if pid <= 0 {
continue
}
// A settings change may have saved and applied a new target while we waited.
placement.Lock()
if placement.moveEpoch != epoch || ctx.Err() != nil {
placement.Unlock()
return
}
cfg := vmstart.ReadVMDisplay(vm.Directory)
if cfg.TargetDisplay == "" {
placement.Unlock()
return
}
target, fallback := vmstart.ResolveTargetDisplay(cfg, a.displayHost.displays())
if target == nil {
placement.Unlock()
return
}
moved, err := a.displayHost.move(uint32(pid), target.Name, borderless)
placement.Unlock()
switch {
case errors.Is(err, host.ErrDisplayWindowNotFound), errors.Is(err, host.ErrDisplayNotFound):
// The window or monitor may have changed since enumeration.
continue
case err != nil:
log("Could not move VM display: " + err.Error())
case moved:
if fallback {
log(displayFallbackLog(cfg.TargetDisplay))
}
log(fmt.Sprintf("Moved VM window to display %q.", target.Name))
}
return
}
}
+381
View File
@@ -0,0 +1,381 @@
package app
import (
"context"
"errors"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func newDisplayTestApp(t *testing.T, d driver.Driver) *App {
t.Helper()
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test.display", Version: "1.0.0"},
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, d.ID(), d)
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
router := driver.NewRouter(reg, nil)
return &App{
cfg: config.Default(),
driverRouter: router,
lifecycleSvc: vmlifecycle.New(reg, router, nil),
}
}
func TestGetAndSetVMDisplay(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID
const name = "test-vm"
pid := 123
vm := driver.VMInfo{Name: name, DriverID: driverID, Directory: t.TempDir(), State: "stopped"}
d := &appSecondDriver{id: driverID, vms: []driver.VMInfo{vm}}
a := newDisplayTestApp(t, d)
displays := []host.DisplayInfo{
{Name: "DISPLAY1", Primary: true, Width: 1920, Height: 1080},
{Name: "DISPLAY2", Width: 3840, Height: 2160, WorkWidth: 3840, WorkHeight: 2120},
}
moveCalls := 0
var moveErr error
a.displayHost = vmDisplayHost{
displays: func() []host.DisplayInfo { return displays },
move: func(gotPID uint32, target string, borderless bool) (bool, error) {
moveCalls++
if gotPID != uint32(pid) || target != "DISPLAY2" || borderless {
t.Fatalf("move(%d, %q, %t)", gotPID, target, borderless)
}
if cfg := vmstart.ReadVMDisplay(vm.Directory); cfg.TargetDisplay != "display2" {
t.Fatalf("config when moving = %+v", cfg)
}
return moveErr == nil, moveErr
},
}
status, err := a.GetVMDisplayWithDriver(driverID, name)
if err != nil || status.TargetDisplay != "" || status.EffectiveDisplay != "DISPLAY1" ||
!status.Connected || status.FallbackToPrimary || status.Running || len(status.Displays) != 2 {
t.Fatalf("get default = %+v, %v", status, err)
}
if _, err := a.SetVMDisplayWithDriver(driverID, name, "DISCONNECTED"); !errors.Is(err, host.ErrDisplayNotFound) {
t.Fatalf("new offline display error = %v", err)
}
status, err = a.SetVMDisplayWithDriver(driverID, name, " DISPLAY2 ")
if err != nil || status.TargetDisplay != "DISPLAY2" || status.EffectiveDisplay != "DISPLAY2" || moveCalls != 0 {
t.Fatalf("set while stopped = %+v, %v, %d moves", status, err, moveCalls)
}
wantPresets, _ := host.RecommendDisplayPresets(&displays[1])
if !slices.Equal(status.DisplayPresets, wantPresets) || !status.FullscreenHiDPI || status.HiDPIAdvice != host.HiDPIAdvice(&displays[1], wantPresets) {
t.Fatalf("display recommendations = %+v", status)
}
displays = displays[:1]
status, err = a.GetVMDisplayWithDriver(driverID, name)
if err != nil || status.TargetDisplay != "DISPLAY2" || status.EffectiveDisplay != "DISPLAY1" || status.Connected || !status.FallbackToPrimary {
t.Fatalf("get offline display = %+v, %v", status, err)
}
if status, err := a.SetVMDisplayWithDriver(driverID, name, "display2"); err != nil || !status.FallbackToPrimary {
t.Fatalf("keep offline display = %+v, %v", status, err)
}
if status, err := a.SetVMDisplayWithDriver(driverID, name, " PRIMARY "); err != nil || status.TargetDisplay != "" ||
status.FallbackToPrimary || vmstart.ReadVMDisplay(vm.Directory).TargetDisplay != "" {
t.Fatalf("clear offline display = %+v, %v", status, err)
}
displays = append(displays, host.DisplayInfo{Name: "DISPLAY2"})
d.vms[0].State = "running"
// The detail view for the built-in driver gets its PID from the list.
a.lastVMsAt = time.Now()
a.lastVMs = []driver.VMListItem{{Name: name, DriverID: driverID, State: "running", PID: &pid}}
status, err = a.SetVMDisplayWithDriver(driverID, name, "display2")
if err != nil || !status.Running || !status.Connected || status.EffectiveDisplay != "DISPLAY2" ||
!status.AppliedLive || status.MoveError != "" || moveCalls != 1 {
t.Fatalf("set while running = %+v, %v, %d moves", status, err, moveCalls)
}
moveErr = host.ErrDisplayWindowNotFound
if status, err := a.SetVMDisplayWithDriver(driverID, name, "display2"); err != nil || status.AppliedLive || status.MoveError != "" || moveCalls != 2 {
t.Fatalf("set before window creation = %+v, %v, %d moves", status, err, moveCalls)
}
if logs := strings.Join(a.recentLogs, "\n"); !strings.Contains(logs, "Moved VM window") || !strings.Contains(logs, "Display window not ready") {
t.Fatalf("VM display logs = %s", logs)
}
if _, err := vmstart.SaveVMDisplay(vm.Directory, vmstart.VMDisplayConfig{}); err != nil {
t.Fatal(err)
}
moveErr = errors.New("move failed")
status, err = a.SetVMDisplayWithDriver(driverID, name, "display2")
if err != nil || status.AppliedLive || !strings.Contains(status.MoveError, moveErr.Error()) || moveCalls != 3 {
t.Fatalf("set with move failure = %+v, %v, %d moves", status, err, moveCalls)
}
if cfg := vmstart.ReadVMDisplay(vm.Directory); cfg.TargetDisplay != "display2" {
t.Fatalf("config after move failure = %+v", cfg)
}
}
func TestSetVMDisplayReadOnly(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID
vm := driver.VMInfo{Name: "test-vm", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}
a := newDisplayTestApp(t, &appSecondDriver{id: driverID, vms: []driver.VMInfo{vm}})
a.root = dataroot.Status{Dir: vm.Directory, ReadOnly: true, Reason: dataroot.ReasonNewer}
a.displayHost.displays = func() []host.DisplayInfo {
return []host.DisplayInfo{{Name: "DISPLAY1", Primary: true}, {Name: "DISPLAY2"}}
}
path := filepath.Join(vm.Directory, ".reims-go-display.json")
const original = "{\"target_display\":\"DISPLAY1\"}\n"
if err := os.WriteFile(path, []byte(original), 0600); err != nil {
t.Fatal(err)
}
for _, target := range []string{"DISPLAY2", ""} {
_, err := a.SetVMDisplayWithDriver(driverID, vm.Name, target)
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != "E_DATAROOT_NEWER" {
t.Fatalf("set %q on read-only data root: %v", target, err)
}
data, err := os.ReadFile(path)
if err != nil || string(data) != original {
t.Fatalf("config after setting %q = %q, %v", target, data, err)
}
}
}
func TestVMDisplayRejectsUnknownDriverWithoutLifecycleService(t *testing.T) {
a := &App{cfg: config.Default()}
const driverID = "test.driver.other"
_, getErr := a.GetVMDisplayWithDriver(driverID, "test-vm")
_, setErr := a.SetVMDisplayWithDriver(driverID, "test-vm", "")
for _, err := range []error{getErr, setErr} {
if err == nil || err.Error() != `driver "test.driver.other" is unavailable without the plugin manager` {
t.Fatalf("unknown driver error = %v", err)
}
}
}
type displayPIDTestDriver struct {
appSecondDriver
listPID *int
listErr error
}
func (d *displayPIDTestDriver) List(context.Context) ([]driver.VMInfo, error) {
vm := d.vms[0]
vm.PID = d.listPID
return []driver.VMInfo{vm}, d.listErr
}
func TestSetVMDisplayRefreshesStoppedPIDCache(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID
pid := 123
vm := driver.VMInfo{Name: "test-vm", DriverID: driverID, Directory: t.TempDir(), State: "running"}
d := &displayPIDTestDriver{appSecondDriver: appSecondDriver{id: driverID, vms: []driver.VMInfo{vm}}, listPID: &pid}
a := newDisplayTestApp(t, d)
a.lastVMsAt = time.Now()
a.lastVMs = []driver.VMListItem{{Name: vm.Name, DriverID: driverID, State: "stopped"}}
moveCalls := 0
a.displayHost = vmDisplayHost{
displays: func() []host.DisplayInfo { return []host.DisplayInfo{{Name: "DISPLAY1"}, {Name: "DISPLAY2"}} },
move: func(gotPID uint32, target string, _ bool) (bool, error) {
moveCalls++
if gotPID != uint32(pid) || target != "DISPLAY1" {
t.Fatalf("move(%d, %q)", gotPID, target)
}
return true, nil
},
}
status, err := a.SetVMDisplayWithDriver(driverID, vm.Name, "DISPLAY1")
if err != nil || !status.Running || !status.AppliedLive || status.MoveError != "" || moveCalls != 1 {
t.Fatalf("set with stale cache = %+v, %v, %d moves", status, err, moveCalls)
}
d.listErr = errors.New("PID lookup failed")
status, err = a.SetVMDisplayWithDriver(driverID, vm.Name, "DISPLAY2")
if err != nil || status.AppliedLive || !strings.Contains(status.MoveError, d.listErr.Error()) || moveCalls != 1 {
t.Fatalf("set with PID lookup failure = %+v, %v, %d moves", status, err, moveCalls)
}
if cfg := vmstart.ReadVMDisplay(vm.Directory); cfg.TargetDisplay != "DISPLAY2" {
t.Fatalf("config after PID lookup failure = %+v", cfg)
}
}
func TestSetVMDisplayDoesNotBlockOtherVMs(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID
pid := 123
vmA := driver.VMInfo{Name: "VM-A", DriverID: driverID, Directory: t.TempDir(), State: "running", PID: &pid}
vmB := driver.VMInfo{Name: "VM-B", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}
a := newDisplayTestApp(t, &appSecondDriver{id: driverID, vms: []driver.VMInfo{vmA, vmB}})
moving := make(chan struct{})
release := make(chan struct{})
a.displayHost = vmDisplayHost{
displays: func() []host.DisplayInfo { return []host.DisplayInfo{{Name: "DISPLAY2"}} },
move: func(uint32, string, bool) (bool, error) {
close(moving)
<-release
return true, nil
},
}
var pending sync.WaitGroup
defer func() {
close(release)
pending.Wait()
}()
aResult := make(chan error, 1)
pending.Go(func() {
_, err := a.SetVMDisplayWithDriver(driverID, vmA.Name, "DISPLAY2")
aResult <- err
})
select {
case <-moving:
case err := <-aResult:
t.Fatalf("VM-A returned before moving: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("VM-A did not begin moving")
}
bResult := make(chan error, 1)
pending.Go(func() {
_, err := a.SetVMDisplayWithDriver(driverID, vmB.Name, "DISPLAY2")
bResult <- err
})
select {
case err := <-bResult:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("VM-B could not save while VM-A was moving")
}
if status, err := a.GetVMDisplayWithDriver(driverID, vmB.Name); err != nil || status.TargetDisplay != "DISPLAY2" {
t.Fatalf("get VM-B while VM-A is moving = %+v, %v", status, err)
}
}
func TestPositionVMDisplayOnStartAfterManualSelection(t *testing.T) {
for _, manualMoved := range []bool{true, false} {
name := "manual window unavailable"
if manualMoved {
name = "manual move succeeded"
}
t.Run(name, func(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID
pid := 123
vm := vmInfoFromMacOSDetail(reims.VMDetail{Name: "test-vm", Directory: t.TempDir(), State: "running", Borderless: true})
vm.PID = &pid
if _, err := vmstart.SaveVMDisplay(vm.Directory, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY1"}); err != nil {
t.Fatal(err)
}
a := newDisplayTestApp(t, &appSecondDriver{id: driverID, vms: []driver.VMInfo{vm}})
manualMoves, startMoves := 0, 0
a.displayHost = vmDisplayHost{
displays: func() []host.DisplayInfo { return []host.DisplayInfo{{Name: "DISPLAY1"}, {Name: "DISPLAY2"}} },
move: func(_ uint32, target string, borderless bool) (bool, error) {
if target != "DISPLAY2" {
t.Fatalf("move used stale target %q", target)
}
if borderless {
startMoves++
return true, nil
}
manualMoves++
if !manualMoved {
return false, host.ErrDisplayWindowNotFound
}
return true, nil
},
}
ticks := make(chan time.Time, 1)
ticks <- time.Time{}
close(ticks)
a.positionVMDisplayOnStart(context.Background(), vm, ticks, func(context.Context) (int, error) {
status, err := a.SetVMDisplayWithDriver(driverID, vm.Name, "DISPLAY2")
if err != nil || status.AppliedLive != manualMoved || status.MoveError != "" {
t.Fatalf("manual move = %+v, %v", status, err)
}
return pid, nil
})
wantStartMoves := 1
if manualMoved {
wantStartMoves = 0
}
if manualMoves != 1 || startMoves != wantStartMoves {
t.Fatalf("got %d manual moves and %d start moves, want 1 and %d", manualMoves, startMoves, wantStartMoves)
}
})
}
}
func TestPositionVMDisplayOnStart(t *testing.T) {
vm := vmInfoFromMacOSDetail(reims.VMDetail{Name: "test-vm", Directory: t.TempDir(), Borderless: true})
if _, err := vmstart.SaveVMDisplay(vm.Directory, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2"}); err != nil {
t.Fatal(err)
}
displays := []host.DisplayInfo{{Name: "DISPLAY1", Primary: true}, {Name: "DISPLAY2"}}
probes, moves := 0, 0
a := &App{displayHost: vmDisplayHost{
displays: func() []host.DisplayInfo { return displays },
move: func(pid uint32, target string, borderless bool) (bool, error) {
moves++
want := displays[len(displays)-1].Name
if pid != 123 || target != want || !borderless {
t.Fatalf("start move(%d, %q, %t)", pid, target, borderless)
}
if moves == 1 {
return false, host.ErrDisplayWindowNotFound
}
return true, nil
},
}}
ticks := make(chan time.Time, 4)
for range cap(ticks) {
ticks <- time.Time{}
}
a.positionVMDisplayOnStart(context.Background(), vm, ticks, func(context.Context) (int, error) {
probes++
switch probes {
case 1:
return 0, nil
case 2, 3:
return 123, nil
default:
t.Fatal("continued probing after moving the window")
return 0, nil
}
})
if probes != 3 || moves != 2 || !strings.Contains(strings.Join(a.recentLogs, "\n"), "Moved VM window") {
t.Fatalf("start: %d probes, %d moves, logs %v", probes, moves, a.recentLogs)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
a.positionVMDisplayOnStart(ctx, vm, ticks, func(context.Context) (int, error) {
t.Fatal("probed after cancellation")
return 0, nil
})
displays = displays[:1]
ticks <- time.Time{}
a.positionVMDisplayOnStart(context.Background(), vm, ticks, func(context.Context) (int, error) {
return 123, nil
})
if moves != 3 || vmstart.ReadVMDisplay(vm.Directory).TargetDisplay != "DISPLAY2" {
t.Fatalf("expected a primary-display move with the saved target retained, got %d moves", moves)
}
if logs := strings.Join(a.recentLogs, "\n"); !strings.Contains(logs, "Using the primary display") {
t.Fatalf("fallback log missing: %s", logs)
}
}
+3
View File
@@ -76,6 +76,9 @@ func (a *App) resolveVMInfo(driverID, name string) (driver.VMInfo, error) {
_, vm, err := svc.Resolve(context.Background(), driverID, name)
return vm, err
}
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return driver.VMInfo{}, fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
}
detail, err := a.GetVMDetail(name)
if err != nil {
return driver.VMInfo{}, err
+1 -1
View File
@@ -315,7 +315,7 @@ func (a *App) startVMLegacy(name string) error {
}
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
host.ShouldUseFixedGuestMode(curDetail.Borderless, curDetail.Resolution, rep.PrimaryDisplay) {
vmstart.UsesFixedGuestMode(curDetail.Directory, rep.Displays, curDetail.Borderless, curDetail.Resolution) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
if prep.Runtime.Manifest.HasCapability("client-window-close") {
+12
View File
@@ -67,6 +67,18 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
}{id: myID, cancel: cancel}
vmMonitors.mu.Unlock()
if vmstart.ReadVMDisplay(detail.Directory).TargetDisplay != "" {
go func() {
positionCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
a.positionVMDisplayOnStart(positionCtx, detail, ticker.C, func(ctx context.Context) (int, error) {
return a.displayVMPID(ctx, detail.Ref())
})
}()
}
go func() {
defer func() {
cancel()
+33 -15
View File
@@ -3,16 +3,18 @@ package host
import (
"fmt"
"math"
"strings"
)
// DisplayInfo describes a connected physical monitor on the host.
type DisplayInfo struct {
Name string `json:"name,omitempty"`
Width int `json:"width"`
Height int `json:"height"`
ScalePct int `json:"scale_pct"` // Windows DPI scaling percentage, e.g. 100, 125, 150, 200
RefreshHz int `json:"refresh_hz,omitempty"`
Primary bool `json:"primary"`
Name string `json:"name,omitempty"`
FriendlyName string `json:"friendly_name,omitempty"`
Width int `json:"width"`
Height int `json:"height"`
ScalePct int `json:"scale_pct"` // Windows DPI scaling percentage, e.g. 100, 125, 150, 200
RefreshHz int `json:"refresh_hz,omitempty"`
Primary bool `json:"primary"`
// WorkWidth and WorkHeight are the work area (the screen less the taskbar) in
// pixels; 0 where unknown.
WorkWidth int `json:"work_width,omitempty"`
@@ -43,6 +45,22 @@ func PrimaryDisplayOf(displays []DisplayInfo) *DisplayInfo {
return nil
}
// ConnectedDisplays enumerates the current host monitors.
func ConnectedDisplays() []DisplayInfo { return probeDisplays() }
// FindDisplayByName matches a monitor device name or selects the primary display.
func FindDisplayByName(displays []DisplayInfo, name string) (*DisplayInfo, bool) {
if name == "" || strings.EqualFold(name, "auto") || strings.EqualFold(name, "primary") {
return PrimaryDisplayOf(displays), true
}
for _, display := range displays {
if strings.EqualFold(display.Name, name) {
return &display, true
}
}
return nil, false
}
// When an x86-64 macOS guest on reims-vgpu starts its desktop HiDPI. Upstream
// steelbrain/reims-vgpu 3731afd, guest/kext/src/RgfxDisplayIdentity.hpp:33-41
// and 68-79, crates/reims-vgpu-window/features.md:138-150:
@@ -214,33 +232,33 @@ func ParseResolution(raw string) (w, h int, ok bool) {
// (REIMS_VGPU_WINDOW_FIXED_MODE=1).
//
// - In borderless fullscreen: enabled whenever the configured resolution
// differs from the primary monitor's native pixels (e.g. 5120x2880 HiDPI
// differs from the target monitor's native pixels (e.g. 5120x2880 HiDPI
// 1.5x supersampled onto a 3840x2160 monitor, or 2560x1440 1x upscaled).
// Matching the native monitor stays on the zero-copy 1:1 path.
// - In windowed mode: enabled when the configured resolution exceeds the
// monitor's usable work area (e.g. 5120x2880 supersampled in a window).
func ShouldUseFixedGuestMode(borderless bool, resolution string, primary *DisplayInfo) bool {
func ShouldUseFixedGuestMode(borderless bool, resolution string, target *DisplayInfo) bool {
w, h, ok := ParseResolution(resolution)
if !ok {
return false
}
if borderless {
if primary == nil || primary.Width <= 0 || primary.Height <= 0 {
if target == nil || target.Width <= 0 || target.Height <= 0 {
return true
}
return w != primary.Width || h != primary.Height
return w != target.Width || h != target.Height
}
if primary == nil || primary.Width <= 0 || primary.Height <= 0 {
if target == nil || target.Width <= 0 || target.Height <= 0 {
return false
}
scale := primary.ScalePct
scale := target.ScalePct
if scale <= 0 {
scale = 100
}
usableW, usableH := primary.WorkWidth, primary.WorkHeight
usableW, usableH := target.WorkWidth, target.WorkHeight
if usableW <= 0 || usableH <= 0 {
usableW = primary.Width
usableH = primary.Height - defaultTaskbarPoints*scale/100
usableW = target.Width
usableH = target.Height - defaultTaskbarPoints*scale/100
}
usableH -= windowTitleBarPoints * scale / 100
return w > usableW || h > usableH
+15
View File
@@ -0,0 +1,15 @@
package host
import "errors"
var ErrDisplayNotFound = errors.New("target display not found")
func computeWindowedTargetRect(winRect, targetWork WindowRect) WindowRect {
workWidth := targetWork.Right - targetWork.Left
workHeight := targetWork.Bottom - targetWork.Top
width := min(winRect.Right-winRect.Left, workWidth)
height := min(winRect.Bottom-winRect.Top, workHeight)
left := targetWork.Left + (workWidth-width)/2
top := targetWork.Top + (workHeight-height)/2
return WindowRect{Left: left, Top: top, Right: left + width, Bottom: top + height}
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !windows
package host
func MoveProcessWindowToDisplay(pid uint32, displayName string, borderless bool) (bool, error) {
return false, nil
}
+43
View File
@@ -0,0 +1,43 @@
package host
import "testing"
func TestFindDisplayByName(t *testing.T) {
displays := []DisplayInfo{{Name: "DISPLAY2"}, {Name: "DISPLAY1", Primary: true}}
for _, name := range []string{"", "Auto", "PRIMARY", "display1"} {
if display, ok := FindDisplayByName(displays, name); !ok || display == nil || display.Name != "DISPLAY1" {
t.Fatalf("FindDisplayByName(%q) = %+v, %t", name, display, ok)
}
}
display, ok := FindDisplayByName(displays, "display2")
if !ok || display == nil || display.Name != "DISPLAY2" {
t.Fatalf("secondary display = %+v, %t", display, ok)
}
display.Name = "changed"
if displays[0].Name != "DISPLAY2" {
t.Fatal("lookup returned a pointer into the original slice")
}
if display, ok := FindDisplayByName(displays, "missing"); ok || display != nil {
t.Fatalf("missing display = %+v, %t", display, ok)
}
if display, ok := FindDisplayByName(nil, "auto"); !ok || display != nil {
t.Fatalf("default with no displays = %+v, %t", display, ok)
}
}
func TestComputeWindowedTargetRect(t *testing.T) {
for _, tc := range []struct {
name string
window, work, want WindowRect
}{
{"center", WindowRect{80, 90, 880, 690}, WindowRect{0, 40, 1920, 1080}, WindowRect{560, 260, 1360, 860}},
{"clamp width", WindowRect{0, 0, 2500, 600}, WindowRect{0, 40, 1920, 1080}, WindowRect{0, 260, 1920, 860}},
{"clamp height on negative screen", WindowRect{0, 0, 800, 1440}, WindowRect{-1920, -1080, 0, -40}, WindowRect{-1360, -1080, -560, -40}},
} {
t.Run(tc.name, func(t *testing.T) {
if got := computeWindowedTargetRect(tc.window, tc.work); got != tc.want {
t.Fatalf("target rectangle = %+v, want %+v", got, tc.want)
}
})
}
}
+83
View File
@@ -0,0 +1,83 @@
//go:build windows
package host
import (
"fmt"
"strings"
"syscall"
)
func findDisplayMonitor(name string) (monitorInfoExW, error) {
monitors, err := enumerateDisplayMonitors()
if err != nil {
return monitorInfoExW{}, fmt.Errorf("EnumDisplayMonitors: %w", err)
}
for _, monitor := range monitors {
mi := monitor.info
if name == "" && mi.Flags&monitorInfoPrimary != 0 ||
name != "" && strings.EqualFold(name, syscall.UTF16ToString(mi.Device[:])) {
return mi, nil
}
}
return monitorInfoExW{}, fmt.Errorf("%w: %q", ErrDisplayNotFound, name)
}
// MoveProcessWindowToDisplay positions a VM display window in virtual-screen coordinates.
func MoveProcessWindowToDisplay(pid uint32, displayName string, borderless bool) (bool, error) {
target, err := findDisplayMonitor(displayName)
if err != nil {
return false, err
}
fullscreenState.prune(liveWindowPID)
hwnd := ProcessDisplayWindow(pid)
if hwnd == 0 {
return false, fmt.Errorf("%w for pid %d", ErrDisplayWindowNotFound, pid)
}
unlock := fullscreenState.lock(hwnd)
defer unlock()
if liveWindowPID(hwnd) != pid {
return false, fmt.Errorf("%w for pid %d", ErrDisplayWindowNotFound, pid)
}
if iconic, _, _ := procIsIconic.Call(hwnd); iconic != 0 {
procShowWindow.Call(hwnd, swRestore)
if remaining, _, _ := procIsIconic.Call(hwnd); remaining != 0 {
return false, fmt.Errorf("could not restore display window for pid %d", pid)
}
}
style, err := getWindowLong(hwnd, gwlStyle)
if err != nil {
return false, err
}
exStyle, err := getWindowLong(hwnd, gwlExStyle)
if err != nil {
return false, err
}
rect, monitor, err := getFullscreenGeometry(hwnd, exStyle, false, savedWindowState{})
if err != nil {
return false, err
}
wasFullscreen := isBorderlessFullscreenRect(style, rect, WindowRect(monitor.Monitor))
if !borderless && !wasFullscreen {
work := WindowRect(target.Work)
bounds := computeWindowedTargetRect(rect, work)
if err := setWindowRect(hwnd, bounds, swpNoZOrder|swpNoOwnerZOrder|swpFrameChanged); err != nil {
return false, err
}
return true, nil
}
placement, err := getWindowPlacement(hwnd)
if err != nil {
return false, err
}
current := savedWindowState{pid: pid, style: style, exStyle: exStyle, placement: placement, wasFullscreen: wasFullscreen}
bounds := WindowRect(target.Monitor)
if err := resizeWindowFrame(hwnd, style&^windowFrameStyles, exStyle&^windowFrameExStyles, bounds); err != nil {
return false, rollbackWindowState(hwnd, current, err)
}
fullscreenState.remember(hwnd, current, bounds)
markTaskbarFullscreen(hwnd, true)
return true, nil
}
+73 -47
View File
@@ -13,6 +13,7 @@ var (
procEnumDisplayMonitors = user32.NewProc("EnumDisplayMonitors")
procGetMonitorInfoW = user32.NewProc("GetMonitorInfoW")
procEnumDisplaySettings = user32.NewProc("EnumDisplaySettingsW")
procEnumDisplayDevices = user32.NewProc("EnumDisplayDevicesW")
procGetDC = user32.NewProc("GetDC")
procReleaseDC = user32.NewProc("ReleaseDC")
@@ -42,6 +43,15 @@ type monitorInfoExW struct {
Device [32]uint16
}
type displayDeviceW struct {
Size uint32
DeviceName [32]uint16
DeviceString [128]uint16
StateFlags uint32
DeviceID [128]uint16
DeviceKey [128]uint16
}
type devModeW struct {
DeviceName [32]uint16
SpecVersion uint16
@@ -68,25 +78,54 @@ type devModeW struct {
Extra [8]uint32
}
type displayMonitor struct {
handle uintptr
info monitorInfoExW
}
var (
displayEnumMu sync.Mutex
displayEnumOnce sync.Once
displayEnumCB uintptr
displayEnumResult *[]DisplayInfo
displayEnumMu sync.Mutex
displayEnumCB = sync.OnceValue(func() uintptr { return syscall.NewCallback(enumDisplayMonitorProc) })
displayMonitors []displayMonitor
)
func enumDisplayMonitorProc(hMon uintptr, _ uintptr, _ uintptr, _ uintptr) uintptr {
out := displayEnumResult
if out == nil {
return 0
}
var mi monitorInfoExW
mi.Size = uint32(unsafe.Sizeof(mi))
r, _, _ := procGetMonitorInfoW.Call(hMon, uintptr(unsafe.Pointer(&mi)))
if r == 0 {
return 1
if r != 0 {
displayMonitors = append(displayMonitors, displayMonitor{handle: hMon, info: mi})
}
name := syscall.UTF16ToString(mi.Device[:])
return 1
}
// Reuse one callback slot because Go's Windows callback table never frees slots.
func enumerateDisplayMonitors() ([]displayMonitor, error) {
displayEnumMu.Lock()
defer displayEnumMu.Unlock()
ok, _, err := procEnumDisplayMonitors.Call(0, 0, displayEnumCB(), 0)
monitors := displayMonitors
displayMonitors = nil
if ok == 0 {
return monitors, err
}
return monitors, nil
}
func probeDisplays() []DisplayInfo {
monitors, _ := enumerateDisplayMonitors()
var displays []DisplayInfo
for _, monitor := range monitors {
display := readDisplayInfo(monitor)
if display.Width > 0 && display.Height > 0 {
displays = append(displays, display)
}
}
return displays
}
func readDisplayInfo(monitor displayMonitor) DisplayInfo {
mi := monitor.info
w := int(mi.Monitor.Right - mi.Monitor.Left)
h := int(mi.Monitor.Bottom - mi.Monitor.Top)
refresh := 0
@@ -109,7 +148,7 @@ func enumDisplayMonitorProc(hMon uintptr, _ uintptr, _ uintptr, _ uintptr) uintp
if procGetDpiForMonitor.Find() == nil {
var dpiX, dpiY uint32
hr, _, _ := procGetDpiForMonitor.Call(
hMon,
monitor.handle,
uintptr(mdtEffectiveDPI),
uintptr(unsafe.Pointer(&dpiX)),
uintptr(unsafe.Pointer(&dpiY)),
@@ -125,40 +164,27 @@ func enumDisplayMonitorProc(hMon uintptr, _ uintptr, _ uintptr, _ uintptr) uintp
}
}
if w > 0 && h > 0 {
// The work area in the same units as the monitor rectangle (pixels for a
// DPI-aware process, scaled points otherwise), carried over to w x h.
var workW, workH int
if monW, monH := int(mi.Monitor.Right-mi.Monitor.Left), int(mi.Monitor.Bottom-mi.Monitor.Top); monW > 0 && monH > 0 {
workW = int(mi.Work.Right-mi.Work.Left) * w / monW
workH = int(mi.Work.Bottom-mi.Work.Top) * h / monH
}
*out = append(*out, DisplayInfo{
Name: name,
Width: w,
Height: h,
ScalePct: scalePct,
RefreshHz: refresh,
Primary: mi.Flags&monitorInfoPrimary != 0,
WorkWidth: workW,
WorkHeight: workH,
})
// Scale the work area dimensions to the physical display mode.
var workW, workH int
if monW, monH := int(mi.Monitor.Right-mi.Monitor.Left), int(mi.Monitor.Bottom-mi.Monitor.Top); monW > 0 && monH > 0 {
workW = int(mi.Work.Right-mi.Work.Left) * w / monW
workH = int(mi.Work.Bottom-mi.Work.Top) * h / monH
}
var device displayDeviceW
device.Size = uint32(unsafe.Sizeof(device))
friendlyName := ""
if ok, _, _ := procEnumDisplayDevices.Call(uintptr(unsafe.Pointer(&mi.Device[0])), 0, uintptr(unsafe.Pointer(&device)), 0); ok != 0 {
friendlyName = syscall.UTF16ToString(device.DeviceString[:])
}
return DisplayInfo{
Name: syscall.UTF16ToString(mi.Device[:]),
FriendlyName: friendlyName,
Width: w,
Height: h,
ScalePct: scalePct,
RefreshHz: refresh,
Primary: mi.Flags&monitorInfoPrimary != 0,
WorkWidth: workW,
WorkHeight: workH,
}
return 1
}
// probeDisplays enumerates connected monitors reusing a single syscall.NewCallback
// slot for the lifetime of the process (Go's Windows callback table has a fixed
// 2000-slot limit and never frees allocated callbacks).
func probeDisplays() []DisplayInfo {
displayEnumOnce.Do(func() {
displayEnumCB = syscall.NewCallback(enumDisplayMonitorProc)
})
displayEnumMu.Lock()
defer displayEnumMu.Unlock()
var displays []DisplayInfo
displayEnumResult = &displays
defer func() { displayEnumResult = nil }()
_, _, _ = procEnumDisplayMonitors.Call(0, 0, displayEnumCB, 0)
return displays
}
+1
View File
@@ -64,6 +64,7 @@ type savedWindowState struct {
style, exStyle uintptr
placement windowPlacement
fullscreenRect WindowRect
wasFullscreen bool
}
func minimizedWindowRect(normal WindowRect, exStyle uintptr, monitor, work WindowRect, saved savedWindowState) WindowRect {
+1 -1
View File
@@ -225,7 +225,7 @@ func ToggleProcessWindowFullscreen(pid uint32) (bool, error) {
}
current := savedWindowState{pid: pid, style: style, exStyle: exStyle, placement: placement}
if wasFullscreen {
if hasSaved {
if hasSaved && !saved.wasFullscreen {
err = restoreWindowState(hwnd, saved)
} else {
err = resizeWindowFrame(hwnd, windowFrameStyles|wsVisible, exStyle, computeFallbackWindowRect(WindowRect(monitor.Work)))
+2 -1
View File
@@ -111,7 +111,8 @@ func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (
startLog(stderr, "[plugin] "+warning)
}
c.Env = append(c.Env, reconciled.Env...)
if active.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(cur.Borderless, cur.Resolution, rep.PrimaryDisplay) {
if active.Manifest.HasCapability("display-fixed-mode") &&
vmstart.UsesFixedGuestMode(cur.Directory, rep.Displays, cur.Borderless, cur.Resolution) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
if d.opts.ManagedByDesktop && active.Manifest.HasCapability("client-window-close") {
+2 -1
View File
@@ -117,7 +117,8 @@ func (d *ReimsMacOSDriver) resumeLocked(ctx context.Context, c *reims.Client, ac
if len(extraEnv) > 0 {
c.Env = append(c.Env, extraEnv...)
}
if active.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(cur.Borderless, cur.Resolution, rep.PrimaryDisplay) {
if active.Manifest.HasCapability("display-fixed-mode") &&
vmstart.UsesFixedGuestMode(cur.Directory, rep.Displays, cur.Borderless, cur.Resolution) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
if d.opts.ManagedByDesktop && active.Manifest.HasCapability("client-window-close") {
+83
View File
@@ -0,0 +1,83 @@
package vmstart
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/host"
)
const vmDisplayConfigFile = ".reims-go-display.json"
type VMDisplayConfig struct {
TargetDisplay string `json:"target_display,omitempty"`
}
func NormalizeTargetDisplay(raw string) string {
target := strings.TrimSpace(raw)
if strings.EqualFold(target, "auto") || strings.EqualFold(target, "primary") {
return ""
}
return target
}
func ReadVMDisplay(vmDir string) VMDisplayConfig {
if strings.TrimSpace(vmDir) == "" {
return VMDisplayConfig{}
}
data, err := os.ReadFile(filepath.Join(vmDir, vmDisplayConfigFile))
var cfg VMDisplayConfig
if err != nil || json.Unmarshal(data, &cfg) != nil {
return VMDisplayConfig{}
}
cfg.TargetDisplay = NormalizeTargetDisplay(cfg.TargetDisplay)
return cfg
}
func SaveVMDisplay(vmDir string, cfg VMDisplayConfig) (VMDisplayConfig, error) {
if strings.TrimSpace(vmDir) == "" {
return VMDisplayConfig{}, errors.New("VM directory is empty")
}
cfg.TargetDisplay = NormalizeTargetDisplay(cfg.TargetDisplay)
dst := filepath.Join(vmDir, vmDisplayConfigFile)
if cfg.TargetDisplay == "" {
if err := os.Remove(dst); err != nil && !errors.Is(err, os.ErrNotExist) {
return VMDisplayConfig{}, err
}
return cfg, nil
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return VMDisplayConfig{}, err
}
tmp, err := os.CreateTemp(vmDir, vmDisplayConfigFile+".*")
if err != nil {
return VMDisplayConfig{}, err
}
defer os.Remove(tmp.Name())
_, writeErr := tmp.Write(data)
if err := errors.Join(writeErr, tmp.Close()); err != nil {
return VMDisplayConfig{}, err
}
if err := os.Rename(tmp.Name(), dst); err != nil {
return VMDisplayConfig{}, err
}
return cfg, nil
}
func ResolveTargetDisplay(cfg VMDisplayConfig, displays []host.DisplayInfo) (target *host.DisplayInfo, fallback bool) {
if display, ok := host.FindDisplayByName(displays, NormalizeTargetDisplay(cfg.TargetDisplay)); ok {
return display, false
}
return host.PrimaryDisplayOf(displays), true
}
// UsesFixedGuestMode keeps start and resume on the same display geometry.
func UsesFixedGuestMode(vmDir string, displays []host.DisplayInfo, borderless bool, resolution string) bool {
target, _ := ResolveTargetDisplay(ReadVMDisplay(vmDir), displays)
return host.ShouldUseFixedGuestMode(borderless, resolution, target)
}
+84
View File
@@ -0,0 +1,84 @@
package vmstart
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/host"
)
func TestReadAndSaveVMDisplay(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, vmDisplayConfigFile)
if got := ReadVMDisplay(dir); got != (VMDisplayConfig{}) {
t.Fatalf("new VM config = %+v", got)
}
if err := os.WriteFile(path, []byte(`{"target_display":" AuTo "}`), 0o600); err != nil {
t.Fatal(err)
}
if got := ReadVMDisplay(dir).TargetDisplay; got != "" {
t.Fatalf("read auto = %q", got)
}
for _, input := range []string{"", " Auto ", " PRIMARY "} {
cfg, err := SaveVMDisplay(dir, VMDisplayConfig{TargetDisplay: " DISPLAY2 "})
if err != nil || cfg.TargetDisplay != "DISPLAY2" || ReadVMDisplay(dir) != cfg {
t.Fatalf("save config = %+v, %v", cfg, err)
}
cfg, err = SaveVMDisplay(dir, VMDisplayConfig{TargetDisplay: input})
if err != nil || cfg.TargetDisplay != "" || ReadVMDisplay(dir) != cfg {
t.Fatalf("clear with %q = %+v, %v", input, cfg, err)
}
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected removed config, stat error = %v", err)
}
}
}
func TestSaveVMDisplayReplacesConfig(t *testing.T) {
dir := t.TempDir()
first := VMDisplayConfig{TargetDisplay: "DISPLAY2"}
second := VMDisplayConfig{TargetDisplay: "DISPLAY3"}
if _, err := SaveVMDisplay(dir, first); err != nil {
t.Fatal(err)
}
oldLink := filepath.Join(dir, "original.json")
if err := os.Link(filepath.Join(dir, vmDisplayConfigFile), oldLink); err != nil {
t.Fatal(err)
}
if _, err := SaveVMDisplay(dir, second); err != nil {
t.Fatal(err)
}
if data, err := os.ReadFile(oldLink); err != nil || !strings.Contains(string(data), first.TargetDisplay) {
t.Fatalf("replacing config changed the original file: %s, %v", data, err)
}
if got := ReadVMDisplay(dir); got != second {
t.Fatalf("replacement = %+v, want %+v", got, second)
}
if files, err := filepath.Glob(filepath.Join(dir, vmDisplayConfigFile+".*")); err != nil || len(files) != 0 {
t.Fatalf("temporary files = %v, %v", files, err)
}
}
func TestResolveTargetDisplay(t *testing.T) {
displays := []host.DisplayInfo{{Name: "DISPLAY2"}, {Name: "DISPLAY1", Primary: true}}
for _, tc := range []struct {
input, want string
fallback bool
}{
{"", "DISPLAY1", false},
{" primary ", "DISPLAY1", false},
{"display2", "DISPLAY2", false},
{"disconnected", "DISPLAY1", true},
} {
target, fallback := ResolveTargetDisplay(VMDisplayConfig{TargetDisplay: tc.input}, displays)
if target == nil || target.Name != tc.want || fallback != tc.fallback {
t.Errorf("ResolveTargetDisplay(%q) = %+v, %t", tc.input, target, fallback)
}
}
if target, fallback := ResolveTargetDisplay(VMDisplayConfig{TargetDisplay: "disconnected"}, nil); target != nil || !fallback {
t.Fatalf("no monitors = %+v, %t", target, fallback)
}
}
+14 -1
View File
@@ -459,5 +459,18 @@
"smbiosLoadFailed": "Could not read OpenCore SMBIOS",
"syncHostMemorySMBIOS": "Sync host memory specs",
"syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start",
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4"
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4",
"targetDisplayTitle": "Launch display",
"targetDisplayPrimaryDefault": "Primary display (default)",
"targetDisplayNumbered": "Display {n}",
"targetDisplayRunningHint": "Switching while running moves the VM window right away and applies on next start",
"targetDisplayStoppedHint": "Choose which physical display opens the VM window; applies on next start",
"targetDisplaySingleHint": "Only 1 display detected; connect another display to choose a launch screen",
"targetDisplayNoneHint": "No physical displays detected; uses the default window position",
"targetDisplayDisconnectedOption": "Disconnected · using primary",
"targetDisplayFallbackHint": "Saved {name} is disconnected; falling back to the primary display",
"targetDisplayHint": "Target display: {name} ({w}×{h} at {scale}%)",
"targetDisplayToastMoved": "Switched to {display}",
"targetDisplayToastSaved": "Launch display set to {display}; applies on next start",
"targetDisplaySaveFailed": "Could not update launch display"
}
+14 -1
View File
@@ -459,5 +459,18 @@
"smbiosLoadFailed": "无法读取 OpenCore 设备码",
"syncHostMemorySMBIOS": "同步宿主机内存规格",
"syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效",
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4"
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4",
"targetDisplayTitle": "启动显示器",
"targetDisplayPrimaryDefault": "主显示器(默认)",
"targetDisplayNumbered": "显示器 {n}",
"targetDisplayRunningHint": "运行中切换会立即移动虚拟机窗口,并用于下次启动",
"targetDisplayStoppedHint": "选择虚拟机窗口打开的物理显示器,下次启动生效",
"targetDisplaySingleHint": "当前仅检测到 1 块显示器;接入更多显示器后可指定启动屏幕",
"targetDisplayNoneHint": "未检测到物理显示器,将使用默认窗口位置",
"targetDisplayDisconnectedOption": "已断开 · 回退至主显示器",
"targetDisplayFallbackHint": "已保存的「{name}」当前未连接,将回退至主显示器",
"targetDisplayHint": "目标显示器:{name}({w}×{h},{scale}% 缩放)",
"targetDisplayToastMoved": "已切换至「{display}」",
"targetDisplayToastSaved": "启动显示器已设为「{display}」,下次启动生效",
"targetDisplaySaveFailed": "无法更新启动显示器"
}