Repository Public
1// SP Notes iOS2// File: Features/PDF/PDFPageGeometry.swift3// Description: Coordinates of PDF annotations. Annotations are stored in the unit square of the page as it is displayed (origin4// at its top-left, SPEC §2). This file maps between that space, the PDF page space (origin bottom-left of the media5// box, before the page's rotation, crop box possibly not at the origin) and the points of a view showing the page.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import CoreGraphics10import PDFKit11import SPNotesCore1213/// In this app `PDFAnnotation` is the annotation of a `pdf` block (SPNotesCore), never PDFKit's: nothing is written into a PDF.14typealias PDFAnnotation = SPNotesCore.PDFAnnotation1516struct PDFPageGeometry: Equatable, Sendable {17 /// The visible box of the page in page space (PDF points, y up).18 var box: CGRect19 /// Clockwise rotation applied for display: 0, 90, 180 or 270.20 var rotation: Int2122 init(box: CGRect, rotation: Int) {23 self.box = box.standardized24 self.rotation = ((rotation % 360) + 360) % 360 / 90 * 9025 }2627 init(page: PDFPage) { self.init(box: page.bounds(for: .cropBox), rotation: page.rotation) }2829 /// Size of the page as displayed (sides swapped by a quarter turn).30 var displaySize: CGSize { rotation == 90 || rotation == 270 ? CGSize(width: box.height, height: box.width) : box.size }3132 // MARK: page space ⇄ normalised (top-left of the displayed page)3334 func normalized(_ point: CGPoint) -> PDFPoint {35 guard box.width > 0, box.height > 0 else { return PDFPoint(x: 0, y: 0) }36 let u = Double((point.x - box.minX) / box.width), v = Double((point.y - box.minY) / box.height)37 switch rotation {38 case 90: return PDFPoint(x: v, y: u)39 case 180: return PDFPoint(x: 1 - u, y: v)40 case 270: return PDFPoint(x: 1 - v, y: 1 - u)41 default: return PDFPoint(x: u, y: 1 - v)42 }43 }4445 func pagePoint(_ point: PDFPoint) -> CGPoint {46 let u: Double, v: Double47 switch rotation {48 case 90: (u, v) = (point.y, point.x)49 case 180: (u, v) = (1 - point.x, point.y)50 case 270: (u, v) = (1 - point.y, 1 - point.x)51 default: (u, v) = (point.x, 1 - point.y)52 }53 return CGPoint(x: box.minX + CGFloat(u) * box.width, y: box.minY + CGFloat(v) * box.height)54 }5556 /// The normalised box of a rectangle of page space (a line of a text selection).57 func normalized(_ rect: CGRect) -> PDFRect {58 let a = normalized(CGPoint(x: rect.minX, y: rect.minY)), b = normalized(CGPoint(x: rect.maxX, y: rect.maxY))59 return PDFRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(a.x - b.x), height: abs(a.y - b.y))60 }6162 func pageRect(_ rect: PDFRect) -> CGRect {63 let a = pagePoint(PDFPoint(x: rect.x, y: rect.y)), b = pagePoint(PDFPoint(x: rect.x + rect.width, y: rect.y + rect.height))64 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))65 }6667 // MARK: normalised ⇄ view (a view of `size` showing exactly the displayed page, origin top-left)6869 static func viewPoint(_ point: PDFPoint, in size: CGSize) -> CGPoint { CGPoint(x: CGFloat(point.x) * size.width, y: CGFloat(point.y) * size.height) }7071 static func normalized(viewPoint point: CGPoint, in size: CGSize) -> PDFPoint {72 guard size.width > 0, size.height > 0 else { return PDFPoint(x: 0, y: 0) }73 return PDFPoint(x: Double(point.x / size.width), y: Double(point.y / size.height))74 }7576 static func viewRect(_ rect: PDFRect, in size: CGSize) -> CGRect {77 CGRect(x: CGFloat(rect.x) * size.width, y: CGFloat(rect.y) * size.height, width: CGFloat(rect.width) * size.width, height: CGFloat(rect.height) * size.height)78 }7980 func viewPoint(pagePoint point: CGPoint, in size: CGSize) -> CGPoint { Self.viewPoint(normalized(point), in: size) }81 func pagePoint(viewPoint point: CGPoint, in size: CGSize) -> CGPoint { pagePoint(Self.normalized(viewPoint: point, in: size)) }82}8384/// Building, drawing and hit-testing annotations. Nothing here touches the PDF file or `PDFKit.PDFAnnotation`.85enum PDFAnnotationFactory {86 /// Extra keys written with an ink annotation (unknown to the other editors, which keep them): the line width as a87 /// fraction of the page width, and the opacity of a highlighter stroke.88 static let widthField = "strokeWidth"89 static let opacityField = "opacity"9091 static let highlightColors = ["#ffd54a", "#7ee081", "#7cc4ff", "#ff9ec4"]92 static let inkColors = ["#cc272e", "#2f5ddb", "#151922", "#008b4e"]9394 static func clamp(_ value: Double) -> Double { min(1, max(0, value)) }95 static func rounded(_ value: Double) -> Double { (value * 100_000).rounded() / 100_000 }9697 static func clamped(_ rect: PDFRect) -> PDFRect {98 let x0 = clamp(rect.x), y0 = clamp(rect.y), x1 = clamp(rect.x + rect.width), y1 = clamp(rect.y + rect.height)99 return PDFRect(x: rounded(x0), y: rounded(y0), width: rounded(x1 - x0), height: rounded(y1 - y0))100 }101102 // MARK: highlight103104 /// One highlight per page of the selection: a rectangle per line, and the selected text.105 static func highlights(from selection: PDFSelection, in document: PDFDocument, color: String = highlightColors[0], createdAt: Date = Date()) -> [PDFAnnotation] {106 selection.pages.compactMap { page -> PDFAnnotation? in107 let index = document.index(for: page)108 guard index != NSNotFound else { return nil }109 let geometry = PDFPageGeometry(page: page)110 let lines = selection.selectionsByLine().filter { $0.pages.contains(page) }111 let rects = lines.map { clamped(geometry.normalized($0.bounds(for: page))) }.filter { $0.width > 0 && $0.height > 0 }112 guard !rects.isEmpty else { return nil }113 let text = lines.compactMap { $0.string?.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }.joined(separator: " ")114 return PDFAnnotation(page: index + 1, kind: .highlight, color: color, rects: rects, text: text, createdAt: createdAt)115 }116 }117118 // MARK: ink119120 /// An ink annotation from a stroke drawn on a view of `size` showing the page. The points are simplified (0.4 pt), stored121 /// normalised; `rects` is their bounding box.122 static func ink(viewPoints: [CGPoint], in size: CGSize, page: Int, color: String = inkColors[0], lineWidth: CGFloat = 2.5, opacity: Double = 1, createdAt: Date = Date()) -> PDFAnnotation? {123 let usable = viewPoints.filter { $0.x.isFinite && $0.y.isFinite }124 guard !usable.isEmpty, size.width > 0, size.height > 0 else { return nil }125 let simplified = InkStroke(points: usable.map { InkPoint(x: Double($0.x), y: Double($0.y)) }).simplified(tolerance: 0.4, pressureTolerance: 0).points126 let points = simplified.map { p -> PDFPoint in127 let n = PDFPageGeometry.normalized(viewPoint: p.cgPoint, in: size)128 return PDFPoint(x: rounded(clamp(n.x)), y: rounded(clamp(n.y)))129 }130 var annotation = PDFAnnotation(page: page, kind: .ink, color: color, rects: [boundingBox(points)], ink: points, createdAt: createdAt)131 annotation.fields[widthField] = .double(rounded(Double(lineWidth / size.width)))132 if opacity < 1 { annotation.fields[opacityField] = .double(rounded(clamp(opacity))) }133 return annotation134 }135136 static func boundingBox(_ points: [PDFPoint]) -> PDFRect {137 guard let first = points.first else { return PDFRect(x: 0, y: 0, width: 0, height: 0) }138 var minX = first.x, maxX = first.x, minY = first.y, maxY = first.y139 for p in points { minX = min(minX, p.x); maxX = max(maxX, p.x); minY = min(minY, p.y); maxY = max(maxY, p.y) }140 return PDFRect(x: rounded(minX), y: rounded(minY), width: rounded(maxX - minX), height: rounded(maxY - minY))141 }142143 static func viewPoints(of annotation: PDFAnnotation, in size: CGSize) -> [CGPoint] {144 (annotation.ink ?? []).map { PDFPageGeometry.viewPoint($0, in: size) }145 }146147 /// Line width of an ink annotation on a view of `size` (2.5 pt on a 612 pt page when the annotation does not say).148 static func lineWidth(of annotation: PDFAnnotation, in size: CGSize) -> CGFloat {149 let fraction = annotation.fields[widthField]?.doubleValue ?? 2.5 / 612150 return max(0.75, CGFloat(fraction) * size.width)151 }152153 static func opacity(of annotation: PDFAnnotation) -> CGFloat { CGFloat(clamp(annotation.fields[opacityField]?.doubleValue ?? 1)) }154155 // MARK: note156157 /// Side of the square of a note pin, as a fraction of the page width.158 static let noteSide = 0.04159160 /// A note pinned at a point of the page: `rects` is the small square around it.161 static func note(at point: PDFPoint, page: Int, pageAspect: Double = 1, text: String = "", color: String = highlightColors[0], createdAt: Date = Date()) -> PDFAnnotation {162 let w = noteSide, h = noteSide * max(0.1, pageAspect) // square on screen: the height fraction depends on the page's shape163 let x = min(max(0, point.x - w / 2), 1 - w), y = min(max(0, point.y - h / 2), 1 - h)164 return PDFAnnotation(page: page, kind: .note, color: color, rects: [PDFRect(x: rounded(x), y: rounded(y), width: rounded(w), height: rounded(h))], note: text, createdAt: createdAt)165 }166167 // MARK: hit testing168169 /// The topmost annotation under a normalised point (`tolerance` in the same units, for thin ink).170 static func annotation(at point: PDFPoint, among annotations: [PDFAnnotation], tolerance: Double = 0.012) -> PDFAnnotation? {171 annotations.last { annotation in172 if annotation.kind == .ink, let ink = annotation.ink, !ink.isEmpty {173 if ink.count == 1 { return hypot(ink[0].x - point.x, ink[0].y - point.y) <= tolerance }174 return (1..<ink.count).contains { i in175 let a = ink[i - 1], b = ink[i], dx = b.x - a.x, dy = b.y - a.y, len2 = dx * dx + dy * dy176 let t = len2 > 0 ? min(1, max(0, ((point.x - a.x) * dx + (point.y - a.y) * dy) / len2)) : 0177 return hypot(point.x - (a.x + t * dx), point.y - (a.y + t * dy)) <= tolerance178 }179 }180 return annotation.rects.contains { point.x >= $0.x - tolerance / 2 && point.x <= $0.x + $0.width + tolerance / 2 && point.y >= $0.y - tolerance / 2 && point.y <= $0.y + $0.height + tolerance / 2 }181 }182 }183184 // MARK: colours185186 static func color(_ hex: String) -> UIColor {187 InkColor(hex: hex).map(InkConversion.uiColor) ?? UIColor(red: 1, green: 0.84, blue: 0.29, alpha: 1)188 }189190 /// `#rrggbb` of a colour (alpha dropped: the format has none).191 static func hex(_ color: UIColor) -> String { String(InkConversion.inkColor(color).hex.prefix(7)) }192}193