From 0afeac693c976de600f0d928af9403cc570ccd02 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Mon, 30 Nov 2026 00:00:55 +0800 Subject: [PATCH] feat(gui): guide macOS installation in the VM window --- frontend/src/App.tsx | 7 +- frontend/src/components/VMPage.tsx | 130 +-- frontend/src/i18n.ts | 26 +- frontend/src/styles/app.css | 30 +- frontend/src/wails.ts | 1 + frontend/wailsjs/go/models.ts | 2 + internal/app/app.go | 64 +- internal/app/install_guide.go | 182 +++++ internal/app/install_guide_test.go | 65 ++ internal/app/thumbnail_flow.go | 1 + internal/installguide/appearance_windows.go | 753 ++++++++++++++++++ internal/installguide/dialog_windows.go | 238 ++++++ internal/installguide/guide.go | 391 +++++++++ internal/installguide/overlay_other.go | 7 + internal/installguide/overlay_windows.go | 463 +++++++++++ internal/installguide/overlay_windows_test.go | 329 ++++++++ internal/installguide/picker_windows.go | 53 ++ internal/installguide/progress.go | 105 +++ internal/installguide/session_windows.go | 146 ++++ internal/installguide/session_windows_test.go | 150 ++++ 20 files changed, 2973 insertions(+), 170 deletions(-) create mode 100644 internal/app/install_guide.go create mode 100644 internal/app/install_guide_test.go create mode 100644 internal/installguide/appearance_windows.go create mode 100644 internal/installguide/dialog_windows.go create mode 100644 internal/installguide/guide.go create mode 100644 internal/installguide/overlay_other.go create mode 100644 internal/installguide/overlay_windows.go create mode 100644 internal/installguide/overlay_windows_test.go create mode 100644 internal/installguide/picker_windows.go create mode 100644 internal/installguide/progress.go create mode 100644 internal/installguide/session_windows.go create mode 100644 internal/installguide/session_windows_test.go diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index ed8ee36..9a9c96e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -109,8 +109,12 @@ export const App: React.FC = () => { useEffect(() => { document.documentElement.dataset.theme = theme + events.emitTheme(theme) + }, [theme]) + + useEffect(() => { document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full' - }, [theme, reducedMotion]) + }, [reducedMotion]) useEffect(() => { const mq = window.matchMedia?.('(prefers-color-scheme: dark)') @@ -862,6 +866,7 @@ export const App: React.FC = () => { onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))} macosMajor={macosMajors[selectedVM.name] ?? null} state={effectiveState} + guideActive={state.active_guides?.includes(selectedVM.name) ?? false} detail={detail} host={state.host} pending={pending} diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 88ed38c..d8137ce 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -6,7 +6,6 @@ import { AppWindow, Archive, Camera, - Check, ChevronRight, Code2, Copy, @@ -73,9 +72,6 @@ export type VMAction = | 'delete' | 'openFolder' -// Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing -// macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`. -const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh' const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command' export const PRIMARY_SHORTCUT = 'Ctrl+Enter' @@ -89,6 +85,8 @@ interface Props { /** macOS major version (26, 15, …) for the artwork shown before a first frame; null if unknown. */ macosMajor: number | null state: string + /** Whether the native VM-window installation guide is currently active for this boot. */ + guideActive: boolean detail: VMDetail | null host: HostReport pending: PendingChange[] @@ -125,11 +123,12 @@ interface Spec { } export const VMPage: React.FC = ({ - locale, name, displayName, onDisplayNameSaved, macosMajor, state, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, + locale, name, displayName, onDisplayNameSaved, macosMajor, state, guideActive, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const busy = busyAction !== undefined const running = state === 'running' + const installing = !!detail && (detail.has_installer || detail.recovery_mode) const transitioning = state === 'starting' || state === 'stopping' // Polled here rather than in App so each tick re-renders only this page. const stats = useVMStats(name, running) @@ -207,25 +206,6 @@ export const VMPage: React.FC = ({ } } - // Interactive install guide step checkboxes (persisted per VM in localStorage) - const guideKey = `reims-go-guide:${name}` - const [doneSteps, setDoneSteps] = useState([]) - useEffect(() => { - try { - const raw = localStorage.getItem(guideKey) - setDoneSteps(raw ? JSON.parse(raw) : []) - } catch { - setDoneSteps([]) - } - }, [guideKey]) - const toggleGuideStep = (step: number) => { - setDoneSteps((prev) => { - const next = prev.includes(step) ? prev.filter((x) => x !== step) : [...prev, step] - try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch {} - return next - }) - } - // Offline qcow2 restore points (snapshot_flow.go) const isQcow2 = !!detail && /\.qcow2$/i.test(detail.disk ?? '') const showSnapshots = !!detail && !detail.has_installer && !detail.recovery_mode && isQcow2 @@ -314,10 +294,11 @@ export const VMPage: React.FC = ({ } else if (state === 'stopping') { primary = } else if (running) { + const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow') primary = ( - + ) @@ -329,7 +310,6 @@ export const VMPage: React.FC = ({ } // "More" menu, grouped by purpose; destructive items last (docs/design-guidelines.md §5.2). - const installing = !!detail && (detail.has_installer || detail.recovery_mode) const menu = ( @@ -655,7 +635,7 @@ export const VMPage: React.FC = ({ )} - {detail && installing && (() => { + {detail && installing && state === 'stopped' && (() => { const hasInstaller = detail.has_installer const isOffline = hasInstaller && /offline-installer/i.test(detail.installer_path ?? '') const badgeKey: I18nKey = !hasInstaller @@ -663,88 +643,28 @@ export const VMPage: React.FC = ({ : isOffline ? 'guideKindOffline' : 'guideKindOnline' - const finish = ( - - ) - // Each step's number is a checkbox the user ticks off (kept per VM). - const step = (n: number, body: React.ReactNode) => { - const done = doneSteps.includes(n) - return ( -
  • - - {body} -
  • - ) - } return (

    {tr('guideTitle')}{' '} - {tr(badgeKey)} + {tr(badgeKey)}

    - {!hasInstaller ? ( - <> -
      - {step(1, tr('guideBuiltIn1'))} - {step(2, tr('guideBuiltIn2'))} - {step(3, tr('guideBuiltIn3'))} -
    -
    - - {finish} -
    - - ) : isOffline ? ( - <> -
      - {step(1, tr('guideOffline1'))} - {step(2, ( - <> - {tr('guideOffline2')} -
      - {OFFLINE_INSTALL_CMD} - } onClick={() => onCopy(OFFLINE_INSTALL_CMD)} /> - {running && ( - } busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(OFFLINE_INSTALL_CMD)} /> - )} -
      - - ))} - {step(3, tr('guideOffline3'))} -
    -
    {finish}
    - - ) : ( - <> -
      - {step(1, tr('guideStep1'))} - {step(2, tr('guideStep2'))} - {step(3, tr('guideStep3'))} -
    -
    {finish}
    - - )} +

    {tr('guideStartHint')}

    +
    + {!hasInstaller && ( + + )} + +
    ) })()} diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 1a81365..69aa821 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -73,6 +73,7 @@ const dict = { themeDark: '深色', themeSystem: '跟随系统', showWindow: '显示窗口', + showInstallGuide: '显示安装引导', copyScreenshot: '截屏并复制', toastScreenshotCopied: '已复制虚拟机画面', failFocus: '无法定位虚拟机窗口', @@ -157,18 +158,10 @@ const dict = { pendingTitle: '下次启动生效', restartToApply: '重启以应用', guideTitle: '恢复模式', + guideStartHint: '启动后在虚拟机窗口查看安装引导', guideKindBuiltIn: '内置恢复', guideKindOffline: '离线完整安装', guideKindOnline: '在线恢复安装', - guideBuiltIn1: '启动后在 OpenCore 引导菜单选择「Recovery」', - guideBuiltIn2: '恢复模式可以联网重装;要离线安装就点「挂载离线镜像」', - guideBuiltIn3: '完成后点「退出恢复模式」', - guideStep1: '打开「磁盘工具」,选中最大的「QEMU HARDDISK Media」(看不到就选 View › Show All Devices),点 Erase:名称 Macintosh HD,格式 APFS,方案 GUID。抹除时可能停顿 10–30 秒,不要强制关机', - guideStep2: '回到恢复主界面,选「Reinstall macOS Tahoe」,装到刚抹好的磁盘,中途会重启几次', - guideStep3: '看到「设置助理」后,点「退出恢复模式」弹出安装盘', - guideOffline1: '不要点「Reinstall macOS Tahoe」,从菜单栏打开「Utilities › Terminal」', - guideOffline2: '运行下面的命令(点键盘图标可直接键入)。它会把空白磁盘抹成 APFS 并开始安装,中途会重启几次:', - guideOffline3: '看到「设置助理」后,点「退出恢复模式」弹出安装盘并恢复网络', finishInstall: '退出恢复模式', enterRecovery: '进入恢复模式', attachInstaller: '挂载离线镜像', @@ -402,7 +395,7 @@ const dict = { offlineCached: '已下载', offlineHint: '约 20 GB,安装时不联网', offlineSpaceWarn: '可用空间 {free} GB,下载这个版本需要约 {need} GB', - networkOfflineHint: '离线安装时默认关闭,装完会自动打开', + networkOfflineHint: '离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网', summaryOfflineSource: '离线安装包 · macOS {v}', macosVersion: 'macOS 版本', diskSize: '磁盘上限', @@ -842,6 +835,7 @@ const dict = { themeDark: 'Dark', themeSystem: 'System', showWindow: 'Show window', + showInstallGuide: 'Show install guide', copyScreenshot: 'Copy screenshot', toastScreenshotCopied: 'VM screenshot copied', failFocus: 'Could not focus VM window', @@ -923,18 +917,10 @@ const dict = { pendingTitle: 'Applies on next start', restartToApply: 'Restart to apply', guideTitle: 'Recovery mode', + guideStartHint: 'Start the VM to open the installation guide in its window', guideKindBuiltIn: 'Built-in recovery', guideKindOffline: 'Offline install', guideKindOnline: 'Online recovery', - guideBuiltIn1: 'After starting, choose “Recovery” in the OpenCore boot menu', - guideBuiltIn2: 'Recovery can reinstall over the network; for an offline install, click “Attach offline image”', - guideBuiltIn3: 'When you are done, click “Exit recovery mode”', - guideStep1: 'Open Disk Utility and select the largest “QEMU HARDDISK Media” (View › Show All Devices if it is hidden). Click Erase: name Macintosh HD, format APFS, scheme GUID. It may pause for 10–30 seconds; don’t force it off', - guideStep2: 'Back in Recovery, choose “Reinstall macOS Tahoe” and install to the disk you erased. It restarts a few times', - guideStep3: 'When Setup Assistant appears, click “Exit recovery mode” to eject the installer', - guideOffline1: 'Don’t click “Reinstall macOS Tahoe”; open Utilities › Terminal from the menu bar', - guideOffline2: 'Run the command below (the keyboard icon types it for you). It erases the blank disk as APFS and starts the install; it restarts a few times:', - guideOffline3: 'When Setup Assistant appears, click “Exit recovery mode” to eject the installer and turn the network back on', finishInstall: 'Exit recovery mode', enterRecovery: 'Enter recovery mode', attachInstaller: 'Attach offline image', @@ -1161,7 +1147,7 @@ const dict = { offlineCached: 'Downloaded', offlineHint: 'About 20 GB; installs with no network', offlineSpaceWarn: '{free} GB free; this release needs about {need} GB', - networkOfflineHint: 'Off for offline installs; turned back on after installing', + networkOfflineHint: 'Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking', summaryOfflineSource: 'Offline installer · macOS {v}', macosVersion: 'macOS version', diskSize: 'Disk size', diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 51df30f..4973092 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -474,6 +474,7 @@ h1, h2, h3, p { margin: 0; } box-shadow: var(--shadow-card); } .card-title { font-size: var(--fs-14); font-weight: var(--fw-strong); display: flex; align-items: center; gap: 8px; } +.card-desc { font-size: var(--fs-13); color: var(--text-2); line-height: 1.5; } .card-foot { display: flex; justify-content: flex-end; gap: var(--sp-2); padding-top: 2px; } .notice { @@ -493,22 +494,6 @@ h1, h2, h3, p { margin: 0; } .notice-sub { color: var(--text-2); font-variant-numeric: tabular-nums; } .notice-info .notice-icon { color: var(--accent-soft-text); } -/* Numbered visual stepper for Install / Recovery Guide */ -.guide-steps { - list-style: none; margin: 0; padding: 0; - display: flex; flex-direction: column; gap: 12px; -} -.guide-step { - display: flex; align-items: flex-start; gap: 12px; - font-size: var(--fs-13); color: var(--text-2); line-height: 1.55; -} -.guide-step-num { - width: 22px; height: 22px; border-radius: 50%; flex-shrink: 0; margin-top: 1px; - display: grid; place-items: center; - background: var(--accent-soft); color: var(--accent-soft-text); - font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums; -} -.guide-step-body { flex: 1; min-width: 0; } .steps { margin: 0; padding-left: var(--sp-6); display: flex; flex-direction: column; gap: var(--sp-1); color: var(--text-2); font-size: var(--fs-13); } /* ── Command line & technical details ──────────────────── */ @@ -1143,7 +1128,6 @@ button.status-issue + .status-metric { margin-left: 6px; } .choice-other { align-self: flex-start; } .task-inline { display: flex; align-items: center; gap: var(--sp-2); font-variant-numeric: tabular-nums; } -.guide-cmd { margin-top: var(--sp-2); } /* ── Telemetry meter (GPU compositor scaleX) ───────────── */ .resource-meter { @@ -1406,18 +1390,6 @@ button.status-issue + .status-metric { margin-left: 6px; } backdrop-filter: var(--blur-overlay); } -/* Interactive install stepper */ -.guide-step-btn { - width: 22px; height: 22px; padding: 0; border-radius: 50%; flex-shrink: 0; margin-top: 1px; - display: grid; place-items: center; border: none; cursor: pointer; - background: var(--accent-soft); color: var(--accent-soft-text); - font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums; - transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out); -} -.guide-step-btn:active { transform: scale(0.92); } -.guide-step-btn.done { background: var(--ok-soft); color: var(--ok-text); } -.guide-step.is-done .guide-step-body { opacity: 0.62; } - /* Inline snapshot creation bar */ .snap-create-bar { display: flex; align-items: center; gap: 8px; diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 0749bd5..61257ce 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -161,4 +161,5 @@ export const events = { onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb), emitUIPong: () => eventsEmit('reims:ui-pong'), emitUIError: (detail: string) => eventsEmit('reims:ui-error', detail), + emitTheme: (theme: 'light' | 'dark') => eventsEmit('reims:theme', theme), } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index ab2fa3c..2a3a5e4 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -9,6 +9,7 @@ export namespace app { vms: reims.VMListItem[]; transitions: Record; pending_changes: Record>; + active_guides: string[] | null; needs_setup: boolean; app_version: string; safe_mode?: boolean; @@ -28,6 +29,7 @@ export namespace app { this.vms = this.convertValues(source["vms"], reims.VMListItem); this.transitions = source["transitions"]; this.pending_changes = this.convertValues(source["pending_changes"], Array, true); + this.active_guides = source["active_guides"]; this.needs_setup = source["needs_setup"]; this.app_version = source["app_version"]; this.safe_mode = source["safe_mode"]; diff --git a/internal/app/app.go b/internal/app/app.go index 2d5e79f..877e56d 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -8,6 +8,7 @@ import ( "maps" "os" "path/filepath" + "slices" "strings" "sync" "time" @@ -19,6 +20,7 @@ import ( "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/installguide" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/qmp" @@ -45,6 +47,7 @@ type AppState struct { VMs []reims.VMListItem `json:"vms"` Transitions map[string]string `json:"transitions"` PendingChanges map[string][]PendingChange `json:"pending_changes"` + ActiveGuides []string `json:"active_guides"` // NeedsSetup is true on first launch, until a data folder is chosen (setup.go). NeedsSetup bool `json:"needs_setup"` AppVersion string `json:"app_version"` @@ -84,6 +87,8 @@ type App struct { driverRouter *driver.Router runtimeKinds *rt.KindRegistry uiHealth uiHealthState + themeMode installguide.Theme + activeGuides map[string]*activeGuide } // Lifecycle exposes Wails lifecycle callbacks without exporting them as @@ -114,6 +119,7 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) { diskPaths: make(map[string]cachedDiskPath), procSamples: make(map[string]host.ProcessSample), uiHealth: uiHealthState{windowHidden: launch.Background}, + activeGuides: make(map[string]*activeGuide), } return a, Lifecycle{ OnStartup: a.startup, @@ -129,6 +135,7 @@ func (a *App) startup(ctx context.Context) { a.ctx = ctx pollCtx, cancel := context.WithCancel(ctx) a.stopPoll = cancel + a.bindGuideEvents(ctx) a.startTray() a.initPlugins() // Without a plugin manager, run the IME bridge and Guest Tools directly. @@ -208,7 +215,7 @@ func (a *App) shutdown(ctx context.Context) { // stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`. // Start, stop and delete call wakePoll so their result shows up at once. const ( - pollBusy = 2 * time.Second + pollBusy = 2 * time.Second // Exits are caught at once by watchExits and GUI actions call wakePoll, so // the steady tick only has to notice VMs started or removed elsewhere (CLI). pollSteady = 10 * time.Second @@ -243,7 +250,11 @@ func (a *App) pollVMs(ctx context.Context) { } a.mu.Unlock() timer.Reset(next) - vms, err := a.listVMsInternal(ctx) + c, err := a.client() + if err != nil { + continue + } + vms, err := c.List(ctx) if err != nil { continue } @@ -326,6 +337,7 @@ func (a *App) pollVMs(ctx context.Context) { a.lastVMsAt = time.Now() a.mu.Unlock() prunePinnedPIDs(pinnedPIDs, vms) + guidesChanged := a.cancelStoppedGuides(pinnedPIDs) for name := range removedVMs { a.mu.Lock() delete(a.transitions, name) @@ -353,21 +365,36 @@ func (a *App) pollVMs(ctx context.Context) { } } for _, cand := range toPin { - vmCPUs := 0 - vmDir := cand.dir - if c, cerr := a.client(); cerr == nil { - if det, derr := c.Show(ctx, cand.name); derr == nil { - vmCPUs = det.CPUs - if vmDir == "" { - vmDir = det.Directory - } - } + det, err := c.Show(ctx, cand.name) + if err != nil { + // Retry boot discovery if the runtime was still starting. + delete(pinnedPIDs, cand.pid) + continue } - if line, _ := vmstart.ApplyVMAffinity(loc, cachedHost, vmDir, autoPin, cand.pid, vmCPUs, false); line != "" { + vmDir := cand.dir + if vmDir == "" { + vmDir = det.Directory + } + if det.Directory == "" { + det.Directory = vmDir + } + kind, recovery := installGuideKind(det) + g := installguide.Guide{ + Name: cand.name, + PID: uint32(cand.pid), + Locale: loc, + Kind: kind, + ToolsAttached: reims.HasGuestToolsArgs(det.ExtraArgs), + } + if g.Resume(det.Directory, det.InstallerPath, recovery) { + a.startInstallGuide(ctx, g, det) + guidesChanged = true + } + if line, _ := vmstart.ApplyVMAffinity(loc, cachedHost, vmDir, autoPin, cand.pid, det.CPUs, false); line != "" { a.emitLog(cand.name, line) } } - if sig != lastSig { + if sig != lastSig || guidesChanged { lastSig = sig wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) } @@ -545,6 +572,7 @@ func (a *App) GetState() AppState { pcCopy[k] = append([]PendingChange(nil), v...) } needsSetup := a.needsSetup + activeGuides := slices.Sorted(maps.Keys(a.activeGuides)) a.mu.Unlock() rep := host.Inspect(cfgCopy.DataRoot) @@ -581,6 +609,7 @@ func (a *App) GetState() AppState { VMs: vms, Transitions: trCopy, PendingChanges: pcCopy, + ActiveGuides: activeGuides, NeedsSetup: needsSetup, AppVersion: version.Version, SafeMode: safeMode, @@ -1258,10 +1287,15 @@ func (a *App) StopVM(name string, force bool) error { } func (a *App) RestartVM(name string) error { + _, err := a.restartVM(name) + return err +} + +func (a *App) restartVM(name string) (stopped bool, err error) { if err := a.StopVM(name, false); err != nil { - return err + return false, err } - return a.StartVM(name) + return true, a.StartVM(name) } func (a *App) EjectInstaller(name string) error { diff --git a/internal/app/install_guide.go b/internal/app/install_guide.go new file mode 100644 index 0000000..76154af --- /dev/null +++ b/internal/app/install_guide.go @@ -0,0 +1,182 @@ +package app + +import ( + "context" + "fmt" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/installguide" + "github.com/Nwflower/reims-go/internal/vmstart" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +type activeGuide struct { + pid int + unfold chan struct{} + cancel context.CancelFunc +} + +func (a *App) guidePreferences() (i18n.Locale, installguide.Theme) { + a.mu.Lock() + defer a.mu.Unlock() + return a.cfg.Locale, a.themeMode +} + +func (a *App) bindGuideEvents(ctx context.Context) { + wailsRuntime.EventsOn(ctx, "reims:theme", func(data ...any) { + if len(data) != 1 { + return + } + raw, _ := data[0].(string) + theme := installguide.Theme(raw) + if theme == installguide.ThemeLight || theme == installguide.ThemeDark { + a.mu.Lock() + a.themeMode = theme + a.mu.Unlock() + } + }) +} + +func (a *App) cancelStoppedGuides(running map[int]bool) bool { + a.mu.Lock() + defer a.mu.Unlock() + changed := false + for name, guide := range a.activeGuides { + if !running[guide.pid] { + guide.cancel() + delete(a.activeGuides, name) + changed = true + } + } + return changed +} + +func (a *App) unfoldInstallGuide(name string, pid int) { + a.mu.Lock() + entry := a.activeGuides[name] + a.mu.Unlock() + if entry == nil || entry.pid != pid { + return + } + select { + case entry.unfold <- struct{}{}: + default: + } +} + +// A queued recovery picker ("want") applies at the next boot. The guide +// describes the running boot, including one already running when the app opens. +func installGuideKind(d reims.VMDetail) (installguide.Kind, bool) { + if d.HasInstaller { + if reims.IsOfflineInstallerPath(d.InstallerPath) { + return installguide.Offline, true + } + return installguide.Online, true + } + return installguide.BuiltIn, vmstart.ReadRecoveryMarker(d.Directory) == "on" +} + +func (a *App) startInstallGuide(ctx context.Context, g installguide.Guide, d reims.VMDetail) { + ctx, cancel := context.WithCancel(ctx) + entry := &activeGuide{pid: int(g.PID), unfold: make(chan struct{}, 1), cancel: cancel} + a.mu.Lock() + if prev := a.activeGuides[g.Name]; prev != nil { + prev.cancel() + } + a.activeGuides[g.Name] = entry + a.mu.Unlock() + + g.Unfold = entry.unfold + go func() { + defer cancel() + a.runInstallGuide(ctx, g, d) + a.mu.Lock() + removed := a.activeGuides[g.Name] == entry + if removed { + delete(a.activeGuides, g.Name) + } + a.mu.Unlock() + if removed && a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } + }() +} + +func (a *App) runInstallGuide(ctx context.Context, g installguide.Guide, d reims.VMDetail) { + name, pid := g.Name, int(g.PID) + g.CurrentPreferences = a.guidePreferences + if d.Graphics == "vmware-svga" { + g.ReleaseKeys = "Ctrl+Alt+G" + } else if d.Capture { + g.ReleaseKeys = "Ctrl+Alt+Win" + } + // The panel may have been open across a shutdown. Re-list instead of + // using the poll cache before acting on a VM addressed by name. + checkBoot := func() error { + vms, err := a.listVMsInternal(ctx) + if err != nil { + return err + } + for _, vm := range vms { + if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID == pid { + return ctx.Err() + } + } + if loc, _ := a.guidePreferences(); loc == i18n.ZhCN { + return fmt.Errorf("虚拟机 %s 的运行状态已改变", name) + } + return fmt.Errorf("the running instance of %s has changed", name) + } + g.TypeText = func(text string) error { + if err := checkBoot(); err != nil { + return err + } + _, err := a.TypeText(name, text) + return err + } + g.FinishRecovery = func() error { + if err := checkBoot(); err != nil { + return err + } + return a.FinishInstall(name) + } + g.AttachImage = func(path string) error { + if err := checkBoot(); err != nil { + return err + } + _, err := a.AttachInstaller(name, path) + return err + } + g.LogError = func(err error) { a.emitLog(name, "Installation guide: "+err.Error()) } + g.AttachTools = func() error { + if err := checkBoot(); err != nil { + return err + } + return a.AttachGuestTools(name) + } + g.Restart = func() error { + if err := checkBoot(); err != nil { + return err + } + stopped, err := a.restartVM(name) + if stopped && err != nil { + // The guest window has closed, so report start failures via the tray. + title := "Could not restart VM: " + name + if loc, _ := a.guidePreferences(); loc == i18n.ZhCN { + title = "未能重启虚拟机:" + name + } + a.emitLog(name, title+": "+err.Error()) + a.mu.Lock() + tm := a.trayMgr + a.mu.Unlock() + if tm != nil { + tm.Notify(title, err.Error(), true) + } + } + return err + } + if err := installguide.Run(ctx, g); err != nil { + g.LogError(err) + } +} diff --git a/internal/app/install_guide_test.go b/internal/app/install_guide_test.go new file mode 100644 index 0000000..83d5bb2 --- /dev/null +++ b/internal/app/install_guide_test.go @@ -0,0 +1,65 @@ +package app + +import ( + "context" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/installguide" + "github.com/Nwflower/reims-go/internal/vmstart" +) + +func TestInstallGuideFollowsBootMedia(t *testing.T) { + d := reims.VMDetail{Directory: t.TempDir()} + for _, test := range []struct { + marker, path string + want installguide.Kind + show bool + }{ + {"", "", installguide.BuiltIn, false}, {"want", "", installguide.BuiltIn, false}, + {"on", "", installguide.BuiltIn, true}, {"restore", "", installguide.BuiltIn, false}, + {"", "BaseSystem.img", installguide.Online, true}, {"", "offline-installer-tahoe.img", installguide.Offline, true}, + } { + vmstart.WriteRecoveryMarker(d.Directory, test.marker) + d.HasInstaller, d.InstallerPath = test.path != "", test.path + if kind, show := installGuideKind(d); kind != test.want || show != test.show { + t.Errorf("%+v: got (%d,%t)", test, kind, show) + } + } +} + +func TestActiveGuideTrackingAndUnfold(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + unfold := make(chan struct{}, 1) + a := &App{ + cfg: &config.Config{Locale: i18n.ZhCN}, + themeMode: installguide.ThemeDark, + activeGuides: map[string]*activeGuide{"mac": {pid: 101, unfold: unfold, cancel: cancel}}, + } + if loc, th := a.guidePreferences(); loc != i18n.ZhCN || th != installguide.ThemeDark { + t.Fatalf("guidePreferences = (%q, %q)", loc, th) + } + a.unfoldInstallGuide("mac", 999) // wrong PID should not signal + select { + case <-unfold: + t.Fatal("signaled unfold for mismatched PID") + default: + } + a.unfoldInstallGuide("mac", 101) + select { + case <-unfold: + default: + t.Fatal("unfold was not signaled for matching PID") + } + if a.cancelStoppedGuides(map[int]bool{101: true}) { + t.Fatal("running guide was canceled") + } + if !a.cancelStoppedGuides(map[int]bool{}) { + t.Fatal("stopped guide was not canceled") + } + if ctx.Err() == nil || len(a.activeGuides) != 0 { + t.Fatal("stopped guide was not cleaned up") + } +} diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 6e061ee..b590f00 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -93,6 +93,7 @@ func (a *App) FocusVMWindow(name string) error { if !host.FocusProcessWindow(uint32(*vm.PID)) { return fmt.Errorf("could not locate display window for %s", name) } + a.unfoldInstallGuide(name, *vm.PID) return nil } diff --git a/internal/installguide/appearance_windows.go b/internal/installguide/appearance_windows.go new file mode 100644 index 0000000..450428f --- /dev/null +++ b/internal/installguide/appearance_windows.go @@ -0,0 +1,753 @@ +package installguide + +import ( + "math" + "sync" + "syscall" + "unsafe" + + "golang.org/x/sys/windows/registry" +) + +var ( + gdi = syscall.NewLazyDLL("gdi32.dll") + dwmapi = syscall.NewLazyDLL("dwmapi.dll") + comctl32 = syscall.NewLazyDLL("comctl32.dll") + kernel32 = syscall.NewLazyDLL("kernel32.dll") + + selectGDI = gdi.NewProc("SelectObject") + stockObject = gdi.NewProc("GetStockObject") + deleteGDI = gdi.NewProc("DeleteObject") + brushColor = gdi.NewProc("SetDCBrushColor") + textColor = gdi.NewProc("SetTextColor") + bkMode = gdi.NewProc("SetBkMode") + setDIBitsToDevice = gdi.NewProc("SetDIBitsToDevice") + getObjectW = gdi.NewProc("GetObjectW") + createFontIndirectW = gdi.NewProc("CreateFontIndirectW") + createRoundRectRgn = gdi.NewProc("CreateRoundRectRgn") + gdiFlush = gdi.NewProc("GdiFlush") + + drawText = user32.NewProc("DrawTextW") + sendMessage = user32.NewProc("SendMessageW") + getParent = user32.NewProc("GetParent") + getDlgCtrlID = user32.NewProc("GetDlgCtrlID") + getDlgItem = user32.NewProc("GetDlgItem") + fillRect = user32.NewProc("FillRect") + drawFocusRect = user32.NewProc("DrawFocusRect") + getWindowTextW = user32.NewProc("GetWindowTextW") + invalidateRect = user32.NewProc("InvalidateRect") + redrawWindow = user32.NewProc("RedrawWindow") + trackMouseEvent = user32.NewProc("TrackMouseEvent") + loadCursorW = user32.NewProc("LoadCursorW") + setCursor = user32.NewProc("SetCursor") + mapDialogRect = user32.NewProc("MapDialogRect") + setLayeredAttr = user32.NewProc("SetLayeredWindowAttributes") + setWindowRgn = user32.NewProc("SetWindowRgn") + beginPaint = user32.NewProc("BeginPaint") + endPaint = user32.NewProc("EndPaint") + getDC = user32.NewProc("GetDC") + releaseDC = user32.NewProc("ReleaseDC") + dwmSetWindowAttr = dwmapi.NewProc("DwmSetWindowAttribute") + setWindowSubclass = comctl32.NewProc("SetWindowSubclass") + removeSubclass = comctl32.NewProc("RemoveWindowSubclass") + defSubclassProc = comctl32.NewProc("DefSubclassProc") + rtlMoveMemory = kernel32.NewProc("RtlMoveMemory") +) + +const ( + panelAlpha = 242 // ~95% opacity, matching --surface-2 rgba(..., 0.94) + linkPadDLU = 4 // symmetric horizontal padding for secondary text link hover pill +) + +type rgb struct{ r, g, b uint8 } + +func (c rgb) colorref() uintptr { + return uintptr(c.r) | uintptr(c.g)<<8 | uintptr(c.b)<<16 +} + +func blendRGB(bg, fg rgb, alpha float64) rgb { + if alpha <= 0 { + return bg + } + if alpha >= 1 { + return fg + } + inv := 1 - alpha + return rgb{ + r: uint8(float64(bg.r)*inv + float64(fg.r)*alpha + 0.5), + g: uint8(float64(bg.g)*inv + float64(fg.g)*alpha + 0.5), + b: uint8(float64(bg.b)*inv + float64(fg.b)*alpha + 0.5), + } +} + +// palette mirrors frontend/src/styles/tokens.css (Light & Dark). +type palette struct { + surface rgb + cardBorder rgb + text rgb + text2 rgb + text3 rgb + accent rgb + accentHover rgb + accentPress rgb + accentHighlight rgb + accentLink rgb + accentSoft rgb + accentLinkHover rgb + btnFill rgb + btnHover rgb + btnPress rgb + btnBorder rgb + ghostHover rgb + ghostPress rgb + codeFill rgb + codeBorder rgb + codeText rgb + okSoft rgb + okText rgb + warnSoft rgb + warnText rgb + dangerSoft rgb + dangerText rgb +} + +var lightPalette = palette{ + surface: rgb{255, 255, 255}, // --surface-2 + cardBorder: rgb{214, 220, 229}, // ~rgba(15,23,42,0.14) + text: rgb{29, 29, 31}, // --text #1d1d1f + text2: rgb{66, 66, 71}, // --text-2 #424247 + text3: rgb{110, 110, 115}, // --text-3 #6e6e73 + accent: rgb{0, 122, 255}, // --accent #007aff + accentHover: rgb{0, 107, 230}, // --accent-hover #006be6 + accentPress: rgb{0, 94, 196}, + accentHighlight: rgb{56, 151, 255}, // inset top highlight + accentLink: rgb{0, 102, 214}, // --accent-soft-text #0066d6 + accentSoft: rgb{229, 242, 255}, // --accent-soft + accentLinkHover: rgb{236, 245, 255}, + btnFill: rgb{255, 255, 255}, // --surface-card-elevated + btnHover: rgb{243, 245, 248}, // --surface-hover + btnPress: rgb{232, 236, 242}, // --surface-active + btnBorder: rgb{207, 213, 223}, // --border-strong + ghostHover: rgb{241, 243, 246}, + ghostPress: rgb{229, 232, 238}, + codeFill: rgb{245, 246, 248}, // --surface-1 #f5f6f8 + codeBorder: rgb{226, 229, 236}, // --border + codeText: rgb{44, 44, 48}, // --text-code #2c2c30 + okSoft: rgb{227, 249, 231}, // --ok-soft + okText: rgb{24, 140, 44}, // --ok-text #188c2c + warnSoft: rgb{255, 242, 220}, // --warn-soft + warnText: rgb{168, 98, 0}, // --warn-text #a86200 + dangerSoft: rgb{255, 235, 234}, // --danger-soft + dangerText: rgb{215, 0, 21}, // --danger-text #d70015 +} + +var darkPalette = palette{ + surface: rgb{42, 43, 50}, // --surface-2 #2a2b32 + cardBorder: rgb{68, 70, 80}, // ~rgba(255,255,255,0.12) + text: rgb{245, 245, 247}, // --text #f5f5f7 + text2: rgb{194, 194, 202}, // --text-2 #c2c2ca + text3: rgb{146, 146, 156}, // --text-3 #92929c + accent: rgb{10, 132, 255}, // --accent #0a84ff + accentHover: rgb{36, 146, 255}, // --accent-hover #2492ff + accentPress: rgb{0, 110, 224}, + accentHighlight: rgb{66, 160, 255}, + accentLink: rgb{100, 176, 255}, // --accent-soft-text #64b0ff + accentSoft: rgb{34, 58, 88}, // --accent-soft + accentLinkHover: rgb{42, 60, 84}, + btnFill: rgb{54, 56, 66}, // --surface-card-elevated + btnHover: rgb{65, 67, 79}, // --surface-hover + btnPress: rgb{75, 77, 90}, // --surface-active + btnBorder: rgb{83, 86, 100}, // --border-strong + ghostHover: rgb{56, 58, 68}, + ghostPress: rgb{67, 69, 81}, + codeFill: rgb{30, 31, 37}, // --surface-input + codeBorder: rgb{62, 64, 74}, // --border + codeText: rgb{212, 214, 224}, // --text-code #d4d6e0 + okSoft: rgb{35, 65, 49}, // --ok-soft + okText: rgb{48, 209, 88}, // --ok-text #30d158 + warnSoft: rgb{69, 62, 36}, // --warn-soft + warnText: rgb{255, 214, 10}, // --warn-text #ffd60a + dangerSoft: rgb{73, 40, 43}, // --danger-soft + dangerText: rgb{255, 139, 131}, // --danger-text #ff8b83 +} + +func paletteFor(dark bool) palette { + if dark { + return darkPalette + } + return lightPalette +} + +func resolveDark(th Theme) bool { + switch th { + case ThemeDark: + return true + case ThemeLight: + return false + default: + return windowsAppsUseDarkTheme() + } +} + +func windowsAppsUseDarkTheme() bool { + k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`, registry.QUERY_VALUE) + if err != nil { + return false + } + defer k.Close() + v, _, err := k.GetIntegerValue("AppsUseLightTheme") + return err == nil && v == 0 +} + +const ( + dialogDark = 1 << iota + dialogCompact + dialogDWM + dialogToneShift = 3 + + // DWLP_USER is the pointer-sized data slot following DWLP_DLGPROC. + dialogUser = 2 * unsafe.Sizeof(uintptr(0)) +) + +var ( + getWindowLongPtr = user32.NewProc("GetWindowLongPtrW") + setWindowLongPtr = user32.NewProc("SetWindowLongPtrW") + hoveredControls sync.Map +) + +type dialogMeta struct { + dark, compact, dwm bool + stageTone tone +} + +func getDialogMeta(hwnd uintptr) dialogMeta { + flags, _, _ := getWindowLongPtr.Call(hwnd, dialogUser) + return dialogMeta{ + dark: flags&dialogDark != 0, + compact: flags&dialogCompact != 0, + dwm: flags&dialogDWM != 0, + stageTone: tone(flags >> dialogToneShift), + } +} + +type drawItem struct { + kind, id, index, action, state uint32 + control, dc uintptr + area rect + data uintptr +} + +type trackMouseStruct struct { + size uint32 + flags uint32 + hwndTrack uintptr + hoverTime uint32 +} + +type paintStruct struct { + dc uintptr + erase int32 + paintRect rect + restore int32 + incUpdate int32 + reserved [32]byte +} + +type bitmapInfoHeader struct { + size uint32 + width int32 + height int32 + planes uint16 + bitCount uint16 + compression uint32 + sizeImage uint32 + xPelsPerMeter int32 + yPelsPerMeter int32 + clrUsed uint32 + clrImportant uint32 +} + +type logFontW struct { + height, width, escapement, orientation, weight int32 + attributes [8]byte + face [32]uint16 +} + +var btnSubclassProc uintptr + +func init() { + btnSubclassProc = syscall.NewCallback(func(hwnd, msg, wp, lp, id, ref uintptr) uintptr { + switch msg { + case 0x0014: // WM_ERASEBKGND: owner-drawn buttons paint 100% of their area; suppress white flash. + return 1 + case 0x0200: // WM_MOUSEMOVE + if _, alreadyHovered := hoveredControls.LoadOrStore(hwnd, struct{}{}); !alreadyHovered { + tme := trackMouseStruct{size: uint32(unsafe.Sizeof(trackMouseStruct{})), flags: 2, hwndTrack: hwnd} // TME_LEAVE + trackMouseEvent.Call(uintptr(unsafe.Pointer(&tme))) + invalidateRect.Call(hwnd, 0, 0) + } + case 0x02a3: // WM_MOUSELEAVE + if _, wasHovered := hoveredControls.LoadAndDelete(hwnd); wasHovered { + invalidateRect.Call(hwnd, 0, 0) + } + case 0x0020: // WM_SETCURSOR + if id == idExtra || id == idJump || ref != 0 { + cur, _, _ := loadCursorW.Call(0, 32649) // IDC_HAND + if cur != 0 { + setCursor.Call(cur) + return 1 + } + } + case 0x0082: // WM_NCDESTROY + hoveredControls.Delete(hwnd) + removeSubclass.Call(hwnd, btnSubclassProc, id) + } + r, _, _ := defSubclassProc.Call(hwnd, msg, wp, lp) + return r + }) +} + +func stylePanel(hwnd, flags uintptr) { + // Keep newly created dialogs at alpha=0 until synchronously painted so DWM + // never shows an unpainted black/white frame during step transitions. + setLayeredAttr.Call(hwnd, 0, 0, 2) // LWA_ALPHA + + dark := flags&dialogDark != 0 + pal := paletteFor(dark) + + // Prefer Windows 11 DWM smooth rounded corners + native drop shadow + dark hint. + var darkMode int32 + if dark { + darkMode = 1 + } + dwmSetWindowAttr.Call(hwnd, 20, uintptr(unsafe.Pointer(&darkMode)), unsafe.Sizeof(darkMode)) // DWMWA_USE_IMMERSIVE_DARK_MODE + + corner := uint32(2) // DWMWCP_ROUND (8 DIPs, matching panelRadius) + hr, _, _ := dwmSetWindowAttr.Call(hwnd, 33, uintptr(unsafe.Pointer(&corner)), unsafe.Sizeof(corner)) // DWMWA_WINDOW_CORNER_PREFERENCE + if hr == 0 { + flags |= dialogDWM + border := uint32(pal.cardBorder.colorref()) + dwmSetWindowAttr.Call(hwnd, 34, uintptr(unsafe.Pointer(&border)), unsafe.Sizeof(border)) // DWMWA_BORDER_COLOR + } + setWindowLongPtr.Call(hwnd, dialogUser, flags) + if hr != 0 { + roundPanel(hwnd) + } + + // Shrink link buttons to hug their text symmetrically so hover pills are + // centered around the label and empty space to the right is not clickable. + for _, id := range []uintptr{idExtra, idJump} { + if ctrl, _, _ := getDlgItem.Call(hwnd, id); ctrl != 0 { + fitLinkControl(hwnd, ctrl) + } + } + + for _, id := range []uintptr{idFold, idLeft, idRight, idExtra, idJump} { + if ctrl, _, _ := getDlgItem.Call(hwnd, id); ctrl != 0 { + setWindowSubclass.Call(ctrl, btnSubclassProc, id, flags&dialogCompact) + } + } +} + +func fitLinkControl(hwnd, ctrl uintptr) { + var caption [256]uint16 + n, _, _ := getWindowTextW.Call(ctrl, uintptr(unsafe.Pointer(&caption[0])), uintptr(len(caption))) + if n == 0 { + return + } + var avail rect + getClientRect.Call(ctrl, uintptr(unsafe.Pointer(&avail))) + if avail.right <= 0 || avail.bottom <= 0 { + return + } + dc, _, _ := getDC.Call(ctrl) + if dc == 0 { + return + } + defer releaseDC.Call(ctrl, dc) + font, _, _ := sendMessage.Call(ctrl, 0x0031, 0, 0) // WM_GETFONT + if font != 0 { + old, _, _ := selectGDI.Call(dc, font) + defer selectGDI.Call(dc, old) + } + var measured rect + drawText.Call(dc, uintptr(unsafe.Pointer(&caption[0])), n, uintptr(unsafe.Pointer(&measured)), 0x400|0x820) + padX := dialogPixels(hwnd, linkPadDLU) + wantW := min(avail.right, (measured.right-measured.left)+padX*2) + if wantW > 0 && wantW < avail.right { + // SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE + setWindowPos.Call(ctrl, 0, 0, 0, uintptr(wantW), uintptr(avail.bottom), 0x16) + } +} + +// revealPanel synchronously repaints the dialog and every child control before +// setting panelAlpha, guaranteeing the first visible DWM frame is complete. +func revealPanel(hwnd uintptr) { + // RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN | RDW_UPDATENOW | RDW_FRAME + redrawWindow.Call(hwnd, 0, 0, 0x0585) + gdiFlush.Call() + setLayeredAttr.Call(hwnd, 0, panelAlpha, 2) // LWA_ALPHA +} + +// Derive pixel sizes from the dialog's font-scaled layout (works across DPIs). +func dialogPixels(hwnd uintptr, units int32) int32 { + r := rect{right: units} + mapDialogRect.Call(hwnd, uintptr(unsafe.Pointer(&r))) + return max(1, r.right) +} + +func panelRadius(hwnd uintptr) int32 { + return max(6, dialogPixels(hwnd, 5)) // ~8 DIPs, matching Win11 DWMWCP_ROUND +} + +func roundPanel(hwnd uintptr) { + if getDialogMeta(hwnd).dwm { + return + } + var r rect + getClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r))) + if r.right <= 0 || r.bottom <= 0 { + return + } + diameter := uintptr(panelRadius(hwnd) * 2) + region, _, _ := createRoundRectRgn.Call(0, 0, uintptr(r.right+1), uintptr(r.bottom+1), diameter, diameter) + if region != 0 { + // SetWindowRgn takes ownership only on success. + if ok, _, _ := setWindowRgn.Call(hwnd, region, 1); ok == 0 { + deleteGDI.Call(region) + } + } +} + +func panelBrush(hwnd, dc, ctrl uintptr) uintptr { + meta := getDialogMeta(hwnd) + pal := paletteFor(meta.dark) + fg := pal.text2 + if ctrl != 0 { + if id, _, _ := getDlgCtrlID.Call(ctrl); id == idInputHint { + fg = pal.text3 + } + } + textColor.Call(dc, fg.colorref()) + bkMode.Call(dc, 1) // TRANSPARENT + brushColor.Call(dc, pal.surface.colorref()) + brush, _, _ := stockObject.Call(18) // DC_BRUSH + return brush +} + +// paintDialogDC draws the fill and crisp 1px border for the rounded popup. +func paintDialogDC(hwnd, dc uintptr) { + meta := getDialogMeta(hwnd) + pal := paletteFor(meta.dark) + var r rect + getClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r))) + if meta.compact { + // The compact button covers the full client area and paints its own border. + brushColor.Call(dc, pal.surface.colorref()) + brush, _, _ := stockObject.Call(18) + fillRect.Call(dc, uintptr(unsafe.Pointer(&r)), brush) + return + } + radius := float64(panelRadius(hwnd)) + paintRoundedBox(dc, r, radius, pal.surface, pal.surface, pal.cardBorder, true, rgb{}, false) +} + +func paintDialogFrame(hwnd uintptr) { + var ps paintStruct + dc, _, _ := beginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + if dc == 0 { + return + } + defer endPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + paintDialogDC(hwnd, dc) +} + +func stageColors(pal palette, tn tone) (rgb, rgb) { + switch tn { + case toneOK: + return pal.okSoft, pal.okText + case toneWarn: + return pal.warnSoft, pal.warnText + case toneDanger: + return pal.dangerSoft, pal.dangerText + default: + return pal.accentSoft, pal.accentLink + } +} + +// The dialog retains real Win32 controls (keyboard navigation, accessible names, +// native click notifications). Only painting is custom, matching tokens.css. +func paintItem(it *drawItem) { + parent, _, _ := getParent.Call(it.control) + meta := getDialogMeta(parent) + pal := paletteFor(meta.dark) + + dc := it.dc + saved, _, _ := gdi.NewProc("SaveDC").Call(dc) + defer gdi.NewProc("RestoreDC").Call(dc, saved) + bkMode.Call(dc, 1) // TRANSPARENT + brushColor.Call(dc, pal.surface.colorref()) + brush, _, _ := stockObject.Call(18) // DC_BRUSH + fillRect.Call(dc, uintptr(unsafe.Pointer(&it.area)), brush) + + r := it.area + h := r.bottom - r.top + font, _, _ := sendMessage.Call(it.control, 0x0031, 0, 0) // WM_GETFONT + if font != 0 { + selectGDI.Call(dc, font) + } + + var caption [256]uint16 + n, _, _ := getWindowTextW.Call(it.control, uintptr(unsafe.Pointer(&caption[0])), uintptr(len(caption))) + if n == 0 { + return + } + + pressed := it.state&1 != 0 + _, hovered := hoveredControls.Load(it.control) + btnRadius := float64(panelRadius(parent)) // ~8px (--r-md) + + // Select custom font if needed (title, stage badge, primary button, code pill). + var ownedFont uintptr + if font != 0 { + var lf logFontW + if got, _, _ := getObjectW.Call(font, unsafe.Sizeof(lf), uintptr(unsafe.Pointer(&lf))); got != 0 { + makeFont := false + switch it.id { + case idTitle: + lf.weight = 600 + lf.height = lf.height * 6 / 5 + makeFont = true + case idStage: + lf.weight = 600 + lf.height = lf.height * 11 / 12 + makeFont = true + case idRight: + lf.weight = 600 + makeFont = true + case idLeft: + lf.weight = 500 + makeFont = true + case idCode: + lf.weight = 400 + lf.height = lf.height * 11 / 12 + setFace(&lf, "Consolas") + makeFont = true + case idFold: + if meta.compact { + lf.weight = 500 + makeFont = true + } + } + if makeFont { + ownedFont, _, _ = createFontIndirectW.Call(uintptr(unsafe.Pointer(&lf))) + } + } + } + if ownedFont != 0 { + prev, _, _ := selectGDI.Call(dc, ownedFont) + defer func() { selectGDI.Call(dc, prev); deleteGDI.Call(ownedFont) }() + } + + flags := uintptr(0x825) // DT_SINGLELINE | DT_VCENTER | DT_CENTER | DT_NOPREFIX + fg := pal.text + textRect := r + + switch it.id { + case idStage: + pillFill, pillFg := stageColors(pal, meta.stageTone) + fg = pillFg + var measured rect + drawText.Call(dc, uintptr(unsafe.Pointer(&caption[0])), n, uintptr(unsafe.Pointer(&measured)), 0x400|0x820) + padX := max(7, dialogPixels(parent, 5)) + pillW := min(r.right-r.left, (measured.right-measured.left)+padX*2) + pillH := min(h, max(measured.bottom-measured.top+6, dialogPixels(parent, 12))) + pillY := r.top + (h-pillH)/2 + pillRect := rect{left: r.left, top: pillY, right: r.left + pillW, bottom: pillY + pillH} + paintRoundedBox(dc, pillRect, float64(pillH)/2, pal.surface, pillFill, rgb{}, false, rgb{}, false) + textRect = rect{left: pillRect.left + padX, top: pillRect.top, right: pillRect.right - padX, bottom: pillRect.bottom} + flags = 0x825 + case idTitle: + flags = 0x824 | 0x8000 // left | vcenter | singleline | noprefix | DT_END_ELLIPSIS + fg = pal.text + case idCode: + paintRoundedBox(dc, r, btnRadius, pal.surface, pal.codeFill, pal.codeBorder, true, rgb{}, false) + padX := max(8, dialogPixels(parent, 6)) + textRect = rect{left: r.left + padX, top: r.top, right: r.right - padX, bottom: r.bottom} + flags = 0x824 | 0x8000 // left | vcenter | singleline | noprefix | DT_END_ELLIPSIS + fg = pal.codeText + case idRight: + fill := pal.accent + if pressed { + fill = pal.accentPress + } else if hovered { + fill = pal.accentHover + } + paintRoundedBox(dc, r, btnRadius, pal.surface, fill, rgb{}, false, pal.accentHighlight, !pressed) + fg = rgb{255, 255, 255} + case idLeft: + fill := pal.btnFill + if pressed { + fill = pal.btnPress + } else if hovered { + fill = pal.btnHover + } + paintRoundedBox(dc, r, btnRadius, pal.surface, fill, pal.btnBorder, true, rgb{}, false) + fg = pal.text + case idFold: + if meta.compact { + fill := pal.surface + if pressed { + fill = pal.btnPress + } else if hovered { + fill = pal.btnHover + } + paintRoundedBox(dc, r, btnRadius, pal.surface, fill, pal.cardBorder, true, rgb{}, false) + // Accent status dot on the left of the compact chip. + dotD := max(7, dialogPixels(parent, 4)) + dotX := r.left + max(10, dialogPixels(parent, 6)) + dotY := r.top + (h-dotD)/2 + paintRoundedBox(dc, rect{left: dotX, top: dotY, right: dotX + dotD, bottom: dotY + dotD}, float64(dotD)/2, fill, pal.accent, rgb{}, false, rgb{}, false) + textRect = rect{left: dotX + dotD + max(6, dialogPixels(parent, 4)), top: r.top, right: r.right - 8, bottom: r.bottom} + flags = 0x824 + fg = pal.text + } else { + fg = pal.text3 + if pressed { + paintRoundedBox(dc, r, max(5, btnRadius-2), pal.surface, pal.ghostPress, rgb{}, false, rgb{}, false) + fg = pal.text + } else if hovered { + paintRoundedBox(dc, r, max(5, btnRadius-2), pal.surface, pal.ghostHover, rgb{}, false, rgb{}, false) + fg = pal.text + } + } + case idExtra, idJump: + fg = pal.accentLink + if pressed || hovered { + fill := pal.accentLinkHover + if pressed { + fill = pal.accentSoft + } + paintRoundedBox(dc, r, max(5, btnRadius-2), pal.surface, fill, rgb{}, false, rgb{}, false) + } + padX := dialogPixels(parent, linkPadDLU) + textRect = rect{left: r.left + padX, top: r.top, right: r.right - padX, bottom: r.bottom} + flags = 0x825 | 0x8000 // center | vcenter | singleline | noprefix | DT_END_ELLIPSIS + } + + textColor.Call(dc, fg.colorref()) + drawText.Call(dc, uintptr(unsafe.Pointer(&caption[0])), n, uintptr(unsafe.Pointer(&textRect)), flags) + if it.state&0x10 != 0 && it.state&0x200 == 0 { // ODS_FOCUS without ODS_NOFOCUSRECT + fr := rect{left: r.left + 3, top: r.top + 3, right: r.right - 3, bottom: r.bottom - 3} + drawFocusRect.Call(dc, uintptr(unsafe.Pointer(&fr))) + } +} + +func setFace(lf *logFontW, name string) { + for i := range lf.face { + lf.face[i] = 0 + } + for i, ch := range name { + if i >= len(lf.face)-1 { + break + } + lf.face[i] = uint16(ch) + } +} + +// paintRoundedBox renders a mathematically anti-aliased rounded rectangle using +// a signed distance field and blits it via SetDIBitsToDevice (no GDI handles, +// no float-ABI syscalls, smooth corners and 1px hairline borders at any DPI). +func paintRoundedBox(dc uintptr, r rect, radius float64, bg, fill, border rgb, hasBorder bool, hi rgb, hasHighlight bool) { + w := int(r.right - r.left) + h := int(r.bottom - r.top) + if w <= 0 || h <= 0 { + return + } + maxR := math.Min(float64(w), float64(h)) / 2 + if radius > maxR { + radius = maxR + } + if radius < 0 { + radius = 0 + } + + buf := make([]byte, w*h*4) + hw := float64(w) / 2 + hh := float64(h) / 2 + bx := hw - radius + by := hh - radius + borderW := 1.0 + + // Precompute corner bounding margin to fast-fill interior spans. + marginX := int(math.Ceil(radius)) + 2 + marginY := int(math.Ceil(radius)) + 2 + + for y := 0; y < h; y++ { + rowOff := y * w * 4 + py := math.Abs(float64(y)+0.5-hh) - by + inFlatY := y >= marginY && y < h-marginY + for x := 0; x < w; x++ { + if inFlatY && x >= marginX && x < w-marginX { + // Fast path: deep interior pixel. + i := rowOff + x*4 + buf[i] = fill.b + buf[i+1] = fill.g + buf[i+2] = fill.r + continue + } + px := math.Abs(float64(x)+0.5-hw) - bx + qx := math.Max(px, 0) + qy := math.Max(py, 0) + // Signed distance to outer edge (negative inside, positive outside). + d := math.Hypot(qx, qy) + math.Min(math.Max(px, py), 0) - radius + outerCov := clamp01(0.5 - d) + + col := bg + if outerCov > 0 { + inner := fill + if hasHighlight && y == 1 && d <= -1.0 { + inner = hi + } + if hasBorder { + // Inner fill starts borderW pixels inside the outer edge. + innerCov := clamp01(0.5 - (d + borderW)) + inner = blendRGB(border, inner, innerCov) + } + col = blendRGB(bg, inner, outerCov) + } + i := rowOff + x*4 + buf[i] = col.b + buf[i+1] = col.g + buf[i+2] = col.r + } + } + + bmi := bitmapInfoHeader{ + size: uint32(unsafe.Sizeof(bitmapInfoHeader{})), + width: int32(w), + height: -int32(h), // top-down + planes: 1, + bitCount: 32, + } + setDIBitsToDevice.Call( + dc, + uintptr(r.left), uintptr(r.top), + uintptr(w), uintptr(h), + 0, 0, + 0, uintptr(h), + uintptr(unsafe.Pointer(&buf[0])), + uintptr(unsafe.Pointer(&bmi)), + 0, // DIB_RGB_COLORS + ) +} + +func clamp01(v float64) float64 { + if v <= 0 { + return 0 + } + if v >= 1 { + return 1 + } + return v +} diff --git a/internal/installguide/dialog_windows.go b/internal/installguide/dialog_windows.go new file mode 100644 index 0000000..896d23a --- /dev/null +++ b/internal/installguide/dialog_windows.go @@ -0,0 +1,238 @@ +package installguide + +import ( + "syscall" + "unicode/utf16" + "unsafe" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +const ( + idTitle = 100 + idBody = 101 + idInputHint = 102 + idCode = 103 + idStage = 104 + idFold = 110 + idLeft = 111 + idRight = 112 + idExtra = 113 + idJump = 114 + wmAction = 0x8001 +) + +// A standard Win32 DLGTEMPLATE in dialog units so Windows scales layout and +// controls to the monitor DPI while supporting plain `go build`. +func dialogTemplate(p page, c content, locale i18n.Locale) []uint16 { + const ( + button = 0x80 + label = 0x82 + ) + zh := locale == i18n.ZhCN + width := uint16(248) + if zh { + width = 228 + } + if p == compact { + width = 82 + if zh { + width = 62 + } + } + + // WS_POPUP | WS_CLIPCHILDREN | DS_SETFONT, WS_EX_TOOLWINDOW | WS_EX_LAYERED. + data := []uint16{0x40, 0x8200, 0x80, 8, 0, 0, 0, width, 20, 0, 0} + addString := func(s string) { + data = append(data, utf16.Encode([]rune(s))...) + data = append(data, 0) + } + addString(c.title) + data = append(data, 9) + if zh { + addString("Microsoft YaHei UI") + } else { + addString("Segoe UI") + } + item := func(class, id, x, y, w, h uint16, caption string) { + if len(data)%2 != 0 { + data = append(data, 0) + } + style := uint16(0x5000) // WS_CHILD | WS_VISIBLE + var controlStyle uint16 + if class == button { + style |= 1 // WS_TABSTOP + controlStyle = 0x0b // BS_OWNERDRAW + } else if id == idTitle || id == idStage || id == idCode { + controlStyle = 0x0d // SS_OWNERDRAW + } + data = append(data, controlStyle, style, 0, 0, x, y, w, h, id, 0xffff, class) + addString(caption) + data = append(data, 0) + data[4]++ + } + + if p == compact { + item(button, idFold, 0, 0, width, 20, c.right) + return data + } + + const padX uint16 = 12 + innerW := width - padX*2 + y := uint16(10) + + // Top meta row: stage/step pill on the left, quiet Hide button on the right. + if c.stage != "" || c.fold != "" { + stageW := innerW + if c.fold != "" { + stageW -= 38 + item(button, idFold, width-padX-34, y, 34, 15, c.fold) + } + if c.stage != "" { + item(label, idStage, padX, y, stageW, 15, c.stage) + } + y += 19 + } + + // Title + item(label, idTitle, padX, y, innerW, 16, c.title) + y += 20 + + // Body: size tightly to the actual text so cards stay compact and balanced. + bodyH := estimateBodyHeight(p, c.body, zh) + item(label, idBody, padX, y, innerW, bodyH, c.body) + y += bodyH + 5 + + // Monospace command / filename box + if c.code != "" { + item(label, idCode, padX, y, innerW, 19, c.code) + y += 24 + } + + // Release-keys footnote + if c.inputHint != "" { + item(label, idInputHint, padX, y, innerW, 13, c.inputHint) + y += 17 + } + + // Secondary text actions: inset left by linkPadDLU so unhovered text aligns + // flush with padX while hover pills sit symmetrically around the label. + if c.extra != "" { + item(button, idExtra, padX-linkPadDLU, y, innerW+linkPadDLU*2, 16, c.extra) + y += 18 + } + if c.jump != "" { + item(button, idJump, padX-linkPadDLU, y, innerW+linkPadDLU*2, 16, c.jump) + y += 18 + } + + // Footer actions + if c.left != "" || c.right != "" { + y += 6 + const btnH uint16 = 19 + leftW := uint16(52) + if zh { + leftW = 48 + } + rightW := primaryButtonWidth(c.right, zh) + rightX := width - padX - rightW + leftX := padX + if c.isConfirm { + // Standard macOS / Reims-Go confirmation order: Cancel left of Confirm. + leftX = rightX - 6 - leftW + } else if c.right == "" { + leftX = width - padX - leftW + } + if c.left != "" { + item(button, idLeft, leftX, y, leftW, btnH, c.left) + } + if c.right != "" { + item(button, idRight, rightX, y, rightW, btnH, c.right) + } + y += btnH + 11 + } else { + y += 8 + } + + data[8] = y + return data +} + +func estimateBodyHeight(p page, body string, zh bool) uint16 { + if p == failed { + return 54 + } + // Estimate visual width in half-width units (CJK = 2, ASCII = 1). + units := 0 + for _, r := range body { + if r > 0x7f { + units += 2 + } else { + units++ + } + } + unitsPerLine := 56 + if zh { + unitsPerLine = 48 + } + lines := max(1, (units+unitsPerLine-1)/unitsPerLine) + return uint16(lines*10 + 3) +} + +func primaryButtonWidth(label string, zh bool) uint16 { + runes := len([]rune(label)) + if zh { + if runes <= 3 { + return 54 + } + if runes <= 5 { + return 72 + } + return 88 + } + if runes <= 8 { + return 64 + } + if runes <= 14 { + return 88 + } + return 108 +} + +var dialogProc = syscall.NewCallback(func(hwnd, msg, wp, lp uintptr) uintptr { + switch msg { + case 0x0110: // WM_INITDIALOG + stylePanel(hwnd, lp) + case 0x0005: // WM_SIZE (including DPI changes) + roundPanel(hwnd) + case 0x000f: // WM_PAINT + paintDialogFrame(hwnd) + return 1 + case 0x0014: // WM_ERASEBKGND (WM_PAINT fills the client area) + return 1 + case 0x0318: // WM_PRINTCLIENT + if wp != 0 { + paintDialogDC(hwnd, wp) + return 1 + } + case 0x0136, 0x0138: // WM_CTLCOLORDLG, WM_CTLCOLORSTATIC + return panelBrush(hwnd, wp, lp) + case 0x002b: // WM_DRAWITEM + if lp != 0 { + var it drawItem + rtlMoveMemory.Call(uintptr(unsafe.Pointer(&it)), lp, unsafe.Sizeof(it)) + paintItem(&it) + return 1 + } + case 0x0111: // WM_COMMAND + id := wp & 0xffff + if wp>>16 == 0 && (id == idFold || id == idLeft || id == idRight || id == idExtra || id == idJump || id == 2) { + postMessage.Call(hwnd, wmAction, id, 0) + return 1 + } + case 0x0010: // WM_CLOSE: leave a way to reopen the guide. + postMessage.Call(hwnd, wmAction, 2, 0) + return 1 + } + return 0 +}) diff --git a/internal/installguide/guide.go b/internal/installguide/guide.go new file mode 100644 index 0000000..d52d2b9 --- /dev/null +++ b/internal/installguide/guide.go @@ -0,0 +1,391 @@ +// Package installguide presents the installation workflow on the guest window. +package installguide + +import ( + "fmt" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +type Kind int + +const ( + Online Kind = iota + Offline + BuiltIn +) + +type Theme string + +const ( + ThemeLight Theme = "light" + ThemeDark Theme = "dark" +) + +const OfflineCommand = "sh /Volumes/REIMSHELP/install.sh" +const ToolsCommand = "sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command" + +type Guide struct { + Name string + PID uint32 + Kind Kind + ReleaseKeys string + Locale i18n.Locale + Theme Theme + ToolsAttached bool + CurrentPreferences func() (i18n.Locale, Theme) + Unfold <-chan struct{} + TypeText func(string) error + FinishRecovery func() error + Restart func() error + AttachImage func(string) error + AttachTools func() error + LogError func(error) + dir, media string + initial page +} + +type page string + +const ( + boot page = "boot" + terminal page = "terminal" + command page = "command" + verifyCommand page = "verify-command" + selectDisk page = "select-disk" + formatDisk page = "format-disk" + reinstall page = "reinstall" + waitInstall page = "installing" + recoverMenu page = "recovery" + mediaChoice page = "media" + pickImage page = "pick-image" + confirmImage page = "confirm-image" + mounting page = "mounting" + confirm page = "confirm-install" + confirmRepair page = "confirm-repair" + restartPending page = "restart-pending" + working page = "restarting" + setup page = "setup" + network page = "network" + account page = "account" + localUser page = "local-user" + preferences page = "preferences" + desktop page = "desktop" + restored page = "restored" + toolsTerminal page = "tools-terminal" + confirmTools page = "confirm-tools" + mountTools page = "mount-tools" + toolsVerify page = "tools-verify" + typingCommand page = "typing" + typingTools page = "typing-tools" + failed page = "failed" + compact page = "compact" + done page = "done" +) + +type tone int + +const ( + toneAccent tone = iota + toneOK + toneWarn + toneDanger +) + +type content struct { + stage string + stageTone tone + title string + body string + code string + left string + right string + extra string + jump string + fold string + inputHint string + prev page + next page + alt page + isConfirm bool +} + +func (g Guide) preferences() (i18n.Locale, Theme) { + if g.CurrentPreferences != nil { + return g.CurrentPreferences() + } + return g.Locale, g.Theme +} + +func (p page) confirmsRestart() bool { + switch p { + case confirm, confirmRepair, confirmImage, confirmTools: + return true + } + return false +} + +func (g Guide) content(p page, detail string) content { + loc, _ := g.preferences() + t := func(zh, en string) string { + if loc == i18n.ZhCN { + return zh + } + return en + } + c := content{fold: t("收起", "Hide"), isConfirm: p.confirmsRestart()} + stage := func(zh, en string, step, total int, tn tone) { + label := t(zh, en) + if step > 0 && total > 0 { + c.stage = fmt.Sprintf("%s · %d / %d", label, step, total) + } else { + c.stage = label + } + c.stageTone = tn + } + card := func(zhTitle, enTitle, zhBody, enBody string) { + c.title = t(zhTitle, enTitle) + c.body = t(zhBody, enBody) + } + next := func(dst page, zh, en string) { c.next = dst; c.right = t(zh, en) } + extra := func(dst page, zh, en string) { c.alt = dst; c.extra = t(zh, en) } + back := func(dst page) { c.prev = dst; c.left = t("上一步", "Back") } + cancel := func(dst page) { c.prev = dst; c.left = t("取消", "Cancel") } + finish := func() { next(done, "完成", "Done") } + + switch p { + case boot: + switch g.Kind { + case Offline, Online: + card("等待进入恢复界面", "Wait for Recovery", + "等待苹果标志和进度条结束。若出现语言选择,选好后继续;看到恢复工具列表即可下一步。", + "Wait for the Apple logo and progress bar. Pick a language if asked, then continue when Recovery utilities appear.") + if g.Kind == Offline { + stage("离线安装", "Offline install", 1, 5, toneAccent) + next(terminal, "继续", "Continue") + } else { + stage("在线恢复", "Online recovery", 1, 5, toneAccent) + next(selectDisk, "继续", "Continue") + } + case BuiltIn: + stage("内置恢复", "Built-in recovery", 1, 2, toneAccent) + card("在引导菜单选 Recovery", "Select Recovery in boot menu", + "在 OpenCore 启动菜单选「Recovery」按回车,等恢复工具列表出现后继续。", + "Choose Recovery in the OpenCore boot picker and press Return. Continue when the recovery utilities appear.") + next(recoverMenu, "继续", "Continue") + } + case terminal: + stage("离线安装", "Offline install", 2, 5, toneAccent) + card("打开恢复终端", "Open Recovery Terminal", + "在顶部菜单栏打开「实用工具 › 终端」(Utilities › Terminal),不要点「重新安装 macOS」。", + "Open Utilities › Terminal from the menu bar. Don’t click Reinstall macOS.") + back(boot) + next(command, "继续", "Continue") + case command: + stage("离线安装", "Offline install", 3, 5, toneAccent) + card("键入安装命令", "Type installer command", + "点「键入命令」自动输入到终端。脚本会抹除空白磁盘为 APFS 并启动安装。", + "Click Type command to send this to Terminal. It formats a blank disk as APFS and starts installation.") + c.code = OfflineCommand + back(terminal) + next(typingCommand, "键入命令", "Type command") + extra(verifyCommand, "已手动输入", "Already typed it") + case verifyCommand: + stage("离线安装", "Offline install", 4, 5, toneAccent) + card("在终端按回车运行", "Press Return in Terminal", + "核对终端命令后按回车;若提示抹盘,确认是目标磁盘再继续。看到安装进度后点下一步。", + "Check the command in Terminal and press Return. Confirm the target disk if asked, then continue once installation starts.") + back(command) + next(waitInstall, "继续", "Continue") + case selectDisk: + stage("在线恢复", "Online recovery", 2, 5, toneAccent) + card("选择目标磁盘", "Select target disk", + "全新空盘打开「磁盘工具」,选「显示 › 显示所有设备」,按容量找到 QEMU 磁盘;已有 APFS 卷可直接重装。", + "For a blank disk, open Disk Utility › View › Show All Devices and find the QEMU disk by size, or use an existing APFS volume.") + back(boot) + next(formatDisk, "抹掉空盘", "Erase disk") + extra(reinstall, "使用现有 APFS 卷", "Use existing APFS volume") + case formatDisk: + stage("在线恢复", "Online recovery", 3, 5, toneAccent) + card("抹掉空白系统盘", "Erase blank disk", + "确认选中目标空盘后点「抹掉」:名称 Macintosh HD,格式 APFS,方案 GUID 分区图。完成后退出磁盘工具。", + "Click Erase on the blank disk: name Macintosh HD, format APFS, scheme GUID Partition Map. Quit Disk Utility when finished.") + back(selectDisk) + next(reinstall, "继续", "Continue") + case reinstall: + if g.Kind == BuiltIn { + stage("内置恢复", "Built-in recovery", 0, 0, toneAccent) + back(mediaChoice) + } else { + stage("在线恢复", "Online recovery", 4, 5, toneAccent) + back(selectDisk) + } + card("开始安装 macOS", "Start macOS install", + "在恢复工具选「重新安装 macOS」,选择目标系统卷并继续。出现安装进度条后点下一步。", + "Choose Reinstall macOS in Recovery and select the target system volume. Continue once the progress bar appears.") + next(waitInstall, "继续", "Continue") + case waitInstall: + switch g.Kind { + case Offline: + stage("离线安装", "Offline install", 5, 5, toneAccent) + back(verifyCommand) + case Online: + stage("在线恢复", "Online recovery", 5, 5, toneAccent) + back(reinstall) + default: + stage("内置恢复", "Built-in recovery", 0, 0, toneAccent) + back(reinstall) + } + card("等待安装完成", "Wait for installation", + "进度条可能停留较久,中途会重启几次。看到「设置助理」或 Apple 账户页后,退出恢复模式。", + "Progress may pause and the VM restarts several times. Exit recovery once Setup Assistant or Apple Account appears.") + next(confirm, "退出恢复…", "Exit recovery…") + case recoverMenu: + stage("内置恢复", "Built-in recovery", 2, 2, toneAccent) + card("使用恢复工具", "Use recovery utilities", + "可使用磁盘工具修复或排查问题;重装系统可选在线恢复或挂载本地镜像。", + "Use Disk Utility or other recovery tools here, or choose to reinstall macOS online or from a local image.") + back(boot) + next(confirmRepair, "退出恢复…", "Exit recovery…") + extra(mediaChoice, "重新安装 macOS", "Reinstall macOS") + case mediaChoice: + stage("内置恢复", "Built-in recovery", 0, 0, toneAccent) + card("选择重装方式", "Choose reinstall source", + "在线重装直接使用当前恢复环境;本地镜像将在挂载并重启虚拟机后启动。", + "Online reinstall uses this recovery environment. A local image boots after attaching it and restarting the VM.") + back(recoverMenu) + next(reinstall, "在线重装", "Reinstall online") + extra(pickImage, "选择本地镜像…", "Choose local image…") + case confirmImage: + stage("确认重启", "Confirm restart", 0, 0, toneWarn) + card("挂载镜像并重启?", "Attach image and restart?", + "确认当前恢复操作已结束。继续会挂载该镜像并重启虚拟机。", + "Make sure recovery work is done. Continuing attaches this image and restarts the VM.") + c.code = detail + cancel(mediaChoice) + next(mounting, "挂载并重启", "Attach and restart") + case confirm, confirmRepair: + stage("确认重启", "Confirm restart", 0, 0, toneWarn) + card("退出恢复模式并重启?", "Exit recovery and restart?", + "若仍有安装进度条,返回继续等待。确认后会退出恢复模式、启用网络并重启「"+g.Name+"」。", + "If installation is still running, go back and wait. Confirm to exit recovery, enable networking and restart “"+g.Name+"”.") + if p == confirmRepair { + cancel(recoverMenu) + } else { + cancel(waitInstall) + } + next(working, "退出并重启", "Exit and restart") + case restartPending: + stage("等待重启", "Restart required", 0, 0, toneWarn) + card("重启虚拟机以生效", "Restart VM to apply", + "配置已更新,重启这台虚拟机后即可生效。", + "Settings were updated. Restart this VM to apply the changes.") + next(working, "重启虚拟机", "Restart VM") + case setup: + stage("设置助理", "Setup Assistant", 1, 6, toneAccent) + card("选择地区与键盘", "Region and keyboard", + "等待系统盘启动。在设置助理中选好国家或地区、语言和键盘,已完成可直接下一步。", + "Wait for macOS to boot, then choose your country or region, language and keyboard.") + next(network, "继续", "Continue") + extra(desktop, "已进入桌面", "Already at desktop") + case network: + stage("设置助理", "Setup Assistant", 2, 6, toneAccent) + card("连接虚拟以太网", "Connect via Ethernet", + "网络现已启用。若提示联网,选择虚拟以太网;已自动连接可直接继续。", + "Networking is enabled. Choose virtual Ethernet if prompted, or continue if already connected.") + back(setup) + next(account, "继续", "Continue") + case account: + stage("设置助理", "Setup Assistant", 3, 6, toneAccent) + card("登录 Apple 账户", "Sign in to Apple Account", + "可直接登录 Apple 账户;若想稍后再登,点「其他登录选项」并选「稍后设置」。", + "Sign in to your Apple Account, or choose Other Sign-In Options › Set Up Later.") + back(network) + next(localUser, "继续", "Continue") + case localUser: + stage("设置助理", "Setup Assistant", 4, 6, toneAccent) + card("创建本地账户", "Create local account", + "填写 macOS 用户名与登录密码;覆盖重装保留原账户时,直接登录即可。", + "Enter a local user name and password, or sign in to an existing account after a reinstall.") + back(account) + next(preferences, "继续", "Continue") + case preferences: + stage("设置助理", "Setup Assistant", 5, 6, toneAccent) + card("完成其余系统选项", "Finish setup screens", + "按需完成隐私、定位与外观等页面,看到程序坞与顶部菜单栏即进入桌面。", + "Finish the remaining privacy, location and appearance screens until the Dock and menu bar appear.") + back(localUser) + next(desktop, "继续", "Continue") + case desktop: + stage("设置助理", "Setup Assistant", 6, 6, toneOK) + card("已进入 macOS 桌面", "macOS is ready", + "现在可以开始使用 macOS。如需双向剪贴板和共享文件夹,可选装 Guest Tools。", + "macOS is ready to use. Optionally install Guest Tools for shared clipboard and folders.") + back(preferences) + finish() + if g.ToolsAttached { + extra(toolsTerminal, "安装 Guest Tools", "Install Guest Tools") + } else { + extra(confirmTools, "挂载 Guest Tools…", "Attach Guest Tools…") + } + case confirmTools: + stage("确认重启", "Confirm restart", 0, 0, toneWarn) + card("挂载工具盘并重启?", "Attach Guest Tools and restart?", + "先保存桌面上的内容。继续会挂载 REIMSTOOLS 工具盘并重启虚拟机。", + "Save open work first. Continuing attaches the REIMSTOOLS disk and restarts the VM.") + cancel(desktop) + next(mountTools, "挂载并重启", "Attach and restart") + case toolsTerminal: + stage("Guest Tools", "Guest Tools", 1, 2, toneAccent) + card("在 macOS 中打开终端", "Open Terminal in macOS", + "打开「应用程序 › 实用工具 › 终端」,点下方按钮键入安装命令。", + "Open Applications › Utilities › Terminal, then click below to type the command.") + c.code = ToolsCommand + back(desktop) + next(typingTools, "键入命令", "Type command") + case toolsVerify: + stage("Guest Tools", "Guest Tools", 2, 2, toneOK) + card("完成 Guest Tools 安装", "Finish Guest Tools setup", + "在终端核对命令后按回车,按提示完成安装即可使用剪贴板与共享文件夹。", + "Check the command in Terminal, press Return and follow the prompts to finish.") + back(toolsTerminal) + finish() + case restored: + stage("已回到系统", "Back on macOS", 0, 0, toneOK) + card("从系统盘继续", "Continue from system disk", + "可正常登录 macOS。若进入设置助理,可继续查看联网与账户步骤。", + "Sign in to macOS as usual, or continue with Setup Assistant guidance if it appears.") + extra(setup, "查看设置助理引导", "Open Setup Assistant guide") + finish() + case failed: + stage("出错", "Error", 0, 0, toneDanger) + card("操作未完成", "Could not complete step", detail, detail) + c.left = t("返回", "Back") + case typingCommand, typingTools, working, mounting, mountTools: + stage("进行中", "Working", 0, 0, toneAccent) + if p == typingCommand || p == typingTools { + card("正在键入命令", "Typing command", + "等待命令输入到终端…", + "Waiting for the command to appear in Terminal…") + } else { + card("正在重启虚拟机", "Restarting VM", + "等待虚拟机窗口重新打开…", + "Waiting for the VM window to reopen…") + } + case compact: + return content{right: t("安装引导", "Install guide")} + } + if (c.next == "" && c.prev == "" && c.alt == "") || c.isConfirm { + c.fold = "" + } + if p == boot && g.ReleaseKeys != "" { + c.inputHint = t("释放键鼠:", "Release input: ") + g.ReleaseKeys + } + // The guest may be ahead of the guide when the user follows the installer + // directly. Keep the setup handoff reachable from earlier install screens. + switch p { + case boot, terminal, command, verifyCommand, selectDisk, formatDisk, reinstall: + c.jump = t("已到设置助理?退出恢复模式", "At Setup Assistant? Exit recovery") + } + return c +} diff --git a/internal/installguide/overlay_other.go b/internal/installguide/overlay_other.go new file mode 100644 index 0000000..7210565 --- /dev/null +++ b/internal/installguide/overlay_other.go @@ -0,0 +1,7 @@ +//go:build !windows + +package installguide + +import "context" + +func Run(context.Context, Guide) error { return nil } diff --git a/internal/installguide/overlay_windows.go b/internal/installguide/overlay_windows.go new file mode 100644 index 0000000..19a2ebd --- /dev/null +++ b/internal/installguide/overlay_windows.go @@ -0,0 +1,463 @@ +package installguide + +import ( + "context" + "fmt" + "runtime" + "sync" + "syscall" + "unsafe" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +const ( + wmSync = 0x8002 + eventSystemForeground = 0x0003 + eventSystemMoveSizeEnd = 0x000B + eventSystemDialogStart = 0x0010 + eventSystemDialogEnd = 0x0011 + eventSystemMinimizeStart = 0x0016 + eventSystemMinimizeEnd = 0x0017 + eventObjectLocation = 0x800B +) + +var ( + user32 = syscall.NewLazyDLL("user32.dll") + createDialog = user32.NewProc("CreateDialogIndirectParamW") + destroyWindow = user32.NewProc("DestroyWindow") + getForeground = user32.NewProc("GetForegroundWindow") + setForeground = user32.NewProc("SetForegroundWindow") + windowPID = user32.NewProc("GetWindowThreadProcessId") + getClientRect = user32.NewProc("GetClientRect") + clientToScreen = user32.NewProc("ClientToScreen") + getWindowRect = user32.NewProc("GetWindowRect") + setWindowPos = user32.NewProc("SetWindowPos") + showWindow = user32.NewProc("ShowWindow") + isWindow = user32.NewProc("IsWindow") + isWindowEnabled = user32.NewProc("IsWindowEnabled") + isIconic = user32.NewProc("IsIconic") + getWindow = user32.NewProc("GetWindow") + getClassNameW = user32.NewProc("GetClassNameW") + setWinEventHook = user32.NewProc("SetWinEventHook") + unhookWinEvent = user32.NewProc("UnhookWinEvent") + setTimer = user32.NewProc("SetTimer") + killTimer = user32.NewProc("KillTimer") + getMessage = user32.NewProc("GetMessageW") + postMessage = user32.NewProc("PostMessageW") + postThreadMsg = user32.NewProc("PostThreadMessageW") + isDialogMessage = user32.NewProc("IsDialogMessageW") + translateMessage = user32.NewProc("TranslateMessage") + dispatchMessage = user32.NewProc("DispatchMessageW") + getCurrentThreadID = kernel32.NewProc("GetCurrentThreadId") + + winEventMu sync.Mutex + winEventHooks = map[uintptr]func(event uint32, hwnd uintptr, idObject, idChild int32){} + winEventProc = syscall.NewCallback(func(hook, event, hwnd, idObject, idChild, thread, ms uintptr) uintptr { + winEventMu.Lock() + fn := winEventHooks[hook] + winEventMu.Unlock() + if fn != nil { + fn(uint32(event), hwnd, int32(idObject), int32(idChild)) + } + return 0 + }) +) + +func registerWinEventHook(minEvent, maxEvent, pid uint32, fn func(event uint32, hwnd uintptr, idObject, idChild int32)) func() { + h, _, _ := setWinEventHook.Call( + uintptr(minEvent), + uintptr(maxEvent), + 0, + winEventProc, + uintptr(pid), + 0, + 0, // WINEVENT_OUTOFCONTEXT + ) + if h == 0 { + return func() {} + } + winEventMu.Lock() + winEventHooks[h] = fn + winEventMu.Unlock() + return func() { + unhookWinEvent.Call(h) + winEventMu.Lock() + delete(winEventHooks, h) + winEventMu.Unlock() + } +} + +type point struct{ x, y int32 } +type rect struct{ left, top, right, bottom int32 } +type message struct { + hwnd uintptr + id uint32 + wp, lp uintptr + time uint32 + pt point + private uint32 +} + +type panel struct { + owner, hwnd uintptr + lastX, lastY int32 + visible bool + stale bool + inModal bool + renderedLoc i18n.Locale + renderedDark bool +} + +func (w *panel) close() { + if w.hwnd != 0 { + destroyWindow.Call(w.hwnd) + w.hwnd = 0 + } + w.visible = false + w.stale = false +} + +func (w *panel) targetOrigin(hwnd uintptr) (int32, int32, bool) { + var client, bounds rect + var origin point + if ok, _, _ := getClientRect.Call(w.owner, uintptr(unsafe.Pointer(&client))); ok == 0 { + return 0, 0, false + } + if client.right <= 0 || client.bottom <= 0 { + return 0, 0, false + } + if ok, _, _ := clientToScreen.Call(w.owner, uintptr(unsafe.Pointer(&origin))); ok == 0 { + return 0, 0, false + } + getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&bounds))) + width := bounds.right - bounds.left + height := bounds.bottom - bounds.top + x := origin.x + max(0, client.right-width-12) + y := origin.y + min(42, max(0, client.bottom-height)) + return x, y, true +} + +func (w *panel) place() { + x, y, ok := w.targetOrigin(w.hwnd) + if !ok { + return + } + if w.visible && x == w.lastX && y == w.lastY { + return + } + wasHidden := !w.visible + // SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER: + // move without changing Z-order, stealing focus, or touching the owner. + flags := uintptr(0x0215) + if wasHidden { + // Re-reveal from alpha=0 after synchronous painting to avoid stale/blank frames. + setLayeredAttr.Call(w.hwnd, 0, 0, 2) + flags |= 0x0040 // SWP_SHOWWINDOW + } + // Preserve Z order and keyboard focus. The guest owns this popup, so + // it stays above this VM without making it desktop-wide topmost. + if res, _, _ := setWindowPos.Call(w.hwnd, 0, uintptr(x), uintptr(y), 0, 0, flags); res != 0 { + if wasHidden { + revealPanel(w.hwnd) + } + w.lastX, w.lastY, w.visible = x, y, true + } +} + +// followOwner updates the overlay position immediately in response to WinEvent +// notifications while the guest display window is dragged, resized, or snapped. +func (w *panel) followOwner() { + if w.inModal || w.hwnd == 0 || w.owner == 0 { + return + } + if iconic, _, _ := isIconic.Call(w.owner); iconic != 0 { + w.hide() + return + } + if enabled, _, _ := isWindowEnabled.Call(w.owner); enabled == 0 { + w.hide() + return + } + if w.visible { + w.place() + } +} + +// attachHooks registers out-of-context WinEvent hooks on the current UI thread +// so moving, resizing, minimizing, or switching away from the guest window +// updates the overlay immediately instead of waiting for the 200ms timer tick. +func (w *panel) attachHooks(pid uint32, onSync func()) func() { + var cleanups []func() + if pid != 0 { + cleanups = append(cleanups, registerWinEventHook(eventObjectLocation, eventObjectLocation, pid, + func(event uint32, hwnd uintptr, idObject, idChild int32) { + if idObject == 0 && idChild == 0 && hwnd != 0 && hwnd == w.owner { + w.followOwner() + } + })) + cleanups = append(cleanups, registerWinEventHook(eventSystemMoveSizeEnd, eventSystemMinimizeEnd, pid, + func(event uint32, hwnd uintptr, idObject, idChild int32) { + if w.inModal { + return + } + switch event { + case eventSystemMoveSizeEnd: + if hwnd == w.owner { + w.followOwner() + onSync() + } + case eventSystemMinimizeStart: + if hwnd == w.owner { + w.hide() + } + case eventSystemMinimizeEnd, eventSystemDialogStart, eventSystemDialogEnd: + onSync() + } + })) + } + cleanups = append(cleanups, registerWinEventHook(eventSystemForeground, eventSystemForeground, 0, + func(event uint32, hwnd uintptr, idObject, idChild int32) { + if !w.inModal { + onSync() + } + })) + return func() { + for i := len(cleanups) - 1; i >= 0; i-- { + cleanups[i]() + } + } +} + +// markStale schedules an atomic swap on the next sync: the old dialog stays on +// screen until the replacement is fully painted and revealed, eliminating flash. +func (w *panel) markStale() { + w.stale = true +} + +// isGuestDisplayWindow reports whether hwnd is a top-level VM display surface +// rather than an owned popup or modal dialog (such as QEMU's "Turn off the VM?" +// MessageBox) belonging to the same QEMU process. +func isGuestDisplayWindow(hwnd uintptr) bool { + if hwnd == 0 { + return false + } + // Owned popups / modal dialogs have GW_OWNER != 0. + if owner, _, _ := getWindow.Call(hwnd, 4); owner != 0 { + return false + } + // Standard Win32 dialogs / MessageBoxes (#32770) are never the VM display. + var cls [32]uint16 + if n, _, _ := getClassNameW.Call(hwnd, uintptr(unsafe.Pointer(&cls[0])), uintptr(len(cls))); n > 0 { + if syscall.UTF16ToString(cls[:n]) == "#32770" { + return false + } + } + // Ignore tiny helper/confirmation windows that cannot host the VM display. + var client rect + if ok, _, _ := getClientRect.Call(hwnd, uintptr(unsafe.Pointer(&client))); ok == 0 { + return false + } + return client.right >= 480 && client.bottom >= 300 +} + +func (w *panel) hide() { + if w.hwnd != 0 && w.visible { + showWindow.Call(w.hwnd, 0) + w.visible = false + } +} + +func (w *panel) sync(fg uintptr, g Guide, p page, failure string) error { + var pid uint32 + windowPID.Call(fg, uintptr(unsafe.Pointer(&pid))) + if w.hwnd != 0 { + if ok, _, _ := isWindow.Call(w.hwnd); ok == 0 { + w.hwnd = 0 + w.visible = false + w.stale = false + } + } + switch { + case w.hwnd != 0 && fg == w.hwnd: + case fg != 0 && pid == g.PID && isGuestDisplayWindow(fg): + if w.owner != fg { + w.close() + w.owner = fg + } + default: + w.hide() + return nil + } + // Hide if the guest display is minimized or disabled by a modal dialog. + if iconic, _, _ := isIconic.Call(w.owner); iconic != 0 { + w.hide() + return nil + } + if enabled, _, _ := isWindowEnabled.Call(w.owner); enabled == 0 { + w.hide() + return nil + } + loc, th := g.preferences() + dark := resolveDark(th) + needBuild := w.hwnd == 0 || w.stale || w.renderedLoc != loc || w.renderedDark != dark + if needBuild { + oldHwnd := w.hwnd + g.Locale = loc + c := g.content(p, failure) + template := dialogTemplate(p, c, loc) + flags := uintptr(c.stageTone) << dialogToneShift + if dark { + flags |= dialogDark + } + if p == compact { + flags |= dialogCompact + } + hwnd, _, err := createDialog.Call(0, uintptr(unsafe.Pointer(&template[0])), w.owner, dialogProc, flags) + if hwnd == 0 { + // The renderer can replace its window while toggling fullscreen. + if ok, _, _ := isWindow.Call(w.owner); ok == 0 { + w.close() + return nil + } + return fmt.Errorf("create installation guide: %w", err) + } + w.hwnd = hwnd + w.visible = false + w.stale = false + w.renderedLoc = loc + w.renderedDark = dark + w.place() + if oldHwnd != 0 { + if fg == oldHwnd { + setForeground.Call(w.owner) + } + destroyWindow.Call(oldHwnd) + } + return nil + } + w.place() + return nil +} + +// Run owns one modeless guide on its own UI thread for the life of this VM +// process. Only an explicit click on the confirmation page invokes the action. +func Run(ctx context.Context, g Guide) error { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + timer, _, err := setTimer.Call(0, 0, 200, 0) + if timer == 0 { + return fmt.Errorf("install guide timer: %w", err) + } + defer killTimer.Call(0, timer) + var w panel + defer w.close() + tid, _, _ := getCurrentThreadID.Call() + var syncQueued bool + postSync := func() { + if syncQueued || tid == 0 { + return + } + if ok, _, _ := postThreadMsg.Call(tid, wmSync, 0, 0); ok != 0 { + syncQueued = true + } + } + defer w.attachHooks(g.PID, postSync)() + s := session{current: g.initial} + result := make(chan outcome, 1) + remember := func(p page) { + if p.recoveryStep(g.Kind) || p.postInstall() { + if err := g.save(p, 0); err != nil && g.LogError != nil { + g.LogError(err) + } + } + } + postSync() + for ctx.Err() == nil { + var msg message + ret, _, err := getMessage.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(ret) == -1 { + return err + } + if ret == 0 { + return nil + } + if msg.id == wmAction && msg.hwnd == w.hwnd && w.hwnd != 0 { + next := s.target(g, msg.wp) + if next == s.current { + continue + } + switch next { + case done: + if err := g.save(done, 0); err != nil { + s.failure, s.returnTo, s.current = err.Error(), s.current, failed + } else { + return nil + } + case pickImage: + w.inModal = true + path, err := chooseImage(w.hwnd, w.renderedLoc) + w.inModal = false + syncQueued = false + if err != nil { + s.failure, s.returnTo, s.current = err.Error(), mediaChoice, failed + } else if path != "" { + s.imagePath = path + s.enter(confirmImage) + } else { + postSync() + continue + } + case working, mounting, mountTools, typingCommand, typingTools: + from := s.current + s.enter(next) + go func(path string) { result <- g.perform(next, from, path) }(s.imagePath) + default: + s.enter(next) + remember(next) + } + w.markStale() + } else if msg.hwnd == 0 && msg.id == wmSync { + syncQueued = false + } else if msg.id != 0x0113 || msg.hwnd != 0 { // WM_TIMER + if w.hwnd != 0 { + if handled, _, _ := isDialogMessage.Call(w.hwnd, uintptr(unsafe.Pointer(&msg))); handled != 0 { + continue + } + } + translateMessage.Call(uintptr(unsafe.Pointer(&msg))) + dispatchMessage.Call(uintptr(unsafe.Pointer(&msg))) + continue + } + syncQueued = false + select { + case <-g.Unfold: + if s.current == compact { + s.enter(s.unfolded) + w.markStale() + } + default: + } + select { + case res := <-result: + if res.err != nil { + s.current, s.returnTo, s.failure = failed, res.next, res.err.Error() + if g.LogError != nil { + g.LogError(res.err) + } + } else if res.next == "" { + return nil + } else { + s.enter(res.next) + remember(res.next) + } + w.markStale() + default: + } + fg, _, _ := getForeground.Call() + if err := w.sync(fg, g, s.current, s.detail()); err != nil { + return err + } + } + return nil +} diff --git a/internal/installguide/overlay_windows_test.go b/internal/installguide/overlay_windows_test.go new file mode 100644 index 0000000..d5ccf8e --- /dev/null +++ b/internal/installguide/overlay_windows_test.go @@ -0,0 +1,329 @@ +package installguide + +import ( + "os" + "runtime" + "syscall" + "testing" + "time" + "unsafe" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +// Exercise the actual Win32 controls without taking focus or starting a VM. +func TestOwnedGuide(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + class, _ := syscall.UTF16PtrFromString("STATIC") + offscreen := int32(-16000) + owner, _, err := user32.NewProc("CreateWindowExW").Call(0x80, uintptr(unsafe.Pointer(class)), 0, 0x80000000, + uintptr(offscreen), uintptr(offscreen), 1280, 720, 0, 0, 0, 0) + if owner == 0 { + t.Fatal(err) + } + defer destroyWindow.Call(owner) + g := Guide{Name: "test-vm", PID: uint32(os.Getpid()), Kind: Offline, Locale: i18n.ZhCN, Theme: ThemeLight} + var w panel + defer w.close() + getItem := user32.NewProc("GetDlgItem") + send := user32.NewProc("SendMessageW") + peek := user32.NewProc("PeekMessageW") + for _, step := range []struct { + from page + button uintptr + want page + }{ + {boot, idFold, compact}, {compact, idFold, boot}, + {boot, idRight, terminal}, {terminal, idRight, command}, {command, idRight, typingCommand}, + {command, idExtra, verifyCommand}, {verifyCommand, idRight, waitInstall}, {waitInstall, idRight, confirm}, + {confirm, idLeft, waitInstall}, {confirm, idRight, working}, {failed, idLeft, command}, + {setup, idRight, network}, {network, idRight, account}, {account, idRight, localUser}, + {localUser, idRight, preferences}, {preferences, idRight, desktop}, {desktop, idRight, done}, + } { + if err := w.sync(owner, g, step.from, "test failure"); err != nil { + t.Fatal(err) + } + if actual, _, _ := user32.NewProc("GetWindow").Call(w.hwnd, 4); actual != owner { + t.Fatal("guide has wrong owner") + } + var guest, overlay rect + getWindowRect.Call(owner, uintptr(unsafe.Pointer(&guest))) + getWindowRect.Call(w.hwnd, uintptr(unsafe.Pointer(&overlay))) + if overlay.right > guest.right || overlay.left < guest.left || overlay.top < guest.top || overlay.bottom > guest.bottom { + t.Fatalf("guide outside guest: %+v vs %+v", overlay, guest) + } + button, _, _ := getItem.Call(w.hwnd, step.button) + if button == 0 { + t.Fatalf("missing button %d on page %s", step.button, step.from) + } + send.Call(button, 0x00f5, 0, 0) // BM_CLICK + var msg message + ok, _, _ := peek.Call(uintptr(unsafe.Pointer(&msg)), w.hwnd, wmAction, wmAction, 1) + if ok == 0 || (session{current: step.from, unfolded: boot, returnTo: command}).target(g, msg.wp) != step.want { + t.Fatalf("click on page %s: %+v", step.from, msg) + } + if err := w.sync(0, g, step.from, ""); err != nil { + t.Fatal(err) + } + if visible, _, _ := user32.NewProc("IsWindowVisible").Call(w.hwnd); visible != 0 { + t.Fatal("guide still visible over another application") + } + w.close() + } + + // Live theme switch & atomic swap rebuild the panel and destroy the old HWND. + g.Theme = ThemeLight + if err := w.sync(owner, g, command, ""); err != nil { + t.Fatal(err) + } + firstHWND := w.hwnd + if getDialogMeta(firstHWND).dark { + t.Fatal("expected light dialog meta") + } + // Verify link control hugs its label symmetrically instead of spanning the whole card. + if extra, _, _ := getItem.Call(firstHWND, idExtra); extra != 0 { + var linkRect, cardRect rect + getClientRect.Call(extra, uintptr(unsafe.Pointer(&linkRect))) + getClientRect.Call(firstHWND, uintptr(unsafe.Pointer(&cardRect))) + if linkRect.right >= cardRect.right/2 { + t.Fatalf("extra link was not shrunk to text width: link=%d card=%d", linkRect.right, cardRect.right) + } + } + g.Theme = ThemeDark + if err := w.sync(owner, g, command, ""); err != nil { + t.Fatal(err) + } + if w.hwnd == firstHWND || !getDialogMeta(w.hwnd).dark { + t.Fatal("theme switch did not rebuild dialog in dark mode") + } + if ok, _, _ := isWindow.Call(firstHWND); ok != 0 { + t.Fatal("atomic swap leaked previous dialog HWND") + } + // Verify stale atomic swap (page change) destroys old HWND and shows new page. + secondHWND := w.hwnd + w.markStale() + if err := w.sync(owner, g, failed, "stop timed out"); err != nil { + t.Fatal(err) + } + if w.hwnd == secondHWND || getDialogMeta(w.hwnd).stageTone != toneDanger { + t.Fatalf("failed page swap: hwnd=%#x tone=%d", w.hwnd, getDialogMeta(w.hwnd).stageTone) + } + if ok, _, _ := isWindow.Call(secondHWND); ok != 0 { + t.Fatal("page swap leaked previous dialog HWND") + } + + // Verify an owned/small QEMU modal dialog (like "Turn off the VM?") hides + // the guide instead of stealing ownership and getting covered by it. + modal, _, err := user32.NewProc("CreateWindowExW").Call(0, uintptr(unsafe.Pointer(class)), 0, 0x80000000, + uintptr(offscreen), uintptr(offscreen), 360, 160, owner, 0, 0, 0) + if modal == 0 { + t.Fatal(err) + } + defer destroyWindow.Call(modal) + if err := w.sync(modal, g, failed, "stop timed out"); err != nil { + t.Fatal(err) + } + if w.owner != owner { + t.Fatal("guide re-parented onto guest modal dialog") + } + if visible, _, _ := user32.NewProc("IsWindowVisible").Call(w.hwnd); visible != 0 { + t.Fatal("guide remained visible over guest modal dialog") + } + if err := w.sync(owner, g, failed, "stop timed out"); err != nil { + t.Fatal(err) + } + if visible, _, _ := user32.NewProc("IsWindowVisible").Call(w.hwnd); visible == 0 { + t.Fatal("guide did not reappear after guest modal dialog closed") + } + w.close() + + if (session{current: working}).target(g, idRight) != working { + t.Fatal("double click repeated the action") + } + + // Verify body and control labels fit cleanly across locales, themes, kinds and pages. + for _, loc := range []i18n.Locale{i18n.ZhCN, i18n.EnUS} { + g.Locale = loc + g.Theme = ThemeLight + g.ReleaseKeys = "Ctrl+Alt+Win" + for _, kind := range []Kind{Offline, Online, BuiltIn} { + g.Kind = kind + for _, p := range []page{boot, terminal, command, verifyCommand, selectDisk, formatDisk, reinstall, waitInstall, recoverMenu, mediaChoice, confirmImage, confirm, confirmRepair, restartPending, setup, network, account, localUser, preferences, desktop, restored, confirmTools, toolsTerminal, toolsVerify, working, typingTools, failed, compact} { + detail := "offline-installer-tahoe-26.7.3.img" + if p == failed { + detail = "stop timed out waiting for guest shutdown" + } + if err := w.sync(owner, g, p, detail); err != nil { + t.Fatal(err) + } + c := g.content(p, detail) + if p == compact { + if ctrl, _, _ := getItem.Call(w.hwnd, idFold); ctrl != 0 { + checkSingleLineFits(t, ctrl, c.right, 500, 1, 1, 22) + } + } else { + if body, _, _ := getItem.Call(w.hwnd, idBody); body != 0 { + checkTextFits(t, body, c.body) + } + if title, _, _ := getItem.Call(w.hwnd, idTitle); title != 0 { + checkSingleLineFits(t, title, c.title, 600, 6, 5, 0) + } + if right, _, _ := getItem.Call(w.hwnd, idRight); right != 0 && c.right != "" { + checkSingleLineFits(t, right, c.right, 600, 1, 1, 12) + } + if left, _, _ := getItem.Call(w.hwnd, idLeft); left != 0 && c.left != "" { + checkSingleLineFits(t, left, c.left, 500, 1, 1, 12) + } + if hint, _, _ := getItem.Call(w.hwnd, idInputHint); hint != 0 && c.inputHint != "" { + checkSingleLineFits(t, hint, c.inputHint, 400, 1, 1, 0) + } + } + w.close() + } + } + } +} + +func checkTextFits(t *testing.T, label uintptr, text string) { + t.Helper() + dc, _, _ := user32.NewProc("GetDC").Call(label) + defer user32.NewProc("ReleaseDC").Call(label, dc) + font, _, _ := sendMessage.Call(label, 0x0031, 0, 0) // WM_GETFONT + old, _, _ := selectGDI.Call(dc, font) + defer selectGDI.Call(dc, old) + var available rect + getClientRect.Call(label, uintptr(unsafe.Pointer(&available))) + needed := available + s, _ := syscall.UTF16FromString(text) + drawText.Call(dc, uintptr(unsafe.Pointer(&s[0])), uintptr(len(s)-1), uintptr(unsafe.Pointer(&needed)), 0x410) // DT_CALCRECT | DT_WORDBREAK + if needed.bottom > available.bottom || needed.right > available.right { + t.Errorf("text needs %+v, have %+v: %s", needed, available, text) + } +} + +func checkSingleLineFits(t *testing.T, ctrl uintptr, text string, weight, num, den, padX int32) { + t.Helper() + dc, _, _ := user32.NewProc("GetDC").Call(ctrl) + defer user32.NewProc("ReleaseDC").Call(ctrl, dc) + font, _, _ := sendMessage.Call(ctrl, 0x0031, 0, 0) + useFont := font + var custom uintptr + if font != 0 { + var lf logFontW + if n, _, _ := getObjectW.Call(font, unsafe.Sizeof(lf), uintptr(unsafe.Pointer(&lf))); n != 0 { + lf.weight = weight + lf.height = lf.height * num / den + if f, _, _ := createFontIndirectW.Call(uintptr(unsafe.Pointer(&lf))); f != 0 { + custom = f + useFont = f + defer deleteGDI.Call(custom) + } + } + } + old, _, _ := selectGDI.Call(dc, useFont) + defer selectGDI.Call(dc, old) + var available rect + getClientRect.Call(ctrl, uintptr(unsafe.Pointer(&available))) + needed := available + s, _ := syscall.UTF16FromString(text) + drawText.Call(dc, uintptr(unsafe.Pointer(&s[0])), uintptr(len(s)-1), uintptr(unsafe.Pointer(&needed)), 0x400|0x820) + if needed.right+padX > available.right || needed.bottom > available.bottom { + t.Errorf("single-line needs %+v (+%dpx pad), have %+v: %q", needed, padX, available, text) + } +} + +func TestWinEventFollowsOwner(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + class, _ := syscall.UTF16PtrFromString("STATIC") + offX, offY := int32(-16000), int32(-16000) + // WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE (0x08000080), WS_POPUP | WS_VISIBLE (0x90000000) + // Offscreen visible window so Win32 emits EVENT_OBJECT_LOCATIONCHANGE without taking focus or showing on screen. + owner, _, err := user32.NewProc("CreateWindowExW").Call( + 0x08000080, uintptr(unsafe.Pointer(class)), 0, 0x90000000, + uintptr(offX), uintptr(offY), 1280, 720, 0, 0, 0, 0, + ) + if owner == 0 { + t.Fatal(err) + } + defer destroyWindow.Call(owner) + + g := Guide{Name: "test-vm", PID: uint32(os.Getpid()), Kind: Offline, Locale: i18n.ZhCN, Theme: ThemeDark} + var w panel + defer w.close() + if err := w.sync(owner, g, terminal, ""); err != nil { + t.Fatal(err) + } + + peek := user32.NewProc("PeekMessageW") + pump := func() { + var msg message + for i := 0; i < 64; i++ { + ok, _, _ := peek.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, 1) + if ok == 0 { + break + } + translateMessage.Call(uintptr(unsafe.Pointer(&msg))) + dispatchMessage.Call(uintptr(unsafe.Pointer(&msg))) + } + } + pump() + + beforeHooks := func() int { + winEventMu.Lock() + defer winEventMu.Unlock() + return len(winEventHooks) + }() + + unhook := w.attachHooks(g.PID, func() {}) + defer func() { + unhook() + winEventMu.Lock() + afterHooks := len(winEventHooks) + winEventMu.Unlock() + if afterHooks != beforeHooks { + t.Fatalf("leaked WinEvent hooks: before=%d after=%d", beforeHooks, afterHooks) + } + }() + + waitForOrigin := func(wantX, wantY int32, label string) { + t.Helper() + deadline := time.Now().Add(1 * time.Second) + for time.Now().Before(deadline) { + pump() + var r rect + getWindowRect.Call(w.hwnd, uintptr(unsafe.Pointer(&r))) + if r.left == wantX && r.top == wantY { + return + } + time.Sleep(2 * time.Millisecond) + } + var r rect + getWindowRect.Call(w.hwnd, uintptr(unsafe.Pointer(&r))) + t.Fatalf("%s: overlay at (%d,%d), want (%d,%d)", label, r.left, r.top, wantX, wantY) + } + + var initial rect + getWindowRect.Call(w.hwnd, uintptr(unsafe.Pointer(&initial))) + overlayW := initial.right - initial.left + + // 1. Move owner window: overlay should follow via EVENT_OBJECT_LOCATIONCHANGE with no timer. + newX, newY := offX+240, offY+130 + setWindowPos.Call(owner, 0, uintptr(newX), uintptr(newY), 0, 0, 0x0015) // SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE + waitForOrigin(newX+1280-overlayW-12, newY+42, "after move") + + // 2. Resize owner window: overlay should stay pinned to the new top-right corner. + setWindowPos.Call(owner, 0, 0, 0, 960, 600, 0x0016) // SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE + waitForOrigin(newX+960-overlayW-12, newY+42, "after resize") + + // 3. Disabling owner (e.g., guest modal dialog) causes followOwner to hide the overlay. + enableWindow := user32.NewProc("EnableWindow") + enableWindow.Call(owner, 0) + defer enableWindow.Call(owner, 1) + w.followOwner() + if visible, _, _ := user32.NewProc("IsWindowVisible").Call(w.hwnd); visible != 0 { + t.Fatal("overlay remained visible after owner was disabled") + } +} diff --git a/internal/installguide/picker_windows.go b/internal/installguide/picker_windows.go new file mode 100644 index 0000000..231b48c --- /dev/null +++ b/internal/installguide/picker_windows.go @@ -0,0 +1,53 @@ +package installguide + +import ( + "fmt" + "syscall" + "unicode/utf16" + "unsafe" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +// OPENFILENAMEW for the native chooser owned by the guest overlay. +type openFileName struct { + size uint32 + owner, instance uintptr + filter, customFilter *uint16 + maxCustomFilter, filterIndex uint32 + file *uint16 + maxFile uint32 + fileTitle *uint16 + maxFileTitle uint32 + initialDir, title *uint16 + flags uint32 + fileOffset, fileExtension uint16 + defaultExt *uint16 + customData, hook uintptr + templateName *uint16 + reserved uintptr + reservedCount, flagsEx uint32 +} + +func chooseImage(owner uintptr, locale i18n.Locale) (string, error) { + title := "Choose a macOS installer image" + label := "Installer images" + if locale == i18n.ZhCN { + title = "选择 macOS 安装镜像" + label = "安装镜像" + } + titleW, _ := syscall.UTF16PtrFromString(title) + filter := utf16.Encode([]rune(label + " (*.img, *.dmg)\x00*.img;*.dmg\x00\x00")) + file := make([]uint16, 32768) + opts := openFileName{owner: owner, filter: &filter[0], filterIndex: 1, file: &file[0], maxFile: uint32(len(file)), title: titleW, + flags: 0x80000 | 0x1000 | 0x800 | 0x8} // Explorer; existing path/file; preserve current directory. + opts.size = uint32(unsafe.Sizeof(opts)) + dll := syscall.NewLazyDLL("comdlg32.dll") + if ok, _, _ := dll.NewProc("GetOpenFileNameW").Call(uintptr(unsafe.Pointer(&opts))); ok != 0 { + return syscall.UTF16ToString(file), nil + } + if code, _, _ := dll.NewProc("CommDlgExtendedError").Call(); code != 0 { + return "", fmt.Errorf("file dialog: %#x", code) + } + return "", nil +} diff --git a/internal/installguide/progress.go b/internal/installguide/progress.go new file mode 100644 index 0000000..f03ff4e --- /dev/null +++ b/internal/installguide/progress.go @@ -0,0 +1,105 @@ +package installguide + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" +) + +const progressFile = ".reims-go-install-guide.json" + +type checkpoint struct { + Name string `json:"name"` + Kind Kind `json:"kind"` + Media string `json:"media,omitempty"` + Step page `json:"step"` + RestartFrom uint32 `json:"restart_from,omitempty"` +} + +func (p page) postInstall() bool { + switch p { + case setup, network, account, localUser, preferences, desktop, restored, toolsTerminal, toolsVerify: + return true + } + return false +} + +func (p page) recoveryStep(k Kind) bool { + switch p { + case boot, waitInstall: + return true + case terminal, command, verifyCommand: + return k == Offline + case selectDisk, formatDisk: + return k == Online + case reinstall: + return k != Offline + case recoverMenu, mediaChoice: + return k == BuiltIn + } + return false +} + +// Resume attaches ordinary boots only when this VM has a pending post-install +// walkthrough. A restart request never replays an operation on startup. +func (g *Guide) Resume(dir, media string, recovery bool) bool { + g.dir, g.media, g.initial = dir, media, boot + if dir == "" { + return recovery + } + raw, err := os.ReadFile(filepath.Join(dir, progressFile)) + var cp checkpoint + if err != nil || json.Unmarshal(raw, &cp) != nil || cp.Name != g.Name { + return recovery + } + if recovery { + if cp.Kind == g.Kind && strings.EqualFold(cp.Media, media) && cp.Step.recoveryStep(g.Kind) { + g.initial = cp.Step + } + return true + } + if !cp.Step.postInstall() { + return false + } + g.Kind, g.initial = cp.Kind, cp.Step + if cp.RestartFrom != 0 && cp.RestartFrom == g.PID { + g.initial = restartPending + } else if g.initial == toolsTerminal && !g.ToolsAttached { + g.initial = desktop + } + return true +} + +func (g Guide) save(step page, restartFrom uint32) error { + if g.dir == "" { + return errors.New("missing VM directory for installation progress") + } + path := filepath.Join(g.dir, progressFile) + if step == done { + err := os.Remove(path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + return err + } + b, err := json.Marshal(checkpoint{g.Name, g.Kind, g.media, step, restartFrom}) + if err != nil { + return err + } + f, err := os.CreateTemp(g.dir, ".install-guide-*.tmp") + if err != nil { + return err + } + defer os.Remove(f.Name()) + _, err = f.Write(b) + closeErr := f.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + return os.Rename(f.Name(), path) +} diff --git a/internal/installguide/session_windows.go b/internal/installguide/session_windows.go new file mode 100644 index 0000000..c857c91 --- /dev/null +++ b/internal/installguide/session_windows.go @@ -0,0 +1,146 @@ +package installguide + +import ( + "path/filepath" + "time" +) + +var getDoubleClickTime = user32.NewProc("GetDoubleClickTime") + +type session struct { + current, unfolded, returnTo, beforeConfirm page + imagePath, failure string + confirmAfter time.Time +} + +func (s session) detail() string { + if s.current == confirmImage { + return filepath.Base(s.imagePath) + } + return s.failure +} + +func (s session) target(g Guide, id uintptr) page { + return s.targetAt(g, id, time.Now()) +} + +func (s session) targetAt(g Guide, id uintptr, now time.Time) page { + p := s.current + if p == compact { + if id == idFold { + return s.unfolded + } + return p + } + if p == failed { + if id == idLeft || id == 2 { + return s.returnTo + } + return p + } + c := g.content(p, "") + if (p == confirm || p == confirmRepair) && s.beforeConfirm != "" { + c.prev = s.beforeConfirm + } + var next page + switch id { + case idFold: + if c.fold != "" { + return compact + } + case 2: // IDCANCEL (Escape) + if c.fold != "" { + return compact + } + fallthrough + case idLeft: + next = c.prev + case idRight: + if !c.isConfirm || !now.Before(s.confirmAfter) { + next = c.next + } + case idExtra: + next = c.alt + case idJump: + if c.jump != "" { + return confirm + } + } + if next != "" { + return next + } + return p +} + +func (s *session) enter(next page) { + s.enterAt(next, time.Now()) +} + +func (s *session) enterAt(next page, now time.Time) { + if next == compact { + s.unfolded = s.current + } + if (next == confirm || next == confirmRepair) && s.current != failed && s.current != compact { + s.beforeConfirm = s.current + } + if next.confirmsRestart() { + // A double-click on the previous card can land on the new primary button. + ms, _, _ := getDoubleClickTime.Call() + s.confirmAfter = now.Add(time.Duration(ms) * time.Millisecond) + } + s.current = next +} + +type outcome struct { + // On failure, next is the page to return to. Empty on success closes the panel. + next page + err error +} + +// Called off the window thread. Save the handoff before shutting down QEMU: +// the previous window may disappear before Restart returns. +func (g Guide) perform(action, from page, path string) outcome { + var handoff page + switch action { + case typingCommand: + if err := g.TypeText(OfflineCommand); err != nil { + return outcome{from, err} + } + return outcome{next: verifyCommand} + case typingTools: + if err := g.TypeText(ToolsCommand); err != nil { + return outcome{from, err} + } + return outcome{next: toolsVerify} + case mounting: + if err := g.AttachImage(path); err != nil { + return outcome{mediaChoice, err} + } + case mountTools: + if err := g.AttachTools(); err != nil { + return outcome{desktop, err} + } + handoff = toolsTerminal + case working: + if from != restartPending { + if err := g.FinishRecovery(); err != nil { + return outcome{from, err} + } + handoff = setup + if from == confirmRepair { + handoff = restored + } + } + default: + panic("unexpected guide operation") + } + if handoff != "" { + if err := g.save(handoff, g.PID); err != nil { + return outcome{from, err} + } + } + if err := g.Restart(); err != nil { + return outcome{restartPending, err} + } + return outcome{} +} diff --git a/internal/installguide/session_windows_test.go b/internal/installguide/session_windows_test.go new file mode 100644 index 0000000..4e9edef --- /dev/null +++ b/internal/installguide/session_windows_test.go @@ -0,0 +1,150 @@ +package installguide + +import ( + "errors" + "testing" + "time" +) + +// Walk the same actions as the modeless dialog, including closing the old +// process and discovering the newly booted VM before Restart returns. +func TestGuideContinuesAcrossBoots(t *testing.T) { + dir := t.TempDir() + g := Guide{Name: "Tahoe", Kind: Offline, PID: 42} + if !g.Resume(dir, "offline-installer.img", true) || g.initial != boot { + t.Fatal("missing initial recovery guide") + } + now := time.Now() + s := session{current: g.initial} + click := func(id uintptr, want page) { + t.Helper() + now = now.Add(10 * time.Second) + next := s.targetAt(g, id, now) + if next != want { + t.Fatalf("on %s: got %s, want %s", s.current, next, want) + } + s.enterAt(next, now) + } + click(idRight, terminal) + click(idRight, command) + click(idRight, typingCommand) + g.TypeText = func(text string) error { + if text != OfflineCommand { + t.Fatalf("unexpected command %q", text) + } + return nil + } + res := g.perform(s.current, command, "") + if res.err != nil || res.next != verifyCommand { + t.Fatal(res) + } + s.enterAt(res.next, now) + click(idRight, waitInstall) + click(idFold, compact) + if s.targetAt(g, 2, now) != compact { + t.Fatal("Escape unexpectedly expanded folded compact pill") + } + click(idFold, waitInstall) + if err := g.save(s.current, 0); err != nil { + t.Fatal(err) + } + g.PID++ + if !g.Resume(dir, "offline-installer.img", true) || g.initial != waitInstall { + t.Fatal("lost install progress on a cold reboot") + } + click(idRight, confirm) + // A repeated click within the Windows double-click interval must stay on confirmation. + if s.targetAt(g, idRight, now) != confirm { + t.Fatal("double-click immediately confirmed restart") + } + click(idRight, working) + finished := false + g.FinishRecovery = func() error { finished = true; return nil } + var post Guide + g.Restart = func() error { + if !finished { + t.Fatal("restart before FinishInstall") + } + old := Guide{Name: g.Name, PID: g.PID} + if !old.Resume(dir, "", false) || old.initial != restartPending { + t.Fatal("same boot shown post-install instructions") + } + post = Guide{Name: g.Name, PID: g.PID + 1} + if !post.Resume(dir, "", false) || post.initial != setup { + t.Fatal("missing post-restart guide") + } + return nil + } + if r := g.perform(s.current, confirm, ""); r.err != nil || r.next != "" { + t.Fatal(r.err) + } + g = post + s = session{current: g.initial} + for _, p := range []page{network, account, localUser, preferences, desktop, done} { + click(idRight, p) + if err := g.save(p, 0); err != nil { + t.Fatal(err) + } + } + if g.Resume(dir, "", false) { + t.Fatal("completed guide reappeared on normal boot") + } +} + +func TestRecoveryGuideBranches(t *testing.T) { + g := Guide{Kind: Online} + walk := func(start page, ids []uintptr, want []page) { + t.Helper() + now := time.Now() + s := session{current: start} + for i, id := range ids { + now = now.Add(10 * time.Second) + p := s.targetAt(g, id, now) + if p != want[i] { + t.Fatalf("on %s: got %s, want %s", s.current, p, want[i]) + } + s.enterAt(p, now) + } + } + walk(boot, []uintptr{idRight, idRight, idRight, idRight, idRight}, []page{selectDisk, formatDisk, reinstall, waitInstall, confirm}) + walk(selectDisk, []uintptr{idExtra}, []page{reinstall}) + g.Kind = BuiltIn + walk(boot, []uintptr{idRight, idExtra, idExtra}, []page{recoverMenu, mediaChoice, pickImage}) + walk(recoverMenu, []uintptr{idExtra, idRight, idRight}, []page{mediaChoice, reinstall, waitInstall}) + walk(recoverMenu, []uintptr{idRight, idRight}, []page{confirmRepair, working}) + walk(boot, []uintptr{idJump, idLeft}, []page{confirm, boot}) + // Escape on confirm after jumping from boot must also return to boot, not waitInstall. + walk(boot, []uintptr{idJump, 2}, []page{confirm, boot}) + g.FinishRecovery = func() error { return errors.New("eject failed") } + g.Restart = func() error { t.Fatal("restarted after failed finish"); return nil } + if r := g.perform(working, confirm, ""); r.err == nil { + t.Fatal("lost finish error") + } + // If AttachImage succeeds and Restart fails, offer restartPending instead of mediaChoice. + g.AttachImage = func(string) error { return nil } + g.Restart = func() error { return errors.New("stop timed out") } + if r := g.perform(mounting, confirmImage, "offline-installer.img"); r.err == nil || r.next != restartPending { + t.Fatalf("mounting restart failure = %+v, want next=%s with error", r, restartPending) + } +} + +func TestGuideKeepsMediaAndVMProgressSeparate(t *testing.T) { + dir := t.TempDir() + g := Guide{Name: "first", Kind: Online, PID: 33} + g.Resume(dir, "recovery.img", true) + if err := g.save(formatDisk, 0); err != nil { + t.Fatal(err) + } + g.Resume(dir, "other.img", true) + if g.initial != boot { + t.Fatal("progress crossed media") + } + if g.Resume(dir, "", false) { + t.Fatal("normal boot inherited recovery instructions") + } + g.Name = "clone" + g.Resume(dir, "recovery.img", true) + if g.initial != boot { + t.Fatal("clone inherited source disk preparation") + } +}