SPB Git

Repository Public License

overview.md 11.5 KB

# Architecture overview

ORIX Scan is a native SwiftUI application for iPhone and iPad. All document work (rendering, text recognition, PDF generation, storage) is done by a Swift package that has no user interface and no networking code, so the same engines are compiled into the app and exercised on a Mac by swift test.

# Layers

Layer Location Role
App target ORIXScan App/Sources/ SwiftUI screens, application state, platform glue (VisionKit scanner, pickers, share sheet, printing, Spotlight, App Intents, App Lock)
ORIXKit library Packages/ORIXKit/Sources/ORIXKit/ On-device engines: model, imaging, OCR, PDF, storage, workflows
ORIXDesign library Packages/ORIXKit/Sources/ORIXDesign/ Design tokens, components and haptics shared by ORIX apps

The package (Packages/ORIXKit/Package.swift) declares two products, ORIXKit and ORIXDesign, for iOS 18 and macOS 15, in Swift 6 language mode. The two targets do not depend on each other and neither has an external dependency. The app target is described by project.yml (XcodeGen) and depends on both products.

flowchart TD
    subgraph App["App target (App/Sources)"]
        UI["SwiftUI screens<br/>Home, Library, Document, Actions, Settings"]
        Model["AppModel + Router + AppSettings"]
        Platform["Platform glue<br/>ScannerView, Intents, Spotlight, AppLock, ShareSheet"]
    end
    subgraph Kit["ORIXKit (no UI, no network)"]
        Processor["DocumentProcessor"]
        Store["DocumentStore (actor)"]
        Renderer["PageRenderer"]
        OCR["OCREngine"]
        PDF["SearchablePDFBuilder + PDFTools"]
        Engine["WorkflowEngine"]
        Index["LibraryIndex (SwiftData)"]
    end
    Design["ORIXDesign<br/>tokens, components, haptics"]
    Apple["Apple frameworks<br/>Vision, VisionKit, Core Image, PDFKit, Core Graphics, SwiftData"]
    Disk[("Application Support/ORIXScan")]

    UI --> Model
    UI --> Design
    Platform --> Model
    Model --> Processor
    Model --> Index
    Model --> Engine
    Engine --> Processor
    Processor --> Store
    Processor --> Renderer
    Processor --> OCR
    Processor --> PDF
    Index --> Processor
    Store --> Disk
    Index --> Disk
    Renderer --> Apple
    OCR --> Apple
    PDF --> Apple

# Module map

# ORIXKit

File Main types Responsibility
Model/Geometry.swift Quad Normalized quadrilateral (origin top-left) for crops and text boxes
Model/Document.swift DocumentManifest, PageRecord, PageSource, PageEdit, FilterMode, ExportPreset, ORIXError On-disk document model and non-destructive edit recipe
Imaging/PageRenderer.swift PageRenderer Core Image pipeline: perspective, straightening, rotation, filters, JPEG encoding, PDF page rasterization
Imaging/DocumentDetector.swift DocumentDetector Page outline detection in imported photos (Vision)
Imaging/QualityAnalyzer.swift QualityAnalyzer, QualityReport, QualityIssue Heuristic page-quality estimates
OCR/OCREngine.swift OCREngine Text recognition with VNRecognizeTextRequest
OCR/OCRModel.swift OCRPage, OCRLine, OCRWord, OCROptions, RecognitionMode Recognized-text model stored per page
OCR/ReadingOrder.swift ReadingOrder Recursive XY-cut ordering
OCR/TableExtractor.swift TableExtractor, ExtractedTable Geometry-based table reconstruction, CSV
OCR/TextMetrics.swift TextMetrics Character and word error rates
PDF/SearchablePDFBuilder.swift SearchablePDFBuilder, PDFPageInput, PDFBuildOptions, PageSizeMode PDF writing with an invisible text layer
PDF/PDFTools.swift PDFTools, PDFInspection Opening, unlocking, inspecting and searching PDFs
Storage/DocumentStore.swift DocumentStore Files on disk, atomic manifests, staged drafts
Storage/DocumentProcessor.swift DocumentProcessor, ExportOptions, ExportResult Facade: render, edit, recognize, export
Storage/Library.swift DocumentRecord, FolderRecord, WorkflowRecord, Library, LibraryIndex SwiftData index and library operations
Actions/Workflow.swift Workflow, ActionStep, ActionKind ORIX Actions model and presets
Actions/WorkflowEngine.swift WorkflowEngine, WorkflowResult, StepOutcome Workflow execution

Details: ocr-engine.md, pdf-engine.md, storage.md, workflows.md.

# App target

File Role
Core/ORIXScanApp.swift @main, Boot, launch view, lock screen, privacy cover, keyboard commands
Core/AppModel.swift AppModel: capture and import, edits, recognition tasks, library operations
Core/Router.swift Router, Route, AppSection, AppTab
Core/RootView.swift Adaptive root (tabs or sidebar), capture presentation, global alerts and overlays, drop import
Core/AppSettings.swift AppSettings (UserDefaults)
Core/Naming.swift User-facing names of engine values, AlertInfo
Core/SharedViews.swift PageThumbnail, DocumentCard, DocumentRow, ActivityOverlay, ToastView
Home/HomeView.swift First screen
Library/LibraryView.swift Library, FolderPicker, DocumentTransfer
Document/DocumentView.swift Document workspace, MetadataSheet
Document/PageEditorView.swift PageEditorView, CropEditorView, QualityDetailsView
Document/PageOrganizerView.swift PageOrganizerView, SplitSheet
Document/DocumentTextView.swift Text, review and tables
Document/ExportSheet.swift ExportSheet, PDFPreviewView, PDFKitView
Capture/ScannerView.swift VNDocumentCameraViewController wrapper
Actions/*.swift ActionsView, WorkflowEditorView, WorkflowRunView, WorkflowLauncher, DocumentChooser
Settings/SettingsView.swift SettingsView, LanguagePicker
Platform/Support.swift ThumbnailCache, BackgroundWork, ShareSheet, Printer, Spotlight, AppLock
Platform/Intents.swift App Intents and ORIXShortcuts
Debug/DemoContent.swift Debug builds only: isolated store and sample documents

# Data flow

A document is a directory holding a manifest.json, the original captures and the recognized text (see storage.md). Nothing in the interface holds a document in memory as a whole:

  1. Views read AppModel.manifests[id] (an observable cache of DocumentManifest) and SwiftData records through @Query.
  2. A change goes through an AppModel method, which calls DocumentProcessor or DocumentStore.
  3. AppModel.didChange(_:) reloads the manifest, refreshes the SwiftData record with LibraryIndex.refresh(_:) and updates the Spotlight entry.

Edits are recipes (PageEdit), never pixels: every render starts from the stored original, which is not modified.

flowchart LR
    Scan["Scanner (VisionKit)"] --> In["Incoming items"]
    Photos["Photos picker"] --> In
    Files["Files, drag and drop, Open in"] --> In
    In --> Receive["AppModel.receive"]
    Receive --> Draft["DocumentStore draft in Staging/"]
    Draft --> Commit["commit: one directory move"]
    Commit --> Doc[("Documents/&lt;uuid&gt;")]
    Doc --> Rec["DocumentProcessor.recognize"]
    Rec --> OCRFile[("ocr/&lt;page&gt;.json")]
    Doc --> Export["DocumentProcessor.exportPDF"]
    OCRFile --> Export
    Export --> Builder["SearchablePDFBuilder"]
    Builder --> Out[("Exports/&lt;uuid&gt;/Title.pdf")]
    Out --> Share["Share, Preview, Print, Save to Files"]
    Doc --> Text["exportText / exportTables / exportImages"]
    Text --> Share

# Concurrency model

  • App target: project.yml sets SWIFT_DEFAULT_ACTOR_ISOLATION: MainActor and SWIFT_STRICT_CONCURRENCY: complete. AppModel, Router, AppSettings and the views are main-actor isolated. Types that must run elsewhere are marked nonisolated (IntentPipeline in Platform/Intents.swift).
  • DocumentStore is an actor: manifest reads and writes, draft creation and page file operations are serialized. Path helpers and ensureSpace(for:) are nonisolated.
  • DocumentProcessor is a final class that is Sendable; it holds only immutable references (store, renderer, ocr). Its async methods run off the main actor. Its synchronous methods (renderedImage, cachedPreviewURL) are called from Task.detached in ThumbnailCache.
  • PageRenderer is @unchecked Sendable around one CIContext; filters are created per call.
  • OCREngine.recognize runs the Vision request on DispatchQueue.global(qos: .userInitiated) inside a checked continuation, with a task cancellation handler that cancels the VNRequest.
  • LibraryIndex is @MainActor and owns the ModelContainer and its mainContext.
  • Progress closures are @Sendable; the app hops back with Task { @MainActor in … }.
  • Long operations started by the user that should survive a short trip to the background (AppModel.startRecognition, WorkflowRunView.start) hold a BackgroundWork assertion (UIApplication.beginBackgroundTask).

# Error model

Engines throw ORIXError (Model/Document.swift): documentNotFound, pageNotFound, unreadableImage, unreadablePDF, passwordRequired, wrongPassword, insufficientStorage, emptyDocument, exportFailed, recognitionFailed, cancelled, corruptedManifest.

In the app, operations run through AppModel.attempt(_:). Cancellation (CancellationError, ORIXError.cancelled) is silent; any other error becomes an AlertInfo (Core/Naming.swift), which maps each case to a title and a message a person can act on. RootView presents AppModel.alert. Messages never contain document content. passwordRequired and wrongPassword are handled before that, by a password prompt loop in AppModel (askPassword).

Router holds both layouts' state:

  • compact width: TabView with three tabs (AppTab.home, .library, .actions), one NavigationStack path per tab;
  • regular width: NavigationSplitView with a sidebar bound to Router.section (AppSection) and one detail stack (detailPath).

RootView chooses the layout from horizontalSizeClass and keeps Router.isRegular in step. Router.push(_:) and Router.open(_:) append to whichever stack is active, so features never know which layout they are in. Destinations are declared once by the routeDestinations() modifier (Route.document, .library, .workflow, .settings). DocumentView hides the tab bar so its bottom toolbar has the full width.

# Capture flow

  1. A view calls AppModel.request(_:for:) with a CaptureSource (scan, photos, files) and a CaptureDestination (newDocument, append, retake, workflow). If the source is scan and ScannerView.isAvailable is false, the model shows an alert instead.
  2. RootView observes AppModel.capture and presents the scanner (fullScreenCover), the Photos picker or the file importer.
  3. The result is converted to [Incoming] (.image(data:fileExtension:) or .pdf(url:)) and passed to AppModel.receive(_:from:for:).
  4. receive stages a draft, adds every item, commits, optionally runs DocumentProcessor.autoCrop (imports only), refreshes the index, and then either opens the document and starts recognition, or starts a WorkflowRun.

Files opened from other apps (onOpenURL), drops (DropImport) and the Files importer all end in AppModel.importFiles(_:for:), which calls the same receive.

Files main
Menu

Theme