Skip to content

v5 F3–F5: headless OCR, output services, triggers (F6 shelved) - #699

Merged
TheJoeFin merged 23 commits into
devfrom
v5/f3-6
Nov 11, 2026
Merged

TheJoeFin merged 23 commits into
devfrom
v5/f3-6

Conversation

@TheJoeFin

@TheJoeFin TheJoeFin commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

Implements v5 foundation phases F3, F4 and F5, and the first two steps of F6, which is shelved until a consumer needs it. Each phase's work plan is in docs/v5/. Each step is its own commit, and every commit passed the build and test gates.

F3: headless OCR service

  • LoadBitmapFromFile no longer uses WPF: it reads the file into memory and decodes with GDI+, so the file isn't locked. EXIF fixtures pin the old behavior first. Mirrored EXIF orientations are still not flipped, as before.
  • Engine dispatch moved to Text-Grab.Core.Windows as OcrEngineUtilities, with OcrOptions? threaded through. The app half keeps the OcrSourceUtilities name, because most call sites point at it.
  • Every Windows OCR call scales through a WPF TransformedBitmap. That now goes through a new seam, BitmapScalingAccess. The app registers its unchanged WPF scaler, so app grabs scale exactly as before; a headless host gets GDI+ bicubic. A test shows both give the engine identical text on three fixtures.
  • IOcrService (Core) and OcrService (Core.Windows) are registered in AppServices. A test with no WPF and no app assembly OCRs fixtures by path and by stream and gets the same text the app produces.

F4: output services

  • IClipboardService, ITextFileWriter, IToastService and IHttpPostService are declared in Core and registered in AppServices, with tests for each.
  • WinRtClipboardService: a caller on an STA thread (the UI thread included) runs inline. Other callers go through UiThreadAccess when it is configured, falling back if the post is dropped, or else a dedicated STA thread. Busy-clipboard retries run synchronously, with WPF Clipboard's own budget.
  • HttpPostService accepts http and https only, times out after 30 s, caps the response at 64 KB, and logs nothing. It has its own non-redirecting client because the shared one must keep following redirects for the Tesseract downloader. It follows only same-host 307/308 redirects itself.
  • ToastService shows toasts through the same Toolkit plumbing the app already uses, and carries no click argument, so clicking existing toasts behaves as before.
  • OutputUtilities.HandleTextFromOcr now writes the clipboard through IClipboardService. The write finishes before ShouldShutDown can exit the app.

F5: trigger infrastructure

  • ITriggerSource, TriggerPayload and TriggerKind in Core.
  • FolderWatcherService: a debounced FileSystemWatcher on an injectable TimeProvider. A rename onto a matching name counts as created, which is how browsers finish downloads.
  • HotkeyActionRouter replaces the hotkey switch. The mapping was pinned by a test against the old switch first, and the same table now passes against the router.
  • ClipboardMonitorService subscribes to WinRT ContentChanged once for the whole app:
    • ContentChanged forwards every change. The Edit Text Window listens here, so its clipboard watcher behaves exactly as before, including collecting grabs.
    • Triggered skips Text Grab's own writes, which are marked with SuppressSelf. The app's IClipboardService is a decorator that marks each write.

F6: shelved

Round-trip characterization tests for HistoryFileUtilities landed (temp folder only, never real history). Building the store itself is shelved. Its plan wants the lists moved out of HistoryService while HistoryServiceTests, which set those private fields by reflection, stay unchanged. The details are recorded in docs/v5/F6-History-Store.md.

Plan corrections

Each phase file's "current state" section now records what turned out to be wrong:

  • F3: the "no WPF" dispatch actually scaled through WPF.
  • F4: there's no clipboard retry pattern to copy, DesktopNotificationManagerCompat isn't the live toast code, and the shared client auto-redirects.
  • F5: not all hotkey cases call TrayActions, and the Edit Text Window already appends Text Grab's own clipboard writes.
  • F6: the cached-bitmap trap is backwards.

docs/Core-Split-Plan.md §7 and §10 are updated for F3.

Tests

Suite Before (dev) After
Tests.Core 997 passed 1030 passed
Tests.Core.Windows 240 (4 skipped) 301 (4 skipped), 0 failed
Tests 893 (3 skipped) 950 (3 skipped), 0 failed

The build reports the same 8 warnings as dev. The folder-watcher tests touch the real file system; they passed 8 runs in a row.

Needs checking by hand

  • MSIX: Text-Grab.Core.Windows now references Microsoft.Toolkit.Uwp.Notifications 7.1.3, the same version the app already ships. Build the wapproj in Visual Studio.
  • A fullscreen grab lands on the clipboard, including in standalone mode where the app exits right after.
  • The grab toast still appears, and clicking it opens the Edit Text Window with the text.
  • Grab Frame grab, a Tesseract language, HDR if available, a barcode image.
  • A rotated phone photo dropped on the Edit Text Window, and "Read folder of images" on mixed orientations.
  • Every global hotkey opens its window (the Settings hotkey still does nothing, as before).
  • The Edit Text Window's clipboard watcher behaves as before.

🤖 Generated with Claude Code

TheJoeFin and others added 23 commits November 9, 2026 21:22
F3 step 1. Six JPEG fixtures store the same 64x32 four-colour image
with EXIF orientation 1, 2, 3, 5, 6 and 8. ExifOrientationTests
pixel-checks each through the current WPF LoadBitmapFromFile path and
pins that it returns 32bpp ARGB, which the downstream WPF scaler needs.

Orientations 2 and 5 pin a quirk the plan did not mention: the
loader's RotateImage switch acts only on the three pure rotations, so
mirrored orientations are never flipped and EXIF 5 and 7 are not even
rotated. The rewrite must keep that.

LoadBitmapFromFile goes from private to internal so the test can reach
it; nothing else in product code changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F3 step 2. LoadBitmapFromFile was the one WPF dependency in the file
OCR path. It now reads the file into memory, decodes with GDI+ and
copies through new Bitmap(Image), which detaches the bitmap from the
stream and normalizes it to 32bpp ARGB as BitmapImageToBitmap did.

Rotation keeps the old semantics: only Rotate90/180/270FlipNone are
applied, matching the RotateImage switch, so mirrored EXIF orientations
are still ignored. The plan's sketch, bitmap.RotateFlip(type), would
have started flipping EXIF 2/4/5/7 images; that is a behaviour change
the plan did not ask for.

ExifOrientationTests passes unchanged, plus a new test that the file is
not locked while the returned bitmap is alive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F3 step 3. The plan listed the dispatch members as WPF-free; four of
them call ImageMethods.ScaleBitmapUniform, a WPF TransformedBitmap
scaler. GetTextFromAbsoluteRectAsync and GetOcrResultFromRegionAsync
are app-bound through the WPF Rect, UIAutomationUtilities and the
HistoryService-caching screen capture, and OcrAbsoluteFilePathAsync
carries a PDF branch. Records the corrected destinations, the seam
chosen for the scaler, and the 21-vs-16 reference count that keeps
the OcrSourceUtilities name on the app half.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F3 steps 4 and 5. The WPF-free half of OcrSourceUtilities - bitmap,
SoftwareBitmap, stream and image-file OCR across the Windows, Windows
AI, Tesseract and description engines, plus barcodes and the ideal
scale factor - moves to Text-Grab.Core.Windows/Utilities/
OcrEngineUtilities.cs. The app half keeps the OcrSourceUtilities name:
21 of the 37 external references point at it, as the census in the F3
plan records.

What had to change, and why:
- Every Windows-OCR call scales through ImageMethods.ScaleBitmapUniform,
  a WPF TransformedBitmap. That becomes BitmapScalingAccess, a fifth
  delegate-resolver seam. The app registers the unchanged WPF scaler
  from a module initializer, so app grabs scale exactly as before; a
  host with nothing registered gets a GDI+ bicubic default. A Tests
  theory pins that the two give the engine identical text on three
  OCR fixtures.
- DefaultSettings reads become SettingsAccess.Current, and OcrOptions?
  threads through every moved method that shapes text, per F2. Null
  snapshots the settings, which is the old behaviour.
- OcrAbsoluteFilePathAsync has a PDF branch, so its image path moved as
  OcrImageFileAsync and it stays as the PDF-aware wrapper; its callers
  are unchanged. OcrFile stays app-side whole: both of its special
  branches, PDF and GrabTemplateExecutor, are app-bound, and its plain
  path already runs through the moved method (step 5).
- GetOcrResultFromRegionAsync stays app-side, because its capture caches
  into HistoryService. Its body after the capture was identical to
  GetOcrResultFromBitmapAsync, so it is now a two-line wrapper over it.
- IsUiAutomationLanguage, GetCompatibleOcrLanguage and LoadBitmapFromFile
  are internal in Core.Windows, which already grants InternalsVisibleTo
  to the app and tests.

16 call sites change only their class qualifier. GrabTemplateExecutor
did not move.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F3 step 6. IOcrService (Text-Grab.Core, Text_Grab.Core.Abstractions)
OCRs a file, an encoded image stream or a virtual-desktop rectangle
and returns text. OcrService (Text-Grab.Core.Windows) is a stateless
layer over OcrEngineUtilities:

- Language comes from OcrOptions.LanguageTag. An empty tag, or the
  persisted LastUsedLang, resolves through LanguageUtilities.
  GetOCRLanguage, exactly as text-grab://grab-text does. Any other
  tag is matched against every capture language, Tesseract included,
  and otherwise taken as a Windows OCR tag.
- Files apply EXIF rotation through LoadBitmapFromFile. PDFs throw
  NotSupportedException, because PdfDocumentRenderer is app-side.
- Streams are copied to memory first, so non-seekable streams work,
  and decode as the pasted-image path does.
- Screen regions truncate like ShapeExtensions.AsRectangle, capture
  and pad like GetRegionOfScreenAsBitmap, and skip its history cache.
- Cancellation is checked between stages.

Registered in AppServices as a singleton.

OcrServiceTests runs in Tests.Core.Windows, with no WPF and no app
assembly. It OCRs font_sample, FontTest and the paragraph fixture by
path, and font_sample by seekable and non-seekable stream, and gets
exactly the text Tests/OcrSourceTests asserts for the app. It also
covers the option override, PDF rejection, missing files, cancellation
and empty regions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F3 step 7. Rewrites the OcrSourceUtilities row of the deferred ledger:
the GDI+/WIC rewrite and the engine dispatch it was waiting on have
landed, and what remains is app-bound for named reasons. Adds
BitmapScalingAccess to the section 10 seam table, noting that it lives
in Core.Windows and falls back instead of throwing, and corrects the
residue bullet that still said LoadBitmapFromFile needed a rewrite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F4 step 1. IClipboardService, ITextFileWriter, IToastService and
IHttpPostService, plus the HttpPostResult record, in
Text_Grab.Core.Abstractions. BCL types only, so Core takes no Windows
reference. The XML docs fix the contracts the implementations follow:
plain text only, UTF-8 files with missing directories created, toasts
that never throw, and POSTs restricted to http and https.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F4 step 2. HttpPostService (Text-Grab.Core) POSTs UTF-8 text over an
injected HttpClient. It accepts only absolute http and https URIs,
times out after 30 s by default (TimeoutException, kept distinct from
the caller's own cancellation), reads at most 64 KB of the response
without splitting a character, and logs nothing.

One deviation from the plan. "No automatic redirect to a different
host" cannot be enforced on the shared HttpClient F1 registered: its
handler follows redirects before the service sees them, and the
Tesseract downloader relies on that. So the service expects a client
that does not redirect (CreateClient builds one) and follows redirects
itself, only for 307/308 on the same host and never from https to
http. 301/302/303 would turn the POST into a GET, so they are returned
to the caller rather than followed.

Tests.Core covers success, non-2xx, empty body, timeout, cancellation,
rejected schemes, the body cap, headers, and each redirect rule,
against a fake handler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F4 step 3. TextFileWriter (Text-Grab.Core.Windows) writes or appends
UTF-8 without a BOM, the encoding FileUtilities.SaveTextFile already
uses, and creates a missing parent directory. It returns false when
the file system refuses the write, rejects non-absolute paths and
honours cancellation. It does not go through SaveTextFile: that method
is for Text Grab's own folders, where packaged and unpackaged storage
differ, and it cannot append.

Tests.Core.Windows covers create, overwrite, append, missing
directories, a refused write, relative paths and cancellation, in a
temp folder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F4 step 4. WinRtClipboardService (Text-Grab.Core.Windows) reads and
writes plain text through Windows.ApplicationModel.DataTransfer.
Clipboard and flushes writes, so the text outlives the process as WPF
Clipboard.SetDataObject(text, copy: true) did.

Where the calls run:
- An STA caller, the app's UI thread included, runs inline. A write
  from the UI thread therefore completes synchronously, so a caller
  that shuts the app down right after writing cannot lose it in the
  dispatcher queue.
- Other callers post through UiThreadAccess when it is configured.
  The app's poster silently drops work while Application.Current is
  null, so a post that has not started within a timeout is claimed
  back and run on the fallback thread. A claim flag guarantees it
  runs exactly once.
- Otherwise the calls run on a dedicated background STA thread owned
  by the service.

CLIPBRD_E_CANT_OPEN/EMPTY/SET/CLOSE are retried up to five times with
a growing delay. The plan said ClipboardUtilities already showed a
retry pattern; it has none, so this is new.

Tests.Core.Windows: a real round trip on the service's STA thread
with nothing configured, plus fake-backend tests for each rule above,
the retry limits, non-retryable failures and cancellation. Tests (WPF):
an off-thread caller marshalled onto a real dispatcher, and a real
round trip on the UI thread that WPF's Clipboard.GetText reads back.
The real-clipboard tests restore the previous text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F4 step 5. ToastService (Text-Grab.Core.Windows) shows a title and
body through ToastContentBuilder.Show(), so it reuses the same
ToastNotificationManagerCompat AUMID and COM-activator registration as
NotificationUtilities. It truncates text with the grab toast's
150-character rule, without splitting a surrogate pair, and swallows
display failures as IToastService promises.

The toast carries no activation argument. App.LaunchFromToast and
TextGrabNotificationActivator both ignore a click without one, so
clicking an existing toast behaves exactly as before.

The plan pointed at DesktopNotificationManagerCompat, but nothing
calls its registration or notifier methods; the live plumbing is
Microsoft.Toolkit.Uwp.Notifications, which only the app referenced.
Core.Windows now references the same 7.1.3. Its net5.0-windows asset
references no WPF assembly, and TierBoundaryTests passes. The app
keeps its own reference because it calls these types directly.

Tests check the composed toast XML only. Calling Show() from an
unpackaged test host would register the runner's AUMID and display a
real toast.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F4 step 6. IClipboardService, ITextFileWriter and IToastService are
singletons over their Core.Windows implementations. IHttpPostService
is a singleton over its own HttpPostService.CreateClient() client,
not the shared HttpClient: that one follows redirects, which the
Tesseract downloader needs and HttpPostService must not delegate.
AppServicesTests resolves each and checks it is one instance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F4 step 7. OutputUtilities.HandleTextFromOcr, the one clipboard write
every grab goes through, now calls the registered IClipboardService
instead of WPF Clipboard.SetDataObject(text, copy: true). No other
clipboard call site changes.

HandleTextFromOcr calls WindowUtilities.ShouldShutDown right after the
write, and that can exit the app. A write that was still queued or
waiting to retry would be lost. Two things prevent it:
- Callers are on the UI thread, which is STA, so the service runs the
  write inline.
- WinRtClipboardService now retries on the clipboard thread itself,
  synchronously, with WPF Clipboard's own budget: 10 attempts, 100 ms
  apart, where the step 4 version used async backoff. A busy
  clipboard therefore delays the return exactly as the WPF write did,
  instead of leaving a retry pending. A new test pins that an STA
  caller's retries finish before the call returns.

Failures are still swallowed, as they were around the WPF call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClipboardUtilities has no write and no retry pattern to copy; WPF's
Clipboard retries internally instead. DesktopNotificationManagerCompat
is not the live toast plumbing; the Toolkit notifications package is.
The shared HttpClient follows redirects, so the POST service has its
own client.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F5 step 1. The shared shape for clipboard, folder and hotkey triggers,
in Text_Grab.Core.Abstractions. As the plan asks, the interface
documents that Triggered may be raised on a background thread and that
a file trigger can arrive while the writer still holds the file.
Nothing here references workflows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F5 step 2. FolderWatcherService (Text-Grab.Core) wraps the BCL
FileSystemWatcher behind ITriggerSource:

- Events coalesce per path. Each new event restarts the path's quiet
  period on an injected TimeProvider, and one TriggerPayload is raised
  when the period ends. The first kind seen wins, so a new file is
  FileCreated even though Changed events followed it.
- A rename onto a matching name is FileCreated, which is how browsers
  finish downloads. Deletions and directories are not reported.
- The watcher's Error event (buffer overflow) raises nothing and swaps
  in a fresh watcher. Events from a stopped or replaced watcher are
  ignored. Stop drops anything still pending.

Tests.Core runs each case on a real temp folder with a fake clock: a
single write, a burst on one file, two files, an existing file
changed, the filter, a rename, Stop, a watcher error, and constructor
and Start validation. ManualTimeProvider is a small hand-written fake,
used instead of adding Microsoft.Extensions.TimeProvider.Testing. All
11 passed in 8 consecutive runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F5 step 3, characterization. A switch statement cannot be inspected,
so the switch in HotKeyManager_HotKeyPressed is restated unchanged as
GetHotkeyHandler, a switch expression returning the delegate the
handler then runs on the UI thread exactly as before. The Flyout
case's lambda becomes the named ToggleFlyoutFromHotkey so the test can
identify it.

HotkeyDispatchTests lists all 11 ShortcutKeyActions values and the
method each maps to, and checks the list is complete. Contrary to the
plan, not all 11 call a TrayActions static: eight do, Flyout calls
TrayFlyoutController.Toggle, and None and Settings do nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F5 step 3. HotkeyActionRouter (app-side, because ShortcutKeyActions is
an app type) maps an action to a handler. TryInvoke runs the handler
on the UI thread with the same synchronous Dispatcher.Invoke the old
switch used, and returns false for an unregistered action.
CreateWithTrayActions registers the old switch case for case. The
container builds it on first resolve, so App startup order is
untouched.

HotKeyManager_HotKeyPressed keeps its settings check and key matching,
then calls router.TryInvoke. The switch and RunOnUiThread are gone.
HotKeyManager and shortcut storage are unchanged.

The characterization table from the previous commit is unchanged and
now passes against the router's registrations, both freshly built and
as resolved from the container. New tests cover TryInvoke, an
unregistered action, replacing a handler and null rejection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F5 step 4. ClipboardMonitorService (app-side, a container singleton)
subscribes to WinRT Clipboard.ContentChanged once and exposes two
events:

- ContentChanged forwards every change on WinRT's own thread. The
  Edit Text Window's clipboard watcher now subscribes here instead of
  to WinRT directly, and calls Start from Window_Loaded on the UI
  thread. It therefore sees exactly the changes it saw before, its own
  writes and grabs included. IsAccessingClipboard stays as its guard.
- Triggered, the ITriggerSource side, carries the clipboard text and
  skips changes marked with SuppressSelf(expectedText). A suppression
  covers the scope plus a one-second window for the late
  notification. It compares content, so a different copy made
  meanwhile still triggers. It is not consumed on first match, because
  SetContent and Flush can notify twice for one write. Unreadable
  content inside a live suppression is skipped, the choice that cannot
  loop. The clipboard is read only when Triggered has a listener.

The app's IClipboardService is now SelfSuppressingClipboardService:
WinRtClipboardService with each write wrapped in SuppressSelf. The
monitor is app-side, so the wrapping cannot live in Core.Windows. A
UI-thread write still completes synchronously, which F4's shutdown
guarantee relies on.

Why the Edit Text Window does not take the suppressed stream: it would
stop collecting grabs, which reach the clipboard through Text Grab,
while its own WPF copies, which bypass IClipboardService, would still
arrive.

Tests use a fake change source, reader and clock, never the real
event. A throwaway, uncommitted probe of the real event showed it is
raised on the WPF UI thread it was subscribed on, and never on an
unpumped MTA thread; the class doc records this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The hotkey switch's cases are not all TrayActions calls, and its enum
is app-side. The Edit Text Window's clipboard watcher already appends
Text Grab's own writes, so one of the plan's manual checks describes
behavior the app does not have. Also records which thread the WinRT
clipboard event is raised on, which a headless consumer depends on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
F6 step 1, characterization only; no product code changes.
HistoryFileRoundTripTests (Tests.Core.Windows) runs HistoryFileUtilities
against a temporary automation-profile root, in a non-parallel
collection because that override is process-global. It never touches
the real history folder.

It covers:
- Every persisted field survives a write and reload, and writes store
  items oldest first.
- The text cap keeps the newest 100. The image file cap is the grab cap
  plus the PDF cap, and visual retention trims grabs and PDFs
  independently.
- A missing file or an empty array loads empty with no rewrite.
- One malformed entry is skipped, the rest recovered and a rewrite
  requested. An unknown LanguageKind falls back to Global.
- A file that is not JSON at all, an object, or truncated JSON loads
  empty and requests a rewrite, so the next write replaces it. That is
  existing behavior, pinned rather than changed.
- ID normalization, word-border sidecars, orphan cleanup and artifact
  deletion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Status rows: F3, F4 and F5 are done. F6 is in progress: its
characterization tests and state census are complete, and step 3 is
held for an owner decision.

The F6 phase file now records why:
- Its cached-bitmap trap is backwards: the save timer disposes the
  bitmap, not the idle timer.
- Moving the lists out of HistoryService cannot coexist with
  "HistoryServiceTests unchanged", because five of those tests set
  exactly those private fields by reflection.
- Every piece of history state is UI-thread-affine and handed out as
  live, mutable objects, so a background-timer write needs a locking
  or marshalling decision on user data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The owner chose to stop F6 after its characterization tests (step 1,
fe8a24b) and state census (step 2) rather than build the store now.
The phase file already said to do it only when a consumer needs one.
It keeps the recorded corrections and the blocker, so whoever resumes
it starts from them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@TheJoeFin
TheJoeFin merged commit b8adc26 into dev Nov 11, 2026
1 check passed
@TheJoeFin
TheJoeFin deleted the v5/f3-6 branch November 11, 2026 05:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant