Files
Reims-Go/internal/installguide/appearance_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

1408 lines
41 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package installguide
import (
"math"
"strings"
"sync"
"syscall"
"unicode/utf16"
"unsafe"
"golang.org/x/sys/windows/registry"
"github.com/Nwflower/reims-go/internal/i18n"
)
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")
createFontIndirectW = gdi.NewProc("CreateFontIndirectW")
createRoundRectRgn = gdi.NewProc("CreateRoundRectRgn")
enumFontFamiliesExW = gdi.NewProc("EnumFontFamiliesExW")
getTextExtentExPointW = gdi.NewProc("GetTextExtentExPointW")
gdiFlush = gdi.NewProc("GdiFlush")
saveDC = gdi.NewProc("SaveDC")
restoreDC = gdi.NewProc("RestoreDC")
drawText = user32.NewProc("DrawTextW")
sendMessage = user32.NewProc("SendMessageW")
getParent = user32.NewProc("GetParent")
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")
setLayeredAttr = user32.NewProc("SetLayeredWindowAttributes")
setWindowRgn = user32.NewProc("SetWindowRgn")
beginPaint = user32.NewProc("BeginPaint")
endPaint = user32.NewProc("EndPaint")
getDC = user32.NewProc("GetDC")
releaseDC = user32.NewProc("ReleaseDC")
getDpiForWindow = user32.NewProc("GetDpiForWindow")
dwmSetWindowAttr = dwmapi.NewProc("DwmSetWindowAttribute")
setWindowSubclass = comctl32.NewProc("SetWindowSubclass")
removeSubclass = comctl32.NewProc("RemoveWindowSubclass")
defSubclassProc = comctl32.NewProc("DefSubclassProc")
rtlMoveMemory = kernel32.NewProc("RtlMoveMemory")
)
const panelAlpha = 244 // ~95.7% opacity, matching --surface-2 rgba(..., 0.94)
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), pre-composited
// over --surface-2 so native controls match the main Reims-Go window verbatim.
type palette struct {
surface rgb
cardBorder rgb
topHighlight rgb
divider rgb
text rgb
text2 rgb
text3 rgb
accent rgb
accentHover rgb
accentPress rgb
accentHighlight rgb
accentLink rgb
accentSoft rgb
btnFill rgb
btnHover rgb
btnPress rgb
btnBorder rgb
btnHighlight 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{224, 228, 234}, // --border (~rgba(15,23,42,0.11))
topHighlight: rgb{255, 255, 255}, // --highlight-top
divider: rgb{235, 237, 240}, // --border (rgba(15,23,42,0.08))
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 0 1px 0 rgba(255,255,255,0.22)
accentLink: rgb{0, 102, 214}, // --accent-soft-text #0066d6
accentSoft: rgb{227, 240, 255}, // --accent-soft
btnFill: rgb{255, 255, 255}, // --surface-card-elevated
btnHover: rgb{244, 245, 247}, // --surface-hover
btnPress: rgb{235, 237, 240}, // --surface-active
btnBorder: rgb{218, 221, 227}, // --border-strong
btnHighlight: rgb{255, 255, 255},
ghostHover: rgb{243, 245, 247},
ghostPress: rgb{234, 236, 240},
codeFill: rgb{245, 246, 248}, // --surface-1 #f5f6f8
codeBorder: rgb{235, 237, 240}, // --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{36, 37, 43}, // --surface-sidebar / floating dark card #24252b
cardBorder: rgb{56, 57, 65}, // --border rgba(255,255,255,0.09)
topHighlight: rgb{54, 55, 63}, // --highlight-top rgba(255,255,255,0.08)
divider: rgb{52, 53, 61}, // --border rgba(255,255,255,0.08)
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, 112, 224},
accentHighlight: rgb{64, 159, 255}, // inset 0 1px 0 rgba(255,255,255,0.22)
accentLink: rgb{100, 176, 255}, // --accent-soft-text #64b0ff
accentSoft: rgb{30, 55, 84}, // --accent-soft
btnFill: rgb{47, 48, 55}, // --surface-card-elevated #2f3037
btnHover: rgb{57, 58, 66}, // --surface-hover
btnPress: rgb{66, 68, 77}, // --surface-active
btnBorder: rgb{67, 68, 76}, // --border-strong #43444c
btnHighlight: rgb{59, 60, 68}, // inset 0 1px 0 rgba(255,255,255,0.06)
ghostHover: rgb{51, 52, 60}, // --surface-hover
ghostPress: rgb{61, 62, 71}, // --surface-active
codeFill: rgb{27, 28, 33}, // --surface-0 / --surface-input #1b1c21
codeBorder: rgb{53, 54, 62}, // --border
codeText: rgb{212, 214, 224}, // --text-code #d4d6e0
okSoft: rgb{37, 63, 49}, // --ok-soft
okText: rgb{48, 209, 88}, // --ok-text #30d158
warnSoft: rgb{68, 63, 38}, // --warn-soft
warnText: rgb{255, 214, 10}, // --warn-text #ffd60a
dangerSoft: rgb{68, 41, 46}, // --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
}
type scriptKind uint8
const (
scriptLatn scriptKind = iota
scriptHans
scriptHant
scriptJpan
scriptKore
)
func scriptForLocale(loc i18n.Locale) scriptKind {
s := strings.ToLower(strings.TrimSpace(string(i18n.ResolveLocale(string(loc)))))
switch {
case s == "zh-tw" || s == "zh-hk" || s == "zh-mo" || strings.HasPrefix(s, "zh-hant"):
return scriptHant
case strings.HasPrefix(s, "zh"):
return scriptHans
case strings.HasPrefix(s, "ja"):
return scriptJpan
case strings.HasPrefix(s, "ko"):
return scriptKore
default:
return scriptLatn
}
}
func (sk scriptKind) isCJK() bool {
return sk != scriptLatn
}
func dialogBaseFontFace(loc i18n.Locale) string {
probeFontFamilies()
if face := scriptFaces[scriptForLocale(loc)]; face != "" {
return face
}
return "Segoe UI"
}
const (
dialogDark = 1 << iota
dialogCompact
dialogDWM
dialogConfirm
dialogToneShift = 4
dialogScriptShift = 8
)
type dialogMeta struct {
dark, compact, dwm, isConfirm bool
stageTone tone
script scriptKind
}
type panelState struct {
meta dialogMeta
dpi int32
dividerY int32
extraStacked bool
buttonsStacked bool
titleLines []string
titleLineH int32
bodyLines []string
bodyLineH int32
}
var (
panelStatesMu sync.RWMutex
panelStates = map[uintptr]*panelState{}
hoveredControls sync.Map
)
func getPanelState(hwnd uintptr) *panelState {
panelStatesMu.RLock()
st := panelStates[hwnd]
panelStatesMu.RUnlock()
return st
}
func getDialogMeta(hwnd uintptr) dialogMeta {
if st := getPanelState(hwnd); st != nil {
return st.meta
}
return dialogMeta{}
}
func cleanupPanelState(hwnd uintptr) {
panelStatesMu.Lock()
delete(panelStates, hwnd)
panelStatesMu.Unlock()
}
// DPI scaling helpers (CSS px -> physical window pixels).
func windowDPI(hwnd uintptr) int32 {
if hwnd != 0 && getDpiForWindow.Find() == nil {
if d, _, _ := getDpiForWindow.Call(hwnd); d >= 96 {
return int32(d)
}
}
return 96
}
func dp(dpi, px int32) int32 {
return (px*dpi + 48) / 96
}
func dpF(dpi int32, px float64) float64 {
return px * float64(dpi) / 96.0
}
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
italic, underline, strikeOut, charSet byte
outPrecision, clipPrecision, quality, pitchFam byte
face [32]uint16
}
type gdiSize struct{ cx, cy int32 }
type fontKey struct {
dpi int32
script scriptKind
}
type fontSet struct {
title uintptr
body uintptr
btn uintptr
btnBold uintptr
badge uintptr
small uintptr
smallMed uintptr
code uintptr
}
var (
fontProbeOnce sync.Once
fontProbeHit bool
fontEnumProc = syscall.NewCallback(func(lpelfe, lpntme, fontType, lparam uintptr) uintptr {
fontProbeHit = true
return 0
})
scriptFaces = map[scriptKind]string{
scriptLatn: "Segoe UI",
scriptHans: "Microsoft YaHei UI",
scriptHant: "Microsoft JhengHei UI",
scriptJpan: "Yu Gothic UI",
scriptKore: "Malgun Gothic",
}
monoFace = "Consolas"
fontCacheMu sync.Mutex
fontCache = map[fontKey]fontSet{}
)
func probeFontFamilies() {
fontProbeOnce.Do(func() {
dc, _, _ := getDC.Call(0)
if dc == 0 {
return
}
defer releaseDC.Call(0, dc)
has := func(name string) bool {
var lf logFontW
lf.charSet = 1 // DEFAULT_CHARSET
setFace(&lf, name)
fontProbeHit = false
enumFontFamiliesExW.Call(dc, uintptr(unsafe.Pointer(&lf)), fontEnumProc, 0, 0)
return fontProbeHit
}
pick := func(sk scriptKind, candidates []string) {
for _, f := range candidates {
if has(f) {
scriptFaces[sk] = f
return
}
}
}
pick(scriptLatn, []string{"Segoe UI Variable Text", "Segoe UI"})
pick(scriptHans, []string{
"PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans",
"Noto Sans SC Medium", "Noto Sans SC", "Source Han Sans CN Medium", "Source Han Sans CN",
"Microsoft YaHei UI", "Segoe UI",
})
pick(scriptHant, []string{
"PingFang TC", "Noto Sans TC", "Source Han Sans TC",
"Microsoft JhengHei UI", "Microsoft JhengHei", "Microsoft YaHei UI", "Segoe UI",
})
pick(scriptJpan, []string{
"Hiragino Sans", "Noto Sans JP", "BIZ UDPGothic",
"Yu Gothic UI", "Meiryo UI", "Meiryo", "Microsoft YaHei UI", "Segoe UI",
})
pick(scriptKore, []string{
"Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", "Segoe UI",
})
for _, f := range []string{"Cascadia Mono", "JetBrains Mono", "Consolas"} {
if has(f) {
monoFace = f
break
}
}
})
}
func makeFont(face string, px float64, dpi, weight int32) uintptr {
var lf logFontW
lf.height = -max(1, int32(math.Round(px*float64(dpi)/96.0)))
lf.weight = weight
lf.charSet = 1 // DEFAULT_CHARSET
lf.quality = 5 // CLEARTYPE_QUALITY
setFace(&lf, face)
h, _, _ := createFontIndirectW.Call(uintptr(unsafe.Pointer(&lf)))
return h
}
func isGDIWeightJumpFont(face string) bool {
switch face {
case "Microsoft YaHei UI", "Microsoft YaHei", "Microsoft JhengHei UI", "Microsoft JhengHei", "Yu Gothic UI", "Meiryo UI", "Meiryo", "Malgun Gothic":
return true
default:
return false
}
}
func getFonts(dpi int32, script scriptKind) fontSet {
probeFontFamilies()
key := fontKey{dpi: dpi, script: script}
fontCacheMu.Lock()
defer fontCacheMu.Unlock()
if fs, ok := fontCache[key]; ok {
return fs
}
face := scriptFaces[script]
if face == "" {
face = scriptFaces[scriptLatn]
}
medWeight := int32(500)
// In GDI, traditional Windows CJK UI families jump straight from Regular (400)
// to Bold (700) at weight 500+, and dense Traditional/Japanese strokes blob
// at small sizes if forced bold. Keep normal/secondary labels crisp at 400.
if isGDIWeightJumpFont(face) {
medWeight = 400
}
fs := fontSet{
title: makeFont(face, 15, dpi, 600),
body: makeFont(face, 13, dpi, 400),
btn: makeFont(face, 13, dpi, medWeight),
btnBold: makeFont(face, 13, dpi, 600),
badge: makeFont(face, 11.5, dpi, 600),
small: makeFont(face, 12, dpi, 400),
smallMed: makeFont(face, 12, dpi, medWeight),
code: makeFont(monoFace, 12, dpi, 400),
}
fontCache[key] = fs
return fs
}
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: pointer cursor on all interactive buttons, matching Reims-Go.
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
meta := dialogMeta{
dark: flags&dialogDark != 0,
compact: flags&dialogCompact != 0,
isConfirm: flags&dialogConfirm != 0,
stageTone: tone((flags >> dialogToneShift) & 0xf),
script: scriptKind((flags >> dialogScriptShift) & 0xf),
}
pal := paletteFor(meta.dark)
// Prefer Windows 11 DWM smooth rounded corners + native drop shadow + single 1px border.
var darkMode int32
if meta.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)
hr, _, _ := dwmSetWindowAttr.Call(hwnd, 33, uintptr(unsafe.Pointer(&corner)), unsafe.Sizeof(corner)) // DWMWA_WINDOW_CORNER_PREFERENCE
if hr == 0 {
meta.dwm = true
border := uint32(pal.cardBorder.colorref())
dwmSetWindowAttr.Call(hwnd, 34, uintptr(unsafe.Pointer(&border)), unsafe.Sizeof(border)) // DWMWA_BORDER_COLOR
}
panelStatesMu.Lock()
panelStates[hwnd] = &panelState{meta: meta, dpi: windowDPI(hwnd)}
panelStatesMu.Unlock()
layoutPanel(hwnd)
if !meta.dwm {
roundPanel(hwnd)
}
for _, id := range []uintptr{idFold, idLeft, idRight, idExtra, idJump} {
if ctrl, _, _ := getDlgItem.Call(hwnd, id); ctrl != 0 {
setWindowSubclass.Call(ctrl, btnSubclassProc, id, 0)
}
}
}
func controlText(ctrl uintptr) string {
if ctrl == 0 {
return ""
}
var buf [512]uint16
n, _, _ := getWindowTextW.Call(ctrl, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if n == 0 {
return ""
}
return syscall.UTF16ToString(buf[:n])
}
func measureLineWidth(dc, font uintptr, text string) int32 {
if text == "" {
return 0
}
old, _, _ := selectGDI.Call(dc, font)
defer selectGDI.Call(dc, old)
u16 := utf16.Encode([]rune(text))
if len(u16) == 0 {
return 0
}
var sz gdiSize
var fit int32
getTextExtentExPointW.Call(
dc,
uintptr(unsafe.Pointer(&u16[0])),
uintptr(len(u16)),
0x7fffffff,
uintptr(unsafe.Pointer(&fit)),
0,
uintptr(unsafe.Pointer(&sz)),
)
return sz.cx
}
func isASCIIWord(u uint16) bool {
return (u >= 'a' && u <= 'z') || (u >= 'A' && u <= 'Z') || (u >= '0' && u <= '9') || u == '_' || u == '\'' || u == '’'
}
func isClosingPunct(u uint16) bool {
switch u {
case '.', ',', ';', ':', '?', '!', ')', ']', '}',
'。', ',', '、', ';', ':', '?', '!', ')', '」', '』', '》', '”', '…',
// Japanese kinsoku shori (行頭禁則文字: prolonged sound mark, nakaguro, iteration & small kana)
'ー', '・', '々', 'ゝ', 'ゞ', 'ヽ', 'ヾ',
'ぁ', 'ぃ', 'ぅ', 'ぇ', 'ぉ', 'っ', 'ゃ', 'ゅ', 'ょ', 'ゎ',
'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ッ', 'ャ', 'ュ', 'ョ', 'ヮ':
return true
}
return false
}
func isOpeningPunct(u uint16) bool {
switch u {
case '(', '[', '{', '(', '「', '『', '《', '“':
return true
}
return false
}
// wrapLines splits text into visual lines fitting within maxW pixels using GDI
// font metrics, respecting Latin word boundaries and CJK punctuation rules.
func wrapLines(dc, font uintptr, text string, maxW int32, maxLines int) []string {
if text == "" || maxW <= 0 {
return nil
}
old, _, _ := selectGDI.Call(dc, font)
defer selectGDI.Call(dc, old)
var out []string
for _, para := range strings.Split(text, "\n") {
u16 := utf16.Encode([]rune(strings.TrimSpace(para)))
if len(u16) == 0 {
continue
}
for len(u16) > 0 {
var fit int32
var sz gdiSize
getTextExtentExPointW.Call(
dc,
uintptr(unsafe.Pointer(&u16[0])),
uintptr(len(u16)),
uintptr(maxW),
uintptr(unsafe.Pointer(&fit)),
0,
uintptr(unsafe.Pointer(&sz)),
)
if int(fit) >= len(u16) {
out = append(out, string(utf16.Decode(u16)))
break
}
cut := int(fit)
if cut <= 0 {
cut = 1
}
// Never split a UTF-16 surrogate pair.
if cut < len(u16) && u16[cut-1] >= 0xD800 && u16[cut-1] <= 0xDBFF {
if cut > 1 {
cut--
} else {
cut++
}
}
if cut < len(u16) && u16[cut] != ' ' {
// Avoid breaking inside an ASCII/Latin word, or splitting an ASCII token when
// pulling closing punctuation onto the next line (e.g. "1129」。").
if (isASCIIWord(u16[cut-1]) && isASCIIWord(u16[cut])) ||
(isClosingPunct(u16[cut]) && isASCIIWord(u16[cut-1])) {
for i := cut - 1; i > 0; i-- {
c := u16[i]
if c == ' ' {
cut = i
break
}
if c == '/' || c == '\\' || c == '-' || c == '·' || c == '›' || c > 0x7f {
cut = i + 1
break
}
}
} else if cut > 1 && isClosingPunct(u16[cut]) && !isOpeningPunct(u16[cut-1]) {
// Avoid orphan closing punctuation at the start of the next line.
cut--
} else if cut > 1 && isOpeningPunct(u16[cut-1]) {
// Avoid dangling opening punctuation at the end of the current line.
cut--
}
}
line := strings.TrimRight(string(utf16.Decode(u16[:cut])), " ")
out = append(out, line)
u16 = u16[cut:]
for len(u16) > 0 && u16[0] == ' ' {
u16 = u16[1:]
}
if maxLines > 0 && len(out) >= maxLines && len(u16) > 0 {
out[len(out)-1] = strings.TrimRight(out[len(out)-1], " ") + "…"
return out
}
}
}
return out
}
func moveControl(ctrl uintptr, x, y, w, h int32) {
if ctrl == 0 {
return
}
// SWP_NOZORDER | SWP_NOACTIVATE
setWindowPos.Call(ctrl, 0, uintptr(x), uintptr(y), uintptr(w), uintptr(h), 0x14)
}
func setCtrlFont(ctrl, font uintptr) {
if ctrl != 0 && font != 0 {
sendMessage.Call(ctrl, 0x0030, font, 0) // WM_SETFONT
}
}
// layoutPanel computes exact DPI-scaled pixel geometry for every control on
// Reims-Go's 4px spacing grid (--sp-1..--sp-4, 31px .btn, 20px .badge, 32px .cmd-line).
func layoutPanel(hwnd uintptr) {
st := getPanelState(hwnd)
if st == nil {
return
}
dpi := windowDPI(hwnd)
st.dpi = dpi
st.dividerY = 0
st.extraStacked = false
st.buttonsStacked = false
st.titleLines = nil
st.bodyLines = nil
fonts := getFonts(dpi, st.meta.script)
dc, _, _ := getDC.Call(hwnd)
if dc == 0 {
return
}
defer releaseDC.Call(hwnd, dc)
if st.meta.compact {
fold, _, _ := getDlgItem.Call(hwnd, idFold)
setCtrlFont(fold, fonts.btn)
textW := measureLineWidth(dc, fonts.btn, controlText(fold))
w := dp(dpi, 11) + dp(dpi, 7) + dp(dpi, 7) + textW + dp(dpi, 12)
h := dp(dpi, 32)
moveControl(fold, 0, 0, w, h)
setWindowPos.Call(hwnd, 0, 0, 0, uintptr(w), uintptr(h), 0x16) // SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
return
}
cardW := dp(dpi, 340)
if !st.meta.script.isCJK() {
cardW = dp(dpi, 376)
}
maxCardW := dp(dpi, 480)
padX := dp(dpi, 16)
stageCtrl, _, _ := getDlgItem.Call(hwnd, idStage)
foldCtrl, _, _ := getDlgItem.Call(hwnd, idFold)
titleCtrl, _, _ := getDlgItem.Call(hwnd, idTitle)
bodyCtrl, _, _ := getDlgItem.Call(hwnd, idBody)
codeCtrl, _, _ := getDlgItem.Call(hwnd, idCode)
hintCtrl, _, _ := getDlgItem.Call(hwnd, idInputHint)
leftCtrl, _, _ := getDlgItem.Call(hwnd, idLeft)
extraCtrl, _, _ := getDlgItem.Call(hwnd, idExtra)
rightCtrl, _, _ := getDlgItem.Call(hwnd, idRight)
jumpCtrl, _, _ := getDlgItem.Call(hwnd, idJump)
// Adaptively widen cardW up to maxCardW when single-line controls (footer strip,
// input hint, or primary/secondary buttons) experience long-locale text expansion.
if jumpCtrl != 0 {
needW := measureLineWidth(dc, fonts.smallMed, controlText(jumpCtrl)) + dp(dpi, 24) + dp(dpi, 16)
if needW > cardW {
cardW = min(maxCardW, needW)
}
}
if hintCtrl != 0 {
needW := measureLineWidth(dc, fonts.small, controlText(hintCtrl)) + padX*2
if needW > cardW {
cardW = min(maxCardW, needW)
}
}
if rightCtrl != 0 {
rw := measureLineWidth(dc, fonts.btnBold, controlText(rightCtrl)) + dp(dpi, 26) + padX*2
if rw > cardW {
cardW = min(maxCardW, rw)
}
}
if leftCtrl != 0 {
lw := measureLineWidth(dc, fonts.btn, controlText(leftCtrl)) + dp(dpi, 26) + padX*2
if lw > cardW {
cardW = min(maxCardW, lw)
}
}
innerW := cardW - padX*2
y := dp(dpi, 14)
// 1. Meta row: 20px .badge pill on left, quiet ghost "收起" optically flush right.
if stageCtrl != 0 || foldCtrl != 0 {
rowH := dp(dpi, 22)
maxStageW := innerW
if foldCtrl != 0 {
setCtrlFont(foldCtrl, fonts.smallMed)
foldPadX := dp(dpi, 8)
foldW := measureLineWidth(dc, fonts.smallMed, controlText(foldCtrl)) + foldPadX*2
foldH := dp(dpi, 24)
foldX := cardW - padX - foldW + foldPadX
foldY := y + (rowH-foldH)/2
moveControl(foldCtrl, foldX, foldY, foldW, foldH)
maxStageW = max(dp(dpi, 40), (foldX-dp(dpi, 8))-padX)
}
if stageCtrl != 0 {
setCtrlFont(stageCtrl, fonts.badge)
pillPadX := dp(dpi, 8)
pillH := dp(dpi, 20)
pillW := min(maxStageW, measureLineWidth(dc, fonts.badge, controlText(stageCtrl))+pillPadX*2)
moveControl(stageCtrl, padX, y+(rowH-pillH)/2, pillW, pillH)
}
y += rowH + dp(dpi, 10)
}
// 2. Title (15px semibold, wraps up to 3 lines for long European / pseudo-localized headings).
if titleCtrl != 0 {
setCtrlFont(titleCtrl, fonts.title)
tLineH := dp(dpi, 22)
tLines := wrapLines(dc, fonts.title, controlText(titleCtrl), innerW, 3)
st.titleLines = tLines
st.titleLineH = tLineH
titleH := max(tLineH, int32(len(tLines))*tLineH)
moveControl(titleCtrl, padX, y, innerW, titleH)
y += titleH + dp(dpi, 4)
}
// 3. Body (13px, 20px line-height = 1.54x, measured to exact line count).
if bodyCtrl != 0 {
setCtrlFont(bodyCtrl, fonts.body)
lineH := dp(dpi, 20)
lines := wrapLines(dc, fonts.body, controlText(bodyCtrl), innerW, 8)
st.bodyLines = lines
st.bodyLineH = lineH
bodyH := max(lineH, int32(len(lines))*lineH)
moveControl(bodyCtrl, padX, y, innerW, bodyH)
y += bodyH
}
// 4. Monospace command / filename box (.cmd-line: 32px tall, r=8px).
if codeCtrl != 0 {
setCtrlFont(codeCtrl, fonts.code)
y += dp(dpi, 12)
codeH := dp(dpi, 32)
moveControl(codeCtrl, padX, y, innerW, codeH)
y += codeH
}
// 5. Input release hint (12px muted).
if hintCtrl != 0 {
setCtrlFont(hintCtrl, fonts.small)
y += dp(dpi, 8)
hintH := dp(dpi, 18)
moveControl(hintCtrl, padX, y, innerW, hintH)
y += hintH
}
// 6. Footer action buttons (31px tall .btn / .btn-primary / .btn-ghost, 8px gap).
if leftCtrl != 0 || extraCtrl != 0 || rightCtrl != 0 {
btnH := dp(dpi, 31)
btnPadX := dp(dpi, 13)
ghostPadX := dp(dpi, 10)
gap := dp(dpi, 8)
var leftW, rightW, extraW int32
if leftCtrl != 0 {
setCtrlFont(leftCtrl, fonts.btn)
leftW = min(innerW, max(dp(dpi, 60), measureLineWidth(dc, fonts.btn, controlText(leftCtrl))+btnPadX*2))
}
if rightCtrl != 0 {
setCtrlFont(rightCtrl, fonts.btnBold)
rightW = min(innerW, max(dp(dpi, 64), measureLineWidth(dc, fonts.btnBold, controlText(rightCtrl))+btnPadX*2))
}
if extraCtrl != 0 {
setCtrlFont(extraCtrl, fonts.btn)
extraW = measureLineWidth(dc, fonts.btn, controlText(extraCtrl)) + ghostPadX*2
}
needInline := rightW
if leftCtrl != 0 {
needInline += leftW + dp(dpi, 12)
}
if extraCtrl != 0 {
needInline += extraW + gap
}
if extraCtrl != 0 && needInline > innerW {
st.extraStacked = true
setCtrlFont(extraCtrl, fonts.smallMed)
stackPadX := dp(dpi, 8)
stackW := min(innerW+stackPadX*2, measureLineWidth(dc, fonts.smallMed, controlText(extraCtrl))+stackPadX*2)
stackH := dp(dpi, 26)
y += dp(dpi, 10)
moveControl(extraCtrl, padX-stackPadX, y, stackW, stackH)
y += stackH + dp(dpi, 10)
} else {
y += dp(dpi, 16)
}
// Stack primary & secondary buttons vertically if both together exceed innerW.
if leftCtrl != 0 && rightCtrl != 0 && leftW+rightW+gap > innerW {
st.buttonsStacked = true
moveControl(rightCtrl, padX, y, innerW, btnH)
y += btnH + gap
moveControl(leftCtrl, padX, y, innerW, btnH)
y += btnH
} else {
rightX := cardW - padX - rightW
if rightCtrl != 0 {
moveControl(rightCtrl, rightX, y, rightW, btnH)
}
if st.meta.isConfirm {
if leftCtrl != 0 {
moveControl(leftCtrl, rightX-gap-leftW, y, leftW, btnH)
}
} else {
if leftCtrl != 0 {
if rightCtrl == 0 {
moveControl(leftCtrl, cardW-padX-leftW, y, leftW, btnH)
} else {
moveControl(leftCtrl, padX, y, leftW, btnH)
}
}
if extraCtrl != 0 && !st.extraStacked {
if leftCtrl != 0 {
moveControl(extraCtrl, rightX-gap-extraW, y, extraW, btnH)
} else {
moveControl(extraCtrl, padX-ghostPadX, y, extraW, btnH)
}
}
}
if leftCtrl != 0 || rightCtrl != 0 || (extraCtrl != 0 && !st.extraStacked) {
y += btnH
}
}
}
// 7. Full-width escape-hatch footer strip separated by a 1px --border hairline.
if jumpCtrl != 0 {
setCtrlFont(jumpCtrl, fonts.smallMed)
y += dp(dpi, 14)
st.dividerY = y
y++ // 1px hairline divider
stripPadX := dp(dpi, 8)
stripPadY := dp(dpi, 4)
jumpH := dp(dpi, 30)
moveControl(jumpCtrl, stripPadX, y+stripPadY, cardW-stripPadX*2, jumpH)
y += jumpH + stripPadY*2
} else {
y += dp(dpi, 16)
}
// SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
setWindowPos.Call(hwnd, 0, 0, 0, uintptr(cardW), uintptr(y), 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
}
func roundPanel(hwnd uintptr) {
st := getPanelState(hwnd)
if st == nil || st.meta.dwm {
return
}
var r rect
getClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
if r.right <= 0 || r.bottom <= 0 {
return
}
diameter := uintptr(dp(st.dpi, 8) * 2)
region, _, _ := createRoundRectRgn.Call(0, 0, uintptr(r.right+1), uintptr(r.bottom+1), diameter, diameter)
if region != 0 {
if ok, _, _ := setWindowRgn.Call(hwnd, region, 1); ok == 0 {
deleteGDI.Call(region)
}
}
}
func panelBrush(hwnd, dc uintptr) uintptr {
pal := paletteFor(getDialogMeta(hwnd).dark)
textColor.Call(dc, pal.text2.colorref())
bkMode.Call(dc, 1) // TRANSPARENT
brushColor.Call(dc, pal.surface.colorref())
brush, _, _ := stockObject.Call(18) // DC_BRUSH
return brush
}
// paintDialogDC paints the card background, subtle top highlight (--highlight-top),
// and optional 1px footer hairline (--border). On Win11 DWM already renders the
// single outer border + rounded clip + drop shadow, avoiding any double border.
func paintDialogDC(hwnd, dc uintptr) {
st := getPanelState(hwnd)
if st == nil {
return
}
pal := paletteFor(st.meta.dark)
var r rect
getClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
brush, _, _ := stockObject.Call(18) // DC_BRUSH
if st.meta.compact {
brushColor.Call(dc, pal.surface.colorref())
fillRect.Call(dc, uintptr(unsafe.Pointer(&r)), brush)
return
}
if st.meta.dwm {
brushColor.Call(dc, pal.surface.colorref())
fillRect.Call(dc, uintptr(unsafe.Pointer(&r)), brush)
if st.meta.dark && r.bottom > 0 {
topLine := rect{left: 0, top: 0, right: r.right, bottom: 1}
brushColor.Call(dc, pal.topHighlight.colorref())
fillRect.Call(dc, uintptr(unsafe.Pointer(&topLine)), brush)
}
} else {
paintRoundedBox(dc, r, dpF(st.dpi, 8), pal.surface, pal.surface, pal.cardBorder, true, pal.topHighlight, st.meta.dark)
}
if st.dividerY > 0 && st.dividerY < r.bottom {
inset := int32(0)
if !st.meta.dwm {
inset = 1
}
sep := rect{left: inset, top: st.dividerY, right: r.right - inset, bottom: st.dividerY + 1}
brushColor.Call(dc, pal.divider.colorref())
fillRect.Call(dc, uintptr(unsafe.Pointer(&sep)), brush)
}
}
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)
st := getPanelState(parent)
if st == nil {
return
}
meta := st.meta
dpi := st.dpi
pal := paletteFor(meta.dark)
fonts := getFonts(dpi, meta.script)
dc := it.dc
saved, _, _ := saveDC.Call(dc)
defer 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
pressed := it.state&1 != 0
_, hovered := hoveredControls.Load(it.control)
btnR := dpF(dpi, 8) // --r-md
smallR := dpF(dpi, 6) // --r-sm
if it.id == idTitle && len(st.titleLines) > 0 {
selectGDI.Call(dc, fonts.title)
textColor.Call(dc, pal.text.colorref())
lineH := st.titleLineH
if lineH <= 0 {
lineH = dp(dpi, 22)
}
for i, line := range st.titleLines {
if line == "" {
continue
}
u16 := utf16.Encode([]rune(line))
if len(u16) == 0 {
continue
}
lr := rect{left: r.left, top: r.top + int32(i)*lineH, right: r.right, bottom: r.top + int32(i+1)*lineH}
drawText.Call(dc, uintptr(unsafe.Pointer(&u16[0])), uintptr(len(u16)), uintptr(unsafe.Pointer(&lr)), 0x8824)
}
return
}
if it.id == idBody {
selectGDI.Call(dc, fonts.body)
textColor.Call(dc, pal.text2.colorref())
lineH := st.bodyLineH
if lineH <= 0 {
lineH = dp(dpi, 20)
}
for i, line := range st.bodyLines {
if line == "" {
continue
}
u16 := utf16.Encode([]rune(line))
if len(u16) == 0 {
continue
}
lr := rect{left: r.left, top: r.top + int32(i)*lineH, right: r.right, bottom: r.top + int32(i+1)*lineH}
drawText.Call(dc, uintptr(unsafe.Pointer(&u16[0])), uintptr(len(u16)), uintptr(unsafe.Pointer(&lr)), 0x8824) // DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS
}
return
}
var caption [512]uint16
n, _, _ := getWindowTextW.Call(it.control, uintptr(unsafe.Pointer(&caption[0])), uintptr(len(caption)))
if n == 0 {
return
}
flags := uintptr(0x825) // DT_SINGLELINE | DT_VCENTER | DT_CENTER | DT_NOPREFIX
fg := pal.text
textRect := r
switch it.id {
case idStage:
selectGDI.Call(dc, fonts.badge)
pillFill, pillFg := stageColors(pal, meta.stageTone)
paintRoundedBox(dc, r, float64(h)/2, pal.surface, pillFill, rgb{}, false, rgb{}, false)
fg = pillFg
flags = 0x825
case idTitle:
selectGDI.Call(dc, fonts.title)
fg = pal.text
flags = 0x8824 // left | vcenter | singleline | noprefix | end_ellipsis
case idInputHint:
selectGDI.Call(dc, fonts.small)
fg = pal.text3
flags = 0x8824
case idCode:
selectGDI.Call(dc, fonts.code)
paintRoundedBox(dc, r, btnR, pal.surface, pal.codeFill, pal.codeBorder, true, rgb{}, false)
padX := dp(dpi, 12)
textRect = rect{left: r.left + padX, top: r.top, right: r.right - padX, bottom: r.bottom}
fg = pal.codeText
flags = 0x8824
case idRight:
selectGDI.Call(dc, fonts.btnBold)
fill := pal.accent
if pressed {
fill = pal.accentPress
} else if hovered {
fill = pal.accentHover
}
paintRoundedBox(dc, r, btnR, pal.surface, fill, rgb{}, false, pal.accentHighlight, !pressed)
fg = rgb{255, 255, 255}
case idLeft:
selectGDI.Call(dc, fonts.btn)
fill := pal.btnFill
if pressed {
fill = pal.btnPress
} else if hovered {
fill = pal.btnHover
}
paintRoundedBox(dc, r, btnR, pal.surface, fill, pal.btnBorder, true, pal.btnHighlight, !pressed)
fg = pal.text
case idExtra:
radius := btnR
if st.extraStacked {
selectGDI.Call(dc, fonts.smallMed)
radius = smallR
} else {
selectGDI.Call(dc, fonts.btn)
}
fg = pal.text2
if pressed {
paintRoundedBox(dc, r, radius, pal.surface, pal.ghostPress, rgb{}, false, rgb{}, false)
fg = pal.text
} else if hovered {
paintRoundedBox(dc, r, radius, pal.surface, pal.ghostHover, rgb{}, false, rgb{}, false)
fg = pal.text
}
case idFold:
if meta.compact {
selectGDI.Call(dc, fonts.btn)
fill := pal.surface
if pressed {
fill = pal.btnPress
} else if hovered {
fill = pal.btnHover
}
if meta.dwm {
brushColor.Call(dc, fill.colorref())
fillRect.Call(dc, uintptr(unsafe.Pointer(&r)), brush)
if meta.dark && !pressed && r.bottom > 0 {
topLine := rect{left: 0, top: 0, right: r.right, bottom: 1}
brushColor.Call(dc, pal.topHighlight.colorref())
fillRect.Call(dc, uintptr(unsafe.Pointer(&topLine)), brush)
}
} else {
paintRoundedBox(dc, r, btnR, pal.surface, fill, pal.cardBorder, true, pal.topHighlight, meta.dark && !pressed)
}
dotD := dp(dpi, 7)
dotX := r.left + dp(dpi, 11)
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 + dp(dpi, 7), top: r.top, right: r.right - dp(dpi, 10), bottom: r.bottom}
flags = 0x824
fg = pal.text
} else {
selectGDI.Call(dc, fonts.smallMed)
fg = pal.text3
if pressed {
paintRoundedBox(dc, r, smallR, pal.surface, pal.ghostPress, rgb{}, false, rgb{}, false)
fg = pal.text
} else if hovered {
paintRoundedBox(dc, r, smallR, pal.surface, pal.ghostHover, rgb{}, false, rgb{}, false)
fg = pal.text
}
}
case idJump:
selectGDI.Call(dc, fonts.smallMed)
if pressed {
paintRoundedBox(dc, r, smallR, pal.surface, pal.ghostPress, rgb{}, false, rgb{}, false)
} else if hovered {
paintRoundedBox(dc, r, smallR, pal.surface, pal.ghostHover, rgb{}, false, rgb{}, false)
}
padX := dp(dpi, 8)
chevW := dp(dpi, 14)
textRect = rect{left: r.left + padX, top: r.top, right: r.right - padX - chevW, bottom: r.bottom}
fg = pal.accentLink
flags = 0x8824
// Draw subtle trailing chevron aligned optically with cardW - 16px.
chevCol := pal.text3
if hovered || pressed {
chevCol = pal.accentLink
}
selectGDI.Call(dc, fonts.title)
textColor.Call(dc, chevCol.colorref())
chevRect := rect{left: r.right - padX - chevW, top: r.top - dp(dpi, 1), right: r.right - padX, bottom: r.bottom}
chev := [1]uint16{'›'}
drawText.Call(dc, uintptr(unsafe.Pointer(&chev[0])), 1, uintptr(unsafe.Pointer(&chevRect)), 0x826) // DT_RIGHT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX
selectGDI.Call(dc, fonts.smallMed)
}
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
hiRow := 0
if hasBorder {
hiRow = 1
}
// 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 {
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)
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 == hiRow {
if !hasBorder && d <= -0.25 {
inner = hi
} else if hasBorder && d <= -1.25 {
inner = hi
}
}
if hasBorder {
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
}