From 30db99fc719b465b1459485c912401e6c8b556b8 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 17:45:29 +0800 Subject: [PATCH] fix(ui): anchor close confirmation to the VM window --- frontend/src/App.tsx | 31 +--- frontend/src/components/VMCloseDialog.tsx | 36 ----- frontend/src/i18n/domains/vm.gen.ts | 6 - frontend/src/i18n/keys.gen.ts | 3 - frontend/src/wails.ts | 1 - internal/app/app.go | 1 + internal/app/vm_close_other.go | 5 + internal/app/vm_close_windows.go | 55 ++++++++ internal/app/window_launch.go | 8 +- internal/cli/handoff_other.go | 2 + internal/cli/handoff_windows.go | 16 +++ internal/cli/window_args.go | 9 +- internal/host/fullscreen_windows.go | 7 +- internal/i18n/catalog_gen.go | 9 ++ internal/installguide/appearance_windows.go | 31 +++- internal/installguide/close_vm_windows.go | 124 ++++++++++++++++ .../installguide/close_vm_windows_test.go | 133 ++++++++++++++++++ internal/installguide/dialog_windows.go | 11 +- internal/installguide/guide.go | 32 +++-- locales/en-US/native.json | 4 + locales/en-US/vm.json | 3 - locales/zh-CN/native.json | 4 + locales/zh-CN/vm.json | 3 - 23 files changed, 416 insertions(+), 118 deletions(-) delete mode 100644 frontend/src/components/VMCloseDialog.tsx create mode 100644 internal/app/vm_close_other.go create mode 100644 internal/app/vm_close_windows.go create mode 100644 internal/installguide/close_vm_windows.go create mode 100644 internal/installguide/close_vm_windows_test.go diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 38e2665..b3e9a8a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,7 +2,6 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react' import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react' import type { WizardDraft } from './components/CreateWizard' import { DeleteDialog } from './components/DeleteDialog' -import { VMCloseDialog } from './components/VMCloseDialog' import { CloneDialog } from './components/CloneDialog' import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog' import { SendTextDialog } from './components/SendTextDialog' @@ -90,7 +89,6 @@ export const App: React.FC = () => { const [affinityVersion, setAffinityVersion] = useState(0) const [deleteTarget, setDeleteTarget] = useState(null) const [discardSuspendTarget, setDiscardSuspendTarget] = useState(null) - const [vmCloseRequests, setVMCloseRequests] = useState([]) const [cloneSource, setCloneSource] = useState(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) @@ -878,19 +876,9 @@ export const App: React.FC = () => { const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) const appDialogOpen = showSetup || showWizard || showSettings || affinityTarget || deleteTarget || discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate - const vmCloseTarget = appDialogOpen ? undefined : vmCloseRequests[0] - const finishVMWindowClose = (name: string, action?: 'stop' | 'suspend') => { - setVMCloseRequests((requests) => requests.filter((target) => target !== name)) - if (action) { - setSelected(name) - onVMActionFor(name, action, true) - } else if (vmCloseRequests.length === 1) { - api.FocusVMWindow(name).catch(() => {}) - } - } shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return - if (appDialogOpen || vmCloseTarget) return + if (appDialogOpen) return if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return const k = e.key.toLowerCase() if (k === 'n') { e.preventDefault(); openWizard() } @@ -916,10 +904,7 @@ export const App: React.FC = () => { setSelected(name) setDiscardSuspendTarget(name) }) - const offClose = events.onVMCloseRequest((name) => { - setVMCloseRequests((requests) => requests.includes(name) ? requests : [...requests, name]) - }) - return () => { offSelect(); offNew(); offDiscard(); offClose() } + return () => { offSelect(); offNew(); offDiscard() } }, []) // Native Wails file drag-and-drop delivery into the selected VM's shared folder. @@ -1322,18 +1307,6 @@ export const App: React.FC = () => { setDeleteTarget(null)} onConfirm={confirmDelete} /> )} - {vmCloseTarget && ( - finishVMWindowClose(vmCloseTarget, 'stop')} - onSuspend={() => finishVMWindowClose(vmCloseTarget, 'suspend')} - onCancel={() => finishVMWindowClose(vmCloseTarget)} - /> - )} - {discardSuspendTarget && ( void - onSuspend: () => void - onCancel: () => void -} - -export const VMCloseDialog: React.FC = ({ locale, name, canSuspend, busy, onStop, onSuspend, onCancel }) => ( - { if (!open) onCancel() }}> - - - -
- {t(locale, 'vmCloseTitle', { name })} - - {t(locale, canSuspend ? 'vmCloseDesc' : 'vmCloseDescNoSuspend')} - -
-
- - - -
-
-
-
-) diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index d03f387..1a97e4e 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -214,9 +214,6 @@ export const vmZh: Record = { "typeIntoVM": "在虚拟机里键入", "typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本", "upgradeToNVMe": "升级到 NVMe", - "vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。", - "vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。", - "vmCloseTitle": "关闭「{name}」?", } export const vmEn: Record = { @@ -433,7 +430,4 @@ export const vmEn: Record = { "typeIntoVM": "Type into the VM", "typeUntypeable": "Only US-keyboard ASCII characters work without Guest Tools; connect Guest Tools for Chinese and Unicode text", "upgradeToNVMe": "Upgrade to NVMe", - "vmCloseDesc": "Shut down asks macOS to shut down. Suspend saves the session.", - "vmCloseDescNoSuspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", - "vmCloseTitle": "Close “{name}”?", } diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 68e7e96..9ee8854 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -888,9 +888,6 @@ export type I18nKey = | "validationPassed" | "vcpus" | "viewLogs" - | "vmCloseDesc" - | "vmCloseDescNoSuspend" - | "vmCloseTitle" | "vmDir" | "vmName" | "welcomeCheckHost" diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index d279a68..182aaa8 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -181,7 +181,6 @@ export const events = { onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb), onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb), onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb), - onVMCloseRequest: (cb: (name: string) => void) => eventsOn('reims:vm-close-request', cb), // Renderer health watchdog & crash reporting (internal/app/ui_health.go). onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb), emitUIPong: () => eventsEmit('reims:ui-pong'), diff --git a/internal/app/app.go b/internal/app/app.go index 07227eb..1983b2a 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -94,6 +94,7 @@ type App struct { runtimeKinds *rt.KindRegistry uiHealth uiHealthState themeMode installguide.Theme + vmClosePrompts sync.Map } // Lifecycle exposes Wails lifecycle callbacks without exporting them as diff --git a/internal/app/vm_close_other.go b/internal/app/vm_close_other.go new file mode 100644 index 0000000..b24d7d1 --- /dev/null +++ b/internal/app/vm_close_other.go @@ -0,0 +1,5 @@ +//go:build !windows + +package app + +func (*App) confirmVMWindowClose(string) {} diff --git a/internal/app/vm_close_windows.go b/internal/app/vm_close_windows.go new file mode 100644 index 0000000..a5d3055 --- /dev/null +++ b/internal/app/vm_close_windows.go @@ -0,0 +1,55 @@ +package app + +import ( + "strings" + + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/installguide" + "github.com/Nwflower/reims-go/internal/tray" +) + +func (a *App) confirmVMWindowClose(name string) { + if _, pending := a.vmClosePrompts.LoadOrStore(name, struct{}{}); pending { + return + } + defer a.vmClosePrompts.Delete(name) + ctx := a.baseCtx() + pid := a.cachedVMPID(name) + owner := host.ProcessDisplayWindow(uint32(pid)) + if owner == 0 { + pid = a.findRunningVMPID(ctx, name) + owner = host.ProcessDisplayWindow(uint32(pid)) + } + if owner == 0 { + a.emitLog(name, "Could not locate the VM display window for close confirmation") + return + } + loc, theme := a.guidePreferences() + label := strings.TrimSpace(a.GetVMNote(name)) + if label == "" { + label = name + } + prep, err := a.prep(name) + canSuspend := err == nil && prep.Runtime.Manifest.HasCapability("vm-suspend") + choice, err := installguide.ConfirmVMClose(ctx, owner, label, loc, theme, canSuspend) + if err != nil { + a.emitLog(name, err.Error()) + return + } + if choice == installguide.VMCloseCancel { + return + } + vms, err := a.listVMsInternal(ctx) + if err != nil { + a.emitLog(name, err.Error()) + return + } + if current, running := findRunningVMPID(vms, name); !running || current != uint32(pid) { + return + } + if choice == installguide.VMCloseSuspend { + a.trayVMAction(name, tray.ActSuspend) + } else { + a.trayVMAction(name, tray.ActStop) + } +} diff --git a/internal/app/window_launch.go b/internal/app/window_launch.go index b3c42db..e4bc918 100644 --- a/internal/app/window_launch.go +++ b/internal/app/window_launch.go @@ -12,7 +12,6 @@ import ( "github.com/Nwflower/reims-go/internal/cli" "github.com/wailsapp/wails/v2/pkg/options" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // afterStartup runs the launch request once the window's context exists. A @@ -44,12 +43,7 @@ func (a *App) onSecondInstance(data options.SecondInstanceData) { // `vm start` handed over from the command line leaves the window as it is. func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { if w.CloseVM != "" { - if a.ctx != nil { - go func() { - a.ShowMainWindow() - wailsRuntime.EventsEmit(a.ctx, "reims:vm-close-request", w.CloseVM) - }() - } + go a.confirmVMWindowClose(w.CloseVM) return } if w.StartVM == "" { diff --git a/internal/cli/handoff_other.go b/internal/cli/handoff_other.go index 22c4aaf..0ddda69 100644 --- a/internal/cli/handoff_other.go +++ b/internal/cli/handoff_other.go @@ -9,6 +9,8 @@ const windowHandoffWorks = false func findWindow() uintptr { return 0 } +func ForwardVMClose(string) bool { return false } + func sendToWindow(uintptr, []string, uint32) error { return errors.ErrUnsupported } func spawnWindow([]string) error { return errors.ErrUnsupported } diff --git a/internal/cli/handoff_windows.go b/internal/cli/handoff_windows.go index c3c76da..50726ee 100644 --- a/internal/cli/handoff_windows.go +++ b/internal/cli/handoff_windows.go @@ -34,6 +34,8 @@ var ( procFindWindowExW = user32.NewProc("FindWindowExW") procSendMessageW = user32.NewProc("SendMessageW") procSendMessageTimeoutW = user32.NewProc("SendMessageTimeoutW") + procGetWindowPID = user32.NewProc("GetWindowThreadProcessId") + procAllowSetForeground = user32.NewProc("AllowSetForegroundWindow") ) type copyDataStruct struct { @@ -57,6 +59,20 @@ func findWindow() uintptr { return h } +// ForwardVMClose delegates both the request and the foreground permission +// inherited from the VM window that launched this helper. +func ForwardVMClose(name string) bool { + hwnd := findWindow() + if hwnd == 0 { + return false + } + var pid uint32 + if tid, _, _ := procGetWindowPID.Call(hwnd, uintptr(unsafe.Pointer(&pid))); tid != 0 { + procAllowSetForeground.Call(uintptr(pid)) + } + return sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), 500) == nil +} + // sendToWindow delivers args to the running window as if a second // `reims-go.exe ` had been launched. func sendToWindow(hwnd uintptr, args []string, timeoutMS uint32) error { diff --git a/internal/cli/window_args.go b/internal/cli/window_args.go index 690f3df..ae9bf05 100644 --- a/internal/cli/window_args.go +++ b/internal/cli/window_args.go @@ -31,7 +31,7 @@ type WindowArgs struct { // StartResult is a file the window writes a StartResult to once StartVM // has returned, so the command that asked can report it. StartResult string - // CloseVM requests a close confirmation in the running desktop window. + // CloseVM asks the running client to show a confirmation over the VM display. CloseVM string // WaitPID is a Reims-Go process that is quitting after installing an // update: the new window waits for it to exit before taking the @@ -95,13 +95,6 @@ func (w WindowArgs) Args() []string { return out } -// ForwardVMClose asks an existing desktop instance to show a confirmation. -func ForwardVMClose(name string) bool { - const timeoutMS = 500 - hwnd := findWindow() - return hwnd != 0 && sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), timeoutMS) == nil -} - // StartResult is the JSON the window writes to WindowArgs.StartResult. type StartResult struct { OK bool `json:"ok"` diff --git a/internal/host/fullscreen_windows.go b/internal/host/fullscreen_windows.go index c722cb2..486e8f7 100644 --- a/internal/host/fullscreen_windows.go +++ b/internal/host/fullscreen_windows.go @@ -118,7 +118,8 @@ func hasDisplayClientArea(hwnd uintptr) bool { (placement.Normal.Bottom-placement.Normal.Top)-(client.Bottom-client.Top) >= 300 } -func findDisplayWindow(pid uint32) uintptr { +// ProcessDisplayWindow finds the VM's display window, preferring the foreground display. +func ProcessDisplayWindow(pid uint32) uintptr { if pid == 0 { return 0 } @@ -149,7 +150,7 @@ func liveWindowPID(hwnd uintptr) uint32 { // IsProcessWindowFullscreen reports whether the selected display window fills its monitor without a frame. func IsProcessWindowFullscreen(pid uint32) bool { fullscreenState.prune(liveWindowPID) - hwnd := findDisplayWindow(pid) + hwnd := ProcessDisplayWindow(pid) if hwnd == 0 { return false } @@ -176,7 +177,7 @@ func IsProcessWindowFullscreen(pid uint32) bool { // borderless fullscreen and windowed mode. func ToggleProcessWindowFullscreen(pid uint32) (bool, error) { fullscreenState.prune(liveWindowPID) - hwnd := findDisplayWindow(pid) + hwnd := ProcessDisplayWindow(pid) if hwnd == 0 { return false, fmt.Errorf("%w for pid %d", ErrDisplayWindowNotFound, pid) } diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 61dcba3..0be7dcb 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -536,6 +536,10 @@ var catalog = map[Locale]map[string]string{ "vmstart.pin.non_lpe": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)", "vmstart.pin.pcores": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)", "vmstart.pin.skipped": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿", + "window.close.description": "关机将请求系统关闭。挂起会保存当前会话。", + "window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。", + "window.close.suspend": "挂起", + "window.close.title": "关闭「{name}」?", }, EnUS: { "affinity.applied.all": "[CPU] Set QEMU (PID {pid}) affinity to all CPUs ({count} logical CPUs, mask {mask}{eco})", @@ -1070,6 +1074,10 @@ var catalog = map[Locale]map[string]string{ "vmstart.pin.non_lpe": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)", "vmstart.pin.pcores": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)", "vmstart.pin.skipped": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall", + "window.close.description": "Shut down asks macOS to shut down. Suspend saves the session.", + "window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", + "window.close.suspend": "Suspend", + "window.close.title": "Close “{name}”?", }, } @@ -1233,4 +1241,5 @@ var paramOrder = map[string][]string{ "vmstart.pin.non_lpe": {"vcpus", "pthreads", "pid", "cores", "threads", "mask", "lpe"}, "vmstart.pin.pcores": {"pid", "cores", "threads", "mask", "excluded"}, "vmstart.pin.skipped": {"vcpus", "pthreads"}, + "window.close.title": {"name"}, } diff --git a/internal/installguide/appearance_windows.go b/internal/installguide/appearance_windows.go index 3caa9f9..a112b3c 100644 --- a/internal/installguide/appearance_windows.go +++ b/internal/installguide/appearance_windows.go @@ -572,7 +572,7 @@ func stylePanel(hwnd, flags uintptr) { roundPanel(hwnd) } - for _, id := range []uintptr{idFold, idLeft, idRight, idExtra, idJump} { + for _, id := range []uintptr{idFold, idLeft, idRight, idExtra, idJump, idCancel} { if ctrl, _, _ := getDlgItem.Call(hwnd, id); ctrl != 0 { setWindowSubclass.Call(ctrl, btnSubclassProc, id, 0) } @@ -785,6 +785,7 @@ func layoutPanel(hwnd uintptr) { leftCtrl, _, _ := getDlgItem.Call(hwnd, idLeft) extraCtrl, _, _ := getDlgItem.Call(hwnd, idExtra) rightCtrl, _, _ := getDlgItem.Call(hwnd, idRight) + cancelCtrl, _, _ := getDlgItem.Call(hwnd, idCancel) jumpCtrl, _, _ := getDlgItem.Call(hwnd, idJump) // Adaptively widen cardW up to maxCardW when single-line controls (footer strip, @@ -911,6 +912,27 @@ func layoutPanel(hwnd uintptr) { if extraCtrl != 0 { needInline += extraW + gap } + if cancelCtrl != 0 { + setCtrlFont(cancelCtrl, fonts.btn) + cancelW := min(innerW, max(dp(dpi, 60), measureLineWidth(dc, fonts.btn, controlText(cancelCtrl))+btnPadX*2)) + y += dp(dpi, 16) + if leftW+rightW+cancelW+gap*2 <= innerW { + x := cardW - padX - cancelW + moveControl(cancelCtrl, x, y, cancelW, btnH) + x -= gap + rightW + moveControl(rightCtrl, x, y, rightW, btnH) + moveControl(leftCtrl, x-gap-leftW, y, leftW, btnH) + y += btnH + } else { + for _, ctrl := range []uintptr{leftCtrl, rightCtrl, cancelCtrl} { + moveControl(ctrl, padX, y, innerW, btnH) + y += btnH + gap + } + y -= gap + } + setWindowPos.Call(hwnd, 0, 0, 0, uintptr(cardW), uintptr(y+dp(dpi, 16)), 0x16) + return + } if extraCtrl != 0 && needInline > innerW { st.extraStacked = true setCtrlFont(extraCtrl, fonts.smallMed) @@ -1187,6 +1209,11 @@ func paintItem(it *drawItem) { flags = 0x8824 case idRight: selectGDI.Call(dc, fonts.btnBold) + if it.state&0x0004 != 0 { // ODS_DISABLED + paintRoundedBox(dc, r, btnR, pal.surface, pal.btnFill, pal.btnBorder, true, rgb{}, false) + fg = pal.text3 + break + } fill := pal.accent if pressed { fill = pal.accentPress @@ -1195,7 +1222,7 @@ func paintItem(it *drawItem) { } paintRoundedBox(dc, r, btnR, pal.surface, fill, rgb{}, false, pal.accentHighlight, !pressed) fg = rgb{255, 255, 255} - case idLeft: + case idLeft, idCancel: selectGDI.Call(dc, fonts.btn) fill := pal.btnFill if pressed { diff --git a/internal/installguide/close_vm_windows.go b/internal/installguide/close_vm_windows.go new file mode 100644 index 0000000..9943241 --- /dev/null +++ b/internal/installguide/close_vm_windows.go @@ -0,0 +1,124 @@ +package installguide + +import ( + "context" + "fmt" + "runtime" + "unsafe" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +type VMCloseChoice uint8 + +const ( + VMCloseCancel VMCloseChoice = iota + VMCloseShutdown + VMCloseSuspend +) + +var setDialogFocus = user32.NewProc("SetFocus") + +// ConfirmVMClose uses the same native card as the installation guide, owned by +// the display window. Keep the foreign window enabled so it remains usable if +// Reims-Go exits while the confirmation is open. +func ConfirmVMClose(ctx context.Context, owner uintptr, name string, loc i18n.Locale, theme Theme, canSuspend bool) (VMCloseChoice, error) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + desc := "window.close.description" + if !canSuspend { + desc = "window.close.description_no_suspend" + } + c := content{ + title: i18n.M(loc, "window.close.title", i18n.Vars{"name": name}), + body: i18n.T(loc, desc), + left: i18n.T(loc, "stop"), + right: i18n.T(loc, "window.close.suspend"), + cancel: i18n.T(loc, "cancel"), + disableRight: !canSuspend, + } + template := dialogTemplate(confirm, c, loc) + flags := uintptr(scriptForLocale(loc)) << dialogScriptShift + if resolveDark(theme) { + flags |= dialogDark + } + hwnd, _, err := createDialog.Call(0, uintptr(unsafe.Pointer(&template[0])), owner, dialogProc, flags) + if hwnd == 0 { + return VMCloseCancel, fmt.Errorf("create VM close confirmation: %w", err) + } + defer destroyWindow.Call(hwnd) + + timer, _, err := setTimer.Call(0, 0, 200, 0) + if timer == 0 { + return VMCloseCancel, fmt.Errorf("track VM window: %w", err) + } + defer killTimer.Call(0, timer) + + centerVMCloseDialog(hwnd, owner) + sendMessage.Call(hwnd, 0x0401, idCancel, 0) // DM_SETDEFID + showWindow.Call(hwnd, 4) // SW_SHOWNOACTIVATE + revealPanel(hwnd) + if foreground, _, _ := getForeground.Call(); foreground == owner { + if active, _, _ := setForeground.Call(hwnd); active != 0 { + cancel, _, _ := getDlgItem.Call(hwnd, idCancel) + setDialogFocus.Call(cancel) + } + } + + for ctx.Err() == nil { + var msg message + ret, _, err := getMessage.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(ret) == -1 { + return VMCloseCancel, err + } + if ret == 0 { + break + } + if currentOwner, _, _ := getWindow.Call(hwnd, 4); currentOwner != owner { // GW_OWNER + break + } + if msg.id == 0x0113 && msg.hwnd == 0 { // WM_TIMER + centerVMCloseDialog(hwnd, owner) + continue + } + if msg.id == wmAction && msg.hwnd == hwnd { + switch msg.wp { + case idLeft: + return VMCloseShutdown, nil + case idRight: + if canSuspend { + return VMCloseSuspend, nil + } + case idCancel: + return VMCloseCancel, nil + } + } + if handled, _, _ := isDialogMessage.Call(hwnd, uintptr(unsafe.Pointer(&msg))); handled == 0 { + translateMessage.Call(uintptr(unsafe.Pointer(&msg))) + dispatchMessage.Call(uintptr(unsafe.Pointer(&msg))) + } + } + return VMCloseCancel, nil +} + +func centerVMCloseDialog(hwnd, owner uintptr) { + if iconic, _, _ := isIconic.Call(owner); iconic != 0 { + return + } + var client, bounds rect + var origin point + if ok, _, _ := getClientRect.Call(owner, uintptr(unsafe.Pointer(&client))); ok == 0 { + return + } + if ok, _, _ := clientToScreen.Call(owner, uintptr(unsafe.Pointer(&origin))); ok == 0 { + return + } + getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&bounds))) + x := origin.x + (client.right-(bounds.right-bounds.left))/2 + y := origin.y + (client.bottom-(bounds.bottom-bounds.top))/2 + if x != bounds.left || y != bounds.top { + // SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER + setWindowPos.Call(hwnd, 0, uintptr(x), uintptr(y), 0, 0, 0x0215) + } +} diff --git a/internal/installguide/close_vm_windows_test.go b/internal/installguide/close_vm_windows_test.go new file mode 100644 index 0000000..946ef15 --- /dev/null +++ b/internal/installguide/close_vm_windows_test.go @@ -0,0 +1,133 @@ +package installguide + +import ( + "bufio" + "context" + "fmt" + "os" + "os/exec" + "runtime" + "syscall" + "testing" + "time" + "unsafe" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +func TestVMCloseConfirmation(t *testing.T) { + const ownerEnv = "REIMS_GO_TEST_CLOSE_DIALOG_OWNER" + if os.Getenv(ownerEnv) != "" { + runCloseDialogOwner(t) + return + } + ownerCtx, stopOwner := context.WithTimeout(context.Background(), 25*time.Second) + defer stopOwner() + proc := exec.CommandContext(ownerCtx, os.Args[0], "-test.run=^TestVMCloseConfirmation$") + proc.Env = append(os.Environ(), ownerEnv+"=1") + proc.Stderr = os.Stderr + stdout, err := proc.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := proc.Start(); err != nil { + t.Fatal(err) + } + defer func() { + stopOwner() + _ = proc.Wait() + }() + var owner uintptr + if _, err := fmt.Fscan(bufio.NewReader(stdout), &owner); err != nil || owner == 0 { + t.Fatalf("read test display HWND: %v", err) + } + + for _, tc := range []struct { + name string + canSuspend bool + button uintptr + want VMCloseChoice + }{ + {"shutdown", true, idLeft, VMCloseShutdown}, + {"suspend", true, idRight, VMCloseSuspend}, + {"escape", true, idCancel, VMCloseCancel}, + {"unsupported", false, idCancel, VMCloseCancel}, + } { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + result := make(chan error, 1) + go func() { + result <- exerciseVMCloseDialog(ctx, owner, tc.name, tc.button, tc.canSuspend) + }() + choice, err := ConfirmVMClose(ctx, owner, tc.name, i18n.ZhCN, ThemeDark, tc.canSuspend) + deadline := ctx.Err() + cancel() + if probeErr := <-result; probeErr != nil || err != nil || choice != tc.want || deadline != nil { + t.Fatalf("%s: choice %v, want %v, dialog error %v, probe error %v, deadline %v", tc.name, choice, tc.want, err, probeErr, deadline) + } + } +} + +func runCloseDialogOwner(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) + fmt.Fprintln(os.Stdout, owner) + for { + var msg message + ret, _, _ := getMessage.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(ret) <= 0 { + return + } + dispatchMessage.Call(uintptr(unsafe.Pointer(&msg))) + } +} + +func exerciseVMCloseDialog(ctx context.Context, owner uintptr, name string, button uintptr, canSuspend bool) error { + findWindowW := user32.NewProc("FindWindowW") + title, _ := syscall.UTF16PtrFromString("关闭「" + name + "」?") + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for ctx.Err() == nil { + hwnd, _, _ := findWindowW.Call(0, uintptr(unsafe.Pointer(title))) + if visible, _, _ := user32.NewProc("IsWindowVisible").Call(hwnd); visible != 0 { + actualOwner, _, _ := getWindow.Call(hwnd, 4) // GW_OWNER + if actualOwner != owner { + return fmt.Errorf("dialog owner %#x, want %#x", actualOwner, owner) + } + var guest, dialog rect + getWindowRect.Call(owner, uintptr(unsafe.Pointer(&guest))) + getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&dialog))) + dx := guest.left + guest.right - dialog.left - dialog.right + dy := guest.top + guest.bottom - dialog.top - dialog.bottom + if dx > 1 || dx < -1 || dy > 1 || dy < -1 { + return fmt.Errorf("dialog %+v is not centered over %+v", dialog, guest) + } + suspend, _, _ := getDlgItem.Call(hwnd, idRight) + if enabled, _, _ := isWindowEnabled.Call(suspend); suspend == 0 || (enabled != 0) != canSuspend { + return fmt.Errorf("suspend button availability differs from %t", canSuspend) + } + control, _, _ := getDlgItem.Call(hwnd, button) + if control == 0 { + return fmt.Errorf("missing button %d", button) + } + if button == idCancel { + postMessage.Call(control, 0x0100, 0x1b, 0) // WM_KEYDOWN, VK_ESCAPE + } else { + postMessage.Call(control, 0x00f5, 0, 0) // BM_CLICK + } + return nil + } + select { + case <-ctx.Done(): + case <-ticker.C: + } + } + return fmt.Errorf("waiting for confirmation window: %w", ctx.Err()) +} diff --git a/internal/installguide/dialog_windows.go b/internal/installguide/dialog_windows.go index 06222f9..4513354 100644 --- a/internal/installguide/dialog_windows.go +++ b/internal/installguide/dialog_windows.go @@ -19,6 +19,7 @@ const ( idRight = 112 idExtra = 113 idJump = 114 + idCancel = 2 // IDCANCEL, including Escape in the dialog message loop. wmAction = 0x8001 ) @@ -50,6 +51,9 @@ func dialogTemplate(p page, c content, locale i18n.Locale) []uint16 { if class == button { style |= 1 // WS_TABSTOP controlStyle = 0x0b // BS_OWNERDRAW + if id == idRight && c.disableRight { + style |= 0x0800 // WS_DISABLED + } } else { controlStyle = 0x0d // SS_OWNERDRAW } @@ -89,6 +93,9 @@ func dialogTemplate(p page, c content, locale i18n.Locale) []uint16 { if c.right != "" { item(button, idRight, c.right) } + if c.cancel != "" { + item(button, idCancel, c.cancel) + } if c.jump != "" { item(button, idJump, c.jump) } @@ -127,12 +134,12 @@ var dialogProc = syscall.NewCallback(func(hwnd, msg, wp, lp uintptr) uintptr { } case 0x0111: // WM_COMMAND id := wp & 0xffff - if wp>>16 == 0 && (id == idFold || id == idLeft || id == idRight || id == idExtra || id == idJump || id == 2) { + if wp>>16 == 0 && (id == idFold || id == idLeft || id == idRight || id == idExtra || id == idJump || id == idCancel) { 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) + postMessage.Call(hwnd, wmAction, idCancel, 0) return 1 case 0x0082: // WM_NCDESTROY cleanupPanelState(hwnd) diff --git a/internal/installguide/guide.go b/internal/installguide/guide.go index 5f02cd4..7a2d3e6 100644 --- a/internal/installguide/guide.go +++ b/internal/installguide/guide.go @@ -94,21 +94,23 @@ const ( ) 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 + 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 + cancel string + disableRight bool } func (g Guide) preferences() (i18n.Locale, Theme) { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 0fdcee5..bc43cb6 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -1,4 +1,8 @@ { + "window.close.title": "Close “{name}”?", + "window.close.description": "Shut down asks macOS to shut down. Suspend saves the session.", + "window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", + "window.close.suspend": "Suspend", "doctor.title": "Reims-Go Host Environment Check", "doctor.os": "Operating System", "doctor.cpu": "CPU & Core Topology", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index bc05abf..6f2f87e 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -50,9 +50,6 @@ "state_resuming": "Resuming", "state_broken": "Error", "suspend": "Suspend", - "vmCloseTitle": "Close “{name}”?", - "vmCloseDesc": "Shut down asks macOS to shut down. Suspend saves the session.", - "vmCloseDescNoSuspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", "resume": "Resume", "resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM", "discardSuspend": "Discard saved state", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 91ce361..784d0e3 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -1,4 +1,8 @@ { + "window.close.title": "关闭「{name}」?", + "window.close.description": "关机将请求系统关闭。挂起会保存当前会话。", + "window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。", + "window.close.suspend": "挂起", "doctor.title": "Reims-Go 宿主机环境体检", "doctor.os": "操作系统", "doctor.cpu": "处理器与核心拓扑", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 7f73d4a..a8ab8f3 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -50,9 +50,6 @@ "state_resuming": "恢复中", "state_broken": "出错", "suspend": "挂起", - "vmCloseTitle": "关闭「{name}」?", - "vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。", - "vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。", "resume": "恢复", "resumeUnavailable": "切换到支持挂起的内核后可恢复", "discardSuspend": "放弃挂起状态",