SPB Git

Repository Public

Importers.swift 12.9 KB 264 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Drive pour iPhone et iPad9// File             : Features/MyDrive/Importers.swift10// Description      : Capture sources for the « add » menu: the camera (one11//                    photo) and the document scanner (pages assembled into a12//                    PDF with PDFKit).13// Module           : Features14// Repository       : https://git.spboucher.ai/sp-drive-ios15// Created          : 2026-11-1916// Last Modified    : 2026-11-1917//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import PDFKit91import SwiftUI92import UIKit93import VisionKit9495private func captureURL(_ prefix: String, ext: String) -> URL {96    let dir = FileManager.default.temporaryDirectory.appendingPathComponent("capture-\(UUID().uuidString)", isDirectory: true)97    try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)98    let stamp = Date.now.formatted(.iso8601.year().month().day().dateSeparator(.dash)) + " " + Date.now.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits).second(.twoDigits)).replacingOccurrences(of: ":", with: ".")99    return dir.appendingPathComponent("\(prefix) \(stamp).\(ext)")100}101102struct CameraPicker: UIViewControllerRepresentable {103    @Environment(\.dismiss) private var dismiss104    let captured: (URL) -> Void105106    func makeCoordinator() -> Coordinator { Coordinator(self) }107    func makeUIViewController(context: Context) -> UIImagePickerController {108        let p = UIImagePickerController()109        p.sourceType = .camera110        p.delegate = context.coordinator111        return p112    }113    func updateUIViewController(_ controller: UIImagePickerController, context: Context) {}114115    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {116        let parent: CameraPicker117        init(_ parent: CameraPicker) { self.parent = parent }118119        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {120            if let image = info[.originalImage] as? UIImage, let data = image.jpegData(compressionQuality: 0.92) {121                let url = captureURL("Photo", ext: "jpg")122                if (try? data.write(to: url)) != nil { parent.captured(url) }123            }124            parent.dismiss()125        }126        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { parent.dismiss() }127    }128}129130/// The pages of one scan, as the document camera delivered them (cropped and straightened by VisionKit).131struct ScannedPages: Identifiable {132    let id = UUID()133    let images: [UIImage]134}135136extension ScanFixtures {137    /// Stand-in for the camera in the simulator (UI tests only).138    static func pages() -> [UIImage] { invoice().map { UIImage(cgImage: $0) } }139}140141/// The system's document camera: multi-page, automatic edge detection, cropping and perspective correction come from VisionKit.142struct DocumentScanner: UIViewControllerRepresentable {143    @Environment(\.dismiss) private var dismiss144    let scanned: ([UIImage]) -> Void145    @MainActor static var isAvailable: Bool { VNDocumentCameraViewController.isSupported }146147    func makeCoordinator() -> Coordinator { Coordinator(self) }148    func makeUIViewController(context: Context) -> VNDocumentCameraViewController {149        let c = VNDocumentCameraViewController()150        c.delegate = context.coordinator151        return c152    }153    func updateUIViewController(_ controller: VNDocumentCameraViewController, context: Context) {}154155    final class Coordinator: NSObject, VNDocumentCameraViewControllerDelegate {156        let parent: DocumentScanner157        init(_ parent: DocumentScanner) { self.parent = parent }158159        func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {160            let pages = (0..<scan.pageCount).map { scan.imageOfPage(at: $0) }161            parent.dismiss()162            if !pages.isEmpty { parent.scanned(pages) }163        }164        func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) { parent.dismiss() }165        func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFailWithError error: Error) { parent.dismiss() }166    }167}168169/// After the camera: name, destination folder, searchable text or not — then the PDF is built on the device and joins the upload queue.170struct ScanReviewSheet: View {171    @Environment(AppModel.self) private var model172    @Environment(\.dismiss) private var dismiss173    let pages: ScannedPages174    @State private var name = (ScanPipeline.defaultName() as NSString).deletingPathExtension175    @AppStorage("scan.ocr") private var ocr = true176    @State private var destination: String177    @State private var pickingFolder = false178    @State private var working = false179    @State private var progress: (page: Int, of: Int)?180181    init(pages: ScannedPages, folderID: String) { self.pages = pages; _destination = State(initialValue: folderID) }182183    var body: some View {184        let folder = model.store.item(destination)185        NavigationStack {186            Form {187                Section {188                    ScrollView(.horizontal, showsIndicators: false) {189                        HStack(spacing: SPDTheme.Space.md) {190                            ForEach(Array(pages.images.enumerated()), id: \.offset) { index, image in191                                Image(uiImage: image).resizable().scaledToFit().frame(height: 150)192                                    .clipShape(RoundedRectangle(cornerRadius: SPDTheme.Radius.sm, style: .continuous))193                                    .overlay(RoundedRectangle(cornerRadius: SPDTheme.Radius.sm, style: .continuous).strokeBorder(SPDTheme.Palette.hairline, lineWidth: 0.5))194                                    .accessibilityLabel(Text("Page \(index + 1) sur \(pages.images.count)"))195                            }196                        }197                        .padding(.vertical, 4)198                    }199                } header: {200                    Text(pages.images.count == 1 ? "1 page" : "\(pages.images.count) pages")201                }202                Section("Document") {203                    TextField("Nom du document", text: $name).textInputAutocapitalization(.sentences).accessibilityIdentifier("scan.name")204                    Button { pickingFolder = true } label: {205                        LabeledContent { Text(folder?.parentID == nil ? String(localized: "Mon Drive") : (folder?.name ?? "")).foregroundStyle(.secondary) } label: { Label("Dossier", systemImage: "folder") }206                    }207                    .foregroundStyle(.primary)208                    .accessibilityIdentifier("scan.destination")209                }210                Section {211                    Toggle(isOn: $ocr) { Label("Texte cherchable (OCR)", systemImage: "text.viewfinder") }.accessibilityIdentifier("scan.ocr")212                } footer: {213                    Text("La reconnaissance du texte se fait sur cet appareil : aucune image n’est envoyée ailleurs que dans ton Drive. Le PDF garde l’image de chaque page ; le texte reconnu est ajouté en couche invisible pour la recherche et la sélection.")214                }215                Section {216                    Button { save() } label: {217                        HStack {218                            Label("Enregistrer dans le Drive", systemImage: "arrow.up.doc.fill").frame(maxWidth: .infinity)219                            if working { ProgressView() }220                        }221                    }222                    .buttonStyle(GradientButtonStyle())223                    .listRowInsets(EdgeInsets()).listRowBackground(Color.clear)224                    .disabled(working || name.trimmingCharacters(in: .whitespaces).isEmpty)225                    .accessibilityIdentifier("scan.save")226                } footer: {227                    if let progress { Text(ocr ? "Reconnaissance du texte… page \(progress.page) sur \(progress.of)" : "Assemblage du PDF… page \(progress.page) sur \(progress.of)") }228                }229            }230            .navigationTitle("Numérisation")231            .navigationBarTitleDisplayMode(.inline)232            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() }.disabled(working) } }233            .sheet(isPresented: $pickingFolder) { FolderPicker(title: String(localized: "Enregistrer dans"), excluding: [], startAt: destination) { destination = $0 } }234        }235        .interactiveDismissDisabled(working)236    }237238    private func save() {239        working = true240        let images = pages.images.compactMap(\.cgImage)241        let options = ScanPipeline.Options(ocr: ocr)242        let fileName = LocalFiles.safeName(name.trimmingCharacters(in: .whitespaces)) + ".pdf"243        let dest = destination244        Task {245            await model.perform(success: String(localized: "Numérisation ajoutée à la file d’envoi")) {246                let dir = FileManager.default.temporaryDirectory.appendingPathComponent("scan-\(UUID().uuidString)", isDirectory: true)247                try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)248                let url = dir.appendingPathComponent(fileName)249                let (stream, continuation) = AsyncStream<(Int, Int)>.makeStream()250                let watcher = Task { for await p in stream { progress = p } }251                defer { watcher.cancel() }252                _ = try await Task.detached(priority: .userInitiated) {253                    defer { continuation.finish() }254                    return try ScanPipeline.makePDF(pages: images, to: url, options: options) { page, of in continuation.yield((page, of)) }255                }.value256                _ = try await model.engine.importFile(at: url, named: fileName, into: dest, move: true)257                Haptics.success()258                dismiss()259            }260            working = false261        }262    }263}264
Files main
Menu

Theme