Merge branch 'main' into feat/runtime-window-fullscreen

This commit is contained in:
千川白浪 committed 2026-11-30 05:08:56 -07:00
commit f4993fa333
25 files changed
+956 -34

No files matched your search

+23 -5
View File
@@ -18,6 +18,8 @@ import {
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
fullscreenDisplayPresets,
FullscreenDisplayPreset,
hidpiLooksLike,
hostDisplayAdvice,
hostDisplayDesc,
@@ -552,17 +554,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
title={tr('resolution')}
disabled={opts.graphics !== 'reims-vgpu'}
reason={tr('gpuSvgaReason')}
desc={[hostDisplayDesc(host, tr), hostDisplayAdvice(host, tr)].filter(Boolean).join(' · ') || undefined}
desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr) : undefined].filter(Boolean).join(' · ') || undefined}
control={
<PopupSelect
id="vm-res"
label={tr('resolution')}
value={opts.resolution}
onChange={(resolution) => set({ resolution })}
options={recommendedDisplayPresets(host).map((p) => ({
options={(opts.borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host)).map((p: FullscreenDisplayPreset) => ({
value: p.resolution,
label: p.label,
detail: [p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean).join(' · ') || undefined,
detail: [
p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '',
p.scaleBadge ?? '',
p.native ? tr('resNativeBadge') : '',
p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean).join(' · ') || undefined,
}))}
/>
}
@@ -613,8 +620,19 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, tasks = [], draft,
/>
<SetRow
title={tr('fullscreenLaunch')}
desc={tr('fullscreenLaunchHint')}
control={<Switch label={tr('fullscreenLaunch')} checked={!!opts.borderless} onChange={(borderless) => set({ borderless })} />}
desc={opts.borderless ? tr('fullscreenDecoupledHint') : tr('fullscreenLaunchHint')}
control={
<Switch
label={tr('fullscreenLaunch')}
checked={!!opts.borderless}
onChange={(borderless) => {
const list = borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host)
const keep = list.some((p) => p.resolution === opts.resolution)
const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution
set(keep ? { borderless } : { borderless, resolution: fallback })
}}
/>
}
/>
<SetRow
title={tr('enableLogs')}
+44 -23
View File
@@ -13,11 +13,14 @@ import {
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
fullscreenDisplayPresets,
FullscreenDisplayPreset,
hidpiLooksLike,
hostDisplayAdvice,
hostDisplayDesc,
recommendedDisplayPresets,
recommendedMemoryGB,
recommendedResolution,
shortGPUName,
sshCommand,
} from '../lib/format'
@@ -73,7 +76,6 @@ const FIELDS = Object.keys(FIELD_CAT) as Field[]
const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
const CUSTOM = '__custom'
const FULLSCREEN = '__fullscreen'
const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i
const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase()
@@ -200,7 +202,9 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
}
const presets = recommendedDisplayPresets(host)
const presetHit = presets.some((p) => same('resolution', p.resolution, form.resolution))
const fsPresets = fullscreenDisplayPresets(host)
const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets
const presetHit = activePresets.some((p) => same('resolution', p.resolution, form.resolution))
const [customRes, setCustomRes] = useState(!presetHit)
const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level))
@@ -211,7 +215,8 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
useEffect(() => {
if (edited.current) return
setForm(base)
setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
const list = base.borderless ? fsPresets : presets
setCustomRes(!list.some((p) => same('resolution', p.resolution, base.resolution)))
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}, [base]) // presets come from host, which base already follows
@@ -224,7 +229,12 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
const dirty = (f: Field) => !same(f, form[f], base[f])
const reset = (f: Field) => () => {
set({ [f]: base[f] } as Partial<SetOpts>)
if (f === 'resolution') setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
if (f === 'resolution' || f === 'borderless') {
const nextBorderless = f === 'borderless' ? base.borderless : form.borderless
const nextRes = f === 'resolution' ? base.resolution : form.resolution
const list = nextBorderless ? fsPresets : presets
setCustomRes(!list.some((p) => same('resolution', p.resolution, nextRes)))
}
if (f === 'log_level') setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
const changed = FIELDS.filter(dirty)
@@ -509,7 +519,18 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
const vgpu = form.graphics !== 'vmware-svga'
const pd = host.primary_display
const hidpiAdvice = hostDisplayAdvice(host, tr)
const resValue = form.borderless ? FULLSCREEN : customRes ? CUSTOM : presets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
const resValue = customRes ? CUSTOM : activePresets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
const toggleBorderless = (borderless: boolean) => {
const targetPresets = borderless ? fsPresets : presets
if (!customRes && !targetPresets.some((p) => same('resolution', p.resolution, form.resolution))) {
const nextRes = borderless
? (pd ? `${pd.width}x${pd.height}` : targetPresets[0]?.resolution ?? form.resolution)
: recommendedResolution(host)
set({ borderless, resolution: nextRes })
return
}
set({ borderless })
}
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} />
@@ -565,11 +586,14 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
/>
</SetGroup>
<SetGroup title={tr('displayGroup')}>
<SetRow
{...rowProps('borderless')}
title={tr('fullscreenLaunch')}
desc={form.borderless ? tr('fullscreenDecoupledHint') : tr('fullscreenLaunchHint')}
control={<Switch label={tr('fullscreenLaunch')} checked={!!form.borderless} onChange={toggleBorderless} />}
/>
<SetRow
{...rowProps('resolution')}
// Full screen is one of the sizes here, so the row also owns borderless.
dirty={dirty('resolution') || dirty('borderless')}
onReset={() => { reset('resolution')(); reset('borderless')() }}
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
title={tr('resolution')}
desc={hostDisplayDesc(host, tr)}
@@ -579,40 +603,37 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
label={tr('resolution')}
value={resValue}
onChange={(v) => {
if (v === FULLSCREEN) { setCustomRes(false); set({ borderless: true }); return }
if (v === CUSTOM) { setCustomRes(true); set({ borderless: false }); return }
if (v === CUSTOM) { setCustomRes(true); return }
setCustomRes(false)
set({ resolution: v, borderless: false })
set({ resolution: v })
}}
options={[
...presets.map((p) => ({
...activePresets.map((p) => ({
value: p.resolution,
title: p.label,
sub: p.hidpi ? hidpiLooksLike(p.resolution, tr) : undefined,
art: resArt(p.resolution),
badges: [p.hidpi ? tr('hidpiPresetBadge') : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean),
badges: [
p.hidpi ? tr('hidpiPresetBadge') : '',
p.scaleBadge ?? '',
p.native ? tr('resNativeBadge') : '',
p.recommended ? tr('recommendedBadge') : '',
].filter(Boolean),
})),
{
value: FULLSCREEN,
title: tr('resFullscreen'),
sub: pd ? `${pd.width} × ${pd.height}` : undefined,
art: pd ? resArt(`${pd.width}x${pd.height}`) : resArt('16x10'),
badges: host.fullscreen_hidpi ? [tr('hidpiPresetBadge')] : [],
},
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> },
]}
/>
{customRes && !form.borderless && (
{customRes && (
<input
className="input mono res-input"
aria-label={tr('resolution')}
placeholder="2560x1600"
placeholder={form.borderless ? '5120x2880' : '2560x1600'}
autoFocus
value={form.resolution ?? ''}
onChange={(e) => set({ resolution: e.target.value })}
/>
)}
{hidpiAdvice && <div className="srow-desc res-advice">{hidpiAdvice}</div>}
{!form.borderless && hidpiAdvice && <div className="srow-desc res-advice">{hidpiAdvice}</div>}
</>
}
/>
@@ -138,6 +138,7 @@ export const settingsZh: Record<string, string> = {
"footerDisk": "磁盘可用 {gb} GB",
"footerMem": "内存 {pct}%",
"footerMemAvail": "可用 {avail} GB",
"fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放",
"fullscreenLaunch": "无边框全屏启动",
"fullscreenLaunchHint": "启动后直接进入无边框全屏",
"gpuAutoOption": "自动(优先独显)",
@@ -263,6 +264,7 @@ export const settingsZh: Record<string, string> = {
"resCustomSub": "宽 × 高",
"resFullscreen": "全屏",
"resInvalid": "格式为 宽x高,例如 2560x1600",
"resNativeBadge": "原生",
"resetAll": "全部还原",
"resetField": "还原为当前值",
"runtimeDelete": "删除运行时",
@@ -453,6 +455,7 @@ export const settingsEn: Record<string, string> = {
"footerDisk": "Disk {gb} GB free",
"footerMem": "Memory {pct}%",
"footerMemAvail": "{avail} GB free",
"fullscreenDecoupledHint": "Fills the monitor; pick native or supersampled HiDPI (e.g. 5120×2880 for 4K 1.5×) below, scaled on the GPU",
"fullscreenLaunch": "Launch borderless fullscreen",
"fullscreenLaunchHint": "Opens macOS in borderless full screen",
"gpuAutoOption": "Automatic (prefers discrete)",
@@ -578,6 +581,7 @@ export const settingsEn: Record<string, string> = {
"resCustomSub": "Width × height",
"resFullscreen": "Full screen",
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
"resNativeBadge": "Native",
"resetAll": "Revert all",
"resetField": "Revert to current value",
"runtimeDelete": "Delete runtime",
+2
View File
@@ -246,6 +246,7 @@ export type I18nKey =
| "footerMemValue"
| "footerRunningVMs"
| "forceStop"
| "fullscreenDecoupledHint"
| "fullscreenLaunch"
| "fullscreenLaunchHint"
| "gpuAuto"
@@ -591,6 +592,7 @@ export type I18nKey =
| "resFullscreen"
| "resInvalid"
| "resLooksLike"
| "resNativeBadge"
| "resetAll"
| "resetField"
| "resizeLogPanel"
+89
View File
@@ -247,6 +247,95 @@ export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
return DEFAULT_DISPLAY_PRESETS
}
export interface FullscreenDisplayPreset extends DisplayPreset {
native?: boolean
scaleBadge?: string
}
/**
* Resolution presets for borderless fullscreen mode, decoupled from the host
* monitor's physical pixels (requires runtime with display-fixed-mode patch
* for non-native sizes). On a 4K screen, 5120x2880 renders 2x HiDPI and
* downscales to 3840x2160 for a crisp 1.5x ("looks like 2560x1440") desktop.
*/
export function fullscreenDisplayPresets(host: HostReport): FullscreenDisplayPreset[] {
const d = host.primary_display
if (!d || d.width <= 0 || d.height <= 0) {
return [
{ resolution: '5120x2880', label: '5120 × 2880', hidpi: true, scaleBadge: '1.5×' },
{ resolution: '3840x2160', label: '3840 × 2160', hidpi: true, native: true, recommended: true },
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
]
}
const w = d.width
const h = d.height
const scalePct = d.scale_pct || 100
const align16 = (n: number) => Math.max(16, Math.floor(n / 16) * 16)
const align2 = (n: number) => Math.max(2, Math.floor(n / 2) * 2)
const out: FullscreenDisplayPreset[] = []
const seen = new Set<string>()
const push = (p: FullscreenDisplayPreset) => {
if (!seen.has(p.resolution)) {
seen.add(p.resolution)
out.push(p)
}
}
// 1.5× HiDPI supersampling for ~4K+ displays (e.g. 3840×2160 -> 5120×2880,
// 3840×2400 -> 5120×3200; macOS renders 2× HiDPI = looks like 2560×1440 / 1600).
if (w >= 3200) {
const sw = align16((w * 4) / 3)
const sh = align2((h * 4) / 3)
if (sw <= 5120 && sh <= 3200 && (sw !== w || sh !== h)) {
push({
resolution: `${sw}x${sh}`,
label: `${sw} × ${sh}`,
hidpi: true,
scaleBadge: '1.5×',
recommended: scalePct >= 125 && scalePct < 175,
})
}
} else if (w >= 1920) {
// Supersampled 2× HiDPI for 1080p / 1440p displays (capped at 5120×3200;
// on 2560×1440, 3840×2160 gives crisp "looks like 1920×1080").
const factor = w <= 1920 ? 2 : 1.5
const sw = Math.min(5120, align16(w * factor))
const sh = Math.min(3200, align2((sw * h) / w))
if (sw >= 3840 && sh >= 2160 && (sw !== w || sh !== h)) {
push({
resolution: `${sw}x${sh}`,
label: `${sw} × ${sh}`,
hidpi: true,
})
}
}
// Native 1:1 monitor resolution (zero-copy blit path).
const nativeRecommended = !out.some((p) => p.recommended)
push({
resolution: `${w}x${h}`,
label: `${w} × ${h}`,
hidpi: !!host.fullscreen_hidpi,
native: true,
recommended: nativeRecommended,
})
// 1× scaled option for 4K+ monitors (e.g. 2560×1440 on 4K = 1.5× logical size without HiDPI).
if (w >= 3840) {
const lw = align16((w * 2) / 3)
const lh = align2((h * 2) / 3)
if (lw >= 1920 && lh >= 1080) {
push({
resolution: `${lw}x${lh}`,
label: `${lw} × ${lh}`,
hidpi: false,
})
}
}
return out
}
export function recommendedResolution(host: HostReport): string {
if (host.recommended_resolution) return host.recommended_resolution
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
+5
View File
@@ -1423,6 +1423,11 @@ func (a *App) StartVM(name string) error {
}
}
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
host.ShouldUseFixedGuestMode(curDetail.Borderless, curDetail.Resolution, rep.PrimaryDisplay) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
a.mu.Lock()
a.transitions[name] = "starting"
delete(a.pendingChanges, name)
+91 -1
View File
@@ -3,13 +3,18 @@ package reims
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
@@ -152,10 +157,95 @@ func (w *captureWriter) String() string {
return w.buf.String()
}
// StartWithCompat starts a VM and automatically recovers once if QEMU aborts
var driverStoreICDPattern = regexp.MustCompile(`^([a-z]:/(?:[^/]+/)*driverstore/filerepository)/([^/]+)_[0-9a-f]{8,}/([^/]+(?:/[^/]+)*)$`)
func parseDriverStoreICD(raw string) []string {
cleaned := path.Clean(strings.ToLower(strings.ReplaceAll(strings.TrimSpace(raw), `\`, "/")))
return driverStoreICDPattern.FindStringSubmatch(cleaned)
}
// ResolveStaleDriverStoreICD matches a stale ICD to the same driver package and
// relative path, provided exactly one physical adapter matches and is usable.
func ResolveStaleDriverStoreICD(oldPath string, gpus []host.GPUInfo) (newPath string, ambiguous bool) {
old := parseDriverStoreICD(oldPath)
if old == nil {
return "", false
}
var matched []host.GPUInfo
for _, gpu := range gpus {
if gpu.Kind == host.GPUVirtual {
continue
}
candidate := parseDriverStoreICD(gpu.VulkanICD)
if candidate != nil && slices.Equal(candidate[1:], old[1:]) {
matched = append(matched, gpu)
}
}
if len(matched) != 1 {
return "", len(matched) > 1
}
gpu := matched[0]
// Warning grades can also come from PCI IDs alone. A Vulkan version
// confirms that the adapter was probed.
if gpu.VulkanVersion == "" || (gpu.Compat != host.GPUCompatSupported && gpu.Compat != host.GPUCompatWarn) {
return "", false
}
return gpu.VulkanICD, false
}
func (c *Client) reconcileStaleGPUICD(ctx context.Context, name string, stderr io.Writer, onNote func(string)) error {
detail, err := c.Show(ctx, name)
if err != nil || detail.Graphics != "reims-vgpu" || detail.State == "running" {
return nil
}
oldPath := strings.TrimSpace(detail.GPU)
if !strings.HasSuffix(strings.ToLower(oldPath), ".json") {
return nil
}
stat := c.statFile
if stat == nil {
stat = os.Stat
}
if _, err := stat(oldPath); !errors.Is(err, os.ErrNotExist) {
return nil
}
probe := c.probeGPUs
if probe == nil {
probe = host.ProbeVulkanGPUs
}
if onNote == nil && stderr != nil {
onNote = func(msg string) { fmt.Fprintln(stderr, msg) }
}
newPath, _ := ResolveStaleDriverStoreICD(oldPath, probe())
if newPath == "" {
msg := i18n.M(c.Locale, "err.gpu_icd_stale", i18n.Vars{"path": oldPath})
if onNote != nil {
onNote(msg)
}
return errors.New(msg)
}
var setErrBuf bytes.Buffer
if err := c.Set(ctx, SetOpts{Name: name, GPU: newPath}, io.Discard, &setErrBuf); err != nil {
if detail := strings.TrimSpace(setErrBuf.String()); detail != "" {
return fmt.Errorf("reims-ctl set %s --gpu: %w (%s)", name, err, detail)
}
return fmt.Errorf("reims-ctl set %s --gpu: %w", name, err)
}
if onNote != nil {
onNote(i18n.M(c.Locale, "compat.gpu_icd_rebound", i18n.Vars{"old": oldPath, "new": newPath}))
}
return nil
}
// StartWithCompat checks the configured Vulkan ICD before starting a VM and
// automatically recovers once if QEMU aborts
// with the WHPX nested-virtualization property error (hr=80370302) by writing
// `-machine kernel-irqchip=off` via `reims-ctl set` (D3) and retrying start.
func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stderr io.Writer, onNote func(string)) error {
if err := c.reconcileStaleGPUICD(ctx, name, stderr, onNote); err != nil {
return err
}
outCap := &captureWriter{dst: stdout}
errCap := &captureWriter{dst: stderr}
err := c.Start(ctx, name, outCap, errCap)
+261
View File
@@ -1,13 +1,274 @@
package reims
import (
"bytes"
"cmp"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"slices"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
const (
fileRepository = "C:/Windows/System32/DriverStore/FileRepository/"
intelOldICD = fileRepository + "iigd_dch.inf_amd64_010a7b33a54cb65d/igvk64.json"
intelNewICD = fileRepository + "iigd_dch.inf_amd64_413e993a06fd9302/igvk64.json"
nvidiaNewICD = fileRepository + "nv_dispig.inf_amd64_b45678ef/Vulkan/nv-vk64.json"
)
func TestResolveStaleDriverStoreICD(t *testing.T) {
intel := host.GPUInfo{Kind: host.GPUIntegrated, VulkanICD: intelNewICD, VulkanVersion: "1.4.0", Compat: host.GPUCompatSupported}
nvidia := host.GPUInfo{Kind: host.GPUDiscrete, VulkanICD: nvidiaNewICD, VulkanVersion: "1.4.0", Compat: host.GPUCompatSupported}
amd := host.GPUInfo{Kind: host.GPUDiscrete, VulkanICD: fileRepository + "u0406575.inf_amd64_9abc5678/amd-vulkan64.json", VulkanVersion: "1.3.0", Compat: host.GPUCompatWarn}
mixed := intel
mixed.VulkanICD = "c:/WINDOWS\\System32/DRIVERSTORE\\FileRepository/IIGD_DCH.INF_AMD64_413E993A06FD9302\\IGVK64.JSON"
secondIntel := intel
secondIntel.VulkanICD = fileRepository + "iigd_dch.inf_amd64_1234567890abcdef/igvk64.json"
unprobed := intel
unprobed.VulkanVersion = ""
unprobed.Compat = host.GPUCompatUnknown
warnUnprobed := amd
warnUnprobed.VulkanVersion = ""
unsupported := intel
unsupported.Compat = host.GPUCompatUnsupported
virtual := intel
virtual.Kind = host.GPUVirtual
differentINF := intel
differentINF.VulkanICD = fileRepository + "iigd_other.inf_amd64_413e993a06fd9302/igvk64.json"
for _, tc := range []struct {
name string
oldPath string
gpus []host.GPUInfo
wantPath string
ambiguous bool
}{
{name: "Intel Arc B390", oldPath: intelOldICD, gpus: []host.GPUInfo{intel}, wantPath: intelNewICD},
{name: "NVIDIA nested manifest", oldPath: fileRepository + "nv_dispig.inf_amd64_a12345cd/Vulkan/nv-vk64.json", gpus: []host.GPUInfo{nvidia}, wantPath: nvidiaNewICD},
{name: "AMD warning grade", oldPath: fileRepository + "u0406575.inf_amd64_1234abcd/amd-vulkan64.json", gpus: []host.GPUInfo{amd}, wantPath: amd.VulkanICD},
{name: "mixed case and separators", oldPath: strings.ReplaceAll(intelOldICD, "/", "\\"), gpus: []host.GPUInfo{mixed}, wantPath: mixed.VulkanICD},
{name: "Intel and NVIDIA", oldPath: intelOldICD, gpus: []host.GPUInfo{nvidia, intel}, wantPath: intelNewICD},
{name: "different vendor", oldPath: intelOldICD, gpus: []host.GPUInfo{nvidia}},
{name: "same vendor multiple adapters", oldPath: intelOldICD, gpus: []host.GPUInfo{intel, secondIntel}, ambiguous: true},
{name: "shared manifest", oldPath: intelOldICD, gpus: []host.GPUInfo{intel, intel}, ambiguous: true},
{name: "unprobed also counts towards ambiguity", oldPath: intelOldICD, gpus: []host.GPUInfo{intel, unprobed}, ambiguous: true},
{name: "only match unprobed", oldPath: intelOldICD, gpus: []host.GPUInfo{unprobed}},
{name: "PCI-based warning without a probe", oldPath: fileRepository + "u0406575.inf_amd64_1234abcd/amd-vulkan64.json", gpus: []host.GPUInfo{warnUnprobed}},
{name: "only match unsupported", oldPath: intelOldICD, gpus: []host.GPUInfo{unsupported}},
{name: "ignore virtual adapter", oldPath: intelOldICD, gpus: []host.GPUInfo{virtual, intel}, wantPath: intelNewICD},
{name: "different INF package", oldPath: intelOldICD, gpus: []host.GPUInfo{differentINF}},
{name: "different repository", oldPath: "D" + intelOldICD[1:], gpus: []host.GPUInfo{intel}},
{name: "different relative path", oldPath: fileRepository + "iigd_dch.inf_amd64_010a7b33a54cb65d/Vulkan/igvk64.json", gpus: []host.GPUInfo{intel}},
{name: "invalid package hash", oldPath: fileRepository + "iigd_dch.inf_amd64_0123456g/igvk64.json", gpus: []host.GPUInfo{intel}},
{name: "short package hash", oldPath: fileRepository + "iigd_dch.inf_amd64_0123456/igvk64.json", gpus: []host.GPUInfo{intel}},
{name: "custom path", oldPath: "C:/custom/igvk64.json", gpus: []host.GPUInfo{intel}},
} {
t.Run(tc.name, func(t *testing.T) {
got, ambiguous := ResolveStaleDriverStoreICD(tc.oldPath, tc.gpus)
if got != tc.wantPath || ambiguous != tc.ambiguous {
t.Fatalf("ResolveStaleDriverStoreICD() = (%q, %v), want (%q, %v)", got, ambiguous, tc.wantPath, tc.ambiguous)
}
})
}
}
func TestStartWithCompatStaleGPUICD(t *testing.T) {
const name = "macOS test"
const newPath = "C:/Windows/System32/DriverStore/FileRepository/iigd_dch.inf_amd64_413e993a06fd9302/ICD manifests/igvk64.json"
const oldPath = "C:/Windows/System32/DriverStore/FileRepository/iigd_dch.inf_amd64_010a7b33a54cb65d/ICD manifests/igvk64.json"
const customPath = "C:/custom/igvk64.JSON"
intel := host.GPUInfo{Kind: host.GPUIntegrated, VulkanICD: newPath, VulkanVersion: "1.4.0", Compat: host.GPUCompatSupported}
show := "show\t" + name
start := "start\t" + name
set := "set\t" + name + "\t--gpu\t" + newPath
rebound := "显卡 Vulkan ICD 路径已从 " + oldPath + " 更新为 " + newPath
stale := "原显卡的 Vulkan ICD 文件已不存在(" + oldPath + ")。在设置 → 图形与显示器中重新选择显卡,或选择自动"
staleCustom := "The selected GPU's Vulkan ICD file no longer exists (" + customPath + "). In Settings → Graphics & displays, reselect the GPU or choose Automatic"
binary, err := os.Executable()
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
gpu string
graphics string
state string
statErr error
gpus []host.GPUInfo
fail string
twice bool
useStderr bool
wantCalls []string
wantStats []string
wantProbe int
wantNote string
wantStale bool
}{
{name: "existing file", gpu: oldPath, wantCalls: []string{show, start}, wantStats: []string{oldPath}},
{name: "auto", gpu: "automatic: the only GPU", wantCalls: []string{show, start}},
{name: "GPU name", gpu: "Intel Arc B390", wantCalls: []string{show, start}},
{name: "SVGA", gpu: oldPath, graphics: "VMware SVGA", wantCalls: []string{show, start}},
{name: "running", gpu: oldPath, state: "running, pid 1234", wantCalls: []string{show, start}},
{name: "show failure", gpu: oldPath, fail: "show", wantCalls: []string{show, start}},
{name: "stat permission denied", gpu: oldPath, statErr: os.ErrPermission, wantCalls: []string{show, start}, wantStats: []string{oldPath}},
{name: "rebind once across two starts", gpu: oldPath, statErr: os.ErrNotExist, gpus: []host.GPUInfo{intel}, twice: true, wantCalls: []string{show, set, start, show, start}, wantStats: []string{oldPath, newPath}, wantProbe: 1, wantNote: rebound},
{name: "rebind note falls back to stderr", gpu: oldPath, statErr: os.ErrNotExist, gpus: []host.GPUInfo{intel}, useStderr: true, wantCalls: []string{show, set, start}, wantStats: []string{oldPath}, wantProbe: 1, wantNote: rebound},
{name: "ambiguous", gpu: oldPath, statErr: os.ErrNotExist, gpus: []host.GPUInfo{intel, intel}, wantCalls: []string{show}, wantStats: []string{oldPath}, wantProbe: 1, wantNote: stale, wantStale: true},
{name: "no match", gpu: oldPath, statErr: os.ErrNotExist, wantCalls: []string{show}, wantStats: []string{oldPath}, wantProbe: 1, wantNote: stale, wantStale: true},
{name: "missing custom JSON", gpu: customPath, statErr: os.ErrNotExist, gpus: []host.GPUInfo{intel}, useStderr: true, wantCalls: []string{show}, wantStats: []string{customPath}, wantProbe: 1, wantNote: staleCustom, wantStale: true},
{name: "set failure", gpu: oldPath, statErr: os.ErrNotExist, gpus: []host.GPUInfo{intel}, fail: "set", wantCalls: []string{show, set}, wantStats: []string{oldPath}, wantProbe: 1},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
gpuFile := filepath.Join(dir, "gpu")
if err := os.WriteFile(gpuFile, []byte(tc.gpu), 0o644); err != nil {
t.Fatal(err)
}
locale := i18n.ZhCN
if tc.gpu == customPath {
locale = i18n.EnUS
}
var statPaths, notes []string
probes := 0
client := Client{
Binary: binary,
Env: append(os.Environ(),
"REIMS_TEST_CTL_DIR="+dir,
"REIMS_TEST_CTL_GRAPHICS="+cmp.Or(tc.graphics, "reims-vgpu"),
"REIMS_TEST_CTL_STATE="+cmp.Or(tc.state, "stopped"),
"REIMS_TEST_CTL_FAIL="+tc.fail,
),
Locale: locale,
statFile: func(path string) (os.FileInfo, error) {
statPaths = append(statPaths, path)
if path == newPath {
return nil, nil
}
if tc.statErr == nil {
return nil, nil
}
return nil, &os.PathError{Op: "stat", Path: path, Err: tc.statErr}
},
probeGPUs: func() []host.GPUInfo {
probes++
return tc.gpus
},
}
var stderr bytes.Buffer
onNote := func(msg string) { notes = append(notes, msg) }
if tc.useStderr {
onNote = nil
}
err := client.StartWithCompat(t.Context(), name, nil, &stderr, onNote)
switch {
case tc.wantStale:
if err == nil || err.Error() != tc.wantNote {
t.Fatalf("start error = %v, want %q", err, tc.wantNote)
}
case tc.fail == "set":
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 7 || !strings.Contains(err.Error(), "reims-ctl set "+name+" --gpu") {
t.Fatalf("start error = %v, want wrapped set exit status 7", err)
}
case err != nil:
t.Fatal(err)
}
if tc.twice {
if err := client.StartWithCompat(t.Context(), name, nil, &stderr, onNote); err != nil {
t.Fatal(err)
}
}
calls, err := os.ReadFile(filepath.Join(dir, "commands"))
if err != nil {
t.Fatal(err)
}
if want := strings.Join(tc.wantCalls, "\n") + "\n"; string(calls) != want {
t.Errorf("reims-ctl commands = %q, want %q", calls, want)
}
if probes != tc.wantProbe || !slices.Equal(statPaths, tc.wantStats) {
t.Errorf("probes = %d, stat paths = %q, want %d and %q", probes, statPaths, tc.wantProbe, tc.wantStats)
}
wantGPU := tc.gpu
if slices.Contains(tc.wantCalls, set) && tc.fail != "set" {
wantGPU = newPath
}
gpu, err := os.ReadFile(gpuFile)
if err != nil || string(gpu) != wantGPU {
t.Errorf("saved GPU = %q, err = %v, want %q", gpu, err, wantGPU)
}
var wantNotes []string
wantStderr := ""
if tc.useStderr {
wantStderr = tc.wantNote + "\n"
} else if tc.wantNote != "" {
wantNotes = []string{tc.wantNote}
}
if !slices.Equal(notes, wantNotes) || stderr.String() != wantStderr {
t.Errorf("notes = %q, stderr = %q, want %q and %q", notes, stderr.String(), wantNotes, wantStderr)
}
})
}
}
func TestMain(m *testing.M) {
if os.Getenv("REIMS_TEST_CTL_DIR") != "" {
// Client.run invokes the test binary with the original ctl arguments.
os.Args = append([]string{os.Args[0], "-test.run=^TestHelperProcess$", "--"}, os.Args[1:]...)
}
os.Exit(m.Run())
}
func TestHelperProcess(t *testing.T) {
dir := os.Getenv("REIMS_TEST_CTL_DIR")
if dir == "" {
return
}
args := os.Args[3:]
if len(args) < 2 {
t.Fatalf("expected ctl command and VM name, got %q", args)
}
log, err := os.OpenFile(filepath.Join(dir, "commands"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
t.Fatal(err)
}
_, writeErr := fmt.Fprintln(log, strings.Join(args, "\t"))
if closeErr := log.Close(); writeErr != nil || closeErr != nil {
t.Fatalf("record ctl call: write %v, close %v", writeErr, closeErr)
}
if args[0] == os.Getenv("REIMS_TEST_CTL_FAIL") {
os.Exit(7)
}
gpuFile := filepath.Join(dir, "gpu")
switch args[0] {
case "show":
gpu, err := os.ReadFile(gpuFile)
if err != nil {
t.Fatal(err)
}
fmt.Printf("%s\n state %s\n graphics %s\n gpu %s\n", args[1], os.Getenv("REIMS_TEST_CTL_STATE"), os.Getenv("REIMS_TEST_CTL_GRAPHICS"), gpu)
case "set":
if len(args) != 4 || args[2] != "--gpu" {
t.Fatalf("expected set <name> --gpu <path>, got %q", args)
}
if err := os.WriteFile(gpuFile, []byte(args[3]), 0o644); err != nil {
t.Fatal(err)
}
case "start":
default:
t.Fatalf("unexpected ctl command %q", args)
}
}
func TestBuildDeleteArgs(t *testing.T) {
got := BuildDeleteArgs("macos-tahoe", false)
want := []string{"delete", "--yes", "macos-tahoe"}
+3
View File
@@ -24,6 +24,9 @@ type Client struct {
Binary string
Env []string
Locale i18n.Locale
probeGPUs func() []host.GPUInfo
statFile func(string) (os.FileInfo, error)
}
func NewClient(cfg *config.Config, installed rt.Installed) *Client {
+20
View File
@@ -173,3 +173,23 @@ func TestParseShowNonDefaultLines(t *testing.T) {
t.Errorf("reims-vgpu / 30 s parsed as %q / %d", d.Graphics, d.StopTimeout)
}
}
func TestFixedDriverStoreICDShowAndSetArgs(t *testing.T) {
for _, path := range []string{
"C:\\Windows\\System32\\DriverStore\\FileRepository\\iigd_dch.inf_amd64_010a7b33a54cb65d\\igvk64.json",
"C:\\Windows\\System32\\DriverStore\\FileRepository\\nv_dispig.inf_amd64_b45678ef\\ICD manifests\\nv-vk64.json",
} {
t.Run(path, func(t *testing.T) {
const name = "m0"
detail := ParseShow(name, name+"\n state stopped\n graphics reims-vgpu\n gpu "+path+"\n")
if detail.GPU != path || detail.Graphics != "reims-vgpu" || detail.State != "stopped" {
t.Fatalf("unexpected VM detail: %+v", detail)
}
args, err := BuildSetArgs(SetOpts{Name: name, GPU: detail.GPU})
want := []string{"set", name, "--gpu", path}
if err != nil || !reflect.DeepEqual(args, want) {
t.Fatalf("BuildSetArgs() = %q, %v, want %q, nil", args, err, want)
}
})
}
}
+57
View File
@@ -188,3 +188,60 @@ func RecommendDisplayPresets(primary *DisplayInfo) ([]DisplayPreset, string) {
out[rec].Recommended = true
return out, out[rec].Resolution
}
// ParseResolution parses "WxH" or "W×H" (ignoring surrounding spaces).
func ParseResolution(raw string) (w, h int, ok bool) {
var x rune
for _, r := range raw {
if r == 'x' || r == 'X' || r == '×' {
x = r
break
}
}
if x == 0 {
return 0, 0, false
}
var rw, rh int
n, err := fmt.Sscanf(raw, "%d"+string(x)+"%d", &rw, &rh)
if err != nil || n != 2 || rw <= 0 || rh <= 0 {
return 0, 0, false
}
return rw, rh, true
}
// ShouldUseFixedGuestMode reports whether reims-vgpu should decouple the
// guest's display mode from the window's physical pixels
// (REIMS_VGPU_WINDOW_FIXED_MODE=1).
//
// - In borderless fullscreen: enabled whenever the configured resolution
// differs from the primary monitor's native pixels (e.g. 5120x2880 HiDPI
// 1.5x supersampled onto a 3840x2160 monitor, or 2560x1440 1x upscaled).
// Matching the native monitor stays on the zero-copy 1:1 path.
// - In windowed mode: enabled when the configured resolution exceeds the
// monitor's usable work area (e.g. 5120x2880 supersampled in a window).
func ShouldUseFixedGuestMode(borderless bool, resolution string, primary *DisplayInfo) bool {
w, h, ok := ParseResolution(resolution)
if !ok {
return false
}
if borderless {
if primary == nil || primary.Width <= 0 || primary.Height <= 0 {
return true
}
return w != primary.Width || h != primary.Height
}
if primary == nil || primary.Width <= 0 || primary.Height <= 0 {
return false
}
scale := primary.ScalePct
if scale <= 0 {
scale = 100
}
usableW, usableH := primary.WorkWidth, primary.WorkHeight
if usableW <= 0 || usableH <= 0 {
usableW = primary.Width
usableH = primary.Height - defaultTaskbarPoints*scale/100
}
usableH -= windowTitleBarPoints * scale / 100
return w > usableW || h > usableH
}
+26
View File
@@ -139,6 +139,32 @@ func TestRecommendDisplayPresets(t *testing.T) {
}
}
func TestShouldUseFixedGuestMode(t *testing.T) {
uhd := &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150, WorkWidth: 3840, WorkHeight: 2088, Primary: true}
cases := []struct {
name string
borderless bool
res string
primary *DisplayInfo
want bool
}{
{"fullscreen 4K 1.5x supersampled", true, "5120x2880", uhd, true},
{"fullscreen 4K native stays 1:1", true, "3840x2160", uhd, false},
{"fullscreen 4K upscaled 1440p", true, "2560x1440", uhd, true},
{"windowed fits monitor", false, "3200x1800", uhd, false},
{"windowed exceeds monitor supersampled", false, "5120x2880", uhd, true},
{"invalid resolution", true, "bad", uhd, false},
{"fullscreen unknown display", true, "5120x2880", nil, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := ShouldUseFixedGuestMode(tc.borderless, tc.res, tc.primary); got != tc.want {
t.Fatalf("ShouldUseFixedGuestMode(%v, %q) = %v, want %v", tc.borderless, tc.res, got, tc.want)
}
})
}
}
func TestInspectDiskUsageQCOW2(t *testing.T) {
tmp := t.TempDir()
qcow := filepath.Join(tmp, "disk.qcow2")
+5
View File
@@ -29,6 +29,11 @@ func Inspect(dataRoot string) Report {
}
}
// ProbeVulkanGPUs returns no adapters on hosts without Windows Vulkan probing.
func ProbeVulkanGPUs() []GPUInfo {
return nil
}
func PinProcessToPCores(pid uint32, mask uint64) error {
return SetProcessAffinityMask(pid, mask)
}
+5
View File
@@ -543,6 +543,11 @@ func isUSBBusVolume(vol string) bool {
return busType == 7
}
// ProbeVulkanGPUs returns the current Vulkan adapters without using Inspect's cache.
func ProbeVulkanGPUs() []GPUInfo {
return probeVulkanGPUs()
}
func probeVulkanGPUs() []GPUInfo {
const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`
var regGPUs []GPUInfo
+6
View File
@@ -60,6 +60,7 @@ var catalog = map[Locale]map[string]string{
"close": "关闭",
"closeWindow": "关闭",
"collapseLogs": "收起日志",
"compat.gpu_icd_rebound": "显卡 Vulkan ICD 路径已从 {old} 更新为 {new}",
"copy": "复制",
"copyTechInfo": "复制技术信息",
"core.preflight.whpx_irqchip_advice": "宿主不支持 nested-virt 属性且当前运行时未包含非致命降级补丁,启动虚拟机时将自动附加 kernel-irqchip=off",
@@ -119,6 +120,7 @@ var catalog = map[Locale]map[string]string{
"err.fullscreen_failed": "无法切换 {name} 的全屏状态",
"err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏",
"err.gpu_device_lost": "宿主显卡 Vulkan 设备丢失(ERROR_DEVICE_LOST)。请更新显卡驱动;若为 AMD Vega/Polaris 等受影响显卡,请改用其他独显或在设置中将虚拟显卡切为 VMware SVGA",
"err.gpu_icd_stale": "原显卡的 Vulkan ICD 文件已不存在({path})。在设置 → 图形与显示器中重新选择显卡,或选择自动",
"err.gpu_vulkan_floor": "宿主显卡不满足 Reims vGPU 的 Vulkan 1.3 硬件要求。请更新显卡驱动,或在设置中将虚拟显卡切为 VMware SVGA(软件渲染)",
"err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠",
"err.plugin.high_risk_unapproved": "插件「{id}」包含高危权限,需要先确认授权后才能启用",
@@ -570,6 +572,7 @@ var catalog = map[Locale]map[string]string{
"close": "Close",
"closeWindow": "Close",
"collapseLogs": "Hide logs",
"compat.gpu_icd_rebound": "Updated the GPU Vulkan ICD path from {old} to {new}",
"copy": "Copy",
"copyTechInfo": "Copy technical details",
"core.preflight.whpx_irqchip_advice": "Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied",
@@ -629,6 +632,7 @@ var catalog = map[Locale]map[string]string{
"err.fullscreen_failed": "Couldn’t toggle full screen for {name}",
"err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen",
"err.gpu_device_lost": "Host Vulkan GPU device lost (ERROR_DEVICE_LOST). Update GPU drivers; on affected AMD Vega/Polaris GPUs, switch to another discrete GPU or use VMware SVGA in VM Settings",
"err.gpu_icd_stale": "The selected GPU's Vulkan ICD file no longer exists ({path}). In Settings → Graphics & displays, reselect the GPU or choose Automatic",
"err.gpu_vulkan_floor": "Host GPU does not meet Reims vGPU's Vulkan 1.3 requirements. Update GPU drivers or switch graphics to VMware SVGA (software rendering) in VM Settings",
"err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake",
"err.plugin.high_risk_unapproved": "Plugin “{id}” requests high-risk permissions and requires confirmation before enabling",
@@ -1042,6 +1046,7 @@ var paramOrder = map[string][]string{
"cli.start.running_in_tray": {"name"},
"cli.start.spawning_tray": {"name"},
"cli.start.timeout": {"name", "timeout"},
"compat.gpu_icd_rebound": {"old", "new"},
"core.start.warn.offline_helper_skipped": {"err"},
"core.start.warn.opencore_lang_failed": {"err"},
"core.start.warn.opencore_picker_failed": {"err"},
@@ -1063,6 +1068,7 @@ var paramOrder = map[string][]string{
"err.commit_memory": {"need", "avail", "rec"},
"err.fullscreen_failed": {"name"},
"err.fullscreen_vmware_svga": {"name"},
"err.gpu_icd_stale": {"path"},
"err.plugin.high_risk_unapproved": {"id"},
"err.plugin.in_use": {"id", "reason"},
"err.plugin.system_locked": {"id"},
+6 -5
View File
@@ -42,11 +42,12 @@ var BuiltinOnlyQEMUOptionFamilies = map[string]bool{
// AllowedHostEnvVars lists non-namespaced environment variables permitted in
// builtin/plugin StartIntents (§4.4).
var AllowedHostEnvVars = map[string]bool{
"REIMS_GO_INPUT_URL": true,
"REIMS_GO_INPUT_TOKEN": true,
"REIMS_VGPU_LOG": true,
"VK_ICD_FILENAMES": true,
"SDL_VIDEODRIVER": true,
"REIMS_GO_INPUT_URL": true,
"REIMS_GO_INPUT_TOKEN": true,
"REIMS_VGPU_LOG": true,
"REIMS_VGPU_WINDOW_FIXED_MODE": true,
"VK_ICD_FILENAMES": true,
"SDL_VIDEODRIVER": true,
}
// ArgFragment is one QEMU argument group contributed by a plugin.
+2
View File
@@ -167,6 +167,8 @@ func (m Manifest) EffectiveCapabilities() []string {
if sha := strings.TrimSpace(p.SHA256); sha != "" && !strings.EqualFold(sha, buggyWin32UnicodeInputPatchSHA256) {
add("win32-unicode-input")
}
case strings.Contains(low, "display-fixed-mode"):
add("display-fixed-mode")
}
}
return out
+4
View File
@@ -39,6 +39,10 @@ func TestKindRegistryAndCapabilities(t *testing.T) {
if !m.HasCapability("nested-virt-nonfatal") || !m.HasCapability("win10-startup-ipis") {
t.Fatalf("expected inferred capabilities, got %v", m.EffectiveCapabilities())
}
fixedModeM := Manifest{Patches: []Patch{{Name: "reims-vgpu-display-fixed-mode.patch"}}}
if !fixedModeM.HasCapability("display-fixed-mode") {
t.Fatalf("expected display-fixed-mode capability, got %v", fixedModeM.EffectiveCapabilities())
}
// Buggy p2/p3 win32-unicode-input patch hash (issue #14) and empty hash must
// not advertise the win32-unicode-input capability; fixed patch hashes and
+13
View File
@@ -67,6 +67,19 @@
"doctor.gpu.err.vulkan_cpu": "Software Vulkan implementation does not meet the vGPU floor; use VMware SVGA instead",
"err.gpu_device_lost": "Host Vulkan GPU device lost (ERROR_DEVICE_LOST). Update GPU drivers; on affected AMD Vega/Polaris GPUs, switch to another discrete GPU or use VMware SVGA in VM Settings",
"err.gpu_vulkan_floor": "Host GPU does not meet Reims vGPU's Vulkan 1.3 requirements. Update GPU drivers or switch graphics to VMware SVGA (software rendering) in VM Settings",
"compat.gpu_icd_rebound": {
"message": "Updated the GPU Vulkan ICD path from {old} to {new}",
"$params": [
"old",
"new"
]
},
"err.gpu_icd_stale": {
"message": "The selected GPU's Vulkan ICD file no longer exists ({path}). In Settings → Graphics & displays, reselect the GPU or choose Automatic",
"$params": [
"path"
]
},
"doctor.runtime": "Portable Runtime",
"doctor.runtime.none": "Not installed (run `reims-go runtime install <archive>`)",
"doctor.runtime.active": {
+2
View File
@@ -180,6 +180,7 @@
"resCustom": "Custom",
"resCustomSub": "Width × height",
"resFullscreen": "Full screen",
"resNativeBadge": "Native",
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
"driveShareTitle": "Windows drive sharing",
"driveShareMaster": "Share Windows drives",
@@ -287,6 +288,7 @@
"recommendedBadge": "Recommended",
"fullscreenLaunch": "Launch borderless fullscreen",
"fullscreenLaunchHint": "Opens macOS in borderless full screen",
"fullscreenDecoupledHint": "Fills the monitor; pick native or supersampled HiDPI (e.g. 5120×2880 for 4K 1.5×) below, scaled on the GPU",
"guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately",
"guestLangHint": "Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable",
"guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window",
+13
View File
@@ -67,6 +67,19 @@
"doctor.gpu.err.vulkan_cpu": "软件渲染 Vulkan 实现不满足 vGPU 硬件加速要求,请改用 VMware SVGA",
"err.gpu_device_lost": "宿主显卡 Vulkan 设备丢失(ERROR_DEVICE_LOST)。请更新显卡驱动;若为 AMD Vega/Polaris 等受影响显卡,请改用其他独显或在设置中将虚拟显卡切为 VMware SVGA",
"err.gpu_vulkan_floor": "宿主显卡不满足 Reims vGPU 的 Vulkan 1.3 硬件要求。请更新显卡驱动,或在设置中将虚拟显卡切为 VMware SVGA(软件渲染)",
"compat.gpu_icd_rebound": {
"message": "显卡 Vulkan ICD 路径已从 {old} 更新为 {new}",
"$params": [
"old",
"new"
]
},
"err.gpu_icd_stale": {
"message": "原显卡的 Vulkan ICD 文件已不存在({path})。在设置 → 图形与显示器中重新选择显卡,或选择自动",
"$params": [
"path"
]
},
"doctor.runtime": "便携运行时",
"doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)",
"doctor.runtime.active": {
+2
View File
@@ -180,6 +180,7 @@
"resCustom": "自定义",
"resCustomSub": "宽 × 高",
"resFullscreen": "全屏",
"resNativeBadge": "原生",
"resInvalid": "格式为 宽x高,例如 2560x1600",
"driveShareTitle": "Windows 盘符共享",
"driveShareMaster": "共享 Windows 盘符",
@@ -287,6 +288,7 @@
"recommendedBadge": "推荐",
"fullscreenLaunch": "无边框全屏启动",
"fullscreenLaunchHint": "启动后直接进入无边框全屏",
"fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放",
"guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效",
"guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错",
"guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言",
+7
View File
@@ -19,6 +19,7 @@
| :--- | :--- | :--- | :--- |
| [`reims-vgpu-cargo-lock.patch`](reims-vgpu-cargo-lock.patch) | `reims-vgpu` (`Cargo.lock`) | 补齐 `metal2vulkan` 三个 crate 的 `source` 锁定信息,使源码包与实际 Cargo 构建逐字节一致 | 仅用于构建可复现;上游补齐 `Cargo.lock` 后删除 |
| [`reims-vgpu-win32-unicode-input.patch`](reims-vgpu-win32-unicode-input.patch) | `reims-vgpu` (`crates/reims-vgpu-window`) | 通过 `SDL_SetWindowsMessageHook` 在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时转发非物理按键的 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`,解决 Windows IME 与中文输入被吞 | 待编入 `alpha` 冒烟验证后提 PR |
| [`reims-vgpu-display-fixed-mode.patch`](reims-vgpu-display-fixed-mode.patch) | `reims-vgpu` (`crates/reims-vgpu-window`, `crates/reims-vgpu`) | 新增 `REIMS_VGPU_WINDOW_FIXED_MODE=1` 将全屏/窗口物理尺寸与客体渲染分辨率解耦,按 `scale * (guest_w / drawable_w)` 推导有效 DPI,并在帧尺寸与目标区域不一致时自动走线性采样 GPU 着色器缩放(支持 4K 全屏 1.5× 超采样 `5120×2880` HiDPI) | `git apply --check` 在 `3731afd9` 通过;待编入 `alpha` 真机验证后提 PR |
| [`reims-ctl-win32-random-bytes.patch`](reims-ctl-win32-random-bytes.patch) | `reims-vgpu` (`crates/reims-ctl/src/vm.rs`) | 修复 Windows 下打不开 `/dev/urandom` 时回退到低熵时间戳种子的缺陷,改用标准库 `RandomState`(底层调用 `ProcessPrng`)生成 MAC/ROM 随机字节 | `git apply --check` 通过;待编入 `alpha` 验证后提 PR |
| [`reims-ctl-virtio-discard-iothread.patch`](reims-ctl-virtio-discard-iothread.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 为 VirtIO 系统盘补齐 `discard=unmap`(与 NVMe 一致透传客体 TRIM)并启用独立 `-object iothread,id=io0`,避免块完成回调与 QEMU 主循环争抢 | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;真机实测与休眠唤醒通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR |
| [`reims-ctl-qcow2-l2-cache.patch`](reims-ctl-qcow2-l2-cache.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 按 `qcow2` 文件头虚拟容量与簇大小计算全覆盖所需 `l2-cache-size`(上限 32 MiB,仅大于 8 MiB 默认值时追加),避免非 Linux 宿主默认 8 MiB 上限仅覆盖 64 GiB | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;128 GiB 镜像真机实测通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR |
@@ -36,6 +37,12 @@
- **根因**:SDL3 窗口层未启用文本输入且仅转发 `0x04..=0xE7` 物理扫描码,扫描码为 0 的 `VK_PACKET` 及 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`(宿主机 IME、中文、语音与远程输入)全部被丢弃。
- **最小修复**:仅在检测到 `REIMS_GO_INPUT_URL`(限定回环地址)时挂接 `SDL_SetWindowsMessageHook` 异步转发非物理字符;对 `WM_CHAR` 按 `lParam` 硬件扫描码(`scan_code == 0`)过滤(不比对 `msg.time`,避免 `TranslateMessage` 写入当前 `GetTickCount()` 导致物理按键被二次转发),对物理键码路径零影响。
### 1b. `reims-vgpu-display-fixed-mode.patch`
- **目标**:`steelbrain/reims-vgpu`(`crates/reims-vgpu-window/src/env.rs`、`crates/reims-vgpu/src/graphics.rs`、`crates/reims-vgpu/src/graphics/sink.rs`)
- **根因**:上游 `WindowScreen::mode()` 始终以窗口/全屏物理像素作为唯一客体显示模式,`encode_shown` 对 `BGRA8` 表面默认走 1:1 blit 拷贝不缩放;在 4K 全屏下 macOS 仅提供 1×(3840×2160)和 2× HiDPI(1920×1080),无法渲染 1.5× 超采样(`5120×2880` 2× HiDPI 下采样至 4K,看起来像 `2560×1440`)。
- **最小修复**:新增可选环境变量 `REIMS_VGPU_WINDOW_FIXED_MODE=1`(默认关闭,对上游默认路径零影响),启用时 `WindowScreen::mode()` 保持上报配置分辨率并按 `host_scale * (guest_w / drawable_w)` 计算 `scale_120ths`;在 `sink.rs` 中当帧尺寸与绘制区域不一致时自动切换至已有的线性采样 `displayPresentFragment` GPU 着色器(含启动/恢复阶段原始 scanout 的暂存纹理缩放)。
- **实测状态**:已在 `3731afd9` 通过 `git apply --check`,待编入 `alpha` 运行时真机验证。
### 2. `reims-ctl-win32-random-bytes.patch`
- **目标**:`steelbrain/reims-vgpu`(`crates/reims-ctl/src/vm.rs:849-864`)
- **根因**:`random_bytes()` 在 `/dev/urandom` 不可用时退回 `纳秒时间 ^ (pid << 64)`。Windows 始终走此分支,导致新 VM 的 MAC 后 3 字节(OpenCore ROM)熵值极低且可预测。
+265
View File
@@ -0,0 +1,265 @@
diff --git a/crates/reims-vgpu-window/src/env.rs b/crates/reims-vgpu-window/src/env.rs
index e73d36f..9e67173 100644
--- a/crates/reims-vgpu-window/src/env.rs
+++ b/crates/reims-vgpu-window/src/env.rs
@@ -14,6 +14,10 @@
//! no window ever captures the keyboard or the pointer ([`crate::capture`]). `1`, `true`,
//! `yes` or `on` turns it on. Default: [`CAPTURE_DEFAULT`]. reims-ctl sets it from a VM's
//! settings.
+//! - `REIMS_VGPU_WINDOW_FIXED_MODE`: `1`, `true`, `yes` or `on`, in any case, decouples the
+//! guest's display mode from the window's pixel size so the display keeps offering the
+//! configured resolution (e.g. 5120x2880 HiDPI supersampled into a 4K borderless window) and
+//! scales the frame on the GPU. Default: off.
use std::sync::OnceLock;
@@ -25,6 +29,8 @@ pub const SCREENS_VAR: &str = "REIMS_VGPU_WINDOW_SCREENS";
pub const IMPL_VAR: &str = "REIMS_VGPU_WINDOW_IMPL";
/// The capture switch's variable.
pub const CAPTURE_VAR: &str = "REIMS_VGPU_WINDOW_CAPTURE";
+/// The fixed guest mode switch's variable.
+pub const FIXED_MODE_VAR: &str = "REIMS_VGPU_WINDOW_FIXED_MODE";
/// Whether a click into the image captures input where the capture switch is unset.
pub const CAPTURE_DEFAULT: bool = true;
@@ -40,6 +46,8 @@ pub struct Settings {
pub window_impl: WindowImpl,
/// Whether a click into the image captures input; off, nothing ever does.
pub capture: bool,
+ /// Keep offering the configured guest resolution instead of following the window's pixels.
+ pub fixed_mode: bool,
}
impl Default for Settings {
@@ -49,6 +57,7 @@ impl Default for Settings {
screens: Vec::new(),
window_impl: WindowImpl::AppKit,
capture: CAPTURE_DEFAULT,
+ fixed_mode: false,
}
}
}
@@ -116,6 +125,11 @@ fn parse_screens(value: &str) -> Option<Vec<usize>> {
.collect()
}
+/// Whether fixed guest mode is on (`1`, `true`, `yes` or `on`, in any case); default off.
+pub fn parse_fixed_mode(value: Option<&str>) -> bool {
+ value.is_some_and(parse_switch)
+}
+
/// The process's settings, read from its environment the first time they are asked for. A
/// value that is not UTF-8 counts as unset.
pub fn settings() -> &'static Settings {
@@ -126,6 +140,7 @@ pub fn settings() -> &'static Settings {
Settings {
window_impl: parse_impl(var(IMPL_VAR).as_deref()),
capture: parse_capture(var(CAPTURE_VAR).as_deref()),
+ fixed_mode: parse_fixed_mode(var(FIXED_MODE_VAR).as_deref()),
..parse(borderless.as_deref(), screens.as_deref())
}
})
diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs
index 9ce42b2..8cac38c 100644
--- a/crates/reims-vgpu/src/graphics.rs
+++ b/crates/reims-vgpu/src/graphics.rs
@@ -5321,19 +5321,35 @@ impl Screen for WindowScreen {
/// draw).
fn mode(&self) -> Mode {
let drawn = *self.shown.drawable.lock();
- let (width, height) = geometry::offered_mode(drawn.map_or_else(
- || {
- let (w, h) = self.window.offered().unwrap_or((1920, 1080));
- (u64::from(w), u64::from(h))
- },
- |d| d.pixels,
- ));
+ let fixed = reims_vgpu_window::env::settings().fixed_mode;
+ let offered = self
+ .window
+ .offered()
+ .map(|(w, h)| (u64::from(w), u64::from(h)));
+ let raw = if fixed {
+ offered
+ .or_else(|| drawn.map(|d| d.pixels))
+ .unwrap_or((1920, 1080))
+ } else {
+ drawn.map_or_else(|| offered.unwrap_or((1920, 1080)), |d| d.pixels)
+ };
+ let (width, height) = geometry::offered_mode(raw);
let clamp = |v: u64| u32::try_from(v.max(1)).unwrap_or(u32::MAX);
+ let clamped_w = clamp(width);
+ let clamped_h = clamp(height);
+ let scale_120ths = drawn.map_or(0, |d| {
+ let eff = if fixed && d.pixels.0 > 0 {
+ d.scale * (f64::from(clamped_w) / f64::from(clamp(d.pixels.0)))
+ } else {
+ d.scale
+ };
+ scale_in_120ths(eff)
+ });
Mode {
- width: clamp(width),
- height: clamp(height),
+ width: clamped_w,
+ height: clamped_h,
refresh_mhz: self.refresh_mhz,
- scale_120ths: drawn.map_or(0, |d| scale_in_120ths(d.scale)),
+ scale_120ths,
}
}
diff --git a/crates/reims-vgpu/src/graphics/sink.rs b/crates/reims-vgpu/src/graphics/sink.rs
index 9dd3e90..5e9994b 100644
--- a/crates/reims-vgpu/src/graphics/sink.rs
+++ b/crates/reims-vgpu/src/graphics/sink.rs
@@ -239,6 +239,8 @@ pub(crate) struct ScanoutDraw<P: Platform> {
ramps: Mutex<Vec<(u64, P::Texture)>>,
/// The scanout's ramp, made at its first use; `None` inside where the platform refused it.
scanout_ramp: Kept<ScanoutRead<P>>,
+ /// Staging texture used to GPU-scale a raw scanout whose size differs from the window's image.
+ scanout_stage: Mutex<Option<P::Texture>>,
/// What draws the guest's cursor where the window draws it (`cursor`): its pipelines and its
/// glyph's texture, made at their first use.
cursor: Mutex<CursorPass<P>>,
@@ -568,6 +570,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
color_table: Mutex::new(None),
ramps: Mutex::default(),
scanout_ramp: Kept::new(),
+ scanout_stage: Mutex::new(None),
cursor: Mutex::new(CursorPass::cursor()),
overlay: Mutex::new(CursorPass::overlay()),
#[cfg(test)]
@@ -607,6 +610,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
*self.color_table.lock() = None;
self.ramps.lock().clear();
self.scanout_ramp.forget();
+ *self.scanout_stage.lock() = None;
*self.cursor.lock() = CursorPass::cursor();
*self.overlay.lock() = CursorPass::overlay();
}
@@ -900,7 +904,8 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
if let Some((surface, view, hold)) = self.presented.shown() {
let (from, to) = (surface.pixel_format(), texture.pixel_format());
self.presented.seen_format(from, to);
- let copied = BGRA8_FORMATS.contains(&from) && BGRA8_FORMATS.contains(&to);
+ let same_size = surface.width() == region.width && surface.height() == region.height;
+ let copied = same_size && BGRA8_FORMATS.contains(&from) && BGRA8_FORMATS.contains(&to);
let drawn = if color.is_none() && copied {
self.encode_surface(&surface, texture, region)
} else {
@@ -1463,6 +1468,15 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
fn encode_scanout(&self, texture: &P::Texture, region: PixelRect) -> Option<P::CommandBuffer> {
let scanout = (*self.shown.scanout.lock())?;
let (buffer, source_offset) = self.scanout_buffer(&scanout)?;
+ let (sw, sh) = (u64::from(scanout.width), u64::from(scanout.height));
+ if sw > 0
+ && sh > 0
+ && (sw != region.width || sh != region.height)
+ && let Some(cb) =
+ self.encode_scanout_scaled(&scanout, &buffer, source_offset, texture, region)
+ {
+ return Some(cb);
+ }
let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?;
let (texture_width, texture_height) = (texture.width(), texture.height());
let x = region.x.min(texture_width);
@@ -1569,6 +1583,62 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
})
}
+ /// Stages `scanout` into a `BGRA8Unorm` texture and scales it into `texture` at `region` via
+ /// the linear-filtered display present shader (used when guest mode != window pixels, e.g.
+ /// `REIMS_VGPU_WINDOW_FIXED_MODE=1` during boot/Recovery).
+ fn encode_scanout_scaled(
+ &self,
+ scanout: &Scanout,
+ buffer: &P::Buffer,
+ source_offset: u64,
+ texture: &P::Texture,
+ region: PixelRect,
+ ) -> Option<P::CommandBuffer> {
+ let (sw, sh) = (u64::from(scanout.width), u64::from(scanout.height));
+ let stage = {
+ let mut slot = self.scanout_stage.lock();
+ let reuse = slot
+ .as_ref()
+ .is_some_and(|t| t.width() == sw && t.height() == sh);
+ if !reuse {
+ let desc = self.platform.texture_descriptor(&TextureDesc {
+ pixel_format: 80,
+ width: sw,
+ height: sh,
+ usage: RAMP_USAGE,
+ resource_options: Some(PRIVATE),
+ ..TextureDesc::default()
+ });
+ let made = no_catch(self.device.new_texture(OnFault::Die, &desc))?;
+ *slot = Some(made);
+ }
+ slot.as_ref()?.clone_ref()
+ };
+ let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?;
+ let blit = Open::new(
+ no_catch(command_buffer.blit_encoder(OnFault::Die))?,
+ end_blit::<P>,
+ );
+ let stride = u64::from(scanout.stride);
+ no_catch(blit.get().encode(
+ OnFault::Die,
+ BlitCmd::CopyBufferToTexture {
+ source_buffer: buffer,
+ source_offset,
+ source_bytes_per_row: stride,
+ source_bytes_per_image: stride * sh,
+ source_size: MtlSize::new(sw, sh, 1),
+ destination_texture: &stage,
+ destination_slice: 0,
+ destination_level: 0,
+ destination_origin: MtlOrigin::new(0, 0, 0),
+ },
+ ));
+ blit.end();
+ self.encode_converted_into(&command_buffer, &stage, texture, region)?;
+ Some(command_buffer)
+ }
+
/// A command buffer of the sink's queue with the presented `surface` drawn into `texture` at
/// `region` by the display's present shaders, which convert its format to the drawable's,
/// after a clear of the drawable to black where `region` does not cover it ([`pass_load`]);
@@ -1580,12 +1650,25 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
texture: &P::Texture,
region: PixelRect,
) -> Option<P::CommandBuffer> {
+ let command_buffer = self.surface_command_buffer()?;
+ self.encode_converted_into(&command_buffer, surface, texture, region)?;
+ Some(command_buffer)
+ }
+
+ /// Encodes the linear-filtered display present shader drawing `surface` into `texture` at
+ /// `region` on `command_buffer`.
+ fn encode_converted_into(
+ &self,
+ command_buffer: &P::CommandBuffer,
+ surface: &P::Texture,
+ texture: &P::Texture,
+ region: PixelRect,
+ ) -> Option<()> {
let converter = self.converter()?;
let pipeline = converter.pipelines.pipeline_for(PipelineKey {
format: texture.pixel_format(),
gamma: false,
})?;
- let command_buffer = self.surface_command_buffer()?;
let (texture_width, texture_height) = (texture.width(), texture.height());
let x = region.x.min(texture_width);
let y = region.y.min(texture_height);
@@ -1657,7 +1740,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
}
}
encoder.end();
- Some(command_buffer)
+ Some(())
}
/// Clears all of `texture` to opaque black, in a render pass of `command_buffer` with no
+1
View File
@@ -5,6 +5,7 @@
# scripts/pack-runtime.ps1 both read this file; add or retire patches here.
reims-vgpu reims-vgpu-cargo-lock.patch
reims-vgpu reims-vgpu-win32-unicode-input.patch
reims-vgpu reims-vgpu-display-fixed-mode.patch
reims-vgpu reims-ctl-win32-random-bytes.patch
reims-vgpu reims-ctl-virtio-discard-iothread.patch
reims-vgpu reims-ctl-qcow2-l2-cache.patch