SPB Git

Repository Public License

ExportSheet.swift 14.3 KB 295 lines swift

1// ORIX Scan2// File: App/Sources/Document/ExportSheet.swift3// Description: Export: searchable PDF with measured file sizes per quality preset, password, page size; preview with search, share, print, save.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import ORIXDesign8import ORIXKit9import PDFKit10import SwiftUI1112struct ExportSheet: View {13    @Environment(AppModel.self) private var model14    @Environment(\.orixAccent) private var accent15    @Environment(\.dismiss) private var dismiss16    let documentID: UUID1718    @State private var preset: ExportPreset = .balanced19    @State private var searchable = true20    @State private var pageSize: PageSizeMode = .automatic21    @State private var usePassword = false22    @State private var password = ""23    /// Results of exports actually produced with the current options, by preset.24    @State private var results: [ExportPreset: ExportResult] = [:]25    @State private var working: ExportPreset?26    @State private var progress = 0.027    @State private var task: Task<Void, Never>?28    @State private var share: SharePayload?29    @State private var preview: PreviewPayload?30    @State private var saving: URL?31    @State private var storedSize: Int64 = 03233    struct PreviewPayload: Identifiable {34        let id = UUID()35        var url: URL36        var password: String?37    }3839    private var options: ExportOptions {40        ExportOptions(preset: preset, searchable: searchable, pageSize: pageSize, password: usePassword && !password.isEmpty ? password : nil)41    }42    private var optionsKey: String { "\(searchable)-\(pageSize.rawValue)-\(usePassword ? password : "")" }43    private var record: DocumentRecord? { model.index.record(documentID) }4445    var body: some View {46        NavigationStack {47            Form {48                Section {49                    ForEach(ExportPreset.allCases) { candidate in50                        Button { preset = candidate; ORIXHaptics.tick() } label: {51                            HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.sm) {52                                Image(systemName: preset == candidate ? "largecircle.fill.circle" : "circle")53                                    .foregroundStyle(preset == candidate ? accent.primary : ORIX.Palette.textTertiary)54                                VStack(alignment: .leading, spacing: 2) {55                                    Text(candidate.title).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)56                                    Text(candidate.detail).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)57                                }58                                Spacer()59                                sizeLabel(candidate)60                            }61                        }62                        .accessibilityAddTraits(preset == candidate ? .isSelected : [])63                        .accessibilityIdentifier("export.preset.\(candidate.rawValue)")64                    }65                    Button { measureAll() } label: { Label("Measure All Sizes", systemImage: "ruler") }66                        .disabled(working != nil || results.count == ExportPreset.allCases.count)67                        .accessibilityIdentifier("export.measure")68                } header: { Text("Quality") } footer: {69                    Text("Sizes are measured by building the PDF, never estimated. A smaller preset does not always produce a smaller file. Stored document: \(storedSize.byteCountString).")70                }7172                Section {73                    Toggle("Searchable Text Layer", isOn: $searchable)74                        .accessibilityIdentifier("export.searchable")75                    Picker("Page Size", selection: $pageSize) { ForEach(PageSizeMode.allCases) { Text($0.title).tag($0) } }76                    Toggle("Password Protection", isOn: $usePassword.animation())77                    if usePassword {78                        SecureField("Password", text: $password).textContentType(.newPassword)79                            .accessibilityIdentifier("export.password")80                    }81                } header: { Text("Options") } footer: {82                    if searchable, record?.hasText == false {83                        Text("Text has not been recognized yet. It will be recognized on this device before the PDF is built.")84                    } else if usePassword {85                        Text("The password is needed to open the PDF. ORIX Scan does not keep it: if you forget it, the exported file can't be opened.")86                    }87                }8889                if let result = results[preset] {90                    Section("Result") {91                        LabeledContent("File Size", value: result.byteSize.byteCountString)92                        LabeledContent("Pages", value: result.pageCount.formatted())93                        LabeledContent("Pages With Text Layer", value: result.pagesWithTextLayer.formatted())94                        if result.pagesPassedThrough > 0 {95                            LabeledContent("Pages Kept As Imported", value: result.pagesPassedThrough.formatted())96                        }97                    }98                }99100                Section {101                    if working != nil {102                        VStack(alignment: .leading, spacing: ORIX.Space.xs) {103                            HStack {104                                Text("Building PDF…").font(.orixCallout.weight(.medium))105                                Spacer()106                                Button("Cancel") { task?.cancel() }107                            }108                            ORIXProgressBar(value: progress)109                        }110                        .accessibilityIdentifier("export.progress")111                    } else {112                        Button { run { share = SharePayload(urls: [$0.url]) } } label: { Label("Share PDF", systemImage: "square.and.arrow.up") }113                            .accessibilityIdentifier("export.share")114                        Button { run { preview = PreviewPayload(url: $0.url, password: options.password) } } label: { Label("Preview and Search", systemImage: "doc.text.magnifyingglass") }115                            .accessibilityIdentifier("export.preview")116                        Button { run { saving = $0.url } } label: { Label("Save to Files", systemImage: "folder") }117                        if Printer.isAvailable {118                            Button { run { Printer.print($0.url, jobName: record?.title ?? "ORIX Scan") } } label: { Label("Print", systemImage: "printer") }119                                .disabled(usePassword)120                        }121                    }122                }123124                Section("Other Formats") {125                    Button {126                        Task {127                            await ensureText()128                            if let url = await model.attempt({ try await model.processor.exportText(documentID) }) { share = SharePayload(urls: [url]) }129                        }130                    } label: { Label("Plain Text (.txt)", systemImage: "text.alignleft") }131                    Button {132                        Task { if let urls = await model.attempt({ try await model.processor.exportImages(documentID) }) { share = SharePayload(urls: urls) } }133                    } label: { Label("Images (.jpg)", systemImage: "photo.on.rectangle") }134                }135            }136            .navigationTitle("Export")137            .navigationBarTitleDisplayMode(.inline)138            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { task?.cancel(); dismiss() } } }139            .onChange(of: optionsKey) { _, _ in results = [:] }140            .task {141                preset = model.settings.exportPreset142                pageSize = model.settings.pageSize143                storedSize = await model.processor.store.byteSize(of: documentID)144            }145            .sheet(item: $share) { ShareSheet(items: $0.urls) }146            .sheet(item: $preview) { PDFPreviewView(url: $0.url, password: $0.password, title: record?.title ?? "") }147            .fileMover(isPresented: Binding(get: { saving != nil }, set: { if !$0 { saving = nil } }), file: saving) { result in148                if case .success = result { model.toast = String(localized: "Saved to Files"); results[preset] = nil }149                saving = nil150            }151        }152    }153154    @ViewBuilder private func sizeLabel(_ candidate: ExportPreset) -> some View {155        if let result = results[candidate] {156            Text(result.byteSize.byteCountString).font(.orixMono).foregroundStyle(ORIX.Palette.textPrimary)157                .accessibilityIdentifier("export.size.\(candidate.rawValue)")158        } else if working == candidate {159            ProgressView().controlSize(.small)160        } else {161            Text("—").foregroundStyle(ORIX.Palette.textTertiary).accessibilityLabel("Not measured")162        }163    }164165    private func ensureText() async {166        await model.waitForRecognition(documentID)167        if record?.hasText == false {168            model.startRecognition(documentID)169            await model.waitForRecognition(documentID)170        }171    }172173    /// Builds the PDF for a preset unless it already exists with the same options.174    private func build(_ candidate: ExportPreset) async -> ExportResult? {175        if let existing = results[candidate], FileManager.default.fileExists(atPath: existing.url.path) { return existing }176        working = candidate177        progress = 0178        defer { working = nil }179        if searchable { await ensureText() }180        if Task.isCancelled { return nil }181        var chosen = options182        chosen.preset = candidate183        let result = await model.attempt {184            try await model.processor.exportPDF(documentID, options: chosen) { fraction in Task { @MainActor in progress = fraction } }185        }186        if let result { results[candidate] = result }187        return result188    }189190    private func run(_ then: @escaping (ExportResult) -> Void) {191        let chosen = preset192        task = Task {193            if let result = await build(chosen), !Task.isCancelled {194                ORIXHaptics.success()195                then(result)196            }197        }198    }199200    private func measureAll() {201        task = Task {202            for candidate in ExportPreset.allCases {203                if Task.isCancelled { break }204                _ = await build(candidate)205            }206        }207    }208}209210/// The exported PDF in PDFKit, with the same text search any PDF reader offers. This is how the text layer is checked.211struct PDFPreviewView: View {212    @Environment(\.dismiss) private var dismiss213    @Environment(\.orixAccent) private var accent214    let url: URL215    var password: String?216    let title: String217    @State private var query = ""218    @State private var matches: [PDFSelection] = []219    @State private var current = 0220    @State private var document: PDFDocument?221222    var body: some View {223        NavigationStack {224            VStack(spacing: 0) {225                HStack(spacing: ORIX.Space.xs) {226                    Image(systemName: "magnifyingglass").foregroundStyle(ORIX.Palette.textSecondary)227                    TextField("Search in PDF", text: $query).textInputAutocapitalization(.never).autocorrectionDisabled().submitLabel(.search)228                        .accessibilityIdentifier("preview.search")229                    if !query.isEmpty {230                        Text(matches.isEmpty ? String(localized: "No matches") : String(localized: "\(current + 1) of \(matches.count)"))231                            .font(.orixCaption).monospacedDigit()232                            .foregroundStyle(matches.isEmpty ? ORIX.Palette.danger : ORIX.Palette.textSecondary)233                            .accessibilityIdentifier("preview.matches")234                        Button { step(-1) } label: { Image(systemName: "chevron.up") }.disabled(matches.count < 2).accessibilityLabel("Previous match")235                        Button { step(1) } label: { Image(systemName: "chevron.down") }.disabled(matches.count < 2).accessibilityLabel("Next match")236                    }237                }238                .padding(.horizontal, ORIX.Space.sm)239                .frame(minHeight: ORIX.minimumTarget)240                .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))241                .padding(ORIX.Space.sm)242                if let document {243                    PDFKitView(document: document, highlights: matches, current: matches.indices.contains(current) ? matches[current] : nil)244                        .ignoresSafeArea(edges: .bottom)245                } else {246                    ORIXEmptyState(systemName: "doc.questionmark", title: "Preview Unavailable", message: "The PDF could not be opened for preview.")247                }248            }249            .background(ORIX.Palette.desk)250            .navigationTitle(title)251            .navigationBarTitleDisplayMode(.inline)252            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }253            .task {254                let opened = PDFDocument(url: url)255                if let password, opened?.isLocked == true { _ = opened?.unlock(withPassword: password) }256                document = opened257            }258            .onChange(of: query) { _, new in259                matches = new.isEmpty ? [] : (document?.findString(new, withOptions: [.caseInsensitive, .diacriticInsensitive]) ?? [])260                current = 0261            }262        }263    }264265    private func step(_ delta: Int) {266        guard !matches.isEmpty else { return }267        current = (current + delta + matches.count) % matches.count268    }269}270271struct PDFKitView: UIViewRepresentable {272    let document: PDFDocument273    var highlights: [PDFSelection]274    var current: PDFSelection?275276    func makeUIView(context: Context) -> PDFView {277        let view = PDFView()278        view.autoScales = true279        view.displayMode = .singlePageContinuous280        view.displayDirection = .vertical281        view.backgroundColor = .clear282        view.document = document283        return view284    }285286    func updateUIView(_ view: PDFView, context: Context) {287        if view.document !== document { view.document = document }288        for selection in highlights { selection.color = selection === current ? .systemOrange : UIColor.systemYellow.withAlphaComponent(0.6) }289        view.highlightedSelections = highlights.isEmpty ? nil : highlights290        if let current {291            view.go(to: current)292        }293    }294}295
Files main
Menu

Theme