Files
Reims-Go/internal/macos/autoinstall/rules/normalize.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

548 lines
13 KiB
Go

package rules
import (
"image"
"strings"
"unicode"
"github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr"
)
func isCJK(r rune) bool {
return unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r) || unicode.Is(unicode.Hangul, r)
}
// NormalizeText removes spaces inserted between CJK runes by Windows.Media.Ocr
// (e.g. "实 用 工 具" -> "实用工具"), folds full-width forms to ASCII, lowercases,
// and trims punctuation and ellipses.
func NormalizeText(s string) string {
var runes []rune
for _, r := range s {
if r >= 0xFF01 && r <= 0xFF5E {
r = r - 0xFF01 + 0x21
} else if r == 0x3000 {
r = ' '
}
if r == '…' {
continue
}
r = unicode.ToLower(r)
runes = append(runes, r)
}
var out []rune
for i := 0; i < len(runes); i++ {
r := runes[i]
if unicode.IsSpace(r) {
if len(out) == 0 {
continue
}
prev := out[len(out)-1]
// Look ahead to next non-space rune.
j := i + 1
for j < len(runes) && unicode.IsSpace(runes[j]) {
j++
}
if j >= len(runes) {
break
}
next := runes[j]
i = j - 1
// Drop spaces adjacent to CJK characters to reverse WinRT spacing.
if isCJK(prev) || isCJK(next) {
continue
}
out = append(out, ' ')
continue
}
out = append(out, r)
}
trimmed := strings.TrimSpace(string(out))
trimmed = strings.Trim(trimmed, ".,:;!?()[]{}\"'`~-—–•·")
return trimmed
}
// CompactText removes all spaces after NormalizeText for tolerant phrase matching.
func CompactText(s string) string {
return strings.ReplaceAll(NormalizeText(s), " ", "")
}
// MatchPhrase matches needle against haystack using priority:
// 1. exact normalized match
// 2. unnegated substring match (normalized or space-compacted)
// 3. optional Levenshtein distance <= 1 for normalized needles >= 4 runes
// (avoiding high-risk negation inversions such as "use" vs "don't use",
// "agree" vs "disagree", or "同意" vs "不同意")
func MatchPhrase(haystack, needle string, fuzzy bool) bool {
hn := NormalizeText(haystack)
nn := NormalizeText(needle)
if nn == "" || hn == "" {
return false
}
hc := CompactText(haystack)
nc := CompactText(needle)
needleNeg := startsWithNegation(nc)
if hn == nn {
return true
}
if hasUnnegatedMatch(hn, nn, needleNeg) {
return true
}
if nc != "" && hasUnnegatedMatch(hc, nc, needleNeg) {
return true
}
// If every exact occurrence of needle in haystack was negated (e.g. "不使用" vs "使用"),
// do not let fuzzy matching bypass the negation guard.
if !needleNeg && nc != "" && strings.Contains(hc, nc) {
return false
}
if !fuzzy {
return false
}
nr := []rune(nc)
minFuzzy := 4
if isPureASCIIWord(nc) {
// Short pure-ASCII needles (e.g. "siri", "skip", "agree") collide easily
// with unrelated 3-5 char sliding substrings at Levenshtein <= 1.
minFuzzy = 6
}
if len(nr) < minFuzzy {
return false
}
hr := []rune(hc)
if len(hr) < len(nr)-1 {
return false
}
for start := 0; start < len(hr); start++ {
if !needleNeg && isPrecededByNegation(string(hr[:start])) {
continue
}
for _, span := range []int{len(nr) - 1, len(nr), len(nr) + 1} {
if span <= 0 || start+span > len(hr) {
continue
}
cand := hr[start : start+span]
if !needleNeg && startsWithNegation(string(cand)) {
continue
}
if levenshtein(cand, nr) <= 1 {
return true
}
}
}
return false
}
var (
cjkNegPrefixes = []string{"不", "未", "非", "别"}
latinNegPrefixes = []string{"don't", "dont", "not", "no", "dis"}
)
func startsWithNegation(compact string) bool {
for _, p := range cjkNegPrefixes {
if strings.HasPrefix(compact, p) {
return true
}
}
for _, p := range latinNegPrefixes {
if strings.HasPrefix(compact, p) {
return true
}
}
return false
}
func isASCIILetter(b byte) bool {
return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')
}
// isPrecededByNegation reports whether prefix immediately ends with a negation
// token that would invert a following positive phrase.
func isPrecededByNegation(prefix string) bool {
trimmed := strings.TrimRight(prefix, " ")
if trimmed == "" {
return false
}
for _, p := range cjkNegPrefixes {
if strings.HasSuffix(trimmed, p) {
return true
}
}
for _, p := range latinNegPrefixes {
if !strings.HasSuffix(trimmed, p) {
continue
}
// Require a word boundary before Latin negation prefixes when spaces are
// present (or start of string) so words like "marino" do not look like "no".
before := len(trimmed) - len(p)
if before == 0 || !isASCIILetter(trimmed[before-1]) {
return true
}
// Also catch joined compact Latin forms like "cannot" + "agree" or "didn't" + "use".
if p == "not" && strings.HasSuffix(trimmed, "cannot") {
return true
}
}
return false
}
func hasUnnegatedMatch(haystack, needle string, needleNeg bool) bool {
if needle == "" {
return false
}
offset := 0
for {
idx := strings.Index(haystack[offset:], needle)
if idx < 0 {
return false
}
pos := offset + idx
if needleNeg || !isPrecededByNegation(haystack[:pos]) {
// For pure Latin needles in spaced text, reject mid-word suffixes like
// "disagree" matching "agree" even if preceded by another prefix.
if isASCIILetter(needle[0]) && pos > 0 && isASCIILetter(haystack[pos-1]) && strings.Contains(haystack, " ") {
offset = pos + 1
continue
}
return true
}
offset = pos + 1
}
}
func levenshtein(a, b []rune) int {
if len(a) == 0 {
return len(b)
}
if len(b) == 0 {
return len(a)
}
prev := make([]int, len(b)+1)
cur := make([]int, len(b)+1)
for j := range prev {
prev[j] = j
}
for i := 1; i <= len(a); i++ {
cur[0] = i
for j := 1; j <= len(b); j++ {
cost := 0
if a[i-1] != b[j-1] {
cost = 1
}
m := prev[j] + 1
if cur[j-1]+1 < m {
m = cur[j-1] + 1
}
if prev[j-1]+cost < m {
m = prev[j-1] + cost
}
cur[j] = m
}
prev, cur = cur, prev
}
return prev[len(b)]
}
type scoredHit struct {
line ocr.Line
pt image.Point
tier int // 0 = exact whole line, 1 = short button/action line, 2 = sentence/prose line
wordCount int
extraLen int
centerY int
}
func betterScoredHit(a, b scoredHit) bool {
if a.tier != b.tier {
return a.tier < b.tier
}
if a.wordCount != b.wordCount {
return a.wordCount < b.wordCount
}
if a.extraLen != b.extraLen {
return a.extraLen < b.extraLen
}
// Dialog buttons sit below explanatory body prose inside modal/body ROIs.
return a.centerY > b.centerY
}
// FindHit locates the best matching word or line rectangle among OCR lines for
// any candidate phrase and returns its clickable center point.
func FindHit(lines []ocr.Line, candidates []string, fuzzy bool) (ocr.Line, image.Point, bool) {
// Pass 0: exact whole-line normalized match (isolated buttons such as "Skip",
// "Don't Use", "Set Up Later", "跳过" beat any occurrence inside body prose).
for _, cand := range candidates {
wantNorm := NormalizeText(cand)
if wantNorm == "" {
continue
}
var (
best scoredHit
found bool
)
for _, ln := range lines {
if ln.Rect.Empty() || NormalizeText(ln.Text) != wantNorm {
continue
}
pt := rectCenter(ln.Rect)
h := scoredHit{line: ln, pt: pt, tier: 0, wordCount: len(ln.Words), centerY: pt.Y}
if !found || betterScoredHit(h, best) {
best = h
found = true
}
}
if found {
return best.line, best.pt, true
}
}
// Pass 1a: exact normalized word-level match (highest precision on dense bars
// such as menu_bar or "Disagree / Agree" action bars). Prefer short button
// rows over words embedded in multi-word prose sentences.
for _, cand := range candidates {
wantNorm := NormalizeText(cand)
if wantNorm == "" {
continue
}
needleNeg := startsWithNegation(CompactText(cand))
var (
best scoredHit
found bool
)
for _, ln := range lines {
lineWordCount := len(ln.Words)
tier := 2
if NormalizeText(ln.Text) == wantNorm {
tier = 0
} else if lineWordCount <= 3 {
tier = 1
}
for idx, w := range ln.Words {
if w.Rect.Empty() {
continue
}
if NormalizeText(w.Text) == wantNorm {
if !needleNeg && idx > 0 && isPrecededByNegation(CompactText(ln.Words[idx-1].Text)) {
continue
}
pt := rectCenter(w.Rect)
h := scoredHit{
line: ocr.Line{Text: w.Text, Rect: w.Rect},
pt: pt,
tier: tier,
wordCount: lineWordCount,
extraLen: len([]rune(CompactText(ln.Text))) - len([]rune(CompactText(cand))),
centerY: pt.Y,
}
if h.extraLen < 0 {
h.extraLen = 0
}
if !found || betterScoredHit(h, best) {
best = h
found = true
}
}
}
}
if found {
return best.line, best.pt, true
}
}
// Pass 1b: unnegated substring word-level match (preferring short/lower rows).
for _, cand := range candidates {
wantCompact := CompactText(cand)
needleNeg := startsWithNegation(wantCompact)
var (
best scoredHit
found bool
)
for _, ln := range lines {
lineWordCount := len(ln.Words)
tier := 2
if lineWordCount <= 3 {
tier = 1
}
for idx, w := range ln.Words {
if MatchPhrase(w.Text, cand, false) && !w.Rect.Empty() {
if !needleNeg && idx > 0 && isPrecededByNegation(CompactText(ln.Words[idx-1].Text)) {
continue
}
pt := rectCenter(w.Rect)
extra := len([]rune(CompactText(ln.Text))) - len([]rune(wantCompact))
if extra < 0 {
extra = 0
}
h := scoredHit{
line: ocr.Line{Text: w.Text, Rect: w.Rect},
pt: pt,
tier: tier,
wordCount: lineWordCount,
extraLen: extra,
centerY: pt.Y,
}
if !found || betterScoredHit(h, best) {
best = h
found = true
}
}
}
}
if found {
return best.line, best.pt, true
}
}
// Pass 2: exact/substring line-level match (multi-word phrases like "Set Up Later" or "实用工具"),
// ranking standalone/short button lines ahead of long explanatory sentences.
for _, cand := range candidates {
wantNorm := NormalizeText(cand)
wantCompact := CompactText(cand)
var (
best scoredHit
found bool
)
for _, ln := range lines {
if !MatchPhrase(ln.Text, cand, false) || ln.Rect.Empty() {
continue
}
r := ln.Rect
if subR, ok := locatePhraseSubRect(ln, cand, false); ok {
r = subR
}
pt := rectCenter(r)
extra := len([]rune(CompactText(ln.Text))) - len([]rune(wantCompact))
if extra < 0 {
extra = 0
}
tier := 2
if NormalizeText(ln.Text) == wantNorm {
tier = 0
} else if extra <= 6 && len(ln.Words) <= 4 {
tier = 1
}
h := scoredHit{
line: ocr.Line{Text: ln.Text, Rect: r},
pt: pt,
tier: tier,
wordCount: len(ln.Words),
extraLen: extra,
centerY: pt.Y,
}
if !found || betterScoredHit(h, best) {
best = h
found = true
}
}
if found {
return best.line, best.pt, true
}
}
if !fuzzy {
return ocr.Line{}, image.Point{}, false
}
// Pass 3: fuzzy word/line match.
for _, cand := range candidates {
wantCompact := CompactText(cand)
var (
best scoredHit
found bool
)
for _, ln := range lines {
if !MatchPhrase(ln.Text, cand, true) || ln.Rect.Empty() {
continue
}
r := ln.Rect
if subR, ok := locatePhraseSubRect(ln, cand, true); ok {
r = subR
}
pt := rectCenter(r)
extra := len([]rune(CompactText(ln.Text))) - len([]rune(wantCompact))
if extra < 0 {
extra = 0
}
tier := 2
if extra <= 4 && len(ln.Words) <= 4 {
tier = 1
}
h := scoredHit{
line: ocr.Line{Text: ln.Text, Rect: r},
pt: pt,
tier: tier,
wordCount: len(ln.Words),
extraLen: extra,
centerY: pt.Y,
}
if !found || betterScoredHit(h, best) {
best = h
found = true
}
}
if found {
return best.line, best.pt, true
}
}
return ocr.Line{}, image.Point{}, false
}
func locatePhraseSubRect(ln ocr.Line, cand string, fuzzy bool) (image.Rectangle, bool) {
if len(ln.Words) == 0 {
return image.Rectangle{}, false
}
wantCompact := CompactText(cand)
needleNeg := startsWithNegation(wantCompact)
var (
bestRect image.Rectangle
found bool
bestExact bool
bestExtra int
bestSpan int
bestWidth int
)
for i := 0; i < len(ln.Words); i++ {
if !needleNeg && i > 0 && isPrecededByNegation(CompactText(ln.Words[i-1].Text)) {
continue
}
var joined strings.Builder
var rect image.Rectangle
for j := i; j < len(ln.Words) && j < i+10; j++ {
if j > i {
joined.WriteByte(' ')
}
joined.WriteString(ln.Words[j].Text)
if rect.Empty() {
rect = ln.Words[j].Rect
} else {
rect = rect.Union(ln.Words[j].Rect)
}
txt := joined.String()
if !MatchPhrase(txt, cand, fuzzy) {
continue
}
gotCompact := CompactText(txt)
exact := wantCompact != "" && gotCompact == wantCompact
extra := len([]rune(gotCompact)) - len([]rune(wantCompact))
if extra < 0 {
extra = -extra
}
span := j - i + 1
width := rect.Dx()
better := !found ||
(exact && !bestExact) ||
(exact == bestExact && extra < bestExtra) ||
(exact == bestExact && extra == bestExtra && span < bestSpan) ||
(exact == bestExact && extra == bestExtra && span == bestSpan && width < bestWidth)
if better {
bestRect = rect
found = true
bestExact = exact
bestExtra = extra
bestSpan = span
bestWidth = width
}
}
}
return bestRect, found
}
func rectCenter(r image.Rectangle) image.Point {
return image.Pt((r.Min.X+r.Max.X)/2, (r.Min.Y+r.Max.Y)/2)
}