diff --git a/frontend/src/i18n/domains/plugins.gen.ts b/frontend/src/i18n/domains/plugins.gen.ts index 0bec700..4cd5847 100644 --- a/frontend/src/i18n/domains/plugins.gen.ts +++ b/frontend/src/i18n/domains/plugins.gen.ts @@ -14,7 +14,6 @@ export const pluginsZh: Record = { "pluginBuiltinSection": "内置插件", "pluginClearSecret": "清除", "pluginColorSchemes": "配色方案", - "pluginColorSchemesHint": "修改种子色派生整套界面色阶", "pluginDeleteScheme": "删除方案", "pluginDisable": "停用", "pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件和挂起状态都会保留,重新启用即可恢复。运行中的虚拟机需要先停止或挂起。", @@ -70,7 +69,6 @@ export const pluginsZh: Record = { "pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签", "pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引", "pluginMarketSyncing": "正在同步插件市场", - "pluginMarketUpdate": "更新至 v{version}", "pluginMarketUpdateShort": "更新", "pluginMarketVersionTip": "已安装 v{installed},可更新至 v{version}", "pluginMarketWithdrawn": "已撤回", @@ -98,7 +96,6 @@ export const pluginsZh: Record = { "pluginScanHardSection": "硬性拦截项(禁止安装)", "pluginScanInspect": "安全扫描", "pluginScanInstallConfirm": "确认导入安装", - "pluginScanLoading": "正在扫描插件包…", "pluginScanModalTitle": "插件静态安全报告", "pluginScanMoreItems": "另有 {count} 项已折叠", "pluginSchemeDefault": "默认", @@ -139,7 +136,6 @@ export const pluginsEn: Record = { "pluginBuiltinSection": "Built-in plugins", "pluginClearSecret": "Clear", "pluginColorSchemes": "Color schemes", - "pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp", "pluginDeleteScheme": "Delete scheme", "pluginDisable": "Disable", "pluginDisableInUseBody": "Its VMs will show as “Driver unavailable” and can’t be started or changed. Their files and any suspended state are kept; turning the plugin back on restores them. Stop or suspend any running VM first.", @@ -195,7 +191,6 @@ export const pluginsEn: Record = { "pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags", "pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data", "pluginMarketSyncing": "Syncing the plugin market", - "pluginMarketUpdate": "Update to v{version}", "pluginMarketUpdateShort": "Update", "pluginMarketVersionTip": "v{installed} installed, v{version} available", "pluginMarketWithdrawn": "Withdrawn", @@ -223,7 +218,6 @@ export const pluginsEn: Record = { "pluginScanHardSection": "Hard blockers (install refused)", "pluginScanInspect": "Security scan", "pluginScanInstallConfirm": "Proceed with install", - "pluginScanLoading": "Scanning plugin package…", "pluginScanModalTitle": "Plugin security report", "pluginScanMoreItems": "...and {count} more", "pluginSchemeDefault": "Default", diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 02e3482..aca3c0a 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -59,7 +59,6 @@ export const settingsZh: Record = { "affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})", "affinityTitle": "处理器核心", "appCheckUpdate": "检查更新", - "appDownloadUpdate": "前往下载", "appUpToDate": "已是最新", "appUpdateAvailable": "发现新版本 {v}(稳定版)", "appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)", @@ -169,11 +168,9 @@ export const settingsZh: Record = { "effectNextStart": "下次启动生效", "enableAudio": "音频", "enableLogs": "记录图形与串口日志", - "enableNetwork": "网络(NAT)", "enableWHPX": "启用", "extraArgs": "额外 QEMU 参数", "extraArgsDesc": "原样追加到 QEMU 命令行", - "failAffinity": "设置处理器相关性失败", "folderShareAdd": "添加目录…", "folderShareAddTitle": "宿主机目录", "folderShareConfirmRWAction": "改为读写", @@ -199,9 +196,6 @@ export const settingsZh: Record = { "folderShareRemove": "移除目录", "folderShareTitle": "自定义共享目录", "folderShareWritableWarn": "读写模式:macOS 中的修改和删除会直接作用于宿主机原目录", - "footerDisk": "磁盘可用 {gb} GB", - "footerMem": "内存 {pct}%", - "footerMemAvail": "可用 {avail} GB", "forceQuitAppButton": "强制退出", "forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。", "forceQuitAppTitle": "强制退出 Reims-Go", @@ -247,7 +241,6 @@ export const settingsZh: Record = { "groupMacOS": "macOS", "groupPerformance": "性能", "groupQemu": "QEMU", - "gtInstallCmd": "安装命令", "guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错", "guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言", "guestLangShort": "系统语言", @@ -279,9 +272,6 @@ export const settingsZh: Record = { "guestTimezoneUTC": "UTC(协调世界时)", "guestTimezoneUpgradeAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看升级到版本 {version} 的命令", "guestTimezoneUpgradeHint": "在 macOS 终端运行以下命令,将 Guest Tools 升级到版本 {version}", - "guestToolsConnected": "已连接", - "guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效", - "guestToolsReady": "已配置", "hidpiPresetBadge": "HiDPI", "hostAudioInput": "Windows 麦克风", "hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音", @@ -356,7 +346,6 @@ export const settingsZh: Record = { "installersDownloaded": "已下载", "installersDownloadingForVM": "为 {vm} 下载中", "installersDownloadingPct": "下载中 {p}%", - "installersEmpty": "还没有下载任何镜像", "installersHint": "下载好的镜像可以重复用来新建虚拟机", "installersKindOffline": "离线完整包", "installersKindOnline": "在线恢复镜像", @@ -425,7 +414,6 @@ export const settingsZh: Record = { "nestedVirtLabel": "嵌套虚拟化", "nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。", "networkBridge": "桥接", - "networkDesc": "通过 Windows 的网络连接上网", "networkNAT": "NAT", "networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网", "networkTitle": "网络", @@ -436,7 +424,6 @@ export const settingsZh: Record = { "npcapInstalling": "正在准备 Npcap,在弹出的官方安装向导中完成安装后将自动重新检查", "npcapMissing": "未检测到完整安装;应用网络时自动从官网下载,也可提前安装。许可与 UAC 在官方向导确认", "npcapStopFirst": "安装驱动前需先关闭全部虚拟机", - "offlineListFailed": "无法读取 Apple 的版本列表", "opencore": "OpenCore", "optAuto": "已自动开启", "optAvailable": "可用", @@ -449,11 +436,9 @@ export const settingsZh: Record = { "optPCoreSub": "仅调度到性能核({detail}),减少卡顿", "optPCoreUnavailable": "当前处理器无大小核架构,无需开启", "optRecommended": "推荐", - "optSchedBackground": "后台服务", "optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)", "optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)", "optSchedOpen": "更改…", - "optSchedPrograms": "程序优先", "optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)", "optSchedTitle": "Windows 处理器调度", "optUnavailable": "不可用", @@ -462,7 +447,6 @@ export const settingsZh: Record = { "recommendedBadge": "推荐", "resCustom": "自定义", "resCustomSub": "宽 × 高", - "resFullscreen": "全屏", "resInvalid": "格式为 宽x高,例如 2560x1600", "resNativeBadge": "原生", "resScaleToFitWindow": "缩放以适应窗口", @@ -504,11 +488,6 @@ export const settingsZh: Record = { "sshOffDesc": "从 Windows 用 SSH 登录 macOS", "sshPort": "SSH 转发端口", "startAfterCreate": "创建后立即启动", - "statsCPU": "QEMU CPU", - "statsDisk": "磁盘占用", - "statsDiskSub": "实际 {actual} / 上限 {virtual}", - "statsMemory": "宿主机内存", - "statsUptime": "运行时长", "stopBeforeDiskOp": "关机后才能操作", "stopTimeout": "关机等待时间", "stopTimeoutHint": "0 表示一直等待", @@ -547,7 +526,6 @@ export const settingsZh: Record = { "vcpus": "虚拟处理器", "vmDir": "存放目录", "vmName": "名称", - "welcomeCheckHost": "先完成内核环境配置 →", "welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置", "welcomeTitle": "创建第一台 macOS 虚拟机", "whpxHvOff": "Hypervisor 启动已关闭,启用后重启 Windows", @@ -624,7 +602,6 @@ export const settingsEn: Record = { "affinitySummaryPCores": "P-Cores ({count}T · {mask})", "affinityTitle": "CPU cores", "appCheckUpdate": "Check for updates", - "appDownloadUpdate": "Download", "appUpToDate": "Up to date", "appUpdateAvailable": "New stable release {v} available", "appUpdateAvailableAlpha": "New alpha release {v} available", @@ -734,11 +711,9 @@ export const settingsEn: Record = { "effectNextStart": "Next start", "enableAudio": "Audio", "enableLogs": "Keep graphics and serial logs", - "enableNetwork": "Network (NAT)", "enableWHPX": "Enable", "extraArgs": "Extra QEMU arguments", "extraArgsDesc": "Appended to the QEMU command line as is", - "failAffinity": "Could not update processor affinity", "folderShareAdd": "Add folder…", "folderShareAddTitle": "Host folders", "folderShareConfirmRWAction": "Enable read-write", @@ -764,9 +739,6 @@ export const settingsEn: Record = { "folderShareRemove": "Remove folder", "folderShareTitle": "Custom shared folders", "folderShareWritableWarn": "Read-write: changes and deletions in macOS modify the host folder directly", - "footerDisk": "Disk {gb} GB free", - "footerMem": "Memory {pct}%", - "footerMemAvail": "{avail} GB free", "forceQuitAppButton": "Force quit", "forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.", "forceQuitAppTitle": "Force quit Reims-Go", @@ -812,7 +784,6 @@ export const settingsEn: Record = { "groupMacOS": "macOS", "groupPerformance": "Performance", "groupQemu": "QEMU", - "gtInstallCmd": "Install command", "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", "guestLangShort": "System language", @@ -844,9 +815,6 @@ export const settingsEn: Record = { "guestTimezoneUTC": "UTC", "guestTimezoneUpgradeAttachHint": "Attach the Guest Tools image on the VM details page to see the command for updating to version {version}", "guestTimezoneUpgradeHint": "Run the command below in macOS Terminal to update Guest Tools to version {version}", - "guestToolsConnected": "Connected", - "guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately", - "guestToolsReady": "Configured", "hidpiPresetBadge": "HiDPI", "hostAudioInput": "Windows microphone", "hostAudioMissingIn": "No microphone found; macOS will record silence", @@ -921,7 +889,6 @@ export const settingsEn: Record = { "installersDownloaded": "Downloaded", "installersDownloadingForVM": "Downloading for {vm}", "installersDownloadingPct": "Downloading {p}%", - "installersEmpty": "No images downloaded yet", "installersHint": "Downloaded images can be reused for new VMs", "installersKindOffline": "Offline installer", "installersKindOnline": "Online recovery", @@ -990,7 +957,6 @@ export const settingsEn: Record = { "nestedVirtLabel": "Nested virtualization", "nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.", "networkBridge": "Bridged", - "networkDesc": "Uses the Windows network connection", "networkNAT": "NAT", "networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking", "networkTitle": "Network", @@ -1001,7 +967,6 @@ export const settingsEn: Record = { "npcapInstalling": "Preparing Npcap. Complete the official installer; availability will be checked afterwards", "npcapMissing": "A complete installation was not detected. Downloaded from the official website when applying, or install now. Confirm the license and UAC in the official wizard", "npcapStopFirst": "Shut down all VMs before installing the driver", - "offlineListFailed": "Couldn’t read Apple’s release list", "opencore": "OpenCore", "optAuto": "Automatic", "optAvailable": "Available", @@ -1014,11 +979,9 @@ export const settingsEn: Record = { "optPCoreSub": "Schedule QEMU on performance cores only ({detail})", "optPCoreUnavailable": "CPU has no hybrid P/E cores", "optRecommended": "Recommended", - "optSchedBackground": "Background services", "optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)", "optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)", "optSchedOpen": "Change…", - "optSchedPrograms": "Programs", "optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)", "optSchedTitle": "Windows processor scheduling", "optUnavailable": "Unavailable", @@ -1027,7 +990,6 @@ export const settingsEn: Record = { "recommendedBadge": "Recommended", "resCustom": "Custom", "resCustomSub": "Width × height", - "resFullscreen": "Full screen", "resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600", "resNativeBadge": "Native", "resScaleToFitWindow": "Scale to fit window", @@ -1069,11 +1031,6 @@ export const settingsEn: Record = { "sshOffDesc": "Log in to macOS over SSH from Windows", "sshPort": "SSH forward port", "startAfterCreate": "Start after creating", - "statsCPU": "QEMU CPU", - "statsDisk": "Disk usage", - "statsDiskSub": "{actual} actual / {virtual} max", - "statsMemory": "Host RAM", - "statsUptime": "Uptime", "stopBeforeDiskOp": "Shut down the VM first", "stopTimeout": "Shutdown timeout", "stopTimeoutHint": "0 waits indefinitely", @@ -1112,7 +1069,6 @@ export const settingsEn: Record = { "vcpus": "Virtual CPUs", "vmDir": "Folder", "vmName": "Name", - "welcomeCheckHost": "Set up Engine first →", "welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes", "welcomeTitle": "Create your first macOS VM", "whpxHvOff": "Hypervisor launch is off — enable and restart Windows", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 5bc845f..1159fac 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -59,7 +59,6 @@ export type I18nKey = | "affinitySummaryPCores" | "affinityTitle" | "appCheckUpdate" - | "appDownloadUpdate" | "appUpToDate" | "appUpdateAvailable" | "appUpdateAvailableAlpha" @@ -245,7 +244,6 @@ export type I18nKey = | "emptyVMs" | "enableAudio" | "enableLogs" - | "enableNetwork" | "enableWHPX" | "endpointCopyADB" | "endpointEditConnection" @@ -278,7 +276,6 @@ export type I18nKey = | "factGraphics" | "factGuestOS" | "factMemory" - | "failAffinity" | "failAttachInstaller" | "failCloneVM" | "failCreate" @@ -346,14 +343,11 @@ export type I18nKey = | "folderShareTitle" | "folderShareWritableWarn" | "fontMissingFoDHint" - | "footerDisk" | "footerDiskLabel" | "footerDiskTip" | "footerDiskValue" | "footerHostIssue" | "footerHostIssueTip" - | "footerMem" - | "footerMemAvail" | "footerMemLabel" | "footerMemTip" | "footerMemValue" @@ -412,7 +406,6 @@ export type I18nKey = | "groupPerformance" | "groupQemu" | "gtInstall" - | "gtInstallCmd" | "gtInstallSub" | "gtNotInstalledDesc" | "gtStatusConnected" @@ -464,13 +457,10 @@ export type I18nKey = | "guestTimezoneUTC" | "guestTimezoneUpgradeAttachHint" | "guestTimezoneUpgradeHint" - | "guestToolsConnected" | "guestToolsHostDNS" | "guestToolsModeSync" | "guestToolsModeWebDAV" | "guestToolsPreventSleep" - | "guestToolsPreventSleepSub" - | "guestToolsReady" | "guestToolsSleepActive" | "guestToolsTitle" | "guestToolsUpgradeHint" @@ -588,7 +578,6 @@ export type I18nKey = | "installersDownloading" | "installersDownloadingForVM" | "installersDownloadingPct" - | "installersEmpty" | "installersHint" | "installersKindOffline" | "installersKindOnline" @@ -694,7 +683,6 @@ export type I18nKey = | "netOff" | "netShared" | "networkBridge" - | "networkDesc" | "networkNAT" | "networkOfflineHint" | "networkTitle" @@ -712,7 +700,6 @@ export type I18nKey = | "offlineCached" | "offlineDownloading" | "offlineHint" - | "offlineListFailed" | "offlineListFailedDetail" | "offlineLoading" | "offlineQueued" @@ -737,11 +724,9 @@ export type I18nKey = | "optPCoreSub" | "optPCoreUnavailable" | "optRecommended" - | "optSchedBackground" | "optSchedNowBackground" | "optSchedNowPrograms" | "optSchedOpen" - | "optSchedPrograms" | "optSchedSub" | "optSchedTitle" | "optUnavailable" @@ -767,7 +752,6 @@ export type I18nKey = | "pluginBuiltinSection" | "pluginClearSecret" | "pluginColorSchemes" - | "pluginColorSchemesHint" | "pluginDeleteScheme" | "pluginDisable" | "pluginDisableInUseBody" @@ -823,7 +807,6 @@ export type I18nKey = | "pluginMarketSearchPlaceholder" | "pluginMarketStaleBanner" | "pluginMarketSyncing" - | "pluginMarketUpdate" | "pluginMarketUpdateShort" | "pluginMarketVersionTip" | "pluginMarketWithdrawn" @@ -852,7 +835,6 @@ export type I18nKey = | "pluginScanHardSection" | "pluginScanInspect" | "pluginScanInstallConfirm" - | "pluginScanLoading" | "pluginScanModalTitle" | "pluginScanMoreItems" | "pluginSchemeDefault" @@ -884,7 +866,6 @@ export type I18nKey = | "refresh" | "resCustom" | "resCustomSub" - | "resFullscreen" | "resInvalid" | "resLooksLike" | "resNativeBadge" @@ -1051,11 +1032,6 @@ export type I18nKey = | "state_stopping" | "state_suspended" | "state_suspending" - | "statsCPU" - | "statsDisk" - | "statsDiskSub" - | "statsMemory" - | "statsUptime" | "step1" | "step2" | "step3" @@ -1208,7 +1184,6 @@ export type I18nKey = | "vmDir" | "vmName" | "vulkanProbeFailed" - | "welcomeCheckHost" | "welcomeSub" | "welcomeTitle" | "whpxHvOff" diff --git a/internal/app/appupdate_flow.go b/internal/app/appupdate_flow.go index abc0a09..e31d3d0 100644 --- a/internal/app/appupdate_flow.go +++ b/internal/app/appupdate_flow.go @@ -175,7 +175,7 @@ func (a *App) InstallAppUpdate() error { } a.mu.Unlock() target := selfupdate.Target(exe, filepath.Base(path)) - if err := selfupdate.SwapWithOptions(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil { + if err := selfupdate.Swap(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil { return err } a.emitLog("app", fmt.Sprintf("Installed update %s at %s; restarting", ver, target)) diff --git a/internal/app/create_flow.go b/internal/app/create_flow.go index ddcaca1..8bcda84 100644 --- a/internal/app/create_flow.go +++ b/internal/app/create_flow.go @@ -56,7 +56,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) { ctx, cancel := context.WithCancel(a.baseCtx()) defer cancel() - taskID, w, finishTask := a.ctlTaskWriterWithCancel("vm-create", opts.Name, cancel) + taskID, w, finishTask := a.ctlTaskWriter("vm-create", opts.Name, cancel) if opts.NetworkMode == "bridge" { tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: networkmsg.Text(a.locale(), "log.create_network_prepare"), Percent: -1}) } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index f917484..cec64cd 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -23,7 +23,7 @@ func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.Dis ref := driver.VMRef{DriverID: driverID, Name: name} taskCtx, cancel := context.WithCancel(a.baseCtx()) defer cancel() - _, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", ref.Key(), cancel) + _, w, finishTask := a.ctlTaskWriter("vm-disk-resize", ref.Key(), cancel) a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize))) res, err := svc.ResizeDisk(taskCtx, ref, newSize, w, w) if err != nil { @@ -70,7 +70,7 @@ func (a *App) runCompactVMDisk(driverID, name string, optimize bool) (driver.Dis taskKind = "vm-disk-optimize" message = fmt.Sprintf("Optimizing qcow2 disk for %s with extended L2 subclusters...", name) } - _, w, finishTask := a.ctlTaskWriterWithCancel(taskKind, ref.Key(), cancel) + _, w, finishTask := a.ctlTaskWriter(taskKind, ref.Key(), cancel) a.emitVMLogForDriver(driverID, name, message) var ( res driver.DiskCompactResult diff --git a/internal/app/host_drop.go b/internal/app/host_drop.go index 94f8711..6d43552 100644 --- a/internal/app/host_drop.go +++ b/internal/app/host_drop.go @@ -14,7 +14,6 @@ import ( "time" "github.com/Nwflower/reims-go/internal/guesttools" - "github.com/Nwflower/reims-go/internal/qmp" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) @@ -199,9 +198,6 @@ func (a *App) currentGuestToolsServer() *guesttools.Server { return a.guestTools } -var sendDropClickAndPaste = qmp.SendAbsoluteClickAndPaste -var defaultDropClickAndPaste = true - func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error { if _, running := a.currentVMPID(ctx, name); !running { return fmt.Errorf("%s is not running", name) @@ -210,12 +206,7 @@ func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID strin if err != nil { return err } - if defaultDropClickAndPaste && fmt.Sprintf("%p", sendDropClickAndPaste) == fmt.Sprintf("%p", qmp.SendAbsoluteClickAndPaste) { - if svc, svcErr := a.computerUseService(); svcErr == nil && svc != nil { - return svc.SendAbsoluteClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait) - } - } - return sendDropClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait) + return a.computerUseInternalService().SendAbsoluteClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait) } func (a *App) handleHostDropAck(vmKey, name string, ack guesttools.DropEventAck) { diff --git a/internal/app/install_flow.go b/internal/app/install_flow.go index 5d6ac62..4b5fe6c 100644 --- a/internal/app/install_flow.go +++ b/internal/app/install_flow.go @@ -79,7 +79,7 @@ func (a *App) EnterRecovery(name string) error { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.enterRecoveryLegacy(name) + return a.enterMacOSRecovery(name) } raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "enter_recovery", nil) if err != nil { @@ -103,10 +103,10 @@ func (a *App) EnterRecovery(name string) error { return nil } -// enterRecoveryLegacy is the direct reims-ctl fallback when the lifecycle +// enterMacOSRecovery is the direct reims-ctl fallback when the lifecycle // router is unconfigured; it enables OpenCore's boot picker (--boot-selection=true) // immediately when stopped or queues a "want" marker when running. -func (a *App) enterRecoveryLegacy(name string) error { +func (a *App) enterMacOSRecovery(name string) error { c, err := a.client() if err != nil { return err @@ -286,7 +286,7 @@ func (a *App) FinishInstall(name string) error { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.finishInstallLegacy(name) + return a.finishMacOSInstall(name) } vm, err := a.resolveVMInfo("", name) if err != nil { @@ -333,10 +333,10 @@ func (a *App) FinishInstall(name string) error { return nil } -// FinishInstall exits recovery mode: ejects any attached installer, removes +// finishMacOSInstall exits recovery mode: ejects any attached installer, removes // REIMSHELP, enables the network if off, and restores OpenCore direct boot // (--boot-selection=false) if recovery mode enabled the boot picker. -func (a *App) finishInstallLegacy(name string) error { +func (a *App) finishMacOSInstall(name string) error { c, err := a.client() if err != nil { return err diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index b3c0ea3..5a343c2 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -118,7 +118,7 @@ func (a *App) StartVMWithDriver(driverID, name string) error { return err } return a.withComputerUseVM(context.Background(), vm.Directory, func(context.Context) error { - return a.startVMLegacy(vm.Name) + return a.startMacOSVM(vm.Name) }) } _, vm, err := svc.Resolve(context.Background(), driverID, name) @@ -137,7 +137,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface { Start(context.Context, driver.VMRef, io.Writer, io.Writer) (driver.StartResult, error) }, vm driver.VMInfo) error { if svc == nil { - return a.startVMLegacy(vm.Name) + return a.startMacOSVM(vm.Name) } ref := vm.Ref() key := ref.Key() @@ -193,7 +193,7 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver is unavailable without the plugin manager") } - return a.stopVMLegacyCtx(ctx, name, force) + return a.stopMacOSVM(ctx, name, force) } _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { @@ -238,7 +238,7 @@ func (a *App) EjectInstallerWithDriver(driverID, name string) error { if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver is unavailable without the plugin manager") } - return a.ejectInstallerLegacy(name) + return a.ejectMacOSInstaller(name) } vm, err := a.resolveVMInfo(driverID, name) if err != nil { @@ -260,7 +260,7 @@ func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string, svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.readVMLogsLegacy(name, serial) + return a.readMacOSVMLogs(name, serial) } return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial) } @@ -318,7 +318,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { return errors.New("driver is unavailable without the plugin manager") } - return a.deleteVMLegacy(name, keepFiles) + return a.deleteMacOSVM(name, keepFiles) } d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name) if err != nil { diff --git a/internal/app/macos_detail.go b/internal/app/macos_detail.go index 8830f67..6d4e713 100644 --- a/internal/app/macos_detail.go +++ b/internal/app/macos_detail.go @@ -30,7 +30,7 @@ func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo { return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data} } -func (a *App) getVMDetailLegacy(name string, epoch uint64) (reims.VMDetail, error) { +func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, error) { c, err := a.client() if err != nil { return reims.VMDetail{}, err @@ -56,7 +56,7 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.getVMDetailLegacy(name, epoch) + return a.loadMacOSVMDetail(name, epoch) } // This adapter only serves the built-in macOS driver, so resolve within it: // a same-named VM in another driver must not make the lookup ambiguous. diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index ec5cf4d..bf02ef3 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -194,7 +194,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string { return strings.TrimSpace(s) } -func (a *App) startVMLegacy(name string) error { +func (a *App) startMacOSVM(name string) error { if err := a.requireWritableDataRoot(); err != nil { return err } @@ -433,11 +433,7 @@ func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlCli return nil } -func (a *App) stopVMLegacy(name string, force bool) error { - return a.stopVMLegacyCtx(context.Background(), name, force) -} - -func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) error { +func (a *App) stopMacOSVM(ctx context.Context, name string, force bool) error { c, err := a.client() if err != nil { return err @@ -447,11 +443,11 @@ func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) erro return err } return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error { - return a.stopVMLegacyLocked(operationCtx, name, force, c) + return a.stopMacOSVMLocked(operationCtx, name, force, c) }) } -func (a *App) stopVMLegacyLocked(ctx context.Context, name string, force bool, c *reims.Client) error { +func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c *reims.Client) error { a.cancelRebootWatcher(name) stopVMMonitor(name) a.mu.Lock() @@ -541,7 +537,7 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo return true, a.startResolvedVMLocked(ctx, svc, vm) } -func (a *App) ejectInstallerLegacy(name string) error { +func (a *App) ejectMacOSInstaller(name string) error { c, err := a.client() if err != nil { return err @@ -563,7 +559,7 @@ func (a *App) ejectInstallerLegacy(name string) error { return nil } -func (a *App) deleteVMLegacy(name string, keepFiles bool) error { +func (a *App) deleteMacOSVM(name string, keepFiles bool) error { c, err := a.client() if err != nil { return err @@ -573,11 +569,11 @@ func (a *App) deleteVMLegacy(name string, keepFiles bool) error { return err } return a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error { - return a.deleteVMLegacyLocked(ctx, name, keepFiles, c) + return a.deleteMacOSVMLocked(ctx, name, keepFiles, c) }) } -func (a *App) deleteVMLegacyLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error { +func (a *App) deleteMacOSVMLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error { a.cancelRebootWatcher(name) stopVMMonitor(name) w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) @@ -628,7 +624,7 @@ func (a *App) ReadVMLogs(name string, serial bool) (string, error) { return a.ReadVMLogsWithDriver("", name, serial) } -func (a *App) readVMLogsLegacy(name string, serial bool) (string, error) { +func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) { c, err := a.client() if err != nil { return "", err diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index 365b564..db906d7 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -36,7 +36,7 @@ func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue { root := a.cfg.DataRoot loc := i18n.EffectiveLocale(a.cfg.Locale) a.mu.Unlock() - issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc) + issues := reims.ValidateCreate(opts, host.Inspect(root), loc) // reims-ctl refuses a name already registered; say so before the create runs. if vms, err := a.listVMsInternal(context.Background()); err == nil { for _, vm := range vms { @@ -69,7 +69,7 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) { root := a.cfg.DataRoot loc := a.cfg.Locale a.mu.Unlock() - return reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc), nil + return reims.ValidateSet(opts, cur, host.Inspect(root), loc), nil } func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) { @@ -107,7 +107,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) { root := a.cfg.DataRoot loc := a.cfg.Locale a.mu.Unlock() - if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 { + if issues := reims.ValidateSet(opts, cur, host.Inspect(root), loc); len(issues) > 0 { return fmt.Errorf("%s", issues[0].Message) } w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) }) @@ -526,29 +526,6 @@ func (a *App) recoverPacketNetwork(ctx context.Context, c networkControlClient, })() } -// 启动和恢复只重开 Npcap 通道,不改写封存的设备参数。 -func (a *App) prepareVMNetwork(c *reims.Client, d reims.VMDetail) (err error) { - defer a.localizeNetworkError(&err) - record, err := reims.ReadNetworkRecord(d.Directory) - if err != nil { - return err - } - if record.Corrupt { - return networkmsg.Error("record_invalid", nil) - } - if record.Pending { - return networkmsg.Error("packet_pending", nil) - } - if d.NetworkMode != "bridge" { - a.stopPacketBridge(d.Name) - return nil - } - if !a.npcapPluginEnabled() { - return networkmsg.Error("plugin_disabled", nil) - } - return a.preparePacketNetwork(a.baseCtx(), c, d, record, false) -} - func selectPacketUplink(adapters []packetbridge.Adapter, guid string) (packetbridge.Adapter, error) { for _, adapter := range adapters { if guid != "" && adapterGUIDKey(adapter.GUID) == adapterGUIDKey(guid) && adapter.Status == "Up" { diff --git a/internal/app/macos_window.go b/internal/app/macos_window.go deleted file mode 100644 index 3cae6d1..0000000 --- a/internal/app/macos_window.go +++ /dev/null @@ -1,86 +0,0 @@ -package app - -import ( - "context" - "errors" - "fmt" - - "github.com/Nwflower/reims-go/internal/driver" - "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/macos/reims" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" -) - -// ToggleVMFullscreen switches the running VM's display between full screen and windowed mode. -func (a *App) toggleVMFullscreenLegacy(name string) (bool, error) { - a.mu.Lock() - preference := a.cfg.Locale - a.mu.Unlock() - loc := i18n.EffectiveLocale(preference) - c, err := a.client() - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", i18n.Vars{"name": name}, err) - } - fullscreen, err := toggleVMFullscreen(context.Background(), name, loc, c, host.ToggleProcessWindowFullscreen) - if err != nil { - return false, err - } - a.emitVMLog(name, fmt.Sprintf("VM window full screen: %t", fullscreen)) - if a.ctx != nil { - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } - return fullscreen, nil -} - -type fullscreenVMClient interface { - Show(context.Context, string) (reims.VMDetail, error) - List(context.Context) ([]driver.VMListItem, error) -} - -func findRunningVMPID(vms []driver.VMListItem, name string) (uint32, bool) { - for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return uint32(*vm.PID), true - } - } - return 0, false -} - -func toggleVMFullscreen(ctx context.Context, name string, loc i18n.Locale, c fullscreenVMClient, toggleWindow func(uint32) (bool, error)) (bool, error) { - vars := i18n.Vars{"name": name} - beforeVMs, err := c.List(ctx) - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) - } - pidBefore, ok := findRunningVMPID(beforeVMs, name) - if !ok { - return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil) - } - detail, err := c.Show(ctx, name) - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) - } - if detail.State != "running" { - return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil) - } - if detail.Graphics == "vmware-svga" { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_VMWARE_SVGA", "err.fullscreen_vmware_svga", vars, nil) - } - afterVMs, err := c.List(ctx) - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) - } - pidAfter, ok := findRunningVMPID(afterVMs, name) - if !ok || pidAfter != pidBefore { - return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil) - } - fullscreen, err := toggleWindow(pidAfter) - if errors.Is(err, host.ErrDisplayWindowNotFound) { - return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, err) - } - if err != nil { - return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err) - } - return fullscreen, nil -} diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 5e84a4d..c622ea8 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -103,7 +103,7 @@ func (a *App) initPlugins() { } kindReg := rt.NewKindRegistry() - drvRouter := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { + drvRouter := driver.NewRouter(mgr.Registry(), func() string { a.mu.Lock() defer a.mu.Unlock() return a.cfg.DataRoot diff --git a/internal/app/runtime_bindings.go b/internal/app/runtime_bindings.go index 2e336d5..8380f6d 100644 --- a/internal/app/runtime_bindings.go +++ b/internal/app/runtime_bindings.go @@ -234,7 +234,7 @@ func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) { if !force && appUpdateCache.info != nil && appUpdateCache.channel == ch && time.Since(appUpdateCache.at) < remoteCacheTTL { return *appUpdateCache.info, nil } - info, err := version.DefaultSource().CheckUpdateChannel(a.baseCtx(), version.Version, ch) + info, err := version.DefaultSource().CheckUpdate(a.baseCtx(), version.Version, ch) if err != nil { return info, err } diff --git a/internal/app/ssh_flow.go b/internal/app/ssh_flow.go index d099549..b89215f 100644 --- a/internal/app/ssh_flow.go +++ b/internal/app/ssh_flow.go @@ -15,9 +15,6 @@ const sshUserFileName = ".reims-go-ssh-user" var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) -// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM. -func sshHostAlias(vmName string) string { return sshHostAliasForDriver("", vmName) } - func sshHostAliasForDriver(driverID, vmName string) string { var b strings.Builder b.WriteString("reims-") @@ -183,7 +180,7 @@ func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, err } cfgPath := filepath.Join(sshDir, "config") alias := sshHostAliasForDriver(driverID, name) - if err := upsertSSHConfigBlockHost(cfgPath, sshConfigKey(driverID, name), alias, sshHost, sshPort, user); err != nil { + if err := upsertSSHConfigBlock(cfgPath, sshConfigKey(driverID, name), alias, sshHost, sshPort, user); err != nil { return "", err } a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (%s:%d)", alias, sshHost, sshPort)) @@ -218,11 +215,7 @@ func (a *App) OpenVSCodeSSHWithDriver(driverID, name, user string) error { return nil } -func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string) error { - return upsertSSHConfigBlockHost(cfgPath, vmName, alias, "127.0.0.1", port, user) -} - -func upsertSSHConfigBlockHost(cfgPath, vmName, alias, host string, port int, user string) error { +func upsertSSHConfigBlock(cfgPath, vmName, alias, host string, port int, user string) error { startMark := fmt.Sprintf("# >>> reims-go:%s >>>", vmName) endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName) diff --git a/internal/app/ssh_flow_test.go b/internal/app/ssh_flow_test.go index 2481cb9..a0099c6 100644 --- a/internal/app/ssh_flow_test.go +++ b/internal/app/ssh_flow_test.go @@ -11,10 +11,10 @@ func TestSSHHostAlias(t *testing.T) { if sshHostAliasForDriver("test.driver.linux", "dev") == sshHostAliasForDriver("", "dev") { t.Fatal("same-name drivers share an SSH alias") } - if got := sshHostAlias("macos-tahoe"); got != "reims-macos-tahoe" { + if got := sshHostAliasForDriver("", "macos-tahoe"); got != "reims-macos-tahoe" { t.Fatalf("alias = %q", got) } - if got := sshHostAlias("My Mac 26"); got != "reims-my-mac-26" { + if got := sshHostAliasForDriver("", "My Mac 26"); got != "reims-my-mac-26" { t.Fatalf("alias = %q", got) } } @@ -26,7 +26,7 @@ func TestUpsertSSHConfigBlockIdempotent(t *testing.T) { t.Fatal(err) } - if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2222, "alice"); err != nil { + if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", "127.0.0.1", 2222, "alice"); err != nil { t.Fatal(err) } b1, _ := os.ReadFile(cfg) @@ -36,7 +36,7 @@ func TestUpsertSSHConfigBlockIdempotent(t *testing.T) { } // Updating port and user must replace the block in place without duplicating it. - if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2223, "bob"); err != nil { + if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", "127.0.0.1", 2223, "bob"); err != nil { t.Fatal(err) } b2, _ := os.ReadFile(cfg) diff --git a/internal/app/tasks.go b/internal/app/tasks.go index 25c10ff..7acb892 100644 --- a/internal/app/tasks.go +++ b/internal/app/tasks.go @@ -399,12 +399,7 @@ func (a *App) ensureTaskEmitter() { // a ": " prefix, which is dropped from the step. Each new step is logged // once, so the log keeps the milestones without one line per percent. // finish closes the task with the command's error. -func (a *App) ctlTaskWriter(kind, vm string) (w io.Writer, finish func(error)) { - _, w, finish = a.ctlTaskWriterWithCancel(kind, vm, nil) - return w, finish -} - -func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) { +func (a *App) ctlTaskWriter(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) { a.ensureTaskEmitter() id = tasks.start(kind, vm, vm, cancel) lastStep := "" diff --git a/internal/app/tasks_test.go b/internal/app/tasks_test.go index c7fb7e3..aa3c24b 100644 --- a/internal/app/tasks_test.go +++ b/internal/app/tasks_test.go @@ -75,7 +75,7 @@ func TestTaskCancelAndFailure(t *testing.T) { func TestCtlTaskWriterRoutesProgressToTheTask(t *testing.T) { sent := newTestTasks(t) a := &App{} // no Wails context: emitLog is a no-op - w, finish := a.ctlTaskWriter("vm-create", "macos-tahoe") + _, w, finish := a.ctlTaskWriter("vm-create", "macos-tahoe", nil) fmt.Fprintln(w, "macos-tahoe: creating the disk") for p := 0; p <= 100; p += 5 { fmt.Fprintf(w, "macos-tahoe: downloading OpenCore 1.0.8: %d%% of 11 MB\n", p) diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 29c4830..20bc9d9 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -41,7 +41,6 @@ var thumbLocks = struct { locks map[string]*sync.Mutex }{locks: make(map[string]*sync.Mutex)} -func (a *App) thumbPath(name string) string { return a.thumbPathForDriver("", name) } func (a *App) thumbPathForDriver(driverID, name string) string { a.mu.Lock() dir := a.cfg.XDGCacheDir() @@ -58,7 +57,6 @@ func (a *App) thumbPathForDriver(driverID, name string) string { return filepath.Join(dir, "thumbs", prefix+name+".jpg") } -func vmThumbLock(name string) *sync.Mutex { return vmThumbLockForDriver("", name) } func vmThumbLockForDriver(driverID, name string) *sync.Mutex { key := vmKeyForDriver(driverID, name) thumbLocks.mu.Lock() @@ -237,9 +235,6 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error { return nil } -func (a *App) captureThumb(name, path string) (VMThumbnail, bool) { - return a.captureThumbWithDriver("", name, path) -} func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, bool) { typing.mu.Lock() busy := typing.busy[vmKeyForDriver(driverID, name)] diff --git a/internal/app/thumbnail_flow_test.go b/internal/app/thumbnail_flow_test.go index 0fbadb9..44e6fd6 100644 --- a/internal/app/thumbnail_flow_test.go +++ b/internal/app/thumbnail_flow_test.go @@ -2,20 +2,23 @@ package app import ( "context" - "errors" - "slices" + "os" + "runtime" + "strings" "testing" - "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/macos/reims" + vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" + "github.com/Nwflower/reims-go/internal/plugin" ) func TestReleaseVMThumbnailRemovesLock(t *testing.T) { const name = "thumbnail-release-test" t.Cleanup(func() { releaseVMThumbnail(name) }) - first := vmThumbLock(name) - if got := vmThumbLock(name); got != first { + first := vmThumbLockForDriver("", name) + if got := vmThumbLockForDriver("", name); got != first { t.Fatal("same VM should share a thumbnail lock") } releaseVMThumbnail(name) @@ -25,124 +28,58 @@ func TestReleaseVMThumbnailRemovesLock(t *testing.T) { if remaining != 0 { t.Fatalf("thumbnail locks remain after release: %d", remaining) } - if got := vmThumbLock(name); got == first { + if got := vmThumbLockForDriver("", name); got == first { t.Fatal("released lock was reused") } } -type testFullscreenClient struct { - detail reims.VMDetail - vms []reims.VMListItem - listCalls [][]reims.VMListItem - calls []string -} - -func (c *testFullscreenClient) Show(_ context.Context, name string) (reims.VMDetail, error) { - c.calls = append(c.calls, "show "+name) - return c.detail, nil -} - -func (c *testFullscreenClient) List(context.Context) ([]reims.VMListItem, error) { - idx := 0 - for _, call := range c.calls { - if call == "list" { - idx++ - } - } - c.calls = append(c.calls, "list") - if len(c.listCalls) > 0 { - if idx < len(c.listCalls) { - return c.listCalls[idx], nil - } - return c.listCalls[len(c.listCalls)-1], nil - } - return c.vms, nil -} - -func TestToggleVMFullscreenUsesLiveVMState(t *testing.T) { - const name = "Tahoe" - oldPID, livePID, zeroPID, invalidPID := 301, 542, 0, -1 - for _, tt := range []struct { - name string - state string - vms []reims.VMListItem - listCalls [][]reims.VMListItem - wantCalls []string - target uint32 - }{ - {"stopped at show", "stopped", []reims.VMListItem{{Name: name, State: "running", PID: &oldPID}}, nil, []string{"list", "show Tahoe"}, 0}, - {"stopped before first list", "running", []reims.VMListItem{{Name: name, State: "stopped", PID: &oldPID}}, nil, []string{"list"}, 0}, - {"missing from list", "running", []reims.VMListItem{{Name: "Other", State: "running", PID: &oldPID}}, nil, []string{"list"}, 0}, - {"missing PID", "running", []reims.VMListItem{{Name: name, State: "running"}}, nil, []string{"list"}, 0}, - {"zero PID", "running", []reims.VMListItem{{Name: name, State: "running", PID: &zeroPID}}, nil, []string{"list"}, 0}, - {"negative PID", "running", []reims.VMListItem{{Name: name, State: "running", PID: &invalidPID}}, nil, []string{"list"}, 0}, - {"restarted with different PID between show and list (e.g. switched to SVGA)", "running", nil, [][]reims.VMListItem{ - {{Name: name, State: "running", PID: &oldPID}}, - {{Name: name, State: "running", PID: &livePID}}, - }, []string{"list", "show Tahoe", "list"}, 0}, - {"live running VM with stable PID", "running", []reims.VMListItem{ - {Name: "Other", State: "running", PID: &oldPID}, {Name: name, State: "running", PID: &livePID}, - }, nil, []string{"list", "show Tahoe", "list"}, uint32(livePID)}, - } { - t.Run(tt.name, func(t *testing.T) { - c := &testFullscreenClient{detail: reims.VMDetail{State: tt.state, Graphics: "reims-vgpu"}, vms: tt.vms, listCalls: tt.listCalls} - got, err := toggleVMFullscreen(context.Background(), name, i18n.EnUS, c, func(pid uint32) (bool, error) { - if pid != tt.target || tt.target == 0 { - t.Fatalf("toggled PID %d, want %d", pid, tt.target) - } - return true, nil - }) - if !slices.Equal(c.calls, tt.wantCalls) { - t.Fatalf("client calls = %v, want %v", c.calls, tt.wantCalls) - } - if tt.target == 0 { - if got || err == nil || err.Error() != "VM Tahoe is not running [E_VM_NOT_RUNNING]" { - t.Fatalf("toggle = (%v, %v), want a not-running error", got, err) - } - } else if !got || err != nil { - t.Fatalf("toggle = (%v, %v), want (true, nil)", got, err) - } - }) - } -} - +// Every refusal carries a localized summary and a stable code. func TestToggleVMFullscreenLocalizesErrors(t *testing.T) { - win32Error := errors.New("SetWindowPos: access denied") - pid := 542 + windowless := os.Getpid() for _, tt := range []struct { - name string - detail reims.VMDetail - hostError error - en, zh string + name, state, graphics string + pid *int + en, zh string }{ - {"stopped", reims.VMDetail{State: "stopped"}, nil, + {"stopped", "stopped", "", nil, "VM Tahoe is not running [E_VM_NOT_RUNNING]", "虚拟机 Tahoe 未运行 [E_VM_NOT_RUNNING]"}, - {"SVGA", reims.VMDetail{State: "running", Graphics: "vmware-svga"}, nil, + {"no process", "running", "reims-vgpu", nil, + "VM Tahoe is not running [E_VM_NOT_RUNNING]", "虚拟机 Tahoe 未运行 [E_VM_NOT_RUNNING]"}, + {"SVGA", "running", "vmware-svga", &windowless, "Press Ctrl+Alt+F in the QEMU window for Tahoe to toggle full screen [E_FULLSCREEN_VMWARE_SVGA]", "在 Tahoe 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏 [E_FULLSCREEN_VMWARE_SVGA]"}, - {"missing window", reims.VMDetail{State: "running", Graphics: "reims-vgpu"}, host.ErrDisplayWindowNotFound, + {"missing window", "running", "reims-vgpu", &windowless, "Couldn’t find the display window for Tahoe [E_VM_WINDOW_NOT_FOUND]", "找不到 Tahoe 的显示窗口 [E_VM_WINDOW_NOT_FOUND]"}, - {"Win32 failure", reims.VMDetail{State: "running", Graphics: "reims-vgpu"}, win32Error, - "Couldn’t toggle full screen for Tahoe [E_FULLSCREEN_FAILED]", "无法切换 Tahoe 的全屏状态 [E_FULLSCREEN_FAILED]"}, } { - for loc, summary := range map[i18n.Locale]string{i18n.EnUS: tt.en, i18n.ZhCN: tt.zh} { - t.Run(tt.name+"/"+string(loc), func(t *testing.T) { - c := &testFullscreenClient{detail: tt.detail, vms: []reims.VMListItem{{Name: "Tahoe", State: "running", PID: &pid}}} - got, err := toggleVMFullscreen(context.Background(), "Tahoe", loc, c, func(uint32) (bool, error) { - if tt.hostError == nil { - t.Fatal("toggled a stopped or SVGA VM") - } - return false, tt.hostError - }) - want := summary - if tt.hostError != nil { - want += "\n[detail] " + tt.hostError.Error() - if !errors.Is(err, tt.hostError) { - t.Errorf("error lost original cause: %v", err) - } + if tt.name == "missing window" && runtime.GOOS != "windows" { + continue // only the Windows host looks for windows + } + for locale, want := range map[string]string{"en-US": tt.en, "zh-CN": tt.zh} { + t.Run(tt.name+"/"+locale, func(t *testing.T) { + drv := &appSecondDriver{id: driver.BuiltinReimsMacOSDriverID, vms: []driver.VMInfo{{ + Name: "Tahoe", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir(), + State: tt.state, PID: tt.pid, DriverData: map[string]any{"graphics": tt.graphics}, + }}} + reg := plugin.NewRegistry(nil) + if err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: "test.macos", Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true, + Activate: func(_ context.Context, sc *plugin.Scope) error { + reg.RegisterGuestDriver(sc, drv.id, drv) + return nil + }, + }); err != nil { + t.Fatal(err) } - if got || err == nil || err.Error() != want { - t.Fatalf("toggle = (%v, %v), want (false, %q)", got, err, want) + reg.Reconcile(t.Context()) + a := &App{cfg: &config.Config{DataRoot: t.TempDir(), Locale: i18n.Locale(locale)}, + lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), + transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}} + got, err := a.ToggleVMFullscreen("Tahoe") + if got || err == nil { + t.Fatalf("toggle = (%v, %v), want an error", got, err) + } + if summary, _, _ := strings.Cut(err.Error(), "\n"); summary != want { + t.Fatalf("summary = %q, want %q", summary, want) } }) } diff --git a/internal/app/vm_close_windows.go b/internal/app/vm_close_windows.go index 8d7b789..71e2068 100644 --- a/internal/app/vm_close_windows.go +++ b/internal/app/vm_close_windows.go @@ -12,6 +12,16 @@ import ( "github.com/Nwflower/reims-go/internal/tray" ) +// runningVMPID returns the process ID of the named VM when it is running. +func runningVMPID(vms []driver.VMListItem, name string) (uint32, bool) { + for _, vm := range vms { + if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { + return uint32(*vm.PID), true + } + } + return 0, false +} + func (a *App) confirmVMWindowClose(name string) { if _, pending := a.vmClosePrompts.LoadOrStore(name, struct{}{}); pending { return @@ -56,7 +66,7 @@ func (a *App) confirmVMWindowClose(name string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error()) return } - if current, running := findRunningVMPID(vms, ref.Name); !running || current != uint32(pid) { + if current, running := runningVMPID(vms, ref.Name); !running || current != uint32(pid) { return } if choice == host.VMCloseSuspend { diff --git a/internal/app/vm_monitor_test.go b/internal/app/vm_monitor_test.go index 529befd..4127693 100644 --- a/internal/app/vm_monitor_test.go +++ b/internal/app/vm_monitor_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/macos/reims" + "github.com/Nwflower/reims-go/internal/host" ) func TestLogTailDiscardsOversizeLinesAndResumes(t *testing.T) { @@ -96,11 +96,11 @@ func TestFormatBootHeartbeatAndRedactLogLine(t *testing.T) { t.Fatalf("unexpected heartbeat: %q", hb) } - redacted := reims.RedactLogLine("network user, mac 52:54:00:bc:bc:0d, ssh on 127.0.0.1:2222") + redacted := host.RedactLine("network user, mac 52:54:00:bc:bc:0d, ssh on 127.0.0.1:2222") if strings.Contains(redacted, "bc:bc:0d") || !strings.Contains(redacted, "mac [redacted]") { t.Fatalf("MAC not redacted: %q", redacted) } - redactedSerial := reims.RedactLogLine("OpenCore presents the VM as an iMac20,1, serial C02FDGY9PN5T") + redactedSerial := host.RedactLine("OpenCore presents the VM as an iMac20,1, serial C02FDGY9PN5T") if strings.Contains(redactedSerial, "C02FDGY9PN5T") || !strings.Contains(redactedSerial, "serial [redacted]") { t.Fatalf("serial not redacted: %q", redactedSerial) } diff --git a/internal/app/vm_processes.go b/internal/app/vm_processes.go index ad19b9c..3972113 100644 --- a/internal/app/vm_processes.go +++ b/internal/app/vm_processes.go @@ -11,16 +11,6 @@ import ( "github.com/Nwflower/reims-go/internal/vmstart" ) -// canScreendump reports whether the host can read a VM's screen over its QMP -// socket: the VM must declare `qmp` and must not be hosted. A VM with no -// declared capabilities is a legacy macOS VM. -func canScreendump(caps []string) bool { - if driver.IsHosted(caps) { - return false - } - return len(caps) == 0 || driver.HasCapability(caps, driver.CapQMP) -} - // readyToken and endpointSignature fold a VM's readiness and endpoints into // the poll signature, so the UI refreshes when a driver flips them. func readyToken(ready *bool) string { diff --git a/internal/app/vmref_test.go b/internal/app/vmref_test.go index 5ec2b30..e9c4d7f 100644 --- a/internal/app/vmref_test.go +++ b/internal/app/vmref_test.go @@ -35,7 +35,4 @@ func TestSameNamedVMMemoryStatesUseDriverQualifiedKeys(t *testing.T) { if a.thumbPathForDriver("test.driver.a", "shared") == a.thumbPathForDriver("test.driver.b", "shared") { t.Fatal("same-named VMs share a thumbnail path") } - if got := a.thumbPath("shared"); got != a.thumbPathForDriver("", "shared") { - t.Fatal("default thumbnail path changed") - } } diff --git a/internal/archtest/driver_isolation_test.go b/internal/archtest/driver_isolation_test.go index 9ab5df7..339b797 100644 --- a/internal/archtest/driver_isolation_test.go +++ b/internal/archtest/driver_isolation_test.go @@ -1,9 +1,6 @@ package archtest import ( - "io/fs" - "os" - "path/filepath" "strings" "testing" ) @@ -20,44 +17,14 @@ var externalDriverIDs = []string{ } func TestHostCodeNamesNoExternalDriver(t *testing.T) { - root, err := filepath.Abs(filepath.Join("..", "..")) - if err != nil { - t.Fatal(err) - } - skipDirs := map[string]bool{".git": true, ".debug": true, "build": true, "frontend": true, "node_modules": true} - scanned := 0 - err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err + for _, s := range sources(t) { + if s.isTest() { + continue } - rel, _ := filepath.Rel(root, path) - rel = filepath.ToSlash(rel) - if d.IsDir() { - if skipDirs[d.Name()] || rel == "internal/archtest" { - return filepath.SkipDir - } - return nil - } - if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { - return nil - } - raw, err := os.ReadFile(path) - if err != nil { - return err - } - scanned++ - text := string(raw) for _, id := range externalDriverIDs { - if strings.Contains(text, id) { - t.Errorf("%s names the external driver %q: host code must stay driver-agnostic", rel, id) + if strings.Contains(s.raw, id) { + t.Errorf("%s names the external driver %q: host code must stay driver-agnostic", s.rel, id) } } - return nil - }) - if err != nil { - t.Fatal(err) - } - if scanned < 50 { - t.Fatalf("scanned only %d Go files: the walk no longer finds the host sources", scanned) } } diff --git a/internal/archtest/locales_test.go b/internal/archtest/locales_test.go new file mode 100644 index 0000000..2f12691 --- /dev/null +++ b/internal/archtest/locales_test.go @@ -0,0 +1,75 @@ +package archtest + +import ( + "encoding/json" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +var stringLiteral = regexp.MustCompile("[\"'`]([A-Za-z0-9_.-]+)(?:[\"'`]|[$]{|%s)") + +// Every message costs a translation in every language pack, so one that no +// code shows must go. A key also counts as used when code builds it from a +// literal prefix, such as "cli.start." + step. +func TestCatalogHasNoUnusedMessages(t *testing.T) { + literals := map[string]bool{} + collect := func(text string) { + for _, m := range stringLiteral.FindAllStringSubmatch(text, -1) { + literals[m[1]] = true + } + } + for _, s := range sources(t) { + if !strings.HasSuffix(s.rel, "_gen.go") && !s.isTest() { + collect(s.raw) + } + } + err := filepath.WalkDir(filepath.Join("..", "..", "frontend", "src"), func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || strings.Contains(p, ".gen.") { + return err + } + raw, err := os.ReadFile(p) + collect(string(raw)) + return err + }) + if err != nil { + t.Fatal(err) + } + + used := func(key string) bool { + if literals[key] { + return true + } + for i := range key { + if (key[i] == '.' || key[i] == '_') && literals[key[:i+1]] { + return true + } + } + return false + } + catalogs, err := filepath.Glob(filepath.Join("..", "..", "locales", "en-US", "*.json")) + if err != nil || len(catalogs) == 0 { + t.Fatalf("no message catalogs: %v", err) + } + for _, path := range catalogs { + if filepath.Base(path) == "macos-glossary.json" { + continue // Apple's wording, looked up by the text it translates + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var messages map[string]json.RawMessage + if err := json.Unmarshal(raw, &messages); err != nil { + t.Fatalf("%s: %v", path, err) + } + for key := range messages { + if !strings.HasPrefix(key, "$") && !used(key) { + t.Errorf("%s: no code shows message %q", filepath.Base(path), key) + } + } + } +} diff --git a/internal/archtest/macos_boundary_test.go b/internal/archtest/macos_boundary_test.go index ba93700..7804269 100644 --- a/internal/archtest/macos_boundary_test.go +++ b/internal/archtest/macos_boundary_test.go @@ -1,19 +1,11 @@ package archtest import ( - "go/parser" - "go/token" - "io/fs" - "os" - "path/filepath" "sort" - "strconv" "strings" "testing" ) -const macosImportPrefix = "github.com/Nwflower/reims-go/internal/macos" - // macosImporter is a package outside internal/macos that may still import // macOS code: debt to pay down before macOS leaves this repository. type macosImporter struct { @@ -29,7 +21,6 @@ var macosImporters = map[string]macosImporter{ "internal/datamigrate": {src: true, test: true, why: "data layout v3 invokes and verifies the macOS-owned state and ledger migration"}, "internal/plugin/builtin": {src: true, why: "host Guest Tools bridge still uses reims argument helpers; guest registration moved to internal/macos/guest"}, "internal/guesttools": {src: true, test: true, why: "mixed: host transport and clipboard next to the macOS guest agent image"}, - "internal/plugin": {test: true, why: "sidecar manager test builds a reims-ctl stand-in"}, } // macosSourceFiles is the file-scoped native macOS boundary. plugins_flow.go @@ -48,7 +39,6 @@ var macosSourceFiles = map[string][]string{ "internal/app/macos_detail.go", "internal/app/macos_lifecycle_native.go", "internal/app/macos_settings.go", - "internal/app/macos_window.go", "internal/app/opencore_flow.go", "internal/app/plugins_flow.go", }, @@ -60,55 +50,28 @@ var macosSourceFiles = map[string][]string{ } func TestMacOSBoundary(t *testing.T) { - root, err := filepath.Abs(filepath.Join("..", "..")) - if err != nil { - t.Fatal(err) - } type use struct{ src, test []string } found := map[string]*use{} - - skipDirs := map[string]bool{".git": true, ".debug": true, "build": true, "frontend": true, "node_modules": true} - err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err + for _, s := range sources(t) { + if isMacOSDir(s.dir()) { + continue } - rel, _ := filepath.Rel(root, path) - rel = filepath.ToSlash(rel) - if d.IsDir() { - if skipDirs[d.Name()] || rel == "internal/macos" { - return filepath.SkipDir - } - return nil - } - if !strings.HasSuffix(path, ".go") { - return nil - } - f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly) - if err != nil { - return err - } - for _, imp := range f.Imports { - p, _ := strconv.Unquote(imp.Path.Value) - if p != macosImportPrefix && !strings.HasPrefix(p, macosImportPrefix+"/") { + for _, dir := range s.imports() { + if !isMacOSDir(dir) { continue } - dir := filepath.ToSlash(filepath.Dir(rel)) - u := found[dir] + u := found[s.dir()] if u == nil { u = &use{} - found[dir] = u + found[s.dir()] = u } - if strings.HasSuffix(path, "_test.go") { - u.test = append(u.test, rel) + if s.isTest() { + u.test = append(u.test, s.rel) } else { - u.src = append(u.src, rel) + u.src = append(u.src, s.rel) } break } - return nil - }) - if err != nil { - t.Fatal(err) } var problems []string @@ -162,14 +125,6 @@ func TestMacOSBoundary(t *testing.T) { } } -// The ratchet only means something if internal/macos exists where the test -// looks; guard against the walk silently finding nothing after a move. -func TestMacOSBoundaryRootExists(t *testing.T) { - if st, err := os.Stat(filepath.Join("..", "macos")); err != nil || !st.IsDir() { - t.Fatalf("internal/macos not found next to internal/archtest: %v", err) - } -} - // macosHostImports is the reverse ratchet: dependencies of internal/macos on // private host packages. External repositories cannot import these, so the // list must shrink to zero before macOS becomes a separate Go module. @@ -190,39 +145,16 @@ var macosHostImports = map[string]string{ } func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) { - root, err := filepath.Abs(filepath.Join("..", "macos")) - if err != nil { - t.Fatal(err) - } found := map[string][]string{} - err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err + for _, s := range sources(t) { + if !isMacOSDir(s.dir()) { + continue } - if d.IsDir() || !strings.HasSuffix(path, ".go") { - return nil - } - f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly) - if err != nil { - return err - } - for _, imp := range f.Imports { - p, _ := strconv.Unquote(imp.Path.Value) - const prefix = "github.com/Nwflower/reims-go/internal/" - if !strings.HasPrefix(p, prefix) { - continue + for _, dir := range s.imports() { + if name, ok := strings.CutPrefix(dir, "internal/"); ok && !isMacOSDir(dir) { + found[name] = append(found[name], s.rel) } - name := strings.TrimPrefix(p, prefix) - if strings.HasPrefix(name, "macos") { - continue - } - rel, _ := filepath.Rel(root, path) - found[name] = append(found[name], filepath.ToSlash(rel)) } - return nil - }) - if err != nil { - t.Fatal(err) } for name, files := range found { if _, ok := macosHostImports[name]; !ok { @@ -235,3 +167,7 @@ func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) { } } } + +func isMacOSDir(dir string) bool { + return dir == "internal/macos" || strings.HasPrefix(dir, "internal/macos/") +} diff --git a/internal/archtest/sources_test.go b/internal/archtest/sources_test.go new file mode 100644 index 0000000..296cf2b --- /dev/null +++ b/internal/archtest/sources_test.go @@ -0,0 +1,98 @@ +package archtest + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" +) + +const modulePath = "github.com/Nwflower/reims-go" + +// source is one Go file of the repository. All build constraints are covered: +// the checks read every file, not one platform's selection. +type source struct { + rel string // slash-separated path from the repository root + raw string + file *ast.File +} + +func (s source) dir() string { return path.Dir(s.rel) } +func (s source) isTest() bool { return strings.HasSuffix(s.rel, "_test.go") } + +// imports maps the local name of every module-internal import to its +// repository directory. +func (s source) imports() map[string]string { + out := map[string]string{} + for _, imp := range s.file.Imports { + p, err := strconv.Unquote(imp.Path.Value) + if err != nil || !strings.HasPrefix(p, modulePath+"/") { + continue + } + name := path.Base(p) + if imp.Name != nil { + name = imp.Name.Name + } + out[name] = strings.TrimPrefix(p, modulePath+"/") + } + return out +} + +var fileSet = token.NewFileSet() + +var loadSources = sync.OnceValues(func() ([]source, error) { + root, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + return nil, err + } + skip := map[string]bool{".git": true, ".debug": true, ".local": true, "build": true, "frontend": true, "node_modules": true, "archtest": true} + var out []source + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if skip[d.Name()] { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(p, ".go") { + return nil + } + raw, err := os.ReadFile(p) + if err != nil { + return err + } + f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution) + if err != nil { + return err + } + rel, err := filepath.Rel(root, p) + if err != nil { + return err + } + out = append(out, source{rel: filepath.ToSlash(rel), raw: string(raw), file: f}) + return nil + }) + return out, err +}) + +func sources(t *testing.T) []source { + t.Helper() + all, err := loadSources() + if err != nil { + t.Fatal(err) + } + if len(all) < 300 { + t.Fatalf("found only %d Go files: the walk no longer sees the repository", len(all)) + } + return all +} diff --git a/internal/archtest/unused_test.go b/internal/archtest/unused_test.go new file mode 100644 index 0000000..0e5c966 --- /dev/null +++ b/internal/archtest/unused_test.go @@ -0,0 +1,61 @@ +package archtest + +import ( + "go/ast" + "strings" + "testing" +) + +// A function that only tests call is a second implementation the product does +// not run: delete it and test the one it does run. pkg/ is public API and +// internal/testutil exists for tests, so both are exempt. Exported methods are +// too, since interfaces and the Wails bindings call them. +func TestProductCodeHasNoUncalledFunctions(t *testing.T) { + type decl struct { + src source + fn *ast.FuncDecl + } + decls := map[string]decl{} // "." + used := map[string]bool{} + + for _, s := range sources(t) { + if s.isTest() { + continue + } + imports := s.imports() + for _, d := range s.file.Decls { + fn, _ := d.(*ast.FuncDecl) + self := "" + if fn != nil { + self = s.dir() + "." + fn.Name.Name + checked := strings.HasPrefix(s.rel, "internal/") && !strings.HasPrefix(s.rel, "internal/testutil/") || strings.HasPrefix(s.rel, "cmd/") + entry := fn.Name.Name == "main" || fn.Name.Name == "init" || fn.Name.Name == "_" + if checked && !entry && (fn.Recv == nil || !fn.Name.IsExported()) { + decls[self] = decl{s, fn} + } + } + ast.Inspect(d, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.SelectorExpr: + if x, ok := n.X.(*ast.Ident); ok { + if dir, ok := imports[x.Name]; ok { + used[dir+"."+n.Sel.Name] = true + return false + } + } + case *ast.Ident: + // The declaration's own name and recursion are not callers. + if key := s.dir() + "." + n.Name; key != self { + used[key] = true + } + } + return true + }) + } + } + for key, d := range decls { + if !used[key] { + t.Errorf("%s: no product code calls %s", fileSet.Position(d.fn.Pos()), d.fn.Name.Name) + } + } +} diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index c4eddc2..5966720 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -53,7 +53,7 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * return value, ok }, } - router := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory()) + router := driver.NewRouter(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory()) mgr.Registry().SetInUseChecker(router.PluginInUseChecker()) mgr.Registry().SetBusyChecker(router.PluginBusyChecker()) if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil { @@ -582,20 +582,6 @@ func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) return nil } -func printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error { - hasErr := false - for _, f := range findings { - fmt.Printf("[%s] (%s) %s\n", f.Severity, f.Check, f.Message) - if f.Severity == "error" { - hasErr = true - } - } - if hasErr { - return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors")) - } - return nil -} - func cmdPluginLocale(loc i18n.Locale, args []string) error { if len(args) == 0 { return fmt.Errorf("usage: reims-go plugin locale ...") diff --git a/internal/console/manager.go b/internal/console/manager.go index 4375f73..e692929 100644 --- a/internal/console/manager.go +++ b/internal/console/manager.go @@ -122,7 +122,7 @@ func (m *Manager) SendAbsoluteClickAndPaste(ctx context.Context, vmDir string, n focusWait = 120 * time.Millisecond } return m.withConn(ctx, vmDir, func(conn qmpSession) error { - return qmp.ClickAndPasteWithActivate(ctx, conn, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey) + return qmp.ClickAndPaste(ctx, conn, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey) }) } diff --git a/internal/console/manager_test.go b/internal/console/manager_test.go index 64a7458..e341eb2 100644 --- a/internal/console/manager_test.go +++ b/internal/console/manager_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "os" "path/filepath" + "strings" "sync" "sync/atomic" "testing" @@ -159,3 +160,10 @@ func TestManagerQMPOperationHoldsLifecycleFileLock(t *testing.T) { } filelock.Unlock(lockFile) } + +func TestSendPasteShortcutComboRejectsBadComboBeforeDialing(t *testing.T) { + err := NewManager().SendPasteShortcutCombo(t.Context(), t.TempDir(), "ctrl+") + if err == nil || !strings.Contains(err.Error(), "empty key") { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/datamigrate/guest_migration_test.go b/internal/datamigrate/guest_migration_test.go index a03d717..55698f5 100644 --- a/internal/datamigrate/guest_migration_test.go +++ b/internal/datamigrate/guest_migration_test.go @@ -51,7 +51,10 @@ func TestV1ToV3GuestPluginMigration(t *testing.T) { if got := marker(t, vmDir); got != driver.BuiltinReimsMacOSDriverID { t.Fatalf("late v1 VM marker = %q", got) } - st := plugin.ReadState(root) + st, err := store.Load() + if err != nil { + t.Fatal(err) + } rec := st.Plugins[guest.ID] if rec == nil || !rec.Enabled { t.Fatalf("guest record = %+v", rec) diff --git a/internal/datamigrate/release_upgrade_test.go b/internal/datamigrate/release_upgrade_test.go index 5854070..47e4371 100644 --- a/internal/datamigrate/release_upgrade_test.go +++ b/internal/datamigrate/release_upgrade_test.go @@ -37,7 +37,10 @@ func TestUnstampedReleaseUpgradeRestoresOriginalBackup(t *testing.T) { if got := marker(t, vmDir); got != driver.BuiltinReimsMacOSDriverID { t.Fatalf("owner marker = %q", got) } - st := plugin.ReadState(root) + st, err := store.Load() + if err != nil { + t.Fatal(err) + } rec := st.Plugins[guest.ID] if rec == nil || guest.SettingOn(rec.AppSettings, guest.SettingWHPXFallback) || guest.SettingOn(rec.AppSettings, guest.SettingInstallGuide) { t.Fatalf("guest settings = %+v", rec) diff --git a/internal/datamigrate/vmref_settings.go b/internal/datamigrate/vmref_settings.go index 3ea346c..a4fe325 100644 --- a/internal/datamigrate/vmref_settings.go +++ b/internal/datamigrate/vmref_settings.go @@ -5,20 +5,6 @@ import ( "github.com/Nwflower/reims-go/internal/plugin" ) -// migrateVMRefSettings qualifies legacy per-VM plugin settings with the only -// driver that existed before VMRef. Existing qualified keys win field by field. -func migrateVMRefSettings(dataRoot string) error { - store := plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root) - st, err := store.Load() - if err != nil { - return err - } - if migrateVMRefSettingsState(st) { - return store.Save(st) - } - return nil -} - func migrateVMRefSettingsState(st *plugin.StateFile) bool { changed := false for _, rec := range st.Plugins { diff --git a/internal/datamigrate/vmref_settings_test.go b/internal/datamigrate/vmref_settings_test.go index 1a90425..ab26737 100644 --- a/internal/datamigrate/vmref_settings_test.go +++ b/internal/datamigrate/vmref_settings_test.go @@ -28,7 +28,10 @@ func TestV3MigratesVMSettingsToVMRefKeys(t *testing.T) { if err != nil || res.From != 2 || res.To != 3 { t.Fatalf("Run = %+v, %v", res, err) } - st := plugin.ReadState(root) + st, err := store.Load() + if err != nil { + t.Fatal(err) + } vals := st.Plugins["test.plugin"].VMSettings[key] if vals["legacy"] != true || vals["priority"] != "new" { t.Fatalf("merged settings = %+v", vals) diff --git a/internal/driver/driver.go b/internal/driver/driver.go index 51d637c..cc33f87 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -316,11 +316,10 @@ const HostedReportMaxAge = 15 * time.Second // Router aggregates active guest drivers from the plugin Registry and routes // VM operations by ownership (§5.3). type Router struct { - reg *plugin.Registry - dataRootDir func() string // DataRoot for statically declared guest VM roots - legacyVMRoot func() string // compatibility root for tests and older embedders - inventories []VMInventory - states *StateTable + reg *plugin.Registry + dataRootDir func() string // DataRoot for statically declared guest VM roots + inventories []VMInventory + states *StateTable } // SetStateTable attaches the table of driver-reported VM states that @@ -345,14 +344,9 @@ type VMInventory struct { List func(dataRoot string) ([]VMInfo, error) } -// NewRouter creates a driver Router backed by reg. -func NewRouter(reg *plugin.Registry, vmRootDir func() string) *Router { - return &Router{reg: reg, legacyVMRoot: vmRootDir} -} - -// NewRouterWithDataRoot discovers unavailable VMs through driver inventories +// NewRouter discovers unavailable VMs through driver inventories // or through ownership markers in declared roots. -func NewRouterWithDataRoot(reg *plugin.Registry, dataRootDir func() string, inventories ...VMInventory) *Router { +func NewRouter(reg *plugin.Registry, dataRootDir func() string, inventories ...VMInventory) *Router { return &Router{reg: reg, dataRootDir: dataRootDir, inventories: inventories} } @@ -379,9 +373,6 @@ func (rt *Router) vmRoots() []string { } } } - if rt != nil && rt.legacyVMRoot != nil { - add(rt.legacyVMRoot()) - } return roots } diff --git a/internal/driver/driver_test.go b/internal/driver/driver_test.go index ec7b799..c6eb75a 100644 --- a/internal/driver/driver_test.go +++ b/internal/driver/driver_test.go @@ -16,25 +16,43 @@ type fakeDriver struct { vms []VMInfo } -func (f *fakeDriver) ID() string { return f.id } -func (f *fakeDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: f.id} } -func (f *fakeDriver) RuntimeKind() string { return "qemu-ovmf" } -func (f *fakeDriver) RuntimeAPIRange() string { return "^1.0.0" } -func (f *fakeDriver) Capabilities() []string { return []string{CapCloudInit, CapSSH} } -func (f *fakeDriver) CreateSchema() *plugin.SettingsSchema { return nil } -func (f *fakeDriver) SettingsSchema() *plugin.SettingsSchema { return nil } -func (f *fakeDriver) List(context.Context) ([]VMInfo, error) { return f.vms, nil } -func (f *fakeDriver) Show(_ context.Context, n string) (VMInfo, error) { return VMInfo{Name: n, DriverID: f.id}, nil } -func (f *fakeDriver) ValidateCreate(context.Context, CreateRequest) []ValidationIssue { return nil } -func (f *fakeDriver) Create(context.Context, CreateRequest, io.Writer, io.Writer) error { return nil } -func (f *fakeDriver) ValidateSet(context.Context, SetRequest) []ValidationIssue { return nil } -func (f *fakeDriver) Set(context.Context, SetRequest, io.Writer, io.Writer) error { return nil } -func (f *fakeDriver) Start(context.Context, StartRequest) (StartResult, error) { return StartResult{}, nil } -func (f *fakeDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { return nil } -func (f *fakeDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil } +func (f *fakeDriver) ID() string { return f.id } +func (f *fakeDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: f.id} } +func (f *fakeDriver) RuntimeKind() string { return "qemu-ovmf" } +func (f *fakeDriver) RuntimeAPIRange() string { return "^1.0.0" } +func (f *fakeDriver) Capabilities() []string { return []string{CapCloudInit, CapSSH} } +func (f *fakeDriver) CreateSchema() *plugin.SettingsSchema { return nil } +func (f *fakeDriver) SettingsSchema() *plugin.SettingsSchema { return nil } +func (f *fakeDriver) List(context.Context) ([]VMInfo, error) { return f.vms, nil } +func (f *fakeDriver) Show(_ context.Context, n string) (VMInfo, error) { + return VMInfo{Name: n, DriverID: f.id}, nil +} +func (f *fakeDriver) ValidateCreate(context.Context, CreateRequest) []ValidationIssue { return nil } +func (f *fakeDriver) Create(context.Context, CreateRequest, io.Writer, io.Writer) error { return nil } +func (f *fakeDriver) ValidateSet(context.Context, SetRequest) []ValidationIssue { return nil } +func (f *fakeDriver) Set(context.Context, SetRequest, io.Writer, io.Writer) error { return nil } +func (f *fakeDriver) Start(context.Context, StartRequest) (StartResult, error) { + return StartResult{}, nil +} +func (f *fakeDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { return nil } +func (f *fakeDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil } + +// declareVMRoot registers an installed but disabled driver plugin that keeps +// its VMs in /vms. +func declareVMRoot(t *testing.T, reg *plugin.Registry, driverID string) { + t.Helper() + if err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: "test.disabled-driver", Version: "1.0.0", + Contributes: plugin.Contributes{GuestDrivers: []plugin.GuestDriverContribution{{ID: driverID, VMRoots: []string{"vms"}}}}}, + Source: plugin.SourceBuiltin, + }); err != nil { + t.Fatal(err) + } +} func TestOwnerMarkerZeroMigrationAndRouterUnavailable(t *testing.T) { - vmRoot := t.TempDir() + dataRoot := t.TempDir() + vmRoot := filepath.Join(dataRoot, "vms") legacyVM := filepath.Join(vmRoot, "macos-tahoe") _ = os.MkdirAll(legacyVM, 0o755) if got := ReadOwnerDriver(legacyVM); got != BuiltinReimsMacOSDriverID { @@ -63,8 +81,9 @@ func TestOwnerMarkerZeroMigrationAndRouterUnavailable(t *testing.T) { }, }) reg.Reconcile(context.Background()) + declareVMRoot(t, reg, "reims.driver.linux") - router := NewRouter(reg, func() string { return vmRoot }) + router := NewRouter(reg, func() string { return dataRoot }) all, err := router.ListAllVMs(context.Background()) if err != nil { t.Fatal(err) @@ -97,7 +116,8 @@ func TestRenamedDriverKeepsMarkedVMsVisible(t *testing.T) { RenamedDriverIDs[BuiltinReimsMacOSDriverID] = newID t.Cleanup(func() { delete(RenamedDriverIDs, BuiltinReimsMacOSDriverID) }) - vmRoot := t.TempDir() + dataRoot := t.TempDir() + vmRoot := filepath.Join(dataRoot, "vms") vmDir := filepath.Join(vmRoot, "macos-tahoe") if err := WriteOwnerDriver(vmDir, BuiltinReimsMacOSDriverID); err != nil { t.Fatal(err) @@ -106,7 +126,9 @@ func TestRenamedDriverKeepsMarkedVMsVisible(t *testing.T) { t.Fatalf("renamed owner = %q, want %q", got, newID) } - router := NewRouter(plugin.NewRegistry(nil), func() string { return vmRoot }) + reg := plugin.NewRegistry(nil) + declareVMRoot(t, reg, newID) + router := NewRouter(reg, func() string { return dataRoot }) all, err := router.ListAllVMs(context.Background()) if err != nil { t.Fatal(err) diff --git a/internal/driver/vmref_test.go b/internal/driver/vmref_test.go index 558ce1a..6c9fdae 100644 --- a/internal/driver/vmref_test.go +++ b/internal/driver/vmref_test.go @@ -57,7 +57,7 @@ func TestRouterScansDeclaredVMRoots(t *testing.T) { }, Source: plugin.SourceBuiltin}); err != nil { t.Fatal(err) } - router := NewRouterWithDataRoot(reg, func() string { return dataRoot }) + router := NewRouter(reg, func() string { return dataRoot }) vms, err := router.ListAllVMs(context.Background()) if err != nil || len(vms) != 1 || !vms[0].DriverUnavailable { t.Fatalf("ListAllVMs = %+v, %v", vms, err) diff --git a/internal/host/fonts_other.go b/internal/host/fonts_other.go index b14b0a7..080b58b 100644 --- a/internal/host/fonts_other.go +++ b/internal/host/fonts_other.go @@ -4,10 +4,6 @@ package host import "github.com/Nwflower/reims-go/internal/i18n" -func CheckMissingLocaleFonts(locale string) string { - return "" -} - func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string { return "" } diff --git a/internal/host/fonts_windows.go b/internal/host/fonts_windows.go index 3a4bf14..15409ef 100644 --- a/internal/host/fonts_windows.go +++ b/internal/host/fonts_windows.go @@ -65,14 +65,6 @@ func hasInstalledFontFamily(name string) bool { return fontDetectHit } -// CheckMissingLocaleFonts checks whether Windows has at least one modern UI -// font installed for the East Asian script required by locale (detecting missing -// Windows Features-on-Demand supplemental font packages on non-CJK Windows installs). -// Returns "" when fonts are present or not needed, or a localized script label. -func CheckMissingLocaleFonts(locale string) string { - return CheckMissingLocaleFontsForUI(locale, i18n.ResolveLocale(locale)) -} - // CheckMissingLocaleFontsForUI checks whether Windows has fonts for targetLocale // and returns the localized script name in uiLocale when missing. func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string { diff --git a/internal/host/foreground_other.go b/internal/host/foreground_other.go index dc62b0a..106bb85 100644 --- a/internal/host/foreground_other.go +++ b/internal/host/foreground_other.go @@ -5,9 +5,6 @@ package host // ForegroundPID is not implemented off Windows and always reports no owner. func ForegroundPID() uint32 { return 0 } -// FocusProcessWindow is not implemented off Windows. -func FocusProcessWindow(uint32) bool { return false } - // FocusProcessTreeWindow is not implemented off Windows. func FocusProcessTreeWindow([]uint32) bool { return false } diff --git a/internal/host/foreground_windows.go b/internal/host/foreground_windows.go index f9d252d..355e691 100644 --- a/internal/host/foreground_windows.go +++ b/internal/host/foreground_windows.go @@ -73,12 +73,6 @@ func enumFocusWindowProc(hwnd uintptr, _ uintptr) uintptr { return 1 } -// FocusProcessWindow finds the primary visible top-level window belonging to -// pid, restores it if minimized, and brings it to the foreground. -func FocusProcessWindow(pid uint32) bool { - return FocusProcessTreeWindow([]uint32{pid}) -} - // FocusProcessTreeWindow does the same for a launcher and the child processes // it started: the first visible top-level window of any of pids is focused. func FocusProcessTreeWindow(pids []uint32) bool { diff --git a/internal/host/fullscreen_other.go b/internal/host/fullscreen_other.go index 8eef1c9..004cd73 100644 --- a/internal/host/fullscreen_other.go +++ b/internal/host/fullscreen_other.go @@ -4,17 +4,9 @@ package host import "errors" -// IsProcessWindowFullscreen is not implemented off Windows. -func IsProcessWindowFullscreen(uint32) bool { return false } - // IsProcessTreeWindowFullscreen is not implemented off Windows. func IsProcessTreeWindowFullscreen([]uint32) bool { return false } -// ToggleProcessWindowFullscreen is not implemented off Windows. -func ToggleProcessWindowFullscreen(uint32) (bool, error) { - return false, errors.New("toggling a VM window's full screen mode is only supported on Windows") -} - // ToggleProcessTreeWindowFullscreen is not implemented off Windows. func ToggleProcessTreeWindowFullscreen([]uint32) (bool, error) { return false, errors.New("toggling a VM window's full screen mode is only supported on Windows") diff --git a/internal/host/fullscreen_windows.go b/internal/host/fullscreen_windows.go index a7d4b5f..8d24899 100644 --- a/internal/host/fullscreen_windows.go +++ b/internal/host/fullscreen_windows.go @@ -168,11 +168,6 @@ func liveWindowPID(hwnd uintptr) uint32 { return windowPID(hwnd) } -// IsProcessWindowFullscreen reports whether the selected display window fills its monitor without a frame. -func IsProcessWindowFullscreen(pid uint32) bool { - return IsProcessTreeWindowFullscreen([]uint32{pid}) -} - // IsProcessTreeWindowFullscreen is IsProcessWindowFullscreen for a process tree. func IsProcessTreeWindowFullscreen(pids []uint32) bool { fullscreenState.prune(liveWindowPID) @@ -200,12 +195,6 @@ func IsProcessTreeWindowFullscreen(pids []uint32) bool { return err == nil && isBorderlessFullscreenRect(style, rect, WindowRect(monitor.Monitor)) } -// ToggleProcessWindowFullscreen switches the selected display window between -// borderless fullscreen and windowed mode. -func ToggleProcessWindowFullscreen(pid uint32) (bool, error) { - return ToggleProcessTreeWindowFullscreen([]uint32{pid}) -} - // ToggleProcessTreeWindowFullscreen is ToggleProcessWindowFullscreen for a // process tree: the display window may belong to any of pids. func ToggleProcessTreeWindowFullscreen(pids []uint32) (bool, error) { diff --git a/internal/host/host_other.go b/internal/host/host_other.go index f9673dd..3a51243 100644 --- a/internal/host/host_other.go +++ b/internal/host/host_other.go @@ -37,10 +37,6 @@ func ProbeVulkanGPUs() []GPUInfo { return nil } -func PinProcessToPCores(pid uint32, mask uint64) error { - return SetProcessAffinityMask(pid, mask) -} - func SetProcessAffinityMask(pid uint32, mask uint64) error { return fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS) } @@ -52,7 +48,3 @@ func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) { func DisableProcessPowerThrottling(pid uint32) error { return fmt.Errorf("process power throttling control is only supported on Windows (current OS: %s)", runtime.GOOS) } - -func EnableWHPXElevated() error { - return fmt.Errorf("WHPX elevation is only supported on Windows (current OS: %s)", runtime.GOOS) -} diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 6c42092..a7d790b 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -3,7 +3,6 @@ package host import ( - "context" "encoding/binary" "fmt" "math/bits" @@ -38,11 +37,11 @@ var ( ) const ( - hkeyLocalMachine = 0x80000002 - keyRead = 0x20019 - regSZ = 1 - regExpandSZ = 2 - regMultiSZ = 7 + hkeyLocalMachine = 0x80000002 + keyRead = 0x20019 + regSZ = 1 + regExpandSZ = 2 + regMultiSZ = 7 processSetInformation = 0x0200 processQueryLimitedInformation = 0x1000 processPowerThrottlingClass = 4 @@ -197,11 +196,6 @@ func Inspect(dataRoot string) Report { return rep } -// PinProcessToPCores restricts the given PID's affinity mask to the given bitmask. -func PinProcessToPCores(pid uint32, mask uint64) error { - return SetProcessAffinityMask(pid, mask) -} - // SetProcessAffinityMask sets the Win32 processor affinity mask for pid. func SetProcessAffinityMask(pid uint32, mask uint64) error { if mask == 0 { @@ -273,17 +267,6 @@ func DisableProcessPowerThrottling(pid uint32) error { return nil } -// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows -// Hypervisor Platform (if missing) and set hypervisorlaunchtype to auto. -func EnableWHPXElevated() error { - return SetHypervisorBootElevated(context.Background(), true) -} - -func probeWHPX() WHPXState { - st, _ := probeWHPXAndFirmware() - return st -} - func probeWHPXAndFirmware() (WHPXState, bool) { firmwareVirt := probeFirmwareVirtEnabled() mod := syscall.NewLazyDLL("WinHvPlatform.dll") diff --git a/internal/host/hypervisor.go b/internal/host/hypervisor.go index b074105..61b0c73 100644 --- a/internal/host/hypervisor.go +++ b/internal/host/hypervisor.go @@ -157,10 +157,6 @@ func RecordPendingHypervisorBoot(dataRoot string, liveState WHPXState, enable bo return recordPendingHypervisorBootSession(dataRoot, liveState, enable, currentBootSession()) } -func recordPendingHypervisorBootAt(dataRoot string, liveState WHPXState, enable bool, bootEpoch int64) string { - return recordPendingHypervisorBootSession(dataRoot, liveState, enable, bootSession{EpochSec: bootEpoch}) -} - func recordPendingHypervisorBootSession(dataRoot string, liveState WHPXState, enable bool, sess bootSession) string { target := ResolvePendingHypervisorTarget(liveState, enable) pendingBootMu.Lock() @@ -208,10 +204,6 @@ func ReadPendingHypervisorBoot(dataRoot string, liveState WHPXState) string { return readPendingHypervisorBootSession(dataRoot, liveState, currentBootSession()) } -func readPendingHypervisorBootAt(dataRoot string, liveState WHPXState, bootEpoch int64) string { - return readPendingHypervisorBootSession(dataRoot, liveState, bootSession{EpochSec: bootEpoch}) -} - func readPendingHypervisorBootSession(dataRoot string, liveState WHPXState, sess bootSession) string { if !sess.valid() { return "" diff --git a/internal/host/hypervisor_test.go b/internal/host/hypervisor_test.go index 5d53262..9a9b19e 100644 --- a/internal/host/hypervisor_test.go +++ b/internal/host/hypervisor_test.go @@ -104,6 +104,15 @@ func TestPendingHypervisorBootLifecycle(t *testing.T) { } } +// The epoch-only helpers stand in for a boot session without a volatile marker. +func recordPendingHypervisorBootAt(dataRoot string, liveState WHPXState, enable bool, bootEpoch int64) string { + return recordPendingHypervisorBootSession(dataRoot, liveState, enable, bootSession{EpochSec: bootEpoch}) +} + +func readPendingHypervisorBootAt(dataRoot string, liveState WHPXState, bootEpoch int64) string { + return readPendingHypervisorBootSession(dataRoot, liveState, bootSession{EpochSec: bootEpoch}) +} + func TestPendingHypervisorBootUndoAcrossDataRoots(t *testing.T) { defer func() { pendingBootMu.Lock() @@ -185,4 +194,3 @@ func TestPendingHypervisorBootFastRebootAndSleepResilience(t *testing.T) { t.Fatalf("fallback fast reboot with reset TickMs must expire pending state, got %q", got) } } - diff --git a/internal/host/hypervisor_windows.go b/internal/host/hypervisor_windows.go index 7974aed..5b52ad5 100644 --- a/internal/host/hypervisor_windows.go +++ b/internal/host/hypervisor_windows.go @@ -68,10 +68,6 @@ func currentBootSession() bootSession { } } -func currentBootEpochSec() int64 { - return currentBootSession().EpochSec -} - // probeVolatileBootMarker reads the LastWriteTime of HKLM\HARDWARE\DESCRIPTION\System, // an in-memory REG_OPTION_VOLATILE hive recreated by the Windows kernel on every OS // boot. Unlike wall-clock minus GetTickCount64, it stays constant across S3 sleep, diff --git a/internal/host/progress_parse_test.go b/internal/host/progress_parse_test.go new file mode 100644 index 0000000..69bad39 --- /dev/null +++ b/internal/host/progress_parse_test.go @@ -0,0 +1,26 @@ +package host + +import "testing" + +func TestParseCtlLine(t *testing.T) { + // Formats from reims_util.rs:480-488 and its test at :777-786. + u, _ := ParseCtlLine("downloading the macOS Tahoe 26 recovery image: 45% of 2.0 GB") + if u.Kind != KindProgress || u.Step != "downloading the macOS Tahoe 26 recovery image" || u.Percent != 45 || u.Total != 2_000_000_000 { + t.Fatalf("percent line = %+v", u) + } + u, _ = ParseCtlLine("macos-tahoe: downloading OpenCore 1.0.8: 5% of 11 MB") + if u.Step != "macos-tahoe: downloading OpenCore 1.0.8" || u.Total != 11_000_000 { + t.Fatalf("ctl-prefixed line = %+v", u) + } + u, _ = ParseCtlLine("downloading the installer: 300 MB") + if u.Kind != KindProgress || u.Percent != -1 || u.Done != 300_000_000 { + t.Fatalf("size line = %+v", u) + } + u, _ = ParseCtlLine("creating the disk") + if u.Kind != KindNote || u.Message != "creating the disk" { + t.Fatalf("note = %+v", u) + } + if _, ok := ParseCtlLine(" "); ok { + t.Fatal("blank line") + } +} diff --git a/internal/host/smbios_memory.go b/internal/host/smbios_memory.go index 172d5d6..6e322f8 100644 --- a/internal/host/smbios_memory.go +++ b/internal/host/smbios_memory.go @@ -2,7 +2,6 @@ package host import ( "encoding/binary" - "fmt" ) // HostMemorySpec describes the host's physical memory speed and generation @@ -13,22 +12,6 @@ type HostMemorySpec struct { TypeName string `json:"type_name,omitempty"` } -// FormatMemorySpec returns a concise human-readable label such as -// "6400 MHz DDR5" or "3200 MHz", or "" when speed is unknown. -func FormatMemorySpec(spec *HostMemorySpec) string { - if spec == nil || spec.SpeedMHz <= 0 { - return "" - } - name := spec.TypeName - if name == "" && spec.MemoryType > 0 { - name = SMBIOSMemoryTypeName(spec.MemoryType) - } - if name != "" { - return fmt.Sprintf("%d MHz %s", spec.SpeedMHz, name) - } - return fmt.Sprintf("%d MHz", spec.SpeedMHz) -} - // SMBIOSMemoryTypeName maps DMTF SMBIOS Type 17 Memory Type codes to short // display names. Returns "" for unknown/unspecified codes. func SMBIOSMemoryTypeName(code int) string { diff --git a/internal/host/smbios_memory_test.go b/internal/host/smbios_memory_test.go index de0c837..5fb9ced 100644 --- a/internal/host/smbios_memory_test.go +++ b/internal/host/smbios_memory_test.go @@ -44,9 +44,6 @@ func TestParseSMBIOSType17DDR5ConfiguredSpeed(t *testing.T) { if spec.SpeedMHz != 6400 || spec.MemoryType != 34 || spec.TypeName != "DDR5" { t.Fatalf("got %+v, want 6400 MHz DDR5 (type 34)", spec) } - if got := FormatMemorySpec(spec); got != "6400 MHz DDR5" { - t.Fatalf("FormatMemorySpec = %q, want %q", got, "6400 MHz DDR5") - } } func TestParseSMBIOSType17FallsBackToRatedSpeed(t *testing.T) { @@ -86,7 +83,7 @@ func TestProbeHostMemorySpecLiveWindows(t *testing.T) { t.Skip("Windows live SMBIOS probe test") } spec := probeHostMemorySpec() - t.Logf("live Windows host memory spec: %+v (%q)", spec, FormatMemorySpec(spec)) + t.Logf("live Windows host memory spec: %+v", spec) if spec != nil && (spec.SpeedMHz < 200 || spec.SpeedMHz > 65535) { t.Fatalf("out-of-range live SpeedMHz: %+v", spec) } diff --git a/internal/host/stats.go b/internal/host/stats.go index 0ecd556..7615319 100644 --- a/internal/host/stats.go +++ b/internal/host/stats.go @@ -251,22 +251,6 @@ func resolveDiskPathFromVMToml(vmDir string) string { return filepath.Join(vmDir, "disk.qcow2") } -// readQCOW2VirtualSize reads the 8-byte big-endian virtual size from a QCOW2 -// header (magic "QFI\xfb", version 2 or 3, size at byte offset 24). -func readQCOW2VirtualSize(path string) (uint64, bool) { - size, _, _, ok := readQCOW2HeaderMeta(path) - return size, ok -} - -func readQCOW2HeaderMeta(path string) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) { - f, err := os.Open(path) - if err != nil { - return 0, false, 0, false - } - defer f.Close() - return decodeQCOW2HeaderMeta(f) -} - func decodeQCOW2HeaderMeta(f io.ReaderAt) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) { var hdr [104]byte n, err := f.ReadAt(hdr[:], 0) diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 8374445..485799c 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -76,10 +76,6 @@ var catalog = map[Locale]map[string]string{ "copy": "复制", "copyTechInfo": "复制技术信息", "core.preflight.whpx_irqchip_advice": "宿主不支持 nested-virt 属性且当前运行时未包含非致命降级补丁,启动虚拟机时将自动附加 kernel-irqchip=off", - "core.start.warn.offline_helper_skipped": "已跳过离线装机辅助盘挂载:{err}", - "core.start.warn.opencore_lang_failed": "未能向 OpenCore 写入客户机语言设置:{err}", - "core.start.warn.opencore_picker_failed": "未能更新 OpenCore 启动选择器配置:{err}", - "core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数", "dataRootChooseOther": "选择其他数据目录", "dataRootChooseTitle": "选择数据目录", "dataRootReadOnlyDetail": "详细信息", @@ -619,7 +615,6 @@ var catalog = map[Locale]map[string]string{ "tray.menu.suspend": "挂起(&P)", "tray.menu.toggle_fullscreen": "切换全屏", "tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次", - "tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态", "tray.notify.focus_fail": "找不到 {name} 的窗口", "tray.notify.force_stop_fail": "无法强制关机 {name}", "tray.notify.fullscreen_fail": "无法切换 {name} 全屏", @@ -632,8 +627,6 @@ var catalog = map[Locale]map[string]string{ "tray.notify.stop_fail": "无法关机 {name}", "tray.notify.suspend_fail": "无法挂起 {name}", "tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}", - "tray.running.many": "Reims-Go — {count} 台虚拟机运行中", - "tray.running.one": "Reims-Go — 1 台虚拟机运行中", "tray.state.broken": "配置损坏", "tray.state.resuming": "正在恢复…", "tray.state.running": "运行中", @@ -688,21 +681,16 @@ var catalog = map[Locale]map[string]string{ "viewLogs": "查看日志", "vm.already_running": "{name} 已在运行中", "vm.compact.done": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)", - "vm.compact.stop_first": "请先停止 {name} 再回收磁盘空间", "vm.empty": "当前没有已创建的虚拟机。", "vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。", "vm.install_guide.step2": "2. 回到「恢复」窗口,选「重新安装 macOS」,装到刚抹掉的磁盘上(中途会自动重启几次)。", "vm.install_guide.step3": "3. 看到「设置助理」后,运行 `reims-go vm eject {name}`(或在界面点「退出恢复模式」)移除安装盘,下次启动生效。", "vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):", "vm.resize.done": "{name}:虚拟磁盘已扩容 {before, number, .0} GB -> {after, number, .0} GB\n请在 macOS 终端执行以下命令扩展 APFS 容器:\n {cmd}", - "vm.resize.stop_first": "请先停止 {name} 再扩容虚拟磁盘", "vm.typed": "{count, plural, other {已敲入 # 个键。}}", "vmstart.compat.nested_virt": "[兼容] 当前 Windows 不支持嵌套虚拟化属性({code}),已自动启用 kernel-irqchip=off", "vmstart.nested_vmx.invalid": "无法读取嵌套虚拟化设置。虚拟机将按默认 CPU 设置启动。", "vmstart.nested_vmx.unavailable": "当前 Windows 宿主机和中断控制器设置无法启用嵌套虚拟化。", - "vmstart.pin.non_lpe": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)", - "vmstart.pin.pcores": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)", - "vmstart.pin.skipped": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿", "window.close.description": "关机将请求系统关闭。挂起会保存当前会话。", "window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。", "window.close.suspend": "挂起", @@ -781,10 +769,6 @@ var catalog = map[Locale]map[string]string{ "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", - "core.start.warn.offline_helper_skipped": "Offline install helper disk skipped: {err}", - "core.start.warn.opencore_lang_failed": "Could not apply macOS language to OpenCore: {err}", - "core.start.warn.opencore_picker_failed": "Could not update OpenCore boot picker: {err}", - "core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically", "dataRootChooseOther": "Choose another data folder", "dataRootChooseTitle": "Choose data folder", "dataRootReadOnlyDetail": "Details", @@ -1324,7 +1308,6 @@ var catalog = map[Locale]map[string]string{ "tray.menu.suspend": "Sus&pend", "tray.menu.toggle_fullscreen": "Toggle full screen", "tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again", - "tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}", "tray.notify.focus_fail": "Couldn't find the window of {name}", "tray.notify.force_stop_fail": "Couldn't force shut down {name}", "tray.notify.fullscreen_fail": "Couldn’t toggle full screen for {name}", @@ -1337,8 +1320,6 @@ var catalog = map[Locale]map[string]string{ "tray.notify.stop_fail": "Couldn't shut down {name}", "tray.notify.suspend_fail": "Couldn't suspend {name}", "tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}", - "tray.running.many": "Reims-Go — {count} VMs running", - "tray.running.one": "Reims-Go — 1 VM running", "tray.state.broken": "Broken", "tray.state.resuming": "Resuming…", "tray.state.running": "Running", @@ -1393,21 +1374,16 @@ var catalog = map[Locale]map[string]string{ "viewLogs": "View logs", "vm.already_running": "{name} is already running", "vm.compact.done": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)", - "vm.compact.stop_first": "stop {name} before compacting its disk", "vm.empty": "No virtual machines found.", "vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.", "vm.install_guide.step2": "2. Back in the Recovery window, choose 'Reinstall macOS' and install onto the disk you erased (it restarts a few times).", "vm.install_guide.step3": "3. When Setup Assistant appears, run `reims-go vm eject {name}` (or click 'Exit recovery mode') to remove the installer at next start.", "vm.install_guide.title": "macOS Setup Steps (Recovery UI):", "vm.resize.done": "{name}: expanded disk {before, number, .0} GB -> {after, number, .0} GB\nRun inside macOS Terminal to expand APFS:\n {cmd}", - "vm.resize.stop_first": "stop {name} before resizing its disk", "vm.typed": "{count, plural, one {Typed # key.} other {Typed # keys.}}", "vmstart.compat.nested_virt": "[compat] Host rejects nested-virtualization property ({code}); enabled kernel-irqchip=off automatically", "vmstart.nested_vmx.invalid": "The nested virtualization setting could not be read. Starting with the default CPU settings.", "vmstart.nested_vmx.unavailable": "Nested virtualization is unavailable with the current Windows host and interrupt controller settings.", - "vmstart.pin.non_lpe": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)", - "vmstart.pin.pcores": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)", - "vmstart.pin.skipped": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall", "window.close.description": "Shut down asks macOS to shut down. Suspend saves the session.", "window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", "window.close.suspend": "Suspend", @@ -1438,9 +1414,6 @@ var paramOrder = map[string][]string{ "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"}, "doctor.cow_chain.broken": {"vm", "depth", "path"}, "doctor.cow_chain.item": {"vm", "depth", "warn"}, "doctor.ecores.detail": {"count", "cpus"}, @@ -1574,7 +1547,6 @@ var paramOrder = map[string][]string{ "toastInstallerReady": {"v"}, "toastRuntimeReady": {"v"}, "toastSSHConfigWritten": {"alias"}, - "tray.notify.discard_suspend_fail": {"name"}, "tray.notify.focus_fail": {"name"}, "tray.notify.force_stop_fail": {"name"}, "tray.notify.fullscreen_fail": {"name"}, @@ -1585,7 +1557,6 @@ var paramOrder = map[string][]string{ "tray.notify.stop_fail": {"name"}, "tray.notify.suspend_fail": {"name"}, "tray.running": {"count"}, - "tray.running.many": {"count"}, "updateCapsuleAvailable": {"v"}, "updateCapsuleDownloadingPct": {"p"}, "updateCapsuleReady": {"v"}, @@ -1602,14 +1573,9 @@ var paramOrder = map[string][]string{ "validate.name_taken": {"name"}, "vm.already_running": {"name"}, "vm.compact.done": {"name", "before", "after", "saved"}, - "vm.compact.stop_first": {"name"}, "vm.install_guide.step3": {"name"}, "vm.resize.done": {"name", "before", "after", "cmd"}, - "vm.resize.stop_first": {"name"}, "vm.typed": {"count"}, "vmstart.compat.nested_virt": {"code"}, - "vmstart.pin.non_lpe": {"vcpus", "pthreads", "pid", "cores", "threads", "mask", "lpe"}, - "vmstart.pin.pcores": {"pid", "cores", "threads", "mask", "excluded"}, - "vmstart.pin.skipped": {"vcpus", "pthreads"}, "window.close.title": {"name"}, } diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index c12ab7b..112977c 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -95,14 +95,6 @@ func rewriteLegacyPositionalVerbs(s string) string { return b.String() } -// HasPluginLocale reports whether an active plugin pack provides translations for loc. -func HasPluginLocale(loc Locale) bool { - pluginCatalogMu.RLock() - _, ok := pluginCatalogs[loc] - pluginCatalogMu.RUnlock() - return ok -} - func primarySubtag(tag string) string { s := strings.ToLower(strings.TrimSpace(tag)) if idx := strings.IndexAny(s, "-_"); idx >= 0 { diff --git a/internal/macos/guest/guest.go b/internal/macos/guest/guest.go index 485fcfb..5d3f497 100644 --- a/internal/macos/guest/guest.go +++ b/internal/macos/guest/guest.go @@ -42,27 +42,6 @@ func SettingOn(vals map[string]any, key string) bool { return true } -// SettingOnInState reads a setting without starting a Manager. Explicit -// values on the new plugin win over the released former core record. -func SettingOnInState(st *plugin.StateFile, key string) bool { - if st == nil { - return true - } - for _, id := range []string{ID, builtin.IDCore} { - if rec := st.Plugins[id]; rec != nil { - if _, ok := rec.AppSettings[key]; ok { - return SettingOn(rec.AppSettings, key) - } - } - } - if key == SettingInstallGuide { - if rec := st.Plugins[LegacyInstallGuideID]; rec != nil { - return rec.Enabled - } - } - return true -} - func settingOn(cb builtin.HostCallbacks, key string) bool { if cb.GetSetting == nil { return true diff --git a/internal/macos/guest/guest_test.go b/internal/macos/guest/guest_test.go index 3a643e0..6b3e9f9 100644 --- a/internal/macos/guest/guest_test.go +++ b/internal/macos/guest/guest_test.go @@ -79,9 +79,6 @@ func TestMigrateFilesPreservesChoicesBeforeRegistration(t *testing.T) { }}); err != nil { t.Fatal(err) } - if SettingOnInState(plugin.ReadState(root), SettingWHPXFallback) { - t.Fatal("old off switch not honoured") - } if err := MigrateFiles(root); err != nil { t.Fatal(err) } @@ -94,7 +91,10 @@ func TestMigrateFilesPreservesChoicesBeforeRegistration(t *testing.T) { if string(first) != string(second) { t.Fatal("second migration rewrote state") } - st := plugin.ReadState(root) + st, err := store.Load() + if err != nil { + t.Fatal(err) + } rec := st.Plugins[ID] if rec == nil || !rec.Enabled { t.Fatalf("guest record = %+v", rec) diff --git a/internal/macos/installer/events.go b/internal/macos/installer/events.go index 8d03f96..a4fbc0a 100644 --- a/internal/macos/installer/events.go +++ b/internal/macos/installer/events.go @@ -59,6 +59,3 @@ func percentOf(done, total int64) float64 { } return float64(done) * 100 / float64(total) } - -// ParseCtlLine delegates engine progress parsing to the host progress package. -func ParseCtlLine(line string) (Update, bool) { return host.ParseCtlLine(line) } diff --git a/internal/macos/installer/installer_test.go b/internal/macos/installer/installer_test.go index 9f51fc5..426781c 100644 --- a/internal/macos/installer/installer_test.go +++ b/internal/macos/installer/installer_test.go @@ -227,29 +227,6 @@ func TestListCachedSkipsHiddenFiles(t *testing.T) { } } -func TestParseCtlLine(t *testing.T) { - // Formats from reims_util.rs:480-488 and its test at :777-786. - u, _ := ParseCtlLine("downloading the macOS Tahoe 26 recovery image: 45% of 2.0 GB") - if u.Kind != KindProgress || u.Step != "downloading the macOS Tahoe 26 recovery image" || u.Percent != 45 || u.Total != 2_000_000_000 { - t.Fatalf("percent line = %+v", u) - } - u, _ = ParseCtlLine("macos-tahoe: downloading OpenCore 1.0.8: 5% of 11 MB") - if u.Step != "macos-tahoe: downloading OpenCore 1.0.8" || u.Total != 11_000_000 { - t.Fatalf("ctl-prefixed line = %+v", u) - } - u, _ = ParseCtlLine("downloading the installer: 300 MB") - if u.Kind != KindProgress || u.Percent != -1 || u.Done != 300_000_000 { - t.Fatalf("size line = %+v", u) - } - u, _ = ParseCtlLine("creating the disk") - if u.Kind != KindNote || u.Message != "creating the disk" { - t.Fatalf("note = %+v", u) - } - if _, ok := ParseCtlLine(" "); ok { - t.Fatal("blank line") - } -} - // TestLockExcludesReimsCtl checks the lock against the real reims-ctl: while we // hold installers/.lock, `reims-ctl downloads delete` must refuse a file as // "being downloaded" (downloads.rs:139-159). Runs only with REIMS_GO_TEST_CTL diff --git a/internal/macos/macosdriver/clone.go b/internal/macos/macosdriver/clone.go index bead74d..90c289b 100644 --- a/internal/macos/macosdriver/clone.go +++ b/internal/macos/macosdriver/clone.go @@ -91,7 +91,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s return fmt.Errorf("source disk %s: %w", srcDisk, err) } rep := host.Inspect(cfg.DataRoot) - for _, issue := range reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfg.Locale) { + for _, issue := range reims.ValidateCreate(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfg.Locale) { if issue.Field == "name" { return fmt.Errorf("invalid clone name %q: %s", cloneName, issue.Message) } diff --git a/internal/macos/macosdriver/driver.go b/internal/macos/macosdriver/driver.go index 20bec16..0405319 100644 --- a/internal/macos/macosdriver/driver.go +++ b/internal/macos/macosdriver/driver.go @@ -225,7 +225,7 @@ func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRe } cfg := d.getConfig() rep := host.Inspect(cfg.DataRoot) - issues := reims.ValidateCreateLocalized(opts, rep, cfg.Locale) + issues := reims.ValidateCreate(opts, rep, cfg.Locale) out := make([]driver.ValidationIssue, 0, len(issues)) for _, is := range issues { out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message}) @@ -276,7 +276,7 @@ func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req driver.SetReques } cfg := d.getConfig() rep := host.Inspect(cfg.DataRoot) - issues := reims.ValidateSetLocalized(opts, cur, rep, cfg.Locale) + issues := reims.ValidateSet(opts, cur, rep, cfg.Locale) out := make([]driver.ValidationIssue, 0, len(issues)) for _, is := range issues { out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message}) diff --git a/internal/macos/macosdriver/optimizations.go b/internal/macos/macosdriver/optimizations.go index 0078556..08e3e94 100644 --- a/internal/macos/macosdriver/optimizations.go +++ b/internal/macos/macosdriver/optimizations.go @@ -47,17 +47,6 @@ func DriverOptimizations(rep host.Report, runtimePatches []string) []host.Optimi return out } -// EvaluateOptimizations preserves the existing host-page ordering. -func EvaluateOptimizations(rep host.Report, runtimePatches []string) []host.Optimization { - core := host.EvaluateCoreOptimizations(rep) - extra := DriverOptimizations(rep, runtimePatches) - if len(core) == 0 { - return extra - } - out := append([]host.Optimization{core[0]}, extra...) - return append(out, core[1:]...) -} - func (d *ReimsMacOSDriver) EvaluateOptimizations(_ context.Context, rep host.Report) []host.Optimization { var patches []string if _, active, err := d.startClient(); err == nil { diff --git a/internal/macos/macosdriver/optimizations_test.go b/internal/macos/macosdriver/optimizations_test.go index fbd6928..5687fcb 100644 --- a/internal/macos/macosdriver/optimizations_test.go +++ b/internal/macos/macosdriver/optimizations_test.go @@ -20,8 +20,8 @@ func TestEvaluateOptimizationsWin10AndWin11(t *testing.T) { win10 := host.Report{WHPX: host.WHPXReady, HasHybridCores: true, PCoreCount: 8, ECoreCount: 4, NeedsColdRebootWorkaround: true, WHPXCaps: host.WHPXCapabilities{APICEmulation: true, KernelIrqchipAvailable: true}, RecommendedGPU: &host.GPUInfo{Name: "NVIDIA GeForce RTX 4070 Ti", Kind: host.GPUDiscrete, VulkanICD: "nv-vk64.json"}} - opts := EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch"}) - if o := findOpt(t, opts, "pcore_pin"); o.Status != "recommended" || !o.Supported { + opts := DriverOptimizations(win10, []string{"qemu-whpx-win10-compat.patch"}) + if o := findOpt(t, host.EvaluateCoreOptimizations(win10), "pcore_pin"); o.Status != "recommended" || !o.Supported { t.Fatalf("pcore_pin = %+v", o) } if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "win10-needs-patch" { @@ -30,26 +30,26 @@ func TestEvaluateOptimizationsWin10AndWin11(t *testing.T) { if o := findOpt(t, opts, "cold_reboot"); o.Status != "auto" { t.Fatalf("cold_reboot = %+v", o) } - opts = EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch", "qemu-whpx-win10-startup-ipis.patch"}) + opts = DriverOptimizations(win10, []string{"qemu-whpx-win10-compat.patch", "qemu-whpx-win10-startup-ipis.patch"}) if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "experimental" || !o.Supported { t.Fatalf("patched kernel_irqchip = %+v", o) } win11 := host.Report{WHPX: host.WHPXReady, WHPXCaps: host.WHPXCapabilities{ModernOS: true, APICEmulation: true, KernelIrqchipAvailable: true, NestedVirtProperty: false, NestedVirtProbeError: "0x80370302"}} - opts = EvaluateOptimizations(win11, nil) + opts = DriverOptimizations(win11, nil) if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "0x80370302" { t.Fatalf("win11 broken nested = %+v", o) } if o := findOpt(t, opts, "cold_reboot"); o.Status != "unavailable" { t.Fatalf("win11 cold_reboot = %+v", o) } - opts = EvaluateOptimizations(win11, []string{"qemu-whpx-nested-virt-nonfatal.patch"}) + opts = DriverOptimizations(win11, []string{"qemu-whpx-nested-virt-nonfatal.patch"}) if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "recommended" || !o.Supported { t.Fatalf("win11 patched = %+v", o) } win11.WHPXCaps.NestedVirtProperty = true win11.WHPXCaps.NestedVirtProbeError = "" - opts = EvaluateOptimizations(win11, nil) + opts = DriverOptimizations(win11, nil) if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "recommended" || !o.Supported { t.Fatalf("win11 full support = %+v", o) } diff --git a/internal/macos/macosdriver/storage.go b/internal/macos/macosdriver/storage.go index a142dbc..6007925 100644 --- a/internal/macos/macosdriver/storage.go +++ b/internal/macos/macosdriver/storage.go @@ -165,7 +165,7 @@ func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name stri } defer releaseDisk() cfg := d.getConfig() - res, err := reims.CompactDiskWithOptions(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, opts, stdout, stderr) + res, err := reims.CompactDisk(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, opts, stdout, stderr) if err != nil { return driver.DiskCompactResult{}, err } diff --git a/internal/macos/opencore/lang.go b/internal/macos/opencore/lang.go index c0bcfd4..28336c4 100644 --- a/internal/macos/opencore/lang.go +++ b/internal/macos/opencore/lang.go @@ -23,21 +23,6 @@ type Preset struct { LabelEN string `json:"label_en"` } -// Presets returns the built-in macOS prev-lang:kbd choices. -// `:0` pairs the locale with the standard US keyboard layout so terminal -// commands in macOS Recovery / Setup Assistant stay predictable; `:252` uses -// OpenCore's Pinyin layout ID. -func Presets() []Preset { - return []Preset{ - {Value: "zh-Hans:0", LabelZH: "简体中文(美式键盘,推荐)", LabelEN: "Simplified Chinese (US Keyboard)"}, - {Value: "zh-Hans:252", LabelZH: "简体中文(拼音键盘)", LabelEN: "Simplified Chinese (Pinyin)"}, - {Value: "zh-Hant:0", LabelZH: "繁體中文(美式键盘)", LabelEN: "Traditional Chinese (US Keyboard)"}, - {Value: "en-US:0", LabelZH: "English (US)", LabelEN: "English (US)"}, - {Value: "ja-JP:0", LabelZH: "日本語(美式键盘)", LabelEN: "Japanese (US Keyboard)"}, - {Value: "ko-KR:0", LabelZH: "한국어(美式键盘)", LabelEN: "Korean (US Keyboard)"}, - } -} - // DefaultGuestLang chooses the default macOS prev-lang:kbd matching the app UI locale. func DefaultGuestLang(locale i18n.Locale) string { resolved := strings.ToLower(string(i18n.ResolveLocale(string(locale)))) diff --git a/internal/macos/reims/compat_test.go b/internal/macos/reims/compat_test.go index 6fc9c3b..fdc8ef2 100644 --- a/internal/macos/reims/compat_test.go +++ b/internal/macos/reims/compat_test.go @@ -282,13 +282,6 @@ func TestBuildDeleteArgs(t *testing.T) { } } -func TestRedactLogLine(t *testing.T) { - got := RedactLogLine("mac 52:54:00:12:34:56 serial C02ABCDEFGH") - if got != "mac [redacted] serial [redacted]" { - t.Fatalf("RedactLogLine = %q", got) - } -} - func TestCleanAbortedCreateDir(t *testing.T) { dataDir := t.TempDir() vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "macos-tahoe") @@ -474,11 +467,11 @@ func TestDiskImportAndCoWArgs(t *testing.T) { if conv != "convert -O qcow2 -o "+wantOpts+" in.vmdk out.qcow2" { t.Fatalf("BuildConvertToQCOW2Args = %q", conv) } - cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2"), " ") + cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2", DefaultQCOW2CreateOptions()), " ") if cow != "create -f qcow2 -b golden.qcow2 -F qcow2 -o "+wantOpts+" cow-dev.qcow2" { t.Fatalf("BuildCoWOverlayArgs = %q", cow) } - cmp := strings.Join(BuildCompactDiskArgs("disk.qcow2", "disk.compact.tmp"), " ") + cmp := strings.Join(BuildCompactDiskArgs("disk.qcow2", "disk.compact.tmp", DefaultQCOW2CreateOptions()), " ") if cmp != "convert -p -f qcow2 -O qcow2 -o "+wantOpts+" disk.qcow2 disk.compact.tmp" { t.Fatalf("BuildCompactDiskArgs = %q", cmp) } diff --git a/internal/macos/reims/disk_import.go b/internal/macos/reims/disk_import.go index 44ba8bf..6344717 100644 --- a/internal/macos/reims/disk_import.go +++ b/internal/macos/reims/disk_import.go @@ -223,15 +223,9 @@ func BuildResizeDiskArgs(diskPath, sizeArg string) []string { return []string{"resize", diskPath, sizeArg} } -// BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2` arguments -// using the default qcow2 creation options. -func BuildCompactDiskArgs(srcPath, dstPath string) []string { - return BuildCompactDiskArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions()) -} - -// BuildCompactDiskArgsWithOptions builds `qemu-img convert -p -f qcow2 -O qcow2` +// BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2` // arguments preserving explicit qcow2 creation options. -func BuildCompactDiskArgsWithOptions(srcPath, dstPath string, opts QCOW2CreateOptions) []string { +func BuildCompactDiskArgs(srcPath, dstPath string, opts QCOW2CreateOptions) []string { args := []string{"convert", "-p", "-f", "qcow2", "-O", "qcow2"} if optStr := opts.OptionString(); optStr != "" { args = append(args, "-o", optStr) @@ -247,30 +241,14 @@ func NeedsDiskConversion(srcPath string) bool { } // BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments -// using the canonical default qcow2 creation options. +// using the default qcow2 creation options. func BuildConvertToQCOW2Args(srcPath, dstPath string) []string { - return BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions()) -} - -// BuildConvertToQCOW2ArgsWithOptions constructs `qemu-img convert -O qcow2` -// arguments with explicit qcow2 creation options. -func BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath string, opts QCOW2CreateOptions) []string { - args := []string{"convert", "-O", "qcow2"} - if optStr := opts.OptionString(); optStr != "" { - args = append(args, "-o", optStr) - } - return append(args, srcPath, dstPath) + return []string{"convert", "-O", "qcow2", "-o", DefaultQCOW2CreateOptions().OptionString(), srcPath, dstPath} } // BuildCoWOverlayArgs constructs `qemu-img create -f qcow2 -b -F qcow2` -// arguments using the default qcow2 creation options. -func BuildCoWOverlayArgs(backingPath, overlayPath string) []string { - return BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, DefaultQCOW2CreateOptions()) -} - -// BuildCoWOverlayArgsWithOptions constructs `qemu-img create -f qcow2 -b -F qcow2` // arguments with explicit qcow2 creation options inherited from the backing image. -func BuildCoWOverlayArgsWithOptions(backingPath, overlayPath string, opts QCOW2CreateOptions) []string { +func BuildCoWOverlayArgs(backingPath, overlayPath string, opts QCOW2CreateOptions) []string { args := []string{"create", "-f", "qcow2", "-b", backingPath, "-F", "qcow2"} if optStr := opts.OptionString(); optStr != "" { args = append(args, "-o", optStr) @@ -319,7 +297,7 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac if err != nil { return fmt.Errorf("inspect backing qcow2 options: %w", err) } - cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, opts)...) + cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath, opts)...) configureCmd(cmd) cmd.Env = env if stdout != nil { @@ -372,14 +350,7 @@ func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath, }, nil } -// CompactDisk rewrites a stopped VM's standalone qcow2 image into a freshly -// compacted sparse qcow2 file, verifies it with `qemu-img check`, and atomically -// swaps it into place to reclaim deleted/TRIMmed host disk space. -func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, stdout, stderr io.Writer) (DiskCompactResult, error) { - return CompactDiskWithOptions(ctx, qemuImgPath, env, diskPath, CompactDiskOptions{}, stdout, stderr) -} - -func CompactDiskWithOptions(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) { +func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) { before, err := host.InspectDiskUsage(diskPath) if err != nil { return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err) @@ -420,7 +391,7 @@ func CompactDiskWithOptions(ctx context.Context, qemuImgPath string, env []strin _ = os.Remove(tmpPath) defer os.Remove(tmpPath) - cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgsWithOptions(diskPath, tmpPath, opts)...) + cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgs(diskPath, tmpPath, opts)...) configureCmd(cmd) cmd.Env = env if stdout != nil { diff --git a/internal/macos/reims/disk_ops_test.go b/internal/macos/reims/disk_ops_test.go index 295e52b..c990fe3 100644 --- a/internal/macos/reims/disk_ops_test.go +++ b/internal/macos/reims/disk_ops_test.go @@ -62,8 +62,8 @@ func TestDiskRewriteRefusesSnapshotsAndBackingFiles(t *testing.T) { if err := os.WriteFile(disk, hdr, 0o644); err != nil { t.Fatal(err) } - _, compactErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, nil, nil) - _, optimizeErr := CompactDiskWithOptions(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{EnableExtendedL2: true}, nil, nil) + _, compactErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{}, nil, nil) + _, optimizeErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{EnableExtendedL2: true}, nil, nil) for _, err := range []error{compactErr, optimizeErr} { if err == nil || !strings.Contains(err.Error(), want) { t.Fatalf("rewrite error = %v, want %q", err, want) @@ -331,7 +331,7 @@ func TestResizeAndCompactRealQemuImg(t *testing.T) { if res.NewVirtualBytes != 128<<20 { t.Fatalf("NewVirtualBytes = %d, want %d", res.NewVirtualBytes, 128<<20) } - cmp, err := CompactDisk(context.Background(), qemuImg, nil, disk, nil, nil) + cmp, err := CompactDisk(context.Background(), qemuImg, nil, disk, CompactDiskOptions{}, nil, nil) if err != nil { t.Fatalf("CompactDisk: %v", err) } @@ -355,7 +355,7 @@ func TestResizeAndCompactRealQemuImg(t *testing.T) { t.Fatalf("unexpected beforeOpts: %+v", beforeOpts) } - if _, err := CompactDisk(context.Background(), qemuImg, nil, customDisk, nil, nil); err != nil { + if _, err := CompactDisk(context.Background(), qemuImg, nil, customDisk, CompactDiskOptions{}, nil, nil); err != nil { t.Fatalf("CompactDisk(custom): %v", err) } afterCompactOpts, err := InspectQCOW2CreateOptions(context.Background(), qemuImg, nil, customDisk) diff --git a/internal/macos/reims/network.go b/internal/macos/reims/network.go index 33b0437..2b96c9e 100644 --- a/internal/macos/reims/network.go +++ b/internal/macos/reims/network.go @@ -127,17 +127,6 @@ type mainNetwork struct { func isMainNetworkID(id string) bool { return id == "net0" || id == PacketBridgeID } -func setQEMUField(value, key, replacement string) string { - parts := qemuFields(value) - for i, part := range parts { - if strings.HasPrefix(part, key+"=") { - parts[i] = key + "=" + replacement - } - parts[i] = strings.ReplaceAll(parts[i], "\x00", ",,") - } - return strings.Join(parts, ",") -} - func findMainNetwork(args []string) (mainNetwork, error) { var n mainNetwork for i := 0; i < len(args); i++ { @@ -435,27 +424,3 @@ func PacketBridgeUnixTokens(mac, socketPath string) ([]string, error) { "-device", fmt.Sprintf("virtio-net-pci,netdev=%s,id=net0,mac=%s,addr=0x3", PacketBridgeID, strings.ToLower(hw.String())), }, nil } - -// BuildPacketBridgeExtra 保留用于兼容旧版调用与回归测试。 -func BuildPacketBridgeExtra(extra, generated string, port int) (string, error) { - if port < 1 || port > 65535 { - return "", networkError("packet_port", nil) - } - args, err := cleanMainNetwork(extra) - if err != nil { - return "", err - } - all, err := ShellArgs(generated) - if err != nil { - return "", err - } - actual, err := findMainNetwork(all) - if err != nil { - return "", err - } - if actual.backends != 1 || actual.devices != 1 { - return "", networkError("args_main_unknown", nil) - } - args = append(args, "-netdev", fmt.Sprintf("stream,id=%s,server=off,addr.type=inet,addr.host=127.0.0.1,addr.port=%d,reconnect-ms=1000", PacketBridgeID, port), "-device", setQEMUField(actual.device, "netdev", PacketBridgeID)) - return JoinShellArgs(args), nil -} diff --git a/internal/macos/reims/network_test.go b/internal/macos/reims/network_test.go index 707b0f1..da93140 100644 --- a/internal/macos/reims/network_test.go +++ b/internal/macos/reims/network_test.go @@ -66,10 +66,8 @@ func TestNetworkModesAndUnixTokens(t *testing.T) { } // Legacy TCP bridge detection still works for pre-upgrade running/suspended VMs. - legacy, err := BuildPacketBridgeExtra("-cpu host", "qemu -netdev user,id=net0 -device virtio-net-pci,netdev=net0,id=net0,mac="+mac+",addr=0x3", 12363) - if err != nil { - t.Fatalf("BuildPacketBridgeExtra: %v", err) - } + legacy := "-cpu host -netdev stream,id=" + PacketBridgeID + ",server=off,addr.type=inet,addr.host=127.0.0.1,addr.port=12363,reconnect-ms=1000" + + " -device virtio-net-pci,netdev=" + PacketBridgeID + ",id=net0,mac=" + mac + ",addr=0x3" if got := NetworkMode(false, legacy); got != "bridge" { t.Fatalf("NetworkMode(legacy tcp) = %q, want bridge", got) } diff --git a/internal/macos/reims/redact.go b/internal/macos/reims/redact.go deleted file mode 100644 index 306d33b..0000000 --- a/internal/macos/reims/redact.go +++ /dev/null @@ -1,9 +0,0 @@ -package reims - -import "github.com/Nwflower/reims-go/internal/host" - -// RedactLogLine preserves the engine package API while sharing the host redactor. -func RedactLogLine(line string) string { return host.RedactLine(line) } - -// RedactText applies RedactLogLine across a multi-line text block. -func RedactText(s string) string { return host.RedactText(s) } diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index 66a28f7..0cdaa5f 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -215,13 +215,8 @@ func ParseSizeGB(raw string) (float64, bool) { return v, true } -// ValidateCreate performs pre-save validation aligned with VZVirtualMachineConfiguration.validate(). -func ValidateCreate(o CreateOpts, rep host.Report) []ValidationIssue { - return ValidateCreateLocalized(o, rep, i18n.EnUS) -} - -// ValidateCreateLocalized performs pre-save validation with localized issue messages. -func ValidateCreateLocalized(o CreateOpts, rep host.Report, loc i18n.Locale) []ValidationIssue { +// ValidateCreate performs pre-save validation with localized issue messages. +func ValidateCreate(o CreateOpts, rep host.Report, loc i18n.Locale) []ValidationIssue { var issues []ValidationIssue if o.NetworkMode != "" && o.NetworkMode != "off" && o.NetworkMode != "nat" && o.NetworkMode != "bridge" { issues = append(issues, ValidationIssue{Field: "network_mode", Code: "invalid_network_mode", Message: i18n.T(loc, "validate.invalid_network_mode")}) @@ -290,13 +285,8 @@ func ValidateCreateLocalized(o CreateOpts, rep host.Report, loc i18n.Locale) []V return issues } -// ValidateSet validates configuration edits before invoking `reims-ctl set`. -func ValidateSet(o SetOpts, current VMDetail, rep host.Report) []ValidationIssue { - return ValidateSetLocalized(o, current, rep, i18n.EnUS) -} - -// ValidateSetLocalized validates configuration edits with localized issue messages. -func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n.Locale) []ValidationIssue { +// ValidateSet validates configuration edits with localized issue messages. +func ValidateSet(o SetOpts, current VMDetail, rep host.Report, loc i18n.Locale) []ValidationIssue { var issues []ValidationIssue if strings.TrimSpace(o.Name) == "" { issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: i18n.T(loc, "validate.missing_name")}) diff --git a/internal/macos/reims/suspend.go b/internal/macos/reims/suspend.go index 26c9f20..c74210c 100644 --- a/internal/macos/reims/suspend.go +++ b/internal/macos/reims/suspend.go @@ -206,21 +206,6 @@ func shortRev(rev string) string { return rev } -// HasIncomingDeferArg reports whether extraArgs contains `-incoming defer`. -func HasIncomingDeferArg(extraArgs string) bool { - tokens := splitShellTokens(extraArgs) - for i := 0; i < len(tokens); i++ { - tok := tokens[i] - if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" { - return true - } - if tok == "-incoming=defer" { - return true - } - } - return false -} - // StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer` // arguments from QEMU extra-args while leaving all other arguments intact. func StripIncomingDeferArgs(existing string) string { diff --git a/internal/macos/reims/suspend_test.go b/internal/macos/reims/suspend_test.go index 0549c80..ee28d48 100644 --- a/internal/macos/reims/suspend_test.go +++ b/internal/macos/reims/suspend_test.go @@ -90,11 +90,8 @@ func TestSuspendStateLifecycle(t *testing.T) { } func TestIncomingDeferArgsIdempotent(t *testing.T) { - if HasIncomingDeferArg("") || HasIncomingDeferArg("-machine q35") { - t.Fatal("unexpected HasIncomingDeferArg=true") - } m := MergeIncomingDeferArgs(`-drive "id=x,file=C:/a b/c.img"`) - if !HasIncomingDeferArg(m) { + if !strings.HasSuffix(m, " -incoming defer") { t.Fatalf("expected -incoming defer in %q", m) } if m2 := MergeIncomingDeferArgs(m); m2 != m { @@ -126,7 +123,7 @@ func TestSuspendLegacyRuntimeStillRequiresExactVersion(t *testing.T) { } func TestValidateSetRejectsSuspendedVM(t *testing.T) { - issues := ValidateSetLocalized( + issues := ValidateSet( SetOpts{Name: "tahoe", CPUs: 6}, VMDetail{Name: "tahoe", State: "suspended", CPUs: 8, Memory: "8G"}, host.Report{LogicalCPUs: 16, TotalRAMGB: 32}, diff --git a/internal/packetbridge/start_guard_other.go b/internal/packetbridge/start_guard_other.go index c01191b..b49b548 100644 --- a/internal/packetbridge/start_guard_other.go +++ b/internal/packetbridge/start_guard_other.go @@ -4,4 +4,3 @@ package packetbridge func AcquireBridgeStart() (func(), error) { return func() {}, nil } func AcquireNpcapInstall() (func(), error) { return func() {}, nil } -func AcquireVMStart() (func(), error) { return func() {}, nil } diff --git a/internal/packetbridge/start_guard_windows.go b/internal/packetbridge/start_guard_windows.go index 13d8e62..a15107c 100644 --- a/internal/packetbridge/start_guard_windows.go +++ b/internal/packetbridge/start_guard_windows.go @@ -61,11 +61,6 @@ func AcquireNpcapInstall() (func(), error) { return acquireGuard(lockPath, statePath, true) } -// AcquireVMStart 保留向后兼容别名,语义已收敛为共享读锁(供桥接 VM 启动使用)。 -func AcquireVMStart() (func(), error) { - return AcquireBridgeStart() -} - func acquireGuard(lockPath, statePath string, exclusive bool) (func(), error) { if err := checkTrackedInstaller(statePath); err != nil { return nil, err diff --git a/internal/plugin/assets.go b/internal/plugin/assets.go index 6adc38f..d4b4393 100644 --- a/internal/plugin/assets.go +++ b/internal/plugin/assets.go @@ -125,7 +125,7 @@ func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { ct = "image/svg+xml; charset=utf-8" data = SanitizeSVG(data) } else { - if err := ValidateThemeCSSSafetyInDir(string(data), filepath.Dir(fullPath)); err != nil { + if err := ValidateThemeCSSSafety(string(data), filepath.Dir(fullPath)); err != nil { http.Error(w, "unsafe stylesheet blocked", http.StatusForbidden) return } diff --git a/internal/plugin/blockers_test.go b/internal/plugin/blockers_test.go index e15682b..51c561c 100644 --- a/internal/plugin/blockers_test.go +++ b/internal/plugin/blockers_test.go @@ -191,7 +191,7 @@ func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) { {"traversal-url", `.rg-p-shell { background: url("../../secret.png"); }`}, } for _, tc := range badCSS { - if err := ValidateThemeCSSSafety(tc.css); err == nil { + if err := ValidateThemeCSSSafety(tc.css, ""); err == nil { t.Errorf("ValidateThemeCSSSafety(%s) expected error, got nil", tc.name) } } @@ -204,10 +204,10 @@ func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) { if err := os.WriteFile(filepath.Join(dir, "assets", "bg.png"), []byte("png"), 0o644); err != nil { t.Fatal(err) } - if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil { + if err := ValidateThemeCSSSafety(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil { t.Errorf("valid local asset rejected: %v", err) } - if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil { + if err := ValidateThemeCSSSafety(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil { t.Error("missing local asset should be rejected") } diff --git a/internal/plugin/kernel_test.go b/internal/plugin/kernel_test.go index 99f6bbe..38c7d49 100644 --- a/internal/plugin/kernel_test.go +++ b/internal/plugin/kernel_test.go @@ -445,10 +445,12 @@ func TestArgLedgerReconcilePreserveUserArgsAndStripOnDisable(t *testing.T) { } // Disable thirdparty.tweak -> its fragment is stripped cleanly, user + builtin remain. - stripped, changed := StripPluginFromArgs(res.ExtraArgs, reloaded, "thirdparty.tweak") - if !changed { + delete(active, "thirdparty.tweak") + after := ReconcileStartIntents(res.ExtraArgs, reloaded, active, intents[:1]) + if !after.Changed { t.Fatal("expected change on strip") } + stripped := after.ExtraArgs if strings.Contains(stripped, "usb-tablet") { t.Fatalf("plugin fragment not stripped: %q", stripped) } diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index 13bbff5..e54dfa5 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -596,19 +596,6 @@ func reconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu return res } -// StripPluginFromArgs removes all fragments owned by pluginID from currentExtraArgs -// and updates ledger, leaving user args and other plugins' args intact. -func StripPluginFromArgs(currentExtraArgs string, ledger *ArgLedger, pluginID string) (string, bool) { - if ledger == nil || len(ledger.Owners[pluginID]) == 0 { - return strings.TrimSpace(currentExtraArgs), false - } - sub := &ArgLedger{Owners: map[string][]ArgFragment{pluginID: ledger.Owners[pluginID]}} - tokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), sub) - delete(ledger.Owners, pluginID) - next := strings.TrimSpace(strings.Join(tokens, " ")) - return next, next != strings.TrimSpace(currentExtraArgs) -} - func fragWins(candidate, existing ArgFragment) bool { if candidate.Builtin != existing.Builtin { return candidate.Builtin diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index ade6d7a..5612917 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -1326,7 +1326,7 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload { if installDir != "" && th.Stylesheet != "" { if full, err := safeJoin(installDir, th.Stylesheet); err == nil { if raw, err := os.ReadFile(full); err == nil { - if ValidateThemeCSSSafetyInDir(string(raw), filepath.Dir(full)) == nil { + if ValidateThemeCSSSafety(string(raw), filepath.Dir(full)) == nil { payload.CSS = string(raw) } } diff --git a/internal/plugin/manager_sidecar_test.go b/internal/plugin/manager_sidecar_test.go index 1024549..2bd296e 100644 --- a/internal/plugin/manager_sidecar_test.go +++ b/internal/plugin/manager_sidecar_test.go @@ -19,7 +19,7 @@ import ( "time" "github.com/Nwflower/reims-go/internal/driver" - "github.com/Nwflower/reims-go/internal/macos/reims" + "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/pkg/pluginsdk" ) @@ -148,7 +148,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) { Trust: plugin.TrustOfficial, PublicKey: pub, }}, - RedactFn: reims.RedactText, + RedactFn: host.RedactText, }) if err != nil { t.Fatal(err) @@ -268,7 +268,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) { // 4. Market redline: reject Apple .ipsw inside zip. redlineZip := makePluginZip(t, map[string][]byte{ - "plugin.json": manifestJSON, + "plugin.json": manifestJSON, "Universal.ipsw": []byte("nope"), }, nil, false) if _, err := mgr.InstallLocalArchive(context.Background(), redlineZip, plugin.PackageInstallOptions{}); err == nil { @@ -289,7 +289,7 @@ func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) { dataRoot := t.TempDir() layout := plugin.NewPluginsLayout(dataRoot) reg := plugin.NewRegistry(nil) - broker := plugin.NewBroker(layout, reg, reims.RedactText) + broker := plugin.NewBroker(layout, reg, host.RedactText) notified := make(chan string, 1) broker.SetNotifier(func(pid, title, body string) { @@ -361,7 +361,7 @@ func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) { } // 3. Diagnostics collection enforces host redaction of MAC & serial (§4.2, §7.1). - diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", reims.RedactText) + diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", host.RedactText) if len(diags) != 1 { t.Fatalf("expected 1 diag entry, got %d", len(diags)) } diff --git a/internal/plugin/scanner.go b/internal/plugin/scanner.go index be55b18..e02596b 100644 --- a/internal/plugin/scanner.go +++ b/internal/plugin/scanner.go @@ -403,7 +403,7 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { if ext == ".css" && !declaredThemeCSS[rel] && !inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes { if b, rErr := os.ReadFile(full); rErr == nil { - if err := ValidateThemeCSSSafetyInDir(string(b), filepath.Dir(full)); err != nil { + if err := ValidateThemeCSSSafety(string(b), filepath.Dir(full)); err != nil { addHard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err), fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err), fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err)) @@ -843,12 +843,12 @@ func describePermission(perm string) (LocalizedText, LocalizedText) { if strings.HasPrefix(perm, "net:") { host := strings.TrimPrefix(perm, "net:") return LocalizedText{ - ZhCN: "访问指定网络主机", - EnUS: "Access declared network host", - }, LocalizedText{ - ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host), - EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host), - } + ZhCN: "访问指定网络主机", + EnUS: "Access declared network host", + }, LocalizedText{ + ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host), + EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host), + } } switch perm { case "ui:script": diff --git a/internal/plugin/state.go b/internal/plugin/state.go index 1cff3c1..f3de906 100644 --- a/internal/plugin/state.go +++ b/internal/plugin/state.go @@ -145,18 +145,6 @@ func (s *StateStore) Save(st *StateFile) error { return nil } -// ReadState reads `/plugins/state.json` without starting a Manager, -// for processes such as `vm start` that only need a setting or two. It returns -// nil when the file is unreadable; callers then use their defaults, as the -// GUI's Manager does. -func ReadState(dataRoot string) *StateFile { - st, err := NewStateStore(NewPluginsLayout(dataRoot).Root).Load() - if err != nil { - return nil - } - return st -} - // --- Safe-mode startup sentinel (§9) --- // SentinelPath returns `/plugins/.startup-sentinel`. diff --git a/internal/plugin/theme_css.go b/internal/plugin/theme_css.go index 3ab5029..b50f1a8 100644 --- a/internal/plugin/theme_css.go +++ b/internal/plugin/theme_css.go @@ -12,26 +12,20 @@ import ( ) var ( - reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`) - reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`) - reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`) - reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`) - reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`) - reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`) - reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`) + reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`) + reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`) + reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`) + reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`) + reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`) + reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`) + reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`) ) // ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments, // CSS-escaped url()/image-set()/expression() bypasses, remote @import, and -// external or unsafe data: URLs. -func ValidateThemeCSSSafety(css string) error { - return ValidateThemeCSSSafetyInDir(css, "") -} - -// ValidateThemeCSSSafetyInDir performs ValidateThemeCSSSafety and, when rootDir -// is non-empty, also verifies that every relative url()/@import resolves to an -// existing file inside rootDir. -func ValidateThemeCSSSafetyInDir(css, rootDir string) error { +// external or unsafe data: URLs. When rootDir is non-empty, every relative +// url()/@import must also resolve to an existing file inside rootDir. +func ValidateThemeCSSSafety(css, rootDir string) error { if strings.Contains(strings.ToLower(css), ""), negotiates capabilities, and waits for a SHUTDOWN event. It -// returns true iff the VM exited because the guest requested a reset -// (`reason == "guest-reset"` under `-no-reboot`). -func WatchForGuestReset(ctx context.Context, addr string) (bool, error) { - reason, err := WatchShutdownReason(ctx, addr) - if err != nil { - return false, err - } - return reason == "guest-reset", nil -} - // WatchShutdownReason waits for QEMU's SHUTDOWN event over QMP and returns its // reason (e.g. "guest-reset", "guest-shutdown", "host-qmp-quit"), or "" on EOF. func WatchShutdownReason(ctx context.Context, addr string) (string, error) { diff --git a/internal/qmp/watcher_test.go b/internal/qmp/watcher_test.go index 011b9ff..943ae27 100644 --- a/internal/qmp/watcher_test.go +++ b/internal/qmp/watcher_test.go @@ -66,7 +66,7 @@ func TestRebootSocketPathFallback(t *testing.T) { } } -func runMockQMPUnix(t *testing.T, eventJSON string) (bool, error) { +func runMockQMPUnix(t *testing.T, eventJSON string) (string, error) { t.Helper() const sockPath = "reims-go-reboot.sock" ln, err := net.Listen("unix", sockPath) @@ -91,25 +91,17 @@ func runMockQMPUnix(t *testing.T, eventJSON string) (bool, error) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() - return WatchForGuestReset(ctx, "unix:"+sockPath) + return WatchShutdownReason(ctx, "unix:"+sockPath) } -func TestWatchForGuestReset(t *testing.T) { +func TestWatchShutdownReason(t *testing.T) { // Unix socket addresses have a small byte limit. The isolated working // directory lets the mock and watcher use the same short relative address. t.Chdir(t.TempDir()) - reset, err := runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"guest-reset"}}`) - if err != nil || !reset { - t.Fatalf("guest-reset: got reset=%v err=%v, want true nil", reset, err) - } - - reset, err = runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"guest-shutdown"}}`) - if err != nil || reset { - t.Fatalf("guest-shutdown: got reset=%v err=%v, want false nil", reset, err) - } - - reset, err = runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":false,"reason":"host-ui"}}`) - if err != nil || reset { - t.Fatalf("host-ui: got reset=%v err=%v, want false nil", reset, err) + for _, want := range []string{"guest-reset", "guest-shutdown", "host-ui"} { + got, err := runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"`+want+`"}}`) + if err != nil || got != want { + t.Fatalf("reason = %q, %v, want %q", got, err, want) + } } } diff --git a/internal/selfupdate/selfupdate.go b/internal/selfupdate/selfupdate.go index 07652a5..6ada3d1 100644 --- a/internal/selfupdate/selfupdate.go +++ b/internal/selfupdate/selfupdate.go @@ -71,17 +71,10 @@ func Writable(dir string) error { } // Swap installs newExe at target (see Target; usually exe itself) and moves -// the running exe aside to ".old" (or a timestamped name when an earlier -// one is still locked). A file already at target is replaced. On any failure -// the original executable is left in place. -func Swap(exe, target, newExe string) error { - return SwapWithOptions(exe, target, newExe, false) -} - -// SwapWithOptions behaves like Swap, except when keepOld is true it never -// deletes an existing ".old" backup (falling back to a timestamped -// ".old-" name instead). -func SwapWithOptions(exe, target, newExe string, keepOld bool) error { +// the running exe aside to ".old", or to a timestamped name when an +// earlier backup is still locked or keepOld asks to preserve it. A file already +// at target is replaced. On any failure the original executable stays in place. +func Swap(exe, target, newExe string, keepOld bool) error { staged := target + ".new" if err := copyFile(newExe, staged); err != nil { os.Remove(staged) diff --git a/internal/selfupdate/selfupdate_test.go b/internal/selfupdate/selfupdate_test.go index 10ade82..d2f10cd 100644 --- a/internal/selfupdate/selfupdate_test.go +++ b/internal/selfupdate/selfupdate_test.go @@ -30,7 +30,7 @@ func TestSwapAndCleanup(t *testing.T) { write(t, newExe, "new build") write(t, exe+".old", "left over from an earlier update") - if err := Swap(exe, exe, newExe); err != nil { + if err := Swap(exe, exe, newExe, false); err != nil { t.Fatal(err) } if got := read(t, exe); got != "new build" { @@ -56,7 +56,7 @@ func TestSwapLeavesExeOnFailure(t *testing.T) { dir := t.TempDir() exe := filepath.Join(dir, "reims-go.exe") write(t, exe, "old build") - if err := Swap(exe, exe, filepath.Join(dir, "missing.exe")); err == nil { + if err := Swap(exe, exe, filepath.Join(dir, "missing.exe"), false); err == nil { t.Fatal("a missing download must fail") } if got := read(t, exe); got != "old build" { @@ -107,7 +107,7 @@ func TestSwapRenamesReleaseFile(t *testing.T) { write(t, newExe, "v0.2.6") target := Target(exe, filepath.Base(newExe)) - if err := Swap(exe, target, newExe); err != nil { + if err := Swap(exe, target, newExe, false); err != nil { t.Fatal(err) } if got := read(t, target); got != "v0.2.6" { @@ -138,7 +138,7 @@ func TestSwapKeepOldAndCleanupStaging(t *testing.T) { write(t, exe+".old", "stable backup") write(t, newExe, "new dev-2") - if err := SwapWithOptions(exe, exe, newExe, true); err != nil { + if err := Swap(exe, exe, newExe, true); err != nil { t.Fatal(err) } if got := read(t, exe); got != "new dev-2" { diff --git a/internal/testutil/fakedriver/harness.go b/internal/testutil/fakedriver/harness.go index 9ad20d8..d5efe87 100644 --- a/internal/testutil/fakedriver/harness.go +++ b/internal/testutil/fakedriver/harness.go @@ -34,7 +34,7 @@ func NewHarness(t *testing.T) *Harness { broker.SetVMStateHandler(func(_ string, rep plugin.ReportedVMState) error { return states.Report(driver.ReportedStateFromPlugin(rep)) }) - router := driver.NewRouterWithDataRoot(reg, func() string { return root }) + router := driver.NewRouter(reg, func() string { return root }) router.SetStateTable(states) h := &Harness{Registry: reg, Broker: broker, Router: router, States: states, DataRoot: root, StopFile: filepath.Join(t.TempDir(), "stop"), t: t} diff --git a/internal/version/version.go b/internal/version/version.go index fec814c..c17239f 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -109,12 +109,6 @@ type ghAsset struct { URL string `json:"browser_download_url"` } -// ParseSemver parses a tag like "v0.2.1" or "0.2.1-rc1" into major/minor/patch. -func ParseSemver(v string) (major, minor, patch int, ok bool) { - major, minor, patch, _, ok = parseSemverFull(v) - return major, minor, patch, ok -} - func parseSemverFull(v string) (major, minor, patch int, pre string, ok bool) { s := strings.TrimSpace(v) s = strings.TrimPrefix(s, "v") @@ -242,12 +236,6 @@ func Compare(a, b string) int { return comparePrerelease(aPre, bPre) } -// CheckUpdate queries GitHub Releases for the newest stable (non-draft, -// non-prerelease) application release tagged "vX.Y.Z". -func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, error) { - return s.CheckUpdateChannel(ctx, current, ChannelStable) -} - type releaseCandidate struct { rel *ghRelease ver string @@ -322,9 +310,9 @@ func isSameBaseDevBuild(a, b string) bool { strings.HasPrefix(strings.ToLower(bPre), "dev-") } -// CheckUpdateChannel queries GitHub Releases for the newest eligible Reims-Go +// CheckUpdate queries GitHub Releases for the newest eligible Reims-Go // release on the requested channel ("stable", "alpha", or "dev"). -func (s Source) CheckUpdateChannel(ctx context.Context, current, channel string) (UpdateInfo, error) { +func (s Source) CheckUpdate(ctx context.Context, current, channel string) (UpdateInfo, error) { if current == "" { current = Version } diff --git a/internal/version/version_test.go b/internal/version/version_test.go index e031034..056d9d7 100644 --- a/internal/version/version_test.go +++ b/internal/version/version_test.go @@ -61,7 +61,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) { defer srv.Close() src := Source{APIBase: srv.URL, Repo: "Nwflower/Reims-Go", Client: srv.Client()} - info, err := src.CheckUpdate(context.Background(), "v0.2.1") + info, err := src.CheckUpdate(context.Background(), "v0.2.1", ChannelStable) if err != nil { t.Fatalf("CheckUpdate: %v", err) } @@ -79,7 +79,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) { } // Same version reports up to date. - upToDate, err := src.CheckUpdate(context.Background(), "v0.2.2") + upToDate, err := src.CheckUpdate(context.Background(), "v0.2.2", ChannelStable) if err != nil { t.Fatalf("CheckUpdate(same): %v", err) } @@ -89,7 +89,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) { // Prerelease of the released stable version upgrades to stable. for _, pre := range []string{"v0.2.2-alpha.1", "v0.2.2-dev-66da194"} { - preInfo, err := src.CheckUpdate(context.Background(), pre) + preInfo, err := src.CheckUpdate(context.Background(), pre, ChannelStable) if err != nil { t.Fatalf("CheckUpdate(%s): %v", pre, err) } @@ -99,7 +99,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) { } // Prerelease of a newer version does not downgrade to an older stable release. - ahead, err := src.CheckUpdate(context.Background(), "v0.2.3-dev-66da194") + ahead, err := src.CheckUpdate(context.Background(), "v0.2.3-dev-66da194", ChannelStable) if err != nil { t.Fatalf("CheckUpdate(ahead): %v", err) } @@ -155,7 +155,7 @@ func TestCheckUpdateChannels(t *testing.T) { src := Source{APIBase: srv.URL, Repo: "Nwflower/Reims-Go", Client: srv.Client()} // Stable channel ignores alpha and dev. - st, err := src.CheckUpdateChannel(context.Background(), "v0.2.8", ChannelStable) + st, err := src.CheckUpdate(context.Background(), "v0.2.8", ChannelStable) if err != nil { t.Fatalf("stable: %v", err) } @@ -164,7 +164,7 @@ func TestCheckUpdateChannels(t *testing.T) { } // Alpha channel picks v0.2.9-alpha.1 (ignoring dev). - al, err := src.CheckUpdateChannel(context.Background(), "v0.2.8", ChannelAlpha) + al, err := src.CheckUpdate(context.Background(), "v0.2.8", ChannelAlpha) if err != nil { t.Fatalf("alpha: %v", err) } @@ -173,7 +173,7 @@ func TestCheckUpdateChannels(t *testing.T) { } // Dev channel extracts version from rolling dev asset and detects update across non-monotonic SHAs. - dv, err := src.CheckUpdateChannel(context.Background(), "v0.2.9-dev-fffffff", ChannelDev) + dv, err := src.CheckUpdate(context.Background(), "v0.2.9-dev-fffffff", ChannelDev) if err != nil { t.Fatalf("dev: %v", err) } @@ -182,7 +182,7 @@ func TestCheckUpdateChannels(t *testing.T) { } // Dev channel reports up to date when SHA matches. - dvSame, err := src.CheckUpdateChannel(context.Background(), "v0.2.9-dev-0123456", ChannelDev) + dvSame, err := src.CheckUpdate(context.Background(), "v0.2.9-dev-0123456", ChannelDev) if err != nil { t.Fatalf("dev same: %v", err) } diff --git a/internal/vmstart/core.go b/internal/vmstart/core.go index 4880972..b8fa272 100644 --- a/internal/vmstart/core.go +++ b/internal/vmstart/core.go @@ -5,14 +5,12 @@ package vmstart import ( "bufio" "context" - "fmt" "os" "strconv" "strings" "time" "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/i18n" ) func parseSizeGB(raw string) (float64, bool) { @@ -78,25 +76,6 @@ func waitForCommitMemory(ctx context.Context, memory string, timeout, pollInterv } } -// PinQEMU applies the safe host affinity plan and returns a human log line. -func PinQEMU(loc i18n.Locale, rep host.Report, pid, vcpus int) string { - plan := host.SelectSafeAffinity(rep, vcpus) - if plan.Mode == "all" { - return i18n.M(loc, "vmstart.pin.skipped", i18n.Vars{"vcpus": vcpus, "pthreads": plan.PThreads}) - } - err := host.PinProcessToPCores(uint32(pid), plan.Mask) - if plan.Mode == "non_lpe" { - if err != nil { - return fmt.Sprintf("[CPU] Warning: P+E core pinning failed for PID %d: %v", pid, err) - } - return i18n.M(loc, "vmstart.pin.non_lpe", i18n.Vars{"vcpus": vcpus, "pthreads": plan.PThreads, "pid": pid, "cores": plan.CoreCount, "threads": plan.ThreadCount, "mask": plan.MaskHex, "lpe": rep.LPECoreCount}) - } - if err != nil { - return fmt.Sprintf("[CPU] Warning: P-core pinning failed for PID %d: %v", pid, err) - } - return i18n.M(loc, "vmstart.pin.pcores", i18n.Vars{"pid": pid, "cores": plan.CoreCount, "threads": plan.ThreadCount, "mask": plan.MaskHex, "excluded": rep.ECoreCount + rep.LPECoreCount}) -} - // LineWriter turns command output into one log call per non-empty line. type LineWriter func(string) diff --git a/locales/en-US/native.json b/locales/en-US/native.json index a0100fb..124aa75 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -259,12 +259,6 @@ "name" ] }, - "vm.resize.stop_first": { - "message": "stop {name} before resizing its disk", - "$params": [ - "name" - ] - }, "vm.resize.done": { "message": "{name}: expanded disk {before, number, .0} GB -> {after, number, .0} GB\nRun inside macOS Terminal to expand APFS:\n {cmd}", "$params": [ @@ -274,12 +268,6 @@ "cmd" ] }, - "vm.compact.stop_first": { - "message": "stop {name} before compacting its disk", - "$params": [ - "name" - ] - }, "vm.compact.done": { "message": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)", "$params": [ @@ -511,13 +499,6 @@ "backend" ] }, - "tray.running.one": "Reims-Go — 1 VM running", - "tray.running.many": { - "message": "Reims-Go — {count} VMs running", - "$params": [ - "count" - ] - }, "tray.running": { "message": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}", "$params": [ @@ -570,12 +551,6 @@ "name" ] }, - "tray.notify.discard_suspend_fail": { - "message": "Couldn't discard saved state for {name}", - "$params": [ - "name" - ] - }, "tray.notify.stop_fail": { "message": "Couldn't shut down {name}", "$params": [ @@ -842,35 +817,6 @@ "code" ] }, - "vmstart.pin.skipped": { - "message": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall", - "$params": [ - "vcpus", - "pthreads" - ] - }, - "vmstart.pin.non_lpe": { - "message": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)", - "$params": [ - "vcpus", - "pthreads", - "pid", - "cores", - "threads", - "mask", - "lpe" - ] - }, - "vmstart.pin.pcores": { - "message": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)", - "$params": [ - "pid", - "cores", - "threads", - "mask", - "excluded" - ] - }, "affinity.eco_suffix": ", EcoQoS disabled", "affinity.applied.pcores": { "message": "[CPU] Pinned QEMU (PID {pid}) to P-cores ({count} logical CPUs, mask {mask}{eco})", @@ -1098,25 +1044,6 @@ }, "err.affinity.empty_mask": "Select at least 1 logical processor", "core.preflight.whpx_irqchip_advice": "Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied", - "core.start.warn.offline_helper_skipped": { - "message": "Offline install helper disk skipped: {err}", - "$params": [ - "err" - ] - }, - "core.start.warn.opencore_picker_failed": { - "message": "Could not update OpenCore boot picker: {err}", - "$params": [ - "err" - ] - }, - "core.start.warn.opencore_lang_failed": { - "message": "Could not apply macOS language to OpenCore: {err}", - "$params": [ - "err" - ] - }, - "core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically", "validate.invalid_guest_lang": "Invalid guest language code (expected format like zh-Hans:0 or en-US:0)", "validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings", "err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support", diff --git a/locales/en-US/plugins.json b/locales/en-US/plugins.json index d3219bb..363b1fe 100644 --- a/locales/en-US/plugins.json +++ b/locales/en-US/plugins.json @@ -39,7 +39,6 @@ "pluginThemePackLabel": "Theme pack", "pluginNewScheme": "New scheme", "pluginColorSchemes": "Color schemes", - "pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp", "pluginDeleteScheme": "Delete scheme", "pluginExternalSection": "Installed plugins", "pluginLinkDevBtn": "Link plugin dev folder", @@ -74,7 +73,6 @@ "pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.", "pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data", "pluginMarketInstall": "Install", - "pluginMarketUpdate": "Update to v{version}", "pluginMarketInstalled": "Installed", "pluginMarketIncompatible": "Incompatible", "pluginMarketWithdrawn": "Withdrawn", @@ -96,7 +94,6 @@ "pluginScanMoreItems": "...and {count} more", "pluginScanInstallConfirm": "Proceed with install", "pluginScanBlockedBtn": "Blocked — cannot install", - "pluginScanLoading": "Scanning plugin package…", "pluginFailScan": "Couldn’t scan plugin", "pluginPermCount": { "message": "{count, plural, one {# permission} other {# permissions}}", diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 65cba79..c9f06ae 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -67,7 +67,6 @@ "message": "{count, plural, one {# older version} other {# older versions}}", "$comment": "镜像页面折叠的旧点版本计数按钮" }, - "installersEmpty": "No images downloaded yet", "installersPartial": "Partly downloaded", "installersResume": "Resume", "installersDownload": "Download", @@ -89,9 +88,6 @@ "installersQueued": "Queued", "installersQueuedForVM": "Queued for {vm}", "installersWaitingVM": "{vm} waiting", - "footerMem": "Memory {pct}%", - "footerMemAvail": "{avail} GB free", - "footerDisk": "Disk {gb} GB free", "updateDownloadInstall": "Download and install", "updateReleaseNotes": "Release notes", "updateDownloadingSub": "Downloading {v}", @@ -117,12 +113,9 @@ "storageRuntimes": "Reims-Go", "welcomeTitle": "Create your first macOS VM", "welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes", - "welcomeCheckHost": "Set up Engine first →", "back": "Back", "next": "Next", "choose": "Browse…", - "guestToolsConnected": "Connected", - "guestToolsReady": "Configured", "hostRuntime": "Runtime", "hostGPUs": "Graphics cards", "language": "Language", @@ -139,7 +132,6 @@ "appUpdateChannelAlpha": "Alpha", "appUpdateChannelDev": "Dev", "appCheckUpdate": "Check for updates", - "appDownloadUpdate": "Download", "appUpdateLookupFailed": "Couldn’t check GitHub for updates", "aboutDiscord": "Discord community", "aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins", @@ -191,7 +183,6 @@ "vmDir": "Folder", "sourceInstaller": "Local installer image (.img / .dmg)", "sourceDisk": "Existing virtual disk (.qcow2)", - "offlineListFailed": "Couldn’t read Apple’s release list", "networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking", "macosVersion": "macOS version", "diskSize": "Disk size", @@ -204,12 +195,10 @@ "gpuSelect": "GPU", "gpuAutoOption": "Automatic (prefers discrete)", "enableAudio": "Audio", - "enableNetwork": "Network (NAT)", "sshPort": "SSH forward port", "enableLogs": "Keep graphics and serial logs", "startAfterCreate": "Start after creating", "settingsTitle": "{name}", - "gtInstallCmd": "Install command", "networkTitle": "Network", "logLevelDesc": "Raise only when troubleshooting", "secondsUnit": "s", @@ -250,7 +239,6 @@ "displayGroup": "Displays", "resCustom": "Custom", "resCustomSub": "Width × height", - "resFullscreen": "Full screen", "resNativeBadge": "Native", "resScaleToFitWindow": "Scale to fit window", "resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600", @@ -319,8 +307,6 @@ "affinitySummaryPCores": "P-Cores ({count}T · {mask})", "affinitySummaryNonLPE": "P + E ({count}T · {mask})", "affinitySummaryCustom": "Custom ({count}T · {mask})", - "failAffinity": "Could not update processor affinity", - "networkDesc": "Uses the Windows network connection", "sshForward": "SSH port forwarding", "sshOffDesc": "Log in to macOS over SSH from Windows", "sshNeedsNetwork": "Turn on the network first", @@ -361,8 +347,6 @@ "optKernelIrqchipNestedErr": "Not supported by this Windows ({code}); Auto keeps it off", "optKernelIrqchipUnavailable": "Not supported on this PC", "optSchedTitle": "Windows processor scheduling", - "optSchedPrograms": "Programs", - "optSchedBackground": "Background services", "optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)", "optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)", "optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)", @@ -395,7 +379,6 @@ "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", "diskControllerVirtioHint": "Lower overhead but experimental; switch back to NVMe if you hit problems", @@ -436,11 +419,6 @@ "hostAudioMissingOut": "No speakers or headphones found; the VM will be silent", "hostAudioMissingIn": "No microphone found; macOS will record silence", "audioTroubleshootNote": "If audio crackles, set the Windows sound format to 48000 Hz. If the mic is silent, check Windows Privacy › Microphone", - "statsCPU": "QEMU CPU", - "statsMemory": "Host RAM", - "statsDisk": "Disk usage", - "statsUptime": "Uptime", - "statsDiskSub": "{actual} actual / {virtual} max", "effectImmediate": "Immediate", "effectNextStart": "Next start", "themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 6132c64..664be53 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -259,12 +259,6 @@ "name" ] }, - "vm.resize.stop_first": { - "message": "请先停止 {name} 再扩容虚拟磁盘", - "$params": [ - "name" - ] - }, "vm.resize.done": { "message": "{name}:虚拟磁盘已扩容 {before, number, .0} GB -> {after, number, .0} GB\n请在 macOS 终端执行以下命令扩展 APFS 容器:\n {cmd}", "$params": [ @@ -274,12 +268,6 @@ "cmd" ] }, - "vm.compact.stop_first": { - "message": "请先停止 {name} 再回收磁盘空间", - "$params": [ - "name" - ] - }, "vm.compact.done": { "message": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)", "$params": [ @@ -511,13 +499,6 @@ "backend" ] }, - "tray.running.one": "Reims-Go — 1 台虚拟机运行中", - "tray.running.many": { - "message": "Reims-Go — {count} 台虚拟机运行中", - "$params": [ - "count" - ] - }, "tray.running": { "message": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}", "$params": [ @@ -570,12 +551,6 @@ "name" ] }, - "tray.notify.discard_suspend_fail": { - "message": "无法放弃 {name} 的挂起状态", - "$params": [ - "name" - ] - }, "tray.notify.stop_fail": { "message": "无法关机 {name}", "$params": [ @@ -842,35 +817,6 @@ "code" ] }, - "vmstart.pin.skipped": { - "message": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿", - "$params": [ - "vcpus", - "pthreads" - ] - }, - "vmstart.pin.non_lpe": { - "message": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)", - "$params": [ - "vcpus", - "pthreads", - "pid", - "cores", - "threads", - "mask", - "lpe" - ] - }, - "vmstart.pin.pcores": { - "message": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)", - "$params": [ - "pid", - "cores", - "threads", - "mask", - "excluded" - ] - }, "affinity.eco_suffix": ",已禁用 EcoQoS 节流", "affinity.applied.pcores": { "message": "[CPU] 已将 QEMU (PID {pid}) 绑定到 P 核({count} 个逻辑处理器,掩码 {mask}{eco})", @@ -1098,25 +1044,6 @@ }, "err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器", "core.preflight.whpx_irqchip_advice": "宿主不支持 nested-virt 属性且当前运行时未包含非致命降级补丁,启动虚拟机时将自动附加 kernel-irqchip=off", - "core.start.warn.offline_helper_skipped": { - "message": "已跳过离线装机辅助盘挂载:{err}", - "$params": [ - "err" - ] - }, - "core.start.warn.opencore_picker_failed": { - "message": "未能更新 OpenCore 启动选择器配置:{err}", - "$params": [ - "err" - ] - }, - "core.start.warn.opencore_lang_failed": { - "message": "未能向 OpenCore 写入客户机语言设置:{err}", - "$params": [ - "err" - ] - }, - "core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数", "validate.invalid_guest_lang": "客户机系统语言标识格式无效(如 zh-Hans:0、en-US:0)", "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", "err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本", diff --git a/locales/zh-CN/plugins.json b/locales/zh-CN/plugins.json index 5954c67..b3aa6db 100644 --- a/locales/zh-CN/plugins.json +++ b/locales/zh-CN/plugins.json @@ -39,7 +39,6 @@ "pluginThemePackLabel": "主题包", "pluginNewScheme": "新建配色方案", "pluginColorSchemes": "配色方案", - "pluginColorSchemesHint": "修改种子色派生整套界面色阶", "pluginDeleteScheme": "删除方案", "pluginExternalSection": "已安装插件", "pluginLinkDevBtn": "链接插件开发目录", @@ -74,7 +73,6 @@ "pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址", "pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引", "pluginMarketInstall": "安装", - "pluginMarketUpdate": "更新至 v{version}", "pluginMarketInstalled": "已安装", "pluginMarketIncompatible": "不兼容", "pluginMarketWithdrawn": "已撤回", @@ -96,7 +94,6 @@ "pluginScanMoreItems": "另有 {count} 项已折叠", "pluginScanInstallConfirm": "确认导入安装", "pluginScanBlockedBtn": "已拦截,无法安装", - "pluginScanLoading": "正在扫描插件包…", "pluginFailScan": "插件安全扫描失败", "pluginPermCount": { "message": "{count, plural, other {# 项权限}}", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 96a4453..6a1e680 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -67,7 +67,6 @@ "message": "{count, plural, other {# 个旧版本}}", "$comment": "镜像页面折叠的旧点版本计数按钮" }, - "installersEmpty": "还没有下载任何镜像", "installersPartial": "未下载完", "installersResume": "继续下载", "installersDownload": "下载", @@ -89,9 +88,6 @@ "installersQueued": "排队中", "installersQueuedForVM": "为 {vm} 排队中", "installersWaitingVM": "{vm} 等待使用", - "footerMem": "内存 {pct}%", - "footerMemAvail": "可用 {avail} GB", - "footerDisk": "磁盘可用 {gb} GB", "updateDownloadInstall": "下载并安装", "updateReleaseNotes": "发行说明", "updateDownloadingSub": "正在下载 {v}", @@ -117,12 +113,9 @@ "storageRuntimes": "Reims-Go", "welcomeTitle": "创建第一台 macOS 虚拟机", "welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置", - "welcomeCheckHost": "先完成内核环境配置 →", "back": "上一步", "next": "下一步", "choose": "浏览…", - "guestToolsConnected": "已连接", - "guestToolsReady": "已配置", "hostRuntime": "运行时", "hostGPUs": "显卡", "language": "语言", @@ -139,7 +132,6 @@ "appUpdateChannelAlpha": "Alpha", "appUpdateChannelDev": "Dev", "appCheckUpdate": "检查更新", - "appDownloadUpdate": "前往下载", "appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新", "aboutDiscord": "Discord 社区", "aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发", @@ -191,7 +183,6 @@ "vmDir": "存放目录", "sourceInstaller": "本地安装器镜像(.img / .dmg)", "sourceDisk": "已有虚拟磁盘(.qcow2)", - "offlineListFailed": "无法读取 Apple 的版本列表", "networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网", "macosVersion": "macOS 版本", "diskSize": "磁盘上限", @@ -204,12 +195,10 @@ "gpuSelect": "显卡", "gpuAutoOption": "自动(优先独显)", "enableAudio": "音频", - "enableNetwork": "网络(NAT)", "sshPort": "SSH 转发端口", "enableLogs": "记录图形与串口日志", "startAfterCreate": "创建后立即启动", "settingsTitle": "{name}", - "gtInstallCmd": "安装命令", "networkTitle": "网络", "logLevelDesc": "排查问题时再调高", "secondsUnit": "秒", @@ -250,7 +239,6 @@ "displayGroup": "显示器", "resCustom": "自定义", "resCustomSub": "宽 × 高", - "resFullscreen": "全屏", "resNativeBadge": "原生", "resScaleToFitWindow": "缩放以适应窗口", "resInvalid": "格式为 宽x高,例如 2560x1600", @@ -319,8 +307,6 @@ "affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})", "affinitySummaryNonLPE": "P + E 核({count} 线程 · {mask})", "affinitySummaryCustom": "自定义({count} 线程 · {mask})", - "failAffinity": "设置处理器相关性失败", - "networkDesc": "通过 Windows 的网络连接上网", "sshForward": "SSH 端口转发", "sshOffDesc": "从 Windows 用 SSH 登录 macOS", "sshNeedsNetwork": "需要先开启网络", @@ -361,8 +347,6 @@ "optKernelIrqchipNestedErr": "当前 Windows 不支持({code}),「自动」会保持关闭", "optKernelIrqchipUnavailable": "当前电脑不支持", "optSchedTitle": "Windows 处理器调度", - "optSchedPrograms": "程序优先", - "optSchedBackground": "后台服务", "optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)", "optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)", "optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)", @@ -395,7 +379,6 @@ "fullscreenLaunch": "无边框全屏启动", "fullscreenLaunchHint": "启动后直接进入无边框全屏", "fullscreenDecoupledHint": "窗口铺满屏幕;下方分辨率可独立设为原生或超采样 HiDPI(如 4K 1.5× = 5120×2880),由 GPU 自动缩放", - "guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效", "guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错", "guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言", "diskControllerVirtioHint": "VirtIO 开销更低,仍属实验性;遇到问题请改回 NVMe", @@ -436,11 +419,6 @@ "hostAudioMissingOut": "没有检测到扬声器或耳机,虚拟机将没有声音", "hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音", "audioTroubleshootNote": "有爆音时,把 Windows 声音格式设为 48000 Hz;麦克风没声音时,检查 Windows「隐私 › 麦克风」权限", - "statsCPU": "QEMU CPU", - "statsMemory": "宿主机内存", - "statsDisk": "磁盘占用", - "statsUptime": "运行时长", - "statsDiskSub": "实际 {actual} / 上限 {virtual}", "effectImmediate": "立即生效", "effectNextStart": "下次启动生效", "themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用",