Files
Reims-Go/internal/host/sessionoverlay/render_windows.go
T
球球 7fd1947bef feat(plugin,host,macos,ui): 实现 Agent 受控接管、受保护阶段确认、离线预配置与自动装机基础 (#103, #105, #129) (#134)
* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation

* feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129)

Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM.

* feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap

Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion.

* feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes

* fix(app,host,macos,ui): address PR #134 automated review findings

- Frontend & i18n:
  - Fix UTF-8/GBK mojibake in VMPage.tsx.
  - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure.
  - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable.
- App / Sessions / Confirm / Lifecycle:
  - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits.
  - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization.
  - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session.
  - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts.
  - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing.
- Host Takeover Hooks:
  - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures.
- macOS Provisioning & Autoinstall Engine:
  - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures.
  - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints.
  - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages.

* fix(app,cli,host,macos,ui): address PR #134 second automated review findings

- CLI & Desktop Control Channel:
  - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners.
  - Merge live runners with on-disk checkpoints when listing status without a VM argument.
- App Sessions, Confirmations, Downloads & Telemetry:
  - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted.
  - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling.
  - Revoke protected-phase grants when a VM disappears from poll results.
  - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback.
  - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors.
  - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots.
  - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV.
  - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging.
- Host Takeover & Guest Tools:
  - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed.
  - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall.
- macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner):
  - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry.
  - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush.
  - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified).
  - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds.
  - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O.
  - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit.
- Frontend:
  - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs.

* fix(app,cli,host,macos,ui): address PR #134 third automated review findings

Addresses all confirmed findings from Review #6204465334 (commit d516350)
with targeted regression tests and hardens verified COM vtable bindings:

- App & Session Lifecycle:
  - Track hostPaused separately in agentSession so plugin host/session.update
    (paused_for_user=false) cannot clear physical user takeover or explicit
    PauseAgentSession holds; only host ResumeAgentSession or timed takeover
    expiry clears them.
  - Give each auto-install session watcher a monotonic watchGen + cancelable
    child context so restarting/resuming auto-install on the same VM cancels
    any superseded watcher and prevents stale timeout or secret cleanup.
  - Bound fast 500ms unbound-PID discovery for running VMs to
    sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind).
  - Keep non-blocking buffered confirm resolution send inside confirmMu for
    clear mutual exclusion with cancelPendingConfirmations.
  - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return
    and StartVM-failure paths in watchColdReboot.
  - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving
    install_guest_tools) whenever VM is stopped instead of reusing stale images.
- CLI & macOS Provisioning / StartPrep:
  - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the
    VM is running or paused.
  - Guard live "/" root in postinstall against macOS Recovery/Installer
    (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope
    chmod 644 strictly to com.apple.keyboardtype.plist.
  - Reject unknown -* options in REIMSHELP/install.sh (including after --erase).
  - Defer clearing the one-shot REIMSPROV staged marker until after
    setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed.
  - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when
    checkpoint is already at StepDesktop.
- Host Input & Session Overlay:
  - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED)
    in locked-input mode consistently with the mouse hook.
  - Clean up exited overlay entries in entry.run() and recreate dead entries on
    Manager.Upsert when CreateWindowExW fails or exits early.
  - Cache the static island base surface (shell + icons + DirectWrite text) and
    measured text metrics across breathing frames, raising timerBreathMs to 100ms.
  - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h /
    dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite
    rendering smoke test.
- Autoinstall OCR, Rules, Watchdog & Runner:
  - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/
    before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate
    whitelisted basenames in offline zip imports.
  - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait +
    channel wakeup in Recognize so Close() immediately cancels in-flight OCR.
  - Fall back to installed RapidOCR when WinOCR initialization fails in Open(),
    and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe.
  - Pause instead of pressing Return when post-TypeSecret login screenshot fails.
  - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume.
  - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char
    pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word
    boundaries for short names (<4 runes) in RedactDiagnosticText, and honor
    rule verify.wait_change_ms with early exit on visual frame diff.

* fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
2026-12-06 15:46:39 +08:00

1444 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.
//go:build windows
package sessionoverlay
import (
"math"
"strings"
"sync"
"syscall"
"unicode/utf16"
"unsafe"
)
type rgba struct {
r, g, b uint8
}
type scriptKind uint8
const (
scriptLatn scriptKind = iota
scriptHans
scriptHant
scriptJpan
scriptKore
)
func scriptForLocale(locale string) scriptKind {
s := strings.ToLower(strings.TrimSpace(locale))
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 detectCJKScript(texts ...string) scriptKind {
hasHan := false
for _, s := range texts {
for _, r := range s {
switch {
case (r >= 0xAC00 && r <= 0xD7AF) || (r >= 0x1100 && r <= 0x11FF):
return scriptKore
case r >= 0x3040 && r <= 0x30FF:
return scriptJpan
case (r >= 0x4E00 && r <= 0x9FFF) || (r >= 0x3400 && r <= 0x4DBF) || (r >= 0xF900 && r <= 0xFAFF):
hasHan = true
}
}
}
if hasHan {
return scriptHans
}
return scriptLatn
}
// scriptForState picks the typography script from st.Locale and falls back to
// inspecting rendered text when Locale is unresolved (e.g. "auto" or "") or
// Latin while displaying CJK text, preventing Windows DirectWrite from mixing
// Japanese Yu Gothic and Chinese Microsoft YaHei glyphs in the same word.
func scriptForState(st State) scriptKind {
if sk := scriptForLocale(st.Locale); sk != scriptLatn {
return sk
}
return detectCJKScript(st.StepText, st.Title, st.StatusLine, st.PauseLabel, st.ResumeLabel, st.StopLabel, st.CloseLabel, st.CollapseLabel)
}
type logFontW struct {
height, width, escapement, orientation, weight int32
italic, underline, strikeOut, charSet byte
outPrecision, clipPrecision, quality, pitchFam byte
face [32]uint16
}
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 gdiSize struct{ cx, cy int32 }
type fontKey struct {
dpi int32
script scriptKind
}
type islandFontSet struct {
compactTitle uintptr
title uintptr
stepBadge uintptr
stepText uintptr
status uintptr
btn 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",
}
fontCacheMu sync.Mutex
fontCache = map[fontKey]islandFontSet{}
)
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)
}
}
func probeFontFamilies() {
fontProbeOnce.Do(func() {
dc, _, _ := procGetDC.Call(0)
if dc == 0 {
return
}
defer procReleaseDC.Call(0, dc)
has := func(name string) bool {
var lf logFontW
lf.charSet = 1 // DEFAULT_CHARSET
setFace(&lf, name)
fontProbeHit = false
_, _, _ = procEnumFontFamiliesExW.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",
})
})
}
func isWeightJumpCJK(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 makeAAFont(face string, px float64, dpi, weight int32) uintptr {
var lf logFontW
lf.height = -max(int32(1), int32(math.Round(px*float64(dpi)/96.0)))
lf.weight = weight
lf.charSet = 1 // DEFAULT_CHARSET
// ANTIALIASED_QUALITY (4) produces clean grayscale glyph coverage suitable
// for accurate premultiplied-alpha compositing onto layered windows.
lf.quality = 4
setFace(&lf, face)
h, _, _ := procCreateFontIndirectW.Call(uintptr(unsafe.Pointer(&lf)))
return h
}
func getIslandFonts(dpi int32, script scriptKind) islandFontSet {
if dpi < 96 {
dpi = 96
}
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(550)
titleWeight := int32(600)
if isWeightJumpCJK(face) {
medWeight = 400
titleWeight = 600
}
fs := islandFontSet{
compactTitle: makeAAFont(face, 12.5, dpi, medWeight),
title: makeAAFont(face, 13.5, dpi, titleWeight),
stepBadge: makeAAFont(face, 10.5, dpi, titleWeight),
stepText: makeAAFont(face, 12.5, dpi, titleWeight),
status: makeAAFont(face, 12.0, dpi, 400),
btn: makeAAFont(face, 12.5, dpi, medWeight),
}
fontCache[key] = fs
return fs
}
// dibSurface holds a reusable top-down 32-bit BGRA GDI DIB section for either
// the final premultiplied-alpha layered canvas or the grayscale text scratchpad.
type dibSurface struct {
hdc uintptr
hbmp uintptr
old uintptr
bits []byte
w, h int32
}
func (s *dibSurface) ensure(screenDC uintptr, w, h int32) bool {
if w <= 0 || h <= 0 {
return false
}
if s.hdc != 0 && s.w == w && s.h == h && len(s.bits) == int(w)*int(h)*4 {
return true
}
s.release()
memDC, _, _ := procCreateCompatibleDC.Call(screenDC)
if memDC == 0 {
return false
}
bmi := bitmapInfoHeader{
size: uint32(unsafe.Sizeof(bitmapInfoHeader{})),
width: w,
height: -h, // top-down DIB
planes: 1,
bitCount: 32,
}
var ptr unsafe.Pointer
hbmp, _, _ := procCreateDIBSection.Call(memDC, uintptr(unsafe.Pointer(&bmi)), 0, uintptr(unsafe.Pointer(&ptr)), 0, 0)
if hbmp == 0 || ptr == nil {
_, _, _ = procDeleteDC.Call(memDC)
return false
}
old, _, _ := procSelectObject.Call(memDC, hbmp)
s.hdc = memDC
s.hbmp = hbmp
s.old = old
s.w = w
s.h = h
s.bits = unsafe.Slice((*byte)(ptr), int(w)*int(h)*4)
return true
}
func (s *dibSurface) clear() {
clear(s.bits)
}
func (s *dibSurface) release() {
if s.hdc != 0 {
if s.old != 0 {
_, _, _ = procSelectObject.Call(s.hdc, s.old)
}
if s.hbmp != 0 {
_, _, _ = procDeleteObject.Call(s.hbmp)
}
_, _, _ = procDeleteDC.Call(s.hdc)
}
s.hdc = 0
s.hbmp = 0
s.old = 0
s.bits = nil
s.w = 0
s.h = 0
}
// blendPixel composites straight (r,g,b,a) over premultiplied BGRA at (x, y).
func (s *dibSurface) blendPixel(x, y int, c rgba, a float64) {
if x < 0 || y < 0 || x >= int(s.w) || y >= int(s.h) || a <= 0.001 {
return
}
if a > 1 {
a = 1
}
i := (y*int(s.w) + x) * 4
inv := 1.0 - a
sb := float64(c.b) * a
sg := float64(c.g) * a
sr := float64(c.r) * a
sa := 255.0 * a
db := float64(s.bits[i])
dg := float64(s.bits[i+1])
dr := float64(s.bits[i+2])
da := float64(s.bits[i+3])
aOut := clampByte(sa + da*inv)
bOut := clampByte(sb + db*inv)
gOut := clampByte(sg + dg*inv)
rOut := clampByte(sr + dr*inv)
if bOut > aOut {
bOut = aOut
}
if gOut > aOut {
gOut = aOut
}
if rOut > aOut {
rOut = aOut
}
s.bits[i] = bOut
s.bits[i+1] = gOut
s.bits[i+2] = rOut
s.bits[i+3] = aOut
}
func clampByte(v float64) uint8 {
if v <= 0 {
return 0
}
if v >= 255 {
return 255
}
return uint8(v + 0.5)
}
func roundedBoxSDF(px, py, cx, cy, hw, hh, r float64) float64 {
dx := math.Abs(px-cx) - (hw - r)
dy := math.Abs(py-cy) - (hh - r)
qx := math.Max(dx, 0)
qy := math.Max(dy, 0)
return math.Hypot(qx, qy) + math.Min(math.Max(dx, dy), 0) - r
}
func segmentSDF(px, py, ax, ay, bx, by float64) float64 {
pax, pay := px-ax, py-ay
bax, bay := bx-ax, by-ay
denom := bax*bax + bay*bay
h := 0.0
if denom > 1e-6 {
h = clamp01((pax*bax + pay*bay) / denom)
}
return math.Hypot(pax-bax*h, pay-bay*h)
}
// paintIslandShell renders a crisp, fully opaque light macOS Tahoe floating
// card matching Reims-Go's main window & install guide palette (#FFFFFF ->
// #F8F9FB), with a delicate cool-slate layered elevation shadow, clean 1px
// hairline border, and warm amber pulse when the locked VM screen is clicked.
func (s *dibSurface) paintIslandShell(l islandLayout, paused bool, pulse float64) {
px0 := float64(l.PadX)
py0 := float64(l.PadTop)
pw := float64(l.PillW)
ph := float64(l.PillH)
cx := px0 + pw*0.5
cy := py0 + ph*0.5
hw := pw * 0.5
hh := ph * 0.5
r := l.PillRadius
dpiF := float64(l.DPI) / 96.0
shadowBlur := 14.5 * dpiF
shadowOffY := 5.8 * dpiF
contactBlur := 3.2 * dpiF
contactOffY := 1.2 * dpiF
borderW := math.Max(1.0, 1.0*dpiF)
// Pure white -> ultra-soft cool alabaster (matching tokens.css light surface).
topCol := rgba{255, 255, 255} // #FFFFFF
botCol := rgba{248, 249, 252} // #F8F9FC
shadowCol := rgba{15, 23, 42} // --shadow-overlay slate tint
rimBase := rgba{15, 23, 42}
pulseCol := rgba{245, 158, 11} // crisp Apple Amber for light surface
_ = paused
flatX0 := int(math.Ceil(px0 + r + borderW + 2))
flatX1 := int(math.Floor(px0 + pw - r - borderW - 2))
flatY0 := int(math.Ceil(py0 + borderW + 2))
flatY1 := int(math.Floor(py0 + ph - borderW - 2))
w := int(s.w)
h := int(s.h)
for y := 0; y < h; y++ {
fy := float64(y) + 0.5
vNorm := clamp01((fy - py0) / math.Max(1, ph))
rowOff := y * w * 4
inFlatY := y >= flatY0 && y < flatY1
baseR := lerpFloat(float64(topCol.r), float64(botCol.r), vNorm)
baseG := lerpFloat(float64(topCol.g), float64(botCol.g), vNorm)
baseB := lerpFloat(float64(topCol.b), float64(botCol.b), vNorm)
if pulse > 0.005 {
pf := 0.045 * pulse
baseR = baseR*(1-pf) + float64(pulseCol.r)*pf
baseG = baseG*(1-pf) + float64(pulseCol.g)*pf
baseB = baseB*(1-pf) + float64(pulseCol.b)*pf
}
for x := 0; x < w; x++ {
fx := float64(x) + 0.5
if inFlatY && x >= flatX0 && x < flatX1 {
off := rowOff + x*4
s.bits[off] = clampByte(baseB)
s.bits[off+1] = clampByte(baseG)
s.bits[off+2] = clampByte(baseR)
s.bits[off+3] = 255
continue
}
d := roundedBoxSDF(fx, fy, cx, cy, hw, hh, r)
// 1. Delicate layered cool-slate macOS elevation shadow (gap-free).
var outR, outG, outB, outA float64
if d > -1.5 {
var shA float64
ds := roundedBoxSDF(fx, fy-shadowOffY, cx, cy, hw, hh, r)
if ds < shadowBlur {
t := clamp01(1.0 - math.Max(0, ds)/shadowBlur)
shA = 0.22 * t * t * t
}
dc := roundedBoxSDF(fx, fy-contactOffY, cx, cy, hw, hh, r)
if dc < contactBlur {
tc := clamp01(1.0 - math.Max(0, dc)/contactBlur)
cA := 0.13 * tc * tc
shA = cA + shA*(1.0-cA)
}
if shA > 0.001 {
outR = float64(shadowCol.r) * shA
outG = float64(shadowCol.g) * shA
outB = float64(shadowCol.b) * shA
outA = shA
}
if pulse > 0.005 && d >= -0.5 && d < 6.0*dpiF {
tp := clamp01(1.0 - math.Max(0, d)/(6.0*dpiF))
glowA := 0.34 * pulse * tp * tp
inv := 1.0 - glowA
outR = float64(pulseCol.r)*glowA + outR*inv
outG = float64(pulseCol.g)*glowA + outG*inv
outB = float64(pulseCol.b)*glowA + outB*inv
outA = glowA + outA*inv
}
}
// 2. Opaque pure-white card interior + crisp 1px subtle slate hairline border.
outerCov := clamp01(0.5 - d)
if outerCov > 0.001 {
innerCov := clamp01(0.5 - (d + borderW))
rimCov := clamp01(outerCov - innerCov)
bodyA := outerCov
invBody := 1.0 - bodyA
outR = baseR*bodyA + outR*invBody
outG = baseG*bodyA + outG*invBody
outB = baseB*bodyA + outB*invBody
outA = bodyA + outA*invBody
if rimCov > 0.001 {
rimAlpha := 0.095
rimR, rimG, rimB := float64(rimBase.r), float64(rimBase.g), float64(rimBase.b)
if pulse > 0.005 {
mixP := clamp01(pulse * 0.92)
rimR = lerpFloat(rimR, float64(pulseCol.r), mixP)
rimG = lerpFloat(rimG, float64(pulseCol.g), mixP)
rimB = lerpFloat(rimB, float64(pulseCol.b), mixP)
rimAlpha = lerpFloat(rimAlpha, 0.72, mixP)
}
ra := rimAlpha * rimCov
invR := 1.0 - ra
outR = rimR*ra + outR*invR
outG = rimG*ra + outG*invR
outB = rimB*ra + outB*invR
outA = ra + outA*invR
}
}
if outA > 0.001 {
aOut := clampByte(outA * 255.0)
s.bits[rowOff+x*4] = min(aOut, clampByte(outB))
s.bits[rowOff+x*4+1] = min(aOut, clampByte(outG))
s.bits[rowOff+x*4+2] = min(aOut, clampByte(outR))
s.bits[rowOff+x*4+3] = aOut
}
}
}
}
// paintTactilePill draws a crisp, anti-aliased solid matte button or badge with
// vertical micro-gradient, 1px hairline border, and delicate top inner highlight.
func (s *dibSurface) paintTactilePill(r rect2i, radius float64, topFill, botFill rgba, fillA float64, border rgba, borderA float64, topHiA float64) {
if r.width() <= 0 || r.height() <= 0 || (fillA <= 0.001 && borderA <= 0.001) {
return
}
cx := float64(r.Left+r.Right) * 0.5
cy := float64(r.Top+r.Bottom) * 0.5
hw := float64(r.width()) * 0.5
hh := float64(r.height()) * 0.5
if radius > math.Min(hw, hh) {
radius = math.Min(hw, hh)
}
x0 := max(0, int(r.Left)-1)
y0 := max(0, int(r.Top)-1)
x1 := min(int(s.w), int(r.Right)+1)
y1 := min(int(s.h), int(r.Bottom)+1)
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
vNorm := clamp01((fy - float64(r.Top)) / math.Max(1, float64(r.height())))
curFill := rgba{
r: clampByte(lerpFloat(float64(topFill.r), float64(botFill.r), vNorm)),
g: clampByte(lerpFloat(float64(topFill.g), float64(botFill.g), vNorm)),
b: clampByte(lerpFloat(float64(topFill.b), float64(botFill.b), vNorm)),
}
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
d := roundedBoxSDF(fx, fy, cx, cy, hw, hh, radius)
cov := clamp01(0.5 - d)
if cov <= 0.001 {
continue
}
if fillA > 0.001 {
s.blendPixel(x, y, curFill, fillA*cov)
if topHiA > 0.001 && vNorm < 0.30 {
boost := (1.0 - vNorm/0.30) * topHiA * cov
s.blendPixel(x, y, rgba{255, 255, 255}, boost)
}
}
if borderA > 0.001 {
innerCov := clamp01(0.5 - (d + 1.0))
rim := clamp01(cov - innerCov)
if rim > 0.001 {
s.blendPixel(x, y, border, clamp01(borderA)*rim)
}
}
}
}
}
// paintStatusDot draws the breathing Apple light-mode green (running) or warm
// amber (paused) indicator dot with a soft pastel halo.
func (s *dibSurface) paintStatusDot(center point2i, dpi int32, paused bool, breath float64) {
col := rgba{40, 205, 65} // --status-running #28cd41
if paused {
col = rgba{255, 159, 10} // --status-busy #ff9f0a
}
coreR := scaleDPF(dpi, 3.4)
haloR := scaleDPF(dpi, 7.2+2.0*breath)
haloPeak := 0.14 + 0.14*breath
if paused {
haloR = scaleDPF(dpi, 7.6)
haloPeak = 0.18
}
cx := float64(center.X)
cy := float64(center.Y)
rad := int(math.Ceil(haloR)) + 1
x0 := max(0, int(math.Floor(cx))-rad)
y0 := max(0, int(math.Floor(cy))-rad)
x1 := min(int(s.w), int(math.Ceil(cx))+rad)
y1 := min(int(s.h), int(math.Ceil(cy))+rad)
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
dist := math.Hypot(fx-cx, fy-cy)
if dist < haloR {
ht := clamp01(1.0 - dist/haloR)
s.blendPixel(x, y, col, haloPeak*ht*ht)
}
coreCov := clamp01(0.5 - (dist - coreR))
if coreCov > 0.001 {
// Subtle top-left specular gleam inside the dot for jewel-like depth.
gleamDist := math.Hypot(fx-(cx-coreR*0.28), fy-(cy-coreR*0.28))
gleam := clamp01(1.0-gleamDist/(coreR*0.85)) * 0.32
c := rgba{
r: clampByte(lerpFloat(float64(col.r), 255, gleam)),
g: clampByte(lerpFloat(float64(col.g), 255, gleam)),
b: clampByte(lerpFloat(float64(col.b), 255, gleam)),
}
s.blendPixel(x, y, c, coreCov)
}
}
}
}
func (s *dibSurface) paintPauseIcon(cx, cy float64, dpi int32, col rgba, alpha float64) {
if alpha <= 0.005 {
return
}
barW := scaleDPF(dpi, 2.3)
barH := scaleDPF(dpi, 9.2)
gap := scaleDPF(dpi, 2.6)
rad := barW * 0.45
leftCX := cx - (gap+barW)*0.5
rightCX := cx + (gap+barW)*0.5
boundX := int(math.Ceil(gap*0.5+barW)) + 2
boundY := int(math.Ceil(barH*0.5)) + 2
x0 := max(0, int(math.Floor(cx))-boundX)
y0 := max(0, int(math.Floor(cy))-boundY)
x1 := min(int(s.w), int(math.Ceil(cx))+boundX)
y1 := min(int(s.h), int(math.Ceil(cy))+boundY)
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
d1 := roundedBoxSDF(fx, fy, leftCX, cy, barW*0.5, barH*0.5, rad)
d2 := roundedBoxSDF(fx, fy, rightCX, cy, barW*0.5, barH*0.5, rad)
cov := clamp01(0.5 - math.Min(d1, d2))
if cov > 0.001 {
s.blendPixel(x, y, col, cov*alpha)
}
}
}
}
func (s *dibSurface) paintPlayIcon(cx, cy float64, dpi int32, col rgba, alpha float64) {
if alpha <= 0.005 {
return
}
// Optically shift right slightly so triangle center feels visually balanced.
ocx := cx + scaleDPF(dpi, 0.7)
sz := scaleDPF(dpi, 4.4)
ax, ay := ocx-sz*0.85, cy-sz
bx, by := ocx-sz*0.85, cy+sz
tx, ty := ocx+sz*1.05, cy
round := scaleDPF(dpi, 0.85)
bound := int(math.Ceil(sz*1.6)) + 2
x0 := max(0, int(math.Floor(ocx))-bound)
y0 := max(0, int(math.Floor(cy))-bound)
x1 := min(int(s.w), int(math.Ceil(ocx))+bound)
y1 := min(int(s.h), int(math.Ceil(cy))+bound)
// Signed distance to triangle (a, b, t) in counter-clockwise order.
cross := func(px, py, x1, y1, x2, y2 float64) float64 {
return (px-x2)*(y1-y2) - (x1-x2)*(py-y2)
}
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
d1 := segmentSDF(fx, fy, ax, ay, bx, by)
d2 := segmentSDF(fx, fy, bx, by, tx, ty)
d3 := segmentSDF(fx, fy, tx, ty, ax, ay)
edgeD := math.Min(d1, math.Min(d2, d3))
c1 := cross(fx, fy, ax, ay, bx, by)
c2 := cross(fx, fy, bx, by, tx, ty)
c3 := cross(fx, fy, tx, ty, ax, ay)
inside := (c1 >= 0 && c2 >= 0 && c3 >= 0) || (c1 <= 0 && c2 <= 0 && c3 <= 0)
sd := edgeD
if inside {
sd = -edgeD
}
cov := clamp01(0.5 - (sd - round))
if cov > 0.001 {
s.blendPixel(x, y, col, cov*alpha)
}
}
}
}
// paintCompletedDot draws a steady Apple green circular badge with a crisp
// white checkmark when an automated session has completed and unlocked input.
func (s *dibSurface) paintCompletedDot(center point2i, dpi int32) {
col := rgba{40, 205, 65} // --status-running #28cd41
coreR := scaleDPF(dpi, 4.8)
haloR := scaleDPF(dpi, 7.6)
haloPeak := 0.14
cx := float64(center.X)
cy := float64(center.Y)
rad := int(math.Ceil(haloR)) + 1
x0 := max(0, int(math.Floor(cx))-rad)
y0 := max(0, int(math.Floor(cy))-rad)
x1 := min(int(s.w), int(math.Ceil(cx))+rad)
y1 := min(int(s.h), int(math.Ceil(cy))+rad)
ax, ay := cx-scaleDPF(dpi, 2.2), cy+scaleDPF(dpi, 0.1)
bx, by := cx-scaleDPF(dpi, 0.5), cy+scaleDPF(dpi, 1.8)
tx, ty := cx+scaleDPF(dpi, 2.4), cy-scaleDPF(dpi, 1.6)
stroke := scaleDPF(dpi, 0.65)
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
dist := math.Hypot(fx-cx, fy-cy)
if dist < haloR {
ht := clamp01(1.0 - dist/haloR)
s.blendPixel(x, y, col, haloPeak*ht*ht)
}
coreCov := clamp01(0.5 - (dist - coreR))
if coreCov > 0.001 {
s.blendPixel(x, y, col, coreCov)
d1 := segmentSDF(fx, fy, ax, ay, bx, by) - stroke
d2 := segmentSDF(fx, fy, bx, by, tx, ty) - stroke
chkCov := clamp01(0.5 - math.Min(d1, d2))
if chkCov > 0.001 {
s.blendPixel(x, y, rgba{255, 255, 255}, chkCov*coreCov)
}
}
}
}
}
func (s *dibSurface) paintCloseIcon(cx, cy float64, dpi int32, col rgba, alpha float64) {
if alpha <= 0.005 {
return
}
half := scaleDPF(dpi, 3.4)
stroke := scaleDPF(dpi, 0.78)
bound := int(math.Ceil(half+stroke)) + 2
x0 := max(0, int(math.Floor(cx))-bound)
y0 := max(0, int(math.Floor(cy))-bound)
x1 := min(int(s.w), int(math.Ceil(cx))+bound)
y1 := min(int(s.h), int(math.Ceil(cy))+bound)
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
d1 := segmentSDF(fx, fy, cx-half, cy-half, cx+half, cy+half) - stroke
d2 := segmentSDF(fx, fy, cx+half, cy-half, cx-half, cy+half) - stroke
cov := clamp01(0.5 - math.Min(d1, d2))
if cov > 0.001 {
s.blendPixel(x, y, col, cov*alpha)
}
}
}
}
func (s *dibSurface) paintStopIcon(cx, cy float64, dpi int32, col rgba, alpha float64) {
if alpha <= 0.005 {
return
}
half := scaleDPF(dpi, 3.8)
rad := scaleDPF(dpi, 1.7)
bound := int(math.Ceil(half)) + 2
x0 := max(0, int(math.Floor(cx))-bound)
y0 := max(0, int(math.Floor(cy))-bound)
x1 := min(int(s.w), int(math.Ceil(cx))+bound)
y1 := min(int(s.h), int(math.Ceil(cy))+bound)
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
d := roundedBoxSDF(fx, fy, cx, cy, half, half, rad)
cov := clamp01(0.5 - d)
if cov > 0.001 {
s.blendPixel(x, y, col, cov*alpha)
}
}
}
}
func (s *dibSurface) paintLockIcon(cx, cy float64, dpi int32, col rgba, alpha float64) {
if alpha <= 0.005 {
return
}
bodyHW := scaleDPF(dpi, 4.0)
bodyHH := scaleDPF(dpi, 3.0)
bodyCY := cy + scaleDPF(dpi, 1.8)
bodyR := scaleDPF(dpi, 1.2)
shackleR := scaleDPF(dpi, 2.5)
shackleCY := bodyCY - bodyHH - scaleDPF(dpi, 0.2)
strokeHalf := scaleDPF(dpi, 0.65)
bound := int(math.Ceil(scaleDPF(dpi, 7))) + 2
x0 := max(0, int(math.Floor(cx))-bound)
y0 := max(0, int(math.Floor(cy))-bound)
x1 := min(int(s.w), int(math.Ceil(cx))+bound)
y1 := min(int(s.h), int(math.Ceil(cy))+bound)
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
dBody := roundedBoxSDF(fx, fy, cx, bodyCY, bodyHW, bodyHH, bodyR)
// Shackle: upper semicircle + short vertical legs into lock body.
var dShackle float64
if fy <= shackleCY {
dShackle = math.Abs(math.Hypot(fx-cx, fy-shackleCY)-shackleR) - strokeHalf
} else {
dL := segmentSDF(fx, fy, cx-shackleR, shackleCY, cx-shackleR, bodyCY-bodyHH+0.5) - strokeHalf
dR := segmentSDF(fx, fy, cx+shackleR, shackleCY, cx+shackleR, bodyCY-bodyHH+0.5) - strokeHalf
dShackle = math.Min(dL, dR)
}
cov := clamp01(0.5 - math.Min(dBody, dShackle))
if cov > 0.001 {
s.blendPixel(x, y, col, cov*alpha)
}
}
}
}
func (s *dibSurface) paintFoldIcon(cx, cy float64, dpi int32, col rgba, alpha float64) {
if alpha <= 0.005 {
return
}
halfW := scaleDPF(dpi, 3.8)
halfH := scaleDPF(dpi, 2.0)
stroke := scaleDPF(dpi, 0.85)
topY := cy - halfH
botY := cy + halfH
bound := int(math.Ceil(halfW+stroke)) + 2
x0 := max(0, int(math.Floor(cx))-bound)
y0 := max(0, int(math.Floor(cy))-bound)
x1 := min(int(s.w), int(math.Ceil(cx))+bound)
y1 := min(int(s.h), int(math.Ceil(cy))+bound)
for y := y0; y < y1; y++ {
fy := float64(y) + 0.5
for x := x0; x < x1; x++ {
fx := float64(x) + 0.5
d1 := segmentSDF(fx, fy, cx-halfW, botY, cx, topY) - stroke
d2 := segmentSDF(fx, fy, cx, topY, cx+halfW, botY) - stroke
cov := clamp01(0.5 - math.Min(d1, d2))
if cov > 0.001 {
s.blendPixel(x, y, col, cov*alpha)
}
}
}
}
func measureLineWidthDC(dc, font uintptr, text string) int32 {
if text == "" || dc == 0 || font == 0 {
return 0
}
old, _, _ := procSelectObject.Call(dc, font)
defer procSelectObject.Call(dc, old)
u16 := utf16.Encode([]rune(text))
if len(u16) == 0 {
return 0
}
var sz gdiSize
var fit int32
_, _, _ = procGetTextExtentExPointW.Call(
dc,
uintptr(unsafe.Pointer(&u16[0])),
uintptr(len(u16)),
0x7fffffff,
uintptr(unsafe.Pointer(&fit)),
0,
uintptr(unsafe.Pointer(&sz)),
)
return sz.cx
}
func isASCIIWordU16(u uint16) bool {
return (u >= 'a' && u <= 'z') || (u >= 'A' && u <= 'Z') || (u >= '0' && u <= '9') || u == '_' || u == '\''
}
func isClosingPunctU16(u uint16) bool {
switch u {
case '.', ',', ';', ':', '?', '!', ')', ']', '}',
'。', ',', '、', ';', ':', '?', '!', ')', '」', '』', '》', '”', '…':
return true
}
return false
}
func wrapStatusLines(dc, font uintptr, text string, maxW int32, maxLines int) []string {
text = strings.TrimSpace(text)
if text == "" || maxW <= 0 || dc == 0 || font == 0 {
return nil
}
old, _, _ := procSelectObject.Call(dc, font)
defer procSelectObject.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
_, _, _ = procGetTextExtentExPointW.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 := max(1, int(fit))
if cut < len(u16) && u16[cut-1] >= 0xD800 && u16[cut-1] <= 0xDBFF {
if cut > 1 {
cut--
} else {
cut++
}
}
if cut < len(u16) && u16[cut] != ' ' {
if (isASCIIWordU16(u16[cut-1]) && isASCIIWordU16(u16[cut])) ||
(isClosingPunctU16(u16[cut]) && isASCIIWordU16(u16[cut-1])) {
for i := cut - 1; i > 0; i-- {
c := u16[i]
if c == ' ' {
cut = i
break
}
if c == '/' || c == '\\' || c == '-' || c == '·' || c > 0x7f {
cut = i + 1
break
}
}
} else if cut > 1 && isClosingPunctU16(u16[cut]) {
cut--
}
}
if maxLines > 0 && len(out)+1 >= maxLines {
// Last allowed line: keep full remainder so DrawTextW with DT_END_ELLIPSIS truncates accurately.
out = append(out, string(utf16.Decode(u16)))
return out
}
out = append(out, strings.TrimRight(string(utf16.Decode(u16[:cut])), " "))
u16 = u16[cut:]
for len(u16) > 0 && u16[0] == ' ' {
u16 = u16[1:]
}
}
}
return out
}
// drawAlphaText renders anti-aliased text via the grayscale scratch DIB and
// composites it onto the premultiplied BGRA target canvas with accurate alpha.
func (s *dibSurface) drawAlphaText(scratch *dibSurface, screenDC, font uintptr, text string, dst rect2i, flags uintptr, col rgba, alpha float64) {
if text == "" || alpha <= 0.005 || dst.width() <= 0 || dst.height() <= 0 || font == 0 {
return
}
w := dst.width()
h := dst.height()
if !scratch.ensure(screenDC, max(scratch.w, w), max(scratch.h, h)) {
return
}
// Clear only the exact sub-rect we are about to draw into.
sw := int(scratch.w)
for row := 0; row < int(h); row++ {
off := row * sw * 4
clear(scratch.bits[off : off+int(w)*4])
}
oldFont, _, _ := procSelectObject.Call(scratch.hdc, font)
_, _, _ = procSetBkMode.Call(scratch.hdc, transparent)
_, _, _ = procSetTextColor.Call(scratch.hdc, rgb(255, 255, 255))
localRect := winRect{Left: 0, Top: 0, Right: w, Bottom: h}
drawWinText(scratch.hdc, text, &localRect, flags|dtNoPrefix)
_, _, _ = procSelectObject.Call(scratch.hdc, oldFont)
_, _, _ = procGdiFlush.Call()
for row := 0; row < int(h); row++ {
dy := int(dst.Top) + row
if dy < 0 || dy >= int(s.h) {
continue
}
srcRowOff := row * sw * 4
for colX := 0; colX < int(w); colX++ {
dx := int(dst.Left) + colX
if dx < 0 || dx >= int(s.w) {
continue
}
// Grayscale AA writes identical luminance to R/G/B on black background.
lum := scratch.bits[srcRowOff+colX*4+2]
if lum == 0 {
continue
}
// Slight stem-weight lift (gamma 0.86) improves crispness of light glyphs on dark glass.
cov := math.Pow(float64(lum)/255.0, 0.86)
s.blendPixel(dx, dy, col, cov*alpha)
}
}
}
type renderParams struct {
state State
layout islandLayout
statusLines []string
fonts islandFontSet
dw *dwriteEngine
hoverZone hitZone
pressedZone hitZone
breath float64
pulse float64
baseCache *islandBaseCache
}
func shiftRect(r rect2i, dx, dy int32) rect2i {
return rect2i{Left: r.Left + dx, Top: r.Top + dy, Right: r.Right + dx, Bottom: r.Bottom + dy}
}
type pillVisual struct {
topFill rgba
botFill rgba
fillA float64
border rgba
borderA float64
fg rgba
topHi float64
}
func buttonStyle(kind string, hovered, pressed bool) pillVisual {
switch kind {
case "resume":
// Crisp macOS Tahoe Apple System Blue primary CTA (--accent #007aff).
v := pillVisual{
topFill: rgba{10, 130, 255},
botFill: rgba{0, 114, 240},
fillA: 1.0,
border: rgba{0, 94, 196},
borderA: 0.18,
fg: rgba{255, 255, 255},
topHi: 0.14,
}
if pressed {
v.topFill = rgba{0, 96, 204}
v.botFill = rgba{0, 88, 192}
v.borderA = 0.22
v.topHi = 0.02
} else if hovered {
v.topFill = rgba{0, 116, 245}
v.botFill = rgba{0, 102, 224}
v.borderA = 0.22
v.topHi = 0.16
}
return v
case "pause", "close":
// Lightweight borderless tonal macOS secondary button (#F2F3F7).
v := pillVisual{
topFill: rgba{244, 245, 248},
botFill: rgba{239, 241, 245},
fillA: 1.0,
border: rgba{15, 23, 42},
borderA: 0.055,
fg: rgba{29, 29, 31}, // --text #1d1d1f
topHi: 0,
}
if pressed {
v.topFill = rgba{223, 226, 234}
v.botFill = rgba{220, 223, 232}
v.borderA = 0.09
v.fg = rgba{17, 17, 19}
} else if hovered {
v.topFill = rgba{235, 237, 242}
v.botFill = rgba{231, 234, 240}
v.borderA = 0.08
v.fg = rgba{17, 17, 19}
}
return v
default: // stop
// Soft macOS light-mode crimson-tinted pill (--danger-soft / --danger-text).
v := pillVisual{
topFill: rgba{255, 241, 240},
botFill: rgba{255, 235, 234},
fillA: 1.0,
border: rgba{215, 0, 21},
borderA: 0.08,
fg: rgba{215, 0, 21}, // --danger-text #d70015
topHi: 0,
}
if pressed {
v.topFill = rgba{224, 45, 34}
v.botFill = rgba{208, 34, 24}
v.border = rgba{184, 20, 14}
v.borderA = 0.24
v.fg = rgba{255, 255, 255}
v.topHi = 0.06
} else if hovered {
v.topFill = rgba{255, 229, 227}
v.botFill = rgba{255, 222, 220}
v.border = rgba{215, 0, 21}
v.borderA = 0.18
v.fg = rgba{194, 0, 18}
}
return v
}
}
type textDrawItem struct {
style textStyle
text string
dst rect2i
align uint32
maxLines int
col rgba
alpha float64
gdiFont uintptr
gdiFlags uintptr
}
type islandBaseCacheKey struct {
state State
layout islandLayout
hoverZone hitZone
pressedZone hitZone
pulse float64
}
type islandBaseCache struct {
surface dibSurface
key islandBaseCacheKey
valid bool
}
func (c *islandBaseCache) release() {
c.surface.release()
c.valid = false
}
func islandBaseCacheKeyFor(p renderParams) islandBaseCacheKey {
st := p.state
st.PID = 0
pulse := p.pulse
if pulse <= 0.005 {
pulse = 0
}
return islandBaseCacheKey{
state: st,
layout: p.layout,
hoverZone: p.hoverZone,
pressedZone: p.pressedZone,
pulse: pulse,
}
}
func renderIslandFrame(canvas, scratch *dibSurface, screenDC uintptr, p renderParams) bool {
l := p.layout
if !canvas.ensure(screenDC, l.CanvasW, l.CanvasH) {
return false
}
if cache := p.baseCache; cache != nil {
key := islandBaseCacheKeyFor(p)
if !cache.valid || cache.key != key || cache.surface.w != l.CanvasW || cache.surface.h != l.CanvasH || len(cache.surface.bits) != len(canvas.bits) {
if !renderIslandStaticBase(&cache.surface, scratch, screenDC, p) {
cache.valid = false
return false
}
cache.key = key
cache.valid = true
}
copy(canvas.bits, cache.surface.bits)
} else if !renderIslandStaticBase(canvas, scratch, screenDC, p) {
return false
}
// Paint the breathing/completed status dot on top of the cached static base so
// breathing ticks avoid recomputing the SDF shadow/shell and DirectWrite text.
dotPos := point2i{X: l.PadX + l.DotCenter.X, Y: l.PadTop + l.DotCenter.Y}
if p.state.Completed {
canvas.paintCompletedDot(dotPos, l.DPI)
} else {
canvas.paintStatusDot(dotPos, l.DPI, p.state.CanResume, p.breath)
}
return true
}
func renderIslandStaticBase(canvas, scratch *dibSurface, screenDC uintptr, p renderParams) bool {
l := p.layout
if !canvas.ensure(screenDC, l.CanvasW, l.CanvasH) {
return false
}
canvas.clear()
// 1. Opaque matte-obsidian shell, floating elevation shadow, crisp rim & pulse.
canvas.paintIslandShell(l, p.state.CanResume, p.pulse)
ox := l.PadX
oy := l.PadTop
script := scriptForState(p.state)
var textQueue []textDrawItem
measureTextW := func(style textStyle, gdiFont uintptr, s string) int32 {
if p.dw != nil {
if w, ok := p.dw.measureLineWidth(l.DPI, script, style, s); ok && w > 0 {
return w
}
}
if w := measureLineWidthDC(scratch.hdc, gdiFont, s); w > 0 {
return w
}
return measureLineWidthDC(screenDC, gdiFont, s)
}
// 3. Compact pill elements (fades out cleanly during first 35% of expand).
if l.CompactAlpha > 0.01 {
a := l.CompactAlpha
if p.state.InputLocked && l.CompactLockRect.width() > 0 {
lr := shiftRect(l.CompactLockRect, ox, oy)
canvas.paintLockIcon(float64(lr.Left+lr.Right)*0.5, float64(lr.Top+lr.Bottom)*0.5, l.DPI, rgba{110, 110, 115}, 0.88*a)
}
tr := shiftRect(l.CompactTitleRect, ox, oy)
titleCol := rgba{29, 29, 31}
if p.hoverZone == zoneInfo {
titleCol = rgba{0, 0, 0}
}
textQueue = append(textQueue, textDrawItem{
style: styleCompact, text: compactPrimaryText(p.state), dst: tr,
align: dwAlignLeading, maxLines: 1, col: titleCol, alpha: 0.98 * a,
gdiFont: p.fonts.compactTitle, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis,
})
if l.HasToggle {
kind := "pause"
if p.state.CanResume {
kind = "resume"
}
btnR := shiftRect(l.CompactToggleBtn, ox, oy)
st := buttonStyle(kind, p.hoverZone == zoneToggle, p.pressedZone == zoneToggle)
canvas.paintTactilePill(btnR, float64(btnR.height())*0.5, st.topFill, st.botFill, st.fillA*a, st.border, st.borderA*a, st.topHi*a)
bcx := float64(btnR.Left+btnR.Right) * 0.5
bcy := float64(btnR.Top+btnR.Bottom) * 0.5
if p.state.CanResume {
canvas.paintPlayIcon(bcx, bcy, l.DPI, st.fg, a)
} else {
canvas.paintPauseIcon(bcx, bcy, l.DPI, st.fg, a)
}
}
stopR := shiftRect(l.CompactStopBtn, ox, oy)
stopKind := "stop"
if p.state.Completed {
stopKind = "close"
}
st := buttonStyle(stopKind, p.hoverZone == zoneStop, p.pressedZone == zoneStop)
canvas.paintTactilePill(stopR, float64(stopR.height())*0.5, st.topFill, st.botFill, st.fillA*a, st.border, st.borderA*a, st.topHi*a)
if p.state.Completed {
canvas.paintCloseIcon(float64(stopR.Left+stopR.Right)*0.5, float64(stopR.Top+stopR.Bottom)*0.5, l.DPI, st.fg, a)
} else {
canvas.paintStopIcon(float64(stopR.Left+stopR.Right)*0.5, float64(stopR.Top+stopR.Bottom)*0.5, l.DPI, st.fg, a)
}
}
// 4. Expanded light macOS card elements (fades in smoothly during 42..100%).
if l.ExpandedAlpha > 0.01 {
a := l.ExpandedAlpha
// Row 1: Subtle Apple grey session meta label + borderless lock glyph + ghost fold button.
titleR := shiftRect(l.ExpandedTitleRect, ox, oy)
textQueue = append(textQueue, textDrawItem{
style: styleMeta, text: p.state.Title, dst: titleR,
align: dwAlignLeading, maxLines: 1, col: rgba{110, 110, 115}, alpha: 0.96 * a,
gdiFont: p.fonts.status, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis,
})
if p.state.InputLocked && l.ExpandedLockBadge.width() > 0 {
badgeR := shiftRect(l.ExpandedLockBadge, ox, oy)
lockCol := rgba{142, 142, 147}
lockA := 0.90 * a
if p.pulse > 0.05 {
lockCol = rgba{217, 119, 6}
lockA = a
}
canvas.paintLockIcon(float64(badgeR.Left+badgeR.Right)*0.5, float64(badgeR.Top+badgeR.Bottom)*0.5, l.DPI, lockCol, lockA)
}
if l.ExpandedFoldBtn.width() > 0 {
foldR := shiftRect(l.ExpandedFoldBtn, ox, oy)
iconCol := rgba{110, 110, 115}
if p.pressedZone == zoneFold {
canvas.paintTactilePill(foldR, float64(foldR.height())*0.5, rgba{228, 231, 238}, rgba{224, 227, 235}, a, rgba{15, 23, 42}, 0.06*a, 0)
iconCol = rgba{29, 29, 31}
} else if p.hoverZone == zoneFold {
canvas.paintTactilePill(foldR, float64(foldR.height())*0.5, rgba{240, 242, 246}, rgba{236, 238, 243}, a, rgba{15, 23, 42}, 0.04*a, 0)
iconCol = rgba{29, 29, 31}
}
canvas.paintFoldIcon(float64(foldR.Left+foldR.Right)*0.5, float64(foldR.Top+foldR.Bottom)*0.5, l.DPI, iconCol, a)
}
// Row 2: Crisp Apple Ink Hero Step headline (#1D1D1F).
if l.HasStep && l.ExpandedStepRect.width() > 0 {
stepR := shiftRect(l.ExpandedStepRect, ox, oy)
textQueue = append(textQueue, textDrawItem{
style: styleHero, text: p.state.StepText, dst: stepR,
align: dwAlignLeading, maxLines: 1, col: rgba{29, 29, 31}, alpha: 0.99 * a,
gdiFont: p.fonts.title, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis,
})
}
// Row 3: Clean Apple Secondary Grey detail (up to 2 lines).
if l.HasStatus && strings.TrimSpace(p.state.StatusLine) != "" {
statusBase := shiftRect(l.ExpandedStatusRect, ox, oy)
if p.dw != nil && p.dw.ensureInit() {
textQueue = append(textQueue, textDrawItem{
style: styleStatus, text: strings.TrimSpace(p.state.StatusLine), dst: statusBase,
align: dwAlignLeading, maxLines: 2, col: rgba{110, 110, 115}, alpha: 0.96 * a,
gdiFont: p.fonts.status, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis,
})
} else {
lineH := scaleDP(l.DPI, 18)
for idx, line := range p.statusLines {
if idx >= 2 {
break
}
lr := rect2i{
Left: statusBase.Left,
Top: statusBase.Top + int32(idx)*lineH,
Right: statusBase.Right,
Bottom: statusBase.Top + int32(idx+1)*lineH,
}
textQueue = append(textQueue, textDrawItem{
style: styleStatus, text: line, dst: lr,
align: dwAlignLeading, maxLines: 1, col: rgba{110, 110, 115}, alpha: 0.96 * a,
gdiFont: p.fonts.status, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis,
})
}
}
}
// Row 4: Concentric solid matte action buttons (icon + label).
if l.HasToggle {
kind := "pause"
label := p.state.PauseLabel
if p.state.CanResume {
kind = "resume"
label = p.state.ResumeLabel
}
btnR := shiftRect(l.ExpandedToggleBtn, ox, oy)
if item, ok := paintExpandedActionButton(canvas, btnR, kind, label, p.fonts.btn, l.DPI, p.hoverZone == zoneToggle, p.pressedZone == zoneToggle, a, measureTextW); ok {
textQueue = append(textQueue, item)
}
}
stopR := shiftRect(l.ExpandedStopBtn, ox, oy)
stopKind := "stop"
stopLabel := p.state.StopLabel
if p.state.Completed {
stopKind = "close"
stopLabel = p.state.CloseLabel
}
if item, ok := paintExpandedActionButton(canvas, stopR, stopKind, stopLabel, p.fonts.btn, l.DPI, p.hoverZone == zoneStop, p.pressedZone == zoneStop, a, measureTextW); ok {
textQueue = append(textQueue, item)
}
}
// 5. Render all queued text through Direct2D + DirectWrite in one crisp pass
// (automatically falling back to grayscale GDI DIB compositing if unavailable).
usedDWrite := false
if p.dw != nil && len(textQueue) > 0 && p.dw.beginSurface(canvas) {
usedDWrite = true
for _, it := range textQueue {
if !p.dw.drawText(l.DPI, script, it.style, it.text, it.dst, it.align, it.maxLines, it.col, it.alpha) {
usedDWrite = false
break
}
}
if !p.dw.endSurface() {
usedDWrite = false
}
}
if !usedDWrite {
for _, it := range textQueue {
canvas.drawAlphaText(scratch, screenDC, it.gdiFont, it.text, it.dst, it.gdiFlags, it.col, it.alpha)
}
}
return true
}
func paintExpandedActionButton(
canvas *dibSurface,
btnR rect2i,
kind, label string,
gdiFont uintptr,
dpi int32,
hovered, pressed bool,
alpha float64,
measureW func(textStyle, uintptr, string) int32,
) (textDrawItem, bool) {
st := buttonStyle(kind, hovered, pressed)
btnRadius := scaleDPF(dpi, 8)
canvas.paintTactilePill(btnR, btnRadius, st.topFill, st.botFill, st.fillA*alpha, st.border, st.borderA*alpha, st.topHi*alpha)
iconW := scaleDP(dpi, 10)
gap := scaleDP(dpi, 7)
textW := measureW(styleBtn, gdiFont, label)
maxTextW := max(int32(0), btnR.width()-scaleDP(dpi, 20)-iconW-gap)
if textW > maxTextW {
textW = maxTextW
}
groupW := iconW + gap + textW
startX := btnR.Left + (btnR.width()-groupW)/2
midY := float64(btnR.Top+btnR.Bottom) * 0.5
iconCX := float64(startX) + float64(iconW)*0.5
switch kind {
case "resume":
canvas.paintPlayIcon(iconCX, midY, dpi, st.fg, alpha)
case "pause":
canvas.paintPauseIcon(iconCX, midY, dpi, st.fg, alpha)
case "close":
canvas.paintCloseIcon(iconCX, midY, dpi, st.fg, alpha)
default:
canvas.paintStopIcon(iconCX, midY, dpi, st.fg, alpha)
}
textR := rect2i{
Left: startX + iconW + gap,
Top: btnR.Top,
Right: min(btnR.Right-scaleDP(dpi, 8), startX+iconW+gap+textW+scaleDP(dpi, 6)),
Bottom: btnR.Bottom,
}
return textDrawItem{
style: styleBtn, text: label, dst: textR,
align: dwAlignLeading, maxLines: 1, col: st.fg, alpha: alpha,
gdiFont: gdiFont, gdiFlags: dtLeft | dtVCenter | dtSingleLine | dtEndEllipsis,
}, true
}