Repository Public
1// SP Notes iOS2// File: Features/PDF/PDFAnnotationModel.swift3// Description: State of the PDF annotation screen: the `pdf` block, its document, the current tool and the annotation edits.4// Every change goes to the block's attributes through `PDFBlock.add / update / remove` and is committed to the note;5// the PDF file is only ever read.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Observation10import PDFKit11import SPNotesCore12import UIKit1314@MainActor @Observable15final class PDFAnnotationModel {16 enum Tool: String, CaseIterable, Identifiable {17 /// Read, select text (to highlight it), tap an annotation.18 case select19 /// Draw with the Pencil (or the finger).20 case ink21 /// Tap the page to pin a note.22 case note23 var id: String { rawValue }24 }2526 enum Phase: Equatable { case loading, ready, failed(String) }2728 private(set) var block: PDFBlock29 private(set) var phase = Phase.loading30 private(set) var document: PDFDocument?31 let isEditable: Bool32 var tool = Tool.select33 var highlightColor = PDFAnnotationFactory.highlightColors[0]34 var inkColor = PDFAnnotationFactory.inkColors[0]35 var inkWidth: CGFloat = 2.536 /// 1-based page shown.37 private(set) var currentPage: Int38 var pageCount: Int { document?.pageCount ?? 0 }39 /// True while the PDF view holds a text selection that can be highlighted.40 var hasSelection = false41 /// The annotation being edited in the sheet.42 var editing: PDFAnnotation?43 /// Bumped whenever the annotations change: the page overlays redraw.44 private(set) var revision = 045 /// Asks the PDF view to go to a page (1-based); consumed by the view.46 var pageRequest: Int?4748 @ObservationIgnored private let commit: (PMNode?) -> Void49 @ObservationIgnored private var committedPage: Int5051 init(block: PDFBlock, isEditable: Bool, commit: @escaping (PMNode?) -> Void) {52 self.block = block53 self.isEditable = isEditable54 self.commit = commit55 currentPage = block.page56 committedPage = block.page57 }5859 var annotations: [PDFAnnotation] { block.annotations }60 func annotations(onPage page: Int) -> [PDFAnnotation] { block.annotations(onPage: page) }6162 // MARK: loading6364 /// Opens the attachment read-only. The file is never written by this screen.65 func load(app: AppModel) async {66 guard phase == .loading else { return }67 guard let id = block.attachmentId else { phase = .failed(String(localized: "Ce bloc n’a pas de fichier PDF.")); return }68 guard let url = try? await app.localFile(forAttachment: id) else {69 phase = .failed(String(localized: "Ce PDF n’est pas sur cet appareil pour l’instant. Il sera disponible une fois téléchargé. Rien n’a été modifié."))70 return71 }72 open(url)73 }7475 func open(_ url: URL) {76 guard let document = PDFDocument(url: url), document.pageCount > 0 else {77 phase = .failed(String(localized: "Ce fichier ne peut pas être lu comme un PDF. Rien n’a été modifié."))78 return79 }80 guard !document.isLocked else {81 phase = .failed(String(localized: "Ce PDF est protégé par un mot de passe : il ne peut pas être annoté ici. Rien n’a été modifié."))82 return83 }84 self.document = document85 currentPage = min(max(1, block.page), document.pageCount)86 phase = .ready87 }8889 // MARK: pages9091 func pageChanged(to page: Int) {92 guard page >= 1, page != currentPage else { return }93 currentPage = page94 }9596 func go(toPage page: Int) {97 guard pageCount > 0 else { return }98 let target = min(max(1, page), pageCount)99 pageRequest = target100 currentPage = target101 }102103 /// Remembers the page shown in the block (called when the screen closes; a page change alone is not worth a save per swipe).104 func commitPageIfNeeded() {105 guard isEditable, currentPage != committedPage else { return }106 block.page = currentPage107 committedPage = currentPage108 commit(block.node())109 }110111 // MARK: annotations112113 private func changed() {114 block.page = currentPage115 committedPage = currentPage116 revision += 1117 commit(block.node())118 }119120 func add(_ annotation: PDFAnnotation) {121 guard isEditable else { return }122 block.add(annotation)123 changed()124 }125126 func update(_ annotation: PDFAnnotation) {127 guard isEditable, block.update(annotation) else { return }128 changed()129 }130131 func remove(_ id: String) {132 guard isEditable, block.remove(annotationId: id) else { return }133 if editing?.id == id { editing = nil }134 changed()135 }136137 /// Highlights the selection (one annotation per page it spans). Returns how many were added.138 @discardableResult139 func highlight(_ selection: PDFSelection) -> Int {140 guard isEditable, let document else { return 0 }141 let made = PDFAnnotationFactory.highlights(from: selection, in: document, color: highlightColor)142 guard !made.isEmpty else { return 0 }143 made.forEach { block.add($0) }144 changed()145 Haptics.success()146 return made.count147 }148149 /// A stroke drawn on the overlay of a page (`size` = the overlay's size).150 func addInk(viewPoints: [CGPoint], in size: CGSize, page: Int, color: String? = nil, lineWidth: CGFloat? = nil, opacity: Double = 1) {151 guard let annotation = PDFAnnotationFactory.ink(viewPoints: viewPoints, in: size, page: page, color: color ?? inkColor, lineWidth: lineWidth ?? inkWidth, opacity: opacity) else { return }152 add(annotation)153 }154155 /// Pins a note and opens it for typing.156 func addNote(at point: PDFPoint, page: Int, pageAspect: Double) {157 guard isEditable else { return }158 let annotation = PDFAnnotationFactory.note(at: point, page: page, pageAspect: pageAspect, color: highlightColor)159 add(annotation)160 editing = annotation161 tool = .select162 }163164 /// A tap on a page in the reading tool: opens the annotation under the finger, if any.165 func tap(at point: PDFPoint, page: Int) {166 if let hit = PDFAnnotationFactory.annotation(at: point, among: annotations(onPage: page)) { editing = hit }167 }168}169