SPB Git

Repository Public License

DemoContent.swift 12.0 KB 180 lines swift

1// ORIX Scan2// File: App/Sources/Debug/DemoContent.swift3// Description: Debug builds only: isolated store for UI tests and sample documents drawn on device, then processed by the real engines.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7#if DEBUG8import ORIXKit9import SwiftUI10import UIKit1112/// Launch arguments (Debug only):13/// `-ORIXUITest YES`  use a separate store under tmp, never the user's library14/// `-ORIXReset YES`   empty that store first15/// `-ORIXDemo YES`    add the sample documents when the library is empty16/// `-ORIXImport path` import that file through the same code path as the Files picker (the picker itself is system UI)17enum DemoContent {18    private static var defaults: UserDefaults { .standard }1920    static func makeModel() throws -> AppModel {21        guard defaults.bool(forKey: "ORIXUITest") else { return try AppModel() }22        let root = FileManager.default.temporaryDirectory.appendingPathComponent("ORIXUITest", isDirectory: true)23        if defaults.bool(forKey: "ORIXReset") {24            try? FileManager.default.removeItem(at: root)25            for key in ["recognitionMode", "languages", "librarySort", "librarySortAscending", "libraryShowsList", "appLock", "dismissedQualityWarnings"] {26                defaults.removeObject(forKey: key)27            }28        }29        return try AppModel(root: root)30    }3132    static func seedIfRequested(_ model: AppModel) async {33        if let path = defaults.string(forKey: "ORIXImport") {34            Task { await model.importFiles([URL(fileURLWithPath: path)]) }35        }36        guard defaults.bool(forKey: "ORIXDemo"), model.index.allRecords().isEmpty else { return }37        let store = model.processor.store38        func make(_ title: String, _ pages: [UIImage], filter: FilterMode = .color, recognize: Bool = true, favorite: Bool = false, folder: String? = nil) async {39            do {40                var draft = try await store.beginDraft(title: title)41                for page in pages {42                    guard let data = page.jpegData(compressionQuality: 0.92) else { continue }43                    try await store.addImage(data, fileExtension: "jpg", edit: PageEdit(filter: filter), to: &draft)44                }45                let manifest = try await store.commit(draft)46                if recognize { _ = try await model.processor.recognize(manifest.id, options: OCROptions(mode: .accurate, languages: ["en-US", "fr-FR"])) }47                await model.didChange(manifest.id)48                if favorite { model.index.setFavorite([manifest.id], true) }49                if let folder, let record = model.index.folder(named: folder) { model.index.move([manifest.id], to: record) }50            } catch {51                assertionFailure("demo seed failed: \(error)")52            }53        }54        await make("Meeting Notes", [Page.notes()], filter: .grayscale, recognize: false)55        await make("Lettre Hydro-Québec", [Page.letter()], folder: "Maison")56        await make("Café Receipt", [Page.receipt()], filter: .grayscale, folder: "Receipts")57        await make("Quarterly Report", [Page.report(1), Page.report(2), Page.report(3)], favorite: true)58        await make("Invoice 2026-041", [Page.invoice()], favorite: true, folder: "Receipts")59    }6061    /// Sample pages drawn with UIKit text. A soft lighting gradient is added so enhancement has something real to correct.62    enum Page {63        static func canvas(_ size: CGSize = CGSize(width: 1654, height: 2339), _ draw: (CGRect) -> Void) -> UIImage {64            let format = UIGraphicsImageRendererFormat()65            format.scale = 166            format.opaque = true67            return UIGraphicsImageRenderer(size: size, format: format).image { context in68                let bounds = CGRect(origin: .zero, size: size)69                UIColor(red: 0.93, green: 0.92, blue: 0.89, alpha: 1).setFill()70                context.fill(bounds)71                draw(bounds)72                // Uneven light: darker toward one corner, as under a desk lamp.73                let colors = [UIColor.black.withAlphaComponent(0).cgColor, UIColor.black.withAlphaComponent(0.22).cgColor] as CFArray74                if let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors, locations: [0, 1]) {75                    context.cgContext.drawLinearGradient(gradient, start: CGPoint(x: size.width * 0.3, y: 0), end: CGPoint(x: size.width, y: size.height), options: [])76                }77            }78        }7980        @discardableResult81        static func text(_ string: String, at point: CGPoint, size: CGFloat = 34, weight: UIFont.Weight = .regular, color: UIColor = UIColor(white: 0.1, alpha: 1),82                         width: CGFloat = 1300) -> CGFloat {83            let paragraph = NSMutableParagraphStyle()84            paragraph.lineSpacing = size * 0.3585            let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: size, weight: weight), .foregroundColor: color, .paragraphStyle: paragraph]86            let rect = (string as NSString).boundingRect(with: CGSize(width: width, height: 4000), options: [.usesLineFragmentOrigin], attributes: attributes, context: nil)87            (string as NSString).draw(with: CGRect(origin: point, size: CGSize(width: width, height: rect.height)), options: [.usesLineFragmentOrigin], attributes: attributes, context: nil)88            return point.y + rect.height89        }9091        static func rule(_ y: CGFloat, from x0: CGFloat = 150, to x1: CGFloat = 1504) {92            let path = UIBezierPath()93            path.move(to: CGPoint(x: x0, y: y)); path.addLine(to: CGPoint(x: x1, y: y))94            UIColor(white: 0.3, alpha: 1).setStroke()95            path.lineWidth = 296            path.stroke()97        }9899        static func invoice() -> UIImage {100            canvas { _ in101                text("NORTHWIND STUDIO", at: CGPoint(x: 150, y: 150), size: 56, weight: .bold)102                text("1200 Avenue des Érables, Québec QC G1R 2B5", at: CGPoint(x: 150, y: 235), size: 30, color: UIColor(white: 0.3, alpha: 1))103                text("INVOICE 2026-041", at: CGPoint(x: 150, y: 360), size: 44, weight: .semibold)104                text("Date: November 12, 2026", at: CGPoint(x: 150, y: 430))105                text("Bill to: Atelier Lumen Inc.", at: CGPoint(x: 150, y: 485))106                rule(590)107                let columns: [CGFloat] = [150, 820, 1040, 1290]108                let rows = [["Description", "Qty", "Rate", "Amount"], ["Brand identity design", "12", "95.00", "1140.00"], ["Icon system", "18", "95.00", "1710.00"],109                            ["Website prototype", "24", "110.00", "2640.00"], ["Print production", "10", "62.50", "625.00"], ["Project management", "15", "80.00", "1200.00"]]110                var y: CGFloat = 620111                for (r, row) in rows.enumerated() {112                    for (c, cell) in row.enumerated() { text(cell, at: CGPoint(x: columns[c], y: y), size: 32, weight: r == 0 ? .semibold : .regular, width: 640) }113                    y += 78114                    if r == 0 { rule(y - 14) }115                }116                rule(y + 6)117                text("Subtotal 7315.00", at: CGPoint(x: 1040, y: y + 40), size: 32)118                text("Total due 8410.42 CAD", at: CGPoint(x: 1040, y: y + 100), size: 36, weight: .bold, width: 500)119                text("Payment is due within thirty days. Thank you for your business.", at: CGPoint(x: 150, y: y + 260), size: 30, color: UIColor(white: 0.3, alpha: 1))120            }121        }122123        static func letter() -> UIImage {124            canvas { _ in125                text("Hydro-Québec", at: CGPoint(x: 150, y: 150), size: 54, weight: .bold)126                text("Montréal, le 3 novembre 2026", at: CGPoint(x: 150, y: 290))127                text("Objet : Avis de modification de votre mode de versements égaux", at: CGPoint(x: 150, y: 400), size: 36, weight: .semibold)128                var y = text("Madame, Monsieur,", at: CGPoint(x: 150, y: 520))129                y = text("Nous avons révisé votre consommation d'électricité des douze derniers mois. À compter du 1er décembre 2026, votre versement mensuel passera de 128,00 $ à 134,50 $.", at: CGPoint(x: 150, y: y + 50))130                y = text("Cette révision tient compte de l'hiver précédent, plus froid que la moyenne, et des tarifs en vigueur depuis le 1er avril. Aucune démarche n'est requise de votre part : le nouveau montant sera prélevé automatiquement.", at: CGPoint(x: 150, y: y + 40))131                y = text("Pour consulter le détail de votre consommation ou modifier vos préférences, ouvrez votre Espace client. Vous pouvez aussi nous joindre du lundi au vendredi, de 8 h à 20 h 30.", at: CGPoint(x: 150, y: y + 40))132                y = text("Nous vous prions d'agréer, Madame, Monsieur, nos salutations distinguées.", at: CGPoint(x: 150, y: y + 40))133                text("Le Service à la clientèle", at: CGPoint(x: 150, y: y + 130), weight: .medium)134            }135        }136137        static func receipt() -> UIImage {138            canvas(CGSize(width: 900, height: 2000)) { _ in139                text("CAFÉ DES ARTISANS", at: CGPoint(x: 120, y: 120), size: 50, weight: .bold, width: 700)140                text("87 rue Saint-Jean, Québec", at: CGPoint(x: 120, y: 200), size: 30, width: 700)141                text("2026-11-18  09:42", at: CGPoint(x: 120, y: 260), size: 30, width: 700)142                rule(340, from: 100, to: 800)143                var y: CGFloat = 380144                for (item, price) in [("Latte grand", "5.75"), ("Croissant beurre", "3.95"), ("Jus orange", "4.50"), ("Sandwich jambon", "9.25")] {145                    text(item, at: CGPoint(x: 120, y: y), size: 34, width: 480)146                    text(price, at: CGPoint(x: 660, y: y), size: 34, width: 200)147                    y += 74148                }149                rule(y + 10, from: 100, to: 800)150                text("Sous-total", at: CGPoint(x: 120, y: y + 50), size: 34, width: 480); text("23.45", at: CGPoint(x: 660, y: y + 50), size: 34, width: 200)151                text("Taxes", at: CGPoint(x: 120, y: y + 120), size: 34, width: 480); text("3.51", at: CGPoint(x: 660, y: y + 120), size: 34, width: 200)152                text("TOTAL", at: CGPoint(x: 120, y: y + 200), size: 42, weight: .bold, width: 480); text("26.96", at: CGPoint(x: 660, y: y + 200), size: 42, weight: .bold, width: 200)153                text("Merci et à bientôt !", at: CGPoint(x: 120, y: y + 340), size: 32, width: 700)154            }155        }156157        static func notes() -> UIImage {158            canvas { _ in159                text("Product Meeting Notes", at: CGPoint(x: 150, y: 150), size: 52, weight: .bold)160                text("Decisions\n\nShip the scanner update before the holidays.\n\nKeep recognition fully on device.\n\nAdd French metadata to the store page.", at: CGPoint(x: 150, y: 320), size: 32, width: 600)161                text("Next steps\n\nReview the export presets with design.\n\nMeasure recognition time on older devices.\n\nPrepare the release notes draft.", at: CGPoint(x: 880, y: 320), size: 32, width: 600)162            }163        }164165        static func report(_ page: Int) -> UIImage {166            canvas { _ in167                text(page == 1 ? "Quarterly Report" : "Quarterly Report, continued", at: CGPoint(x: 150, y: 150), size: 52, weight: .bold)168                let bodies = [169                    "Revenue increased by eighteen percent compared with the previous quarter, driven by strong demand for the professional plan.\n\nOperating costs remained stable while customer satisfaction improved for the third consecutive quarter.",170                    "The support team answered nine out of ten requests within one business day.\n\nChurn decreased among small teams after the onboarding redesign shipped in September.",171                    "Priorities for the next quarter are reliability, accessibility and faster document export.\n\nThe board will review these figures at the meeting on Thursday.",172                ]173                let y = text(bodies[page - 1], at: CGPoint(x: 150, y: 320), size: 36)174                text("Page \(page) of 3", at: CGPoint(x: 150, y: max(y + 200, 2100)), size: 28, color: UIColor(white: 0.35, alpha: 1))175            }176        }177    }178}179#endif180
Files main
Menu

Theme