Files
Reims-Go/internal/host/close_vm_windows.go
T
2026-12-03 21:31:11 -07:00

600 lines
17 KiB
Go

//go:build windows
package host
import (
"context"
"fmt"
"runtime"
"strings"
"sync"
"syscall"
"unicode/utf16"
"unsafe"
"golang.org/x/sys/windows/registry"
"github.com/Nwflower/reims-go/internal/i18n"
)
type VMCloseChoice uint8
const (
VMCloseCancel VMCloseChoice = iota
VMCloseShutdown
VMCloseSuspend
)
const (
vcIDTitle = 100
vcIDBody = 101
vcIDLeft = 111
vcIDRight = 112
vcIDCancel = 2 // IDCANCEL, including Escape in the dialog message loop.
vcWMAction = 0x8001
)
var (
vcGDI = syscall.NewLazyDLL("gdi32.dll")
vcDWM = syscall.NewLazyDLL("dwmapi.dll")
vcKernel = syscall.NewLazyDLL("kernel32.dll")
vcCreateDialog = user32.NewProc("CreateDialogIndirectParamW")
vcDestroyWindow = user32.NewProc("DestroyWindow")
vcSetTimer = user32.NewProc("SetTimer")
vcKillTimer = user32.NewProc("KillTimer")
vcSendMessage = user32.NewProc("SendMessageW")
vcPostMessage = user32.NewProc("PostMessageW")
vcGetDlgItem = user32.NewProc("GetDlgItem")
vcSetFocus = user32.NewProc("SetFocus")
vcIsDialogMessage = user32.NewProc("IsDialogMessageW")
vcTranslateMsg = user32.NewProc("TranslateMessage")
vcDispatchMsg = user32.NewProc("DispatchMessageW")
vcClientToScreen = user32.NewProc("ClientToScreen")
vcDrawText = user32.NewProc("DrawTextW")
vcFillRect = user32.NewProc("FillRect")
vcGetWindowTextW = user32.NewProc("GetWindowTextW")
vcSetLayeredAttr = user32.NewProc("SetLayeredWindowAttributes")
vcSetWindowRgn = user32.NewProc("SetWindowRgn")
vcBeginPaint = user32.NewProc("BeginPaint")
vcEndPaint = user32.NewProc("EndPaint")
vcIsWindowEnabled = user32.NewProc("IsWindowEnabled")
vcMoveWindow = user32.NewProc("MoveWindow")
vcSelectObj = vcGDI.NewProc("SelectObject")
vcStockObj = vcGDI.NewProc("GetStockObject")
vcDeleteObj = vcGDI.NewProc("DeleteObject")
vcSetDCBrushColor = vcGDI.NewProc("SetDCBrushColor")
vcSetDCPenColor = vcGDI.NewProc("SetDCPenColor")
vcSetTextColor = vcGDI.NewProc("SetTextColor")
vcSetBkMode = vcGDI.NewProc("SetBkMode")
vcCreateFontW = vcGDI.NewProc("CreateFontIndirectW")
vcCreateRoundRect = vcGDI.NewProc("CreateRoundRectRgn")
vcRoundRect = vcGDI.NewProc("RoundRect")
vcDwmSetWindowAttr = vcDWM.NewProc("DwmSetWindowAttribute")
vcRtlMoveMemory = vcKernel.NewProc("RtlMoveMemory")
)
type vcRect struct{ left, top, right, bottom int32 }
type vcMessage struct {
hwnd uintptr
id uint32
wp, lp uintptr
time uint32
pt point
}
type vcPaintStruct struct {
hdc uintptr
erase int32
rcPaint vcRect
restore int32
incUpdate int32
rgbReserve [32]byte
}
type vcDrawItem struct {
ctlType uint32
ctlID uint32
itemID uint32
itemAction uint32
itemState uint32
hwndItem uintptr
hdc uintptr
rcItem vcRect
itemData uintptr
}
type vcLogFont struct {
height, width, escapement, orientation, weight int32
italic, underline, strikeOut, charSet byte
outPrecision, clipPrecision, quality, pitch byte
faceName [32]uint16
}
type vcPalette struct {
surface, border, divider uintptr
text, text2, textDisabled uintptr
accent, accentPress uintptr
btnFill, btnPress, btnBorder uintptr
dangerText uintptr
}
func vcRGB(r, g, b uint8) uintptr {
return uintptr(r) | uintptr(g)<<8 | uintptr(b)<<16
}
var (
vcLightPalette = vcPalette{
surface: vcRGB(255, 255, 255),
border: vcRGB(224, 228, 234),
divider: vcRGB(235, 237, 240),
text: vcRGB(29, 29, 31),
text2: vcRGB(66, 66, 71),
textDisabled: vcRGB(154, 154, 160),
accent: vcRGB(0, 122, 255),
accentPress: vcRGB(0, 94, 196),
btnFill: vcRGB(246, 247, 249),
btnPress: vcRGB(235, 237, 240),
btnBorder: vcRGB(218, 221, 227),
dangerText: vcRGB(215, 0, 21),
}
vcDarkPalette = vcPalette{
surface: vcRGB(36, 37, 43),
border: vcRGB(56, 57, 65),
divider: vcRGB(52, 53, 61),
text: vcRGB(245, 245, 247),
text2: vcRGB(194, 194, 202),
textDisabled: vcRGB(110, 110, 118),
accent: vcRGB(10, 132, 255),
accentPress: vcRGB(0, 107, 230),
btnFill: vcRGB(48, 49, 57),
btnPress: vcRGB(60, 61, 70),
btnBorder: vcRGB(68, 70, 80),
dangerText: vcRGB(255, 69, 58),
}
)
type vcDialogState struct {
dark bool
fontTitle uintptr
fontBody uintptr
fontBtn uintptr
titleText string
bodyText string
}
var (
vcStatesMu sync.Mutex
vcStates = map[uintptr]*vcDialogState{}
)
func vcResolveDark(theme string) bool {
switch strings.ToLower(strings.TrimSpace(theme)) {
case "dark":
return true
case "light":
return false
}
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
}
func vcFontFace(loc i18n.Locale) string {
if strings.HasPrefix(strings.ToLower(string(loc)), "zh") {
return "Microsoft YaHei UI"
}
return "Segoe UI"
}
func vcCreateFont(px int32, weight int32, face string) uintptr {
var lf vcLogFont
lf.height = -px
lf.weight = weight
lf.charSet = 1 // DEFAULT_CHARSET
lf.quality = 5 // CLEARTYPE_QUALITY
u := utf16.Encode([]rune(face))
for i := 0; i < len(u) && i < len(lf.faceName)-1; i++ {
lf.faceName[i] = u[i]
}
h, _, _ := vcCreateFontW.Call(uintptr(unsafe.Pointer(&lf)))
return h
}
func vcScale(px int32, dpi uint32) int32 {
if dpi == 0 {
dpi = 96
}
return (px*int32(dpi) + 48) / 96
}
func vcPaletteFor(dark bool) vcPalette {
if dark {
return vcDarkPalette
}
return vcLightPalette
}
// ConfirmVMClose shows a native Win32 confirmation card owned by the VM
// display window, offering Shutdown, Suspend (when supported), and Cancel.
func ConfirmVMClose(ctx context.Context, owner uintptr, name string, loc i18n.Locale, theme string, canSuspend bool) (VMCloseChoice, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
desc := "window.close.description"
if !canSuspend {
desc = "window.close.description_no_suspend"
}
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")
cancelText := i18n.T(loc, "cancel")
template := vcBuildDialogTemplate(title, body, left, right, cancelText, !canSuspend, loc)
var flags uintptr
if vcResolveDark(theme) {
flags |= 1
}
if strings.HasPrefix(strings.ToLower(string(loc)), "zh") {
flags |= 2
}
hwnd, _, err := vcCreateDialog.Call(0, uintptr(unsafe.Pointer(&template[0])), owner, vcDialogProc, flags)
if hwnd == 0 {
return VMCloseCancel, fmt.Errorf("create VM close confirmation: %w", err)
}
defer vcDestroyWindow.Call(hwnd)
timer, _, err := vcSetTimer.Call(0, 0, 200, 0)
if timer == 0 {
return VMCloseCancel, fmt.Errorf("track VM window: %w", err)
}
defer vcKillTimer.Call(0, timer)
centerVMCloseDialog(hwnd, owner)
vcSendMessage.Call(hwnd, 0x0401, vcIDCancel, 0) // DM_SETDEFID
procShowWindow.Call(hwnd, 4) // SW_SHOWNOACTIVATE
vcSetLayeredAttr.Call(hwnd, 0, 244, 2) // LWA_ALPHA
if foreground, _, _ := procGetForegroundWindow.Call(); foreground == owner {
if active, _, _ := procSetForegroundWin.Call(hwnd); active != 0 {
cancelBtn, _, _ := vcGetDlgItem.Call(hwnd, vcIDCancel)
vcSetFocus.Call(cancelBtn)
}
}
for ctx.Err() == nil {
var msg vcMessage
ret, _, err := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(ret) == -1 {
return VMCloseCancel, err
}
if ret == 0 {
break
}
if currentOwner, _, _ := procGetWindow.Call(hwnd, 4); currentOwner != owner { // GW_OWNER
break
}
if msg.id == 0x0113 && msg.hwnd == 0 { // WM_TIMER
centerVMCloseDialog(hwnd, owner)
continue
}
if msg.id == vcWMAction && msg.hwnd == hwnd {
switch msg.wp {
case vcIDLeft:
return VMCloseShutdown, nil
case vcIDRight:
if canSuspend {
return VMCloseSuspend, nil
}
case vcIDCancel:
return VMCloseCancel, nil
}
}
if handled, _, _ := vcIsDialogMessage.Call(hwnd, uintptr(unsafe.Pointer(&msg))); handled == 0 {
vcTranslateMsg.Call(uintptr(unsafe.Pointer(&msg)))
vcDispatchMsg.Call(uintptr(unsafe.Pointer(&msg)))
}
}
return VMCloseCancel, nil
}
func vcBuildDialogTemplate(title, body, left, right, cancel string, disableRight bool, loc i18n.Locale) []uint16 {
const (
clsButton = 0x80
clsStatic = 0x82
)
// WS_POPUP | WS_CLIPCHILDREN | DS_SETFONT, WS_EX_TOOLWINDOW | WS_EX_LAYERED.
data := []uint16{0x40, 0x8200, 0x80, 8, 0, 0, 0, 220, 80, 0, 0}
addStr := func(s string) {
data = append(data, utf16.Encode([]rune(s))...)
data = append(data, 0)
}
addStr(title)
data = append(data, 9)
addStr(vcFontFace(loc))
addItem := func(class, id uint16, caption string, disabled bool) {
if len(data)%2 != 0 {
data = append(data, 0)
}
style := uint16(0x5000) // WS_CHILD | WS_VISIBLE
var ctlStyle uint16
if class == clsButton {
style |= 1 // WS_TABSTOP
ctlStyle = 0x0b // BS_OWNERDRAW
if disabled {
style |= 0x0800 // WS_DISABLED
}
} else {
ctlStyle = 0x0d // SS_OWNERDRAW
}
data = append(data, ctlStyle, style, 0, 0, 0, 0, 10, 10, id, 0xffff, class)
addStr(caption)
data = append(data, 0)
data[4]++
}
addItem(clsStatic, vcIDTitle, title, false)
addItem(clsStatic, vcIDBody, body, false)
addItem(clsButton, vcIDLeft, left, false)
addItem(clsButton, vcIDRight, right, disableRight)
addItem(clsButton, vcIDCancel, cancel, false)
return data
}
func vcGetText(hwnd uintptr) string {
var buf [512]uint16
n, _, _ := vcGetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
return syscall.UTF16ToString(buf[:n])
}
func vcMeasureHeight(hdc, font uintptr, text string, width int32) int32 {
if text == "" {
return 0
}
old, _, _ := vcSelectObj.Call(hdc, font)
defer vcSelectObj.Call(hdc, old)
u := utf16.Encode([]rune(text))
r := vcRect{right: width}
// DT_CALCRECT | DT_WORDBREAK | DT_NOPREFIX
vcDrawText.Call(hdc, uintptr(unsafe.Pointer(&u[0])), uintptr(len(u)), uintptr(unsafe.Pointer(&r)), 0x0c10)
return r.bottom - r.top
}
func vcLayout(hwnd uintptr, st *vcDialogState) {
dpiRaw, _, _ := procGetDpiForWindow.Call(hwnd)
dpi := uint32(dpiRaw)
if dpi == 0 {
dpi = 96
}
s := func(px int32) int32 { return vcScale(px, dpi) }
pad := s(20)
width := s(380)
innerW := width - pad*2
hdc, _, _ := procGetDC.Call(hwnd)
titleH := vcMeasureHeight(hdc, st.fontTitle, st.titleText, innerW)
if titleH < s(22) {
titleH = s(22)
}
bodyH := vcMeasureHeight(hdc, st.fontBody, st.bodyText, innerW)
if bodyH < s(34) {
bodyH = s(34)
}
procReleaseDC.Call(hwnd, hdc)
y := pad
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDTitle); h != 0 {
vcMoveWindow.Call(h, uintptr(pad), uintptr(y), uintptr(innerW), uintptr(titleH), 0)
}
y += titleH + s(8)
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDBody); h != 0 {
vcMoveWindow.Call(h, uintptr(pad), uintptr(y), uintptr(innerW), uintptr(bodyH), 0)
}
y += bodyH + s(18)
btnH := s(32)
gap := s(8)
btnW := (innerW - gap*2) / 3
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDCancel); h != 0 {
vcMoveWindow.Call(h, uintptr(pad), uintptr(y), uintptr(btnW), uintptr(btnH), 0)
}
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDLeft); h != 0 {
vcMoveWindow.Call(h, uintptr(pad+btnW+gap), uintptr(y), uintptr(btnW), uintptr(btnH), 0)
}
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDRight); h != 0 {
vcMoveWindow.Call(h, uintptr(pad+(btnW+gap)*2), uintptr(y), uintptr(innerW-(btnW+gap)*2), uintptr(btnH), 0)
}
height := y + btnH + pad
procSetWindowPos.Call(hwnd, 0, 0, 0, uintptr(width), uintptr(height), 0x0016) // SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
r := s(12)
rgn, _, _ := vcCreateRoundRect.Call(0, 0, uintptr(width+1), uintptr(height+1), uintptr(r*2), uintptr(r*2))
if rgn != 0 {
vcSetWindowRgn.Call(hwnd, rgn, 1)
}
// DWMWA_WINDOW_CORNER_PREFERENCE = 33, DWMWCP_ROUND = 2
pref := uint32(2)
vcDwmSetWindowAttr.Call(hwnd, 33, uintptr(unsafe.Pointer(&pref)), unsafe.Sizeof(pref))
}
var vcDialogProc = syscall.NewCallback(func(hwnd, msg, wp, lp uintptr) uintptr {
switch msg {
case 0x0110: // WM_INITDIALOG
dark := lp&1 != 0
face := "Segoe UI"
if lp&2 != 0 {
face = "Microsoft YaHei UI"
}
dpiRaw, _, _ := procGetDpiForWindow.Call(hwnd)
dpi := uint32(dpiRaw)
if dpi == 0 {
dpi = 96
}
titleH, _, _ := vcGetDlgItem.Call(hwnd, vcIDTitle)
bodyH, _, _ := vcGetDlgItem.Call(hwnd, vcIDBody)
st := &vcDialogState{
dark: dark,
fontTitle: vcCreateFont(vcScale(15, dpi), 600, face),
fontBody: vcCreateFont(vcScale(13, dpi), 400, face),
fontBtn: vcCreateFont(vcScale(13, dpi), 500, face),
titleText: vcGetText(titleH),
bodyText: vcGetText(bodyH),
}
vcStatesMu.Lock()
vcStates[hwnd] = st
vcStatesMu.Unlock()
vcLayout(hwnd, st)
return 0
case 0x000f: // WM_PAINT
var ps vcPaintStruct
hdc, _, _ := vcBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
vcStatesMu.Lock()
st := vcStates[hwnd]
vcStatesMu.Unlock()
pal := vcPaletteFor(st != nil && st.dark)
var rc vcRect
procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc)))
brush, _, _ := vcStockObj.Call(18) // DC_BRUSH
pen, _, _ := vcStockObj.Call(19) // DC_PEN
vcSetDCBrushColor.Call(hdc, pal.surface)
vcSetDCPenColor.Call(hdc, pal.border)
oldB, _, _ := vcSelectObj.Call(hdc, brush)
oldP, _, _ := vcSelectObj.Call(hdc, pen)
dpiRaw, _, _ := procGetDpiForWindow.Call(hwnd)
r := vcScale(12, uint32(dpiRaw))
vcRoundRect.Call(hdc, uintptr(rc.left), uintptr(rc.top), uintptr(rc.right), uintptr(rc.bottom), uintptr(r*2), uintptr(r*2))
vcSelectObj.Call(hdc, oldB)
vcSelectObj.Call(hdc, oldP)
vcEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
return 1
case 0x0014: // WM_ERASEBKGND
return 1
case 0x002b: // WM_DRAWITEM
if lp != 0 {
var it vcDrawItem
vcRtlMoveMemory.Call(uintptr(unsafe.Pointer(&it)), lp, unsafe.Sizeof(it))
vcPaintItem(hwnd, &it)
return 1
}
case 0x0111: // WM_COMMAND
id := wp & 0xffff
if wp>>16 == 0 && (id == vcIDLeft || id == vcIDRight || id == vcIDCancel) {
vcPostMessage.Call(hwnd, vcWMAction, id, 0)
return 1
}
case 0x0010: // WM_CLOSE
vcPostMessage.Call(hwnd, vcWMAction, vcIDCancel, 0)
return 1
case 0x0082: // WM_NCDESTROY
vcStatesMu.Lock()
st := vcStates[hwnd]
delete(vcStates, hwnd)
vcStatesMu.Unlock()
if st != nil {
for _, f := range []uintptr{st.fontTitle, st.fontBody, st.fontBtn} {
if f != 0 {
vcDeleteObj.Call(f)
}
}
}
}
return 0
})
func vcPaintItem(dlg uintptr, it *vcDrawItem) {
vcStatesMu.Lock()
st := vcStates[dlg]
vcStatesMu.Unlock()
if st == nil {
return
}
pal := vcPaletteFor(st.dark)
brush, _, _ := vcStockObj.Call(18) // DC_BRUSH
pen, _, _ := vcStockObj.Call(19) // DC_PEN
vcSetBkMode.Call(it.hdc, 1) // TRANSPARENT
text := vcGetText(it.hwndItem)
u := utf16.Encode([]rune(text))
if it.ctlID == vcIDTitle || it.ctlID == vcIDBody {
vcSetDCBrushColor.Call(it.hdc, pal.surface)
vcFillRect.Call(it.hdc, uintptr(unsafe.Pointer(&it.rcItem)), brush)
if it.ctlID == vcIDTitle {
vcSelectObj.Call(it.hdc, st.fontTitle)
vcSetTextColor.Call(it.hdc, pal.text)
} else {
vcSelectObj.Call(it.hdc, st.fontBody)
vcSetTextColor.Call(it.hdc, pal.text2)
}
if len(u) > 0 {
vcDrawText.Call(it.hdc, uintptr(unsafe.Pointer(&u[0])), uintptr(len(u)), uintptr(unsafe.Pointer(&it.rcItem)), 0x0810) // DT_WORDBREAK | DT_NOPREFIX
}
return
}
// Owner-drawn buttons: Cancel, Left (Shutdown), Right (Suspend).
disabled := it.itemState&0x0004 != 0 // ODS_DISABLED
selected := it.itemState&0x0001 != 0 // ODS_SELECTED
fill, border, fg := pal.btnFill, pal.btnBorder, pal.text
if selected {
fill = pal.btnPress
}
switch it.ctlID {
case vcIDRight:
if !disabled {
fill, border, fg = pal.accent, pal.accent, vcRGB(255, 255, 255)
if selected {
fill, border = pal.accentPress, pal.accentPress
}
} else {
fg = pal.textDisabled
}
case vcIDLeft:
fg = pal.dangerText
}
vcSetDCBrushColor.Call(it.hdc, pal.surface)
vcFillRect.Call(it.hdc, uintptr(unsafe.Pointer(&it.rcItem)), brush)
vcSetDCBrushColor.Call(it.hdc, fill)
vcSetDCPenColor.Call(it.hdc, border)
oldB, _, _ := vcSelectObj.Call(it.hdc, brush)
oldP, _, _ := vcSelectObj.Call(it.hdc, pen)
dpiRaw, _, _ := procGetDpiForWindow.Call(dlg)
r := vcScale(7, uint32(dpiRaw))
vcRoundRect.Call(it.hdc, uintptr(it.rcItem.left), uintptr(it.rcItem.top), uintptr(it.rcItem.right), uintptr(it.rcItem.bottom), uintptr(r*2), uintptr(r*2))
vcSelectObj.Call(it.hdc, oldB)
vcSelectObj.Call(it.hdc, oldP)
vcSelectObj.Call(it.hdc, st.fontBtn)
vcSetTextColor.Call(it.hdc, fg)
if len(u) > 0 {
// DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX
vcDrawText.Call(it.hdc, uintptr(unsafe.Pointer(&u[0])), uintptr(len(u)), uintptr(unsafe.Pointer(&it.rcItem)), 0x0825)
}
}
func centerVMCloseDialog(hwnd, owner uintptr) {
if iconic, _, _ := procIsIconic.Call(owner); iconic != 0 {
return
}
var client, bounds vcRect
var origin point
if ok, _, _ := procGetClientRect.Call(owner, uintptr(unsafe.Pointer(&client))); ok == 0 {
return
}
if ok, _, _ := vcClientToScreen.Call(owner, uintptr(unsafe.Pointer(&origin))); ok == 0 {
return
}
procGetWindowRect.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
procSetWindowPos.Call(hwnd, 0, uintptr(x), uintptr(y), 0, 0, 0x0215)
}
}