Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/MediaBlocks/PDFCoordinateMapping.swift3// Description: The mapping between PDF page space (user space of PDFKit: origin bottom-left of the media box, unrotated,4// the visible box may start anywhere) and the normalised rectangles of a `pdf` node's annotations (0…1,5// origin top-left of the page AS DISPLAYED, i.e. inside the crop box and after the page rotation). Pure and6// unit-tested for offset boxes and the four rotations; also the pure description of how a node annotation7// becomes a PDFKit annotation and back.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import CoreGraphics12import Foundation13import SPNotesDocument1415/// The visible box of a page and its rotation.16public struct PDFPageGeometry: Sendable, Equatable {17 /// The displayed box (crop box) in page space.18 public var box: CGRect19 /// Clockwise rotation of the page when displayed: 0, 90, 180 or 270 (any multiple of 90 is normalised).20 public var rotation: Int2122 public init(box: CGRect, rotation: Int = 0) {23 self.box = box.standardized24 self.rotation = ((rotation % 360) + 360) % 360 / 90 * 9025 }2627 /// Size of the page as displayed (width and height swap at 90° and 270°).28 public var displaySize: CGSize { rotation % 180 == 0 ? box.size : CGSize(width: box.height, height: box.width) }2930 /// Page space → normalised display position (0…1, origin top-left).31 public func normalized(_ point: CGPoint) -> CGPoint {32 guard box.width > 0, box.height > 0 else { return .zero }33 let u = (point.x - box.minX) / box.width, v = (point.y - box.minY) / box.height // origin bottom-left, unrotated34 switch rotation {35 case 90: return CGPoint(x: v, y: u)36 case 180: return CGPoint(x: 1 - u, y: v)37 case 270: return CGPoint(x: 1 - v, y: 1 - u)38 default: return CGPoint(x: u, y: 1 - v)39 }40 }4142 /// Normalised display position → page space.43 public func pagePoint(_ normalized: CGPoint) -> CGPoint {44 let u: CGFloat, v: CGFloat45 switch rotation {46 case 90: (u, v) = (normalized.y, normalized.x)47 case 180: (u, v) = (1 - normalized.x, normalized.y)48 case 270: (u, v) = (1 - normalized.y, 1 - normalized.x)49 default: (u, v) = (normalized.x, 1 - normalized.y)50 }51 return CGPoint(x: box.minX + u * box.width, y: box.minY + v * box.height)52 }5354 /// A rectangle of page space → the normalised rectangle that covers it on the displayed page.55 public func normalized(_ rect: CGRect) -> PDFRect {56 let a = normalized(CGPoint(x: rect.minX, y: rect.minY)), b = normalized(CGPoint(x: rect.maxX, y: rect.maxY))57 return PDFRect(x: Double(min(a.x, b.x)), y: Double(min(a.y, b.y)), width: Double(abs(a.x - b.x)), height: Double(abs(a.y - b.y)))58 }5960 /// A normalised rectangle → page space.61 public func pageRect(_ rect: PDFRect) -> CGRect {62 let a = pagePoint(CGPoint(x: rect.x, y: rect.y)), b = pagePoint(CGPoint(x: rect.x + rect.width, y: rect.y + rect.height))63 return CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(a.x - b.x), height: abs(a.y - b.y))64 }6566 /// Clamps a normalised rectangle to the page.67 public static func clamped(_ rect: PDFRect) -> PDFRect {68 let x0 = min(1, max(0, rect.x)), y0 = min(1, max(0, rect.y))69 let x1 = min(1, max(0, rect.x + rect.width)), y1 = min(1, max(0, rect.y + rect.height))70 return PDFRect(x: x0, y: y0, width: max(0, x1 - x0), height: max(0, y1 - y0))71 }72}7374/// What a text selection (or a stroke) gives before it becomes an annotation of the node.75public struct PDFSelectionCapture: Sendable, Equatable {76 /// 1-based page number.77 public var page: Int78 /// One normalised rectangle per selected line.79 public var rects: [PDFRect]80 public var text: String8182 public init(page: Int, rects: [PDFRect], text: String) {83 self.page = page84 self.rects = rects85 self.text = text86 }8788 /// From the line rectangles of a selection in page space.89 public init(page: Int, lineRects: [CGRect], text: String, geometry: PDFPageGeometry) {90 self.page = page91 rects = lineRects.filter { $0.width > 0 && $0.height > 0 }.map { PDFPageGeometry.clamped(geometry.normalized($0)) }92 self.text = text.replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespacesAndNewlines)93 }9495 public var isEmpty: Bool { rects.isEmpty }96}9798/// How a node annotation is drawn with PDFKit, in page space — the node → `PDFAnnotation` direction, as data.99public struct PDFAnnotationPlacement: Sendable, Equatable {100 public var id: String101 public var kind: SPNotesDocument.PDFAnnotationKind102 /// Union of the rectangles (or of the stroke), the PDFKit annotation's `bounds`.103 public var bounds: CGRect104 /// One rectangle per line (highlight, note).105 public var lineRects: [CGRect]106 /// The stroke (ink).107 public var path: [CGPoint]108 public var color: String109 /// The note, shown by PDFKit as the annotation's contents.110 public var contents: String111112 /// Quadrilateral points of a highlight relative to `bounds.origin`, PDFKit order per line: top-left, top-right,113 /// bottom-left, bottom-right.114 public var quadrilateralPoints: [CGPoint] {115 lineRects.flatMap { rect -> [CGPoint] in116 let r = rect.offsetBy(dx: -bounds.minX, dy: -bounds.minY)117 return [CGPoint(x: r.minX, y: r.maxY), CGPoint(x: r.maxX, y: r.maxY), CGPoint(x: r.minX, y: r.minY), CGPoint(x: r.maxX, y: r.minY)]118 }119 }120121 public init?(_ annotation: SPNotesDocument.PDFAnnotation, geometry: PDFPageGeometry) {122 id = annotation.id123 kind = annotation.kind124 color = annotation.color125 contents = annotation.note126 lineRects = annotation.rects.map(geometry.pageRect)127 path = (annotation.ink ?? []).map { geometry.pagePoint(CGPoint(x: $0.x, y: $0.y)) }128 var union = lineRects.reduce(CGRect.null) { $0.union($1) }129 if kind == .ink, !path.isEmpty {130 let xs = path.map(\.x), ys = path.map(\.y)131 union = CGRect(x: xs.min()!, y: ys.min()!, width: xs.max()! - xs.min()!, height: ys.max()! - ys.min()!).insetBy(dx: -2, dy: -2)132 }133 guard !union.isNull, union.width > 0 || union.height > 0 else { return nil }134 bounds = union135 }136}137138/// The `PDFAnnotation` → node direction: a highlight or an ink annotation that exists in the file (or was just made with139/// PDFKit) expressed as a node annotation.140public enum PDFAnnotationImport {141 /// - Parameters:142 /// - quadrilateralPoints: relative to `bounds.origin`, four per line (PDFKit); empty = the bounds are the one line.143 public static func highlight(page: Int, bounds: CGRect, quadrilateralPoints: [CGPoint], color: String, text: String, note: String, geometry: PDFPageGeometry,144 id: String = UUID().uuidString.lowercased(), createdAt: Date = Date()) -> SPNotesDocument.PDFAnnotation {145 var lines: [CGRect] = []146 var index = 0147 while index + 3 < quadrilateralPoints.count {148 let quad = quadrilateralPoints[index..<(index + 4)].map { CGPoint(x: $0.x + bounds.minX, y: $0.y + bounds.minY) }149 let xs = quad.map(\.x), ys = quad.map(\.y)150 lines.append(CGRect(x: xs.min()!, y: ys.min()!, width: xs.max()! - xs.min()!, height: ys.max()! - ys.min()!))151 index += 4152 }153 if lines.isEmpty { lines = [bounds] }154 return SPNotesDocument.PDFAnnotation(id: id, page: page, kind: note.isEmpty ? .highlight : .note, color: color,155 rects: lines.map { PDFPageGeometry.clamped(geometry.normalized($0)) }, text: text, note: note, createdAt: createdAt)156 }157158 public static func ink(page: Int, path: [CGPoint], color: String, geometry: PDFPageGeometry, id: String = UUID().uuidString.lowercased(), createdAt: Date = Date()) -> SPNotesDocument.PDFAnnotation? {159 let points = path.map(geometry.normalized).map { PDFPoint(x: Double(min(1, max(0, $0.x))), y: Double(min(1, max(0, $0.y)))) }160 guard points.count >= 2 else { return nil }161 let xs = points.map(\.x), ys = points.map(\.y)162 let box = PDFRect(x: xs.min()!, y: ys.min()!, width: xs.max()! - xs.min()!, height: ys.max()! - ys.min()!)163 return SPNotesDocument.PDFAnnotation(id: id, page: page, kind: .ink, color: color, rects: [box], ink: points, createdAt: createdAt)164 }165}166