Repository Public License
1// ORIX Scan2// File: App/Sources/Platform/Support.swift3// Description: Platform glue: thumbnail cache, background-time assertion, share sheet, printing, Spotlight indexing, App Lock.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import CoreSpotlight8import LocalAuthentication9import ORIXKit10import SwiftUI11import UIKit1213/// Decoded previews kept in memory; the JPEG files behind them live in each document's cache directory.14final class ThumbnailCache {15 private let cache = NSCache<NSString, UIImage>()16 private let processor: DocumentProcessor1718 init(processor: DocumentProcessor) {19 self.processor = processor20 cache.totalCostLimit = 96 * 1024 * 102421 }2223 func removeAll() { cache.removeAllObjects() }2425 func image(for page: PageRecord, in id: UUID, maxDimension: Int) async -> UIImage? {26 let key = "\(page.id.uuidString)-\(page.edit.cacheKey)-\(maxDimension)" as NSString27 if let hit = cache.object(forKey: key) { return hit }28 let processor = processor29 let image: UIImage? = await Task.detached(priority: .userInitiated) {30 guard let url = try? processor.cachedPreviewURL(page, in: id, maxDimension: maxDimension), let data = try? Data(contentsOf: url) else { return nil }31 return UIImage(data: data)?.preparingForDisplay()32 }.value33 if let image { cache.setObject(image, forKey: key, cost: Int(image.size.width * image.size.height * image.scale * image.scale * 4)) }34 return image35 }3637 /// Renders a page with an edit that is not saved yet (live preview while adjusting).38 func preview(for page: PageRecord, in id: UUID, edit: PageEdit, maxDimension: CGFloat) async -> UIImage? {39 let processor = processor40 return await Task.detached(priority: .userInitiated) {41 guard let cg = try? processor.renderedImage(page, in: id, edit: edit, maxDimension: maxDimension) else { return nil }42 return UIImage(cgImage: cg)43 }.value44 }45}4647/// Asks iOS for time to finish when the app leaves the foreground mid-operation.48struct BackgroundWork {49 private let identifier: UIBackgroundTaskIdentifier5051 static func begin(named name: String) -> BackgroundWork {52 BackgroundWork(identifier: UIApplication.shared.beginBackgroundTask(withName: name))53 }5455 func end() {56 if identifier != .invalid { UIApplication.shared.endBackgroundTask(identifier) }57 }58}5960struct ShareSheet: UIViewControllerRepresentable {61 let items: [URL]62 var onDone: () -> Void = {}6364 func makeUIViewController(context: Context) -> UIActivityViewController {65 let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)66 controller.completionWithItemsHandler = { _, _, _, _ in onDone() }67 return controller68 }6970 func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}71}7273struct SharePayload: Identifiable {74 let id = UUID()75 var urls: [URL]76}7778enum Printer {79 static var isAvailable: Bool { UIPrintInteractionController.isPrintingAvailable }8081 static func print(_ url: URL, jobName: String) {82 let controller = UIPrintInteractionController.shared83 let info = UIPrintInfo(dictionary: nil)84 info.outputType = .general85 info.jobName = jobName86 controller.printInfo = info87 controller.printingItem = url88 controller.present(animated: true)89 }90}9192enum Spotlight {93 static let activityType = CSSearchableItemActionType94 private static let domain = "ai.spboucher.orix.scan.documents"9596 /// Adds the document to the on-device Spotlight index (title and the first lines of its text). Nothing leaves the device.97 static func index(_ record: DocumentRecord) {98 guard record.deletedAt == nil else { remove([record.id]); return }99 let attributes = CSSearchableItemAttributeSet(contentType: .pdf)100 attributes.title = record.title101 attributes.contentDescription = record.snippet102 attributes.contentModificationDate = record.modifiedAt103 attributes.pageCount = NSNumber(value: record.pageCount)104 let item = CSSearchableItem(uniqueIdentifier: record.id.uuidString, domainIdentifier: domain, attributeSet: attributes)105 CSSearchableIndex.default().indexSearchableItems([item])106 }107108 static func remove(_ ids: [UUID]) {109 CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ids.map(\.uuidString))110 }111112 static func documentID(from activity: NSUserActivity) -> UUID? {113 (activity.userInfo?[CSSearchableItemActivityIdentifier] as? String).flatMap(UUID.init(uuidString:))114 }115}116117/// Optional lock: the device's own authentication (Face ID, Touch ID or passcode). ORIX Scan never sees or stores credentials.118@Observable119final class AppLock {120 var isLocked = false121 var isAuthenticating = false122123 static var biometryName: String {124 let context = LAContext()125 _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)126 switch context.biometryType {127 case .faceID: return "Face ID"128 case .touchID: return "Touch ID"129 case .opticID: return "Optic ID"130 default: return String(localized: "Passcode")131 }132 }133134 static var isAvailable: Bool { LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) }135136 func lockIfEnabled(_ enabled: Bool) {137 if enabled && Self.isAvailable { isLocked = true }138 }139140 func unlock() async {141 guard isLocked, !isAuthenticating else { return }142 isAuthenticating = true143 defer { isAuthenticating = false }144 let context = LAContext()145 let reason = String(localized: "Unlock your documents")146 if (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true { isLocked = false }147 }148149 /// Confirms the user can authenticate before turning the lock on.150 static func confirm() async -> Bool {151 let context = LAContext()152 return (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: String(localized: "Turn on App Lock"))) == true153 }154}155