Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/MediaBlocks/PDFBlockModel.swift3// Description: View model of a `pdf` node: loads the attachment into PDFKit, keeps the current page, turns a text4// selection or a stroke into node annotations (normalised rectangles) and node annotations into PDFKit5// annotations on the pages. Edits go back to the caller as updated `PDFBlock` attributes; the editor owns6// saving the page.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import CoreGraphics11import Foundation12import Observation13import PDFKit14import SPNotesDesign15import SPNotesDocument16#if os(macOS)17import AppKit18typealias PDFPlatformColor = NSColor19typealias PDFPlatformPath = NSBezierPath20#else21import UIKit22typealias PDFPlatformColor = UIColor23typealias PDFPlatformPath = UIBezierPath24#endif2526@Observable @MainActor27public final class PDFBlockModel {28 public enum Tool: String, Sendable, CaseIterable { case read, ink }2930 /// Highlight colours offered (stored in the node as `#rrggbb`).31 public static let colors = ["#ffd54a", "#7cc4ff", "#8fe3a0", "#ff9eb0", "#cc272e"]32 /// Marks the PDFKit annotations this model created from the node (never the file's own annotations).33 static let marker = "spn-node"3435 public private(set) var block: PDFBlock36 public private(set) var phase: LoadPhase = .idle37 public var actionFailure: FeatureFailure?38 public private(set) var document: PDFDocument?39 public private(set) var pageCount = 040 /// 1-based page shown.41 public private(set) var page: Int42 public var tool: Tool = .read43 public var color = PDFBlockModel.colors[0]44 /// The current text selection, ready to become a highlight or a note (nil = nothing selected).45 public var selection: PDFSelectionCapture?46 public var selectedAnnotationId: String?47 public var showsAnnotations = false48 /// Bumped whenever the PDFKit view must go to `page` or redraw its annotations.49 public private(set) var revision = 05051 /// Set by the PDFKit view: converts overlay points to page space (ink).52 @ObservationIgnored var bridge: PDFViewBridge?53 @ObservationIgnored private let loader: FeatureAttachmentLoader54 @ObservationIgnored private let onChange: (PDFBlock) -> Void55 @ObservationIgnored private let now: @Sendable () -> Date56 @ObservationIgnored private let initialPage: Int5758 public init(block: PDFBlock, loader: FeatureAttachmentLoader, now: @escaping @Sendable () -> Date = { Date() }, onChange: @escaping (PDFBlock) -> Void = { _ in }) {59 self.block = block60 self.loader = loader61 self.onChange = onChange62 self.now = now63 page = block.page64 initialPage = block.page65 }6667 public var annotations: [SPNotesDocument.PDFAnnotation] { block.annotations }68 public var canGoBack: Bool { page > 1 }69 public var canGoForward: Bool { page < pageCount }7071 public func load() async {72 guard let id = block.attachmentId else {73 phase = .failed(FeatureFailure(kind: .notFound, message: L("Ce bloc PDF n'a pas encore de fichier.")))74 return75 }76 phase = .loading77 do {78 let data = try await loader.data(id: id)79 guard let document = PDFDocument(data: data), document.pageCount > 0 else {80 phase = .failed(FeatureFailure(kind: .other, message: L("Ce fichier n'est pas un PDF lisible.")))81 return82 }83 load(document)84 } catch {85 phase = .failed(FeatureFailure(error))86 }87 }8889 /// Uses a document that is already in memory.90 public func load(_ document: PDFDocument) {91 self.document = document92 pageCount = document.pageCount93 page = min(max(1, block.page), max(1, pageCount))94 syncAnnotations()95 phase = .loaded96 revision += 197 }9899 // MARK: Pages100101 public func go(to page: Int) {102 let target = min(max(1, page), max(1, pageCount))103 guard target != self.page else { return }104 self.page = target105 selection = nil106 revision += 1107 }108109 /// The PDFKit view scrolled by itself.110 func pageShown(_ page: Int) {111 guard page != self.page, page >= 1, page <= max(1, pageCount) else { return }112 self.page = page113 }114115 /// Writes the page being read into the node (`page` attr). Called when the view goes away: turning pages is not an116 /// edit of the note by itself.117 public func commitPage() {118 guard block.page != page else { return }119 block.page = page120 onChange(block)121 }122123 public func geometry(page: Int) -> PDFPageGeometry? {124 guard let pdfPage = document?.page(at: page - 1) else { return nil }125 return PDFPageGeometry(box: pdfPage.bounds(for: .cropBox), rotation: pdfPage.rotation)126 }127128 // MARK: Selection → annotations129130 /// Reads a PDFKit selection (one rectangle per line and per page; the first page wins).131 public func capture(_ pdfSelection: PDFSelection?) {132 guard let pdfSelection, let document, let first = pdfSelection.pages.first, let geometry = geometry(page: document.index(for: first) + 1) else { selection = nil; return }133 let lines = pdfSelection.selectionsByLine().filter { $0.pages.contains(first) }.map { $0.bounds(for: first) }134 let capture = PDFSelectionCapture(page: document.index(for: first) + 1, lineRects: lines, text: pdfSelection.string ?? "", geometry: geometry)135 selection = capture.isEmpty ? nil : capture136 }137138 /// Turns the current selection into a highlight (or a note when `note` is not empty).139 @discardableResult140 public func annotateSelection(note: String = "") -> String? {141 guard let selection, !selection.isEmpty else { return nil }142 let trimmed = note.trimmingCharacters(in: .whitespacesAndNewlines)143 let annotation = SPNotesDocument.PDFAnnotation(page: selection.page, kind: trimmed.isEmpty ? .highlight : .note, color: color, rects: selection.rects,144 text: selection.text, note: trimmed, createdAt: now())145 block.add(annotation)146 self.selection = nil147 selectedAnnotationId = annotation.id148 changed()149 return annotation.id150 }151152 /// Adds a freehand stroke drawn on a page (points in PAGE space).153 @discardableResult154 public func addInk(page: Int, pagePoints: [CGPoint]) -> String? {155 guard let geometry = geometry(page: page), let annotation = PDFAnnotationImport.ink(page: page, path: pagePoints, color: color, geometry: geometry, createdAt: now()) else { return nil }156 block.add(annotation)157 changed()158 return annotation.id159 }160161 public func setNote(_ note: String, of id: String) {162 guard var annotation = block.annotations.first(where: { $0.id == id }), annotation.note != note else { return }163 annotation.note = note164 if annotation.kind != .ink { annotation.kind = note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? .highlight : .note }165 block.update(annotation)166 changed()167 }168169 public func setColor(_ color: String, of id: String) {170 guard var annotation = block.annotations.first(where: { $0.id == id }), annotation.color != color else { return }171 annotation.color = color172 block.update(annotation)173 changed()174 }175176 public func remove(_ id: String) {177 guard block.remove(annotationId: id) else { return }178 if selectedAnnotationId == id { selectedAnnotationId = nil }179 changed()180 }181182 public func show(_ annotation: SPNotesDocument.PDFAnnotation) {183 selectedAnnotationId = annotation.id184 go(to: annotation.page)185 }186187 private func changed() {188 block.page = page189 syncAnnotations()190 revision += 1191 onChange(block)192 }193194 // MARK: Node annotations → PDFKit annotations195196 /// Rebuilds, on every page, the PDFKit annotations that mirror the node (the file's own annotations are left alone).197 func syncAnnotations() {198 guard let document else { return }199 for index in 0..<document.pageCount {200 guard let pdfPage = document.page(at: index) else { continue }201 for existing in pdfPage.annotations where existing.userName == Self.marker { pdfPage.removeAnnotation(existing) }202 let geometry = PDFPageGeometry(box: pdfPage.bounds(for: .cropBox), rotation: pdfPage.rotation)203 for annotation in block.annotations(onPage: index + 1) {204 guard let placement = PDFAnnotationPlacement(annotation, geometry: geometry) else { continue }205 pdfPage.addAnnotation(Self.pdfKitAnnotation(placement))206 }207 }208 }209210 /// The page as PDFKit draws it — content, the file's annotations and the node's — at up to `maxPixel` on its211 /// longest side (white paper, rotation applied).212 public func pageImage(page: Int, maxPixel: CGFloat = 1600) -> CGImage? {213 guard let pdfPage = document?.page(at: page - 1) else { return nil }214 let box = pdfPage.bounds(for: .cropBox)215 let size = PDFPageGeometry(box: box, rotation: pdfPage.rotation).displaySize216 guard size.width > 0, size.height > 0 else { return nil }217 let scale = min(maxPixel / max(size.width, size.height), 4)218 let width = Int((size.width * scale).rounded()), height = Int((size.height * scale).rounded())219 guard width > 0, height > 0, let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),220 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }221 context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))222 context.fill(CGRect(x: 0, y: 0, width: width, height: height))223 context.scaleBy(x: scale, y: scale)224 pdfPage.draw(with: .cropBox, to: context)225 return context.makeImage()226 }227228 /// The placements of a page (what `syncAnnotations` draws), for tests and custom renderers.229 public func placements(page: Int) -> [PDFAnnotationPlacement] {230 guard let geometry = geometry(page: page) else { return [] }231 return block.annotations(onPage: page).compactMap { PDFAnnotationPlacement($0, geometry: geometry) }232 }233234 static func platformColor(_ hex: String, alpha: CGFloat = 1) -> PDFPlatformColor {235 let rgb = NVRGB(hexString: hex) ?? NVRGB(hex: 0xFFD54A)236 return PDFPlatformColor(red: rgb.red, green: rgb.green, blue: rgb.blue, alpha: alpha)237 }238239 static func pdfKitAnnotation(_ placement: PDFAnnotationPlacement) -> PDFKit.PDFAnnotation {240 let annotation: PDFKit.PDFAnnotation241 if placement.kind == .ink {242 annotation = PDFKit.PDFAnnotation(bounds: placement.bounds, forType: .ink, withProperties: nil)243 let path = PDFPlatformPath()244 for (index, point) in placement.path.enumerated() {245 let local = CGPoint(x: point.x - placement.bounds.minX, y: point.y - placement.bounds.minY)246 #if os(macOS)247 if index == 0 { path.move(to: local) } else { path.line(to: local) }248 #else249 if index == 0 { path.move(to: local) } else { path.addLine(to: local) }250 #endif251 }252 path.lineWidth = 2253 annotation.add(path)254 let border = PDFBorder()255 border.lineWidth = 2256 annotation.border = border257 annotation.color = platformColor(placement.color)258 } else {259 annotation = PDFKit.PDFAnnotation(bounds: placement.bounds, forType: .highlight, withProperties: nil)260 annotation.quadrilateralPoints = placement.quadrilateralPoints.map { NSValue(pdfPoint: $0) }261 annotation.color = platformColor(placement.color, alpha: 0.5)262 if !placement.contents.isEmpty { annotation.contents = placement.contents }263 }264 annotation.userName = marker265 annotation.setValue(placement.id, forAnnotationKey: PDFAnnotationKey(rawValue: "/NM"))266 return annotation267 }268269 /// Imports a highlight that PDFKit holds (the file's own, or one made by another tool) as a node annotation.270 public func importHighlight(_ annotation: PDFKit.PDFAnnotation, on pdfPage: PDFPage) -> SPNotesDocument.PDFAnnotation? {271 guard let document, let geometry = geometry(page: document.index(for: pdfPage) + 1) else { return nil }272 let quads = (annotation.quadrilateralPoints ?? []).map(\.pdfPointValue)273 let hex = NVRGB(platform: annotation.color)?.hexString ?? Self.colors[0]274 let text = pdfPage.selection(for: annotation.bounds)?.string ?? ""275 return PDFAnnotationImport.highlight(page: document.index(for: pdfPage) + 1, bounds: annotation.bounds, quadrilateralPoints: quads, color: String(hex.prefix(7)).lowercased(),276 text: text.replacingOccurrences(of: "\n", with: " "), note: annotation.contents ?? "", geometry: geometry, createdAt: now())277 }278}279280extension NSValue {281 convenience init(pdfPoint: CGPoint) {282 #if os(macOS)283 self.init(point: pdfPoint)284 #else285 self.init(cgPoint: pdfPoint)286 #endif287 }288289 var pdfPointValue: CGPoint {290 #if os(macOS)291 pointValue292 #else293 cgPointValue294 #endif295 }296}297298extension NVRGB {299 init?(platform color: PDFPlatformColor) {300 #if os(macOS)301 guard let rgb = color.usingColorSpace(.sRGB) else { return nil }302 self.init(red: rgb.redComponent, green: rgb.greenComponent, blue: rgb.blueComponent)303 #else304 var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0305 guard color.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil }306 self.init(red: r, green: g, blue: b)307 #endif308 }309}310