Files
Reims-Go/frontend/src/lib/format.ts
T
NwflowerandClaude Opus 5.5 31a72892de fix(settings): read display settings back and fold full screen into resolution
- `reims-ctl show` prints several displays as "displays  2, in 2 windows
  ...", which was read as one display, so the panel saw no change when
  the count was set back to 1 and refused to save it.
- The resolution was never read back: the pattern used was anchored to a
  whole value and never matched the display line, so the panel always
  showed 1920x1080.
- The settings panel took its values once on open; it now follows a newer
  VM detail until the person edits something (reopening right after a
  save showed the old values).
- Full screen is now a card among the resolutions instead of a separate
  switch; HiDPI sizes say what they look like, and the advice on getting
  HiDPI sits under the cards.

Checked with macos-tahoe: set to 2 displays at 1680x1050 outside the app,
the panel showed both; picking 1 saved and read back as 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:31:09 -07:00

218 lines
8.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { I18nKey, t } from '../i18n'
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
// Human-readable values for the main view (docs/ui-redesign.md §4.3).
// Raw values stay available under "Technical details".
const MEMORY_CHOICES = [4, 6, 8, 12, 16, 24, 32, 48, 64]
/**
* Largest offered memory size that fits in 60% of physical RAM and in the
* commit memory free now, minus 1 GB for QEMU and 2 GB for the host. Mirrors
* host.RecommendedMemoryGB (internal/host/memory.go).
*/
export function recommendedMemoryGB(host: HostReport): number {
let limit = host.total_ram_gb * 0.6
if (host.commit_avail_gb > 0) limit = Math.min(limit, host.commit_avail_gb - 3)
return MEMORY_CHOICES.reduce((best, m) => (m <= limit ? m : best), MEMORY_CHOICES[0])
}
/** Memory sizes offered as quick picks, in GB. */
export const MEMORY_MARKS = MEMORY_CHOICES
/**
* Largest memory size in GB that still fits the same limits
* recommendedMemoryGB applies; above it the settings slider turns amber.
*/
export function memorySafeLimitGB(host: HostReport): number {
let limit = host.total_ram_gb * 0.6
if (host.commit_avail_gb > 0) limit = Math.min(limit, host.commit_avail_gb - 3)
return Math.max(Math.floor(limit), recommendedMemoryGB(host))
}
/** vCPU count suggested for a new VM; same rule as the create wizard. */
export function recommendedCPUs(host: HostReport): number {
const rec = host.logical_cpus >= 12 ? 8 : 4
return host.logical_cpus > 0 ? Math.min(rec, host.logical_cpus) : rec
}
/** "16G" / "16384M" / "16GiB" → 16. Null when the shape is unknown. */
export function parseMemoryGB(raw: string | undefined): number | null {
const m = /^\s*(\d+(?:\.\d+)?)\s*([KMGT])?(?:i?B)?\s*$/i.exec(raw ?? '')
if (!m) return null
const n = Number(m[1])
const unit = (m[2] ?? 'M').toUpperCase()
return unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
}
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
export function formatMemory(raw: string): string {
const gb = parseMemoryGB(raw)
if (gb === null) return raw
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10
return `${rounded} GB`
}
export function controllerLabel(raw: string): string {
switch ((raw ?? '').toLowerCase()) {
case 'ahci': case 'sata': return 'SATA'
case 'nvme': return 'NVMe'
case 'virtio': return 'VirtIO'
default: return raw ? raw.toUpperCase() : '—'
}
}
function findGPU(host: HostReport, icd: string): GPUInfo | undefined {
const norm = (s: string) => s.replace(/\//g, '\\').toLowerCase()
return (host.gpus ?? []).find((g) => norm(g.vulkan_icd) === norm(icd))
}
/** Drop vendor boilerplate: "NVIDIA GeForce RTX 4070 Ti" → "RTX 4070 Ti". */
export function shortGPUName(name: string): string {
return name
.replace(/^NVIDIA\s+(GeForce\s+)?/i, '')
.replace(/^AMD\s+(Radeon\s+)?(?=RX|Pro)/i, 'Radeon ')
.replace(/^Intel\(R\)\s+/i, 'Intel ')
.trim()
}
/** "1920x1080" → "1080p"; non-16:9 sizes keep "W×H". */
export function resolutionLabel(raw: string): string {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(raw ?? '')
if (!m) return raw
const w = Number(m[1]), h = Number(m[2])
return Math.abs(w / h - 16 / 9) < 0.01 ? `${h}p` : `${w}×${h}`
}
/** A `gpu` value ("auto" or a Vulkan ICD path) as the card's short name, e.g. "RTX 4070 Ti". */
export function gpuLabel(locale: Locale, icd: string | undefined, host: HostReport): string {
if (!icd || icd === 'auto') {
return host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : t(locale, 'gpuAuto')
}
const found = findGPU(host, icd)
return found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
}
export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): string {
if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics')
const gpu = gpuLabel(locale, d.gpu, host)
const res = resolutionLabel(d.resolution)
const screens = d.displays > 1 ? `${d.displays} × ${res}` : res
return res ? `${gpu} · ${screens}` : gpu
}
export function sshCommand(port: number): string {
return `ssh -p ${port} 127.0.0.1`
}
export function formatBytes(bytes: number): string {
if (!bytes || bytes <= 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let v = bytes
let i = 0
while (v >= 1024 && i < units.length - 1) {
v /= 1024
i++
}
const digits = v >= 100 || i === 0 ? 0 : v >= 10 ? 1 : 2
return `${v.toFixed(digits)} ${units[i]}`
}
export function formatUptime(sec: number, locale: Locale): string {
if (!sec || sec <= 0) return '—'
const h = Math.floor(sec / 3600)
const m = Math.floor((sec % 3600) / 60)
const s = sec % 60
if (locale === 'zh-CN') {
if (h > 0) return `${h}小时 ${m}分`
if (m > 0) return `${m}分 ${s}秒`
return `${s}秒`
}
if (h > 0) return `${h}h ${m}m`
if (m > 0) return `${m}m ${s}s`
return `${s}s`
}
// Used only when the host report has no presets: with nothing known about the
// screen, no size can be called HiDPI (internal/host/display.go).
const DEFAULT_DISPLAY_PRESETS: DisplayPreset[] = [
{ resolution: '1920x1080', label: '1920 × 1080', hidpi: false, recommended: true },
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: false },
]
type Tr = (k: I18nKey, v?: Record<string, string | number>) => string
// The resolution row's description: the main display and its scaling.
export function hostDisplayDesc(host: HostReport, tr: Tr): string | undefined {
const d = host.primary_display
if (!d) return undefined
return tr('hostDisplayHint', { w: d.width, h: d.height, scale: d.scale_pct || 100 })
}
// How to get a HiDPI (sharp-text) macOS desktop when no window size gives
// one on this screen; undefined when one does.
export function hostDisplayAdvice(host: HostReport, tr: Tr): string | undefined {
const tip: Record<string, I18nKey> = {
fullscreen: 'hidpiTipFullscreen',
scale: 'hidpiTipScale',
unavailable: 'hidpiTipUnavailable',
}
const key = host.hidpi_advice ? tip[host.hidpi_advice] : undefined
return key ? tr(key) : undefined
}
// "Looks like" size of a HiDPI preset: macOS draws it at half each way.
export function hidpiLooksLike(resolution: string, tr: Tr): string | undefined {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(resolution)
return m ? tr('resLooksLike', { w: Math.round(Number(m[1]) / 2), h: Math.round(Number(m[2]) / 2) }) : undefined
}
export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
if (host.display_presets && host.display_presets.length > 0) {
return host.display_presets
}
return DEFAULT_DISPLAY_PRESETS
}
export function recommendedResolution(host: HostReport): string {
if (host.recommended_resolution) return host.recommended_resolution
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
return rec?.resolution ?? '1920x1080'
}
export interface GuestLangPreset {
value: string
zh: string
en: string
}
export const GUEST_LANG_PRESETS: GuestLangPreset[] = [
{ value: 'zh-Hans:0', zh: '简体中文(美式键盘,推荐)', en: 'Simplified Chinese (US Keyboard)' },
{ value: 'zh-Hans:252', zh: '简体中文(拼音键盘)', en: 'Simplified Chinese (Pinyin)' },
{ value: 'zh-Hant:0', zh: '繁體中文(美式键盘)', en: 'Traditional Chinese (US Keyboard)' },
{ value: 'en-US:0', zh: 'English (US)', en: 'English (US)' },
{ value: 'ja-JP:0', zh: '日本語(美式键盘)', en: 'Japanese (US Keyboard)' },
{ value: 'ko-KR:0', zh: '한국어(美式键盘)', en: 'Korean (US Keyboard)' },
]
export function defaultGuestLang(locale: Locale): string {
return locale === 'en-US' ? 'en-US:0' : 'zh-Hans:0'
}
export function guestLangLabel(locale: Locale, code: string | undefined): string {
if (!code) return defaultGuestLang(locale)
const hit = GUEST_LANG_PRESETS.find((p) => p.value === code)
if (hit) return locale === 'zh-CN' ? hit.zh : hit.en
return code
}
/**
* Split "简体中文(美式键盘,推荐)" / "Simplified Chinese (US Keyboard)" into a
* pop-up label and its grey detail, so the menu reads like macOS.
*/
export function splitLangLabel(value: string, text: string): { value: string; label: string; detail?: string } {
const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text)
return m ? { value, label: m[1], detail: m[2] } : { value, label: text }
}