SPB Git

Repository Public

Fixtures.swift 18.9 KB 284 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocFormatsTests/Fixtures.swift3// Description: Test support: a document using every block and inline case, generated images and PDFs, a structural description4//              of a document that ignores generated ids, and a runner for the external tools used as independent oracles.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreGraphics10import CoreText11import ImageIO12import DocModel13import DocContainer14@testable import DocFormats1516enum Fixture {17    /// A real PNG of the given pixel size.18    static func png(width: Int = 8, height: Int = 6, red: CGFloat = 0.2) -> Data {19        let space = CGColorSpaceCreateDeviceRGB()20        let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!21        ctx.setFillColor(CGColor(red: red, green: 0.4, blue: 0.9, alpha: 1))22        ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))23        let out = NSMutableData()24        let dest = CGImageDestinationCreateWithData(out, "public.png" as CFString, 1, nil)!25        CGImageDestinationAddImage(dest, ctx.makeImage()!, nil)26        CGImageDestinationFinalize(dest)27        return out as Data28    }2930    static func jpeg(width: Int = 10, height: Int = 10) -> Data {31        let space = CGColorSpaceCreateDeviceRGB()32        let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!33        ctx.setFillColor(CGColor(red: 0.9, green: 0.5, blue: 0.1, alpha: 1))34        ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))35        let out = NSMutableData()36        let dest = CGImageDestinationCreateWithData(out, "public.jpeg" as CFString, 1, nil)!37        CGImageDestinationAddImage(dest, ctx.makeImage()!, nil)38        CGImageDestinationFinalize(dest)39        return out as Data40    }4142    /// A PDF with one page per string array; each string is drawn as one line of text.43    static func pdf(pages: [[String]], password: String? = nil, title: String? = nil) -> Data {44        let data = NSMutableData()45        var box = CGRect(x: 0, y: 0, width: 612, height: 792)46        var info: [CFString: Any] = [:]47        if let password { info[kCGPDFContextUserPassword] = password; info[kCGPDFContextOwnerPassword] = password + "-owner" }48        if let title { info[kCGPDFContextTitle] = title }49        let consumer = CGDataConsumer(data: data as CFMutableData)!50        let ctx = CGContext(consumer: consumer, mediaBox: &box, info as CFDictionary)!51        let font = CTFontCreateWithName("Helvetica" as CFString, 12, nil)52        for lines in pages {53            ctx.beginPDFPage(nil)54            var y: CGFloat = 72055            for line in lines {56                if !line.isEmpty {57                    let attributed = NSAttributedString(string: line, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font])58                    ctx.textPosition = CGPoint(x: 72, y: y)59                    CTLineDraw(CTLineCreateWithAttributedString(attributed), ctx)60                }61                y -= line.isEmpty ? 28 : 1662            }63            ctx.endPDFPage()64        }65        ctx.closePDF()66        return data as Data67    }6869    static let date1 = Date(timeIntervalSinceReferenceDate: 815_000_000.123456789)70    static let date2 = Date(timeIntervalSinceReferenceDate: 815_086_400.5)7172    /// A document that uses every `Block` case, every `Inline` case and every annotation of the model.73    static func rich() -> DocumentModel {74        var doc = DocumentModel(meta: DocumentMetadata(title: "Rich « fixture »", author: "Ada Lovelace", subject: "Testing", keywords: ["alpha", "beta, gamma"],75                                                       language: "fr-CA", created: date1, modified: date2))76        doc.settings = DocumentSettings(trackChanges: true, citationStyle: "ieee", smartQuotes: false, smartDashes: true)77        doc.styles.upsert(Style(id: "Custom Style/1", name: "Custom", basedOn: StyleID.normal, char: CharProps(fontFamily: "Menlo", fontSize: 9.5, color: RGBA(hex: 0x336699)),78                                para: ParaProps(alignment: .justified, tabs: [TabStop(position: 100, kind: .decimal, leader: .dots)])))79        let bullets = ListDefinition.bullets(id: "bul"), numbers = ListDefinition.multilevel(id: "num")80        doc.lists = [bullets, numbers]81        let png = Asset(id: "img/1 é", mimeType: "image/png", data: png(width: 40, height: 30))82        let jpg = Asset(id: "photo", mimeType: "image/jpeg", data: jpeg())83        doc.assets = [png.id: png, jpg.id: jpg]84        doc.preservedParts = ["/word/vbaProject.bin": Data((0..<600).map { UInt8($0 % 256) }), "customXml/item1.xml": Data("<x a=\"1\"/>".utf8), "odd:name?.bin": Data([1, 2, 3])]85        doc.comments = [Comment(id: "c1", author: "Reviewer", date: date2, text: "Really?", resolved: true, replies: [CommentReply(id: "r1", author: "Ada", date: date1, text: "Yes.")])]86        doc.bibliography = [BibEntry(key: "knuth1984", type: "book", authors: [PersonName(family: "Knuth", given: "Donald E.")], editors: [PersonName(family: "", literal: "ACM")],87                                     year: 1984, month: 5, day: 1, fields: ["title": "The TeXbook", "publisher": "Addison-Wesley"]),88                            BibEntry(key: "doe:2020", fields: ["title": "On Things"])]89        let note1 = Note(id: "n1", kind: .footnote, paragraphs: [Paragraph(style: StyleID.footnoteText, runs: [Run("A footnote with "), Run("emphasis", props: CharProps(italic: true)), Run(".")])])90        let note2 = Note(id: "n2", kind: .endnote, paragraphs: [Paragraph("An endnote.", style: StyleID.footnoteText), Paragraph("Second paragraph.", style: StyleID.footnoteText)])91        doc.notes = [note1.id: note1, note2.id: note2]9293        var body: [Block] = []94        body.append(.paragraph(Paragraph(id: "title", style: StyleID.title, runs: [Run("Rich fixture")])))95        body.append(.toc(TOCBlock(id: "toc", kind: .contents, title: "Sommaire", maxLevel: 2)))96        body.append(.paragraph(Paragraph(id: "h1", style: StyleID.heading(1), runs: [Run(inline: .bookmark("intro")), Run("Introduction")])))9798        var mixed = Paragraph(id: "mixed", props: ParaProps(alignment: .justified, indentLeft: 12, firstLineIndent: 18, spaceBefore: 4, lineSpacing: .exact(15),99                                                           tabs: [TabStop(position: 72, kind: .center)], borderLeft: BorderLine(width: 2, color: RGBA(hex: 0xFF0000), style: .dashed)))100        var commented = Run("Plain ", comments: ["c1"])101        commented.formatRevision = FormatRevision(id: "fr1", author: "Ada", date: date1, previous: CharProps(bold: true), previousCharStyle: StyleID.strong)102        mixed.runs = [103            commented,104            Run("bold", props: CharProps(bold: true)), Run(" "), Run("italic", props: CharProps(italic: true)), Run(" "),105            Run("link", props: CharProps(link: "https://example.org/a?b=1&c=2"), charStyle: StyleID.hyperlink), Run(" "),106            Run("styled", props: CharProps(fontFamily: "Georgia", fontSize: 14, weight: 300, underline: true, strikethrough: true, color: RGBA(r: 0.1, g: 0.2, b: 0.3, a: 0.5),107                                           highlight: RGBA(hex: 0xFFFF00), vertical: .superscript, baselineShift: 1.5, tracking: 0.4, kerning: false, ligatures: false,108                                           smallCaps: true, allCaps: false, language: "de")),109            Run(" inserted", revision: Revision(id: "rv1", kind: .insertion, author: "Ada", date: date1)),110            Run(" deleted", revision: Revision(id: "rv2", kind: .deletion, author: "Bob", date: date2)),111            Run(inline: .image(ImageObject(asset: png.id, width: 120, height: 90, altText: "A blue box", crop: Insets(top: 0.1, left: 0, bottom: 0, right: 0.2), rotation: 15,112                                           placement: .floating(wrap: .square, align: .right, xOffset: 3, yOffset: 4)))),113            Run(inline: .image(ImageObject(asset: jpg.id, width: 10, height: 10, altText: "Photo"))),114            Run(inline: .shape(ShapeObject(kind: .callout, width: 50, height: 20, strokeWidth: 2, fill: RGBA(hex: 0xEEEEEE), text: "Note", altText: "A callout"))),115            Run(inline: .equation(Equation(latex: "e^{i\\pi}+1=0"))),116            Run(inline: .note(NoteRef(kind: .footnote, id: note1.id))),117            Run(inline: .note(NoteRef(kind: .endnote, id: note2.id))),118            Run(inline: .citation(Citation(items: [CitationItem(key: "knuth1984", locator: "p. 4", prefix: "see"), CitationItem(key: "doe:2020", suffix: "passim", suppressAuthor: true)]))),119            Run(inline: .crossRef(CrossRef(target: "figcap", display: .labelAndNumber))),120            Run(inline: .crossRef(CrossRef(target: "intro", display: .page))),121            Run(inline: .field(.pageNumber)), Run(inline: .field(.pageCount)), Run(inline: .field(.date(format: "yyyy"))), Run(inline: .field(.title)),122            Run(inline: .field(.author)), Run(inline: .field(.headingText(level: 2))),123            Run(" end\u{2028}second line\ttabbed"),124        ]125        mixed.markRevision = Revision(id: "rv3", kind: .insertion, author: "Ada", date: date1)126        body.append(.paragraph(mixed))127128        body.append(.paragraph(Paragraph(id: "eq", runs: [Run(inline: .equation(Equation(latex: "\\int_0^1 x^2\\,dx = \\frac{1}{3}", display: true)))])))129        body.append(.paragraph(Paragraph(id: "figcap", style: StyleID.caption, runs: [Run("Figure "), Run(inline: .field(.sequence("Figure"))), Run(": A caption")])))130        body.append(.paragraph(Paragraph(id: "li1", style: StyleID.listParagraph, runs: [Run("First bullet")], list: ListItem(listID: "bul", level: 0))))131        body.append(.paragraph(Paragraph(id: "li2", style: StyleID.listParagraph, runs: [Run("Nested bullet")], list: ListItem(listID: "bul", level: 1))))132        body.append(.paragraph(Paragraph(id: "li3", style: StyleID.listParagraph, runs: [Run("One")], list: ListItem(listID: "num", level: 0))))133        body.append(.paragraph(Paragraph(id: "li4", style: StyleID.listParagraph, runs: [Run("One point one")], list: ListItem(listID: "num", level: 1))))134        body.append(.paragraph(Paragraph(id: "custom", style: "Custom Style/1", runs: [Run("Custom styled")])))135136        var table = Table(id: "tbl", columnWidths: [100, 150, 80], rows: [], style: .banded, alignment: .center)137        var merged = TableCell(id: "c00", paragraphs: [Paragraph("Header A+B", style: StyleID.tableText)], colSpan: 2, shading: RGBA(hex: 0xDDEEFF), vAlign: .center)138        merged.borderTop = BorderLine(width: 1.5, style: .double)139        merged.borderBottom = BorderLine(); merged.borderLeft = BorderLine(style: .dotted); merged.borderRight = BorderLine(color: RGBA(hex: 0x00FF00))140        var formula = TableCell(id: "c22", paragraphs: [Paragraph("42", style: StyleID.tableText)])141        formula.formula = "=SUM(ABOVE)"142        table.rows = [143            TableRow(id: "r0", cells: [merged, TableCell(id: "c02", paragraphs: [Paragraph("Tall", style: StyleID.tableText)], vMerge: .restart)], isHeader: true, minHeight: 24),144            TableRow(id: "r1", cells: [TableCell("a1"), TableCell("b1"), TableCell(id: "c12", vMerge: .continue)]),145            TableRow(id: "r2", cells: [TableCell("a2"), TableCell(id: "b2", paragraphs: [Paragraph("line one", style: StyleID.tableText), Paragraph("line two", style: StyleID.tableText)], vAlign: .bottom), formula]),146        ]147        body.append(.table(table))148        body.append(.pageBreak(BreakBlock(id: "pb", kind: .page)))149        body.append(.pageBreak(BreakBlock(id: "cb", kind: .column)))150        var setup = PageSetup(paper: .a4, landscape: true, margins: Insets(top: 50, left: 60, bottom: 70, right: 80), columns: 2, columnGap: 18, columnRule: true,151                              headerDistance: 30, footerDistance: 28,152                              header: HeaderFooter(default: [Paragraph(id: "hd", style: StyleID.header, runs: [Run("Header "), Run(inline: .field(.pageNumber))])], first: [Paragraph("First", style: StyleID.header)], even: [Paragraph("Even", style: StyleID.header)]),153                              footer: HeaderFooter(default: [Paragraph("Footer", style: StyleID.footer)]),154                              differentFirstPage: true, differentOddEven: true, pageNumberStart: 5, pageNumberFormat: .lowerRoman,155                              border: PageBorder(line: BorderLine(width: 2), inset: 20), background: RGBA(hex: 0xFFFDF5), watermark: "DRAFT")156        setup.columns = 2157        body.append(.sectionBreak(SectionBreak(id: "sb", kind: .oddPage, setup: setup)))158        body.append(.paragraph(Paragraph(id: "h2", style: StyleID.heading(2), runs: [Run("Second section")])))159        body.append(.paragraph(Paragraph(id: "quote", style: StyleID.quote, runs: [Run("A quotation.")])))160        body.append(.paragraph(Paragraph(id: "code", style: StyleID.code, runs: [Run("let x = 1\u{2028}print(x)")])))161        body.append(.toc(TOCBlock(id: "lof", kind: .figures, title: nil, maxLevel: 1)))162        body.append(.toc(TOCBlock(id: "lot", kind: .tables, title: "Tables", maxLevel: 1)))163        body.append(.bibliography(BibliographyBlock(id: "bib", title: "Références")))164        doc.body = body165        doc.pageSetup.header = HeaderFooter(default: [Paragraph(id: "hd0", style: StyleID.header, runs: [Run("Main header")])])166        return doc167    }168}169170/// A structural description of a document that ignores ids: one line per block, with formatting flags and inline objects.171enum Describe {172    static func run(_ r: Run, _ doc: DocumentModel) -> String {173        if let inline = r.inline {174            switch inline {175            case .image(let i): return "<img \(Int(i.width.rounded()))x\(Int(i.height.rounded())) alt=\(i.altText) data=\(doc.assets[i.asset]?.data.count ?? -1)>"176            case .shape(let s): return "<shape \(s.text)>"177            case .equation(let e): return e.display ? "<EQ \(e.latex)>" : "<eq \(e.latex)>"178            case .note(let n): return "<\(n.kind.rawValue) " + (doc.notes[n.id]?.paragraphs.map { paragraph($0, doc) }.joined(separator: " / ") ?? "MISSING") + ">"179            case .citation(let c): return "<cite " + c.items.map { "\($0.prefix ?? "")|\($0.suppressAuthor ? "-" : "")\($0.key)|\($0.locator ?? "")|\($0.suffix ?? "")" }.joined(separator: ";") + ">"180            case .crossRef(let c): return "<ref \(c.display.rawValue)>"181            case .field: return "<field>"182            case .bookmark(let b): return "<bm \(b)>"183            }184        }185        let c = ModelIdiom.explicitChar(r, styles: doc.styles)186        var flags = ""187        if ModelIdiom.isBold(c) { flags += "b" }188        if c.italic == true { flags += "i" }189        if c.underline == true, c.link == nil { flags += "u" }190        if c.strikethrough == true { flags += "s" }191        if c.vertical == .superscript { flags += "^" }192        if c.vertical == .subscript { flags += "_" }193        if r.charStyle == StyleID.inlineCode { flags += "c" }194        if c.highlight != nil { flags += "h" }195        var s = r.text.replacingOccurrences(of: "\u{2028}", with: "⏎")196        if let link = c.link { s = "[\(s)](\(link))" }197        return flags.isEmpty ? s : "{\(flags):\(s)}"198    }199200    static func paragraph(_ p: Paragraph, _ doc: DocumentModel, numbering: Numbering? = nil) -> String {201        var q = p202        // Merge runs that only differ by things the description ignores.203        var parts: [String] = []204        q.normalize()205        for r in q.runs { parts.append(run(r, doc)) }206        var head = p.style207        if let item = p.list { head += " L\(item.level)" + (numbering?.listLabels[p.id].map { "(\($0))" } ?? "") }208        return "\(head): " + parts.joined()209    }210211    static func blocks(_ doc: DocumentModel) -> [String] {212        let numbering = Numbering(doc)213        var out: [String] = []214        for block in doc.body {215            switch block {216            case .paragraph(let p): out.append(ModelIdiom.isRule(p) ? "RULE" : paragraph(p, doc, numbering: numbering))217            case .table(let t):218                out.append("TABLE \(t.columnCount) cols")219                for row in t.rows {220                    out.append("  " + (row.isHeader ? "H " : "R ") + row.cells.map { cell in221                        var s = cell.paragraphs.map { paragraph($0, doc, numbering: numbering) }.joined(separator: " / ")222                        if cell.colSpan > 1 { s = "<span \(cell.colSpan)>" + s }223                        if cell.vMerge != .none { s = "<\(cell.vMerge.rawValue)>" + s }224                        return s225                    }.joined(separator: " | "))226                }227            case .pageBreak: out.append("PAGEBREAK")228            case .sectionBreak: out.append("SECTIONBREAK")229            case .toc(let t): out.append("TOC \(t.kind.rawValue)")230            case .bibliography: out.append("BIBLIOGRAPHY")231            }232        }233        return out234    }235236    /// All the text of the body in reading order, one string per paragraph (table cells included).237    static func texts(_ doc: DocumentModel) -> [String] {238        var out: [String] = []239        DocumentModel.forEachParagraph(in: doc.body) { p, _ in out.append(p.visibleText) }240        return out241    }242}243244/// External command-line tools used as independent oracles. Every use is skipped cleanly when the tool is not installed.245enum Tool {246    static let pandoc = "/opt/homebrew/bin/pandoc"247    static let textutil = "/usr/bin/textutil"248    static func available(_ path: String) -> Bool { FileManager.default.isExecutableFile(atPath: path) }249250    static func run(_ path: String, _ arguments: [String], input: Data? = nil) -> (status: Int32, output: Data)? {251        guard available(path) else { return nil }252        let process = Process()253        process.executableURL = URL(fileURLWithPath: path)254        process.arguments = arguments255        let stdout = Pipe(), stdin = Pipe()256        process.standardOutput = stdout257        process.standardError = Pipe()258        process.standardInput = stdin259        do { try process.run() } catch { return nil }260        // Feed the input from another thread so a full pipe never blocks both sides.261        let writer = Thread { [input] in262            if let input { try? stdin.fileHandleForWriting.write(contentsOf: input) }263            try? stdin.fileHandleForWriting.close()264        }265        writer.start()266        let output = stdout.fileHandleForReading.readDataToEndOfFile()267        process.waitUntilExit()268        return (process.terminationStatus, output)269    }270271    static func temporaryFile(_ name: String, _ data: Data) throws -> URL {272        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("orixdocs-formats-tests-\(UUID().uuidString)")273        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)274        let url = dir.appendingPathComponent(name)275        try data.write(to: url)276        return url277    }278279    /// Letters and digits only, lower-cased: what remains comparable between two renderings of the same text.280    static func words(_ s: String) -> [String] {281        s.lowercased().split(whereSeparator: { !($0.isLetter || $0.isNumber) }).map(String.init)282    }283}284
Files main
Menu

Theme