Repository Public
1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/MediaPDFTests.swift3// Description: The `pdf` node view: the coordinate mapping between PDF page space and normalised annotation rectangles4// (offset media boxes, crop boxes, the four rotations — cross-checked against PDFKit's own page transform on5// PDFs generated here), node annotation ⇄ PDFKit annotation, and the model (load, offline, error, empty,6// selection → highlight / note, ink, edit, delete, page commit).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import CoreGraphics11import Foundation12import PDFKit13import SPNotesDocument14import SwiftUI15import Testing16@testable import SPNotesFeatures17@testable import SPNotesFeaturesCatalog1819private func near(_ a: Double, _ b: Double, _ tolerance: Double = 1e-6) -> Bool { abs(a - b) <= tolerance }20private func near(_ a: CGPoint, _ b: CGPoint, _ tolerance: Double = 1e-6) -> Bool { near(a.x, b.x, tolerance) && near(a.y, b.y, tolerance) }21private func near(_ a: PDFRect, _ b: PDFRect, _ tolerance: Double = 1e-6) -> Bool {22 near(a.x, b.x, tolerance) && near(a.y, b.y, tolerance) && near(a.width, b.width, tolerance) && near(a.height, b.height, tolerance)23}2425@Suite("PDF coordinate mapping")26struct MediaPDFMappingTests {27 @Test("unrotated page: the origin flips from bottom-left to top-left, inside the visible box")28 func unrotated() {29 let geometry = PDFPageGeometry(box: CGRect(x: 0, y: 0, width: 600, height: 800))30 #expect(geometry.normalized(CGPoint(x: 0, y: 800)) == .zero, "top-left of the page")31 #expect(geometry.normalized(CGPoint(x: 600, y: 0)) == CGPoint(x: 1, y: 1))32 #expect(near(geometry.normalized(CGRect(x: 60, y: 640, width: 300, height: 80)), PDFRect(x: 0.1, y: 0.1, width: 0.5, height: 0.1)))33 #expect(geometry.pageRect(PDFRect(x: 0.1, y: 0.1, width: 0.5, height: 0.1)).integral == CGRect(x: 60, y: 640, width: 300, height: 80))34 #expect(geometry.displaySize == CGSize(width: 600, height: 800))35 }3637 @Test("a media / crop box that does not start at the origin")38 func offsetBox() {39 let geometry = PDFPageGeometry(box: CGRect(x: 50, y: 100, width: 400, height: 600))40 #expect(geometry.normalized(CGPoint(x: 50, y: 700)) == .zero)41 #expect(geometry.normalized(CGPoint(x: 250, y: 400)) == CGPoint(x: 0.5, y: 0.5))42 #expect(near(geometry.pagePoint(CGPoint(x: 0.25, y: 0.25)), CGPoint(x: 150, y: 550)))43 // Outside the crop box: clamped when it becomes an annotation.44 let outside = geometry.normalized(CGRect(x: 0, y: 650, width: 100, height: 100))45 #expect(outside.x < 0 && outside.y < 0)46 #expect(near(PDFPageGeometry.clamped(outside), PDFRect(x: 0, y: 0, width: 0.125, height: 1.0 / 12)))47 }4849 @Test("rotated pages: 90, 180, 270 — corners land where the reader sees them and widths / heights swap")50 func rotations() {51 let box = CGRect(x: 0, y: 0, width: 600, height: 800)52 // The unrotated top-left corner (0, 800) is displayed: 90° → top-right, 180° → bottom-right, 270° → bottom-left.53 #expect(PDFPageGeometry(box: box, rotation: 90).normalized(CGPoint(x: 0, y: 800)) == CGPoint(x: 1, y: 0))54 #expect(PDFPageGeometry(box: box, rotation: 180).normalized(CGPoint(x: 0, y: 800)) == CGPoint(x: 1, y: 1))55 #expect(PDFPageGeometry(box: box, rotation: 270).normalized(CGPoint(x: 0, y: 800)) == CGPoint(x: 0, y: 1))56 #expect(PDFPageGeometry(box: box, rotation: 90).displaySize == CGSize(width: 800, height: 600))57 #expect(PDFPageGeometry(box: box, rotation: -90).rotation == 270 && PDFPageGeometry(box: box, rotation: 450).rotation == 90)58 // A line of text near the top of the unrotated page becomes a vertical strip on the right at 90°.59 let line = CGRect(x: 60, y: 700, width: 300, height: 20)60 let rotated = PDFPageGeometry(box: box, rotation: 90).normalized(line)61 #expect(near(rotated, PDFRect(x: 0.875, y: 0.1, width: 0.025, height: 0.5)))62 for rotation in [0, 90, 180, 270] {63 let geometry = PDFPageGeometry(box: CGRect(x: 30, y: -20, width: 500, height: 700), rotation: rotation)64 for point in [CGPoint(x: 30, y: -20), CGPoint(x: 200, y: 333), CGPoint(x: 530, y: 680)] {65 #expect(near(geometry.pagePoint(geometry.normalized(point)), point), "round trip at \(rotation)°")66 }67 let rect = PDFRect(x: 0.2, y: 0.3, width: 0.4, height: 0.1)68 #expect(near(geometry.normalized(geometry.pageRect(rect)), rect), "rect round trip at \(rotation)°")69 }70 }7172 @Test("cross-check with PDFKit on generated PDFs: every rotation and an offset box agree with PDFPage.transform(for:)")73 @MainActor func agreesWithPDFKit() throws {74 for mediaBox in [CGRect(x: 0, y: 0, width: 612, height: 792), CGRect(x: 40, y: 60, width: 500, height: 700)] {75 let document = try #require(PDFDocument(data: FeatureSamples.samplePDF(rotations: [0, 90, 180, 270], mediaBox: mediaBox)))76 #expect(document.pageCount == 4)77 for index in 0..<4 {78 let page = try #require(document.page(at: index))79 #expect(page.rotation == index * 90)80 let box = page.bounds(for: .cropBox)81 let geometry = PDFPageGeometry(box: box, rotation: page.rotation)82 // PDFKit's transform maps page space to the displayed page (origin bottom-left, y up).83 let transform = page.transform(for: .cropBox)84 let display = geometry.displaySize85 for point in [CGPoint(x: box.minX, y: box.maxY), CGPoint(x: box.midX + 31, y: box.midY - 77), CGPoint(x: box.maxX - 5, y: box.minY + 9)] {86 let shown = point.applying(transform)87 let expected = CGPoint(x: shown.x / display.width, y: 1 - shown.y / display.height)88 #expect(near(geometry.normalized(point), expected, 1e-4), "page \(index + 1) box \(mediaBox): \(geometry.normalized(point)) ≠ \(expected)")89 }90 // The title drawn at the top-left of the unrotated page: where is it for the reader?91 let title = try #require(document.findString("Page \(index + 1)", withOptions: []).first)92 let rect = geometry.normalized(title.bounds(for: page))93 switch page.rotation {94 case 0: #expect(rect.x < 0.3 && rect.y < 0.2)95 case 90: #expect(rect.x > 0.8 && rect.y < 0.3)96 case 180: #expect(rect.x > 0.5 && rect.y > 0.8)97 default: #expect(rect.x < 0.2 && rect.y > 0.5)98 }99 #expect(rect.width > 0 && rect.height > 0 && rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= 1.0001 && rect.y + rect.height <= 1.0001)100 }101 }102 }103104 @Test("node annotation → PDFKit placement → node annotation, on a rotated page with an offset box")105 func placementRoundTrip() throws {106 let geometry = PDFPageGeometry(box: CGRect(x: 40, y: 60, width: 500, height: 700), rotation: 90)107 let highlight = SPNotesDocument.PDFAnnotation(id: "h", page: 2, kind: .note, color: "#7cc4ff", rects: [PDFRect(x: 0.1, y: 0.2, width: 0.5, height: 0.03), PDFRect(x: 0.1, y: 0.24, width: 0.3, height: 0.03)],108 text: "deux lignes", note: "à vérifier")109 let placement = try #require(PDFAnnotationPlacement(highlight, geometry: geometry))110 #expect(placement.lineRects.count == 2 && placement.contents == "à vérifier" && placement.quadrilateralPoints.count == 8)111 #expect(placement.bounds == placement.lineRects[0].union(placement.lineRects[1]))112 let back = PDFAnnotationImport.highlight(page: 2, bounds: placement.bounds, quadrilateralPoints: placement.quadrilateralPoints, color: placement.color, text: "deux lignes", note: placement.contents, geometry: geometry, id: "h")113 #expect(back.kind == .note && back.rects.count == 2)114 for (a, b) in zip(back.rects, highlight.rects) { #expect(near(a, b, 1e-9)) }115116 let ink = SPNotesDocument.PDFAnnotation(id: "i", page: 1, kind: .ink, color: "#cc272e", ink: [PDFPoint(x: 0.1, y: 0.1), PDFPoint(x: 0.3, y: 0.2), PDFPoint(x: 0.2, y: 0.4)])117 let inkPlacement = try #require(PDFAnnotationPlacement(ink, geometry: geometry))118 #expect(inkPlacement.path.count == 3 && inkPlacement.bounds.contains(inkPlacement.path[1]))119 let inkBack = try #require(PDFAnnotationImport.ink(page: 1, path: inkPlacement.path, color: "#cc272e", geometry: geometry, id: "i"))120 for (a, b) in zip(inkBack.ink ?? [], ink.ink ?? []) { #expect(near(a.x, b.x, 1e-9) && near(a.y, b.y, 1e-9)) }121 #expect(near(inkBack.rects[0], PDFRect(x: 0.1, y: 0.1, width: 0.2, height: 0.3), 1e-9))122 #expect(PDFAnnotationImport.ink(page: 1, path: [.zero], color: "#000000", geometry: geometry) == nil)123 #expect(PDFAnnotationPlacement(SPNotesDocument.PDFAnnotation(id: "e", page: 1, kind: .highlight), geometry: geometry) == nil, "nothing to draw")124 let capture = PDFSelectionCapture(page: 1, lineRects: [geometry.pageRect(PDFRect(x: 0.1, y: 0.1, width: 0.2, height: 0.02)), .zero], text: " une\nligne ", geometry: geometry)125 #expect(capture.rects.count == 1 && capture.text == "une ligne")126 }127}128129@Suite("PDF block model")130@MainActor131struct MediaPDFModelTests {132 private func model(_ world: FeatureWorld, block: PDFBlock = FeatureSamples.samplePDFBlock(), changes: @escaping (PDFBlock) -> Void = { _ in }) -> PDFBlockModel {133 PDFBlockModel(block: block, loader: FeatureSamples.attachmentLoader(world), now: { FeatureSamples.now }, onChange: changes)134 }135136 @Test("happy path: the attachment loads, the node's annotations are mirrored as PDFKit annotations on their page")137 func loads() async throws {138 let world = try await FeatureWorld()139 let model = model(world)140 await model.load()141 #expect(model.phase == .loaded && model.pageCount == 3 && model.page == 1 && model.annotations.count == 3)142 let page = try #require(model.document?.page(at: 0))143 let mirrored = page.annotations.filter { $0.userName == PDFBlockModel.marker }144 #expect(mirrored.count == 3)145 #expect(mirrored.filter { $0.type == "Highlight" }.count == 2 && mirrored.filter { $0.type == "Ink" }.count == 1)146 #expect(mirrored.first { $0.contents == "Définition à citer dans l'introduction." } != nil)147 // The sample highlight really covers its sentence in the generated file.148 let sentence = try #require(model.document?.findString("Traditional econometric models", withOptions: []).first)149 let placement = try #require(model.placements(page: 1).first { $0.id == "a-highlight" })150 #expect(placement.bounds.intersects(sentence.bounds(for: page)))151 #expect(model.placements(page: 2).isEmpty)152 }153154 @Test("selection → highlight and note with normalised rectangles; edits reach the caller as node attributes")155 func annotating() async throws {156 let world = try await FeatureWorld()157 var received: [PDFBlock] = []158 var block = FeatureSamples.samplePDFBlock()159 block.annotations = []160 let model = model(world, block: block) { received.append($0) }161 await model.load()162 #expect(model.annotateSelection() == nil, "nothing selected")163 model.go(to: 3) // the rotated page164 let document = try #require(model.document), page = try #require(document.page(at: 2))165 let found = try #require(document.findString("autoregressive conditional heteroscedastic", withOptions: []).first { $0.pages.contains(page) })166 model.capture(found)167 let capture = try #require(model.selection)168 #expect(capture.page == 3 && capture.rects.count == 1 && capture.text.contains("heteroscedastic"))169 let rect = capture.rects[0]170 #expect(rect.height > rect.width, "on the page rotated by 90° a line of text is a vertical strip for the reader")171 model.color = "#8fe3a0"172 let id = try #require(model.annotateSelection())173 #expect(model.selection == nil && model.selectedAnnotationId == id)174 #expect(received.last?.annotations.map(\.id) == [id] && received.last?.annotations.first?.kind == .highlight && received.last?.annotations.first?.color == "#8fe3a0")175 #expect(received.last?.page == 3)176 #expect(received.last?.annotations.first?.createdAt != nil)177 #expect(page.annotations.contains { $0.userName == PDFBlockModel.marker })178 // The PDFKit annotation made from the node maps back to the same rectangles (both directions agree).179 let kit = try #require(page.annotations.first { $0.userName == PDFBlockModel.marker })180 let imported = try #require(model.importHighlight(kit, on: page))181 #expect(near(imported.rects[0], rect, 1e-6) && imported.page == 3)182183 model.capture(found)184 let noteId = try #require(model.annotateSelection(note: " À relier à H1 "))185 #expect(model.annotations.first { $0.id == noteId }?.kind == .note && model.annotations.first { $0.id == noteId }?.note == "À relier à H1")186 model.setNote("", of: noteId)187 #expect(model.annotations.first { $0.id == noteId }?.kind == .highlight)188 model.setNote("Nouvelle note", of: id)189 model.setColor("#ff9eb0", of: id)190 #expect(received.last?.annotations.first { $0.id == id }?.note == "Nouvelle note" && received.last?.annotations.first { $0.id == id }?.color == "#ff9eb0")191192 let inkId = try #require(model.addInk(page: 1, pagePoints: [CGPoint(x: 100, y: 700), CGPoint(x: 200, y: 650), CGPoint(x: 300, y: 700)]))193 let ink = try #require(model.annotations.first { $0.id == inkId })194 #expect(ink.kind == .ink && ink.ink?.count == 3 && near(ink.ink?[0].x ?? 0, 100.0 / 612, 1e-9) && near(ink.ink?[0].y ?? 0, 1 - 700.0 / 792, 1e-9))195 #expect(model.addInk(page: 1, pagePoints: [.zero]) == nil)196197 let count = received.count198 model.remove(noteId)199 model.remove("unknown")200 #expect(received.count == count + 1 && model.annotations.count == 2)201 // Unknown attributes of the node and of its annotations survive the edits.202 var custom = FeatureSamples.samplePDFBlock()203 custom.storage.attrs = (custom.storage.attrs ?? [:]).merging(["futur": .string("gardé")]) { _, new in new }204 let keeper = self.model(world, block: custom) { received.append($0) }205 await keeper.load()206 keeper.remove("a-ink")207 #expect(received.last?.storage.attrs?["futur"]?.stringValue == "gardé")208 }209210 @Test("pages: navigation is clamped; the page read is written into the node only when the view goes away")211 func pages() async throws {212 let world = try await FeatureWorld()213 var received: [PDFBlock] = []214 let model = model(world) { received.append($0) }215 await model.load()216 model.go(to: 99)217 #expect(model.page == 3 && !model.canGoForward && model.canGoBack)218 model.go(to: -4)219 #expect(model.page == 1)220 model.pageShown(2)221 #expect(model.page == 2 && received.isEmpty, "turning pages is not an edit")222 model.commitPage()223 #expect(received.count == 1 && received[0].page == 2)224 model.commitPage()225 #expect(received.count == 1)226 let annotation = try #require(model.annotations.first)227 model.show(annotation)228 #expect(model.page == annotation.page && model.selectedAnnotationId == annotation.id)229 }230231 @Test("offline, missing file, not a PDF, empty node: typed calm failures")232 func failures() async throws {233 let world = try await FeatureWorld()234 world.setOffline(true)235 let offline = model(world)236 await offline.load()237 #expect(offline.phase.failure?.isOffline == true)238 world.setOffline(false)239 await offline.load()240 #expect(offline.phase == .loaded, "retry works")241 world.fake.inject(.status(500), method: "GET", path: "^/api/files/")242 let failing = model(world)243 await failing.load()244 #expect(failing.phase.failure?.kind == .server)245 let notPDF = PDFBlockModel(block: PDFBlock(attachmentId: FeatureSamples.canvasImageId, name: "image.png"), loader: FeatureSamples.attachmentLoader(world))246 await notPDF.load()247 #expect(notPDF.phase.failure?.kind == .other)248 var empty = PDFBlock(attachmentId: FeatureSamples.canvasPDFId, name: "")249 empty.attachmentId = nil250 let none = PDFBlockModel(block: empty, loader: FeatureSamples.attachmentLoader(world))251 await none.load()252 #expect(none.phase.failure?.kind == .notFound)253 }254255 #if os(macOS)256 @Test("hosted renders: the PDF with its annotations, the annotation list opened on compact")257 func snapshots() async throws {258 let world = try await FeatureWorld()259 let model = model(world)260 await model.load()261 model.selectedAnnotationId = "a-note"262 // The interactive PDFView does not draw its tiles off screen: the hosted renders use the static page picture263 // (PDFPage.draw with the very same PDFKit annotations).264 Snapshot.render("pdf-block") { PDFBlockView(model: model).environment(\.pdfStaticRendering, true) }265 model.showsAnnotations = true266 Snapshot.render("pdf-block-annotations") { PDFBlockView(model: model).environment(\.pdfStaticRendering, true) }267 // The same highlight on the four rotations of an offset page: where PDFKit draws what the node says.268 let rotated = try #require(PDFDocument(data: FeatureSamples.samplePDF(rotations: [0, 90, 180, 270], mediaBox: CGRect(x: 40, y: 60, width: 500, height: 700))))269 var block = PDFBlock(attachmentId: FeatureSamples.canvasPDFId, name: "rotations.pdf")270 let probe = PDFBlockModel(block: block, loader: .unavailable)271 probe.load(rotated)272 for index in 0..<4 {273 let page = try #require(rotated.page(at: index))274 let title = try #require(rotated.findString("Page \(index + 1)", withOptions: []).first)275 let geometry = try #require(probe.geometry(page: index + 1))276 block.add(SPNotesDocument.PDFAnnotation(id: "t\(index)", page: index + 1, kind: .highlight, color: "#ffd54a", rects: [geometry.normalized(title.bounds(for: page))], text: "Page \(index + 1)"))277 }278 let rotations = PDFBlockModel(block: block, loader: .unavailable)279 rotations.load(rotated)280 for index in 1...4 {281 let image = try #require(rotations.pageImage(page: index, maxPixel: 700))282 let url = Snapshot.directory.appendingPathComponent("pdf-rotation-\((index - 1) * 90).png")283 try #require(InkRenderer.pngData(of: image)).write(to: url)284 }285 }286 #endif287}288