Files
Reims-Go/internal/host/sessionoverlay/dwrite_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

626 lines
17 KiB
Go

//go:build windows
package sessionoverlay
import (
"math"
"strings"
"syscall"
"unicode/utf16"
"unsafe"
)
type comGUID struct {
Data1 uint32
Data2 uint16
Data3 uint16
Data4 [8]byte
}
var (
d2d1DLL = syscall.NewLazyDLL("d2d1.dll")
dwriteDLL = syscall.NewLazyDLL("dwrite.dll")
procD2D1CreateFactory = d2d1DLL.NewProc("D2D1CreateFactory")
procDWriteCreateFactory = dwriteDLL.NewProc("DWriteCreateFactory")
iidID2D1Factory = comGUID{0x06152247, 0x6f50, 0x465a, [8]byte{0x92, 0x45, 0x11, 0x8b, 0xfd, 0x3b, 0x60, 0x07}}
iidIDWriteFactory = comGUID{0xb859ee5a, 0xd838, 0x4b5b, [8]byte{0xa2, 0xe8, 0x1a, 0xdc, 0x7d, 0x93, 0xdb, 0x48}}
)
type comObj struct {
vtbl *[80]uintptr
}
// Windows SDK d2d1.h / dwrite.h COM vtable slot indices (0-based, after
// IUnknown slots 0=QueryInterface, 1=AddRef, 2=Release).
const (
vtblIUnknownRelease = 2
// ID2D1Factory (d2d1.h, inherits IUnknown):
// 3=ReloadSystemMetrics, 4=GetDesktopDpi, 5..10=Create*Geometry,
// 11=CreateStrokeStyle, 12=CreateDrawingStateBlock, 13=CreateWicBitmapRenderTarget,
// 14=CreateHwndRenderTarget, 15=CreateDxgiSurfaceRenderTarget, 16=CreateDCRenderTarget.
vtblD2DFactoryCreateDCRenderTarget = 16
// ID2D1RenderTarget (d2d1.h, inherits ID2D1Resource -> IUnknown; 3=GetFactory):
// 4..7=CreateBitmap*, 8=CreateSolidColorBrush, ..., 28=DrawTextLayout,
// ..., 34=SetTextAntialiasMode, ..., 48=BeginDraw, 49=EndDraw.
// ID2D1DCRenderTarget (inherits ID2D1RenderTarget; slots 4..56): 57=BindDC.
vtblD2DRTCreateSolidColorBrush = 8
vtblD2DRTDrawTextLayout = 28
vtblD2DRTSetTextAntialiasMode = 34
vtblD2DRTBeginDraw = 48
vtblD2DRTEndDraw = 49
vtblD2DDCRTBindDC = 57
// ID2D1SolidColorBrush (d2d1.h, inherits ID2D1Brush -> ID2D1Resource -> IUnknown):
// 3=GetFactory, 4=SetOpacity, 5=SetTransform, 6=GetOpacity, 7=GetTransform, 8=SetColor.
vtblD2DSolidBrushSetColor = 8
// IDWriteFactory (dwrite.h, inherits IUnknown):
// 3=GetSystemFontCollection, ..., 15=CreateTextFormat, ..., 18=CreateTextLayout,
// ..., 20=CreateEllipsisTrimmingSign.
vtblDWFactoryGetSystemFontCollection = 3
vtblDWFactoryCreateTextFormat = 15
vtblDWFactoryCreateTextLayout = 18
vtblDWFactoryCreateEllipsisTrimmingSign = 20
// IDWriteFontCollection (dwrite.h, inherits IUnknown):
// 3=GetFontFamilyCount, 4=GetFontFamily, 5=FindFamilyName.
vtblDWFontCollectionFindFamilyName = 5
// IDWriteTextLayout (dwrite.h, inherits IDWriteTextFormat -> IUnknown):
// 3=SetTextAlignment, 4=SetParagraphAlignment, 5=SetWordWrapping, ..., 9=SetTrimming,
// ..., 31=SetFontFamilyName, 32=SetFontWeight, ..., 60=GetMetrics.
vtblDWLayoutSetTextAlignment = 3
vtblDWLayoutSetParagraphAlignment = 4
vtblDWLayoutSetWordWrapping = 5
vtblDWLayoutSetTrimming = 9
vtblDWLayoutSetFontFamilyName = 31
vtblDWLayoutSetFontWeight = 32
vtblDWLayoutGetMetrics = 60
)
func (o *comObj) release() {
if o != nil {
_, _, _ = syscall.SyscallN(o.vtbl[vtblIUnknownRelease], uintptr(unsafe.Pointer(o)))
}
}
type d2dPixelFormat struct {
format uint32
alphaMode uint32
}
type d2dRTProps struct {
typ uint32
pixelFormat d2dPixelFormat
dpiX, dpiY float32
usage uint32
minLevel uint32
}
type d2dColorF struct {
r, g, b, a float32
}
type dwTrimming struct {
granularity uint32
delimiter uint32
delimiterCount uint32
}
type dwTextMetrics struct {
left float32
top float32
width float32
widthIncludingTrailingWhitespace float32
height float32
layoutWidth float32
layoutHeight float32
maxBidiReorderingDepth uint32
lineCount uint32
}
const (
dwAlignLeading = 0
dwAlignTrailing = 1
dwAlignCenter = 2
dwParaNear = 0
dwParaCenter = 2
dwWrapNormal = 0
dwWrapNone = 1
dwTrimCharacter = 1
)
type textStyle uint8
const (
styleMeta textStyle = iota
styleHero
styleStatus
styleBtn
styleCompact
styleTip
)
type dwFormatKey struct {
dpi int32
script scriptKind
style textStyle
}
type dwFormatEntry struct {
format *comObj
ellipsisSign *comObj
latinFace string
latinWeight uint32
lineHeight float32
}
// dwriteEngine manages per-UI-thread software Direct2D + DirectWrite COM
// resources for crisp, subpixel-positioned grayscale-AA typography on 32-bit
// premultiplied BGRA layered surfaces with zero GPU contention.
type dwriteEngine struct {
ready bool
failed bool
d2dFactory *comObj
dwFactory *comObj
dcRT *comObj
brush *comObj
families map[scriptKind]string
latinText string
latinDisp string
formats map[dwFormatKey]dwFormatEntry
drawing bool
boundCanvas *dibSurface
}
func packD2DPoint2F(x, y float32) uintptr {
return uintptr(uint64(math.Float32bits(x)) | uint64(math.Float32bits(y))<<32)
}
func packDWRange(start, length uint32) uintptr {
return uintptr(uint64(start) | uint64(length)<<32)
}
func (e *dwriteEngine) ensureInit() bool {
if e.ready {
return true
}
if e.failed {
return false
}
if procD2D1CreateFactory.Find() != nil || procDWriteCreateFactory.Find() != nil {
e.failed = true
return false
}
var d2dFac *comObj
hr, _, _ := procD2D1CreateFactory.Call(
0, // D2D1_FACTORY_TYPE_SINGLE_THREADED
uintptr(unsafe.Pointer(&iidID2D1Factory)),
0,
uintptr(unsafe.Pointer(&d2dFac)),
)
if int32(hr) < 0 || d2dFac == nil {
e.failed = true
return false
}
var dwFac *comObj
hr, _, _ = procDWriteCreateFactory.Call(
0, // DWRITE_FACTORY_TYPE_SHARED
uintptr(unsafe.Pointer(&iidIDWriteFactory)),
uintptr(unsafe.Pointer(&dwFac)),
)
if int32(hr) < 0 || dwFac == nil {
d2dFac.release()
e.failed = true
return false
}
props := d2dRTProps{
typ: 1, // D2D1_RENDER_TARGET_TYPE_SOFTWARE (CPU WARP, zero VRAM/GPU contention with reims-vgpu)
pixelFormat: d2dPixelFormat{format: 87, alphaMode: 1}, // DXGI_FORMAT_B8G8R8A8_UNORM + PREMULTIPLIED
dpiX: 96,
dpiY: 96,
}
var rt *comObj
hr, _, _ = syscall.SyscallN(d2dFac.vtbl[vtblD2DFactoryCreateDCRenderTarget], uintptr(unsafe.Pointer(d2dFac)), uintptr(unsafe.Pointer(&props)), uintptr(unsafe.Pointer(&rt)))
if int32(hr) < 0 || rt == nil {
dwFac.release()
d2dFac.release()
e.failed = true
return false
}
// D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE (2) preserves exact premultiplied alpha.
_, _, _ = syscall.SyscallN(rt.vtbl[vtblD2DRTSetTextAntialiasMode], uintptr(unsafe.Pointer(rt)), 2)
white := d2dColorF{1, 1, 1, 1}
var brush *comObj
hr, _, _ = syscall.SyscallN(rt.vtbl[vtblD2DRTCreateSolidColorBrush], uintptr(unsafe.Pointer(rt)), uintptr(unsafe.Pointer(&white)), 0, uintptr(unsafe.Pointer(&brush)))
if int32(hr) < 0 || brush == nil {
rt.release()
dwFac.release()
d2dFac.release()
e.failed = true
return false
}
e.d2dFactory = d2dFac
e.dwFactory = dwFac
e.dcRT = rt
e.brush = brush
e.formats = make(map[dwFormatKey]dwFormatEntry)
e.probeFamilies()
e.ready = true
return true
}
func (e *dwriteEngine) probeFamilies() {
e.families = map[scriptKind]string{
scriptLatn: "Segoe UI",
scriptHans: "Microsoft YaHei UI",
scriptHant: "Microsoft JhengHei UI",
scriptJpan: "Yu Gothic UI",
scriptKore: "Malgun Gothic",
}
e.latinText = "Segoe UI"
e.latinDisp = "Segoe UI"
var col *comObj
hr, _, _ := syscall.SyscallN(e.dwFactory.vtbl[vtblDWFactoryGetSystemFontCollection], uintptr(unsafe.Pointer(e.dwFactory)), uintptr(unsafe.Pointer(&col)), 0)
if int32(hr) < 0 || col == nil {
return
}
defer col.release()
has := func(name string) bool {
ptr, err := syscall.UTF16PtrFromString(name)
if err != nil {
return false
}
var idx uint32
var exists int32
hr, _, _ := syscall.SyscallN(col.vtbl[vtblDWFontCollectionFindFamilyName], uintptr(unsafe.Pointer(col)), uintptr(unsafe.Pointer(ptr)), uintptr(unsafe.Pointer(&idx)), uintptr(unsafe.Pointer(&exists)))
return int32(hr) >= 0 && exists != 0
}
pickFirst := func(candidates []string, fallback string) string {
for _, c := range candidates {
if has(c) {
return c
}
}
return fallback
}
e.latinText = pickFirst([]string{"Segoe UI Variable Text", "Segoe UI"}, "Segoe UI")
e.latinDisp = pickFirst([]string{"Segoe UI Variable Display", "Segoe UI Variable Text", "Segoe UI"}, e.latinText)
e.families[scriptLatn] = e.latinText
e.families[scriptHans] = pickFirst([]string{
"PingFang SC", "HarmonyOS Sans SC", "MiSans",
"Noto Sans SC", "Source Han Sans CN", "Microsoft YaHei UI", "DengXian",
}, "Microsoft YaHei UI")
e.families[scriptHant] = pickFirst([]string{
"PingFang TC", "Noto Sans TC", "Source Han Sans TC", "Microsoft JhengHei UI",
}, "Microsoft JhengHei UI")
e.families[scriptJpan] = pickFirst([]string{
"Hiragino Sans", "Noto Sans JP", "BIZ UDPGothic", "Yu Gothic UI",
}, "Yu Gothic UI")
e.families[scriptKore] = pickFirst([]string{
"Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic",
}, "Malgun Gothic")
}
func (e *dwriteEngine) release() {
if e.drawing {
e.endSurface()
}
for k, fe := range e.formats {
fe.ellipsisSign.release()
fe.format.release()
delete(e.formats, k)
}
e.brush.release()
e.dcRT.release()
e.dwFactory.release()
e.d2dFactory.release()
e.brush = nil
e.dcRT = nil
e.dwFactory = nil
e.d2dFactory = nil
e.ready = false
}
func localeTagForScript(sk scriptKind) string {
switch sk {
case scriptHans:
return "zh-CN"
case scriptHant:
return "zh-TW"
case scriptJpan:
return "ja-JP"
case scriptKore:
return "ko-KR"
default:
return "en-US"
}
}
func (e *dwriteEngine) getFormat(dpi int32, script scriptKind, style textStyle) (dwFormatEntry, bool) {
if !e.ensureInit() {
return dwFormatEntry{}, false
}
if dpi < 96 {
dpi = 96
}
key := dwFormatKey{dpi: dpi, script: script, style: style}
if fe, ok := e.formats[key]; ok {
return fe, true
}
face := e.families[script]
if face == "" {
face = e.latinText
}
scale := float32(dpi) / 96.0
isBinaryWeight := face == "Microsoft YaHei UI" || face == "Microsoft JhengHei UI" || face == "Malgun Gothic" || face == "DengXian"
var px float32
var weight uint32
var latinWeight uint32
latinFace := e.latinText
switch style {
case styleMeta:
px = 11.5
weight = 500
latinWeight = 500
if isBinaryWeight {
weight = 400
}
case styleHero:
px = 15.0
weight = 550
latinWeight = 600
latinFace = e.latinDisp
if isBinaryWeight {
weight = 600
}
case styleStatus:
px = 12.0
weight = 400
latinWeight = 400
case styleBtn:
px = 12.5
weight = 500
latinWeight = 550
if isBinaryWeight {
weight = 400
}
case styleCompact:
px = 12.5
weight = 500
latinWeight = 550
if isBinaryWeight {
weight = 400
}
default: // styleTip
px = 11.5
weight = 500
latinWeight = 500
if isBinaryWeight {
weight = 400
}
}
famPtr, _ := syscall.UTF16PtrFromString(face)
locPtr, _ := syscall.UTF16PtrFromString(localeTagForScript(script))
var tf *comObj
hr, _, _ := syscall.SyscallN(
e.dwFactory.vtbl[vtblDWFactoryCreateTextFormat],
uintptr(unsafe.Pointer(e.dwFactory)),
uintptr(unsafe.Pointer(famPtr)),
0,
uintptr(weight),
0, // DWRITE_FONT_STYLE_NORMAL
5, // DWRITE_FONT_STRETCH_NORMAL
uintptr(math.Float32bits(px*scale)),
uintptr(unsafe.Pointer(locPtr)),
uintptr(unsafe.Pointer(&tf)),
)
if int32(hr) < 0 || tf == nil {
return dwFormatEntry{}, false
}
var sign *comObj
_, _, _ = syscall.SyscallN(
e.dwFactory.vtbl[vtblDWFactoryCreateEllipsisTrimmingSign],
uintptr(unsafe.Pointer(e.dwFactory)),
uintptr(unsafe.Pointer(tf)),
uintptr(unsafe.Pointer(&sign)),
)
fe := dwFormatEntry{
format: tf,
ellipsisSign: sign,
latinFace: latinFace,
latinWeight: latinWeight,
lineHeight: px * scale * 1.45,
}
e.formats[key] = fe
return fe, true
}
func isLatinRunRune(u uint16) bool {
return u >= 0x0021 && u <= 0x007E
}
func (e *dwriteEngine) buildLayout(dpi int32, script scriptKind, style textStyle, text string, maxW, maxH float32, align uint32, maxLines int) (*comObj, bool) {
if text == "" || maxW <= 0 || maxH <= 0 {
return nil, false
}
fe, ok := e.getFormat(dpi, script, style)
if !ok {
return nil, false
}
u16 := utf16.Encode([]rune(text))
if len(u16) == 0 {
return nil, false
}
var layout *comObj
hr, _, _ := syscall.SyscallN(
e.dwFactory.vtbl[vtblDWFactoryCreateTextLayout],
uintptr(unsafe.Pointer(e.dwFactory)),
uintptr(unsafe.Pointer(&u16[0])),
uintptr(len(u16)),
uintptr(unsafe.Pointer(fe.format)),
uintptr(math.Float32bits(maxW)),
uintptr(math.Float32bits(maxH)),
uintptr(unsafe.Pointer(&layout)),
)
if int32(hr) < 0 || layout == nil {
return nil, false
}
_, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetTextAlignment], uintptr(unsafe.Pointer(layout)), uintptr(align))
if maxLines <= 1 {
_, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetParagraphAlignment], uintptr(unsafe.Pointer(layout)), dwParaCenter)
_, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetWordWrapping], uintptr(unsafe.Pointer(layout)), dwWrapNone)
} else {
_, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetParagraphAlignment], uintptr(unsafe.Pointer(layout)), dwParaNear)
_, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetWordWrapping], uintptr(unsafe.Pointer(layout)), dwWrapNormal)
}
if fe.ellipsisSign != nil {
trim := dwTrimming{granularity: dwTrimCharacter}
_, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetTrimming], uintptr(unsafe.Pointer(layout)), uintptr(unsafe.Pointer(&trim)), uintptr(unsafe.Pointer(fe.ellipsisSign)))
}
// Pair crisp Segoe UI Variable on Latin/digit runs inside CJK text for
// balanced Apple-like mixed-script typography.
if script != scriptLatn && fe.latinFace != "" {
latinPtr, _ := syscall.UTF16PtrFromString(fe.latinFace)
i := 0
for i < len(u16) {
if !isLatinRunRune(u16[i]) {
i++
continue
}
start := i
for i < len(u16) && (isLatinRunRune(u16[i]) || u16[i] == ' ') {
i++
}
end := i
for end > start && u16[end-1] == ' ' {
end--
}
if end > start {
r := packDWRange(uint32(start), uint32(end-start))
_, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetFontFamilyName], uintptr(unsafe.Pointer(layout)), uintptr(unsafe.Pointer(latinPtr)), r)
_, _, _ = syscall.SyscallN(layout.vtbl[vtblDWLayoutSetFontWeight], uintptr(unsafe.Pointer(layout)), uintptr(fe.latinWeight), r)
}
}
}
return layout, true
}
func (e *dwriteEngine) measureLineWidth(dpi int32, script scriptKind, style textStyle, text string) (int32, bool) {
if strings.TrimSpace(text) == "" {
return 0, true
}
layout, ok := e.buildLayout(dpi, script, style, text, 4096, 256, dwAlignLeading, 1)
if !ok {
return 0, false
}
defer layout.release()
var m dwTextMetrics
hr, _, _ := syscall.SyscallN(layout.vtbl[vtblDWLayoutGetMetrics], uintptr(unsafe.Pointer(layout)), uintptr(unsafe.Pointer(&m)))
if int32(hr) < 0 {
return 0, false
}
return int32(math.Ceil(float64(m.widthIncludingTrailingWhitespace))), true
}
func (e *dwriteEngine) measureWrappedLines(dpi int32, script scriptKind, style textStyle, text string, maxW int32, maxLines int) (int, bool) {
text = strings.TrimSpace(text)
if text == "" {
return 0, true
}
layout, ok := e.buildLayout(dpi, script, style, text, float32(maxW), 512, dwAlignLeading, maxLines)
if !ok {
return 0, false
}
defer layout.release()
var m dwTextMetrics
hr, _, _ := syscall.SyscallN(layout.vtbl[vtblDWLayoutGetMetrics], uintptr(unsafe.Pointer(layout)), uintptr(unsafe.Pointer(&m)))
if int32(hr) < 0 {
return 0, false
}
cnt := int(m.lineCount)
if cnt < 1 {
cnt = 1
}
if maxLines > 0 && cnt > maxLines {
cnt = maxLines
}
return cnt, true
}
func (e *dwriteEngine) beginSurface(canvas *dibSurface) bool {
if canvas == nil || canvas.hdc == 0 || !e.ensureInit() {
return false
}
rc := winRect{Left: 0, Top: 0, Right: canvas.w, Bottom: canvas.h}
hr, _, _ := syscall.SyscallN(e.dcRT.vtbl[vtblD2DDCRTBindDC], uintptr(unsafe.Pointer(e.dcRT)), canvas.hdc, uintptr(unsafe.Pointer(&rc)))
if int32(hr) < 0 {
return false
}
_, _, _ = syscall.SyscallN(e.dcRT.vtbl[vtblD2DRTBeginDraw], uintptr(unsafe.Pointer(e.dcRT)))
e.drawing = true
e.boundCanvas = canvas
return true
}
func (e *dwriteEngine) endSurface() bool {
if !e.drawing || e.dcRT == nil {
return false
}
hr, _, _ := syscall.SyscallN(e.dcRT.vtbl[vtblD2DRTEndDraw], uintptr(unsafe.Pointer(e.dcRT)), 0, 0)
e.drawing = false
e.boundCanvas = nil
return int32(hr) >= 0
}
func (e *dwriteEngine) drawText(dpi int32, script scriptKind, style textStyle, text string, dst rect2i, align uint32, maxLines int, col rgba, alpha float64) bool {
if !e.drawing || text == "" || alpha <= 0.005 || dst.width() <= 0 || dst.height() <= 0 {
return true
}
layout, ok := e.buildLayout(dpi, script, style, text, float32(dst.width()), float32(dst.height()), align, maxLines)
if !ok {
return false
}
defer layout.release()
c := d2dColorF{
r: float32(col.r) / 255.0,
g: float32(col.g) / 255.0,
b: float32(col.b) / 255.0,
a: float32(clamp01(alpha)),
}
_, _, _ = syscall.SyscallN(e.brush.vtbl[vtblD2DSolidBrushSetColor], uintptr(unsafe.Pointer(e.brush)), uintptr(unsafe.Pointer(&c)))
// D2D1_DRAW_TEXT_OPTIONS_CLIP (0x00000002) prevents overflow outside dst.
_, _, _ = syscall.SyscallN(
e.dcRT.vtbl[vtblD2DRTDrawTextLayout],
uintptr(unsafe.Pointer(e.dcRT)),
packD2DPoint2F(float32(dst.Left), float32(dst.Top)),
uintptr(unsafe.Pointer(layout)),
uintptr(unsafe.Pointer(e.brush)),
2,
)
return true
}