Merge pull request #189 from reiasu2/feat/auto-resolution
feat(display): add automatic per-display HiDPI resolution mode
This commit is contained in:
39 files changed
+3056
-235
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["reiasu2"],
|
||||
"zh": "虚拟机可在冷启动时自动选用当前目标显示器的推荐分辨率。",
|
||||
"en": "VMs can automatically use the target monitor's recommended resolution on cold start."
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const mod = await loadTestModule(`
|
||||
import './i18n/domains/settings.gen'
|
||||
import './i18n/domains/wizard.gen'
|
||||
export * from './i18n'
|
||||
export * from './lib/format'
|
||||
export * from './lib/displayResolution'
|
||||
`)
|
||||
|
||||
const host4K150 = {
|
||||
primary_display: { width: 3840, height: 2160, scale_pct: 150, work_width: 3840, work_height: 2088, primary: true },
|
||||
display_presets: [
|
||||
{ resolution: '3200x1800', label: '3200 × 1800', hidpi: true, recommended: true },
|
||||
{ resolution: '2880x1620', label: '2880 × 1620', hidpi: true },
|
||||
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
|
||||
],
|
||||
fullscreen_hidpi: true,
|
||||
recommended_gpu: { name: 'NVIDIA GeForce RTX 4070', kind: 'discrete' },
|
||||
gpus: [{ name: 'NVIDIA GeForce RTX 4070', kind: 'discrete' }],
|
||||
}
|
||||
|
||||
const host32K200 = {
|
||||
primary_display: { width: 3200, height: 2000, scale_pct: 200, work_width: 3200, work_height: 1904, primary: true },
|
||||
display_presets: [
|
||||
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: true, recommended: true },
|
||||
{ resolution: '2560x1600', label: '2560 × 1600', hidpi: true },
|
||||
{ resolution: '1920x1200', label: '1920 × 1200', hidpi: false },
|
||||
],
|
||||
fullscreen_hidpi: true,
|
||||
recommended_gpu: { name: 'Intel(R) Arc Graphics', kind: 'integrated' },
|
||||
gpus: [{ name: 'Intel(R) Arc Graphics', kind: 'integrated' }],
|
||||
}
|
||||
|
||||
test('resolveAutoDisplayPreset matches Go RecommendAutoResolution for 4K 16:9 and 3.2K 16:10', () => {
|
||||
// 4K 16:9 @ 150%
|
||||
const win4k = mod.resolveAutoDisplayPreset(host4K150, false, true)
|
||||
assert.equal(win4k.resolution, '3200x1800')
|
||||
assert.equal(win4k.hidpi, true)
|
||||
|
||||
const fs4kFixed = mod.resolveAutoDisplayPreset(host4K150, true, true)
|
||||
assert.equal(fs4kFixed.resolution, '5120x2880')
|
||||
assert.equal(fs4kFixed.hidpi, true)
|
||||
assert.equal(fs4kFixed.scaleBadge, '1.5×')
|
||||
|
||||
const fs4kNoFixed = mod.resolveAutoDisplayPreset(host4K150, true, false)
|
||||
assert.equal(fs4kNoFixed.resolution, '3840x2160')
|
||||
assert.equal(fs4kNoFixed.hidpi, true)
|
||||
assert.equal(fs4kNoFixed.native, true)
|
||||
|
||||
// 3.2K 16:10 @ 200% (scale >= 175 -> native fullscreen even with fixedModeSupported)
|
||||
const win32k = mod.resolveAutoDisplayPreset(host32K200, false, true)
|
||||
assert.equal(win32k.resolution, '2880x1800')
|
||||
assert.equal(win32k.hidpi, true)
|
||||
|
||||
const fs32kFixed = mod.resolveAutoDisplayPreset(host32K200, true, true)
|
||||
assert.equal(fs32kFixed.resolution, '3200x2000')
|
||||
assert.equal(fs32kFixed.hidpi, true)
|
||||
assert.equal(fs32kFixed.native, true)
|
||||
|
||||
const fs32kNoFixed = mod.resolveAutoDisplayPreset(host32K200, true, false)
|
||||
assert.equal(fs32kNoFixed.resolution, '3200x2000')
|
||||
assert.equal(fs32kNoFixed.hidpi, true)
|
||||
assert.equal(fs32kNoFixed.native, true)
|
||||
})
|
||||
|
||||
test('resolveAutoDisplayPreset falls back safely to 1920x1080 non-HiDPI when host display is empty or invalid (#6)', () => {
|
||||
const emptyHost = {}
|
||||
const winEmpty = mod.resolveAutoDisplayPreset(emptyHost, false, true)
|
||||
assert.equal(winEmpty.resolution, '1920x1080')
|
||||
assert.equal(winEmpty.hidpi, false)
|
||||
|
||||
for (const fixedModeSupported of [true, false]) {
|
||||
const fsEmpty = mod.resolveAutoDisplayPreset(emptyHost, true, fixedModeSupported)
|
||||
assert.equal(fsEmpty.resolution, '1920x1080')
|
||||
assert.equal(fsEmpty.label, '1920 × 1080')
|
||||
assert.equal(fsEmpty.hidpi, false)
|
||||
assert.equal(fsEmpty.native, true)
|
||||
assert.equal(fsEmpty.recommended, true)
|
||||
|
||||
const zeroHeightHost = {
|
||||
primary_display: { width: 3200, height: 0, scale_pct: 150, primary: true },
|
||||
fullscreen_hidpi: true,
|
||||
}
|
||||
const fsZeroHeight = mod.resolveAutoDisplayPreset(zeroHeightHost, true, fixedModeSupported)
|
||||
assert.equal(fsZeroHeight.resolution, '1920x1080')
|
||||
assert.equal(fsZeroHeight.label, '1920 × 1080')
|
||||
assert.equal(fsZeroHeight.hidpi, false)
|
||||
assert.equal(fsZeroHeight.native, true)
|
||||
}
|
||||
})
|
||||
|
||||
test('SettingsModal auto resolution never falls into custom or resBad across display and borderless switches', () => {
|
||||
// Auto mode with a resolution from 4K screen, now moved to 3.2K screen where 3200x1800 is not a preset
|
||||
const onLaptop = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: true, resolution: '3200x1800', borderless: false },
|
||||
displayProfile: host32K200,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: false,
|
||||
})
|
||||
assert.equal(onLaptop.presetHit, false)
|
||||
assert.equal(onLaptop.customRes, false)
|
||||
assert.equal(onLaptop.resValue, mod.AUTO_RESOLUTION_OPTION)
|
||||
assert.equal(onLaptop.resBad, false)
|
||||
assert.equal(onLaptop.autoPreset.resolution, '2880x1800')
|
||||
|
||||
// Even empty or invalid resolution string must not trigger resBad while auto_resolution is on
|
||||
const emptyResAuto = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: true, resolution: '', borderless: false },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: true,
|
||||
})
|
||||
assert.equal(emptyResAuto.customRes, false)
|
||||
assert.equal(emptyResAuto.resBad, false)
|
||||
assert.equal(emptyResAuto.resValue, mod.AUTO_RESOLUTION_OPTION)
|
||||
|
||||
// Toggling borderless in auto mode keeps auto_resolution intact and refreshes autoPreset
|
||||
const borderlessPatch = mod.toggleSettingsBorderless({
|
||||
borderless: true,
|
||||
form: { auto_resolution: true, resolution: '3200x1800' },
|
||||
displayProfile: host4K150,
|
||||
targetDisplay: host4K150.primary_display,
|
||||
presets: onLaptop.presets,
|
||||
fsPresets: onLaptop.fsPresets,
|
||||
customRes: false,
|
||||
})
|
||||
assert.deepEqual(borderlessPatch, { borderless: true })
|
||||
|
||||
const afterBorderless = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: true, resolution: '3200x1800', borderless: true },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: false,
|
||||
})
|
||||
assert.equal(afterBorderless.resValue, mod.AUTO_RESOLUTION_OPTION)
|
||||
assert.equal(afterBorderless.autoPreset.resolution, '5120x2880')
|
||||
})
|
||||
|
||||
test('SettingsModal dirty count, save payload, reset, and custom blur snap-back behave consistently', () => {
|
||||
const baseFixed = { name: 'mac', auto_resolution: false, resolution: '3200x1800', borderless: false }
|
||||
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
|
||||
|
||||
// Fixed -> Auto: keeps base.resolution so only auto_resolution is dirty (count = 1), save diff omits resolution
|
||||
const toAuto = mod.selectSettingsResolution({
|
||||
value: mod.AUTO_RESOLUTION_OPTION,
|
||||
form: { resolution: '2560x1440' },
|
||||
base: baseFixed,
|
||||
autoPreset,
|
||||
})
|
||||
assert.equal(toAuto.forceCustomRes, false)
|
||||
assert.deepEqual(toAuto.patch, { auto_resolution: true, resolution: '3200x1800' })
|
||||
assert.equal(mod.countChangedSettingsFields(['auto_resolution']), 1)
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], { ...baseFixed, auto_resolution: true, resolution: '2560x1440' }),
|
||||
{ name: 'mac', auto_resolution: true },
|
||||
)
|
||||
|
||||
// Auto -> Fixed different resolution: both fields dirty, UI count = 1, save diff sends both
|
||||
assert.equal(mod.countChangedSettingsFields(['auto_resolution', 'resolution']), 1)
|
||||
assert.equal(mod.countChangedSettingsFields(['auto_resolution', 'resolution', 'borderless']), 2)
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], { ...baseFixed, auto_resolution: false, resolution: '2560x1440' }),
|
||||
{ name: 'mac', auto_resolution: false, resolution: '2560x1440' },
|
||||
)
|
||||
|
||||
// Selecting custom disables auto_resolution and falls back to autoPreset when empty
|
||||
const toCustom = mod.selectSettingsResolution({
|
||||
value: mod.CUSTOM_RESOLUTION_OPTION,
|
||||
form: { resolution: '' },
|
||||
base: baseFixed,
|
||||
autoPreset,
|
||||
})
|
||||
assert.equal(toCustom.forceCustomRes, true)
|
||||
assert.deepEqual(toCustom.patch, { auto_resolution: false, resolution: '3200x1800' })
|
||||
|
||||
// Typing a known preset in custom input snaps back to preset card on blur
|
||||
const typedPreset = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: false, resolution: '3200x1800', borderless: false },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: true,
|
||||
})
|
||||
assert.equal(typedPreset.presetHit, true)
|
||||
assert.equal(typedPreset.customRes, true)
|
||||
assert.equal(
|
||||
mod.shouldExitCustomResOnBlur({ autoResolution: false, forceCustomRes: true, presetHit: typedPreset.presetHit }),
|
||||
true,
|
||||
)
|
||||
|
||||
// Typing an invalid custom resolution triggers resBad and does not snap back
|
||||
const typedInvalid = mod.deriveSettingsResolutionState({
|
||||
form: { auto_resolution: false, resolution: 'not-a-res', borderless: false },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: true,
|
||||
})
|
||||
assert.equal(typedInvalid.presetHit, false)
|
||||
assert.equal(typedInvalid.resBad, true)
|
||||
assert.equal(
|
||||
mod.shouldExitCustomResOnBlur({ autoResolution: false, forceCustomRes: true, presetHit: typedInvalid.presetHit }),
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
test('CreateWizard defaults to auto resolution and keeps preview resolution synced on borderless toggle', () => {
|
||||
const init = mod.initialWizardResolution(host4K150, true)
|
||||
assert.deepEqual(init, { auto_resolution: true, resolution: '3200x1800' })
|
||||
|
||||
const windowPresets = mod.windowDisplayPresets(host4K150, true)
|
||||
const fullscreenPresets = mod.fullscreenDisplayPresets(host4K150)
|
||||
|
||||
// Toggling borderless ON in auto mode updates preview resolution to fullscreen auto preset
|
||||
const fsOnFixed = mod.toggleWizardBorderless({
|
||||
borderless: true,
|
||||
opts: init,
|
||||
host: host4K150,
|
||||
fixedModeSupported: true,
|
||||
windowPresets,
|
||||
fullscreenPresets,
|
||||
})
|
||||
assert.deepEqual(fsOnFixed, { borderless: true, auto_resolution: true, resolution: '5120x2880' })
|
||||
|
||||
const fsOnNoFixed = mod.toggleWizardBorderless({
|
||||
borderless: true,
|
||||
opts: init,
|
||||
host: host4K150,
|
||||
fixedModeSupported: false,
|
||||
windowPresets,
|
||||
fullscreenPresets,
|
||||
})
|
||||
assert.deepEqual(fsOnNoFixed, { borderless: true, auto_resolution: true, resolution: '3840x2160' })
|
||||
|
||||
// Selecting a fixed preset turns auto_resolution off
|
||||
const fixedChoice = mod.selectWizardResolution('2560x1440', mod.resolveAutoDisplayPreset(host4K150, false, true))
|
||||
assert.deepEqual(fixedChoice, { auto_resolution: false, resolution: '2560x1440' })
|
||||
|
||||
// Selecting AUTO turns auto_resolution back on with current autoPreset
|
||||
const autoChoice = mod.selectWizardResolution(mod.AUTO_RESOLUTION_OPTION, mod.resolveAutoDisplayPreset(host4K150, true, true))
|
||||
assert.deepEqual(autoChoice, { auto_resolution: true, resolution: '5120x2880' })
|
||||
})
|
||||
|
||||
test('VM summary, formatResolutionLabel, and pendingChangeText format auto_resolution in zh-CN and en-US', () => {
|
||||
const trZh = (k, v) => mod.t('zh-CN', k, v)
|
||||
const trEn = (k, v) => mod.t('en-US', k, v)
|
||||
|
||||
assert.equal(mod.formatResolutionLabel('3200x1800', true, trZh), '自动(3200 × 1800)')
|
||||
assert.equal(mod.formatResolutionLabel('3200x1800', true, trEn), 'Auto (3200 × 1800)')
|
||||
assert.equal(mod.formatResolutionLabel('3200x1800', false, trZh), '3200 × 1800')
|
||||
assert.equal(mod.formatResolutionLabel('', true, trEn), 'Auto')
|
||||
|
||||
const autoDetail = {
|
||||
graphics: 'reims-vgpu',
|
||||
gpu: 'auto',
|
||||
resolution: '3200x1800',
|
||||
auto_resolution: true,
|
||||
displays: 1,
|
||||
}
|
||||
assert.equal(mod.graphicsLabel('zh-CN', autoDetail, host4K150), 'RTX 4070 · 自动(3200 × 1800)')
|
||||
assert.equal(mod.graphicsLabel('en-US', autoDetail, host4K150), 'RTX 4070 · Auto (3200 × 1800)')
|
||||
|
||||
const fixedDetail = { ...autoDetail, auto_resolution: false }
|
||||
assert.equal(mod.graphicsLabel('en-US', fixedDetail, host4K150), 'RTX 4070 · 1800p')
|
||||
|
||||
const pendingOnZh = mod.pendingChangeText('zh-CN', { field: 'auto_resolution', from: 'false', to: 'true' }, host4K150)
|
||||
const pendingOffEn = mod.pendingChangeText('en-US', { field: 'auto_resolution', from: 'true', to: 'false' }, host4K150)
|
||||
assert.equal(pendingOnZh, '自动分辨率 关闭 → 开启')
|
||||
assert.equal(pendingOffEn, 'Auto resolution On → Off')
|
||||
assert.ok(!pendingOnZh.includes('auto_resolution'))
|
||||
assert.ok(!pendingOffEn.includes('auto_resolution'))
|
||||
})
|
||||
|
||||
test('vmware-svga disables and hides auto resolution across wizard, settings, and summary (#5)', () => {
|
||||
// Wizard initialization: svga defaults to auto_resolution: false, reims-vgpu defaults to true
|
||||
assert.deepEqual(mod.initialWizardResolution(host4K150, true, 'vmware-svga'), {
|
||||
auto_resolution: false,
|
||||
resolution: '3200x1800',
|
||||
})
|
||||
assert.deepEqual(mod.initialWizardResolution(host4K150, true, 'reims-vgpu'), {
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
})
|
||||
|
||||
// Switching graphics in wizard disables auto on svga, and restores auto on reims-vgpu only if user did not pick a fixed preset
|
||||
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
|
||||
assert.deepEqual(
|
||||
mod.switchWizardGraphics({ graphics: 'vmware-svga', manualResolutionPicked: false, autoPreset }),
|
||||
{ graphics: 'vmware-svga', auto_resolution: false },
|
||||
)
|
||||
assert.deepEqual(
|
||||
mod.switchWizardGraphics({ graphics: 'reims-vgpu', manualResolutionPicked: false, autoPreset }),
|
||||
{ graphics: 'reims-vgpu', auto_resolution: true, resolution: '3200x1800' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
mod.switchWizardGraphics({ graphics: 'reims-vgpu', manualResolutionPicked: true, autoPreset }),
|
||||
{ graphics: 'reims-vgpu' },
|
||||
)
|
||||
|
||||
// SettingsModal switching to svga only patches graphics and exits custom input (R2 #11)
|
||||
assert.deepEqual(mod.switchSettingsGraphics('vmware-svga'), {
|
||||
patch: { graphics: 'vmware-svga' },
|
||||
forceCustomRes: false,
|
||||
})
|
||||
const svgaState = mod.deriveSettingsResolutionState({
|
||||
form: { graphics: 'vmware-svga', auto_resolution: true, resolution: 'not-a-res', borderless: false },
|
||||
displayProfile: host4K150,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: true,
|
||||
})
|
||||
assert.notEqual(svgaState.resValue, mod.AUTO_RESOLUTION_OPTION)
|
||||
assert.equal(svgaState.customRes, false)
|
||||
assert.equal(svgaState.resBad, false)
|
||||
|
||||
// R2 #2: SVGA never includes the AUTO resolution card in SettingsModal or CreateWizard options
|
||||
const activePresets = mod.windowDisplayPresets(host4K150, true)
|
||||
const settingsSvgaOpts = mod.buildResolutionOptions({
|
||||
graphics: 'vmware-svga',
|
||||
autoPreset,
|
||||
activePresets,
|
||||
includeCustom: true,
|
||||
})
|
||||
const wizardSvgaOpts = mod.buildResolutionOptions({
|
||||
graphics: 'vmware-svga',
|
||||
autoPreset,
|
||||
activePresets,
|
||||
})
|
||||
assert.equal(settingsSvgaOpts.some((o) => o.value === mod.AUTO_RESOLUTION_OPTION), false)
|
||||
assert.equal(wizardSvgaOpts.some((o) => o.value === mod.AUTO_RESOLUTION_OPTION), false)
|
||||
const settingsVgpuOpts = mod.buildResolutionOptions({
|
||||
graphics: 'reims-vgpu',
|
||||
autoPreset,
|
||||
activePresets,
|
||||
includeCustom: true,
|
||||
})
|
||||
const wizardVgpuOpts = mod.buildResolutionOptions({
|
||||
graphics: 'reims-vgpu',
|
||||
autoPreset,
|
||||
activePresets,
|
||||
})
|
||||
assert.equal(settingsVgpuOpts[0].value, mod.AUTO_RESOLUTION_OPTION)
|
||||
assert.equal(wizardVgpuOpts[0].value, mod.AUTO_RESOLUTION_OPTION)
|
||||
|
||||
// Settings save diff never sends auto_resolution: true for vmware-svga
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['graphics', 'auto_resolution'], {
|
||||
name: 'mac',
|
||||
graphics: 'vmware-svga',
|
||||
auto_resolution: true,
|
||||
resolution: '1920x1080',
|
||||
}),
|
||||
{ name: 'mac', graphics: 'vmware-svga', auto_resolution: false },
|
||||
)
|
||||
|
||||
// graphicsLabel never renders auto resolution label for vmware-svga
|
||||
const svgaDetail = {
|
||||
graphics: 'vmware-svga',
|
||||
gpu: 'auto',
|
||||
resolution: '3200x1800',
|
||||
auto_resolution: true,
|
||||
displays: 1,
|
||||
}
|
||||
assert.equal(mod.graphicsLabel('zh-CN', svgaDetail, host4K150), mod.t('zh-CN', 'softwareGraphics'))
|
||||
assert.equal(mod.graphicsLabel('en-US', svgaDetail, host4K150), mod.t('en-US', 'softwareGraphics'))
|
||||
})
|
||||
|
||||
test('installer wizard draft enables auto resolution by default while preserving user fixed drafts (#7)', () => {
|
||||
const installerDraftVgpu = mod.initialWizardResolution(host4K150, true, 'reims-vgpu')
|
||||
assert.deepEqual(installerDraftVgpu, { auto_resolution: true, resolution: '3200x1800' })
|
||||
|
||||
const installerDraftSvga = mod.initialWizardResolution(host4K150, true, 'vmware-svga')
|
||||
assert.deepEqual(installerDraftSvga, { auto_resolution: false, resolution: '3200x1800' })
|
||||
|
||||
// Returning from a failed create preserves explicit auto_resolution: false
|
||||
const failedFixedDraft = {
|
||||
name: 'macos-tahoe',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: false,
|
||||
resolution: '2560x1440',
|
||||
borderless: false,
|
||||
}
|
||||
const effectiveFixed = mod.resolveEffectiveWizardOpts(
|
||||
failedFixedDraft,
|
||||
mod.resolveAutoDisplayPreset(host32K200, false, true),
|
||||
)
|
||||
assert.equal(effectiveFixed.auto_resolution, false)
|
||||
assert.equal(effectiveFixed.resolution, '2560x1440')
|
||||
})
|
||||
|
||||
test('effective wizard opts track host screen changes in auto mode without mutating fixed mode (#8)', () => {
|
||||
const autoOptsFrom4K = {
|
||||
name: 'macos-tahoe',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
borderless: false,
|
||||
}
|
||||
// Host switches to 3.2K screen while wizard stays open or restores an auto draft
|
||||
const effectiveOn32K = mod.resolveEffectiveWizardOpts(
|
||||
autoOptsFrom4K,
|
||||
mod.resolveAutoDisplayPreset(host32K200, false, true),
|
||||
)
|
||||
assert.equal(effectiveOn32K.auto_resolution, true)
|
||||
assert.equal(effectiveOn32K.resolution, '2880x1800')
|
||||
|
||||
// Borderless auto mode on 4K updates to 5120x2880
|
||||
const effectiveBorderless = mod.resolveEffectiveWizardOpts(
|
||||
{ ...autoOptsFrom4K, borderless: true },
|
||||
mod.resolveAutoDisplayPreset(host4K150, true, true),
|
||||
)
|
||||
assert.equal(effectiveBorderless.resolution, '5120x2880')
|
||||
|
||||
// Fixed mode keeps user-selected resolution even when host changes
|
||||
const fixedOpts = { ...autoOptsFrom4K, auto_resolution: false, resolution: '2560x1440' }
|
||||
const effectiveFixed = mod.resolveEffectiveWizardOpts(
|
||||
fixedOpts,
|
||||
mod.resolveAutoDisplayPreset(host32K200, false, true),
|
||||
)
|
||||
assert.equal(effectiveFixed.auto_resolution, false)
|
||||
assert.equal(effectiveFixed.resolution, '2560x1440')
|
||||
})
|
||||
|
||||
test('custom resolution canonicalizes on blur and save diff to match Go validator (#9)', () => {
|
||||
assert.equal(mod.canonicalResolution('3200 × 1800'), '3200x1800')
|
||||
assert.equal(mod.canonicalResolution(' 3200X1800 '), '3200x1800')
|
||||
assert.equal(mod.canonicalResolution('2400 x 1500'), '2400x1500')
|
||||
assert.equal(mod.canonicalResolution(''), '')
|
||||
|
||||
const presets = mod.windowDisplayPresets(host4K150, true)
|
||||
|
||||
// Typing a known preset with × or uppercase X snaps back and writes canonical preset value
|
||||
assert.deepEqual(
|
||||
mod.resolveCustomResBlur({
|
||||
resolution: '3200 × 1800',
|
||||
autoResolution: false,
|
||||
forceCustomRes: true,
|
||||
activePresets: presets,
|
||||
}),
|
||||
{ exitCustom: true, nextResolution: '3200x1800' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
mod.resolveCustomResBlur({
|
||||
resolution: '3200X1800',
|
||||
autoResolution: false,
|
||||
forceCustomRes: true,
|
||||
activePresets: presets,
|
||||
}),
|
||||
{ exitCustom: true, nextResolution: '3200x1800' },
|
||||
)
|
||||
|
||||
// Typing a non-preset valid size canonicalizes without exiting custom input
|
||||
assert.deepEqual(
|
||||
mod.resolveCustomResBlur({
|
||||
resolution: ' 2400 × 1500 ',
|
||||
autoResolution: false,
|
||||
forceCustomRes: true,
|
||||
activePresets: presets,
|
||||
}),
|
||||
{ exitCustom: false, nextResolution: '2400x1500' },
|
||||
)
|
||||
|
||||
// Save diff always canonicalizes resolution even if saved before blur
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['auto_resolution', 'resolution'], {
|
||||
name: 'mac',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: false,
|
||||
resolution: '3200 × 1800',
|
||||
}),
|
||||
{ name: 'mac', auto_resolution: false, resolution: '3200x1800' },
|
||||
)
|
||||
})
|
||||
|
||||
test('background baseline refresh syncs untouched fields so saving memory never overwrites external auto_resolution (#11)', () => {
|
||||
const initialBase = {
|
||||
name: 'mac',
|
||||
memory: '8G',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
}
|
||||
// User only edits memory
|
||||
const touched = new Set(mod.expandTouchedSettingsFields(['memory']))
|
||||
const editedForm = { ...initialBase, memory: '16G' }
|
||||
|
||||
// External CLI disables auto_resolution and sets fixed 2560x1440; background poll refreshes base
|
||||
const refreshedBase = {
|
||||
...initialBase,
|
||||
auto_resolution: false,
|
||||
resolution: '2560x1440',
|
||||
}
|
||||
const syncedForm = mod.syncUntouchedSettingsForm(editedForm, refreshedBase, touched)
|
||||
assert.equal(syncedForm.memory, '16G')
|
||||
assert.equal(syncedForm.auto_resolution, false)
|
||||
assert.equal(syncedForm.resolution, '2560x1440')
|
||||
|
||||
// Only memory differs from refreshedBase, so save diff only sends memory
|
||||
const dirtyFields = ['memory', 'auto_resolution', 'resolution'].filter(
|
||||
(k) => syncedForm[k] !== refreshedBase[k],
|
||||
)
|
||||
assert.deepEqual(dirtyFields, ['memory'])
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyFields, syncedForm), {
|
||||
name: 'mac',
|
||||
memory: '16G',
|
||||
})
|
||||
|
||||
// Touching resolution pairs both resolution and auto_resolution so background refresh preserves user edits
|
||||
const resTouched = new Set(mod.expandTouchedSettingsFields(['resolution']))
|
||||
assert.ok(resTouched.has('resolution'))
|
||||
assert.ok(resTouched.has('auto_resolution'))
|
||||
const editedResForm = { ...initialBase, auto_resolution: false, resolution: '1920x1080' }
|
||||
const syncedWhileEditingRes = mod.syncUntouchedSettingsForm(editedResForm, refreshedBase, resTouched)
|
||||
assert.equal(syncedWhileEditingRes.auto_resolution, false)
|
||||
assert.equal(syncedWhileEditingRes.resolution, '1920x1080')
|
||||
})
|
||||
|
||||
test('R2 #7: switching VMs resets settings draft to target VM baseline without leaking previous VM edits', () => {
|
||||
const baseA = {
|
||||
name: 'vm-a',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
memory: '8G',
|
||||
}
|
||||
const baseB = {
|
||||
name: 'vm-b',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '2880x1800',
|
||||
memory: '16G',
|
||||
}
|
||||
const touchedA = new Set(mod.expandTouchedSettingsFields(['resolution', 'memory']))
|
||||
const editedA = { ...baseA, auto_resolution: false, resolution: '2560x1440', memory: '12G' }
|
||||
|
||||
const switched = mod.reconcileSettingsFormOnBaseChange({
|
||||
previousVMKey: 'builtin.driver.reims-macos:vm-a',
|
||||
nextVMKey: 'builtin.driver.reims-macos:vm-b',
|
||||
form: editedA,
|
||||
base: baseB,
|
||||
touchedFields: touchedA,
|
||||
})
|
||||
assert.equal(switched.resetDraft, true)
|
||||
assert.deepEqual(switched.form, baseB)
|
||||
|
||||
const dirtyB = Object.keys(baseB).filter((k) => switched.form[k] !== baseB[k])
|
||||
assert.deepEqual(dirtyB, [])
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('vm-b', dirtyB, switched.form, baseB), { name: 'vm-b' })
|
||||
})
|
||||
|
||||
test('R2 #5: internal digit spaces never match presets, keep custom input visible, and block save', () => {
|
||||
const hostWith1080 = {
|
||||
...host4K150,
|
||||
display_presets: [
|
||||
...host4K150.display_presets,
|
||||
{ resolution: '1920x1080', label: '1920 × 1080', hidpi: false },
|
||||
],
|
||||
}
|
||||
|
||||
assert.equal(mod.canonicalResolution('1 920x1080'), '1 920x1080')
|
||||
assert.equal(mod.normalizeResolution('1 920x1080'), '1 920x1080')
|
||||
assert.equal(mod.isValidResolution('1 920x1080'), false)
|
||||
|
||||
// Even when forceCustomRes is false (custom input opened automatically due to non-preset old value),
|
||||
// pasting "1 920x1080" must NOT match 1920x1080 preset, must keep input visible, and must set resBad = true.
|
||||
const badState = mod.deriveSettingsResolutionState({
|
||||
form: { graphics: 'reims-vgpu', auto_resolution: false, resolution: '1 920x1080', borderless: false },
|
||||
displayProfile: hostWith1080,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: false,
|
||||
})
|
||||
assert.equal(badState.presetHit, false)
|
||||
assert.equal(badState.customRes, true)
|
||||
assert.equal(badState.resBad, true)
|
||||
|
||||
// Spaces around × or uppercase X still match preset and canonicalize to 3200x1800
|
||||
assert.equal(mod.isValidResolution('3200 × 1800'), true)
|
||||
assert.equal(mod.isValidResolution('3200X1800'), true)
|
||||
const goodState = mod.deriveSettingsResolutionState({
|
||||
form: { graphics: 'reims-vgpu', auto_resolution: false, resolution: '3200 × 1800', borderless: false },
|
||||
displayProfile: hostWith1080,
|
||||
fixedModeSupported: true,
|
||||
forceCustomRes: false,
|
||||
})
|
||||
assert.equal(goodState.presetHit, true)
|
||||
assert.equal(goodState.matchedPreset?.resolution, '3200x1800')
|
||||
assert.equal(goodState.resBad, false)
|
||||
assert.deepEqual(
|
||||
mod.resolveCustomResBlur({
|
||||
resolution: '3200 × 1800',
|
||||
autoResolution: false,
|
||||
forceCustomRes: false,
|
||||
activePresets: goodState.activePresets,
|
||||
}),
|
||||
{ exitCustom: true, nextResolution: '3200x1800' },
|
||||
)
|
||||
})
|
||||
|
||||
test('R2 #11: switching vGPU+auto to SVGA and resetting graphics leaves 0 changes; saving SVGA disables auto', () => {
|
||||
const base = {
|
||||
name: 'mac',
|
||||
graphics: 'reims-vgpu',
|
||||
auto_resolution: true,
|
||||
resolution: '3200x1800',
|
||||
}
|
||||
|
||||
// Temporarily switch to SVGA
|
||||
const svgaSwitch = mod.switchSettingsGraphics('vmware-svga')
|
||||
assert.deepEqual(svgaSwitch, { patch: { graphics: 'vmware-svga' }, forceCustomRes: false })
|
||||
const svgaForm = { ...base, ...svgaSwitch.patch }
|
||||
assert.equal(svgaForm.auto_resolution, true)
|
||||
|
||||
// Resetting graphics row back to reims-vgpu restores clean form with 0 changes
|
||||
const resetForm = { ...svgaForm, graphics: base.graphics }
|
||||
const dirtyAfterReset = ['graphics', 'auto_resolution', 'resolution'].filter((k) => resetForm[k] !== base[k])
|
||||
assert.deepEqual(dirtyAfterReset, [])
|
||||
assert.equal(mod.countChangedSettingsFields(dirtyAfterReset), 0)
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyAfterReset, resetForm, base), { name: 'mac' })
|
||||
|
||||
// Saving SVGA directly sends graphics: 'vmware-svga' and turns off auto_resolution when base had it on
|
||||
const dirtyOnSvga = ['graphics', 'auto_resolution', 'resolution'].filter((k) => svgaForm[k] !== base[k])
|
||||
assert.deepEqual(dirtyOnSvga, ['graphics'])
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', dirtyOnSvga, svgaForm, base), {
|
||||
name: 'mac',
|
||||
graphics: 'vmware-svga',
|
||||
auto_resolution: false,
|
||||
})
|
||||
|
||||
// If base already had auto_resolution: false, saving SVGA only sends graphics
|
||||
const baseFixed = { ...base, auto_resolution: false }
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', ['graphics'], { ...baseFixed, graphics: 'vmware-svga' }, baseFixed), {
|
||||
name: 'mac',
|
||||
graphics: 'vmware-svga',
|
||||
})
|
||||
})
|
||||
|
||||
test('R2 #3: CreateWizard preserves manual fixed resolution across SVGA create failure and return to vGPU', () => {
|
||||
const autoPreset = mod.resolveAutoDisplayPreset(host4K150, false, true)
|
||||
// Step 1: User starts on vGPU and manually picks fixed 2560x1440
|
||||
let opts = {
|
||||
name: 'macos-tahoe',
|
||||
graphics: 'reims-vgpu',
|
||||
...mod.initialWizardResolution(host4K150, true, 'reims-vgpu'),
|
||||
borderless: false,
|
||||
}
|
||||
let manualResolutionPicked = true
|
||||
opts = { ...opts, ...mod.selectWizardResolution('2560x1440', autoPreset) }
|
||||
assert.equal(opts.auto_resolution, false)
|
||||
assert.equal(opts.resolution, '2560x1440')
|
||||
|
||||
// Step 2: User switches to SVGA and submits; create fails and saves draft with manualResolution: true
|
||||
opts = { ...opts, ...mod.switchWizardGraphics({ graphics: 'vmware-svga', manualResolutionPicked, autoPreset }) }
|
||||
const failedDraft = {
|
||||
opts: mod.resolveEffectiveWizardOpts(opts, autoPreset),
|
||||
step: 5,
|
||||
manualResolution: manualResolutionPicked,
|
||||
}
|
||||
assert.equal(failedDraft.opts.graphics, 'vmware-svga')
|
||||
assert.equal(failedDraft.opts.auto_resolution, false)
|
||||
assert.equal(failedDraft.opts.resolution, '2560x1440')
|
||||
|
||||
// Step 3: Reopen wizard from failed draft and switch back to vGPU
|
||||
const restoredManual = mod.initialWizardManualResolution(failedDraft)
|
||||
assert.equal(restoredManual, true)
|
||||
const backToVgpu = mod.switchWizardGraphics({
|
||||
graphics: 'reims-vgpu',
|
||||
manualResolutionPicked: restoredManual,
|
||||
autoPreset,
|
||||
})
|
||||
const restoredOpts = { ...failedDraft.opts, ...backToVgpu }
|
||||
assert.equal(restoredOpts.graphics, 'reims-vgpu')
|
||||
assert.equal(restoredOpts.auto_resolution, false)
|
||||
assert.equal(restoredOpts.resolution, '2560x1440')
|
||||
|
||||
// Fallback behavior when draft.manualResolution is omitted
|
||||
assert.equal(mod.initialWizardManualResolution(null), false)
|
||||
assert.equal(
|
||||
mod.initialWizardManualResolution({ opts: { graphics: 'vmware-svga', auto_resolution: false } }),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
mod.initialWizardManualResolution({ opts: { graphics: 'reims-vgpu', auto_resolution: false } }),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test('R3 #3 & #6: turning off auto includes fixed resolution; switching to SVGA omits hidden invalid resolution', () => {
|
||||
// R3 #3: switching from auto back to fixed card matching display-0 resolution still submits explicit resolution
|
||||
// so any per-display list (e.g. 3200x1800,2560x1440) is replaced uniformly.
|
||||
const baseAuto = { name: 'mac', graphics: 'reims-vgpu', auto_resolution: true, resolution: '3200x1800' }
|
||||
const formFixed = { ...baseAuto, auto_resolution: false, resolution: '3200x1800' }
|
||||
assert.deepEqual(mod.buildSettingsSaveDiff('mac', ['auto_resolution'], formFixed, baseAuto), {
|
||||
name: 'mac',
|
||||
auto_resolution: false,
|
||||
resolution: '3200x1800',
|
||||
})
|
||||
|
||||
// R3 #6: typing invalid custom resolution then switching to SVGA does not submit hidden invalid resolution
|
||||
const baseVgpu = { name: 'mac', graphics: 'reims-vgpu', auto_resolution: false, resolution: '2560x1440' }
|
||||
const formSvgaWithHiddenInvalid = {
|
||||
...baseVgpu,
|
||||
graphics: 'vmware-svga',
|
||||
resolution: '1 920x1080',
|
||||
}
|
||||
assert.deepEqual(
|
||||
mod.buildSettingsSaveDiff('mac', ['graphics', 'resolution'], formSvgaWithHiddenInvalid, baseVgpu),
|
||||
{
|
||||
name: 'mac',
|
||||
graphics: 'vmware-svga',
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -14,7 +14,8 @@ import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Si
|
||||
import { CreatingVMView } from './components/CreatingVMView'
|
||||
import { VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
import { defaultGuestLang, recommendedMemoryGB } from './lib/format'
|
||||
import { initialWizardResolution } from './lib/displayResolution'
|
||||
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
|
||||
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
|
||||
import { LogLine, appendLog, createLogLine } from './lib/logs'
|
||||
@@ -956,6 +957,7 @@ export const App: React.FC = () => {
|
||||
defaultName = `macos-tahoe-${i}`
|
||||
}
|
||||
const isOffline = item.kind === 'offline' && !!item.version
|
||||
const graphics = state.host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
|
||||
setWizardDraft({
|
||||
step: 1,
|
||||
opts: {
|
||||
@@ -970,9 +972,9 @@ export const App: React.FC = () => {
|
||||
disk_size: '128G',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: 'reims-vgpu',
|
||||
graphics,
|
||||
gpu: state.host.recommended_gpu?.vulkan_icd ?? 'auto',
|
||||
resolution: recommendedResolution(state.host),
|
||||
...initialWizardResolution(state.host, fixedModeSupported, graphics),
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
capture: false,
|
||||
@@ -1463,6 +1465,7 @@ export const App: React.FC = () => {
|
||||
{showSettings && state && detail && (
|
||||
<Suspense fallback={null}>
|
||||
<SettingsModal
|
||||
key={`${selectedVM?.driver_id ?? ''}:${detail.name}`}
|
||||
locale={locale}
|
||||
detail={detail}
|
||||
driverID={selectedVM?.driver_id ?? ''}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useEffect, useState } from 'react'
|
||||
import React, { Suspense, lazy, useEffect, useMemo, useState } from 'react'
|
||||
import { useNetworkPlan } from '../lib/useNetworkPlan'
|
||||
import { NpcapDependency } from './NpcapDependency'
|
||||
import { NetworkErrorNotice } from './NetworkErrorNotice'
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
defaultGuestLang,
|
||||
findGPU,
|
||||
formatMemory,
|
||||
formatResolutionLabel,
|
||||
gpuCompatHint,
|
||||
gpuLabel,
|
||||
gpuOptionValue,
|
||||
@@ -21,22 +22,32 @@ import {
|
||||
memorySafeLimitGB,
|
||||
parseMemoryGB,
|
||||
recommendedCPUs,
|
||||
canKeepDisplayPreset,
|
||||
fullscreenDisplayPresets,
|
||||
FullscreenDisplayPreset,
|
||||
hidpiLooksLike,
|
||||
hostDisplayAdvice,
|
||||
hostDisplayDesc,
|
||||
resolveAutoDisplayPreset,
|
||||
windowDisplayPresets,
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
shortGPUName,
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import {
|
||||
AUTO_RESOLUTION_OPTION,
|
||||
buildResolutionOptions,
|
||||
initialWizardManualResolution,
|
||||
initialWizardResolution,
|
||||
resolveEffectiveWizardOpts,
|
||||
selectWizardResolution,
|
||||
supportsAutoResolution,
|
||||
switchWizardGraphics,
|
||||
toggleWizardBorderless,
|
||||
} from '../lib/displayResolution'
|
||||
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
|
||||
import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { api } from '../wails'
|
||||
|
||||
@@ -47,6 +58,7 @@ const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
|
||||
export interface WizardDraft {
|
||||
opts: CreateOpts
|
||||
step: number
|
||||
manualResolution?: boolean
|
||||
}
|
||||
|
||||
interface Props {
|
||||
@@ -106,6 +118,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
const activeDriver = drivers.find((d) => d.id === driverID)
|
||||
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
|
||||
|
||||
const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga'
|
||||
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
|
||||
name: 'macos-tahoe',
|
||||
dir: '',
|
||||
@@ -120,11 +133,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
disk: '',
|
||||
disk_mode: 'copy',
|
||||
disk_controller: 'nvme',
|
||||
graphics: host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga',
|
||||
graphics: defaultGraphics,
|
||||
// Default to "auto" rather than a DriverStore FileRepository ICD path so
|
||||
// Windows GPU driver updates never break existing VM configs.
|
||||
gpu: 'auto',
|
||||
resolution: recommendedResolution(host),
|
||||
...initialWizardResolution(host, fixedModeSupported, defaultGraphics),
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
...(captureSupported ? { capture: false } : {}),
|
||||
@@ -136,6 +149,9 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
guest_lang: defaultGuestLang(locale),
|
||||
start: true,
|
||||
})
|
||||
const [manualResolutionPicked, setManualResolutionPicked] = useState(() =>
|
||||
initialWizardManualResolution(draft),
|
||||
)
|
||||
const [networkTouched, setNetworkTouched] = useState(!!draft?.opts)
|
||||
const set = (patch: Partial<CreateOpts>) => setOpts((o) => ({ ...o, ...patch }))
|
||||
const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off')
|
||||
@@ -157,9 +173,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
}, [step, networkMode, locale])
|
||||
const windowPresets = windowDisplayPresets(host, fixedModeSupported)
|
||||
const fullscreenPresets = fullscreenDisplayPresets(host)
|
||||
const activePresets: FullscreenDisplayPreset[] = opts.borderless ? fullscreenPresets : windowPresets
|
||||
const autoPreset = resolveAutoDisplayPreset(host, !!opts.borderless, fixedModeSupported)
|
||||
const effectiveOpts = useMemo(
|
||||
() => resolveEffectiveWizardOpts(opts, autoPreset),
|
||||
[opts, autoPreset.resolution],
|
||||
)
|
||||
const changeGraphics = (graphics: CreateOpts['graphics']) => {
|
||||
set(switchWizardGraphics({ graphics, manualResolutionPicked, autoPreset }))
|
||||
}
|
||||
const resArt = (r: string) => {
|
||||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
|
||||
return m ? <ScreenArt w={Number(m[1])} h={Number(m[2])} /> : <ScreenArt w={16} h={10} />
|
||||
}
|
||||
|
||||
const buildPayload = (): CreateOpts => {
|
||||
const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' }
|
||||
const p: CreateOpts = { ...effectiveOpts, offline: effectiveOpts.source_mode === 'offline' }
|
||||
if (!captureSupported) {
|
||||
delete p.capture
|
||||
}
|
||||
@@ -233,7 +262,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
.finally(() => { if (live) setChecking(false) })
|
||||
}, 200)
|
||||
return () => { live = false; clearTimeout(timer) }
|
||||
}, [step, reviewed, opts, validationRefresh, captureSupported])
|
||||
}, [step, reviewed, effectiveOpts, validationRefresh, captureSupported])
|
||||
|
||||
const pickDir = async () => {
|
||||
const dir = await api.PickDirectory(tr('vmDir'))
|
||||
@@ -247,7 +276,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
|
||||
const handleCreate = () => {
|
||||
if (dependencyBusy || networkBlocked) return
|
||||
onSubmit(buildPayload(), { opts, step: REVIEW_STEP })
|
||||
onSubmit(buildPayload(), { opts: effectiveOpts, step: REVIEW_STEP, manualResolution: manualResolutionPicked })
|
||||
}
|
||||
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
|
||||
|
||||
@@ -545,7 +574,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<Segmented
|
||||
label={tr('graphicsBackend')}
|
||||
value={opts.graphics}
|
||||
onChange={(graphics) => set({ graphics })}
|
||||
onChange={changeGraphics}
|
||||
options={[
|
||||
{ value: 'reims-vgpu' as const, label: tr('graphicsReimsShort') },
|
||||
{ value: 'vmware-svga' as const, label: tr('graphicsSvgaShort') },
|
||||
@@ -566,7 +595,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<button
|
||||
type="button"
|
||||
className="link-btn"
|
||||
onClick={() => set({ graphics: 'vmware-svga' })}
|
||||
onClick={() => changeGraphics('vmware-svga')}
|
||||
>
|
||||
{tr('gpuSwitchSvga')}
|
||||
</button>
|
||||
@@ -602,23 +631,47 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
disabled={opts.graphics !== 'reims-vgpu'}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr, windowPresets) : undefined].filter(Boolean).join(' · ') || undefined}
|
||||
control={
|
||||
<PopupSelect
|
||||
id="vm-res"
|
||||
block={
|
||||
<OptionCards
|
||||
label={tr('resolution')}
|
||||
value={opts.resolution}
|
||||
onChange={(resolution) => set({ resolution })}
|
||||
options={(opts.borderless ? fullscreenPresets : windowPresets).map((p: FullscreenDisplayPreset) => ({
|
||||
value: p.resolution,
|
||||
label: p.label,
|
||||
detail: [
|
||||
p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '',
|
||||
p.scaleBadge ?? '',
|
||||
p.native ? tr('resNativeBadge') : '',
|
||||
p.scaleToFit ? tr('resScaleToFitWindow') : '',
|
||||
p.recommended ? tr('recommendedBadge') : '',
|
||||
].filter(Boolean).join(' · ') || undefined,
|
||||
}))}
|
||||
value={supportsAutoResolution(opts.graphics) && opts.auto_resolution ? AUTO_RESOLUTION_OPTION : opts.resolution}
|
||||
onChange={(v) => {
|
||||
setManualResolutionPicked(v !== AUTO_RESOLUTION_OPTION)
|
||||
set(selectWizardResolution(v, autoPreset))
|
||||
}}
|
||||
options={buildResolutionOptions({
|
||||
graphics: opts.graphics,
|
||||
autoPreset,
|
||||
activePresets,
|
||||
}).map((item) => {
|
||||
const p = item.preset!
|
||||
if (item.kind === 'auto') {
|
||||
return {
|
||||
value: item.value,
|
||||
title: tr('resAuto'),
|
||||
sub: tr('resAutoSub', { res: p.label }),
|
||||
art: resArt(p.resolution),
|
||||
badges: [
|
||||
p.hidpi ? tr('hidpiPresetBadge') : '',
|
||||
p.scaleBadge ?? '',
|
||||
tr('recommendedBadge'),
|
||||
].filter(Boolean),
|
||||
}
|
||||
}
|
||||
return {
|
||||
value: item.value,
|
||||
title: p.label,
|
||||
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
|
||||
art: resArt(p.resolution),
|
||||
badges: [
|
||||
p.hidpi ? tr('hidpiPresetBadge') : '',
|
||||
p.scaleBadge ?? '',
|
||||
p.native ? tr('resNativeBadge') : '',
|
||||
p.scaleToFit ? tr('resScaleToFitWindow') : '',
|
||||
p.recommended ? tr('recommendedBadge') : '',
|
||||
].filter(Boolean),
|
||||
}
|
||||
})}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -686,12 +739,14 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<Switch
|
||||
label={tr('fullscreenLaunch')}
|
||||
checked={!!opts.borderless}
|
||||
onChange={(borderless) => {
|
||||
const list = borderless ? fullscreenPresets : windowPresets
|
||||
const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless))
|
||||
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
|
||||
set(keep ? { borderless } : { borderless, resolution: fallback })
|
||||
}}
|
||||
onChange={(borderless) => set(toggleWizardBorderless({
|
||||
borderless,
|
||||
opts,
|
||||
host,
|
||||
fixedModeSupported,
|
||||
windowPresets,
|
||||
fullscreenPresets,
|
||||
}))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -707,7 +762,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
<Review
|
||||
locale={locale}
|
||||
host={host}
|
||||
opts={opts}
|
||||
opts={effectiveOpts}
|
||||
captureSupported={captureSupported}
|
||||
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
|
||||
issues={issues}
|
||||
@@ -801,7 +856,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, i
|
||||
? tr('summaryInstallerSource', { file: fileName(opts.installer) })
|
||||
: tr('summaryDiskSource', { file: fileName(opts.disk) })
|
||||
|
||||
const res = (opts.resolution ?? '').replace(/x/i, ' × ')
|
||||
const res = formatResolutionLabel(opts.resolution ?? '', !!opts.auto_resolution, tr)
|
||||
const graphicsRows: Row[] = opts.graphics === 'reims-vgpu'
|
||||
? [
|
||||
{ label: tr('factGraphics'), value: `${gpuLabel(locale, opts.gpu, host)} · reims-vgpu` },
|
||||
|
||||
@@ -13,18 +13,26 @@ import {
|
||||
memorySafeLimitGB,
|
||||
parseMemoryGB,
|
||||
recommendedCPUs,
|
||||
canKeepDisplayPreset,
|
||||
fullscreenDisplayPresets,
|
||||
FullscreenDisplayPreset,
|
||||
hidpiLooksLike,
|
||||
hostDisplayAdvice,
|
||||
hostDisplayDesc,
|
||||
windowDisplayPresets,
|
||||
recommendedMemoryGB,
|
||||
recommendedResolution,
|
||||
shortGPUName,
|
||||
sshCommand,
|
||||
} from '../lib/format'
|
||||
import {
|
||||
buildResolutionOptions,
|
||||
buildSettingsSaveDiff,
|
||||
countChangedSettingsFields,
|
||||
deriveSettingsResolutionState,
|
||||
expandTouchedSettingsFields,
|
||||
normalizeResolution,
|
||||
reconcileSettingsFormOnBaseChange,
|
||||
resolveCustomResBlur,
|
||||
selectSettingsResolution,
|
||||
switchSettingsGraphics,
|
||||
toggleSettingsBorderless,
|
||||
} from '../lib/displayResolution'
|
||||
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats, DiskCache } from '../types'
|
||||
@@ -70,6 +78,7 @@ const FIELD_CAT: Record<Field, Cat> = {
|
||||
graphics: 'display',
|
||||
gpu: 'display',
|
||||
resolution: 'display',
|
||||
auto_resolution: 'display',
|
||||
displays: 'display',
|
||||
borderless: 'display',
|
||||
disk_controller: 'storage',
|
||||
@@ -88,18 +97,16 @@ const FIELDS = Object.keys(FIELD_CAT) as Field[]
|
||||
|
||||
const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
|
||||
const CUSTOM = '__custom'
|
||||
const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i
|
||||
|
||||
|
||||
const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase()
|
||||
const normRes = (s: string | undefined) => (s ?? '').replace(/\s/g, '').replace(/×/g, 'x').toLowerCase()
|
||||
|
||||
/** Whether two values of a field mean the same thing to reims-ctl. */
|
||||
function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean {
|
||||
switch (field) {
|
||||
case 'memory': return parseMemoryGB(a as string) === parseMemoryGB(b as string)
|
||||
case 'gpu': return normPath(a as string) === normPath(b as string)
|
||||
case 'resolution': return normRes(a as string) === normRes(b as string)
|
||||
case 'resolution': return normalizeResolution(a as string) === normalizeResolution(b as string)
|
||||
case 'log_level':
|
||||
case 'extra_args':
|
||||
case 'audio_backend':
|
||||
@@ -122,6 +129,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
|
||||
disk_controller: detail.disk_controller,
|
||||
disk_cache: (detail.disk_cache as DiskCache) || 'default',
|
||||
resolution: detail.resolution,
|
||||
auto_resolution: !!detail.auto_resolution,
|
||||
borderless: detail.borderless,
|
||||
...(detail.capture_supported ? { capture: detail.capture } : {}),
|
||||
gpu: icd ?? (detail.gpu || 'auto'),
|
||||
@@ -187,24 +195,47 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
const tzBusy = timezone.tzBusy
|
||||
const pane = useRef<HTMLDivElement>(null)
|
||||
|
||||
const presets = windowDisplayPresets(displayProfile, fixedModeSupported)
|
||||
const fsPresets = fullscreenDisplayPresets(displayProfile)
|
||||
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
|
||||
const presetHit = activePresets.some((p) => same('resolution', p.resolution, form.resolution))
|
||||
const [forceCustomRes, setCustomRes] = useState(false)
|
||||
const customRes = forceCustomRes || !presetHit
|
||||
const { presets, fsPresets, activePresets, autoPreset, customRes, resValue, resBad } = deriveSettingsResolutionState({
|
||||
form,
|
||||
displayProfile,
|
||||
fixedModeSupported,
|
||||
forceCustomRes,
|
||||
})
|
||||
const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level))
|
||||
|
||||
// The detail the panel opened with can be a stale one (reopened right after
|
||||
// a save, before the refreshed detail arrives): follow newer details until
|
||||
// the person changes something.
|
||||
const edited = useRef(false)
|
||||
// a save, before the refreshed detail arrives) or refreshed in the background:
|
||||
// sync untouched fields from the latest baseline while preserving user edits.
|
||||
const vmIdentity = `${driverID}:${detail.name}`
|
||||
const vmIdentityRef = useRef(vmIdentity)
|
||||
const touchedFieldsRef = useRef<Set<Field>>(new Set())
|
||||
useEffect(() => {
|
||||
if (edited.current) return
|
||||
setForm(base)
|
||||
setCustomRes(false)
|
||||
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
}, [base])
|
||||
const prevKey = vmIdentityRef.current
|
||||
vmIdentityRef.current = vmIdentity
|
||||
if (prevKey !== vmIdentity) {
|
||||
touchedFieldsRef.current.clear()
|
||||
setIssues([])
|
||||
setErr('')
|
||||
setCustomRes(false)
|
||||
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
} else {
|
||||
const touched = touchedFieldsRef.current
|
||||
if (!touched.has('resolution') && !touched.has('auto_resolution')) {
|
||||
setCustomRes(false)
|
||||
}
|
||||
if (!touched.has('log_level')) {
|
||||
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
}
|
||||
}
|
||||
setForm((cur) => reconcileSettingsFormOnBaseChange({
|
||||
previousVMKey: prevKey,
|
||||
nextVMKey: vmIdentity,
|
||||
form: cur,
|
||||
base,
|
||||
touchedFields: touchedFieldsRef.current,
|
||||
}).form)
|
||||
}, [base, vmIdentity])
|
||||
|
||||
useEffect(() => {
|
||||
setForm((f) => {
|
||||
@@ -216,25 +247,34 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
}, [detail.capture_supported, detail.capture])
|
||||
|
||||
const set = (patch: Partial<SetOpts>) => {
|
||||
edited.current = true
|
||||
const touched = expandTouchedSettingsFields(Object.keys(patch)) as Field[]
|
||||
for (const f of touched) touchedFieldsRef.current.add(f)
|
||||
setForm((f) => ({ ...f, ...patch }))
|
||||
const touched = Object.keys(patch)
|
||||
setIssues((list) => list.filter((i) => !touched.includes(i.field)))
|
||||
setIssues((list) => list.filter((i) => !touched.includes(i.field as Field)))
|
||||
}
|
||||
const dirty = (f: Field) => (f === 'capture' && !detail.capture_supported ? false : !same(f, form[f], base[f]))
|
||||
const reset = (f: Field) => () => {
|
||||
set({ [f]: base[f] } as Partial<SetOpts>)
|
||||
if (f === 'resolution' || f === 'borderless') setCustomRes(false)
|
||||
const toClear = expandTouchedSettingsFields([f]) as Field[]
|
||||
for (const field of toClear) touchedFieldsRef.current.delete(field)
|
||||
setForm((cur) => {
|
||||
const next = { ...cur }
|
||||
for (const field of toClear) {
|
||||
;(next as unknown as Record<string, unknown>)[field] = (base as unknown as Record<string, unknown>)[field]
|
||||
}
|
||||
return next
|
||||
})
|
||||
setIssues((list) => list.filter((i) => !toClear.includes(i.field as Field)))
|
||||
if (f === 'resolution' || f === 'auto_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)
|
||||
const changedIn = (c: Cat) => changed.filter((f) => FIELD_CAT[f] === c).length
|
||||
const changedCount = countChangedSettingsFields(changed)
|
||||
const changedIn = (c: Cat) => countChangedSettingsFields(changed.filter((f) => FIELD_CAT[f] === c))
|
||||
const issueOf = (f: Field) => issues.find((i) => i.field === f)?.message
|
||||
const issueIn = (c: Cat) => issues.some((i) => FIELD_CAT[i.field as Field] === c) || (c === 'display' && resBad)
|
||||
const strayIssues = issues.filter((i) => !(i.field in FIELD_CAT))
|
||||
|
||||
// Inline checks the backend would also reject, so the row says it first.
|
||||
const resBad = customRes && !RES_RE.test(form.resolution ?? '')
|
||||
const sshOn = (form.ssh_port ?? 0) > 0
|
||||
const localBlock = resBad
|
||||
const nestedVirtAvailable = host.whpx === 'ready' && host.whpx_caps?.nested_vmx && !host.needs_cold_reboot_workaround
|
||||
@@ -283,8 +323,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
setIssues([])
|
||||
setBusy(true)
|
||||
try {
|
||||
const diff: SetOpts = { name: detail.name }
|
||||
for (const f of changed) (diff as unknown as Record<string, unknown>)[f] = form[f]
|
||||
const diff = buildSettingsSaveDiff(detail.name, changed, form, base)
|
||||
const iss = await api.ValidateSet(diff)
|
||||
if (iss && iss.length > 0) {
|
||||
setIssues(iss)
|
||||
@@ -302,7 +341,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
}
|
||||
|
||||
const resetAll = () => {
|
||||
edited.current = false
|
||||
touchedFieldsRef.current.clear()
|
||||
setForm(base)
|
||||
setIssues([])
|
||||
setCustomRes(false)
|
||||
@@ -499,19 +538,21 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
const vgpu = form.graphics !== 'vmware-svga'
|
||||
const targetDisp = activeTargetDisplay
|
||||
const hidpiAdvice = hostDisplayAdvice(displayProfile, tr, presets)
|
||||
const resValue = customRes ? CUSTOM : activePresets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
|
||||
const changeGraphics = (graphics: string) => {
|
||||
const next = switchSettingsGraphics(graphics)
|
||||
if (next.forceCustomRes !== undefined) setCustomRes(next.forceCustomRes)
|
||||
set(next.patch)
|
||||
}
|
||||
const toggleBorderless = (borderless: boolean) => {
|
||||
const targetPresets = borderless ? fsPresets : presets
|
||||
if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) {
|
||||
const nextRes = borderless
|
||||
? (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 })
|
||||
set(toggleSettingsBorderless({
|
||||
borderless,
|
||||
form,
|
||||
displayProfile,
|
||||
targetDisplay: targetDisp,
|
||||
presets,
|
||||
fsPresets,
|
||||
customRes,
|
||||
}))
|
||||
}
|
||||
const resArt = (r: string) => {
|
||||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
|
||||
@@ -530,7 +571,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<Segmented
|
||||
label={tr('graphicsBackend')}
|
||||
value={form.graphics}
|
||||
onChange={(graphics) => set({ graphics })}
|
||||
onChange={changeGraphics}
|
||||
options={[
|
||||
{ value: 'reims-vgpu', label: tr('graphicsReimsShort') },
|
||||
{ value: 'vmware-svga', label: tr('graphicsSvgaShort') },
|
||||
@@ -553,7 +594,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
<button
|
||||
type="button"
|
||||
className="link-btn"
|
||||
onClick={() => set({ graphics: 'vmware-svga' })}
|
||||
onClick={() => changeGraphics('vmware-svga')}
|
||||
>
|
||||
{tr('gpuSwitchSvga')}
|
||||
</button>
|
||||
@@ -577,7 +618,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
/>
|
||||
<SetRow
|
||||
{...rowProps('resolution')}
|
||||
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
|
||||
dirty={dirty('resolution') || dirty('auto_resolution')}
|
||||
onReset={reset('resolution')}
|
||||
disabled={!vgpu}
|
||||
reason={tr('gpuSvgaReason')}
|
||||
error={issueOf('resolution') ?? issueOf('auto_resolution') ?? (resBad ? tr('resInvalid') : undefined)}
|
||||
title={tr('resolution')}
|
||||
desc={hostDisplayDesc(host, tr, activeTargetDisplay, (d) =>
|
||||
tr('targetDisplayHint', {
|
||||
@@ -593,13 +638,41 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
label={tr('resolution')}
|
||||
value={resValue}
|
||||
onChange={(v) => {
|
||||
if (v === CUSTOM) { setCustomRes(true); return }
|
||||
setCustomRes(false)
|
||||
set({ resolution: v })
|
||||
const next = selectSettingsResolution({ value: v, form, base, autoPreset })
|
||||
setCustomRes(next.forceCustomRes)
|
||||
set(next.patch)
|
||||
}}
|
||||
options={[
|
||||
...activePresets.map((p) => ({
|
||||
value: p.resolution,
|
||||
options={buildResolutionOptions({
|
||||
graphics: form.graphics,
|
||||
autoPreset,
|
||||
activePresets,
|
||||
includeCustom: true,
|
||||
}).map((item) => {
|
||||
if (item.kind === 'auto') {
|
||||
const p = item.preset!
|
||||
return {
|
||||
value: item.value,
|
||||
title: tr('resAuto'),
|
||||
sub: tr('resAutoSub', { res: p.label }),
|
||||
art: resArt(p.resolution),
|
||||
badges: [
|
||||
p.hidpi ? tr('hidpiPresetBadge') : '',
|
||||
p.scaleBadge ?? '',
|
||||
tr('recommendedBadge'),
|
||||
].filter(Boolean),
|
||||
}
|
||||
}
|
||||
if (item.kind === 'custom') {
|
||||
return {
|
||||
value: item.value,
|
||||
title: tr('resCustom'),
|
||||
sub: tr('resCustomSub'),
|
||||
art: <span className="screen-art custom" aria-hidden="true" />,
|
||||
}
|
||||
}
|
||||
const p = item.preset!
|
||||
return {
|
||||
value: item.value,
|
||||
title: p.label,
|
||||
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
|
||||
art: resArt(p.resolution),
|
||||
@@ -610,9 +683,8 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
p.scaleToFit ? tr('resScaleToFitWindow') : '',
|
||||
p.recommended ? tr('recommendedBadge') : '',
|
||||
].filter(Boolean),
|
||||
})),
|
||||
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> },
|
||||
]}
|
||||
}
|
||||
})}
|
||||
/>
|
||||
{customRes && (
|
||||
<input
|
||||
@@ -622,6 +694,20 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
autoFocus
|
||||
value={form.resolution ?? ''}
|
||||
onChange={(e) => set({ resolution: e.target.value })}
|
||||
onBlur={() => {
|
||||
const blurred = resolveCustomResBlur({
|
||||
resolution: form.resolution,
|
||||
autoResolution: form.auto_resolution,
|
||||
forceCustomRes,
|
||||
activePresets,
|
||||
})
|
||||
if (blurred.nextResolution !== undefined && blurred.nextResolution !== form.resolution) {
|
||||
set({ resolution: blurred.nextResolution })
|
||||
}
|
||||
if (blurred.exitCustom) {
|
||||
setCustomRes(false)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!form.borderless && hidpiAdvice && <div className="srow-desc res-advice">{hidpiAdvice}</div>}
|
||||
@@ -904,10 +990,10 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
|
||||
<div className="dialog-foot">
|
||||
<span className="foot-status" aria-live="polite">
|
||||
{changed.length > 0
|
||||
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changed.length })}</>
|
||||
{changedCount > 0
|
||||
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changedCount })}</>
|
||||
: <span className="muted">{tr('noChanges')}</span>}
|
||||
{changed.length > 0 && (
|
||||
{changedCount > 0 && (
|
||||
<button type="button" className="link-btn" disabled={busy} onClick={resetAll}>{tr('resetAll')}</button>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ChevronRight, Copy } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { formatResolutionLabel } from '../../lib/format'
|
||||
import { Locale, VMDetail, VMInfo } from '../../types'
|
||||
import { IconButton } from '../../ui/controls'
|
||||
|
||||
@@ -16,6 +17,9 @@ interface Props {
|
||||
/** 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 resolutionValue = detail
|
||||
? (detail.graphics !== 'vmware-svga' && detail.auto_resolution ? formatResolutionLabel(detail.resolution, true, tr) : detail.resolution)
|
||||
: ''
|
||||
const copyTechSummary = () => {
|
||||
if (!detail) {
|
||||
if (!vmInfo) return
|
||||
@@ -32,7 +36,7 @@ export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmIn
|
||||
`${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('resolution')}: ${detail.displays} × ${resolutionValue}`,
|
||||
`${tr('fieldController')}: ${detail.disk_controller}`,
|
||||
`${tr('fieldDisk')}: ${detail.disk}`,
|
||||
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`,
|
||||
@@ -71,7 +75,7 @@ export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmIn
|
||||
<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('resolution')}</dt><dd>{detail.displays} × {resolutionValue}</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>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
export const coreZh: Record<string, string> = {
|
||||
"affinityMenu": "处理器相关性…",
|
||||
"appearance": "外观",
|
||||
"autoResolution": "自动分辨率",
|
||||
"backToEdit": "返回修改",
|
||||
"borderless": "无边框全屏",
|
||||
"cancel": "取消",
|
||||
@@ -138,6 +139,8 @@ export const coreZh: Record<string, string> = {
|
||||
"quitFailed": "已取消退出",
|
||||
"quitInProgress": "正在退出…",
|
||||
"refresh": "刷新",
|
||||
"resAuto": "自动",
|
||||
"resAutoValue": "自动({res})",
|
||||
"resLooksLike": "看起来像 {w} × {h}",
|
||||
"resizeLogPanel": "拖动调整日志高度",
|
||||
"resolution": "分辨率",
|
||||
@@ -215,6 +218,7 @@ export const coreZh: Record<string, string> = {
|
||||
export const coreEn: Record<string, string> = {
|
||||
"affinityMenu": "Processor Affinity…",
|
||||
"appearance": "Appearance",
|
||||
"autoResolution": "Auto resolution",
|
||||
"backToEdit": "Edit and retry",
|
||||
"borderless": "Borderless full screen",
|
||||
"cancel": "Cancel",
|
||||
@@ -350,6 +354,8 @@ export const coreEn: Record<string, string> = {
|
||||
"quitFailed": "Quit canceled",
|
||||
"quitInProgress": "Quitting…",
|
||||
"refresh": "Refresh",
|
||||
"resAuto": "Auto",
|
||||
"resAutoValue": "Auto ({res})",
|
||||
"resLooksLike": "Looks like {w} × {h}",
|
||||
"resizeLogPanel": "Drag to resize log panel",
|
||||
"resolution": "Resolution",
|
||||
|
||||
@@ -454,6 +454,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"qemuASLR": "自动为 QEMU 启用 ASLR",
|
||||
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
|
||||
"recommendedBadge": "推荐",
|
||||
"resAutoSub": "当前屏 {res}",
|
||||
"resCustom": "自定义",
|
||||
"resCustomSub": "宽 × 高",
|
||||
"resInvalid": "格式为 宽x高,例如 2560x1600",
|
||||
@@ -1003,6 +1004,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"qemuASLR": "Automatically enable ASLR for QEMU",
|
||||
"qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
|
||||
"recommendedBadge": "Recommended",
|
||||
"resAutoSub": "Follows display · {res}",
|
||||
"resCustom": "Custom",
|
||||
"resCustomSub": "Width × height",
|
||||
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
|
||||
|
||||
@@ -79,6 +79,7 @@ export type I18nKey =
|
||||
| "audioDisabledReason"
|
||||
| "audioTroubleshootNote"
|
||||
| "autoPinPCores"
|
||||
| "autoResolution"
|
||||
| "back"
|
||||
| "backToEdit"
|
||||
| "borderless"
|
||||
@@ -881,6 +882,9 @@ export type I18nKey =
|
||||
| "quitInProgress"
|
||||
| "recommendedBadge"
|
||||
| "refresh"
|
||||
| "resAuto"
|
||||
| "resAutoSub"
|
||||
| "resAutoValue"
|
||||
| "resCustom"
|
||||
| "resCustomSub"
|
||||
| "resInvalid"
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import {
|
||||
canKeepDisplayPreset,
|
||||
FullscreenDisplayPreset,
|
||||
fullscreenDisplayPresets,
|
||||
recommendedResolution,
|
||||
resolveAutoDisplayPreset,
|
||||
windowDisplayPresets,
|
||||
} from './format'
|
||||
import { CreateOpts, DisplayInfo, HostReport, SetOpts } from '../types'
|
||||
|
||||
export const AUTO_RESOLUTION_OPTION = '__auto'
|
||||
export const CUSTOM_RESOLUTION_OPTION = '__custom'
|
||||
const CANONICAL_RESOLUTION_RE = /^\d{3,5}x\d{3,5}$/
|
||||
|
||||
export function canonicalResolution(raw: string | undefined): string {
|
||||
const trimmed = (raw ?? '').trim()
|
||||
const m = /^(\d+)\s*[x×X]\s*(\d+)$/.exec(trimmed)
|
||||
return m ? `${m[1]}x${m[2]}` : trimmed
|
||||
}
|
||||
|
||||
export const normalizeResolution = (raw: string | undefined) => canonicalResolution(raw).toLowerCase()
|
||||
|
||||
export function isValidResolution(raw: string | undefined): boolean {
|
||||
return CANONICAL_RESOLUTION_RE.test(canonicalResolution(raw))
|
||||
}
|
||||
|
||||
interface ResolutionOptionItem {
|
||||
value: string
|
||||
kind: 'auto' | 'preset' | 'custom'
|
||||
preset?: FullscreenDisplayPreset
|
||||
}
|
||||
|
||||
export function buildResolutionOptions(params: {
|
||||
graphics?: string
|
||||
autoPreset: FullscreenDisplayPreset
|
||||
activePresets: FullscreenDisplayPreset[]
|
||||
includeCustom?: boolean
|
||||
}): ResolutionOptionItem[] {
|
||||
const items: ResolutionOptionItem[] = []
|
||||
if (supportsAutoResolution(params.graphics)) {
|
||||
items.push({ value: AUTO_RESOLUTION_OPTION, kind: 'auto', preset: params.autoPreset })
|
||||
}
|
||||
for (const preset of params.activePresets) {
|
||||
items.push({ value: preset.resolution, kind: 'preset', preset })
|
||||
}
|
||||
if (params.includeCustom) {
|
||||
items.push({ value: CUSTOM_RESOLUTION_OPTION, kind: 'custom' })
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
export function supportsAutoResolution(graphics: string | undefined): boolean {
|
||||
return graphics !== 'vmware-svga'
|
||||
}
|
||||
|
||||
export function deriveSettingsResolutionState(params: {
|
||||
form: Pick<SetOpts, 'graphics' | 'resolution' | 'auto_resolution' | 'borderless'>
|
||||
displayProfile: HostReport
|
||||
fixedModeSupported: boolean
|
||||
forceCustomRes: boolean
|
||||
}) {
|
||||
const { form, displayProfile, fixedModeSupported, forceCustomRes } = params
|
||||
const vgpu = supportsAutoResolution(form.graphics)
|
||||
const autoOn = vgpu && !!form.auto_resolution
|
||||
const presets = windowDisplayPresets(displayProfile, fixedModeSupported)
|
||||
const fsPresets = fullscreenDisplayPresets(displayProfile)
|
||||
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
|
||||
const autoPreset = resolveAutoDisplayPreset(displayProfile, !!form.borderless, fixedModeSupported)
|
||||
const matchedPreset = activePresets.find((p) => normalizeResolution(p.resolution) === normalizeResolution(form.resolution))
|
||||
const presetHit = !!matchedPreset
|
||||
const customRes = vgpu && !autoOn && (forceCustomRes || !presetHit)
|
||||
const resValue = autoOn
|
||||
? AUTO_RESOLUTION_OPTION
|
||||
: (customRes ? CUSTOM_RESOLUTION_OPTION : matchedPreset?.resolution)
|
||||
const resBad = vgpu && !autoOn && customRes && !isValidResolution(form.resolution)
|
||||
return { presets, fsPresets, activePresets, autoPreset, matchedPreset, presetHit, customRes, resValue, resBad }
|
||||
}
|
||||
|
||||
export function selectSettingsResolution(params: {
|
||||
value: string
|
||||
form: Pick<SetOpts, 'resolution'>
|
||||
base: Pick<SetOpts, 'resolution'>
|
||||
autoPreset: FullscreenDisplayPreset
|
||||
}): { patch: Partial<SetOpts>; forceCustomRes: boolean } {
|
||||
const { value, form, base, autoPreset } = params
|
||||
if (value === AUTO_RESOLUTION_OPTION) {
|
||||
return {
|
||||
patch: { auto_resolution: true, resolution: base.resolution },
|
||||
forceCustomRes: false,
|
||||
}
|
||||
}
|
||||
if (value === CUSTOM_RESOLUTION_OPTION) {
|
||||
return {
|
||||
patch: { auto_resolution: false, resolution: form.resolution || autoPreset.resolution },
|
||||
forceCustomRes: true,
|
||||
}
|
||||
}
|
||||
return {
|
||||
patch: { auto_resolution: false, resolution: value },
|
||||
forceCustomRes: false,
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldExitCustomResOnBlur(params: {
|
||||
autoResolution?: boolean
|
||||
forceCustomRes: boolean
|
||||
presetHit: boolean
|
||||
}): boolean {
|
||||
return !params.autoResolution && params.forceCustomRes && params.presetHit
|
||||
}
|
||||
|
||||
export function resolveCustomResBlur(params: {
|
||||
resolution?: string
|
||||
autoResolution?: boolean
|
||||
forceCustomRes: boolean
|
||||
activePresets: FullscreenDisplayPreset[]
|
||||
}): { exitCustom: boolean; nextResolution?: string } {
|
||||
const { resolution, autoResolution, forceCustomRes, activePresets } = params
|
||||
if (autoResolution) return { exitCustom: false }
|
||||
const matched = activePresets.find((p) => normalizeResolution(p.resolution) === normalizeResolution(resolution))
|
||||
if (matched) {
|
||||
return {
|
||||
exitCustom: forceCustomRes || true,
|
||||
nextResolution: matched.resolution,
|
||||
}
|
||||
}
|
||||
if (isValidResolution(resolution)) {
|
||||
const canonical = canonicalResolution(resolution)
|
||||
if (canonical && canonical !== resolution) {
|
||||
return { exitCustom: false, nextResolution: canonical }
|
||||
}
|
||||
}
|
||||
return { exitCustom: false }
|
||||
}
|
||||
|
||||
export function switchSettingsGraphics(graphics: string): { patch: Partial<SetOpts>; forceCustomRes?: boolean } {
|
||||
if (!supportsAutoResolution(graphics)) {
|
||||
return { patch: { graphics }, forceCustomRes: false }
|
||||
}
|
||||
return { patch: { graphics } }
|
||||
}
|
||||
|
||||
export function expandTouchedSettingsFields(fields: Iterable<string>): string[] {
|
||||
const out = new Set<string>()
|
||||
for (const field of fields) {
|
||||
out.add(field)
|
||||
if (field === 'resolution' || field === 'auto_resolution') {
|
||||
out.add('resolution')
|
||||
out.add('auto_resolution')
|
||||
}
|
||||
}
|
||||
return Array.from(out)
|
||||
}
|
||||
|
||||
export function syncUntouchedSettingsForm<T extends object>(
|
||||
form: T,
|
||||
base: T,
|
||||
touchedFields: ReadonlySet<string>,
|
||||
): T {
|
||||
let changed = false
|
||||
const next = { ...form } as Record<string, unknown>
|
||||
const baseRec = base as Record<string, unknown>
|
||||
for (const key of Object.keys(baseRec)) {
|
||||
if (touchedFields.has(key)) continue
|
||||
if (next[key] !== baseRec[key]) {
|
||||
next[key] = baseRec[key]
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? (next as T) : form
|
||||
}
|
||||
|
||||
export function reconcileSettingsFormOnBaseChange<T extends object>(params: {
|
||||
previousVMKey: string
|
||||
nextVMKey: string
|
||||
form: T
|
||||
base: T
|
||||
touchedFields: ReadonlySet<string>
|
||||
}): { form: T; resetDraft: boolean } {
|
||||
const { previousVMKey, nextVMKey, form, base, touchedFields } = params
|
||||
if (previousVMKey !== nextVMKey) {
|
||||
return { form: base, resetDraft: true }
|
||||
}
|
||||
return { form: syncUntouchedSettingsForm(form, base, touchedFields), resetDraft: false }
|
||||
}
|
||||
|
||||
export function toggleSettingsBorderless(params: {
|
||||
borderless: boolean
|
||||
form: Pick<SetOpts, 'resolution' | 'auto_resolution'>
|
||||
displayProfile: HostReport
|
||||
targetDisplay?: DisplayInfo
|
||||
presets: FullscreenDisplayPreset[]
|
||||
fsPresets: FullscreenDisplayPreset[]
|
||||
customRes: boolean
|
||||
}): Partial<SetOpts> {
|
||||
const { borderless, form, displayProfile, targetDisplay, presets, fsPresets, customRes } = params
|
||||
if (form.auto_resolution) {
|
||||
return { borderless }
|
||||
}
|
||||
const targetPresets = borderless ? fsPresets : presets
|
||||
if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) {
|
||||
const nextRes = borderless
|
||||
? (targetDisplay && targetDisplay.width > 0 && targetDisplay.height > 0
|
||||
? `${targetDisplay.width}x${targetDisplay.height}`
|
||||
: targetPresets[0]?.resolution ?? form.resolution)
|
||||
: recommendedResolution(displayProfile)
|
||||
return { borderless, resolution: nextRes }
|
||||
}
|
||||
return { borderless }
|
||||
}
|
||||
|
||||
export function countChangedSettingsFields(changedFields: readonly string[]): number {
|
||||
const hasBothRes = changedFields.includes('resolution') && changedFields.includes('auto_resolution')
|
||||
return changedFields.length - (hasBothRes ? 1 : 0)
|
||||
}
|
||||
|
||||
export function buildSettingsSaveDiff(
|
||||
name: string,
|
||||
changedFields: readonly string[],
|
||||
form: SetOpts,
|
||||
base?: Pick<SetOpts, 'auto_resolution'>,
|
||||
): SetOpts {
|
||||
const diff: SetOpts = { name }
|
||||
const vgpu = supportsAutoResolution(form.graphics)
|
||||
const effectiveAuto = vgpu && !!form.auto_resolution
|
||||
for (const field of changedFields) {
|
||||
if (field === 'resolution') {
|
||||
if (!vgpu || effectiveAuto) continue
|
||||
diff.resolution = canonicalResolution(form.resolution)
|
||||
continue
|
||||
}
|
||||
if (field === 'auto_resolution') {
|
||||
diff.auto_resolution = effectiveAuto
|
||||
continue
|
||||
}
|
||||
;(diff as unknown as Record<string, unknown>)[field] = (form as unknown as Record<string, unknown>)[field]
|
||||
}
|
||||
if (!vgpu && changedFields.includes('graphics') && base?.auto_resolution) {
|
||||
diff.auto_resolution = false
|
||||
}
|
||||
if (vgpu && !effectiveAuto && diff.auto_resolution === false && !diff.resolution) {
|
||||
const resolved = canonicalResolution(form.resolution)
|
||||
if (resolved) diff.resolution = resolved
|
||||
}
|
||||
return diff
|
||||
}
|
||||
|
||||
export function initialWizardManualResolution(
|
||||
draft?: { opts: Pick<CreateOpts, 'graphics' | 'auto_resolution'>; manualResolution?: boolean } | null,
|
||||
): boolean {
|
||||
if (!draft) return false
|
||||
if (typeof draft.manualResolution === 'boolean') return draft.manualResolution
|
||||
return supportsAutoResolution(draft.opts.graphics) && draft.opts.auto_resolution === false
|
||||
}
|
||||
|
||||
export function initialWizardResolution(
|
||||
host: HostReport,
|
||||
fixedModeSupported: boolean,
|
||||
graphics: string = 'reims-vgpu',
|
||||
): Pick<CreateOpts, 'auto_resolution' | 'resolution'> {
|
||||
return {
|
||||
auto_resolution: supportsAutoResolution(graphics),
|
||||
resolution: resolveAutoDisplayPreset(host, false, fixedModeSupported).resolution,
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveEffectiveWizardOpts(
|
||||
opts: CreateOpts,
|
||||
autoPreset: FullscreenDisplayPreset,
|
||||
): CreateOpts {
|
||||
if (!supportsAutoResolution(opts.graphics)) {
|
||||
return opts.auto_resolution ? { ...opts, auto_resolution: false } : opts
|
||||
}
|
||||
if (opts.auto_resolution) {
|
||||
return { ...opts, resolution: autoPreset.resolution }
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
export function switchWizardGraphics(params: {
|
||||
graphics: CreateOpts['graphics']
|
||||
manualResolutionPicked: boolean
|
||||
autoPreset: FullscreenDisplayPreset
|
||||
}): Partial<CreateOpts> {
|
||||
const { graphics, manualResolutionPicked, autoPreset } = params
|
||||
if (!supportsAutoResolution(graphics)) {
|
||||
return { graphics, auto_resolution: false }
|
||||
}
|
||||
if (!manualResolutionPicked) {
|
||||
return { graphics, auto_resolution: true, resolution: autoPreset.resolution }
|
||||
}
|
||||
return { graphics }
|
||||
}
|
||||
|
||||
export function selectWizardResolution(
|
||||
value: string,
|
||||
autoPreset: FullscreenDisplayPreset,
|
||||
): Pick<CreateOpts, 'auto_resolution' | 'resolution'> {
|
||||
if (value === AUTO_RESOLUTION_OPTION) {
|
||||
return { auto_resolution: true, resolution: autoPreset.resolution }
|
||||
}
|
||||
return { auto_resolution: false, resolution: value }
|
||||
}
|
||||
|
||||
export function toggleWizardBorderless(params: {
|
||||
borderless: boolean
|
||||
opts: Pick<CreateOpts, 'graphics' | 'auto_resolution' | 'resolution'>
|
||||
host: HostReport
|
||||
fixedModeSupported: boolean
|
||||
windowPresets: FullscreenDisplayPreset[]
|
||||
fullscreenPresets: FullscreenDisplayPreset[]
|
||||
}): Partial<CreateOpts> {
|
||||
const { borderless, opts, host, fixedModeSupported, windowPresets, fullscreenPresets } = params
|
||||
if (supportsAutoResolution(opts.graphics) && opts.auto_resolution) {
|
||||
return {
|
||||
borderless,
|
||||
auto_resolution: true,
|
||||
resolution: resolveAutoDisplayPreset(host, borderless, fixedModeSupported).resolution,
|
||||
}
|
||||
}
|
||||
const list = borderless ? fullscreenPresets : windowPresets
|
||||
const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless))
|
||||
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
|
||||
return keep ? { borderless } : { borderless, resolution: fallback }
|
||||
}
|
||||
@@ -155,10 +155,18 @@ export function gpuLabel(locale: Locale, icd: string | undefined, host: HostRepo
|
||||
return found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
|
||||
}
|
||||
|
||||
export function formatResolutionLabel(res: string, auto: boolean, tr: Tr): string {
|
||||
const displayRes = (res ?? '').trim().replace(/\s*[x×]\s*/i, ' × ')
|
||||
if (!auto) return displayRes
|
||||
return displayRes ? tr('resAutoValue', { res: displayRes }) : tr('resAuto')
|
||||
}
|
||||
|
||||
export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): string {
|
||||
if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics')
|
||||
const gpu = gpuLabel(locale, d.gpu, host)
|
||||
const res = resolutionLabel(d.resolution)
|
||||
const tr: Tr = (k, v) => t(locale, k, v)
|
||||
const isAuto = d.graphics !== 'vmware-svga' && !!d.auto_resolution
|
||||
const res = isAuto ? formatResolutionLabel(d.resolution, true, tr) : resolutionLabel(d.resolution)
|
||||
const screens = d.displays > 1 ? `${d.displays} × ${res}` : res
|
||||
return res ? `${gpu} · ${screens}` : gpu
|
||||
}
|
||||
@@ -427,6 +435,38 @@ export function fullscreenDisplayPresets(host: HostReport): FullscreenDisplayPre
|
||||
return out
|
||||
}
|
||||
|
||||
export function resolveAutoDisplayPreset(
|
||||
host: HostReport,
|
||||
borderless: boolean,
|
||||
fixedModeSupported: boolean,
|
||||
): FullscreenDisplayPreset {
|
||||
if (!borderless) {
|
||||
const presets = recommendedDisplayPresets(host)
|
||||
return presets.find((p) => p.recommended) ?? presets[0]
|
||||
}
|
||||
const d = host.primary_display
|
||||
if (!d || d.width <= 0 || d.height <= 0) {
|
||||
return {
|
||||
resolution: '1920x1080',
|
||||
label: '1920 × 1080',
|
||||
hidpi: false,
|
||||
native: true,
|
||||
recommended: true,
|
||||
}
|
||||
}
|
||||
const fsPresets = fullscreenDisplayPresets(host)
|
||||
if (fixedModeSupported) {
|
||||
return fsPresets.find((p) => p.recommended) ?? fsPresets[0]
|
||||
}
|
||||
return {
|
||||
resolution: `${d.width}x${d.height}`,
|
||||
label: `${d.width} × ${d.height}`,
|
||||
hidpi: !!host.fullscreen_hidpi,
|
||||
native: true,
|
||||
recommended: true,
|
||||
}
|
||||
}
|
||||
|
||||
export function recommendedResolution(host: HostReport): string {
|
||||
if (host.recommended_resolution) return host.recommended_resolution
|
||||
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
|
||||
@@ -492,6 +532,7 @@ export function pendingChangeText(locale: Locale, p: { field: string; from: stri
|
||||
cpus: { label: 'factCPU', fmt: (v) => tr('cores', { n: v }) },
|
||||
memory: { label: 'factMemory', fmt: (v) => formatMemory(v, locale) },
|
||||
resolution: { label: 'resolution', fmt: resolutionLabel },
|
||||
auto_resolution: { label: 'autoResolution', fmt: bool },
|
||||
gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) },
|
||||
displays: { label: 'displays', fmt: (v) => v },
|
||||
borderless: { label: 'borderless', fmt: bool },
|
||||
|
||||
@@ -1244,6 +1244,8 @@ export namespace host {
|
||||
scale_pct: number;
|
||||
refresh_hz?: number;
|
||||
primary: boolean;
|
||||
left?: number;
|
||||
top?: number;
|
||||
work_width?: number;
|
||||
work_height?: number;
|
||||
|
||||
@@ -1260,6 +1262,8 @@ export namespace host {
|
||||
this.scale_pct = source["scale_pct"];
|
||||
this.refresh_hz = source["refresh_hz"];
|
||||
this.primary = source["primary"];
|
||||
this.left = source["left"];
|
||||
this.top = source["top"];
|
||||
this.work_width = source["work_width"];
|
||||
this.work_height = source["work_height"];
|
||||
}
|
||||
@@ -3023,6 +3027,7 @@ export namespace reims {
|
||||
graphics?: string;
|
||||
gpu?: string;
|
||||
resolution?: string;
|
||||
auto_resolution?: boolean;
|
||||
displays?: number;
|
||||
borderless?: boolean;
|
||||
capture?: boolean;
|
||||
@@ -3057,6 +3062,7 @@ export namespace reims {
|
||||
this.graphics = source["graphics"];
|
||||
this.gpu = source["gpu"];
|
||||
this.resolution = source["resolution"];
|
||||
this.auto_resolution = source["auto_resolution"];
|
||||
this.displays = source["displays"];
|
||||
this.borderless = source["borderless"];
|
||||
this.capture = source["capture"];
|
||||
@@ -3079,6 +3085,7 @@ export namespace reims {
|
||||
disk_controller?: string;
|
||||
disk_cache?: string;
|
||||
resolution?: string;
|
||||
auto_resolution?: boolean;
|
||||
borderless?: boolean;
|
||||
capture?: boolean;
|
||||
gpu?: string;
|
||||
@@ -3108,6 +3115,7 @@ export namespace reims {
|
||||
this.disk_controller = source["disk_controller"];
|
||||
this.disk_cache = source["disk_cache"];
|
||||
this.resolution = source["resolution"];
|
||||
this.auto_resolution = source["auto_resolution"];
|
||||
this.borderless = source["borderless"];
|
||||
this.capture = source["capture"];
|
||||
this.gpu = source["gpu"];
|
||||
@@ -3186,6 +3194,7 @@ export namespace reims {
|
||||
display: string;
|
||||
displays: number;
|
||||
resolution: string;
|
||||
auto_resolution: boolean;
|
||||
gpu: string;
|
||||
has_opencore: boolean;
|
||||
has_installer: boolean;
|
||||
@@ -3240,6 +3249,7 @@ export namespace reims {
|
||||
this.display = source["display"];
|
||||
this.displays = source["displays"];
|
||||
this.resolution = source["resolution"];
|
||||
this.auto_resolution = source["auto_resolution"];
|
||||
this.gpu = source["gpu"];
|
||||
this.has_opencore = source["has_opencore"];
|
||||
this.has_installer = source["has_installer"];
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
@@ -17,9 +18,10 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
"github.com/Nwflower/reims-go/internal/packetbridge"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
func (a *App) createVMFlow(opts reims.CreateOpts, connectedDisplays func() []host.DisplayInfo) (err error) {
|
||||
defer func() {
|
||||
var coded *i18n.CodedError
|
||||
if errors.As(err, &coded) && strings.HasPrefix(coded.Code, "E_NETWORK_") {
|
||||
@@ -54,6 +56,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
}
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
autoResolution := opts.AutoResolution != nil && *opts.AutoResolution && vmstart.SupportsAutoResolution(opts.Graphics)
|
||||
|
||||
// Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
|
||||
// QMP wiring, and Win11 WHPX nested-virt fallback apply uniformly.
|
||||
@@ -171,6 +174,9 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
opts.DiskMode = "copy"
|
||||
}
|
||||
|
||||
if autoResolution {
|
||||
opts.Resolution, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(connectedDisplays()), opts.Borderless != nil && *opts.Borderless, c.DisplayFixedMode)
|
||||
}
|
||||
err = c.Create(ctx, opts, w, w)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
@@ -195,6 +201,12 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
finishTask(err)
|
||||
return fmt.Errorf("record VM driver ownership: %w", err)
|
||||
}
|
||||
if autoResolution {
|
||||
if _, err := vmstart.SaveVMAutoResolution(createdDir, true); err != nil {
|
||||
finishTask(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, c.AllowsSetCapture()); ok {
|
||||
var parts []string
|
||||
if postSet.DiskController != "" {
|
||||
|
||||
@@ -94,21 +94,16 @@ func (a *App) SetVMDisplay(driverID, name, targetDisplay string) (VMDisplayStatu
|
||||
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 {
|
||||
status, err := saveVMTargetDisplay(vm, targetDisplay, a.displayHost.displays())
|
||||
if err != nil {
|
||||
return VMDisplayStatus{}, err
|
||||
}
|
||||
defer a.emitStateChanged()
|
||||
if !status.Running || len(displays) == 0 {
|
||||
if !status.Running || len(status.Displays) == 0 {
|
||||
return status, nil
|
||||
}
|
||||
if status.FallbackToPrimary {
|
||||
a.emitVMLogForDriver(vm.DriverID, vm.Name, displayFallbackLog(cfg.TargetDisplay))
|
||||
a.emitVMLogForDriver(vm.DriverID, vm.Name, displayFallbackLog(status.TargetDisplay))
|
||||
}
|
||||
if driver.IsHosted(vm.Capabilities) {
|
||||
// The driver owns a hosted VM's display; only the choice is saved.
|
||||
@@ -158,6 +153,27 @@ func (a *App) SetVMDisplay(driverID, name, targetDisplay string) (VMDisplayStatu
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func saveVMTargetDisplay(vm driver.VMInfo, targetDisplay string, displays []host.DisplayInfo) (VMDisplayStatus, error) {
|
||||
if vm.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
release, err := lockMacOSDisplaySettings(vm.Directory)
|
||||
if err != nil {
|
||||
return VMDisplayStatus{}, err
|
||||
}
|
||||
defer release()
|
||||
}
|
||||
cfg := vmstart.ReadVMDisplay(vm.Directory)
|
||||
previousTarget := cfg.TargetDisplay
|
||||
cfg.TargetDisplay = vmstart.NormalizeTargetDisplay(targetDisplay)
|
||||
status := buildVMDisplayStatus(vm, cfg, displays)
|
||||
if status.FallbackToPrimary && !strings.EqualFold(cfg.TargetDisplay, previousTarget) {
|
||||
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
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func displayFallbackLog(target string) string {
|
||||
return fmt.Sprintf("Display %q is disconnected. Using the primary display.", target)
|
||||
}
|
||||
|
||||
@@ -131,6 +131,26 @@ func TestGetAndSetVMDisplay(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetVMDisplayPreservesAutoResolution(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.displayHost.displays = func() []host.DisplayInfo {
|
||||
return []host.DisplayInfo{{Name: "DISPLAY1", Primary: true}, {Name: "DISPLAY2"}}
|
||||
}
|
||||
if _, err := vmstart.SaveVMAutoResolution(vm.Directory, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, target := range []string{"DISPLAY2", ""} {
|
||||
if _, err := a.SetVMDisplay(driverID, vm.Name, target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := vmstart.ReadVMDisplay(vm.Directory); got != (vmstart.VMDisplayConfig{TargetDisplay: target, AutoResolution: true}) {
|
||||
t.Fatalf("selection %q saved %+v", target, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetVMDisplayReadOnly(t *testing.T) {
|
||||
const driverID = driver.BuiltinReimsMacOSDriverID
|
||||
vm := driver.VMInfo{Name: "test-vm", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}
|
||||
|
||||
@@ -44,6 +44,7 @@ func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, erro
|
||||
a.populateGuestLangDetail(&d)
|
||||
populateSuspendDetail(&d)
|
||||
populateNestedVirtDetail(&d)
|
||||
d.AutoResolution = vmstart.SupportsAutoResolution(d.Graphics) && vmstart.ReadVMDisplay(d.Directory).AutoResolution
|
||||
return d, nil
|
||||
}
|
||||
|
||||
@@ -78,6 +79,7 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
|
||||
a.populateGuestLangDetail(&d)
|
||||
populateSuspendDetail(&d)
|
||||
populateNestedVirtDetail(&d)
|
||||
d.AutoResolution = vmstart.SupportsAutoResolution(d.Graphics) && vmstart.ReadVMDisplay(d.Directory).AutoResolution
|
||||
return d, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -193,6 +193,10 @@ func stripLegacyManagedExtraArgs(extraArgs string) string {
|
||||
}
|
||||
|
||||
func (a *App) startMacOSVM(name string) error {
|
||||
return a.startMacOSVMWithHost(name, host.Inspect)
|
||||
}
|
||||
|
||||
func (a *App) startMacOSVMWithHost(name string, inspect func(string) host.Report) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -206,7 +210,7 @@ func (a *App) startMacOSVM(name string) error {
|
||||
tmpDir := a.cfg.TempDir()
|
||||
locale := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
rep := inspect(root)
|
||||
if err := prep.CheckWHPX(rep); err != nil {
|
||||
a.emitVMLog(name, "Start refused: "+err.Error())
|
||||
return err
|
||||
@@ -347,9 +351,9 @@ func (a *App) startMacOSVM(name string) error {
|
||||
}
|
||||
}
|
||||
|
||||
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
|
||||
vmstart.UsesFixedGuestMode(curDetail.Directory, rep.Displays, curDetail.Borderless, curDetail.Resolution) {
|
||||
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
if err := macosdriver.PrepareColdStartDisplay(context.Background(), c, &curDetail, rep.Displays, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("client-window-close") {
|
||||
c.Env = append(c.Env, vmstart.CloseRequestEnv(name)...)
|
||||
@@ -363,7 +367,6 @@ func (a *App) startMacOSVM(name string) error {
|
||||
|
||||
startAt := time.Now()
|
||||
a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, "Starting "+name+"...")
|
||||
err = c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
|
||||
a.emitVMLog(name, msg)
|
||||
|
||||
@@ -7,12 +7,15 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/networkmsg"
|
||||
@@ -79,7 +82,7 @@ func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.createVMFlow(opts)
|
||||
return a.createVMFlow(opts, host.ConnectedDisplays)
|
||||
}
|
||||
|
||||
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
|
||||
@@ -132,16 +135,17 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
|
||||
if issues := reims.ValidateSet(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
|
||||
return fmt.Errorf("%s", issues[0].Message)
|
||||
}
|
||||
var outcome macosdriver.SettingsOutcome
|
||||
ctx := macosdriver.WithSettingsOutcome(context.Background(), &outcome)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) })
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
guestLangChanged := strings.TrimSpace(opts.GuestLang) != "" && strings.TrimSpace(opts.GuestLang) != cur.GuestLang
|
||||
if svc != nil {
|
||||
raw, _ := json.Marshal(opts)
|
||||
var changes map[string]any
|
||||
_ = json.Unmarshal(raw, &changes)
|
||||
if err := svc.Set(context.Background(), driver.NewVMRef("", opts.Name), changes, w, w); err != nil {
|
||||
if err := svc.Set(ctx, driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, opts.Name), changes, w, w); err != nil {
|
||||
a.emitVMLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
@@ -165,93 +169,98 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if reims.HasCtlSetChanges(opts) {
|
||||
if err := c.Set(context.Background(), opts, w, w); err != nil {
|
||||
a.emitVMLog(opts.Name, "Set error: "+err.Error())
|
||||
if err := macosdriver.ApplyVMOptions(ctx, c, locked, opts, w, w, func(cur reims.VMDetail) error {
|
||||
live := cur.State == "running" || cur.State == "paused"
|
||||
if lang := strings.TrimSpace(opts.GuestLang); lang != "" && lang != cur.GuestLang {
|
||||
prep, err := a.prep(opts.Name)
|
||||
if err == nil {
|
||||
err = prep.ApplyGuestLang(ctx, cur.Directory, opts.GuestLang, live)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
if opts.NestedVirt != nil {
|
||||
if err := vmstart.SaveVMNestedVirt(locked.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if guestLangChanged {
|
||||
prep, err := a.prep(opts.Name)
|
||||
if err == nil {
|
||||
err = prep.ApplyGuestLang(context.Background(), cur.Directory, opts.GuestLang, cur.State == "running")
|
||||
}
|
||||
if err != nil {
|
||||
a.emitVMLog(opts.Name, "Guest language error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
} else if cur.State != "running" && opts.Graphics != "" && opts.Graphics != cur.Graphics {
|
||||
if prep, err := a.prep(opts.Name); err == nil {
|
||||
prep.ReplayGuestLang(context.Background(), cur.Directory)
|
||||
if !live && opts.Graphics != "" && opts.Graphics != cur.Graphics {
|
||||
if prep, err := a.prep(opts.Name); err == nil {
|
||||
prep.ReplayGuestLang(ctx, cur.Directory)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
a.emitVMLog(opts.Name, "Set error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
if cur.State == "running" {
|
||||
var diffs []PendingChange
|
||||
if opts.CPUs > 0 && opts.CPUs != cur.CPUs {
|
||||
diffs = append(diffs, PendingChange{Field: "cpus", From: fmt.Sprintf("%d", cur.CPUs), To: fmt.Sprintf("%d", opts.CPUs)})
|
||||
}
|
||||
if opts.Memory != "" && !strings.EqualFold(opts.Memory, cur.Memory) {
|
||||
diffs = append(diffs, PendingChange{Field: "memory", From: cur.Memory, To: opts.Memory})
|
||||
}
|
||||
if opts.Resolution != "" && opts.Resolution != cur.Resolution {
|
||||
diffs = append(diffs, PendingChange{Field: "resolution", From: cur.Resolution, To: opts.Resolution})
|
||||
}
|
||||
if opts.GPU != "" && opts.GPU != cur.GPU {
|
||||
diffs = append(diffs, PendingChange{Field: "gpu", From: cur.GPU, To: opts.GPU})
|
||||
}
|
||||
if opts.Displays > 0 && opts.Displays != cur.Displays {
|
||||
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
|
||||
}
|
||||
if dc := strings.ToLower(strings.TrimSpace(opts.DiskController)); dc != "" && !strings.EqualFold(dc, cur.DiskController) {
|
||||
diffs = append(diffs, PendingChange{Field: "disk_controller", From: cur.DiskController, To: dc})
|
||||
}
|
||||
if dcache := strings.ToLower(strings.TrimSpace(opts.DiskCache)); dcache != "" && !strings.EqualFold(dcache, cur.DiskCache) {
|
||||
from := cur.DiskCache
|
||||
if from == "" {
|
||||
from = "default"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "disk_cache", From: from, To: dcache})
|
||||
}
|
||||
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
|
||||
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
|
||||
}
|
||||
if opts.NestedVirt != nil && *opts.NestedVirt != cur.NestedVirt {
|
||||
diffs = append(diffs, PendingChange{Field: "nested_virt", From: fmt.Sprintf("%v", cur.NestedVirt), To: fmt.Sprintf("%v", *opts.NestedVirt)})
|
||||
}
|
||||
if opts.Audio != nil && *opts.Audio != cur.Audio {
|
||||
diffs = append(diffs, PendingChange{Field: "audio", From: fmt.Sprintf("%v", cur.Audio), To: fmt.Sprintf("%v", *opts.Audio)})
|
||||
}
|
||||
if opts.AudioBackend != "" && opts.AudioBackend != cur.AudioBackend {
|
||||
from := cur.AudioBackend
|
||||
if from == "" {
|
||||
from = "auto"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "audio_backend", From: from, To: opts.AudioBackend})
|
||||
}
|
||||
if guestLangChanged {
|
||||
from := cur.GuestLang
|
||||
if from == "" {
|
||||
from = "en-US:0"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "guest_lang", From: from, To: strings.TrimSpace(opts.GuestLang)})
|
||||
}
|
||||
if len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
a.pendingChanges[vmKey(opts.Name)] = append(a.pendingChanges[vmKey(opts.Name)], diffs...)
|
||||
a.mu.Unlock()
|
||||
if diffs := pendingVMSettingsChanges(outcome, opts); len(diffs) > 0 {
|
||||
a.mu.Lock()
|
||||
key := vmKey(opts.Name)
|
||||
a.pendingChanges[key] = mergePendingChanges(a.pendingChanges[key], diffs)
|
||||
if len(a.pendingChanges[key]) == 0 {
|
||||
delete(a.pendingChanges, key)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name)
|
||||
a.emitStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func pendingVMSettingsChanges(outcome macosdriver.SettingsOutcome, opts reims.SetOpts) []PendingChange {
|
||||
if !outcome.Valid || !outcome.Running {
|
||||
return nil
|
||||
}
|
||||
before, after := outcome.Before, outcome.After
|
||||
candidates := []struct {
|
||||
touched bool
|
||||
change PendingChange
|
||||
}{
|
||||
{opts.CPUs > 0, PendingChange{Field: "cpus", From: strconv.Itoa(before.CPUs), To: strconv.Itoa(after.CPUs)}},
|
||||
{opts.Memory != "", PendingChange{Field: "memory", From: before.Memory, To: after.Memory}},
|
||||
{opts.AutoResolution != nil, PendingChange{Field: "auto_resolution", From: strconv.FormatBool(before.AutoResolution), To: strconv.FormatBool(after.AutoResolution)}},
|
||||
{opts.Resolution != "", PendingChange{Field: "resolution", From: before.Resolution, To: after.Resolution}},
|
||||
{opts.GPU != "", PendingChange{Field: "gpu", From: before.GPU, To: after.GPU}},
|
||||
{opts.Displays > 0, PendingChange{Field: "displays", From: strconv.Itoa(before.Displays), To: strconv.Itoa(after.Displays)}},
|
||||
{strings.TrimSpace(opts.DiskController) != "", PendingChange{Field: "disk_controller", From: before.DiskController, To: after.DiskController}},
|
||||
{strings.TrimSpace(opts.DiskCache) != "", PendingChange{Field: "disk_cache", From: before.DiskCache, To: after.DiskCache}},
|
||||
{opts.Borderless != nil, PendingChange{Field: "borderless", From: strconv.FormatBool(before.Borderless), To: strconv.FormatBool(after.Borderless)}},
|
||||
{opts.NestedVirt != nil, PendingChange{Field: "nested_virt", From: strconv.FormatBool(before.NestedVirt), To: strconv.FormatBool(after.NestedVirt)}},
|
||||
{opts.Audio != nil, PendingChange{Field: "audio", From: strconv.FormatBool(before.Audio), To: strconv.FormatBool(after.Audio)}},
|
||||
{opts.AudioBackend != "", PendingChange{Field: "audio_backend", From: before.AudioBackend, To: after.AudioBackend}},
|
||||
{strings.TrimSpace(opts.GuestLang) != "", PendingChange{Field: "guest_lang", From: before.GuestLang, To: after.GuestLang}},
|
||||
}
|
||||
out := make([]PendingChange, 0, len(candidates))
|
||||
for _, item := range candidates {
|
||||
if item.touched || !noPendingChange(item.change) {
|
||||
out = append(out, item.change)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func mergePendingChanges(existing, incoming []PendingChange) []PendingChange {
|
||||
merged := make([]PendingChange, 0, len(existing)+len(incoming))
|
||||
for _, changes := range [2][]PendingChange{existing, incoming} {
|
||||
for _, change := range changes {
|
||||
index := slices.IndexFunc(merged, func(pending PendingChange) bool { return pending.Field == change.Field })
|
||||
if index < 0 {
|
||||
merged = append(merged, change)
|
||||
} else {
|
||||
merged[index].To = change.To
|
||||
}
|
||||
}
|
||||
}
|
||||
return slices.DeleteFunc(merged, noPendingChange)
|
||||
}
|
||||
|
||||
func noPendingChange(change PendingChange) bool {
|
||||
if change.Field == "memory" || change.Field == "resolution" || change.Field == "disk_controller" || change.Field == "disk_cache" {
|
||||
return strings.EqualFold(change.From, change.To)
|
||||
}
|
||||
return change.From == change.To
|
||||
}
|
||||
|
||||
func lockMacOSDisplaySettings(vmDir string) (func(), error) {
|
||||
return reims.LockVMOperation(vmDir)
|
||||
}
|
||||
|
||||
type VMNetworkSettings struct {
|
||||
Adapters []NetworkAdapter `json:"adapters"`
|
||||
UplinkGUID string `json:"uplink_guid"`
|
||||
|
||||
@@ -0,0 +1,703 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
const (
|
||||
displayFixtureVM = "test-vm"
|
||||
displayFixtureClone = "test-clone"
|
||||
)
|
||||
|
||||
type displayCtlFixture struct {
|
||||
Dir, State, Resolution string
|
||||
Memory string
|
||||
BeforeLockResolution string
|
||||
Shows int
|
||||
Graphics string
|
||||
CloneDir string
|
||||
Borderless bool
|
||||
FailSet bool
|
||||
NestedVirtBeforeSet bool
|
||||
FailShowAfterSet bool
|
||||
ReplaceDisplayAfterSet bool
|
||||
Commands []string
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
if path := os.Getenv("REIMS_TEST_DISPLAY_CTL"); path != "" {
|
||||
switch filepath.Base(os.Args[0]) {
|
||||
case "reims-ctl", "reims-ctl.exe":
|
||||
if err := runDisplayCtl(path, os.Args[1:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
case "qemu-img", "qemu-img.exe":
|
||||
if os.Args[1] == "info" {
|
||||
fmt.Println(`{"format":"qcow2"}`)
|
||||
return
|
||||
}
|
||||
if os.Args[1] == "create" {
|
||||
if err := os.WriteFile(os.Args[len(os.Args)-1], []byte("overlay"), 0o600); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if os.Args[1] == "convert" {
|
||||
if err := os.WriteFile(os.Args[len(os.Args)-1], []byte("converted disk"), 0o600); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "unexpected qemu-img call", os.Args[1:])
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func runDisplayCtl(path string, args []string) error {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var vm displayCtlFixture
|
||||
if err := json.Unmarshal(raw, &vm); err != nil {
|
||||
return err
|
||||
}
|
||||
switch args[0] {
|
||||
case "show":
|
||||
if args[1] == displayFixtureClone && vm.CloneDir != "" {
|
||||
fmt.Printf("state stopped\ndirectory %s\ndisplay one opening at %s\n", vm.CloneDir, vm.Resolution)
|
||||
return nil
|
||||
}
|
||||
if vm.State == "" || args[1] != displayFixtureVM || vm.FailShowAfterSet && len(vm.Commands) > 0 {
|
||||
return fmt.Errorf("VM %q not found", args[1])
|
||||
}
|
||||
if vm.BeforeLockResolution != "" {
|
||||
vm.Shows++
|
||||
if vm.Shows == 2 {
|
||||
unlock, err := reims.LockVMOperation(vm.Dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unlock()
|
||||
vm.Resolution = vm.BeforeLockResolution
|
||||
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := vmstart.SaveVMAutoResolution(vm.Dir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, raw, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Printf("state %s\ndirectory %s\ndisk system.qcow2\ngraphics %s\nmemory %s\n", vm.State, vm.Dir, vm.Graphics, vm.Memory)
|
||||
if vm.Borderless {
|
||||
fmt.Printf("display one borderless at %s\n", vm.Resolution)
|
||||
} else {
|
||||
fmt.Printf("display one opening at %s\n", vm.Resolution)
|
||||
}
|
||||
return nil
|
||||
case "list":
|
||||
if vm.State == "" {
|
||||
fmt.Println("[]")
|
||||
return nil
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode([]reims.VMListItem{{Name: displayFixtureVM, State: vm.State, Dir: vm.Dir}})
|
||||
case "create":
|
||||
if args[1] == displayFixtureClone {
|
||||
vm.CloneDir = filepath.Join(filepath.Dir(vm.Dir), displayFixtureClone)
|
||||
if err := os.MkdirAll(vm.CloneDir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
vm.State = "stopped"
|
||||
if err := os.MkdirAll(vm.Dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "set", "start":
|
||||
if args[0] == "set" && len(args) > 1 && args[1] == "--help" {
|
||||
return nil
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unexpected command %v", args)
|
||||
}
|
||||
failSet := args[0] == "set" && vm.FailSet
|
||||
if failSet {
|
||||
nested, err := vmstart.ReadVMNestedVirt(vm.Dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vm.NestedVirtBeforeSet = nested.Enabled
|
||||
}
|
||||
for i := 2; !failSet && i+1 < len(args); i++ {
|
||||
switch args[i] {
|
||||
case "--resolution":
|
||||
vm.Resolution = args[i+1]
|
||||
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
|
||||
return err
|
||||
}
|
||||
case "--borderless":
|
||||
vm.Borderless = args[i+1] == "true"
|
||||
case "--graphics":
|
||||
vm.Graphics = args[i+1]
|
||||
case "--memory":
|
||||
vm.Memory = args[i+1]
|
||||
}
|
||||
}
|
||||
if args[0] == "set" && vm.ReplaceDisplayAfterSet {
|
||||
vm.Resolution = "1024x768"
|
||||
if _, err := vmstart.SaveVMAutoResolution(vm.Dir, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
command := strings.Join(args, " ")
|
||||
if args[0] == "start" {
|
||||
command += " fixed=" + os.Getenv("REIMS_VGPU_WINDOW_FIXED_MODE")
|
||||
}
|
||||
vm.Commands = append(vm.Commands, command)
|
||||
raw, err = json.Marshal(vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, raw, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if args[0] == "start" {
|
||||
return fmt.Errorf("stop before launching QEMU")
|
||||
}
|
||||
if failSet {
|
||||
return fmt.Errorf("fixture refused set")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeDisplayCtlResolution(dir, resolution string) error {
|
||||
config := fmt.Sprintf("disk = 'system.qcow2'\n[display]\nresolution = %q\n", resolution)
|
||||
return os.WriteFile(filepath.Join(dir, "vm.toml"), []byte(config), 0o600)
|
||||
}
|
||||
|
||||
func newDisplayCtlApp(t *testing.T, vm displayCtlFixture, useDriver bool) (*App, func() displayCtlFixture) {
|
||||
t.Helper()
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "test-rt"}
|
||||
if err := cfg.EnsureDirs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
active := rt.Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)}
|
||||
control := active.ControlPath()
|
||||
if err := os.MkdirAll(filepath.Dir(control), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(active.Dir, "manifest.json"), []byte(`{"schema_version":2,"commit":"test-rt","kind":"reims-vgpu","runtime_api":"1.0.0","capabilities":["display-fixed-mode","vm-suspend"]}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exe, err := os.ReadFile(self)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(control, exe, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(active.QemuImgPath()), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Link(control, active.QemuImgPath()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixturePath := filepath.Join(cfg.DataRoot, "display-fixture.json")
|
||||
t.Setenv("REIMS_TEST_DISPLAY_CTL", fixturePath)
|
||||
t.Setenv("REIMS_VGPU_WINDOW_FIXED_MODE", "")
|
||||
t.Setenv("GORACE", "atexit_sleep_ms=0")
|
||||
registryDir := filepath.Join(cfg.XDGConfigDir(), "reims-ctl")
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", registryDir)
|
||||
if err := os.MkdirAll(registryDir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm.Dir = filepath.Join(cfg.DataRoot, displayFixtureVM)
|
||||
if vm.State != "" {
|
||||
if err := os.MkdirAll(vm.Dir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writeDisplayCtlResolution(vm.Dir, vm.Resolution); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(vm.Dir, "system.qcow2"), []byte("source disk fixture"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := fmt.Sprintf("[[vm]]\nname = %q\ndir = '%s'\n", displayFixtureVM, vm.Dir)
|
||||
if err := os.WriteFile(filepath.Join(registryDir, "vms.toml"), []byte(registry), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(vm)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(fixturePath, raw, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := &App{}
|
||||
if useDriver {
|
||||
a = newDisplayTestApp(t, macosdriver.NewReimsMacOSDriver(func() config.Config { return cfg }))
|
||||
}
|
||||
a.cfg = &cfg
|
||||
a.transitions = map[string]string{}
|
||||
a.pendingChanges = map[string][]PendingChange{}
|
||||
return a, func() displayCtlFixture {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(fixturePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var current displayCtlFixture
|
||||
if err := json.Unmarshal(raw, ¤t); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return current
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionWhileRunning(t *testing.T) {
|
||||
for _, useDriver := range []bool{false, true} {
|
||||
for _, state := range []string{"running", "paused"} {
|
||||
t.Run(fmt.Sprintf("driver=%t/%s", useDriver, state), func(t *testing.T) {
|
||||
initial := "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: state, Resolution: initial}, useDriver)
|
||||
on := true
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm := fixture()
|
||||
want := []PendingChange{
|
||||
{Field: "auto_resolution", From: "false", To: "true"},
|
||||
}
|
||||
if vm.Resolution != initial || len(vm.Commands) != 0 || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) {
|
||||
t.Fatalf("enable auto: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want)
|
||||
}
|
||||
if raw, found := reims.ReadConfiguredResolution(vm.Dir); !found || raw != initial {
|
||||
t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial)
|
||||
}
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: initial}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm = fixture()
|
||||
if vm.Resolution != initial || vmstart.ReadVMDisplay(vm.Dir).AutoResolution || len(a.pendingChanges) != 0 {
|
||||
t.Fatalf("manual resolution: VM %+v, want initial resolution and no pending changes, got %+v", vm, a.pendingChanges)
|
||||
}
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want = []PendingChange{{Field: "resolution", From: initial, To: "1280x800"}}
|
||||
if vm = fixture(); vm.Resolution != "1280x800" || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) {
|
||||
t.Fatalf("changed fixed resolution: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionDoesNotReadBackSettings(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
failShow, replace bool
|
||||
}{
|
||||
{name: "show fails", failShow: true},
|
||||
{name: "display changed externally", replace: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
const initial = "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
|
||||
State: "running", Resolution: initial, FailShowAfterSet: tc.failShow, ReplaceDisplayAfterSet: tc.replace,
|
||||
}, true)
|
||||
on := true
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, CPUs: 1, AutoResolution: &on}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []PendingChange{
|
||||
{Field: "cpus", From: "0", To: "1"},
|
||||
{Field: "auto_resolution", From: "false", To: "true"},
|
||||
}
|
||||
if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) {
|
||||
t.Fatalf("pending changes = %+v, want %+v", got, want)
|
||||
}
|
||||
if got := fixture().Commands; !slices.Equal(got, []string{"set test-vm --cpus 1"}) {
|
||||
t.Fatalf("commands = %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionUsesLockedSettingsForPendingChanges(t *testing.T) {
|
||||
for _, useDriver := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("driver=%t", useDriver), func(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
|
||||
State: "running", Resolution: "1234x876", BeforeLockResolution: "2560x1600", Memory: "2G",
|
||||
}, useDriver)
|
||||
if _, err := vmstart.SaveVMAutoResolution(fixture().Dir, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Memory: "3G"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vm := fixture()
|
||||
if vm.Resolution != "2560x1600" || vm.Memory != "3G" || vmstart.ReadVMDisplay(vm.Dir).AutoResolution {
|
||||
t.Fatalf("saved VM = %+v, display = %+v", vm, vmstart.ReadVMDisplay(vm.Dir))
|
||||
}
|
||||
want := []PendingChange{{Field: "memory", From: "2G", To: "3G"}}
|
||||
if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) {
|
||||
t.Fatalf("pending changes = %+v, want %+v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergePendingChangesKeepsRunningValues(t *testing.T) {
|
||||
existing := []PendingChange{
|
||||
{Field: "memory", From: "8G", To: "12G"},
|
||||
{Field: "resolution", From: "1920x1080", To: "2560x1440"},
|
||||
{Field: "gpu", From: "gpu-a", To: "gpu-b"},
|
||||
{Field: "cpus", From: "4", To: "6"},
|
||||
}
|
||||
incoming := []PendingChange{
|
||||
{Field: "memory", From: "12G", To: "8g"},
|
||||
{Field: "resolution", From: "2560x1440", To: "1920X1080"},
|
||||
{Field: "gpu", From: "gpu-b", To: "GPU-A"},
|
||||
{Field: "cpus", From: "6", To: "8"},
|
||||
}
|
||||
want := []PendingChange{
|
||||
{Field: "gpu", From: "gpu-a", To: "GPU-A"},
|
||||
{Field: "cpus", From: "4", To: "8"},
|
||||
}
|
||||
if got := mergePendingChanges(existing, incoming); !slices.Equal(got, want) {
|
||||
t.Fatalf("merge = %+v, want %+v", got, want)
|
||||
}
|
||||
// When show reports live running value (4 -> 4) while user explicitly sets cpus back to 4,
|
||||
// pendingVMSettingsChanges still emits cpus so mergePendingChanges removes stale 4 -> 8
|
||||
// without disturbing unrelated pending entries.
|
||||
liveOutcome := macosdriver.SettingsOutcome{
|
||||
Valid: true,
|
||||
Running: true,
|
||||
Before: macosdriver.SettingsState{CPUs: 4, Memory: "8G"},
|
||||
After: macosdriver.SettingsState{CPUs: 4, Memory: "8G"},
|
||||
}
|
||||
diffs := pendingVMSettingsChanges(liveOutcome, reims.SetOpts{Name: displayFixtureVM, CPUs: 4})
|
||||
got := mergePendingChanges([]PendingChange{
|
||||
{Field: "cpus", From: "4", To: "8"},
|
||||
{Field: "memory", From: "8G", To: "12G"},
|
||||
}, diffs)
|
||||
wantAfterRevert := []PendingChange{{Field: "memory", From: "8G", To: "12G"}}
|
||||
if !slices.Equal(got, wantAfterRevert) {
|
||||
t.Fatalf("merge after live-value revert = %+v, want %+v", got, wantAfterRevert)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionTransaction(t *testing.T) {
|
||||
for _, useDriver := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
failSidecar, failSet bool
|
||||
}{
|
||||
{name: "saved"},
|
||||
{name: "sidecar write fails", failSidecar: true},
|
||||
{name: "set fails", failSet: true},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("driver=%t/%s", useDriver, tc.name), func(t *testing.T) {
|
||||
const initial = "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, FailSet: tc.failSet}, useDriver)
|
||||
dir := fixture().Dir
|
||||
prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"}
|
||||
if tc.failSidecar {
|
||||
if err := os.Mkdir(filepath.Join(dir, ".reims-go-display.json"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
on := true
|
||||
err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on, NestedVirt: &on})
|
||||
if tc.failSidecar {
|
||||
if err == nil || len(fixture().Commands) != 0 {
|
||||
t.Fatalf("save = %v, commands = %v, want sidecar error before set", err, fixture().Commands)
|
||||
}
|
||||
return
|
||||
}
|
||||
vm := fixture()
|
||||
target, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true)
|
||||
if !slices.Equal(vm.Commands, []string{"set test-vm --resolution " + target}) {
|
||||
t.Fatalf("commands = %v", vm.Commands)
|
||||
}
|
||||
if nested, readErr := vmstart.ReadVMNestedVirt(dir); readErr != nil || nested.Enabled != !tc.failSet {
|
||||
t.Fatalf("nested virtualization = %+v, %v, want enabled = %t", nested, readErr, !tc.failSet)
|
||||
}
|
||||
if tc.failSet {
|
||||
if err == nil || !vm.NestedVirtBeforeSet || vm.Resolution != initial || vmstart.ReadVMDisplay(dir) != prev {
|
||||
t.Fatalf("save = %v, VM = %+v, display = %+v, want original settings", err, vm, vmstart.ReadVMDisplay(dir))
|
||||
}
|
||||
return
|
||||
}
|
||||
prev.AutoResolution = true
|
||||
if err != nil || vm.Resolution != target || vmstart.ReadVMDisplay(dir) != prev {
|
||||
t.Fatalf("save = %v, VM = %+v, display = %+v, want %s and %+v", err, vm, vmstart.ReadVMDisplay(dir), target, prev)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionWithSVGA(t *testing.T) {
|
||||
for _, useDriver := range []bool{false, true} {
|
||||
for _, graphics := range []string{"vmware-svga", "reims-vgpu"} {
|
||||
t.Run(fmt.Sprintf("driver=%t/from=%s", useDriver, graphics), func(t *testing.T) {
|
||||
const initial = "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, Graphics: graphics}, useDriver)
|
||||
dir := fixture().Dir
|
||||
prev := vmstart.VMDisplayConfig{TargetDisplay: "secondary", AutoResolution: true}
|
||||
if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := a.GetVMDetail(displayFixtureVM)
|
||||
if err != nil || detail.AutoResolution != (graphics == "reims-vgpu") {
|
||||
t.Fatalf("details = %+v, %v", detail, err)
|
||||
}
|
||||
on := true
|
||||
opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on}
|
||||
var want []string
|
||||
if graphics != "vmware-svga" {
|
||||
opts.Graphics = "vmware-svga"
|
||||
want = []string{"set test-vm --graphics vmware-svga"}
|
||||
}
|
||||
if err := a.ApplyVMSettings(opts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prev.AutoResolution = false
|
||||
if vm := fixture(); vm.Graphics != "vmware-svga" || vm.Resolution != initial ||
|
||||
!slices.Equal(vm.Commands, want) || vmstart.ReadVMDisplay(dir) != prev {
|
||||
t.Fatalf("VM = %+v, display = %+v, want commands %v and display %+v", vm, vmstart.ReadVMDisplay(dir), want, prev)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionRollsBackDisplayOnLaterFailure(t *testing.T) {
|
||||
for _, useDriver := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
state, blockedFile string
|
||||
}{
|
||||
{"running", ".reims-go-nested-virt.json"},
|
||||
{"stopped", ".reims-go-nested-virt.json"},
|
||||
{"running", ".reims-go-guest-lang"},
|
||||
{"stopped", ".reims-go-guest-lang"},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("driver=%t/%s/%s", useDriver, tc.state, tc.blockedFile), func(t *testing.T) {
|
||||
const initial = "1234x876"
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: tc.state, Resolution: initial}, useDriver)
|
||||
dir := fixture().Dir
|
||||
prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"}
|
||||
if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(dir, tc.blockedFile), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
on := true
|
||||
opts := reims.SetOpts{Name: displayFixtureVM, Memory: "4G", AutoResolution: &on, NestedVirt: &on}
|
||||
if tc.blockedFile == ".reims-go-guest-lang" {
|
||||
opts.GuestLang = "zh-Hans:0"
|
||||
}
|
||||
if err := a.ApplyVMSettings(opts); err == nil || !strings.Contains(err.Error(), tc.blockedFile) {
|
||||
t.Fatalf("save = %v, want error writing %s", err, tc.blockedFile)
|
||||
}
|
||||
if commands := fixture().Commands; len(commands) != 0 {
|
||||
t.Fatalf("commands = %v, want no reims-ctl set call before local failures", commands)
|
||||
}
|
||||
if got := vmstart.ReadVMDisplay(dir); got != prev || len(a.pendingChanges) != 0 {
|
||||
t.Fatalf("display = %+v, want %+v; pending = %+v", got, prev, a.pendingChanges)
|
||||
}
|
||||
if raw, found := reims.ReadConfiguredResolution(dir); !found || raw != initial {
|
||||
t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial)
|
||||
}
|
||||
if opts.GuestLang != "" {
|
||||
if nested, err := vmstart.ReadVMNestedVirt(dir); err != nil || nested.Enabled {
|
||||
t.Fatalf("nested virtualization = %+v, %v, want disabled", nested, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAutoResolutionSyncsExistingConfiguration(t *testing.T) {
|
||||
for _, useDriver := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name, graphics string
|
||||
borderless bool
|
||||
}{
|
||||
{name: "windowed multi-display"},
|
||||
{name: "borderless multi-display", borderless: true},
|
||||
{name: "from SVGA", graphics: "vmware-svga"},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("driver=%t/%s", useDriver, tc.name), func(t *testing.T) {
|
||||
res, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), tc.borderless, true)
|
||||
raw := res
|
||||
want := "set test-vm --resolution " + res
|
||||
on := true
|
||||
opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on}
|
||||
if tc.graphics == "vmware-svga" {
|
||||
opts.Graphics = "reims-vgpu"
|
||||
want = "set test-vm --graphics reims-vgpu --resolution " + res
|
||||
} else {
|
||||
raw += ",2560x1440"
|
||||
}
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{
|
||||
State: "stopped", Resolution: res, Graphics: tc.graphics, Borderless: tc.borderless,
|
||||
}, useDriver)
|
||||
dir := fixture().Dir
|
||||
if err := writeDisplayCtlResolution(dir, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.ApplyVMSettings(opts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := fixture().Commands; !slices.Equal(got, []string{want}) {
|
||||
t.Fatalf("commands = %v, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateVMWithAutoResolution(t *testing.T) {
|
||||
for _, useDriver := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name, graphics, resolution string
|
||||
wantAuto bool
|
||||
}{
|
||||
{name: "no draft", wantAuto: true},
|
||||
{name: "stale draft", resolution: "1234x876", wantAuto: true},
|
||||
{name: "SVGA", graphics: "vmware-svga", resolution: "1234x876"},
|
||||
{name: "SVGA without resolution", graphics: "vmware-svga"},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("driver=%t/%s", useDriver, tc.name), func(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{}, false)
|
||||
if useDriver {
|
||||
d := macosdriver.NewReimsMacOSDriver(func() config.Config { return *a.cfg })
|
||||
req := driver.CreateRequest{Name: displayFixtureVM, Options: map[string]any{"auto_resolution": true, "resolution": tc.resolution, "graphics": tc.graphics}}
|
||||
if err := d.Create(t.Context(), req, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
on := true
|
||||
if err := a.CreateVM(reims.CreateOpts{Name: displayFixtureVM, CPUs: 1, SourceMode: "disk", AutoResolution: &on, Resolution: tc.resolution, Graphics: tc.graphics}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
vm := fixture()
|
||||
want := tc.resolution
|
||||
if tc.wantAuto {
|
||||
want, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true)
|
||||
}
|
||||
if vm.Resolution != want || vmstart.ReadVMDisplay(vm.Dir).AutoResolution != tc.wantAuto {
|
||||
t.Fatalf("created VM = %+v, want resolution %s and automatic mode %t", vm, want, tc.wantAuto)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateVMWithAutoResolutionRefreshesAfterDiskConversion(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{}, false)
|
||||
source := filepath.Join(a.cfg.DataRoot, "source.raw")
|
||||
if err := os.WriteFile(source, []byte("raw disk"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
connectedDisplays := func() []host.DisplayInfo {
|
||||
converted, err := filepath.Glob(filepath.Join(a.cfg.TempDir(), "import-*.qcow2"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(converted) == 0 {
|
||||
return []host.DisplayInfo{{Primary: true, Width: 3840, Height: 2160, ScalePct: 150}}
|
||||
}
|
||||
return []host.DisplayInfo{{Primary: true, Width: 3200, Height: 2000, ScalePct: 200}}
|
||||
}
|
||||
on := true
|
||||
opts := reims.CreateOpts{Name: displayFixtureVM, CPUs: 1, SourceMode: "disk", Disk: source, AutoResolution: &on, Borderless: &on}
|
||||
if err := a.createVMFlow(opts, connectedDisplays); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if vm := fixture(); vm.Resolution != "3200x2000" || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution {
|
||||
t.Fatalf("created VM = %+v, want automatic 3200x2000", vm)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClonePreservesAutoResolution(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: "2880x1800"}, false)
|
||||
source := fixture().Dir
|
||||
if _, err := vmstart.SaveVMDisplay(source, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2", AutoResolution: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := macosdriver.NewReimsMacOSDriver(func() config.Config { return *a.cfg })
|
||||
if err := d.CloneCoW(t.Context(), displayFixtureVM, displayFixtureClone, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := vmstart.ReadVMDisplay(fixture().CloneDir); got != (vmstart.VMDisplayConfig{AutoResolution: true}) {
|
||||
t.Fatalf("cloned display preference = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyColdStartAutoResolution(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, initial, graphics string
|
||||
auto bool
|
||||
want []string
|
||||
}{
|
||||
{"changed", "3840x2160", "reims-vgpu", true, []string{"set test-vm --resolution 5120x2880", "start test-vm fixed=1"}},
|
||||
{"already current", "5120x2880", "reims-vgpu", true, []string{"start test-vm fixed=1"}},
|
||||
{"disabled", "3840x2160", "reims-vgpu", false, []string{"start test-vm fixed="}},
|
||||
{"SVGA", "3840x2160", "vmware-svga", true, []string{"start test-vm fixed="}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: tc.initial, Graphics: tc.graphics, Borderless: true}, false)
|
||||
if _, err := vmstart.SaveVMAutoResolution(fixture().Dir, tc.auto); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := a.startMacOSVMWithHost(displayFixtureVM, func(string) host.Report {
|
||||
return host.Report{WHPX: host.WHPXReady, Displays: []host.DisplayInfo{{Width: 3840, Height: 2160, ScalePct: 150, Primary: true}}}
|
||||
})
|
||||
if err == nil || !slices.Equal(fixture().Commands, tc.want) {
|
||||
t.Fatalf("legacy start = %v, commands %v, want %v", err, fixture().Commands, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
// startHandoffTimeout bounds how long `vm start` waits for the window to
|
||||
@@ -52,7 +53,7 @@ func startVM(ctx context.Context, cfg *config.Config, driverID, name string, via
|
||||
if err := requireDirectNetwork(vm); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = svc.Start(ctx, vm.Ref(), os.Stdout, os.Stderr)
|
||||
_, err = svc.Start(vmstart.WithPrimaryDisplayOnly(ctx), vm.Ref(), os.Stdout, os.Stderr)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ type DisplayInfo struct {
|
||||
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"`
|
||||
Left int `json:"left,omitempty"`
|
||||
Top int `json:"top,omitempty"`
|
||||
// WorkWidth and WorkHeight are the work area (the screen less the taskbar) in
|
||||
// pixels; 0 where unknown.
|
||||
WorkWidth int `json:"work_width,omitempty"`
|
||||
@@ -207,6 +209,28 @@ func RecommendDisplayPresets(primary *DisplayInfo) ([]DisplayPreset, string) {
|
||||
return out, out[rec].Resolution
|
||||
}
|
||||
|
||||
func RecommendAutoResolution(target *DisplayInfo, borderless, fixedModeSupported bool) (resolution string, hidpi bool) {
|
||||
if !borderless {
|
||||
presets, recommended := RecommendDisplayPresets(target)
|
||||
for _, preset := range presets {
|
||||
if preset.Resolution == recommended {
|
||||
return recommended, preset.HiDPI
|
||||
}
|
||||
}
|
||||
}
|
||||
if target == nil || target.Width <= 0 || target.Height <= 0 {
|
||||
return "1920x1080", false
|
||||
}
|
||||
if fixedModeSupported && target.Width >= 3200 && target.ScalePct >= 125 && target.ScalePct < 175 {
|
||||
width := max(16, (target.Width*4/3)/16*16)
|
||||
height := max(2, (target.Height*4/3)/2*2)
|
||||
if width <= 5120 && height <= 3200 && (width != target.Width || height != target.Height) {
|
||||
return fmt.Sprintf("%dx%d", width, height), true
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%dx%d", target.Width, target.Height), FullscreenStartsHiDPI(target)
|
||||
}
|
||||
|
||||
// ParseResolution parses "WxH" or "W×H" (ignoring surrounding spaces).
|
||||
func ParseResolution(raw string) (w, h int, ok bool) {
|
||||
var x rune
|
||||
|
||||
@@ -139,6 +139,38 @@ func TestRecommendDisplayPresets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecommendAutoResolution(t *testing.T) {
|
||||
uhd := &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150}
|
||||
laptop := &DisplayInfo{Width: 3200, Height: 2000, ScalePct: 200}
|
||||
wideLaptop := &DisplayInfo{Width: 3200, Height: 1800, ScalePct: 200}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
target *DisplayInfo
|
||||
borderless, fixed bool
|
||||
resolution string
|
||||
hidpi bool
|
||||
}{
|
||||
{"window 4K", uhd, false, true, "3200x1800", true},
|
||||
{"window 16:10", laptop, false, true, "2880x1800", true},
|
||||
{"window 16:9", wideLaptop, false, true, "2880x1620", true},
|
||||
{"window no screen", nil, false, true, "1920x1080", false},
|
||||
{"fullscreen supersampled", uhd, true, true, "5120x2880", true},
|
||||
{"fullscreen without fixed mode", uhd, true, false, "3840x2160", true},
|
||||
{"fullscreen 16:10 at 200%", laptop, true, true, "3200x2000", true},
|
||||
{"fullscreen no screen", nil, true, true, "1920x1080", false},
|
||||
{"fullscreen invalid size", &DisplayInfo{Width: 3200}, true, true, "1920x1080", false},
|
||||
{"fullscreen unknown scale", &DisplayInfo{Width: 3200, Height: 1800}, true, true, "3200x1800", false},
|
||||
{"fullscreen above size cap", &DisplayInfo{Width: 5120, Height: 2880, ScalePct: 150}, true, true, "5120x2880", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
res, hidpi := RecommendAutoResolution(tc.target, tc.borderless, tc.fixed)
|
||||
if res != tc.resolution || hidpi != tc.hidpi {
|
||||
t.Fatalf("recommendation = %s, HiDPI %t, want %s, HiDPI %t", res, hidpi, tc.resolution, tc.hidpi)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldUseFixedGuestMode(t *testing.T) {
|
||||
uhd := &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150, WorkWidth: 3840, WorkHeight: 2088, Primary: true}
|
||||
qhd := &DisplayInfo{Width: 2560, Height: 1440, ScalePct: 125, WorkWidth: 2560, WorkHeight: 1380, Primary: true}
|
||||
|
||||
@@ -184,6 +184,8 @@ func readDisplayInfo(monitor displayMonitor) DisplayInfo {
|
||||
ScalePct: scalePct,
|
||||
RefreshHz: refresh,
|
||||
Primary: mi.Flags&monitorInfoPrimary != 0,
|
||||
Left: int(mi.Monitor.Left),
|
||||
Top: int(mi.Monitor.Top),
|
||||
WorkWidth: workW,
|
||||
WorkHeight: workH,
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"affinity.summary.skipped": "自动跳过({vcpus}核≥{pthreads}P线程)",
|
||||
"affinityMenu": "处理器相关性…",
|
||||
"appearance": "外观",
|
||||
"autoResolution": "自动分辨率",
|
||||
"backToEdit": "返回修改",
|
||||
"borderless": "无边框全屏",
|
||||
"cancel": "取消",
|
||||
@@ -534,6 +535,8 @@ var catalog = map[Locale]map[string]string{
|
||||
"quitFailed": "已取消退出",
|
||||
"quitInProgress": "正在退出…",
|
||||
"refresh": "刷新",
|
||||
"resAuto": "自动",
|
||||
"resAutoValue": "自动({res})",
|
||||
"resLooksLike": "看起来像 {w} × {h}",
|
||||
"resizeLogPanel": "拖动调整日志高度",
|
||||
"resolution": "分辨率",
|
||||
@@ -725,6 +728,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"affinity.summary.skipped": "skipped({vcpus}vCPU>={pthreads}PT)",
|
||||
"affinityMenu": "Processor Affinity…",
|
||||
"appearance": "Appearance",
|
||||
"autoResolution": "Auto resolution",
|
||||
"backToEdit": "Edit and retry",
|
||||
"borderless": "Borderless full screen",
|
||||
"cancel": "Cancel",
|
||||
@@ -1241,6 +1245,8 @@ var catalog = map[Locale]map[string]string{
|
||||
"quitFailed": "Quit canceled",
|
||||
"quitInProgress": "Quitting…",
|
||||
"refresh": "Refresh",
|
||||
"resAuto": "Auto",
|
||||
"resAutoValue": "Auto ({res})",
|
||||
"resLooksLike": "Looks like {w} × {h}",
|
||||
"resizeLogPanel": "Drag to resize log panel",
|
||||
"resolution": "Resolution",
|
||||
@@ -1552,6 +1558,7 @@ var paramOrder = map[string][]string{
|
||||
"plugin.removed": {"id", "purge"},
|
||||
"plugin.runtime_settings_skipped": {"settings"},
|
||||
"plugin.target_not_found": {"target"},
|
||||
"resAutoValue": {"res"},
|
||||
"resLooksLike": {"h", "w"},
|
||||
"runtime.activated": {"commit"},
|
||||
"runtime.installed": {"commit", "dir"},
|
||||
|
||||
@@ -198,6 +198,11 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
|
||||
if err := driver.WriteOwnerDriver(cloned.Directory, d.ID()); err != nil {
|
||||
return err
|
||||
}
|
||||
if vmstart.ReadVMDisplay(src.Directory).AutoResolution {
|
||||
if _, err := vmstart.SaveVMAutoResolution(cloned.Directory, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if src.GuestLang != "" {
|
||||
prep, prepErr := startprep.New(cfg, func(line string) { _, _ = fmt.Fprintln(stdout, line) })
|
||||
if prepErr == nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package macosdriver
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
@@ -188,6 +190,7 @@ func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
enrichSuspendDetail(&det)
|
||||
det.AutoResolution = vmstart.SupportsAutoResolution(det.Graphics) && vmstart.ReadVMDisplay(det.Directory).AutoResolution
|
||||
marker := startprep.ReadRecoveryMarker(det.Directory)
|
||||
det.RecoveryMode = marker == "on" || marker == "want"
|
||||
rawBytes, _ := json.Marshal(det)
|
||||
@@ -272,6 +275,14 @@ func (d *ReimsMacOSDriver) Create(ctx context.Context, req driver.CreateRequest,
|
||||
if opts.Dir == "" {
|
||||
opts.Dir = req.Dir
|
||||
}
|
||||
applyAutoResolution := opts.AutoResolution != nil && *opts.AutoResolution && vmstart.SupportsAutoResolution(opts.Graphics)
|
||||
if applyAutoResolution {
|
||||
opts.Resolution, _ = host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), opts.Borderless != nil && *opts.Borderless, c.DisplayFixedMode)
|
||||
}
|
||||
startAfterCreate := applyAutoResolution && opts.Start
|
||||
if startAfterCreate {
|
||||
opts.Start = false
|
||||
}
|
||||
if err := c.Create(ctx, opts, stdout, stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -283,7 +294,19 @@ func (d *ReimsMacOSDriver) Create(ctx context.Context, req driver.CreateRequest,
|
||||
cfg := d.getConfig()
|
||||
vmDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", opts.Name)
|
||||
}
|
||||
return driver.WriteOwnerDriver(vmDir, d.ID())
|
||||
if err := driver.WriteOwnerDriver(vmDir, d.ID()); err != nil {
|
||||
return err
|
||||
}
|
||||
if applyAutoResolution {
|
||||
if _, err := vmstart.SaveVMAutoResolution(vmDir, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if startAfterCreate {
|
||||
_, err := d.Start(ctx, driver.StartRequest{Ref: driver.NewVMRef(d.ID(), opts.Name), Stdout: stdout, Stderr: stderr})
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req driver.SetRequest) []driver.ValidationIssue {
|
||||
@@ -326,34 +349,199 @@ func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdou
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
return ApplyVMOptions(ctx, c, cur, opts, stdout, stderr, func(cur reims.VMDetail) error {
|
||||
live := cur.State == "running" || cur.State == "paused"
|
||||
if opts.GuestLang == "" && (live || opts.Graphics == "" || opts.Graphics == cur.Graphics) {
|
||||
return nil
|
||||
}
|
||||
prep, err := startprep.New(d.getConfig(), func(line string) {
|
||||
if stdout != nil {
|
||||
_, _ = fmt.Fprintln(stdout, line)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.GuestLang != "" {
|
||||
return prep.ApplyGuestLang(ctx, cur.Directory, opts.GuestLang, live)
|
||||
}
|
||||
prep.ReplayGuestLang(ctx, cur.Directory)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func autoResolutionAfterSet(cur reims.VMDetail, opts reims.SetOpts) bool {
|
||||
if !vmstart.SupportsAutoResolution(cmp.Or(opts.Graphics, cur.Graphics)) {
|
||||
return false
|
||||
}
|
||||
if opts.AutoResolution != nil {
|
||||
return *opts.AutoResolution
|
||||
}
|
||||
return cur.AutoResolution && vmstart.SupportsAutoResolution(cur.Graphics) && strings.TrimSpace(opts.Resolution) == ""
|
||||
}
|
||||
|
||||
type SettingsState struct {
|
||||
CPUs, Displays int
|
||||
Memory, Resolution, GPU, DiskController, DiskCache, AudioBackend, GuestLang string
|
||||
AutoResolution, Borderless, NestedVirt, Audio bool
|
||||
}
|
||||
|
||||
type SettingsOutcome struct {
|
||||
Valid, Running bool
|
||||
Before, After SettingsState
|
||||
}
|
||||
|
||||
type settingsOutcomeKey struct{}
|
||||
|
||||
func WithSettingsOutcome(ctx context.Context, outcome *SettingsOutcome) context.Context {
|
||||
return context.WithValue(ctx, settingsOutcomeKey{}, outcome)
|
||||
}
|
||||
|
||||
func configuredResolution(cur reims.VMDetail) string {
|
||||
if raw, ok := reims.ReadConfiguredResolution(cur.Directory); ok {
|
||||
return raw
|
||||
}
|
||||
return cur.Resolution
|
||||
}
|
||||
|
||||
func needsAutoResolutionSync(cur reims.VMDetail, configured, resolution string) bool {
|
||||
return !vmstart.SupportsAutoResolution(cur.Graphics) || !strings.EqualFold(strings.TrimSpace(configured), resolution)
|
||||
}
|
||||
|
||||
// ApplyVMOptions saves the settings batch while the caller holds the VM operation lock.
|
||||
func ApplyVMOptions(ctx context.Context, c *reims.Client, cur reims.VMDetail, opts reims.SetOpts, stdout, stderr io.Writer, applyGuestLang func(reims.VMDetail) error) (err error) {
|
||||
live := cur.State == "running" || cur.State == "paused"
|
||||
prevDisplay := vmstart.ReadVMDisplay(cur.Directory)
|
||||
cur.AutoResolution = prevDisplay.AutoResolution
|
||||
nextDisplay := prevDisplay
|
||||
nextDisplay.AutoResolution = autoResolutionAfterSet(cur, opts)
|
||||
cur.Resolution = configuredResolution(cur)
|
||||
syncAutoResolution := nextDisplay.AutoResolution && opts.AutoResolution != nil
|
||||
if syncAutoResolution {
|
||||
opts.Resolution = ""
|
||||
if !live {
|
||||
borderless := cur.Borderless
|
||||
if opts.Borderless != nil {
|
||||
borderless = *opts.Borderless
|
||||
}
|
||||
target, _ := vmstart.ResolveTargetDisplay(prevDisplay, host.ConnectedDisplays())
|
||||
resolution, _ := host.RecommendAutoResolution(target, borderless, c.DisplayFixedMode)
|
||||
if needsAutoResolutionSync(cur, cur.Resolution, resolution) {
|
||||
opts.Resolution = resolution
|
||||
}
|
||||
}
|
||||
}
|
||||
outcome, _ := ctx.Value(settingsOutcomeKey{}).(*SettingsOutcome)
|
||||
if strings.TrimSpace(opts.GuestLang) != "" {
|
||||
cur.GuestLang = opencore.ReadSavedGuestLang(cur.Directory)
|
||||
if cur.GuestLang == "" {
|
||||
if path := opencore.ResolveOpenCorePath(cur.Directory); path != "" {
|
||||
cur.GuestLang, _ = opencore.ReadImagePrevLang(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
ctlCommitted := false
|
||||
if nextDisplay != prevDisplay {
|
||||
if _, err := vmstart.SaveVMDisplay(cur.Directory, nextDisplay); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil && !ctlCommitted {
|
||||
if _, rollbackErr := vmstart.SaveVMDisplay(cur.Directory, prevDisplay); rollbackErr != nil {
|
||||
err = errors.Join(err, rollbackErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
if opts.NestedVirt != nil {
|
||||
prevNestedVirt, readErr := vmstart.ReadVMNestedVirt(cur.Directory)
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
cur.NestedVirt = prevNestedVirt.Enabled
|
||||
if err := vmstart.SaveVMNestedVirt(cur.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil && !ctlCommitted {
|
||||
if rollbackErr := vmstart.SaveVMNestedVirt(cur.Directory, prevNestedVirt); rollbackErr != nil {
|
||||
err = errors.Join(err, rollbackErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
guestLangAfterSet := !live && opts.Graphics != "" && opts.Graphics != cur.Graphics
|
||||
if !guestLangAfterSet {
|
||||
if err := applyGuestLang(cur); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if reims.HasCtlSetChanges(opts) {
|
||||
if err := c.Set(ctx, opts, stdout, stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
ctlCommitted = true
|
||||
}
|
||||
if opts.NestedVirt != nil {
|
||||
if err := vmstart.SaveVMNestedVirt(cur.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil {
|
||||
if guestLangAfterSet {
|
||||
if err := applyGuestLang(cur); err != nil {
|
||||
if outcome != nil {
|
||||
*outcome = settingsOutcome(cur, opts, nextDisplay.AutoResolution, live)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
if opts.GuestLang == "" && (cur.State == "running" || opts.Graphics == "" || opts.Graphics == cur.Graphics) {
|
||||
return nil
|
||||
if outcome != nil {
|
||||
*outcome = settingsOutcome(cur, opts, nextDisplay.AutoResolution, live)
|
||||
}
|
||||
prep, err := startprep.New(d.getConfig(), func(line string) {
|
||||
if stdout != nil {
|
||||
_, _ = fmt.Fprintln(stdout, line)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.GuestLang != "" {
|
||||
return prep.ApplyGuestLang(ctx, cur.Directory, opts.GuestLang, cur.State == "running")
|
||||
}
|
||||
prep.ReplayGuestLang(ctx, cur.Directory)
|
||||
return nil
|
||||
}
|
||||
|
||||
func settingsOutcome(cur reims.VMDetail, applied reims.SetOpts, autoResolution, live bool) SettingsOutcome {
|
||||
before := SettingsState{
|
||||
CPUs: cur.CPUs, Displays: cur.Displays, Memory: cur.Memory, Resolution: cur.Resolution,
|
||||
GPU: cur.GPU, DiskController: cur.DiskController, DiskCache: cmp.Or(cur.DiskCache, "default"),
|
||||
AudioBackend: cmp.Or(cur.AudioBackend, "auto"), GuestLang: cmp.Or(cur.GuestLang, "en-US:0"),
|
||||
AutoResolution: vmstart.SupportsAutoResolution(cur.Graphics) && cur.AutoResolution,
|
||||
Borderless: cur.Borderless, NestedVirt: cur.NestedVirt, Audio: cur.Audio,
|
||||
}
|
||||
after := before
|
||||
after.AutoResolution = autoResolution
|
||||
after.Memory = cmp.Or(applied.Memory, before.Memory)
|
||||
after.GPU = cmp.Or(applied.GPU, before.GPU)
|
||||
if dc := strings.ToLower(strings.TrimSpace(applied.DiskController)); dc != "" {
|
||||
after.DiskController = dc
|
||||
}
|
||||
if dcache := strings.ToLower(strings.TrimSpace(applied.DiskCache)); dcache != "" {
|
||||
after.DiskCache = dcache
|
||||
}
|
||||
after.AudioBackend = cmp.Or(applied.AudioBackend, before.AudioBackend)
|
||||
if applied.Resolution != "" {
|
||||
after.Resolution = applied.Resolution
|
||||
if raw, found := reims.ReadConfiguredResolution(cur.Directory); found {
|
||||
after.Resolution = raw
|
||||
}
|
||||
}
|
||||
if applied.CPUs > 0 {
|
||||
after.CPUs = applied.CPUs
|
||||
}
|
||||
if applied.Displays > 0 {
|
||||
after.Displays = applied.Displays
|
||||
}
|
||||
if applied.Borderless != nil {
|
||||
after.Borderless = *applied.Borderless
|
||||
}
|
||||
if applied.NestedVirt != nil {
|
||||
after.NestedVirt = *applied.NestedVirt
|
||||
}
|
||||
if applied.Audio != nil {
|
||||
after.Audio = *applied.Audio
|
||||
}
|
||||
if strings.TrimSpace(applied.GuestLang) != "" {
|
||||
after.GuestLang = cmp.Or(opencore.ReadSavedGuestLang(cur.Directory), before.GuestLang)
|
||||
}
|
||||
return SettingsOutcome{Valid: true, Running: live, Before: before, After: after}
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error {
|
||||
c, err := d.client()
|
||||
if err != nil {
|
||||
|
||||
@@ -57,6 +57,34 @@ func runFakeCtl(args []string) int {
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "VM %q not found\n", args[1])
|
||||
return 1
|
||||
case (len(args) == 4 && args[0] == "set" && (args[2] == "--resolution" || args[2] == "--extra-args")) || (len(args) == 2 && args[0] == "start"):
|
||||
path := os.Getenv("REIMS_TEST_CTL_DISPLAY_LOG")
|
||||
if path != "" {
|
||||
command := strings.Join(args, " ")
|
||||
if args[0] == "start" {
|
||||
command += " fixed=" + os.Getenv("REIMS_VGPU_WINDOW_FIXED_MODE")
|
||||
}
|
||||
log, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600)
|
||||
if err == nil {
|
||||
_, err = fmt.Fprintln(log, command)
|
||||
if closeErr := log.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 2
|
||||
}
|
||||
if args[0] == "set" && args[2] == "--resolution" && os.Getenv("REIMS_TEST_CTL_FAIL_RESOLUTION") == "1" {
|
||||
fmt.Fprintln(os.Stderr, "fixture refused resolution")
|
||||
return 1
|
||||
}
|
||||
if args[0] == "start" && os.Getenv("REIMS_TEST_CTL_FAIL_START") == "1" {
|
||||
fmt.Fprintln(os.Stderr, "fixture stopped at incoming launch")
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "fake reims-ctl: unsupported arguments", args)
|
||||
return 2
|
||||
|
||||
@@ -41,6 +41,10 @@ func startLog(w io.Writer, line string) {
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (driver.StartResult, error) {
|
||||
return d.startWithHost(ctx, req, host.Inspect)
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) startWithHost(ctx context.Context, req driver.StartRequest, inspect func(string) host.Report) (driver.StartResult, error) {
|
||||
ref := driver.NewVMRef(req.Ref.DriverID, req.Ref.Name)
|
||||
if ref.DriverID != d.ID() || ref.Name == "" || d.opts.OwnerID == "" {
|
||||
return driver.StartResult{}, fmt.Errorf("invalid macOS start request for %s:%s", ref.DriverID, ref.Name)
|
||||
@@ -73,7 +77,7 @@ func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (
|
||||
intentEnv = append(intentEnv, k+"="+v)
|
||||
}
|
||||
}
|
||||
return d.resumeLocked(ctx, c, active, cur, intentEnv, stdout, stderr)
|
||||
return d.resumeLocked(ctx, c, active, cur, intentEnv, stdout, stderr, inspect)
|
||||
}
|
||||
if cur.State == "running" {
|
||||
return driver.StartResult{}, errors.New(i18n.T(cfg.Locale, "vm.already_running", ref.Name))
|
||||
@@ -87,7 +91,7 @@ func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (
|
||||
defer releaseNet()
|
||||
}
|
||||
}
|
||||
rep := host.Inspect(cfg.DataRoot)
|
||||
rep := inspect(cfg.DataRoot)
|
||||
prep, err := startprep.New(cfg, func(line string) { startLog(stdout, line) })
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
@@ -120,9 +124,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") &&
|
||||
vmstart.UsesFixedGuestMode(cur.Directory, rep.Displays, cur.Borderless, cur.Resolution) {
|
||||
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
if err := PrepareColdStartDisplay(ctx, c, &cur, rep.Displays, vmstart.LineWriter(func(line string) { startLog(stdout, line) })); err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
if d.opts.ManagedByDesktop && active.Manifest.HasCapability("client-window-close") {
|
||||
c.Env = append(c.Env, vmstart.CloseRequestEnv(ref.Name)...)
|
||||
@@ -141,6 +144,35 @@ func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (
|
||||
return driver.StartResult{PostStart: reconciled.PostStart}, nil
|
||||
}
|
||||
|
||||
// PrepareColdStartDisplay applies the monitor's recommendation before deciding
|
||||
// whether the guest needs a fixed display mode.
|
||||
func PrepareColdStartDisplay(ctx context.Context, c *reims.Client, cur *reims.VMDetail, displays []host.DisplayInfo, log io.Writer) error {
|
||||
if vmstart.PrimaryDisplayOnly(ctx) {
|
||||
const key = "REIMS_VGPU_WINDOW_SCREENS"
|
||||
screens, found := reims.ReadConfiguredEnv(cur.Directory, key)
|
||||
if !found {
|
||||
screens = os.Getenv(key)
|
||||
}
|
||||
displays = vmstart.DirectStartDisplays(displays, screens)
|
||||
}
|
||||
if cur.State == "stopped" && vmstart.SupportsAutoResolution(cur.Graphics) {
|
||||
resolution, _, enabled := vmstart.ResolveAutoResolution(cur.Directory, displays, cur.Borderless, c.DisplayFixedMode)
|
||||
if enabled && resolution != "" {
|
||||
if needsAutoResolutionSync(*cur, configuredResolution(*cur), resolution) {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: cur.Name, Resolution: resolution}, log, log); err != nil {
|
||||
return fmt.Errorf("apply automatic display resolution: %w", err)
|
||||
}
|
||||
startLog(log, fmt.Sprintf("Auto-adjusted display resolution to %s.", resolution))
|
||||
}
|
||||
cur.Resolution = resolution
|
||||
}
|
||||
}
|
||||
if c.DisplayFixedMode && vmstart.UsesFixedGuestMode(cur.Directory, displays, cur.Borderless, cur.Resolution) {
|
||||
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func prepareColdStart(ctx context.Context, cur reims.VMDetail, tmpDir string, stdout, stderr io.Writer) (bool, error) {
|
||||
if cur.State != "stopped" {
|
||||
return false, nil
|
||||
|
||||
@@ -3,8 +3,10 @@ package macosdriver
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -13,6 +15,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
@@ -22,6 +25,254 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func newColdDisplayDriver(t *testing.T, resolution, graphics string) (*ReimsMacOSDriver, string, func() string) {
|
||||
t.Helper()
|
||||
d := newFakeRuntimeDriver(t)
|
||||
d.opts.OwnerID = builtin.IDDriverReimsMacOS
|
||||
cfg := d.getConfig()
|
||||
dir := filepath.Join(cfg.DataRoot, "vms", "normal-vm")
|
||||
data := fakeCtlData{Show: map[string]string{
|
||||
"normal-vm": fmt.Sprintf("state stopped\ndirectory %s\ngraphics %s\ndisplay one, borderless\n", dir, graphics),
|
||||
}}
|
||||
raw, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(cfg.XDGDataDir(), fakeCtlFixture), raw, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest := filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime, "manifest.json")
|
||||
if err := os.WriteFile(manifest, []byte(`{"schema_version":2,"commit":"test-rt","kind":"reims-vgpu","runtime_api":"1.0.0","capabilities":["display-fixed-mode","vm-suspend"]}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := filepath.Join(cfg.XDGConfigDir(), "reims-ctl")
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", registry)
|
||||
if err := os.MkdirAll(registry, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(registry, "vms.toml"), []byte(fmt.Sprintf("[[vm]]\nname = 'normal-vm'\ndir = '%s'\n", dir)), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vmConfig := fmt.Sprintf("disk = 'system.qcow2'\n[display]\nresolution = %q\n", resolution)
|
||||
if err := os.WriteFile(filepath.Join(dir, "vm.toml"), []byte(vmConfig), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logPath := filepath.Join(cfg.DataRoot, "display-calls.log")
|
||||
if err := os.WriteFile(logPath, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("REIMS_TEST_CTL_DISPLAY_LOG", logPath)
|
||||
t.Setenv("REIMS_VGPU_WINDOW_FIXED_MODE", "")
|
||||
t.Setenv("REIMS_VGPU_WINDOW_SCREENS", "")
|
||||
t.Setenv("GORACE", "atexit_sleep_ms=0")
|
||||
return d, dir, func() string {
|
||||
t.Helper()
|
||||
log, err := os.ReadFile(logPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(log)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriverColdStartAutoResolution(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, initial, graphics string
|
||||
auto, primaryOnly bool
|
||||
target, want, adjustedTo string
|
||||
}{
|
||||
{"changed", "3840x2160", "reims-vgpu", true, false, "", "set normal-vm --resolution 5120x2880\nstart normal-vm fixed=1\n", "5120x2880"},
|
||||
{"already current", "5120x2880", "reims-vgpu", true, false, "", "start normal-vm fixed=1\n", ""},
|
||||
{"disabled", "3840x2160", "reims-vgpu", false, false, "", "start normal-vm fixed=\n", ""},
|
||||
{"SVGA", "3840x2160", "vmware-svga", true, false, "", "start normal-vm fixed=\n", ""},
|
||||
{"desktop secondary", "3840x2160", "reims-vgpu", true, false, "secondary", "set normal-vm --resolution 3200x2000\nstart normal-vm fixed=\n", "3200x2000"},
|
||||
{"already current with uppercase separator", "3200X2000", "reims-vgpu", true, false, "secondary", "start normal-vm fixed=\n", ""},
|
||||
{"direct CLI primary", "3840x2160", "reims-vgpu", true, true, "secondary", "set normal-vm --resolution 5120x2880\nstart normal-vm fixed=1\n", "5120x2880"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d, dir, commands := newColdDisplayDriver(t, tc.initial, tc.graphics)
|
||||
if _, err := vmstart.SaveVMDisplay(dir, vmstart.VMDisplayConfig{TargetDisplay: tc.target, AutoResolution: tc.auto}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := t.Context()
|
||||
if tc.primaryOnly {
|
||||
ctx = vmstart.WithPrimaryDisplayOnly(ctx)
|
||||
}
|
||||
var log bytes.Buffer
|
||||
req := driver.StartRequest{Ref: driver.NewVMRef(d.ID(), "normal-vm"), Stdout: &log}
|
||||
if _, err := d.startWithHost(ctx, req, coldDisplayHost); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := commands(); got != tc.want {
|
||||
t.Fatalf("reims-ctl = %q, want %q", got, tc.want)
|
||||
}
|
||||
if tc.adjustedTo == "" && strings.Contains(log.String(), "Auto-adjusted display resolution") ||
|
||||
tc.adjustedTo != "" && !strings.Contains(log.String(), "Auto-adjusted display resolution to "+tc.adjustedTo+".") {
|
||||
t.Fatalf("VM log = %q", log.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func coldDisplayHost(string) host.Report {
|
||||
return host.Report{WHPX: host.WHPXReady, Displays: []host.DisplayInfo{
|
||||
{Name: "secondary", Width: 3200, Height: 2000, ScalePct: 200},
|
||||
{Name: "primary", Width: 3840, Height: 2160, ScalePct: 150, Primary: true},
|
||||
}}
|
||||
}
|
||||
|
||||
func TestDriverColdStartHonorsDirectScreenOverride(t *testing.T) {
|
||||
const primaryStart = "set normal-vm --resolution 5120x2880\nstart normal-vm fixed=1\n"
|
||||
const secondaryStart = "set normal-vm --resolution 3200x2000\nstart normal-vm fixed=\n"
|
||||
for _, tc := range []struct {
|
||||
name, parent, configured, want string
|
||||
}{
|
||||
{name: "parent process", parent: "1", want: secondaryStart},
|
||||
{name: "VM extra_env only", configured: "[extra_env]\nREIMS_VGPU_WINDOW_SCREENS = '1'\n", want: secondaryStart},
|
||||
{name: "VM extra_env overrides parent", parent: "0", configured: "[extra_env]\nREIMS_VGPU_WINDOW_SCREENS = '1'\n", want: secondaryStart},
|
||||
{name: "VM env table is ignored", parent: "0", configured: "[env]\nREIMS_VGPU_WINDOW_SCREENS = '1'\n", want: primaryStart},
|
||||
{name: "empty VM extra_env overrides parent", parent: "1", configured: "[extra_env]\nREIMS_VGPU_WINDOW_SCREENS = ''\n", want: primaryStart},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d, dir, commands := newColdDisplayDriver(t, "3840x2160", "reims-vgpu")
|
||||
if _, err := vmstart.SaveVMDisplay(dir, vmstart.VMDisplayConfig{AutoResolution: true, TargetDisplay: "primary"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("REIMS_VGPU_WINDOW_SCREENS", tc.parent)
|
||||
if tc.configured != "" {
|
||||
content := "disk = 'system.qcow2'\n[display]\nresolution = '3840x2160'\n" + tc.configured
|
||||
if err := os.WriteFile(filepath.Join(dir, "vm.toml"), []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
ctx := vmstart.WithPrimaryDisplayOnly(t.Context())
|
||||
req := driver.StartRequest{Ref: driver.NewVMRef(d.ID(), "normal-vm")}
|
||||
if _, err := d.startWithHost(ctx, req, coldDisplayHost); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := commands(); got != tc.want {
|
||||
t.Fatalf("reims-ctl = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareColdStartDisplayUsesMatchingConfiguredResolution(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "vm.toml"), []byte("[display]\nresolution = '3200X2000'\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := vmstart.SaveVMAutoResolution(dir, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur := reims.VMDetail{Directory: dir, Name: "test-vm", State: "stopped", Borderless: true, Resolution: "1920x1080"}
|
||||
c := &reims.Client{DisplayFixedMode: true}
|
||||
displays := []host.DisplayInfo{{Primary: true, Width: 3200, Height: 2000, ScalePct: 200}}
|
||||
if err := PrepareColdStartDisplay(t.Context(), c, &cur, displays, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cur.Resolution != "3200x2000" || slices.Contains(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") {
|
||||
t.Fatalf("resolution = %q, env = %v", cur.Resolution, c.Env)
|
||||
}
|
||||
}
|
||||
|
||||
func TestColdStartSyncsPerDisplayResolutions(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, raw, resolution string
|
||||
borderless bool
|
||||
displays []host.DisplayInfo
|
||||
}{
|
||||
{"windowed", "3200x1800,2560x1440", "3200x1800", false, []host.DisplayInfo{
|
||||
{Primary: true, Width: 3840, Height: 2160, ScalePct: 150},
|
||||
}},
|
||||
{"borderless", "2560x1440,1280x800", "1920x1080", true, []host.DisplayInfo{
|
||||
{Primary: true, Width: 1920, Height: 1080, ScalePct: 100},
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d, dir, commands := newColdDisplayDriver(t, tc.raw, "reims-vgpu")
|
||||
if _, err := vmstart.SaveVMAutoResolution(dir, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := d.client()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur := reims.VMDetail{Name: "normal-vm", Directory: dir, State: "stopped", Graphics: "reims-vgpu", Resolution: tc.resolution, Borderless: tc.borderless, Displays: 2}
|
||||
if err := PrepareColdStartDisplay(t.Context(), c, &cur, tc.displays, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := commands(), "set normal-vm --resolution "+tc.resolution+"\n"; got != want {
|
||||
t.Fatalf("reims-ctl = %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestColdStartStopsWhenAutoResolutionSetFails(t *testing.T) {
|
||||
d, dir, commands := newColdDisplayDriver(t, "3840x2160", "reims-vgpu")
|
||||
if _, err := vmstart.SaveVMAutoResolution(dir, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("REIMS_TEST_CTL_FAIL_RESOLUTION", "1")
|
||||
req := driver.StartRequest{Ref: driver.NewVMRef(d.ID(), "normal-vm")}
|
||||
if _, err := d.startWithHost(t.Context(), req, coldDisplayHost); err == nil || !strings.Contains(err.Error(), "apply automatic display resolution") {
|
||||
t.Fatalf("start = %v, want automatic resolution error", err)
|
||||
}
|
||||
if got := commands(); got != "set normal-vm --resolution 5120x2880\n" {
|
||||
t.Fatalf("reims-ctl = %q, want only the failed resolution write", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuspendResumeDoesNotSyncAutoResolution(t *testing.T) {
|
||||
d, dir, commands := newColdDisplayDriver(t, "1234x876", "reims-vgpu")
|
||||
if _, err := vmstart.SaveVMAutoResolution(dir, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("REIMS_TEST_CTL_FAIL_START", "1")
|
||||
disk := filepath.Join(dir, "system.qcow2")
|
||||
for _, path := range []string{disk, reims.SuspendStatePath(dir) + ".tmp"} {
|
||||
if err := os.WriteFile(path, []byte("fixture"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
vmConfig := filepath.Join(dir, "vm.toml")
|
||||
before, err := os.ReadFile(vmConfig)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := driver.NewVMRef(d.ID(), "normal-vm")
|
||||
c, active, err := d.startClient()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := c.Show(t.Context(), ref.Name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := reims.SealSuspend(detail, active, []string{disk}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var stderr bytes.Buffer
|
||||
_, startErr := d.startWithHost(t.Context(), driver.StartRequest{Ref: ref, Stderr: &stderr}, coldDisplayHost)
|
||||
_, resumeErr := d.resumeWithHost(t.Context(), driver.ResumeRequest{Ref: ref, Stdout: io.Discard, Stderr: &stderr}, coldDisplayHost)
|
||||
for _, err := range []error{startErr, resumeErr} {
|
||||
if err == nil {
|
||||
t.Fatalf("resume = %v, want incoming launch error after fingerprint validation", err)
|
||||
}
|
||||
}
|
||||
if strings.Count(stderr.String(), "fixture stopped at incoming launch") != 2 {
|
||||
t.Fatalf("resume did not reach both incoming launches: %q, start error: %v, resume error: %v", stderr.String(), startErr, resumeErr)
|
||||
}
|
||||
if got := commands(); strings.Contains(got, "--resolution") || strings.Count(got, "start normal-vm ") != 2 ||
|
||||
strings.Count(got, "--extra-args") != 4 {
|
||||
t.Fatalf("resume commands = %q, want two incoming starts with argument setup and restore", got)
|
||||
}
|
||||
if after, err := os.ReadFile(vmConfig); err != nil || !bytes.Equal(before, after) {
|
||||
t.Fatalf("resume changed vm.toml: %q, %v", after, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanStaleSuspendBeforeStart(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
|
||||
@@ -78,6 +78,10 @@ func (d *ReimsMacOSDriver) Suspend(ctx context.Context, req driver.SuspendReques
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) Resume(ctx context.Context, req driver.ResumeRequest) (driver.StartResult, error) {
|
||||
return d.resumeWithHost(ctx, req, host.Inspect)
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) resumeWithHost(ctx context.Context, req driver.ResumeRequest, inspect func(string) host.Report) (driver.StartResult, error) {
|
||||
c, active, err := d.startClient()
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
@@ -87,10 +91,10 @@ func (d *ReimsMacOSDriver) Resume(ctx context.Context, req driver.ResumeRequest)
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
defer release()
|
||||
return d.resumeLocked(ctx, c, active, cur, req.ExtraEnv, req.Stdout, req.Stderr)
|
||||
return d.resumeLocked(ctx, c, active, cur, req.ExtraEnv, req.Stdout, req.Stderr, inspect)
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) resumeLocked(ctx context.Context, c *reims.Client, active rt.Installed, cur reims.VMDetail, extraEnv []string, stdout, stderr io.Writer) (driver.StartResult, error) {
|
||||
func (d *ReimsMacOSDriver) resumeLocked(ctx context.Context, c *reims.Client, active rt.Installed, cur reims.VMDetail, extraEnv []string, stdout, stderr io.Writer, inspect func(string) host.Report) (driver.StartResult, error) {
|
||||
if d.opts.PrepareNetwork != nil {
|
||||
releaseNet, err := d.opts.PrepareNetwork(ctx, cur.Name, true)
|
||||
if err != nil {
|
||||
@@ -107,7 +111,7 @@ func (d *ReimsMacOSDriver) resumeLocked(ctx context.Context, c *reims.Client, ac
|
||||
stderr = io.Discard
|
||||
}
|
||||
cfg := d.getConfig()
|
||||
rep := host.Inspect(cfg.DataRoot)
|
||||
rep := inspect(cfg.DataRoot)
|
||||
var qmpAddr string
|
||||
if d.opts.ManagedByDesktop && cur.State == "stopped" && reims.HasSuspendState(cur.Directory) && rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(cur.Directory, cfg.TempDir(), cur.Name)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
func TestBorderlessResolutionFallback(t *testing.T) {
|
||||
for _, tc := range []struct{ name, display, config, want string }{
|
||||
{"configured", "borderless", "resolution = '5120x2880'", "5120x2880"},
|
||||
{"uppercase separator", "borderless", "resolution = '3200X2000'", "3200x2000"},
|
||||
{"missing", "borderless", "", "1920x1080"},
|
||||
{"explicit", "one, opening at 2560x1440", "resolution = '5120x2880'", "2560x1440"},
|
||||
} {
|
||||
|
||||
@@ -25,9 +25,10 @@ import (
|
||||
|
||||
// Client wraps reims-ctl invocations using an isolated portable runtime.
|
||||
type Client struct {
|
||||
Binary string
|
||||
Env []string
|
||||
Locale i18n.Locale
|
||||
Binary string
|
||||
Env []string
|
||||
Locale i18n.Locale
|
||||
DisplayFixedMode bool
|
||||
|
||||
imagesDir string
|
||||
registryDir string
|
||||
@@ -38,8 +39,9 @@ type Client struct {
|
||||
|
||||
func NewClient(cfg *config.Config, installed rt.Installed) *Client {
|
||||
c := &Client{
|
||||
Binary: installed.ReimsCtlPath(),
|
||||
Env: rt.BuildChildEnv(cfg, installed),
|
||||
Binary: installed.ReimsCtlPath(),
|
||||
Env: rt.BuildChildEnv(cfg, installed),
|
||||
DisplayFixedMode: installed.Manifest.HasCapability("display-fixed-mode"),
|
||||
}
|
||||
if cfg != nil {
|
||||
c.Locale = cfg.Locale
|
||||
@@ -105,6 +107,7 @@ type VMDetail struct {
|
||||
Display string `json:"display"`
|
||||
Displays int `json:"displays"`
|
||||
Resolution string `json:"resolution"`
|
||||
AutoResolution bool `json:"auto_resolution"`
|
||||
GPU string `json:"gpu"`
|
||||
HasOpenCore bool `json:"has_opencore"`
|
||||
HasInstaller bool `json:"has_installer"`
|
||||
@@ -171,6 +174,7 @@ type CreateOpts struct {
|
||||
Graphics string `json:"graphics,omitempty"`
|
||||
GPU string `json:"gpu,omitempty"`
|
||||
Resolution string `json:"resolution,omitempty"`
|
||||
AutoResolution *bool `json:"auto_resolution,omitempty"`
|
||||
Displays int `json:"displays,omitempty"`
|
||||
Borderless *bool `json:"borderless,omitempty"`
|
||||
Capture *bool `json:"capture,omitempty"`
|
||||
@@ -193,6 +197,7 @@ type SetOpts struct {
|
||||
DiskController string `json:"disk_controller,omitempty"`
|
||||
DiskCache string `json:"disk_cache,omitempty"`
|
||||
Resolution string `json:"resolution,omitempty"`
|
||||
AutoResolution *bool `json:"auto_resolution,omitempty"`
|
||||
Borderless *bool `json:"borderless,omitempty"`
|
||||
Capture *bool `json:"capture,omitempty"`
|
||||
GPU string `json:"gpu,omitempty"`
|
||||
@@ -817,29 +822,49 @@ func applyBorderlessResolutionFallback(d *VMDetail) {
|
||||
if !d.Borderless || d.Directory == "" || reResIn.FindString(d.Display) != "" {
|
||||
return
|
||||
}
|
||||
if res := readVMDisplayResolution(d.Directory); res != "" {
|
||||
raw, _ := ReadConfiguredResolution(d.Directory)
|
||||
if res := strings.ToLower(strings.TrimSpace(raw)); reRes.MatchString(res) {
|
||||
d.Resolution = res
|
||||
}
|
||||
}
|
||||
|
||||
func readVMDisplayResolution(vmDir string) string {
|
||||
// ReadConfiguredResolution reads the full display resolution, including per-display values.
|
||||
func ReadConfiguredResolution(vmDir string) (raw string, found bool) {
|
||||
if vmDir == "" {
|
||||
return "", false
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(vmDir, "vm.toml"))
|
||||
if err != nil {
|
||||
return ""
|
||||
return "", false
|
||||
}
|
||||
var cfg struct {
|
||||
Display struct {
|
||||
Resolution string
|
||||
Resolution *string
|
||||
}
|
||||
}
|
||||
if err := toml.Unmarshal(data, &cfg); err != nil || cfg.Display.Resolution == nil {
|
||||
return "", false
|
||||
}
|
||||
return *cfg.Display.Resolution, true
|
||||
}
|
||||
|
||||
// ReadConfiguredEnv reads a per-VM environment override from reims-ctl's extra_env table.
|
||||
func ReadConfiguredEnv(vmDir, key string) (string, bool) {
|
||||
if vmDir == "" {
|
||||
return "", false
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(vmDir, "vm.toml"))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
var cfg struct {
|
||||
ExtraEnv map[string]string `toml:"extra_env"`
|
||||
}
|
||||
if err := toml.Unmarshal(data, &cfg); err != nil {
|
||||
return ""
|
||||
return "", false
|
||||
}
|
||||
res := strings.TrimSpace(cfg.Display.Resolution)
|
||||
if !reRes.MatchString(res) {
|
||||
return ""
|
||||
}
|
||||
return res
|
||||
value, ok := cfg.ExtraEnv[key]
|
||||
return value, ok
|
||||
}
|
||||
|
||||
func (c *Client) ReadLogs(ctx context.Context, name string, serial bool) (string, error) {
|
||||
|
||||
@@ -1,12 +1,46 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadConfiguredResolution(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if raw, found := ReadConfiguredResolution(dir); found || raw != "" {
|
||||
t.Fatalf("missing vm.toml = %q, %t", raw, found)
|
||||
}
|
||||
const want = " 3200x1800, 2560x1440 "
|
||||
content := "[display]\nresolution = '" + want + "'\n"
|
||||
path := filepath.Join(dir, "vm.toml")
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw, found := ReadConfiguredResolution(dir); !found || raw != want {
|
||||
t.Fatalf("resolution = %q, %t, want %q, true", raw, found, want)
|
||||
}
|
||||
if raw, err := os.ReadFile(path); err != nil || string(raw) != content {
|
||||
t.Fatalf("vm.toml = %q, %v, want %q", raw, err, content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoResolutionRemainsClientSide(t *testing.T) {
|
||||
for _, enabled := range []bool{true, false} {
|
||||
create, err := BuildCreateArgs(CreateOpts{Name: "test", AutoResolution: &enabled})
|
||||
if err != nil || strings.Join(create, " ") != "create test" {
|
||||
t.Fatalf("create args = %v, %v", create, err)
|
||||
}
|
||||
opts := SetOpts{Name: "test", AutoResolution: &enabled}
|
||||
set, err := BuildSetArgs(opts)
|
||||
if err != nil || strings.Join(set, " ") != "set test" || HasCtlSetChanges(opts) {
|
||||
t.Fatalf("sidecar-only set args = %v, %v, has ctl changes = %t", set, err, HasCtlSetChanges(opts))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCreateArgs(t *testing.T) {
|
||||
logs := true
|
||||
args, err := BuildCreateArgs(CreateOpts{
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package vmstart
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/atomicfile"
|
||||
@@ -14,7 +18,23 @@ import (
|
||||
const vmDisplayConfigFile = ".reims-go-display.json"
|
||||
|
||||
type VMDisplayConfig struct {
|
||||
TargetDisplay string `json:"target_display,omitempty"`
|
||||
TargetDisplay string `json:"target_display,omitempty"`
|
||||
AutoResolution bool `json:"auto_resolution,omitempty"`
|
||||
}
|
||||
|
||||
type primaryDisplayOnlyKey struct{}
|
||||
|
||||
func WithPrimaryDisplayOnly(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, primaryDisplayOnlyKey{}, true)
|
||||
}
|
||||
|
||||
func PrimaryDisplayOnly(ctx context.Context) bool {
|
||||
only, _ := ctx.Value(primaryDisplayOnlyKey{}).(bool)
|
||||
return only
|
||||
}
|
||||
|
||||
func SupportsAutoResolution(graphics string) bool {
|
||||
return !strings.EqualFold(strings.TrimSpace(graphics), "vmware-svga")
|
||||
}
|
||||
|
||||
func NormalizeTargetDisplay(raw string) string {
|
||||
@@ -44,7 +64,7 @@ func SaveVMDisplay(vmDir string, cfg VMDisplayConfig) (VMDisplayConfig, error) {
|
||||
}
|
||||
cfg.TargetDisplay = NormalizeTargetDisplay(cfg.TargetDisplay)
|
||||
dst := filepath.Join(vmDir, vmDisplayConfigFile)
|
||||
if cfg.TargetDisplay == "" {
|
||||
if cfg.TargetDisplay == "" && !cfg.AutoResolution {
|
||||
if err := os.Remove(dst); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return VMDisplayConfig{}, err
|
||||
}
|
||||
@@ -57,6 +77,22 @@ func SaveVMDisplay(vmDir string, cfg VMDisplayConfig) (VMDisplayConfig, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func SaveVMAutoResolution(vmDir string, enabled bool) (VMDisplayConfig, error) {
|
||||
cfg := ReadVMDisplay(vmDir)
|
||||
cfg.AutoResolution = enabled
|
||||
return SaveVMDisplay(vmDir, cfg)
|
||||
}
|
||||
|
||||
func ResolveAutoResolution(vmDir string, displays []host.DisplayInfo, borderless, fixedModeSupported bool) (resolution string, hidpi, enabled bool) {
|
||||
cfg := ReadVMDisplay(vmDir)
|
||||
if !cfg.AutoResolution {
|
||||
return "", false, false
|
||||
}
|
||||
target, _ := ResolveTargetDisplay(cfg, displays)
|
||||
resolution, hidpi = host.RecommendAutoResolution(target, borderless, fixedModeSupported)
|
||||
return resolution, hidpi, true
|
||||
}
|
||||
|
||||
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
|
||||
@@ -64,6 +100,40 @@ func ResolveTargetDisplay(cfg VMDisplayConfig, displays []host.DisplayInfo) (tar
|
||||
return host.PrimaryDisplayOf(displays), true
|
||||
}
|
||||
|
||||
func DirectStartDisplays(displays []host.DisplayInfo, screens string) []host.DisplayInfo {
|
||||
if target := directStartTargetDisplay(displays, screens); target != nil {
|
||||
return []host.DisplayInfo{*target}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func directStartTargetDisplay(displays []host.DisplayInfo, screens string) *host.DisplayInfo {
|
||||
var first uint64
|
||||
for i, entry := range strings.Split(screens, ",") {
|
||||
index, err := strconv.ParseUint(strings.TrimPrefix(strings.TrimSpace(entry), "+"), 10, strconv.IntSize)
|
||||
if err != nil {
|
||||
return host.PrimaryDisplayOf(displays)
|
||||
}
|
||||
if i == 0 {
|
||||
first = index
|
||||
}
|
||||
}
|
||||
if first < uint64(len(displays)) {
|
||||
ordered := slices.Clone(displays)
|
||||
slices.SortStableFunc(ordered, func(a, b host.DisplayInfo) int {
|
||||
if a.Primary != b.Primary {
|
||||
if a.Primary {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return cmp.Or(cmp.Compare(a.Top, b.Top), cmp.Compare(a.Left, b.Left))
|
||||
})
|
||||
return &ordered[first]
|
||||
}
|
||||
return host.PrimaryDisplayOf(displays)
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
@@ -62,6 +62,95 @@ func TestSaveVMDisplayReplacesConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveVMAutoResolution(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, vmDisplayConfigFile)
|
||||
if cfg, err := SaveVMAutoResolution(dir, true); err != nil || !cfg.AutoResolution || ReadVMDisplay(dir) != cfg {
|
||||
t.Fatalf("enable with default target = %+v, %v", cfg, err)
|
||||
}
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := SaveVMAutoResolution(dir, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("sidecar with both defaults should be removed: %v", err)
|
||||
}
|
||||
if _, err := SaveVMDisplay(dir, VMDisplayConfig{TargetDisplay: "DISPLAY2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, enabled := range []bool{true, false} {
|
||||
want := VMDisplayConfig{TargetDisplay: "DISPLAY2", AutoResolution: enabled}
|
||||
if got, err := SaveVMAutoResolution(dir, enabled); err != nil || got != want || ReadVMDisplay(dir) != want {
|
||||
t.Fatalf("save auto %t = %+v, %v, want %+v", enabled, got, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveAutoResolution(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
displays := []host.DisplayInfo{
|
||||
{Name: "DISPLAY1", Primary: true, Width: 3840, Height: 2160, ScalePct: 150},
|
||||
{Name: "DISPLAY2", Width: 3200, Height: 2000, ScalePct: 200},
|
||||
}
|
||||
if res, hidpi, enabled := ResolveAutoResolution(dir, displays, false, true); res != "" || hidpi || enabled {
|
||||
t.Fatalf("disabled = %q, %t, %t", res, hidpi, enabled)
|
||||
}
|
||||
if _, err := SaveVMDisplay(dir, VMDisplayConfig{TargetDisplay: "display2", AutoResolution: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
displays []host.DisplayInfo
|
||||
res string
|
||||
hidpi bool
|
||||
}{
|
||||
{displays, "2880x1800", true},
|
||||
{displays[:1], "3200x1800", true},
|
||||
{nil, "1920x1080", false},
|
||||
} {
|
||||
if res, hidpi, enabled := ResolveAutoResolution(dir, tc.displays, false, true); res != tc.res || hidpi != tc.hidpi || !enabled {
|
||||
t.Errorf("auto = %q, %t, %t, want %q, %t, true", res, hidpi, enabled, tc.res, tc.hidpi)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveAutoResolutionWithDirectScreenOverride(t *testing.T) {
|
||||
displays := []host.DisplayInfo{
|
||||
{Name: "lower", Top: 1},
|
||||
{Name: "primary", Primary: true, Width: 3840, Height: 2160, ScalePct: 150},
|
||||
{Name: "right", Top: -1},
|
||||
{Name: "secondary", Top: -1, Left: -1, Width: 3200, Height: 2000, ScalePct: 200},
|
||||
{Name: "tied", Top: -1, Left: -1},
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if _, err := SaveVMDisplay(dir, VMDisplayConfig{TargetDisplay: "secondary", AutoResolution: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
screens, resolution string
|
||||
fixed bool
|
||||
}{
|
||||
{"1", "3200x2000", false},
|
||||
{"0", "5120x2880", true},
|
||||
{" +1 , 0 ", "3200x2000", false},
|
||||
{"1,9", "3200x2000", false},
|
||||
{"1,bad", "5120x2880", true},
|
||||
{"1,-1", "5120x2880", true},
|
||||
{"1,", "5120x2880", true},
|
||||
{"9,1", "5120x2880", true},
|
||||
{"", "5120x2880", true},
|
||||
} {
|
||||
t.Run(tc.screens, func(t *testing.T) {
|
||||
targetDisplays := DirectStartDisplays(displays, tc.screens)
|
||||
res, _, enabled := ResolveAutoResolution(dir, targetDisplays, true, true)
|
||||
if fixed := UsesFixedGuestMode(dir, targetDisplays, true, res); !enabled || res != tc.resolution || fixed != tc.fixed {
|
||||
t.Fatalf("resolution = %q, enabled = %t, fixed = %t, want %q, true, %t", res, enabled, fixed, tc.resolution, tc.fixed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTargetDisplay(t *testing.T) {
|
||||
displays := []host.DisplayInfo{{Name: "DISPLAY2"}, {Name: "DISPLAY1", Primary: true}}
|
||||
for _, tc := range []struct {
|
||||
|
||||
@@ -162,6 +162,9 @@
|
||||
"gpuErrMissingExt": "Missing required Vulkan extensions ({ext}); update GPU drivers or use VMware SVGA",
|
||||
"gpuErrVulkanCpu": "Software Vulkan implementation cannot accelerate vGPU; use VMware SVGA",
|
||||
"resolution": "Resolution",
|
||||
"autoResolution": "Auto resolution",
|
||||
"resAuto": "Auto",
|
||||
"resAutoValue": "Auto ({res})",
|
||||
"displays": "Displays",
|
||||
"borderless": "Borderless full screen",
|
||||
"toastCreated": "{name} created",
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"gpuSvgaReason": "VMware SVGA does not use the host GPU",
|
||||
"groupGraphics": "Graphics",
|
||||
"displayGroup": "Displays",
|
||||
"resAutoSub": "Follows display · {res}",
|
||||
"resCustom": "Custom",
|
||||
"resCustomSub": "Width × height",
|
||||
"resNativeBadge": "Native",
|
||||
|
||||
@@ -162,6 +162,9 @@
|
||||
"gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA",
|
||||
"gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA",
|
||||
"resolution": "分辨率",
|
||||
"autoResolution": "自动分辨率",
|
||||
"resAuto": "自动",
|
||||
"resAutoValue": "自动({res})",
|
||||
"displays": "显示器数量",
|
||||
"borderless": "无边框全屏",
|
||||
"toastCreated": "{name} 已创建",
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"gpuSvgaReason": "VMware SVGA 不使用宿主显卡",
|
||||
"groupGraphics": "图形",
|
||||
"displayGroup": "显示器",
|
||||
"resAutoSub": "当前屏 {res}",
|
||||
"resCustom": "自定义",
|
||||
"resCustomSub": "宽 × 高",
|
||||
"resNativeBadge": "原生",
|
||||
|
||||
Reference in new issue
Block a user