From e25c7952ca8fbc8ea5371e789b957042b6e97362 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:52:34 +0800 Subject: [PATCH] feat(display): add automatic per-display HiDPI resolution mode --- changes/auto-display-resolution.json | 7 + frontend/scripts/test-auto-resolution.mjs | 712 ++++++++++++++++++ frontend/src/App.tsx | 9 +- frontend/src/components/CreateWizard.tsx | 125 ++- frontend/src/components/SettingsModal.tsx | 202 +++-- frontend/src/components/vmPage/techInfo.tsx | 8 +- frontend/src/i18n/domains/core.gen.ts | 6 + frontend/src/i18n/domains/settings.gen.ts | 2 + frontend/src/i18n/keys.gen.ts | 4 + frontend/src/lib/displayResolution.ts | 325 ++++++++ frontend/src/lib/format.ts | 43 +- frontend/wailsjs/go/models.ts | 10 + internal/app/create_flow.go | 14 +- internal/app/display_flow.go | 34 +- internal/app/display_flow_test.go | 20 + internal/app/macos_detail.go | 2 + internal/app/macos_lifecycle_native.go | 13 +- internal/app/macos_settings.go | 155 ++-- internal/app/macos_settings_test.go | 690 +++++++++++++++++ internal/cli/start.go | 3 +- internal/host/display.go | 24 + internal/host/display_stats_test.go | 32 + internal/host/display_windows.go | 2 + internal/i18n/catalog_gen.go | 7 + internal/macos/macosdriver/clone.go | 5 + internal/macos/macosdriver/driver.go | 214 +++++- internal/macos/macosdriver/drivertest_test.go | 28 + internal/macos/macosdriver/prepare.go | 42 +- internal/macos/macosdriver/prepare_test.go | 247 ++++++ internal/macos/macosdriver/suspend.go | 10 +- .../macos/reims/borderless_resolution_test.go | 1 + internal/macos/reims/reims.go | 57 +- internal/macos/reims/reims_test.go | 34 + internal/vmstart/display.go | 74 +- internal/vmstart/display_test.go | 89 +++ locales/en-US/core.json | 3 + locales/en-US/settings.json | 1 + locales/zh-CN/core.json | 3 + locales/zh-CN/settings.json | 1 + 39 files changed, 3024 insertions(+), 234 deletions(-) create mode 100644 changes/auto-display-resolution.json create mode 100644 frontend/scripts/test-auto-resolution.mjs create mode 100644 frontend/src/lib/displayResolution.ts create mode 100644 internal/app/macos_settings_test.go diff --git a/changes/auto-display-resolution.json b/changes/auto-display-resolution.json new file mode 100644 index 0000000..6682669 --- /dev/null +++ b/changes/auto-display-resolution.json @@ -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." +} diff --git a/frontend/scripts/test-auto-resolution.mjs b/frontend/scripts/test-auto-resolution.mjs new file mode 100644 index 0000000..b3d52b0 --- /dev/null +++ b/frontend/scripts/test-auto-resolution.mjs @@ -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', + }, + ) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2529e1c..d14c315 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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 && ( = ({ 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(draft?.opts ?? { name: 'macos-tahoe', dir: '', @@ -120,11 +133,11 @@ export const CreateWizard: React.FC = ({ 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 = ({ 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) => setOpts((o) => ({ ...o, ...patch })) const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off') @@ -157,9 +173,22 @@ export const CreateWizard: React.FC = ({ 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 ? : + } 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 = ({ 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 = ({ 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 = ({ locale, host, fixedModeSupported 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 = ({ locale, host, fixedModeSupported @@ -602,23 +631,47 @@ export const CreateWizard: React.FC = ({ 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={ - 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 = ({ locale, host, fixedModeSupported { - 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 = ({ locale, host, fixedModeSupported adapter.guid === opts.uplink_guid)?.name} issues={issues} @@ -801,7 +856,7 @@ const Review: React.FC = ({ 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` }, diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 731de2b..8ac3697 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -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 = { 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 = ({ locale, detail, driverID, stats const tzBusy = timezone.tzBusy const pane = useRef(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>(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 = ({ locale, detail, driverID, stats }, [detail.capture_supported, detail.capture]) const set = (patch: Partial) => { - 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) - 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)[field] = (base as unknown as Record)[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 = ({ locale, detail, driverID, stats setIssues([]) setBusy(true) try { - const diff: SetOpts = { name: detail.name } - for (const f of changed) (diff as unknown as Record)[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 = ({ 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 = ({ 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 = ({ locale, detail, driverID, stats 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 = ({ locale, detail, driverID, stats @@ -577,7 +618,11 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats /> tr('targetDisplayHint', { @@ -593,13 +638,41 @@ export const SettingsModal: React.FC = ({ 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: