fix(ui): anchor close confirmation to the VM window

This commit is contained in:
YXC0915 committed 2026-12-01 17:45:29 +08:00
1 parent e7a6dd7a5b
commit 30db99fc71
23 files changed
+416 -118

No files matched your search

+2 -29
View File
@@ -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<string | null>(null)
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
const [vmCloseRequests, setVMCloseRequests] = useState<string[]>([])
const [cloneSource, setCloneSource] = useState<string | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(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 = () => {
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
)}
{vmCloseTarget && (
<VMCloseDialog
locale={locale}
name={displayNames[vmCloseTarget] || vmCloseTarget}
canSuspend={canSuspend}
busy={Object.prototype.hasOwnProperty.call(busy, vmCloseTarget)}
onStop={() => finishVMWindowClose(vmCloseTarget, 'stop')}
onSuspend={() => finishVMWindowClose(vmCloseTarget, 'suspend')}
onCancel={() => finishVMWindowClose(vmCloseTarget)}
/>
)}
{discardSuspendTarget && (
<ConfirmDialog
title={tr('discardSuspendTitle', { name: displayNames[discardSuspendTarget] || discardSuspendTarget })}
-36
View File
@@ -1,36 +0,0 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import React from 'react'
import { t } from '../i18n'
import type { Locale } from '../types'
import { Button } from '../ui/controls'
interface Props {
locale: Locale
name: string
canSuspend: boolean
busy: boolean
onStop: () => void
onSuspend: () => void
onCancel: () => void
}
export const VMCloseDialog: React.FC<Props> = ({ locale, name, canSuspend, busy, onStop, onSuspend, onCancel }) => (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'vmCloseTitle', { name })}</Alert.Title>
<Alert.Description className="dialog-desc">
{t(locale, canSuspend ? 'vmCloseDesc' : 'vmCloseDescNoSuspend')}
</Alert.Description>
</div>
<div className="dialog-foot">
<Button disabled={busy} onClick={onStop}>{t(locale, 'stop')}</Button>
<Button variant="primary" disabled={busy || !canSuspend} onClick={onSuspend}>{t(locale, 'suspend')}</Button>
<Alert.Cancel asChild><Button>{t(locale, 'cancel')}</Button></Alert.Cancel>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
-6
View File
@@ -214,9 +214,6 @@ export const vmZh: Record<string, string> = {
"typeIntoVM": "在虚拟机里键入",
"typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本",
"upgradeToNVMe": "升级到 NVMe",
"vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。",
"vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。",
"vmCloseTitle": "关闭「{name}」?",
}
export const vmEn: Record<string, string> = {
@@ -433,7 +430,4 @@ export const vmEn: Record<string, string> = {
"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}”?",
}
-3
View File
@@ -888,9 +888,6 @@ export type I18nKey =
| "validationPassed"
| "vcpus"
| "viewLogs"
| "vmCloseDesc"
| "vmCloseDescNoSuspend"
| "vmCloseTitle"
| "vmDir"
| "vmName"
| "welcomeCheckHost"
-1
View File
@@ -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'),
+1
View File
@@ -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
+5
View File
@@ -0,0 +1,5 @@
//go:build !windows
package app
func (*App) confirmVMWindowClose(string) {}
+55
View File
@@ -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)
}
}
+1 -7
View File
@@ -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 == "" {
+2
View File
@@ -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 }
+16
View File
@@ -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 <args>` had been launched.
func sendToWindow(hwnd uintptr, args []string, timeoutMS uint32) error {
+1 -8
View File
@@ -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"`
+4 -3
View File
@@ -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)
}
+9
View File
@@ -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"},
}
+29 -2
View File
@@ -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 {
+124
View File
@@ -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)
}
}
@@ -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())
}
+9 -2
View File
@@ -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)
+17 -15
View File
@@ -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) {
+4
View File
@@ -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",
-3
View File
@@ -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",
+4
View File
@@ -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": "处理器与核心拓扑",
-3
View File
@@ -50,9 +50,6 @@
"state_resuming": "恢复中",
"state_broken": "出错",
"suspend": "挂起",
"vmCloseTitle": "关闭「{name}」?",
"vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。",
"vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。",
"resume": "恢复",
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
"discardSuspend": "放弃挂起状态",