Repository Public License
1// ORIX Scan2// File: App/Sources/Core/AppModel.swift3// Description: Application state and operations: capture and import, page edits, recognition, export, workflows, library index upkeep.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import ORIXDesign9import ORIXKit10import SwiftData11import SwiftUI12import UniformTypeIdentifiers1314enum CaptureSource: Hashable { case scan, photos, files }1516enum CaptureDestination: Hashable {17 case newDocument18 case append(UUID)19 case retake(document: UUID, page: UUID)20 case workflow(Workflow)21}2223struct CaptureRequest: Identifiable, Hashable {24 let id = UUID()25 var source: CaptureSource26 var destination: CaptureDestination27}2829/// One captured or imported item, before it is stored.30enum Incoming: Sendable {31 case image(data: Data, fileExtension: String)32 case pdf(url: URL)33}3435/// A long operation shown with progress and a Cancel button.36struct Activity: Identifiable {37 let id = UUID()38 var title: String39 var detail: String = ""40 /// `nil` = indeterminate.41 var fraction: Double?42 var task: Task<Void, Never>?43}4445struct PasswordPrompt: Identifiable {46 let id = UUID()47 var fileName: String48 var wrong: Bool49 var submit: (String?) -> Void50}5152struct WorkflowRun: Identifiable {53 let id = UUID()54 var workflow: Workflow55 var documentIDs: [UUID]56}5758@Observable59final class AppModel {60 let processor: DocumentProcessor61 let container: ModelContainer62 let index: LibraryIndex63 let settings: AppSettings64 let thumbnails: ThumbnailCache65 let router = Router()6667 /// Manifests of the documents the interface has shown, kept current after every change.68 private(set) var manifests: [UUID: DocumentManifest] = [:]69 /// Background recognition in progress: document → 0…1.70 private(set) var recognitionProgress: [UUID: Double] = [:]71 @ObservationIgnored private var recognitionTasks: [UUID: Task<Void, Never>] = [:]7273 var activity: Activity?74 var alert: AlertInfo?75 var capture: CaptureRequest?76 var passwordPrompt: PasswordPrompt?77 var workflowRun: WorkflowRun?78 /// A workflow waiting for the user to choose library documents.79 var pendingLibraryWorkflow: Workflow?80 /// Message shown briefly at the bottom of the screen ("Moved to Recently Deleted").81 var toast: String?82 var isReady = false8384 init(root: URL? = nil, inMemoryIndex: Bool = false) throws {85 let storeRoot = try root ?? DocumentStore.defaultRoot()86 let store = try DocumentStore(root: storeRoot)87 processor = DocumentProcessor(store: store)88 container = try Library.makeContainer(url: inMemoryIndex ? nil : storeRoot.appendingPathComponent("Library.store"), inMemory: inMemoryIndex)89 index = LibraryIndex(container: container, processor: processor)90 settings = AppSettings()91 thumbnails = ThumbnailCache(processor: processor)92 }9394 /// Launch housekeeping: discard interrupted work, rebuild missing index entries, empty expired Recently Deleted.95 func start() async {96 await processor.store.recoverAfterLaunch()97 await index.reconcile()98 isReady = true99 }100101 // MARK: Manifests102103 func manifest(_ id: UUID) -> DocumentManifest? { manifests[id] }104105 @discardableResult106 func load(_ id: UUID) async -> DocumentManifest? {107 do {108 let manifest = try await processor.store.manifest(id)109 manifests[id] = manifest110 return manifest111 } catch {112 return nil113 }114 }115116 /// Call after anything changed a document: refreshes the cached manifest, the library index and Spotlight.117 func didChange(_ id: UUID) async {118 guard await load(id) != nil else { return }119 if let record = try? await index.refresh(id) { Spotlight.index(record) }120 }121122 /// Runs an operation that can fail, reporting the failure to the user. Returns `nil` on failure.123 @discardableResult124 func attempt<T>(_ work: () async throws -> T) async -> T? {125 do {126 return try await work()127 } catch is CancellationError {128 return nil129 } catch ORIXError.cancelled {130 return nil131 } catch {132 alert = AlertInfo(error)133 ORIXHaptics.failure()134 return nil135 }136 }137138 // MARK: Capture and import139140 func request(_ source: CaptureSource, for destination: CaptureDestination = .newDocument) {141 if source == .scan && !ScannerView.isAvailable {142 alert = AlertInfo(title: String(localized: "Scanner Unavailable"),143 message: String(localized: "Scanning needs a camera, which this device doesn't have. You can import photos or files instead."))144 return145 }146 capture = CaptureRequest(source: source, destination: destination)147 }148149 /// Stores captured or imported items according to the destination. Returns the affected document.150 @discardableResult151 func receive(_ items: [Incoming], from source: CaptureSource, for destination: CaptureDestination) async -> UUID? {152 guard !items.isEmpty else { return nil }153 let store = processor.store154 let filter = settings.defaultFilter155 // VisionKit scans arrive cropped and flattened; photos get edge detection instead.156 let edit = PageEdit(filter: filter, shadowReduction: filter != .original)157 activity = Activity(title: String(localized: "Saving…"))158 defer { activity = nil }159 switch destination {160 case .newDocument, .workflow:161 let title = Library.uniqueTitle(pendingTitle ?? Self.defaultTitle(for: items, source: source), existing: index.allRecords().map(\.title))162 let created: UUID? = await attempt {163 var draft = try await store.beginDraft(title: title)164 do {165 for item in items { try await self.add(item, edit: edit, to: &draft) }166 return try await store.commit(draft).id167 } catch {168 await store.discard(draft)169 throw error170 }171 }172 guard let id = created else { return nil }173 if source != .scan && settings.autoCropImports { _ = try? await processor.autoCrop(id) }174 await didChange(id)175 ORIXHaptics.success()176 if case let .workflow(workflow) = destination {177 workflowRun = WorkflowRun(workflow: workflow, documentIDs: [id])178 } else {179 router.open(id)180 if settings.recognizeAfterCapture { startRecognition(id) }181 }182 return id183 case let .append(id):184 let before = Set(manifests[id]?.pages.map(\.id) ?? [])185 let ok: Bool? = await attempt {186 for item in items {187 switch item {188 case let .image(data, ext): _ = try await store.insertImage(data, fileExtension: ext, edit: edit, into: id)189 case let .pdf(url): try await self.insertPDF(url, into: id)190 }191 }192 return true193 }194 await didChange(id)195 if ok == true, source != .scan, settings.autoCropImports, let manifest = manifests[id] {196 _ = try? await processor.autoCrop(id, pages: Set(manifest.pages.map(\.id)).subtracting(before))197 await didChange(id)198 }199 if ok == true, settings.recognizeAfterCapture { startRecognition(id) }200 return id201 case let .retake(id, page):202 guard case let .image(data, ext)? = items.first else { return nil }203 await attempt { _ = try await store.replaceImage(page: page, in: id, with: data, fileExtension: ext) }204 await didChange(id)205 if settings.recognizeAfterCapture { startRecognition(id) }206 return id207 }208 }209210 private func add(_ item: Incoming, edit: PageEdit, to draft: inout DocumentStore.Draft) async throws {211 let store = processor.store212 switch item {213 case let .image(data, ext):214 try await store.addImage(data, fileExtension: ext, edit: edit, to: &draft)215 case let .pdf(url):216 var password: String?217 while true {218 do {219 try await store.addPDF(at: url, password: password, to: &draft)220 return221 } catch ORIXError.passwordRequired {222 guard let entered = await askPassword(for: url, wrong: false) else { throw ORIXError.cancelled }223 password = entered224 } catch ORIXError.wrongPassword {225 guard let entered = await askPassword(for: url, wrong: true) else { throw ORIXError.cancelled }226 password = entered227 }228 }229 }230 }231232 private func insertPDF(_ url: URL, into id: UUID) async throws {233 var password: String?234 while true {235 do {236 _ = try await processor.store.insertPDF(at: url, password: password, into: id)237 return238 } catch ORIXError.passwordRequired {239 guard let entered = await askPassword(for: url, wrong: false) else { throw ORIXError.cancelled }240 password = entered241 } catch ORIXError.wrongPassword {242 guard let entered = await askPassword(for: url, wrong: true) else { throw ORIXError.cancelled }243 password = entered244 }245 }246 }247248 private func askPassword(for url: URL, wrong: Bool) async -> String? {249 let savedActivity = activity250 activity = nil251 defer { activity = savedActivity }252 return await withCheckedContinuation { continuation in253 passwordPrompt = PasswordPrompt(fileName: url.lastPathComponent, wrong: wrong) { continuation.resume(returning: $0) }254 }255 }256257 /// Files opened from Files, the share sheet, drag and drop or "Open in ORIX Scan".258 func importFiles(_ urls: [URL], for destination: CaptureDestination = .newDocument) async {259 var items: [Incoming] = []260 var scoped: [URL] = []261 defer { for url in scoped { url.stopAccessingSecurityScopedResource() } }262 for url in urls {263 if url.startAccessingSecurityScopedResource() { scoped.append(url) }264 let type = UTType(filenameExtension: url.pathExtension)265 if type?.conforms(to: .pdf) == true {266 items.append(.pdf(url: url))267 } else if type?.conforms(to: .image) == true, let data = try? Data(contentsOf: url, options: .mappedIfSafe) {268 items.append(.image(data: data, fileExtension: url.pathExtension))269 }270 }271 if items.isEmpty {272 alert = AlertInfo(title: String(localized: "Nothing to Import"), message: String(localized: "ORIX Scan imports images and PDF files."))273 return274 }275 // One file keeps its own name as the document title.276 if case .newDocument = destination, urls.count == 1, let name = urls.first?.deletingPathExtension().lastPathComponent, !name.isEmpty {277 pendingTitle = name278 }279 await receive(items, from: .files, for: destination)280 pendingTitle = nil281 }282283 @ObservationIgnored private var pendingTitle: String?284285 private static func defaultTitle(for items: [Incoming], source: CaptureSource) -> String {286 let date = Date.now.formatted(date: .abbreviated, time: .omitted)287 switch source {288 case .scan: return String(localized: "Scan \(date)")289 case .photos: return String(localized: "Photos \(date)")290 case .files: return String(localized: "Import \(date)")291 }292 }293294 // MARK: Editing295296 func updateEdits(in id: UUID, pages: Set<UUID>? = nil, _ transform: @escaping @Sendable (inout PageEdit, PageRecord) -> Void) async {297 await attempt { try await processor.updateEdits(in: id, pages: pages, transform) }298 await didChange(id)299 }300301 func setPages(_ pages: [PageRecord], in id: UUID) async {302 guard var manifest = manifests[id] else { return }303 manifest.pages = pages304 manifests[id] = manifest305 await attempt { try await processor.store.save(manifest) }306 await didChange(id)307 }308309 func deletePages(_ pages: Set<UUID>, in id: UUID) async {310 await attempt { _ = try await processor.store.deletePages(pages, in: id) }311 await didChange(id)312 }313314 func duplicatePage(_ page: UUID, in id: UUID) async {315 await attempt { _ = try await processor.store.duplicatePage(page, in: id) }316 await didChange(id)317 }318319 func setMetadata(_ metadata: DocumentMetadata, title: String, in id: UUID) async {320 guard var manifest = manifests[id] else { return }321 manifest.metadata = metadata322 let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)323 if !trimmed.isEmpty { manifest.title = trimmed }324 await attempt { try await processor.store.save(manifest) }325 await didChange(id)326 }327328 func rename(_ id: UUID, to title: String) async {329 await attempt { try await index.rename(id, to: title) }330 await didChange(id)331 }332333 /// New document from some pages of another (extract / split). Returns the new document.334 @discardableResult335 func derive(from id: UUID, pages: [UUID], title: String) async -> UUID? {336 let unique = Library.uniqueTitle(title, existing: index.allRecords().map(\.title))337 guard let manifest = await attempt({ try await processor.store.derive(from: id, pages: pages, title: unique) }) else { return nil }338 await didChange(manifest.id)339 if let source = index.record(id), let folder = source.folder { index.move([manifest.id], to: folder) }340 return manifest.id341 }342343 @discardableResult344 func merge(_ ids: [UUID]) async -> UUID? {345 guard ids.count >= 2 else { return nil }346 let first = index.record(ids[0])?.title ?? String(localized: "Document")347 let title = Library.uniqueTitle(String(localized: "\(first) (merged)"), existing: index.allRecords().map(\.title))348 activity = Activity(title: String(localized: "Merging…"))349 defer { activity = nil }350 guard let manifest = await attempt({ try await processor.store.merge(ids, title: title) }) else { return nil }351 await didChange(manifest.id)352 ORIXHaptics.success()353 return manifest.id354 }355356 // MARK: Library357358 func moveToTrash(_ ids: [UUID]) {359 for id in ids { cancelRecognition(id); router.close(id) }360 index.moveToTrash(ids)361 Spotlight.remove(ids)362 toast = ids.count == 1 ? String(localized: "Moved to Recently Deleted") : String(localized: "\(ids.count) documents moved to Recently Deleted")363 ORIXHaptics.tick()364 }365366 func restore(_ ids: [UUID]) {367 index.restore(ids)368 for id in ids { if let record = index.record(id) { Spotlight.index(record) } }369 }370371 func deletePermanently(_ ids: [UUID]) async {372 for id in ids { cancelRecognition(id); router.close(id); manifests[id] = nil }373 await index.deletePermanently(ids)374 Spotlight.remove(ids)375 }376377 func duplicate(_ id: UUID) async {378 if let copy = await attempt({ try await index.duplicate(id) }) { await didChange(copy.id) }379 }380381 // MARK: Recognition382383 func isRecognizing(_ id: UUID) -> Bool { recognitionProgress[id] != nil }384385 /// Recognizes in the background of the interface; keeps running briefly if the app is sent to the background.386 func startRecognition(_ id: UUID, force: Bool = false, pages: Set<UUID>? = nil) {387 guard recognitionTasks[id] == nil else { return }388 recognitionProgress[id] = 0389 let options = settings.ocrOptions390 let processor = processor391 recognitionTasks[id] = Task { [weak self] in392 let background = BackgroundWork.begin(named: "ORIX recognition")393 defer { background.end() }394 do {395 try await processor.recognize(id, options: options, pages: pages, force: force) { fraction in396 Task { @MainActor in if self?.recognitionProgress[id] != nil { self?.recognitionProgress[id] = fraction } }397 }398 } catch is CancellationError {399 } catch ORIXError.cancelled {400 } catch {401 self?.alert = AlertInfo(error)402 }403 self?.recognitionProgress[id] = nil404 self?.recognitionTasks[id] = nil405 await self?.didChange(id)406 }407 }408409 func cancelRecognition(_ id: UUID) {410 recognitionTasks[id]?.cancel()411 }412413 /// Waits for a running recognition of this document (used before exporting a searchable PDF).414 func waitForRecognition(_ id: UUID) async {415 await recognitionTasks[id]?.value416 }417418 // MARK: Memory and storage pressure419420 func releaseMemory() {421 thumbnails.removeAll()422 }423424 func clearCaches() async {425 thumbnails.removeAll()426 await processor.store.clearAllCaches()427 }428}429