SPB Git

Repository Public

MediaExportTests.swift 34.4 KB 588 lines swift

1// SP Notes iOS2// File: Tests/MediaExportTests.swift3// Description: Export of a note (Markdown, text, HTML, RTF, PDF), the ZIP writer checked by an independent reader, the table and4//              link models, the equation shortcuts, drawing rendering and on-device text recognition.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import PDFKit9import PencilKit10import Testing11import UIKit12import zlib13import SPNotesCore14@testable import SPNotes1516// MARK: fixtures1718private let imageSource = "/api/files/0b7f6c0e-3f0a-4d5e-9b0a-222222222222"1920@MainActor21private func richDocument() -> NoteDocument {22    var document = NoteDocument(markdown: """23    # Recette de crêpes2425    Un paragraphe avec du **gras**, de l'*italique* et un [lien](https://example.org/page).2627    - farine tamisée28    - lait entier2930    1. mélanger31    2. reposer3233    - [x] acheter les oeufs34    - [ ] beurrer la poêle3536    > Citation mémorable3738    ```39    let pate = 25040    ```4142    Comparaison a < b & c > d "guillemets".43    """)44    var table = PMNode.table(rows: 2, cols: 2, withHeaderRow: true)45    table.setTableCellText("Ingrédient", row: 0, column: 0)46    table.setTableCellText("Quantité", row: 0, column: 1)47    table.setTableCellText("Sucre", row: 1, column: 0)48    table.setTableCellText("40 grammes", row: 1, column: 1)49    var last = document.insertBlockAtom(table, after: document.lines.count - 1)50    last = document.insertBlockAtom(.image(src: imageSource, alt: "photo.png", title: "Légende de la photo"), after: last)51    last = document.insertBlockAtom(.blockMath(latex: "E = mc^2"), after: last)52    last = document.insertBlockAtom(.horizontalRule(), after: last)53    document.insert(lines: [.paragraph(text: "Dernier paragraphe final.")], at: document.lines.count)54    return document55}5657@MainActor58private func samplePicture(size: CGSize = CGSize(width: 120, height: 80)) -> UIImage {59    let format = UIGraphicsImageRendererFormat()60    format.scale = 161    format.opaque = true62    return UIGraphicsImageRenderer(size: size, format: format).image { context in63        UIColor.systemTeal.setFill(); context.fill(CGRect(origin: .zero, size: size))64        UIColor.white.setFill(); context.fill(CGRect(x: 10, y: 10, width: 40, height: 20))65    }66}6768private func normalized(_ text: String) -> String {69    text.replacingOccurrences(of: "\u{00A0}", with: " ").split(whereSeparator: \.isWhitespace).joined(separator: " ").lowercased()70}7172// MARK: exporter7374@MainActor75@Suite struct NoteExporterTests {76    @Test func markdownAndPlainTextComeFromTheDocumentAPI() throws {77        let document = richDocument()78        let url = try NoteExporter.export(document: document, title: "Recette: crêpes / été?", format: .markdown, imageProvider: { _ in nil })79        #expect(url.lastPathComponent == "Recette crêpes été.md")80        #expect(try String(contentsOf: url, encoding: .utf8) == document.markdown())81        let text = try NoteExporter.export(document: document, title: "Texte", format: .plainText, imageProvider: { _ in nil })82        #expect(text.pathExtension == "txt")83        #expect(try String(contentsOf: text, encoding: .utf8) == document.plainText())84    }8586    @Test func fileNamesAreSanitized() {87        #expect(NoteExporter.sanitizedFileName("  a/b\\c:d*e?f\"g<h>i|j  ") == "a b c d e f g h i j")88        #expect(NoteExporter.sanitizedFileName("...") == "Note")89        #expect(NoteExporter.sanitizedFileName("") == "Note")90        #expect(NoteExporter.sanitizedFileName("ligne\nsuivante\t.") == "ligne suivante")91        #expect(NoteExporter.sanitizedFileName(String(repeating: "x", count: 300)).count == 80)92    }9394    @Test func htmlIsSelfContained() throws {95        let document = richDocument()96        let url = try NoteExporter.export(document: document, title: "Crêpes <maison>", format: .html, imageProvider: { $0 == imageSource ? samplePicture() : nil })97        let html = try String(contentsOf: url, encoding: .utf8)98        #expect(html.contains("Crêpes &lt;maison&gt;"))99        #expect(html.contains("a &lt; b &amp; c &gt; d"))100        #expect(html.contains("Dernier paragraphe final."))101        #expect(html.contains("<img src=\"data:image/jpeg;base64,"))102        #expect(!html.contains("src=\"\(imageSource)\""))103        // Without the picture on the device the reference is kept as it is.104        let bare = NoteExporter.html(document: document, title: "t", imageProvider: { _ in nil })105        #expect(bare.contains("src=\"\(imageSource)\""))106    }107108    @Test(arguments: [true, false]) func rtfParsesBack(withPicture: Bool) throws {109        let document = richDocument()110        let url = try NoteExporter.export(document: document, title: "Riche", format: .rtf, imageProvider: { withPicture && $0 == imageSource ? samplePicture() : nil })111        let data = try Data(contentsOf: url)112        #expect(String(decoding: data.prefix(5), as: UTF8.self) == "{\\rtf")113        #expect(String(decoding: data, as: UTF8.self).contains("\\pict\\jpegblip") == withPicture)114        #expect(String(decoding: data, as: UTF8.self).contains("\\pict\\pngblip")) // the block equation115        var attributes: NSDictionary?116        let parsed = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: &attributes)117        let text = parsed.string118        for needle in ["Recette de crêpes", "gras", "farine tamisée", "1.\tmélanger", "•\tlait entier", "☑\tacheter les oeufs", "☐\tbeurrer la poêle", "Citation mémorable", "let pate = 250", "a < b & c > d", "Ingrédient\tQuantité", "Sucre\t40 grammes", "Dernier paragraphe final."] {119            #expect(text.contains(needle), "missing in RTF: \(needle)")120        }121        #expect(!text.contains("SPNPICT"))122        #expect(text.range(of: "[0-9a-f]{64}", options: .regularExpression) == nil, "picture bytes leaked as text")123        #expect(text.contains("[Image : photo.png]") == !withPicture)124        // light appearance: the body is dark text, whatever the device appearance125        let location = (text as NSString).range(of: "Dernier paragraphe").location126        let color = try #require(parsed.attribute(.foregroundColor, at: location, effectiveRange: nil) as? UIColor)127        var white: CGFloat = 1128        color.getWhite(&white, alpha: nil)129        #expect(white < 0.4)130        let bold = try #require(parsed.attribute(.font, at: (text as NSString).range(of: "gras").location, effectiveRange: nil) as? UIFont)131        #expect(bold.fontDescriptor.symbolicTraits.contains(.traitBold))132        #expect(parsed.attribute(.link, at: (text as NSString).range(of: "lien").location, effectiveRange: nil) != nil)133    }134135    @Test func styledStringIsLightWhateverTheAppearance() {136        var string = NSMutableAttributedString()137        UITraitCollection(userInterfaceStyle: .dark).performAsCurrent {138            string = NoteExporter.styledString(document: richDocument(), contentWidth: 400, imageProvider: { _ in nil })139        }140        string.enumerateAttribute(.foregroundColor, in: NSRange(location: 0, length: string.length), options: []) { value, _, _ in141            guard let color = value as? UIColor else { return }142            var white: CGFloat = 0143            color.resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark)).getWhite(&white, alpha: nil)144            #expect(white < 0.75, "a text colour stayed dynamic or light")145        }146    }147148    @Test func pdfHasSelectableText() throws {149        let document = richDocument()150        let url = try NoteExporter.export(document: document, title: "Crêpes du dimanche", format: .pdf, imageProvider: { $0 == imageSource ? samplePicture() : nil })151        let pdf = try #require(PDFDocument(url: url))152        #expect(pdf.pageCount >= 1)153        let text = normalized(pdf.string ?? "")154        for needle in ["recette de crêpes", "farine tamisée", "mélanger", "citation mémorable", "let pate = 250", "dernier paragraphe final", "ingrédient", "40 grammes", "crêpes du dimanche", "1 / \(pdf.pageCount)"] {155            #expect(text.contains(needle), "missing in PDF: \(needle)")156        }157        let page = try #require(pdf.page(at: 0)).bounds(for: .mediaBox).size158        let expected = NoteExporter.PageLayout.forLocale().pageSize159        #expect(abs(page.width - expected.width) < 1 && abs(page.height - expected.height) < 1)160    }161162    @Test func paperSizeFollowsTheRegion() {163        #expect(NoteExporter.PageLayout.forLocale(Locale(identifier: "fr_CA")).pageSize.width == 612)164        #expect(NoteExporter.PageLayout.forLocale(Locale(identifier: "en_US")).pageSize.width == 612)165        #expect(NoteExporter.PageLayout.forLocale(Locale(identifier: "fr_FR")).pageSize.height == 841.8)166    }167168    @Test func longDocumentPaginates() throws {169        let paragraphs = (1...160).map { "Paragraphe numéro \($0) : " + String(repeating: "des mots pour remplir la page, ", count: 6) + "fin\($0)." }170        let document = NoteDocument(markdown: paragraphs.joined(separator: "\n\n"))171        let data = try NoteExporter.data(document: document, title: "Long", format: .pdf, imageProvider: { _ in nil })172        let pdf = try #require(PDFDocument(data: data))173        #expect(pdf.pageCount >= 4)174        let text = normalized(pdf.string ?? "")175        #expect(text.contains("fin1.") && text.contains("fin80.") && text.contains("fin160."))176        let lastPage = normalized(pdf.page(at: pdf.pageCount - 1)?.string ?? "")177        #expect(lastPage.contains("\(pdf.pageCount) / \(pdf.pageCount)"))178        // every page carries text: no blank page from a layout that stopped advancing179        for index in 0..<pdf.pageCount {180            let pageText = pdf.page(at: index)?.string ?? ""181            #expect(pageText.count > 20)182        }183    }184185    @Test func emptyDocumentExportsEverywhere() throws {186        for format in ExportFormat.allCases {187            let data = try NoteExporter.data(document: NoteDocument(), title: "", format: format, imageProvider: { _ in nil })188            if format == .pdf { #expect(PDFDocument(data: data)?.pageCount == 1) }189            if format == .rtf { #expect(throws: Never.self) { try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) } }190        }191    }192}193194// MARK: ZIP195196/// Minimal independent ZIP reader: end of central directory → central directory → local headers → stored / inflated bytes.197struct ZipReader {198    struct Entry { var name: String; var method: UInt16; var flags: UInt16; var crc: UInt32; var compressedSize: Int; var size: Int; var localOffset: Int }199    enum Failure: Error { case structure(String) }200    let data: Data201    var entries: [Entry] = []202203    init(url: URL) throws {204        data = try Data(contentsOf: url)205        guard data.count >= 22 else { throw Failure.structure("too short") }206        let eocd = data.count - 22 // the writer adds no archive comment207        guard u32(eocd) == 0x0605_4b50 else { throw Failure.structure("no end record") }208        let count = Int(u16(eocd + 10)), size = Int(u32(eocd + 12)), start = Int(u32(eocd + 16))209        guard u16(eocd + 8) == count, start + size == eocd else { throw Failure.structure("central directory does not end at the end record") }210        var p = start211        for _ in 0..<count {212            guard u32(p) == 0x0201_4b50 else { throw Failure.structure("bad central signature") }213            let nameLength = Int(u16(p + 28)), extra = Int(u16(p + 30)), comment = Int(u16(p + 32))214            guard let name = String(data: data.subdata(in: (p + 46)..<(p + 46 + nameLength)), encoding: .utf8) else { throw Failure.structure("name is not UTF-8") }215            entries.append(Entry(name: name, method: u16(p + 10), flags: u16(p + 8), crc: u32(p + 16), compressedSize: Int(u32(p + 20)), size: Int(u32(p + 24)), localOffset: Int(u32(p + 42))))216            p += 46 + nameLength + extra + comment217        }218        guard p == eocd else { throw Failure.structure("central directory size mismatch") }219    }220221    func u16(_ offset: Int) -> UInt16 { UInt16(data[data.startIndex + offset]) | UInt16(data[data.startIndex + offset + 1]) << 8 }222    func u32(_ offset: Int) -> UInt32 { UInt32(u16(offset)) | UInt32(u16(offset + 2)) << 16 }223224    /// The bytes of an entry, after checking the local header against the central directory and the CRC-32.225    func contents(of entry: Entry) throws -> Data {226        let p = entry.localOffset227        guard u32(p) == 0x0403_4b50 else { throw Failure.structure("bad local signature") }228        guard u16(p + 6) == entry.flags, u16(p + 8) == entry.method, u32(p + 14) == entry.crc, Int(u32(p + 18)) == entry.compressedSize, Int(u32(p + 22)) == entry.size else { throw Failure.structure("local header differs from central directory for \(entry.name)") }229        let nameLength = Int(u16(p + 26)), extra = Int(u16(p + 28))230        guard data.subdata(in: (p + 30)..<(p + 30 + nameLength)) == Data(entry.name.utf8) else { throw Failure.structure("local name differs") }231        let start = p + 30 + nameLength + extra232        let raw = data.subdata(in: start..<(start + entry.compressedSize))233        let out: Data234        switch entry.method {235        case 0: out = raw236        case 8: out = try Self.inflate(raw, expected: entry.size)237        default: throw Failure.structure("unknown method \(entry.method)")238        }239        guard out.count == entry.size else { throw Failure.structure("size mismatch for \(entry.name)") }240        let crc = out.withUnsafeBytes { crc32(crc32(0, nil, 0), $0.bindMemory(to: Bytef.self).baseAddress, uInt($0.count)) }241        guard UInt32(truncatingIfNeeded: crc) == entry.crc else { throw Failure.structure("CRC mismatch for \(entry.name)") }242        return out243    }244245    static func inflate(_ input: Data, expected: Int) throws -> Data {246        var stream = z_stream()247        guard inflateInit2_(&stream, -MAX_WBITS, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) == Z_OK else { throw Failure.structure("inflate init") }248        defer { inflateEnd(&stream) }249        var out = Data(count: max(expected, 1))250        let status: Int32 = input.withUnsafeBytes { source in251            out.withUnsafeMutableBytes { target in252                stream.next_in = UnsafeMutablePointer(mutating: source.bindMemory(to: Bytef.self).baseAddress)253                stream.avail_in = uInt(source.count)254                stream.next_out = target.bindMemory(to: Bytef.self).baseAddress255                stream.avail_out = uInt(target.count)256                return zlib.inflate(&stream, Z_FINISH)257            }258        }259        guard status == Z_STREAM_END, Int(stream.total_out) == expected else { throw Failure.structure("inflate status \(status), \(stream.total_out) of \(expected) bytes") }260        return out.prefix(expected)261    }262}263264@Suite struct ZipWriterTests {265    private func scratch() throws -> URL {266        let url = FileManager.default.temporaryDirectory.appendingPathComponent("zip-tests-\(UUID().uuidString)", isDirectory: true)267        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)268        return url269    }270271    @Test func roundTripsStoredAndDeflatedEntries() throws {272        let directory = try scratch()273        defer { try? FileManager.default.removeItem(at: directory) }274        // a compressible file larger than several chunks, and an incompressible one275        var generator = SystemRandomNumberGenerator()276        let text = Data(String(repeating: "Les crêpes sont meilleures avec du sirop d'érable. ", count: 40_000).utf8)277        let noise = Data((0..<700_000).map { _ in UInt8.random(in: 0...255, using: &generator) })278        let textURL = directory.appendingPathComponent("long.txt"), noiseURL = directory.appendingPathComponent("bruit.bin")279        try text.write(to: textURL); try noise.write(to: noiseURL)280281        let archive = directory.appendingPathComponent("test.zip")282        let zip = try ZipWriter(url: archive)283        try zip.addData(Data("# Été\n".utf8), path: "Été à Québec – notes.md")284        try zip.addFile(at: textURL, path: "attachments/long.txt")285        try zip.addFile(at: noiseURL, path: "attachments/bruit.bin")286        try zip.addFile(at: noiseURL, path: "attachments/photo.jpg") // stored by extension287        try zip.addData(Data(), path: "vide.txt")288        #expect(throws: ZipError.self) { try zip.addData(Data(), path: "VIDE.txt") }289        #expect(throws: ZipError.self) { try zip.addData(Data(), path: "../dehors.txt") }290        try zip.finish()291        #expect(throws: ZipError.self) { try zip.addData(Data(), path: "tard.txt") }292293        let reader = try ZipReader(url: archive)294        #expect(reader.entries.map(\.name) == ["Été à Québec – notes.md", "attachments/long.txt", "attachments/bruit.bin", "attachments/photo.jpg", "vide.txt"])295        #expect(reader.entries.allSatisfy { $0.flags & 0x0800 != 0 })296        #expect(reader.entries.map(\.method) == [8, 8, 8, 0, 8])297        #expect(try reader.contents(of: reader.entries[0]) == Data("# Été\n".utf8))298        #expect(try reader.contents(of: reader.entries[1]) == text)299        #expect(try reader.contents(of: reader.entries[2]) == noise)300        #expect(try reader.contents(of: reader.entries[3]) == noise)301        #expect(try reader.contents(of: reader.entries[4]).isEmpty)302        #expect(reader.entries[1].compressedSize < text.count / 20)303        #expect(reader.entries[3].compressedSize == noise.count)304    }305306    @Test func crcMatchesTheReferenceValue() throws {307        let directory = try scratch()308        defer { try? FileManager.default.removeItem(at: directory) }309        let archive = directory.appendingPathComponent("crc.zip")310        let zip = try ZipWriter(url: archive)311        try zip.addData(Data("123456789".utf8), path: "check.txt", method: .stored)312        try zip.finish()313        let reader = try ZipReader(url: archive)314        #expect(reader.entries.first?.crc == 0xCBF4_3926) // the standard CRC-32 check value315        #expect(try Data(contentsOf: archive).count == 30 + 9 + 9 + 46 + 9 + 22)316    }317318    @Test func uniqueNamesIgnoreCase() {319        var names = UniqueNames()320        #expect(names.claim("Note") == "Note")321        #expect(names.claim("note") == "note 2")322        #expect(names.claim("Note") == "Note 3")323        #expect(names.claim("photo", extension: "png") == "photo.png")324        #expect(names.claim("Photo", extension: "PNG") == "Photo 2.PNG")325    }326327    @MainActor328    @Test func archiveOfOneNote() throws {329        let directory = try scratch()330        defer { try? FileManager.default.removeItem(at: directory) }331        let id = "0b7f6c0e-3f0a-4d5e-9b0a-222222222222"332        let stored = directory.appendingPathComponent(id, isDirectory: true)333        try FileManager.default.createDirectory(at: stored, withIntermediateDirectories: true)334        let picture = stored.appendingPathComponent("photo de crêpe.png")335        let pictureData = try #require(samplePicture().pngData())336        try pictureData.write(to: picture)337        let other = directory.appendingPathComponent("b", isDirectory: true)338        try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true)339        let duplicate = other.appendingPathComponent("Photo de crêpe.png")340        try Data("autre".utf8).write(to: duplicate)341342        let document = richDocument()343        let url = try NoteArchive.exportArchive(notes: [(title: "Crêpes: la recette", document: document, attachments: [picture, duplicate], metadata: ["id": "n1", "tags": "cuisine"])], format: .markdown)344        #expect(url.lastPathComponent == "Crêpes la recette.zip")345        let reader = try ZipReader(url: url)346        #expect(reader.entries.map(\.name) == ["Crêpes la recette.md", "attachments/photo de crêpe.png", "attachments/Photo de crêpe 2.png", "metadata.json"])347        let markdown = String(decoding: try reader.contents(of: reader.entries[0]), as: UTF8.self)348        #expect(markdown == document.markdown().replacingOccurrences(of: imageSource, with: "attachments/photo%20de%20cr%C3%AApe.png"))349        #expect(markdown.contains("](attachments/photo%20de%20cr%C3%AApe.png)"))350        #expect(try reader.contents(of: reader.entries[1]) == pictureData)351        let metadata = try #require(try JSONSerialization.jsonObject(with: try reader.contents(of: reader.entries[3])) as? [String: Any])352        #expect(metadata["title"] as? String == "Crêpes: la recette")353        #expect(metadata["file"] as? String == "Crêpes la recette.md")354        #expect(metadata["format"] as? String == "markdown")355        #expect(metadata["attachments"] as? [String] == ["attachments/photo de crêpe.png", "attachments/Photo de crêpe 2.png"])356        #expect(metadata["metadata"] as? [String: String] == ["id": "n1", "tags": "cuisine"])357    }358359    @MainActor360    @Test func archiveOfSeveralNotesUsesOneFolderPerNote() async throws {361        let document = NoteDocument(markdown: "Bonjour le monde")362        let notes: [NoteArchive.Note] = [("Même titre", document, [], [:]), ("Même titre", document, [], [:]), ("Autre", document, [], ["id": "3"])]363        let url = try await NoteArchive.exportArchiveInBackground(notes: notes, format: .pdf)364        defer { try? FileManager.default.removeItem(at: url) }365        let reader = try ZipReader(url: url)366        #expect(reader.entries.map(\.name) == ["Même titre/Même titre.pdf", "Même titre/metadata.json", "Même titre 2/Même titre.pdf", "Même titre 2/metadata.json", "Autre/Autre.pdf", "Autre/metadata.json"])367        let pdf = try #require(PDFDocument(data: try reader.contents(of: reader.entries[4])))368        #expect(normalized(pdf.string ?? "").contains("bonjour le monde"))369    }370}371372// MARK: sheets' models373374@Suite struct TableEditorModelTests {375    /// 2 × 2 with a header row; the cell (1, 0) is formatted (bold).376    private func table() -> PMNode {377        var table = PMNode.table(rows: 2, cols: 2, withHeaderRow: true)378        table.setTableCellText("A", row: 0, column: 0)379        table.setTableCellText("B", row: 0, column: 1)380        table.content![1].content![0].content = [PMNode(type: "paragraph", attrs: ["textAlign": .null, "id": .string("pformatted")], content: [.text("gras", marks: [.mark(.bold)]), .text(" normal", marks: [])], text: nil, marks: nil, extra: [:])]381        table.setTableCellText("d", row: 1, column: 1)382        return table383    }384385    @Test func untouchedTableIsReturnedAsIs() {386        let source = table()387        var model = TableEditorModel(node: source)388        #expect(model.rowCount == 2 && model.columnCount == 2 && model.hasHeaderRow && !model.hasChanges)389        #expect(model.text(row: 1, column: 0) == "gras normal")390        // typing then restoring the text keeps the formatted content391        model.setText("autre", row: 1, column: 0)392        #expect(model.hasChanges)393        model.setText("gras normal", row: 1, column: 0)394        #expect(!model.hasChanges)395        #expect(model.result() == source)396    }397398    @Test func editedCellsChangeAndOthersKeepTheirFormatting() {399        let source = table()400        var model = TableEditorModel(node: source)401        model.setText("D majuscule\nsur deux lignes", row: 1, column: 1)402        let result = model.result()403        #expect(result.tableGrid[1][1].text == "D majuscule\nsur deux lignes")404        #expect(result.content![1].content![0] == source.content![1].content![0])405        #expect(result.content![0] == source.content![0])406    }407408    @Test func rowsAndColumnsFollowTheStructure() {409        var model = TableEditorModel(node: table())410        model.setText("pending", row: 1, column: 1)411        do { let changed = model.insertRow(at: 1); #expect(changed) }412        #expect(model.rowCount == 3 && model.text(row: 1, column: 0) == "" && model.text(row: 2, column: 1) == "pending")413        do { let changed = model.insertColumn(at: 0); #expect(changed) }414        #expect(model.columnCount == 3 && model.text(row: 0, column: 0) == "" && model.text(row: 0, column: 1) == "A" && model.text(row: 2, column: 2) == "pending")415        #expect(model.isHeader(row: 0, column: 0) && !model.isHeader(row: 1, column: 0))416        model.setText("nouvelle", row: 1, column: 0)417        do { let changed = model.insertRow(at: model.rowCount); #expect(changed) }418        do { let changed = model.insertColumn(at: model.columnCount); #expect(changed) }419        var grid = model.result().tableGrid420        #expect(grid.map { $0.map(\.text) } == [["", "A", "B", ""], ["nouvelle", "", "", ""], ["", "gras normal", "pending", ""], ["", "", "", ""]])421        do { let changed = model.deleteColumn(at: 0); #expect(changed) }422        do { let changed = model.deleteRow(at: 1); #expect(changed) }423        grid = model.result().tableGrid424        #expect(grid.map { $0.map(\.text) } == [["A", "B", ""], ["gras normal", "pending", ""], ["", "", ""]])425        // the formatted cell went through every structural change untouched426        #expect(model.result().content![1].content![0].content?.first?.content?.first?.marks == [.mark(.bold)])427    }428429    @Test func lastRowAndColumnCannotBeDeleted() {430        var model = TableEditorModel(node: PMNode.table(rows: 1, cols: 1, withHeaderRow: false))431        #expect(!model.canDeleteRow && !model.canDeleteColumn)432        do { let a = model.deleteRow(at: 0), b = model.deleteColumn(at: 0); #expect(!a && !b) }433        do { let a = model.deleteRow(at: 7), b = model.deleteColumn(at: 7); #expect(!a && !b) }434        #expect(model.rowCount == 1 && model.columnCount == 1)435        model.setText("hors grille", row: 4, column: 4)436        #expect(!model.hasChanges)437    }438439    @Test func headerRowToggles() {440        var model = TableEditorModel(node: table())441        do { let changed = model.toggleHeaderRow(); #expect(changed) }442        #expect(!model.hasHeaderRow && model.hasChanges)443        #expect(model.result().tableGrid[0].allSatisfy { !$0.isHeader })444        do { let changed = model.toggleHeaderRow(); #expect(changed) }445        #expect(model.hasHeaderRow && !model.hasChanges)446    }447}448449@Suite struct LinkAndMathModelTests {450    @Test func addressesAreNormalized() {451        #expect(LinkAddress.normalized("  example.org/page ") == "https://example.org/page")452        #expect(LinkAddress.normalized("http://example.org") == "http://example.org")453        #expect(LinkAddress.normalized("example.org:8080/x") == "https://example.org:8080/x")454        #expect(LinkAddress.normalized("contact@spboucher.ai") == "mailto:contact@spboucher.ai")455        #expect(LinkAddress.normalized("mailto:a@b.co") == "mailto:a@b.co")456        #expect(LinkAddress.normalized("/p/abc") == "/p/abc")457        #expect(LinkAddress.normalized("") == nil)458        #expect(LinkAddress.normalized("deux mots") == nil)459        #expect(LinkAddress.normalized("sanspoint") == nil)460        #expect(LinkAddress.normalized("javascript:alert(1)") == nil)461        #expect(LinkAddress.normalized("JavaScript:alert(1)") == nil)462        #expect(LinkAddress.normalized("file:///etc/passwd") == nil)463    }464465    @Test func onlyExternalLinksOpen() {466        #expect(LinkAddress.openableURL("example.org")?.absoluteString == "https://example.org")467        #expect(LinkAddress.openableURL("tel:+15145550100") != nil)468        #expect(LinkAddress.openableURL("/p/abc") == nil)469        #expect(LinkAddress.openableURL("spnotes://x") == nil)470        #expect(LinkAddress.openableURL("javascript:alert(1)") == nil)471    }472473    @Test func shortcutsInsertAtTheSelection() throws {474        let fraction = try #require(MathShortcut.all.first { $0.text == "\\frac{}{}" })475        var result = fraction.apply(to: "", selection: NSRange(location: 0, length: 0))476        #expect(result.text == "\\frac{}{}" && result.caret == 6)477        result = fraction.apply(to: "a + b", selection: NSRange(location: 4, length: 1))478        #expect(result.text == "a + \\frac{}{}" && result.caret == 10)479        let alpha = try #require(MathShortcut.all.first { $0.text == "\\alpha " })480        result = alpha.apply(to: "é𝑥", selection: NSRange(location: 99, length: 5)) // out of range: appended481        #expect(result.text == "é𝑥\\alpha " && result.caret == ("é𝑥\\alpha " as NSString).length)482        #expect(Set(MathShortcut.all.map(\.id)).count == MathShortcut.all.count)483    }484485    @MainActor486    @Test func everyShortcutTypesets() {487        #expect(MathPreview.image(latex: "\\frac{a}{b} + \\sqrt{x^2}", display: true, fontSize: 20, color: .black) != nil)488        #expect(MathPreview.image(latex: "   ", display: false, fontSize: 20, color: .black) == nil)489        #expect(MathPreview.image(latex: "\\frac{a}{", display: true, fontSize: 20, color: .black) == nil)490        for shortcut in MathShortcut.all where shortcut.caretOffset == shortcut.text.count && shortcut.text != "\\" {491            #expect(MathPreview.image(latex: "x " + shortcut.text + " y", display: false, fontSize: 18, color: .black) != nil, "does not typeset: \(shortcut.text)")492        }493    }494}495496// MARK: media497498@MainActor499@Suite struct MediaTests {500    @Test func drawingIsRenderedOnWhiteAndKeepsItsSource() throws {501        let points = stride(from: CGFloat(0), through: 200, by: 10).map { PKStrokePoint(location: CGPoint(x: 100 + $0, y: 300 + $0 / 2), timeOffset: TimeInterval($0) / 100, size: CGSize(width: 6, height: 6), opacity: 1, force: 1, azimuth: 0, altitude: .pi / 2) }502        let drawing = PKDrawing(strokes: [PKStroke(ink: PKInk(.pen, color: .black), path: PKStrokePath(controlPoints: points, creationDate: Date()))])503        var png = Data()504        UITraitCollection(userInterfaceStyle: .dark).performAsCurrent { png = DrawingRenderer.png(of: drawing) }505        let image = try #require(UIImage(data: png))506        let cg = try #require(image.cgImage)507        // cropped to the stroke plus the margin, at 2x508        #expect(abs(CGFloat(cg.width) - (drawing.bounds.width + 2 * DrawingRenderer.margin) * 2) <= 4)509        #expect(abs(CGFloat(cg.height) - (drawing.bounds.height + 2 * DrawingRenderer.margin) * 2) <= 4)510        #expect(cg.alphaInfo == .none || cg.alphaInfo == .noneSkipLast || cg.alphaInfo == .noneSkipFirst)511        let pixels = try rgba(of: cg)512        func pixel(_ x: Int, _ y: Int) -> (UInt8, UInt8, UInt8) { let i = (y * cg.width + x) * 4; return (pixels[i], pixels[i + 1], pixels[i + 2]) }513        #expect(pixel(2, 2) == (255, 255, 255))                // paper514        let middle = pixel(cg.width / 2, cg.height / 2)        // the stroke crosses the centre: dark ink even in dark mode515        #expect(middle.0 < 90 && middle.1 < 90 && middle.2 < 90)516        // the source is never flattened517        #expect(try PKDrawing(data: drawing.dataRepresentation()).strokes.count == 1)518        // an empty drawing still gives a valid picture519        #expect(UIImage(data: DrawingRenderer.png(of: PKDrawing())) != nil)520    }521522    private func rgba(of image: CGImage) throws -> [UInt8] {523        var pixels = [UInt8](repeating: 0, count: image.width * image.height * 4)524        let context = try #require(CGContext(data: &pixels, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: image.width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))525        context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))526        return pixels527    }528529    @Test func temporaryFilesKeepTheirNames() throws {530        let source = FileManager.default.temporaryDirectory.appendingPathComponent("source-\(UUID().uuidString).txt")531        try Data("contenu".utf8).write(to: source)532        defer { try? FileManager.default.removeItem(at: source) }533        let first = try MediaTemp.copy(source, named: "Rapport final.txt")534        let second = try MediaTemp.copy(source, named: "Rapport final.txt")535        #expect(first.lastPathComponent == "Rapport final.txt" && second.lastPathComponent == "Rapport final.txt" && first != second)536        #expect(try Data(contentsOf: first) == Data("contenu".utf8))537        let written = try MediaTemp.write(Data([1, 2, 3]), named: "a/b.bin")538        #expect(written.lastPathComponent == "a-b.bin")539        MediaTemp.discard(first)540        #expect(!FileManager.default.fileExists(atPath: first.path))541        #expect(FileManager.default.fileExists(atPath: second.path))542        MediaTemp.discard(source) // not one of ours: left alone543        #expect(FileManager.default.fileExists(atPath: source.path))544        MediaTemp.discard(second); MediaTemp.discard(written)545    }546547    @Test func pdfThumbnailShowsTheFirstPage() async throws {548        let url = try NoteExporter.export(document: richDocument(), title: "Vignette", format: .pdf, imageProvider: { _ in nil })549        let thumbnail = try #require(PDFThumbnail.image(for: url, size: CGSize(width: 120, height: 160)))550        #expect(thumbnail.size.width <= 120.5 && thumbnail.size.height <= 160.5 && thumbnail.size.width > 60)551        #expect(PDFThumbnail.pageCount(of: url) >= 1)552        #expect(PDFThumbnail.image(for: URL(fileURLWithPath: "/nonexistent.pdf"), size: CGSize(width: 10, height: 10)) == nil)553        #expect(AttachmentPreview.canPreview(url))554        #expect(await PDFThumbnail.loadImage(for: url, size: CGSize(width: 60, height: 80)) != nil)555    }556557    @Test func textRecognizerReadsLargePrintedText() async throws {558        let size = CGSize(width: 1000, height: 320)559        let format = UIGraphicsImageRendererFormat()560        format.scale = 1561        format.opaque = true562        let image = UIGraphicsImageRenderer(size: size, format: format).image { context in563            UIColor.white.setFill(); context.fill(CGRect(origin: .zero, size: size))564            ("BONJOUR MONTREAL" as NSString).draw(at: CGPoint(x: 40, y: 40), withAttributes: [.font: UIFont.boldSystemFont(ofSize: 84), .foregroundColor: UIColor.black])565            ("Notes 2026" as NSString).draw(at: CGPoint(x: 40, y: 170), withAttributes: [.font: UIFont.systemFont(ofSize: 84), .foregroundColor: UIColor.black])566        }567        let text = await TextRecognizer.recognizeText(in: image)568        // Vision's accurate recognizer may be unavailable in some simulator runtimes: an empty answer is tolerated there, a wrong one is not.569        withKnownIssue("Vision returned no text on this simulator", isIntermittent: true) {570            #expect(!text.isEmpty)571        }572        guard !text.isEmpty else { return }573        #expect(text.lowercased().contains("bonjour"))574        #expect(text.lowercased().contains("montreal"))575        #expect(text.contains("2026"))576        // from a file, and a blank picture gives nothing577        let url = try MediaTemp.write(try #require(image.jpegData(compressionQuality: 0.9)), named: "texte.jpg")578        defer { MediaTemp.discard(url) }579        let fromFile = await TextRecognizer.recognizeText(at: url)580        #expect(fromFile.lowercased().contains("bonjour"))581        let blank = UIGraphicsImageRenderer(size: CGSize(width: 200, height: 200), format: format).image { context in582            UIColor.white.setFill(); context.fill(CGRect(x: 0, y: 0, width: 200, height: 200))583        }584        let nothing = await TextRecognizer.recognizeText(in: blank)585        #expect(nothing.isEmpty)586    }587}588
Files main
Menu

Theme