Repository Public License
1<!--2ORIX Scan3File: docs/architecture/overview.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->78# Architecture overview910ORIX Scan is a native SwiftUI application for iPhone and iPad. All document work (rendering, text recognition, PDF11generation, storage) is done by a Swift package that has no user interface and no networking code, so the same engines are12compiled into the app and exercised on a Mac by `swift test`.1314## Layers1516| Layer | Location | Role |17|---|---|---|18| App target `ORIXScan` | `App/Sources/` | SwiftUI screens, application state, platform glue (VisionKit scanner, pickers, share sheet, printing, Spotlight, App Intents, App Lock) |19| `ORIXKit` library | `Packages/ORIXKit/Sources/ORIXKit/` | On-device engines: model, imaging, OCR, PDF, storage, workflows |20| `ORIXDesign` library | `Packages/ORIXKit/Sources/ORIXDesign/` | Design tokens, components and haptics shared by ORIX apps |2122The package (`Packages/ORIXKit/Package.swift`) declares two products, `ORIXKit` and `ORIXDesign`, for iOS 18 and macOS 15, in23Swift 6 language mode. The two targets do not depend on each other and neither has an external dependency. The app target is24described by `project.yml` (XcodeGen) and depends on both products.2526```mermaid27flowchart TD28 subgraph App["App target (App/Sources)"]29 UI["SwiftUI screens<br/>Home, Library, Document, Actions, Settings"]30 Model["AppModel + Router + AppSettings"]31 Platform["Platform glue<br/>ScannerView, Intents, Spotlight, AppLock, ShareSheet"]32 end33 subgraph Kit["ORIXKit (no UI, no network)"]34 Processor["DocumentProcessor"]35 Store["DocumentStore (actor)"]36 Renderer["PageRenderer"]37 OCR["OCREngine"]38 PDF["SearchablePDFBuilder + PDFTools"]39 Engine["WorkflowEngine"]40 Index["LibraryIndex (SwiftData)"]41 end42 Design["ORIXDesign<br/>tokens, components, haptics"]43 Apple["Apple frameworks<br/>Vision, VisionKit, Core Image, PDFKit, Core Graphics, SwiftData"]44 Disk[("Application Support/ORIXScan")]4546 UI --> Model47 UI --> Design48 Platform --> Model49 Model --> Processor50 Model --> Index51 Model --> Engine52 Engine --> Processor53 Processor --> Store54 Processor --> Renderer55 Processor --> OCR56 Processor --> PDF57 Index --> Processor58 Store --> Disk59 Index --> Disk60 Renderer --> Apple61 OCR --> Apple62 PDF --> Apple63```6465## Module map6667### `ORIXKit`6869| File | Main types | Responsibility |70|---|---|---|71| `Model/Geometry.swift` | `Quad` | Normalized quadrilateral (origin top-left) for crops and text boxes |72| `Model/Document.swift` | `DocumentManifest`, `PageRecord`, `PageSource`, `PageEdit`, `FilterMode`, `ExportPreset`, `ORIXError` | On-disk document model and non-destructive edit recipe |73| `Imaging/PageRenderer.swift` | `PageRenderer` | Core Image pipeline: perspective, straightening, rotation, filters, JPEG encoding, PDF page rasterization |74| `Imaging/DocumentDetector.swift` | `DocumentDetector` | Page outline detection in imported photos (Vision) |75| `Imaging/QualityAnalyzer.swift` | `QualityAnalyzer`, `QualityReport`, `QualityIssue` | Heuristic page-quality estimates |76| `OCR/OCREngine.swift` | `OCREngine` | Text recognition with `VNRecognizeTextRequest` |77| `OCR/OCRModel.swift` | `OCRPage`, `OCRLine`, `OCRWord`, `OCROptions`, `RecognitionMode` | Recognized-text model stored per page |78| `OCR/ReadingOrder.swift` | `ReadingOrder` | Recursive XY-cut ordering |79| `OCR/TableExtractor.swift` | `TableExtractor`, `ExtractedTable` | Geometry-based table reconstruction, CSV |80| `OCR/TextMetrics.swift` | `TextMetrics` | Character and word error rates |81| `PDF/SearchablePDFBuilder.swift` | `SearchablePDFBuilder`, `PDFPageInput`, `PDFBuildOptions`, `PageSizeMode` | PDF writing with an invisible text layer |82| `PDF/PDFTools.swift` | `PDFTools`, `PDFInspection` | Opening, unlocking, inspecting and searching PDFs |83| `Storage/DocumentStore.swift` | `DocumentStore` | Files on disk, atomic manifests, staged drafts |84| `Storage/DocumentProcessor.swift` | `DocumentProcessor`, `ExportOptions`, `ExportResult` | Facade: render, edit, recognize, export |85| `Storage/Library.swift` | `DocumentRecord`, `FolderRecord`, `WorkflowRecord`, `Library`, `LibraryIndex` | SwiftData index and library operations |86| `Actions/Workflow.swift` | `Workflow`, `ActionStep`, `ActionKind` | ORIX Actions model and presets |87| `Actions/WorkflowEngine.swift` | `WorkflowEngine`, `WorkflowResult`, `StepOutcome` | Workflow execution |8889Details: [ocr-engine.md](ocr-engine.md), [pdf-engine.md](pdf-engine.md), [storage.md](storage.md), [workflows.md](workflows.md).9091### App target9293| File | Role |94|---|---|95| `Core/ORIXScanApp.swift` | `@main`, `Boot`, launch view, lock screen, privacy cover, keyboard commands |96| `Core/AppModel.swift` | `AppModel`: capture and import, edits, recognition tasks, library operations |97| `Core/Router.swift` | `Router`, `Route`, `AppSection`, `AppTab` |98| `Core/RootView.swift` | Adaptive root (tabs or sidebar), capture presentation, global alerts and overlays, drop import |99| `Core/AppSettings.swift` | `AppSettings` (UserDefaults) |100| `Core/Naming.swift` | User-facing names of engine values, `AlertInfo` |101| `Core/SharedViews.swift` | `PageThumbnail`, `DocumentCard`, `DocumentRow`, `ActivityOverlay`, `ToastView` |102| `Home/HomeView.swift` | First screen |103| `Library/LibraryView.swift` | Library, `FolderPicker`, `DocumentTransfer` |104| `Document/DocumentView.swift` | Document workspace, `MetadataSheet` |105| `Document/PageEditorView.swift` | `PageEditorView`, `CropEditorView`, `QualityDetailsView` |106| `Document/PageOrganizerView.swift` | `PageOrganizerView`, `SplitSheet` |107| `Document/DocumentTextView.swift` | Text, review and tables |108| `Document/ExportSheet.swift` | `ExportSheet`, `PDFPreviewView`, `PDFKitView` |109| `Capture/ScannerView.swift` | `VNDocumentCameraViewController` wrapper |110| `Actions/*.swift` | `ActionsView`, `WorkflowEditorView`, `WorkflowRunView`, `WorkflowLauncher`, `DocumentChooser` |111| `Settings/SettingsView.swift` | `SettingsView`, `LanguagePicker` |112| `Platform/Support.swift` | `ThumbnailCache`, `BackgroundWork`, `ShareSheet`, `Printer`, `Spotlight`, `AppLock` |113| `Platform/Intents.swift` | App Intents and `ORIXShortcuts` |114| `Debug/DemoContent.swift` | Debug builds only: isolated store and sample documents |115116## Data flow117118A document is a directory holding a `manifest.json`, the original captures and the recognized text (see119[storage.md](storage.md)). Nothing in the interface holds a document in memory as a whole:1201211. Views read `AppModel.manifests[id]` (an observable cache of `DocumentManifest`) and SwiftData records through `@Query`.1222. A change goes through an `AppModel` method, which calls `DocumentProcessor` or `DocumentStore`.1233. `AppModel.didChange(_:)` reloads the manifest, refreshes the SwiftData record with `LibraryIndex.refresh(_:)` and updates124 the Spotlight entry.125126Edits are recipes (`PageEdit`), never pixels: every render starts from the stored original, which is not modified.127128```mermaid129flowchart LR130 Scan["Scanner (VisionKit)"] --> In["Incoming items"]131 Photos["Photos picker"] --> In132 Files["Files, drag and drop, Open in"] --> In133 In --> Receive["AppModel.receive"]134 Receive --> Draft["DocumentStore draft in Staging/"]135 Draft --> Commit["commit: one directory move"]136 Commit --> Doc[("Documents/<uuid>")]137 Doc --> Rec["DocumentProcessor.recognize"]138 Rec --> OCRFile[("ocr/<page>.json")]139 Doc --> Export["DocumentProcessor.exportPDF"]140 OCRFile --> Export141 Export --> Builder["SearchablePDFBuilder"]142 Builder --> Out[("Exports/<uuid>/Title.pdf")]143 Out --> Share["Share, Preview, Print, Save to Files"]144 Doc --> Text["exportText / exportTables / exportImages"]145 Text --> Share146```147148## Concurrency model149150- **App target**: `project.yml` sets `SWIFT_DEFAULT_ACTOR_ISOLATION: MainActor` and `SWIFT_STRICT_CONCURRENCY: complete`.151 `AppModel`, `Router`, `AppSettings` and the views are main-actor isolated. Types that must run elsewhere are marked152 `nonisolated` (`IntentPipeline` in `Platform/Intents.swift`).153- **`DocumentStore`** is an `actor`: manifest reads and writes, draft creation and page file operations are serialized. Path154 helpers and `ensureSpace(for:)` are `nonisolated`.155- **`DocumentProcessor`** is a `final class` that is `Sendable`; it holds only immutable references (`store`, `renderer`,156 `ocr`). Its `async` methods run off the main actor. Its synchronous methods (`renderedImage`, `cachedPreviewURL`) are called157 from `Task.detached` in `ThumbnailCache`.158- **`PageRenderer`** is `@unchecked Sendable` around one `CIContext`; filters are created per call.159- **`OCREngine.recognize`** runs the Vision request on `DispatchQueue.global(qos: .userInitiated)` inside a checked160 continuation, with a task cancellation handler that cancels the `VNRequest`.161- **`LibraryIndex`** is `@MainActor` and owns the `ModelContainer` and its `mainContext`.162- Progress closures are `@Sendable`; the app hops back with `Task { @MainActor in … }`.163- Long operations started by the user that should survive a short trip to the background (`AppModel.startRecognition`,164 `WorkflowRunView.start`) hold a `BackgroundWork` assertion (`UIApplication.beginBackgroundTask`).165166## Error model167168Engines throw `ORIXError` (`Model/Document.swift`): `documentNotFound`, `pageNotFound`, `unreadableImage`, `unreadablePDF`,169`passwordRequired`, `wrongPassword`, `insufficientStorage`, `emptyDocument`, `exportFailed`, `recognitionFailed`, `cancelled`,170`corruptedManifest`.171172In the app, operations run through `AppModel.attempt(_:)`. Cancellation (`CancellationError`, `ORIXError.cancelled`) is173silent; any other error becomes an `AlertInfo` (`Core/Naming.swift`), which maps each case to a title and a message a person174can act on. `RootView` presents `AppModel.alert`. Messages never contain document content. `passwordRequired` and175`wrongPassword` are handled before that, by a password prompt loop in `AppModel` (`askPassword`).176177## Navigation178179`Router` holds both layouts' state:180181- compact width: `TabView` with three tabs (`AppTab.home`, `.library`, `.actions`), one `NavigationStack` path per tab;182- regular width: `NavigationSplitView` with a sidebar bound to `Router.section` (`AppSection`) and one detail stack183 (`detailPath`).184185`RootView` chooses the layout from `horizontalSizeClass` and keeps `Router.isRegular` in step. `Router.push(_:)` and186`Router.open(_:)` append to whichever stack is active, so features never know which layout they are in. Destinations are187declared once by the `routeDestinations()` modifier (`Route.document`, `.library`, `.workflow`, `.settings`).188`DocumentView` hides the tab bar so its bottom toolbar has the full width.189190## Capture flow1911921. A view calls `AppModel.request(_:for:)` with a `CaptureSource` (`scan`, `photos`, `files`) and a `CaptureDestination`193 (`newDocument`, `append`, `retake`, `workflow`). If the source is `scan` and `ScannerView.isAvailable` is false, the194 model shows an alert instead.1952. `RootView` observes `AppModel.capture` and presents the scanner (`fullScreenCover`), the Photos picker or the file importer.1963. The result is converted to `[Incoming]` (`.image(data:fileExtension:)` or `.pdf(url:)`) and passed to197 `AppModel.receive(_:from:for:)`.1984. `receive` stages a draft, adds every item, commits, optionally runs `DocumentProcessor.autoCrop` (imports only), refreshes199 the index, and then either opens the document and starts recognition, or starts a `WorkflowRun`.200201Files opened from other apps (`onOpenURL`), drops (`DropImport`) and the Files importer all end in202`AppModel.importFiles(_:for:)`, which calls the same `receive`.203