SPB Git

Repository Public

PDFAnnotator.swift 8.8 KB 176 lines swift

1// SP Drive iOS2// File: Features/MyDrive/PDFAnnotator.swift3// Description: PDF annotation with Apple Pencil (or a finger): a PencilKit canvas over each page of a PDFKit view. Saving flattens the4//              strokes into a copy of the document and hands it to the sync engine as a NEW VERSION of the file, based on the version5//              that was opened (so a concurrent change on the Drive raises a conflict instead of being overwritten).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import PDFKit10import PencilKit11import SwiftUI12import UIKit1314/// Flattening strokes into a PDF. Separate from the interface so it is tested on its own.15enum PDFInk {16    /// An annotation covering a page that draws a PencilKit drawing made in the page's top-left coordinate space.17    final class InkAnnotation: PDFAnnotation {18        var drawing = PKDrawing()19        override func draw(with box: PDFDisplayBox, in context: CGContext) {20            guard !drawing.strokes.isEmpty, let page else { return }21            let pageBounds = page.bounds(for: box)22            let ink = drawing.bounds.intersection(CGRect(origin: .zero, size: pageBounds.size))23            guard !ink.isNull, ink.width > 0, ink.height > 0 else { return }24            // strokes are always rendered as on white paper, whatever the interface's appearance25            var image: UIImage?26            UITraitCollection(userInterfaceStyle: .light).performAsCurrent { image = drawing.image(from: ink, scale: 3) }27            guard let cg = image?.cgImage else { return }28            context.saveGState()29            // PDF space has its origin at the bottom left30            context.draw(cg, in: CGRect(x: pageBounds.minX + ink.minX, y: pageBounds.minY + pageBounds.height - ink.maxY, width: ink.width, height: ink.height))31            context.restoreGState()32        }33    }3435    /// Writes `source` with the drawings burnt into their pages. Pages without strokes are untouched. Returns false when nothing was drawn.36    @MainActor @discardableResult37    static func flatten(_ source: URL, drawings: [Int: PKDrawing], to destination: URL) throws -> Bool {38        guard let document = PDFDocument(url: source) else { throw CocoaError(.fileReadCorruptFile) }39        var any = false40        for (index, drawing) in drawings where !drawing.strokes.isEmpty {41            guard let page = document.page(at: index) else { continue }42            let annotation = InkAnnotation(bounds: page.bounds(for: .mediaBox), forType: .stamp, withProperties: nil)43            annotation.drawing = drawing44            page.addAnnotation(annotation)45            any = true46        }47        guard any else { return false }48        try? FileManager.default.removeItem(at: destination)49        guard document.write(to: destination, withOptions: [.burnInAnnotationsOption: true]) else { throw CocoaError(.fileWriteUnknown) }50        return true51    }52}5354struct PDFAnnotator: View {55    @Environment(AppModel.self) private var model56    @Environment(\.dismiss) private var dismiss57    let item: DriveItem58    let url: URL59    @State private var canvas = AnnotationCanvas()60    @State private var saving = false61    @State private var confirmDiscard = false62    @AppStorage("annotate.fingerDraws") private var fingerDraws = UIDevice.current.userInterfaceIdiom != .pad6364    var body: some View {65        NavigationStack {66            PDFCanvasView(url: url, canvas: canvas, fingerDraws: fingerDraws)67                .ignoresSafeArea(edges: .bottom)68                .navigationTitle(item.name)69                .navigationBarTitleDisplayMode(.inline)70                .toolbar {71                    ToolbarItem(placement: .cancellationAction) { Button("Fermer") { if canvas.hasInk { confirmDiscard = true } else { dismiss() } }.accessibilityIdentifier("annotate.close") }72                    ToolbarItemGroup(placement: .topBarTrailing) {73                        Button { canvas.undo() } label: { Label("Annuler le trait", systemImage: "arrow.uturn.backward") }.disabled(!canvas.hasInk).keyboardShortcut("z", modifiers: .command)74                        Toggle(isOn: $fingerDraws) { Label("Dessiner au doigt", systemImage: "hand.draw") }.accessibilityIdentifier("annotate.finger")75                        Button { save() } label: { if saving { ProgressView() } else { Text("Enregistrer").bold() } }76                            .disabled(!canvas.hasInk || saving).keyboardShortcut("s", modifiers: .command).accessibilityIdentifier("annotate.save")77                    }78                }79                .confirmationDialog("Abandonner les annotations ?", isPresented: $confirmDiscard, titleVisibility: .visible) {80                    Button("Abandonner", role: .destructive) { dismiss() }81                    Button("Continuer à annoter", role: .cancel) {}82                }83        }84        .interactiveDismissDisabled(canvas.hasInk)85        .presentationSizing(.page)86    }8788    private func save() {89        saving = true90        Task {91            await model.perform(success: model.network.online ? String(localized: "Annotations enregistrées comme nouvelle version. Envoi vers le Drive…") : String(localized: "Annotations enregistrées. L’envoi se fera au retour du réseau.")) {92                let out = FileManager.default.temporaryDirectory.appendingPathComponent("annotated-\(UUID().uuidString).pdf")93                defer { try? FileManager.default.removeItem(at: out) }94                guard try PDFInk.flatten(url, drawings: canvas.drawings, to: out) else { return }95                // the existing path for a new version: it names the version the edit started from (`baseVersionId`)96                try await model.engine.replaceContent(of: model.store.item(item.id)?.id ?? item.id, with: out)97                Haptics.success()98                dismiss()99            }100            saving = false101        }102    }103}104105/// The drawings of each page, shared between the PDF view's overlays and the toolbar.106@MainActor @Observable107final class AnnotationCanvas {108    private(set) var hasInk = false109    @ObservationIgnored var views: [Int: PKCanvasView] = [:]110    var drawings: [Int: PKDrawing] { views.mapValues(\.drawing) }111    func refresh() { let ink = views.values.contains { !$0.drawing.strokes.isEmpty }; if ink != hasInk { hasInk = ink } }112    func undo() {113        // the page drawn on last: the one whose newest stroke is the most recent114        guard let target = views.values.filter({ !$0.drawing.strokes.isEmpty }).max(by: { ($0.drawing.strokes.last?.path.creationDate ?? .distantPast) < ($1.drawing.strokes.last?.path.creationDate ?? .distantPast) }) else { return }115        var d = target.drawing116        d.strokes.removeLast()117        target.drawing = d118        refresh()119    }120}121122private struct PDFCanvasView: UIViewRepresentable {123    let url: URL124    let canvas: AnnotationCanvas125    let fingerDraws: Bool126127    func makeCoordinator() -> Coordinator { Coordinator(canvas: canvas) }128129    func makeUIView(context: Context) -> PDFView {130        let view = PDFView()131        view.autoScales = true132        view.displayMode = .singlePageContinuous133        view.displayDirection = .vertical134        view.pageOverlayViewProvider = context.coordinator135        view.isInMarkupMode = true // overlays receive touches136        view.document = PDFDocument(url: url)137        view.backgroundColor = .secondarySystemBackground138        context.coordinator.fingerDraws = fingerDraws139        context.coordinator.picker.setVisible(true, forFirstResponder: view)140        return view141    }142143    func updateUIView(_ view: PDFView, context: Context) {144        context.coordinator.fingerDraws = fingerDraws145        for c in canvas.views.values { c.drawingPolicy = fingerDraws ? .anyInput : .pencilOnly }146    }147148    @MainActor149    final class Coordinator: NSObject, @preconcurrency PDFPageOverlayViewProvider, PKCanvasViewDelegate {150        let canvas: AnnotationCanvas151        let picker = PKToolPicker()152        var fingerDraws = true153        init(canvas: AnnotationCanvas) { self.canvas = canvas }154155        func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {156            guard let index = view.document?.index(for: page) else { return nil }157            if let existing = canvas.views[index] { return existing }158            let c = PKCanvasView()159            c.backgroundColor = .clear160            c.isOpaque = false161            c.drawingPolicy = fingerDraws ? .anyInput : .pencilOnly162            c.tool = PKInkingTool(.pen, color: .systemRed, width: 3)163            c.delegate = self164            c.overrideUserInterfaceStyle = .light165            c.accessibilityIdentifier = "annotate.canvas.\(index)"166            picker.addObserver(c)167            picker.setVisible(true, forFirstResponder: c)168            canvas.views[index] = c169            if index == 0 { DispatchQueue.main.async { c.becomeFirstResponder() } }170            return c171        }172173        func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) { canvas.refresh() }174    }175}176
Files main
Menu

Theme