Files
Reims-Go/internal/installguide/overlay_windows.go
T
Dnyo666 ceeec602be feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI

# Conflicts:
#	frontend/src/i18n.ts
#	internal/cli/cli.go
#	internal/i18n/i18n.go
2026-11-30 14:56:19 +08:00

470 lines
13 KiB
Go

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
dpi := windowDPI(w.owner)
marginX := dp(dpi, 16)
offsetY := dp(dpi, 40)
x := origin.x + max(0, client.right-width-marginX)
y := origin.y + min(offsetY, 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) | (uintptr(scriptForLocale(loc)) << dialogScriptShift)
if dark {
flags |= dialogDark
}
if p == compact {
flags |= dialogCompact
}
if c.isConfirm {
flags |= dialogConfirm
}
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
}