SPB Git

Repository Public

PDFAnnotationTests.swift 26.4 KB 389 lines swift

1// SP Notes iOS2// File: Tests/PDFAnnotationTests.swift3// Description: PDF annotations: the mapping page space ⇄ normalised top-left ⇄ view (every rotation, a crop box away from the4//              origin, checked against PDFKit's own transform), highlight rectangles of a known selection, ink normalisation,5//              annotation edits that leave the other entries and unknown keys untouched, and the proof that annotating never6//              changes a byte of the PDF file (SHA-256 before / after).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import CryptoKit11import PDFKit12import Testing13import UIKit14import SPNotesCore15@testable import SPNotes1617private typealias PDFAnnotation = SPNotesCore.PDFAnnotation1819@MainActor20enum TestPDF {21    static let pageSize = CGSize(width: 612, height: 792)22    static let font = UIFont(name: "Helvetica", size: 24) ?? .systemFont(ofSize: 24)2324    /// Two pages of typed text at known places (UIKit coordinates: origin top-left).25    static func data(pages: Int = 2) -> Data {26        UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size: pageSize)).pdfData { context in27            for page in 1...pages {28                context.beginPage()29                ("Bonjour Pencil" as NSString).draw(at: CGPoint(x: 72, y: 100), withAttributes: [.font: font])30                ("Seconde ligne du texte" as NSString).draw(at: CGPoint(x: 72, y: 140), withAttributes: [.font: font])31                ("Page \(page)" as NSString).draw(at: CGPoint(x: 72, y: 700), withAttributes: [.font: font])32            }33        }34    }3536    /// The same document with its first page turned by `rotation` and, optionally, a crop box away from the origin — written as37    /// a new PDF, so the rotation and the box are those of the file.38    static func transformed(rotation: Int, cropBox: CGRect? = nil) throws -> Data {39        let document = try #require(PDFDocument(data: data()))40        let page = try #require(document.page(at: 0))41        page.rotation = rotation42        if let cropBox { page.setBounds(cropBox, for: .cropBox) }43        return try #require(document.dataRepresentation())44    }4546    static func sha256(_ url: URL) throws -> String {47        SHA256.hash(data: try Data(contentsOf: url)).map { String(format: "%02x", $0) }.joined()48    }49}5051@MainActor52@Suite("PDFAnnotation — coordonnées") struct PDFAnnotationGeometryTests {53    static let boxes = [CGRect(x: 0, y: 0, width: 612, height: 792), CGRect(x: 36, y: 54, width: 500, height: 640), CGRect(x: -20, y: 15.5, width: 841.89, height: 595.28)]5455    @Test func pageSpaceRoundTripsThroughNormalisedAndViewSpace() {56        var rng = SeededGenerator(seed: 2026)57        var worst = 0.058        for box in Self.boxes {59            for rotation in [0, 90, 180, 270, 450, -90] {60                let geometry = PDFPageGeometry(box: box, rotation: rotation)61                #expect([0, 90, 180, 270].contains(geometry.rotation))62                let view = CGSize(width: geometry.displaySize.width * 1.7, height: geometry.displaySize.height * 1.7)63                for _ in 0..<200 {64                    let p = CGPoint(x: CGFloat.random(in: box.minX...box.maxX, using: &rng), y: CGFloat.random(in: box.minY...box.maxY, using: &rng))65                    let n = geometry.normalized(p)66                    #expect(n.x >= -1e-9 && n.x <= 1 + 1e-9 && n.y >= -1e-9 && n.y <= 1 + 1e-9)67                    let back = geometry.pagePoint(n)68                    worst = max(worst, Double(abs(back.x - p.x)), Double(abs(back.y - p.y)))69                    // normalised → view → normalised70                    let v = PDFPageGeometry.viewPoint(n, in: view), n2 = PDFPageGeometry.normalized(viewPoint: v, in: view)71                    worst = max(worst, abs(n2.x - n.x), abs(n2.y - n.y))72                    // page → view → page73                    let again = geometry.pagePoint(viewPoint: geometry.viewPoint(pagePoint: p, in: view), in: view)74                    worst = max(worst, Double(abs(again.x - p.x)), Double(abs(again.y - p.y)))75                }76                // rectangles77                let rect = CGRect(x: box.minX + box.width * 0.2, y: box.minY + box.height * 0.3, width: box.width * 0.4, height: box.height * 0.1)78                let r = geometry.pageRect(geometry.normalized(rect))79                worst = max(worst, Double(abs(r.minX - rect.minX)), Double(abs(r.minY - rect.minY)), Double(abs(r.width - rect.width)), Double(abs(r.height - rect.height)))80            }81        }82        try? String(format: "pdf mapping worst round-trip error %.3e\n", worst).write(toFile: "/tmp/spnote-next/pencil-work/pdf-roundtrip.txt", atomically: true, encoding: .utf8)83        #expect(worst < 1e-6)84    }8586    @Test func theCornersOfThePageLandWhereTheRotationPutsThem() {87        let box = CGRect(x: 36, y: 54, width: 500, height: 640)88        let bottomLeft = CGPoint(x: box.minX, y: box.minY), topLeft = CGPoint(x: box.minX, y: box.maxY), topRight = CGPoint(x: box.maxX, y: box.maxY)89        func n(_ rotation: Int, _ p: CGPoint) -> [Double] { let q = PDFPageGeometry(box: box, rotation: rotation).normalized(p); return [q.x, q.y] }90        // unrotated: the top-left of page space is the origin91        #expect(n(0, topLeft) == [0, 0] && n(0, bottomLeft) == [0, 1] && n(0, topRight) == [1, 0])92        // a quarter turn clockwise: the bottom-left corner of the paper is shown at the top-left93        #expect(n(90, bottomLeft) == [0, 0] && n(90, topLeft) == [1, 0] && n(90, topRight) == [1, 1])94        #expect(n(180, topLeft) == [1, 1] && n(180, bottomLeft) == [1, 0])95        #expect(n(270, topRight) == [0, 0] && n(270, topLeft) == [0, 1] && n(270, bottomLeft) == [1, 1])96        #expect(PDFPageGeometry(box: box, rotation: 90).displaySize == CGSize(width: 640, height: 500))97        #expect(PDFPageGeometry(box: box, rotation: 180).displaySize == box.size)98    }99100    /// PDFKit is the reference: `PDFPage.transform(for:)` maps page space to the displayed box (origin bottom-left, y up).101    @Test func theMappingAgreesWithPDFKitForEveryRotationAndACropBoxAwayFromTheOrigin() throws {102        for rotation in [0, 90, 180, 270] {103            for crop in [nil, CGRect(x: 40, y: 60, width: 480, height: 600)] as [CGRect?] {104                let document = try #require(PDFDocument(data: try TestPDF.transformed(rotation: rotation, cropBox: crop)))105                let page = try #require(document.page(at: 0))106                #expect(page.rotation == rotation)107                let geometry = PDFPageGeometry(page: page)108                if let crop { #expect(abs(geometry.box.minX - crop.minX) < 0.01 && abs(geometry.box.minY - crop.minY) < 0.01 && abs(geometry.box.width - crop.width) < 0.01) }109                let transform = page.transform(for: .cropBox)110                let size = geometry.displaySize111                for p in [CGPoint(x: geometry.box.minX, y: geometry.box.minY), CGPoint(x: geometry.box.maxX, y: geometry.box.minY), CGPoint(x: geometry.box.midX + 31, y: geometry.box.midY - 77), CGPoint(x: 100, y: 692)] {112                    let displayed = p.applying(transform) // bottom-left origin of the displayed box113                    let n = geometry.normalized(p)114                    #expect(abs(CGFloat(n.x) * size.width - displayed.x) < 1e-6, "rotation \(rotation) crop \(String(describing: crop)): x \(n.x * Double(size.width)) vs \(displayed.x)")115                    #expect(abs((1 - CGFloat(n.y)) * size.height - displayed.y) < 1e-6, "rotation \(rotation) crop \(String(describing: crop)): y \((1 - n.y) * Double(size.height)) vs \(displayed.y)")116                }117            }118        }119    }120}121122@MainActor123@Suite("PDFAnnotation — surlignage, traits, notes") struct PDFAnnotationFactoryTests {124    @Test func aKnownSelectionGivesItsRectanglesAndItsText() throws {125        let document = try #require(PDFDocument(data: TestPDF.data()))126        let selection = try #require(document.findString("Pencil", withOptions: []).first)127        let made = PDFAnnotationFactory.highlights(from: selection, in: document, color: "#7ee081", createdAt: Date(timeIntervalSince1970: 1_800_000_000))128        #expect(made.count == 1)129        let highlight = try #require(made.first)130        #expect(highlight.kind == .highlight && highlight.page == 1 && highlight.text == "Pencil" && highlight.color == "#7ee081")131        #expect(highlight.ink == nil && highlight.note.isEmpty)132        #expect(highlight.createdAt?.hasPrefix("2027-01-15T08:00:00") == true)133        let rect = try #require(highlight.rects.first)134        #expect(highlight.rects.count == 1)135        // « Bonjour Pencil » is drawn at (72, 100) in 24 pt Helvetica: « Pencil » starts after « Bonjour »136        let prefix = ("Bonjour " as NSString).size(withAttributes: [.font: TestPDF.font]).width, word = ("Pencil" as NSString).size(withAttributes: [.font: TestPDF.font]).width137        #expect(abs(rect.x - Double((72 + prefix) / 612)) < 0.006)138        #expect(abs(rect.width - Double(word / 612)) < 0.008)139        #expect(rect.y > 100.0 / 792 - 0.008 && rect.y + rect.height < Double(100 + TestPDF.font.lineHeight) / 792 + 0.008)140        #expect(rect.height > 0.015 && rect.height < 0.05)141        // back in page space it covers the selection's own bounds142        let page = try #require(document.page(at: 0))143        let bounds = selection.bounds(for: page), back = PDFPageGeometry(page: page).pageRect(rect)144        #expect(abs(back.minX - bounds.minX) < 0.01 && abs(back.minY - bounds.minY) < 0.01 && abs(back.width - bounds.width) < 0.01 && abs(back.height - bounds.height) < 0.01)145    }146147    @Test func aSelectionOverTwoLinesAndTwoPagesGivesARectanglePerLineAndAnAnnotationPerPage() throws {148        let document = try #require(PDFDocument(data: TestPDF.data()))149        let first = try #require(document.page(at: 0)), second = try #require(document.page(at: 1))150        // from « Pencil » on line 1 to the end of line 2151        let lines = try #require(document.selection(from: first, at: CGPoint(x: 170, y: 792 - 112), to: first, at: CGPoint(x: 330, y: 792 - 152)))152        let made = PDFAnnotationFactory.highlights(from: lines, in: document)153        #expect(made.count == 1)154        #expect(made[0].rects.count == 2)155        #expect(made[0].rects[0].y < made[0].rects[1].y)156        #expect(made[0].text.contains("Seconde"))157        // across the two pages158        let both = try #require(document.selection(from: first, at: CGPoint(x: 72, y: 792 - 712), to: second, at: CGPoint(x: 300, y: 792 - 112)))159        let pages = PDFAnnotationFactory.highlights(from: both, in: document)160        #expect(pages.map(\.page) == [1, 2])161        #expect(pages.allSatisfy { !$0.rects.isEmpty && $0.rects.allSatisfy { $0.x >= 0 && $0.y >= 0 && $0.x + $0.width <= 1.00001 && $0.y + $0.height <= 1.00001 } })162    }163164    @Test func aHighlightOnARotatedPageIsStoredAsItIsSeen() throws {165        let document = try #require(PDFDocument(data: try TestPDF.transformed(rotation: 90)))166        let page = try #require(document.page(at: 0))167        let selection = try #require(document.findString("Pencil", withOptions: []).first { $0.pages.contains(page) })168        let highlight = try #require(PDFAnnotationFactory.highlights(from: selection, in: document).first)169        let rect = try #require(highlight.rects.first)170        // turned a quarter: the word now runs down the page — taller than wide on the displayed (landscape) page, in points171        let size = PDFPageGeometry(page: page).displaySize172        #expect(size == CGSize(width: 792, height: 612))173        #expect(rect.height * 612 > rect.width * 792 * 2)174        // the line was 100 pt from the top of the paper: after a clockwise quarter turn it is ~100 pt from the right edge175        #expect(abs((1 - rect.x - rect.width / 2) * 792 - 112) < 14)176        // and it agrees with PDFKit's transform of the selection bounds177        let shown = selection.bounds(for: page).applying(page.transform(for: .cropBox))178        #expect(abs(rect.x * 792 - Double(shown.minX)) < 0.01 && abs((1 - rect.y - rect.height) * 612 - Double(shown.minY)) < 0.01)179    }180181    @Test func inkIsNormalisedSimplifiedAndComesBack() throws {182        let size = CGSize(width: 600, height: 800)183        let drawn = (0...200).map { i -> CGPoint in let t = CGFloat(i) / 200; return CGPoint(x: 60 + 400 * t, y: 300 + 80 * sin(t * 6)) }184        let ink = try #require(PDFAnnotationFactory.ink(viewPoints: drawn, in: size, page: 3, color: "#2f5ddb", lineWidth: 3, createdAt: Date()))185        #expect(ink.kind == .ink && ink.page == 3 && ink.color == "#2f5ddb" && ink.text.isEmpty)186        let points = try #require(ink.ink)187        #expect(points.count > 5 && points.count < 80) // simplified188        #expect(points.allSatisfy { $0.x >= 0 && $0.x <= 1 && $0.y >= 0 && $0.y <= 1 })189        #expect(abs(points[0].x - 0.1) < 1e-5 && abs(points[0].y - 0.375) < 1e-5)190        // rects = the bounding box of the path191        #expect(ink.rects.count == 1)192        let box = ink.rects[0]193        #expect(abs(box.x - 0.1) < 1e-4 && abs(box.x + box.width - 460.0 / 600) < 1e-4)194        #expect(abs(box.y - (points.map(\.y).min() ?? 0)) < 1e-9 && abs(box.y + box.height - (points.map(\.y).max() ?? 0)) < 1e-4)195        // denormalised on the same view: every drawn point is within the simplification tolerance of the stored path196        let back = PDFAnnotationFactory.viewPoints(of: ink, in: size).map { InkPoint(x: Double($0.x), y: Double($0.y)) }197        for p in drawn { #expect(InkMetrics.nearest(InkPoint(x: Double(p.x), y: Double(p.y)), on: back).distance <= 0.45) }198        // and on a view twice as large the path is twice as large, the line too199        let big = PDFAnnotationFactory.viewPoints(of: ink, in: CGSize(width: 1200, height: 1600))200        #expect(abs(big[0].x - 120) < 0.01 && abs(big[0].y - 600) < 0.01)201        #expect(abs(PDFAnnotationFactory.lineWidth(of: ink, in: size) - 3) < 0.01 && abs(PDFAnnotationFactory.lineWidth(of: ink, in: CGSize(width: 1200, height: 1600)) - 6) < 0.01)202        // strokes leaving the page are clamped to it; nothing is made of nothing203        let outside = try #require(PDFAnnotationFactory.ink(viewPoints: [CGPoint(x: -50, y: 10), CGPoint(x: 700, y: 900)], in: size, page: 1))204        #expect(outside.ink?.first?.x == 0 && outside.ink?.last?.x == 1 && outside.ink?.last?.y == 1)205        #expect(PDFAnnotationFactory.ink(viewPoints: [], in: size, page: 1) == nil)206        #expect(PDFAnnotationFactory.ink(viewPoints: drawn, in: .zero, page: 1) == nil)207        // a highlighter stroke keeps its opacity in an extra key208        let soft = try #require(PDFAnnotationFactory.ink(viewPoints: drawn, in: size, page: 1, opacity: 0.4))209        #expect(abs(PDFAnnotationFactory.opacity(of: soft) - 0.4) < 1e-6 && PDFAnnotationFactory.opacity(of: ink) == 1)210        // the layers that draw them211        let layers = PDFPageOverlayView.layers(for: [ink, soft, PDFAnnotationFactory.note(at: PDFPoint(x: 0.5, y: 0.5), page: 3)], in: size)212        #expect(layers.map(\.name) == ["ink", "ink", "note"])213        #expect((layers[0] as? CAShapeLayer)?.path?.boundingBox.minX ?? 0 > 59 && (layers[0] as? CAShapeLayer)?.lineWidth == 3)214    }215216    @Test func notesArePinnedInsideThePageAndHitTestingFindsTheTopmost() throws {217        let note = PDFAnnotationFactory.note(at: PDFPoint(x: 0.995, y: 0.002), page: 2, pageAspect: 612.0 / 792, text: "À vérifier")218        #expect(note.kind == .note && note.page == 2 && note.note == "À vérifier" && note.text.isEmpty)219        let rect = try #require(note.rects.first)220        #expect(rect.x + rect.width <= 1.000001 && rect.y >= 0)221        #expect(abs(rect.width * 612 - rect.height * 792) < 0.01) // square on screen222        let highlight = PDFAnnotation(page: 2, kind: .highlight, rects: [PDFRect(x: 0.1, y: 0.1, width: 0.5, height: 0.03), PDFRect(x: 0.1, y: 0.14, width: 0.2, height: 0.03)])223        let ink = try #require(PDFAnnotationFactory.ink(viewPoints: [CGPoint(x: 60, y: 400), CGPoint(x: 300, y: 400)], in: CGSize(width: 600, height: 800), page: 2))224        let all = [highlight, ink, note]225        #expect(PDFAnnotationFactory.annotation(at: PDFPoint(x: 0.2, y: 0.155), among: all)?.id == highlight.id)226        #expect(PDFAnnotationFactory.annotation(at: PDFPoint(x: 0.3, y: 0.505), among: all)?.id == ink.id)227        #expect(PDFAnnotationFactory.annotation(at: PDFPoint(x: 0.3, y: 0.56), among: all) == nil)228        #expect(PDFAnnotationFactory.annotation(at: PDFPoint(x: 0.98, y: 0.02), among: all)?.id == note.id)229        // overlapping: the last one drawn is on top230        let over = PDFAnnotation(page: 2, kind: .highlight, rects: [PDFRect(x: 0.15, y: 0.1, width: 0.1, height: 0.03)])231        #expect(PDFAnnotationFactory.annotation(at: PDFPoint(x: 0.2, y: 0.11), among: all + [over])?.id == over.id)232        #expect(PDFAnnotationFactory.hex(PDFAnnotationFactory.color("#7CC4FF")) == "#7cc4ff")233    }234}235236@MainActor237@Suite("PDFAnnotation — bloc et fichier") struct PDFAnnotationModelTests {238    /// A `pdf` node as another editor may have left it: an annotation with keys this build does not know, an annotation of an239    /// unknown kind, an entry that is not an object, and an attribute of a newer schema.240    static func foreignNode(attachmentId: String) throws -> PMNode {241        let json = """242        {"type":"pdf","attrs":{"id":"blk-pdf-1","attachmentId":"\(attachmentId)","name":"cours.pdf","page":1,"futureAttr":{"zoom":1.25},243        "annotations":[244          {"id":"a-web","page":1,"kind":"highlight","color":"#ffd54a","rects":[[0.1,0.2,0.3,0.02]],"text":"du web","note":"","createdAt":"2026-11-19T10:00:00.000Z","author":"web","layer":{"z":3}},245          "entrée inattendue",246          {"id":"a-future","page":2,"kind":"stamp","color":"#00ff00","rects":[],"text":"","note":"","createdAt":"2026-11-19T10:01:00.000Z","stamp":"approved"}247        ]}}248        """249        return try PMNode(json: JSONValue(jsonString: json))250    }251252    @Test func editsKeepTheOtherEntriesAndUnknownKeysUntouched() throws {253        let node = try Self.foreignNode(attachmentId: UUID().uuidString.lowercased())254        let original = try #require(node.attrs?["annotations"]?.arrayValue)255        var committed: [PMNode?] = []256        let foreign = try #require(PDFBlock(node: node))257        let model = PDFAnnotationModel(block: foreign, isEditable: true, commit: { committed.append($0) })258        #expect(model.annotations.count == 2) // the entry that is not an object is skipped for display, never dropped259260        // add261        let ink = try #require(PDFAnnotationFactory.ink(viewPoints: [CGPoint(x: 10, y: 10), CGPoint(x: 90, y: 60)], in: CGSize(width: 100, height: 100), page: 1))262        model.add(ink)263        var raw = try #require(committed.last??.attrs?["annotations"]?.arrayValue)264        #expect(raw.count == 4 && Array(raw.prefix(3)) == original)265        #expect(raw[3]["id"]?.stringValue == ink.id && raw[3]["kind"]?.stringValue == "ink")266267        // update the web's highlight: only what was changed changes, its unknown keys stay268        var edited = try #require(model.annotations.first { $0.id == "a-web" })269        edited.note = "relu sur iPad"270        edited.color = "#7ee081"271        model.update(edited)272        raw = try #require(committed.last??.attrs?["annotations"]?.arrayValue)273        #expect(raw.count == 4)274        #expect(raw[0]["note"]?.stringValue == "relu sur iPad" && raw[0]["color"]?.stringValue == "#7ee081")275        #expect(raw[0]["author"] == original[0]["author"] && raw[0]["layer"] == original[0]["layer"] && raw[0]["rects"] == original[0]["rects"] && raw[0]["createdAt"] == original[0]["createdAt"])276        #expect(raw[1] == original[1] && raw[2] == original[2])277278        // remove ours: the three foreign entries are exactly as they were (but for the edit above)279        model.remove(ink.id)280        raw = try #require(committed.last??.attrs?["annotations"]?.arrayValue)281        #expect(raw.count == 3 && raw[1] == original[1] && raw[2] == original[2])282        // remove the unknown-kind one by id283        model.remove("a-future")284        raw = try #require(committed.last??.attrs?["annotations"]?.arrayValue)285        #expect(raw.count == 2 && raw[1] == original[1])286287        // the node keeps its id, its file and the attribute of a newer schema288        let last = try #require(committed.last ?? nil)289        #expect(last.type == "pdf" && last.attrs?["futureAttr"] == node.attrs?["futureAttr"] && last.attrs?["id"] == node.attrs?["id"] && last.attrs?["attachmentId"] == node.attrs?["attachmentId"])290        #expect(committed.count == 4)291        // unknown ids change nothing and commit nothing292        model.remove("inconnu")293        model.update(PDFAnnotation(page: 1, kind: .note))294        #expect(committed.count == 4)295    }296297    @Test func aReadOnlyBlockIsNeverChanged() throws {298        var committed = 0299        let foreign = try #require(PDFBlock(node: try Self.foreignNode(attachmentId: UUID().uuidString.lowercased())))300        let model = PDFAnnotationModel(block: foreign, isEditable: false, commit: { _ in committed += 1 })301        model.add(PDFAnnotationFactory.note(at: PDFPoint(x: 0.5, y: 0.5), page: 1))302        model.remove("a-web")303        model.addNote(at: PDFPoint(x: 0.2, y: 0.2), page: 1, pageAspect: 1)304        model.commitPageIfNeeded()305        #expect(committed == 0 && model.annotations.count == 2)306    }307308    @Test func annotatingAndSavingNeverChangesAByteOfThePDF() async throws {309        let app = try makeApp()310        let noteId = try await app.createNote(title: "Lecture")311        let fileNode = try await app.attach(data: TestPDF.data(), filename: "cours.pdf", mime: "application/pdf", to: noteId)312        let attachmentId = try DrawingBlockIO.attachmentId(of: fileNode)313        let url = try await app.localFile(forAttachment: attachmentId)314        let hashBefore = try TestPDF.sha256(url)315        let sizeBefore = try #require(try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int)316        let dateBefore = try #require(try FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate] as? Date)317318        var committed: [PMNode] = []319        let model = PDFAnnotationModel(block: PDFBlock(attachmentId: attachmentId, name: "cours.pdf"), isEditable: true, commit: { if let node = $0 { committed.append(node) } })320        await model.load(app: app)321        #expect(model.phase == .ready && model.pageCount == 2 && model.currentPage == 1)322        let document = try #require(model.document)323324        // a highlight from a selection, an ink stroke, a note — then edits, a removal, a page change325        let selection = try #require(document.findString("Seconde ligne", withOptions: []).first)326        #expect(model.highlight(selection) == 1)327        model.addInk(viewPoints: (0...40).map { CGPoint(x: 80 + CGFloat($0) * 6, y: 420 + 30 * sin(CGFloat($0) / 5)) }, in: TestPDF.pageSize, page: 1)328        model.addNote(at: PDFPoint(x: 0.7, y: 0.3), page: 2, pageAspect: 612.0 / 792)329        var note = try #require(model.editing)330        note.note = "Revoir cette définition"331        model.update(note)332        model.editing = nil333        #expect(model.annotations.map(\.kind) == [.highlight, .ink, .note])334        #expect(model.annotations(onPage: 2).first?.note == "Revoir cette définition")335        let inkToRemove = try #require(model.annotations.first { $0.kind == .ink })336        model.remove(inkToRemove.id)337        model.go(toPage: 2)338        model.commitPageIfNeeded()339        model.go(toPage: 99) // clamped340        #expect(model.currentPage == 2 && model.pageRequest == 2)341342        // what was saved: the node's attributes only343        let lastNode = try #require(committed.last)344        let saved = try #require(PDFBlock(node: lastNode))345        #expect(saved.page == 2 && saved.attachmentId == attachmentId && saved.name == "cours.pdf")346        #expect(saved.annotations.map(\.kind) == [.highlight, .note])347        #expect(saved.annotations[0].text == "Seconde ligne" && saved.annotations[0].page == 1 && saved.annotations[0].rects.count == 1)348        // the note travels in the document and its export line349        var note2 = NoteDocument()350        _ = note2.insertBlockAtom(saved.node(), after: 0)351        #expect(note2.plainText().contains("Revoir cette définition") && note2.plainText().contains("Seconde ligne"))352        try await app.save(noteId: noteId, title: "Lecture", document: note2)353354        // the file: same bytes, same size, same modification date; PDFKit still sees no annotation in it355        #expect(try TestPDF.sha256(url) == hashBefore)356        #expect(try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int == sizeBefore)357        #expect(try FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate] as? Date == dateBefore)358        #expect(document.page(at: 0)?.annotations.isEmpty == true && document.page(at: 1)?.annotations.isEmpty == true)359        let reopened = try #require(PDFDocument(url: url))360        #expect(reopened.page(at: 0)?.annotations.isEmpty == true)361        let record = try #require(try await app.store.attachment(id: attachmentId))362        #expect(record.sha256 == hashBefore)363        // reopening the block shows the annotations again, on the remembered page364        let again = PDFAnnotationModel(block: saved, isEditable: true, commit: { _ in })365        await again.load(app: app)366        #expect(again.currentPage == 2 && again.annotations.count == 2)367    }368369    @Test func aMissingOrUnreadableFileIsAnnouncedAndNothingIsCommitted() async throws {370        let app = try makeApp()371        let noteId = try await app.createNote(title: "Lecture")372        var committed = 0373        let missing = PDFAnnotationModel(block: PDFBlock(attachmentId: UUID().uuidString.lowercased(), name: "absent.pdf"), isEditable: true, commit: { _ in committed += 1 })374        await missing.load(app: app)375        if case .failed(let message) = missing.phase { #expect(message.contains("Rien n’a été modifié")) } else { Issue.record("missing file: \(missing.phase)") }376        let badId = try DrawingBlockIO.attachmentId(of: await app.attach(data: Data("pas un pdf".utf8), filename: "faux.pdf", mime: "application/pdf", to: noteId))377        let bad = PDFAnnotationModel(block: PDFBlock(attachmentId: badId, name: "faux.pdf"), isEditable: true, commit: { _ in committed += 1 })378        await bad.load(app: app)379        if case .failed = bad.phase {} else { Issue.record("unreadable file: \(bad.phase)") }380        bad.commitPageIfNeeded()381        #expect(committed == 0)382        // the page remembered by the block is clamped to the document383        let okId = try DrawingBlockIO.attachmentId(of: await app.attach(data: TestPDF.data(), filename: "ok.pdf", mime: "application/pdf", to: noteId))384        let far = PDFAnnotationModel(block: PDFBlock(attachmentId: okId, name: "ok.pdf", page: 40), isEditable: true, commit: { _ in committed += 1 })385        await far.load(app: app)386        #expect(far.phase == .ready && far.currentPage == 2)387    }388}389
Files main
Menu

Theme