Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocLayoutTests/PaginationTests.swift3// Description: Pagination correctness: page geometry, breaks, sections, columns, widow/orphan and keep rules, footnotes, tables across4// pages, generated contents, headers and footers, and geometry queries used by the editor.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Testing9import Foundation10import CoreGraphics11import CoreText12@testable import DocLayout13import DocModel1415let lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."1617func letterDoc(_ blocks: [Block]) -> DocumentModel {18 DocumentModel(styles: .standard(theme: .classic), pageSetup: PageSetup(paper: .letter), body: blocks)19}20func para(_ text: String, style: String = StyleID.normal, props: ParaProps = .none) -> Block { .paragraph(Paragraph(text, style: style, props: props)) }21func longPara(_ sentences: Int, props: ParaProps = .none) -> Block { para(Array(repeating: lorem, count: sentences).joined(separator: " "), props: props) }2223/// Body text fragments of a page, in placement order.24func bodyFragments(_ l: DocumentLayout, page: Int) -> [TextFragment] { l.pages[page].texts.filter { $0.story == .body } }2526@Suite struct PageGeometryTests {27 @Test func everythingStaysInsideTheContentArea() {28 let doc = letterDoc((0..<60).map { _ in longPara(2) })29 let l = Paginator.layout(doc)30 #expect(l.pageCount > 3)31 for page in l.pages {32 #expect(page.size == CGSize(width: 612, height: 792))33 #expect(page.contentRect == CGRect(x: 72, y: 72, width: 468, height: 648))34 for f in page.texts where f.story == .body {35 #expect(f.frame.minY >= page.contentRect.minY - 0.01)36 #expect(f.frame.maxY <= page.contentRect.maxY + 0.01, "fragment overflows the page foot")37 #expect(f.frame.minX >= page.contentRect.minX - 0.01 && f.frame.maxX <= page.contentRect.maxX + 0.01)38 for i in f.lines { #expect(f.layout.lines[i].x + f.layout.lines[i].width <= f.width + 12) }39 }40 }41 }4243 @Test func noLineIsLostOrDuplicatedAcrossPages() {44 let doc = letterDoc((0..<40).map { _ in longPara(3) })45 let l = Paginator.layout(doc)46 for (i, b) in doc.body.enumerated() {47 let frags = l.fragments(story: .body, path: ParaPath(block: i))48 let total = frags.first!.fragment.layout.lines.count49 var covered = 050 var next = 051 for f in frags { #expect(f.fragment.lines.lowerBound == next); next = f.fragment.lines.upperBound; covered += f.fragment.lines.count }52 #expect(covered == total)53 let text = frags.first!.fragment.layout.lines.map { $0.range.count }.reduce(0, +)54 #expect(text == b.paragraph!.length)55 }56 }5758 @Test func landscapeAndMarginsAreHonoured() {59 var doc = letterDoc([para("x")])60 doc.pageSetup = PageSetup(paper: .a4, landscape: true, margins: Insets(top: 50, left: 60, bottom: 70, right: 80))61 let p = Paginator.layout(doc).pages[0]62 #expect(abs(p.size.width - 841.89) < 0.01 && abs(p.size.height - 595.28) < 0.01)63 #expect(abs(p.contentRect.minX - 60) < 0.01 && abs(p.contentRect.maxX - (841.89 - 80)) < 0.01)64 #expect(abs(p.contentRect.minY - 50) < 0.01 && abs(p.contentRect.maxY - (595.28 - 70)) < 0.01)65 }6667 @Test func emptyDocumentHasOnePageAndACaret() {68 let doc = letterDoc([para("")])69 let l = Paginator.layout(doc)70 #expect(l.pageCount == 1)71 let c = l.caret(story: .body, position: Position(block: 0, offset: 0), blocks: doc.body)72 #expect(c?.page == 0 && (c?.rect.height ?? 0) > 8 && abs((c?.rect.midX ?? 0) - 72) < 1)73 }74}7576@Suite struct BreakAndSectionTests {77 @Test func pageBreakBlockAndPageBreakBefore() {78 let doc = letterDoc([para("one"), .pageBreak(BreakBlock()), para("two"), para("three", props: ParaProps(pageBreakBefore: true)), para("four")])79 let l = Paginator.layout(doc)80 #expect(l.pageCount == 3)81 #expect(l.pageOfBlock[doc.body[0].id] == 0 && l.pageOfBlock[doc.body[2].id] == 1 && l.pageOfBlock[doc.body[3].id] == 2 && l.pageOfBlock[doc.body[4].id] == 2)82 #expect(l.pages[0].markers.count == 1)83 }8485 @Test func sectionBreakChangesPageSetupAndNumbering() {86 var roman = PageSetup(paper: .letter); roman.pageNumberFormat = .lowerRoman87 var arabic = PageSetup(paper: .letter, landscape: true); arabic.pageNumberStart = 188 var doc = letterDoc([para("front"), .pageBreak(BreakBlock()), para("front 2"), .sectionBreak(SectionBreak(kind: .nextPage, setup: arabic)), para("body")])89 doc.pageSetup = roman90 let l = Paginator.layout(doc)91 #expect(l.pages.map(\.numberText) == ["i", "ii", "1"])92 #expect(l.pages[2].size.width == 792 && l.pages[2].sectionIndex == 1 && l.pages[2].isFirstOfSection)93 }9495 @Test func oddPageSectionBreakInsertsABlankPage() {96 let doc = letterDoc([para("a"), .sectionBreak(SectionBreak(kind: .oddPage, setup: PageSetup(paper: .letter))), para("b")])97 let l = Paginator.layout(doc)98 #expect(l.pageCount == 3)99 #expect(l.pages[1].isBlank && l.pages[1].texts.isEmpty)100 #expect(l.pages[2].number == 3 && l.pageOfBlock[doc.body[2].id] == 2)101 }102103 @Test func continuousSectionBreakStartsColumnsOnTheSamePage() {104 let two = PageSetup(paper: .letter, columns: 2, columnGap: 24)105 let doc = letterDoc([para("Full width title"), .sectionBreak(SectionBreak(kind: .continuous, setup: two))] + (0..<6).map { _ in longPara(2) })106 let l = Paginator.layout(doc)107 let frags = bodyFragments(l, page: 0)108 let title = frags[0]109 #expect(title.width == 468)110 let cols = frags.dropFirst()111 #expect(cols.allSatisfy { abs($0.width - 222) < 0.01 })112 #expect(cols.allSatisfy { $0.frame.minY > title.frame.maxY })113 let xs = Set(cols.map { Int($0.origin.x.rounded()) })114 #expect(xs == [72, 318])115 // The first column is filled before the second one starts.116 let left = cols.filter { $0.origin.x < 100 }, right = cols.filter { $0.origin.x > 100 }117 #expect((left.map(\.frame.maxY).max() ?? 0) > 600 && !right.isEmpty)118 }119120 @Test func columnBreakMovesToTheNextColumn() {121 var doc = letterDoc([para("a"), .pageBreak(BreakBlock(kind: .column)), para("b"), .pageBreak(BreakBlock(kind: .column)), para("c")])122 doc.pageSetup = PageSetup(paper: .letter, columns: 2)123 let l = Paginator.layout(doc)124 let a = l.fragments(story: .body, path: ParaPath(block: 0))[0], b = l.fragments(story: .body, path: ParaPath(block: 2))[0], c = l.fragments(story: .body, path: ParaPath(block: 4))[0]125 #expect(a.page == 0 && b.page == 0 && b.fragment.origin.x > a.fragment.origin.x && abs(b.fragment.origin.y - a.fragment.origin.y) < 0.01)126 #expect(c.page == 1)127 }128}129130@Suite struct KeepRuleTests {131 /// Fills the first page so that exactly `free` lines of body text remain, then appends `tail`.132 func docLeaving(lines free: Int, then tail: [Block]) -> (DocumentModel, DocumentLayout) {133 // Body line height with the classic theme: measure it.134 let probe = Paginator.layout(letterDoc([longPara(4)]))135 let lineH = probe.pages[0].texts[0].layout.lines[0].height136 let capacity = Int((648 / lineH).rounded(.down))137 // One-line paragraphs without spacing make the arithmetic exact.138 let filler = (0..<(capacity - free)).map { _ in para("Filler line.", props: ParaProps(spaceBefore: 0, spaceAfter: 0)) }139 let doc = letterDoc(filler + tail)140 return (doc, Paginator.layout(doc))141 }142143 @Test func orphanControlMovesALoneFirstLine() {144 let (doc, l) = docLeaving(lines: 1, then: [longPara(3, props: ParaProps(spaceBefore: 0, spaceAfter: 0))])145 let frags = l.fragments(story: .body, path: ParaPath(block: doc.body.count - 1))146 #expect(frags[0].page == 1, "a single first line must not stay at the foot of the page")147 }148149 @Test func widowControlLeavesTwoLinesOnTheNextPage() {150 // A paragraph that would leave exactly one line for the next page gives up one more line.151 let probe = Paginator.layout(letterDoc([longPara(2, props: ParaProps(spaceBefore: 0, spaceAfter: 0))]))152 let n = probe.pages[0].texts[0].layout.lines.count153 let (doc, l) = docLeaving(lines: n - 1, then: [longPara(2, props: ParaProps(spaceBefore: 0, spaceAfter: 0))])154 let frags = l.fragments(story: .body, path: ParaPath(block: doc.body.count - 1))155 #expect(frags.count == 2)156 #expect(frags[0].fragment.lines.count == n - 2 && frags[1].fragment.lines.count == 2)157 }158159 @Test func withoutWidowControlTheParagraphSplitsAnywhere() {160 let (doc, l) = docLeaving(lines: 1, then: [longPara(3, props: ParaProps(spaceBefore: 0, spaceAfter: 0, widowControl: false))])161 let frags = l.fragments(story: .body, path: ParaPath(block: doc.body.count - 1))162 #expect(frags[0].page == 0 && frags[0].fragment.lines.count == 1)163 }164165 @Test func keepLinesTogetherMovesTheWholeParagraph() {166 let (doc, l) = docLeaving(lines: 3, then: [longPara(3, props: ParaProps(spaceBefore: 0, spaceAfter: 0, keepLinesTogether: true))])167 let frags = l.fragments(story: .body, path: ParaPath(block: doc.body.count - 1))168 #expect(frags.count == 1 && frags[0].page == 1)169 }170171 @Test func keepWithNextKeepsAHeadingWithItsText() {172 // Room for the heading but not for the heading plus two lines of what follows.173 let (doc, l) = docLeaving(lines: 3, then: [para("A heading", style: StyleID.heading(2)), longPara(3)])174 let heading = l.fragments(story: .body, path: ParaPath(block: doc.body.count - 2))175 let body = l.fragments(story: .body, path: ParaPath(block: doc.body.count - 1))176 #expect(heading[0].page == body[0].page, "a heading must not be stranded at the foot of a page")177 #expect(heading[0].page == 1)178 }179180 @Test func aParagraphTallerThanAPageStillFlows() {181 let doc = letterDoc([longPara(60, props: ParaProps(keepLinesTogether: true))])182 let l = Paginator.layout(doc)183 #expect(l.pageCount >= 2)184 #expect(l.fragments(story: .body, path: ParaPath(block: 0)).count == l.pageCount)185 }186}187188@Suite struct FootnoteTests {189 func docWithNotes(_ count: Int, fillerBefore: Int = 0) -> DocumentModel {190 var doc = letterDoc([])191 var blocks: [Block] = (0..<fillerBefore).map { _ in longPara(2) }192 for i in 0..<count {193 let note = Note(kind: .footnote, paragraphs: [Paragraph("Footnote number \(i + 1) with enough text to be recognisable.", style: StyleID.footnoteText)])194 doc.notes[note.id] = note195 blocks.append(.paragraph(Paragraph(runs: [Run(lorem), Run(inline: .note(NoteRef(kind: .footnote, id: note.id))), Run(" " + lorem)])))196 }197 doc.body = blocks198 return doc199 }200201 @Test func footnotesSitAtTheFootOfThePageOfTheirReference() {202 let doc = docWithNotes(12)203 let l = Paginator.layout(doc)204 #expect(l.pageCount >= 2)205 for (i, b) in doc.body.enumerated() {206 guard let p = b.paragraph, let (offset, inline) = p.inlineObjects.first, case .note(let ref) = inline else { continue }207 let loc = l.locate(story: .body, position: Position(block: i, offset: offset))!208 let noteFrags = l.fragments(story: .note(ref.id), path: ParaPath(block: 0))209 #expect(noteFrags.count == 1)210 #expect(noteFrags[0].page == loc.page, "note \(i + 1) is not on the page of its reference")211 let page = l.pages[loc.page]212 let bodyBottom = bodyFragments(l, page: loc.page).map(\.frame.maxY).max() ?? 0213 #expect(noteFrags[0].fragment.frame.minY >= bodyBottom - 0.01, "footnote overlaps body text")214 #expect(noteFrags[0].fragment.frame.maxY <= page.contentRect.maxY + 0.01)215 }216 #expect(l.pages.allSatisfy { p in p.footnoteRules.count == (p.texts.contains { if case .note = $0.story { return true } else { return false } } ? 1 : 0) })217 }218219 @Test func noteNumbersFollowDocumentOrder() {220 let doc = docWithNotes(3)221 let n = Numbering(doc)222 #expect(n.footnoteOrder.count == 3 && n.footnoteOrder.enumerated().allSatisfy { n.noteNumbers[$0.element] == $0.offset + 1 })223 }224225 @Test func endnotesAreCollectedAfterTheBody() {226 var doc = letterDoc([])227 let note = Note(kind: .endnote, paragraphs: [Paragraph("An endnote.", style: StyleID.footnoteText)])228 doc.notes[note.id] = note229 doc.body = [.paragraph(Paragraph(runs: [Run("Text"), Run(inline: .note(NoteRef(kind: .endnote, id: note.id)))])), para("last")]230 let l = Paginator.layout(doc)231 let frag = l.fragments(story: .note(note.id), path: ParaPath(block: 0))[0]232 let last = l.fragments(story: .body, path: ParaPath(block: 1)).last!233 #expect(frag.fragment.frame.minY > last.fragment.frame.maxY)234 #expect(frag.fragment.layout.label?.text == "i.")235 }236}237238@Suite struct TableLayoutTests {239 func bigTable(rows: Int) -> Table {240 Table(strings: [["Name", "Value", "Comment"]] + (1...rows).map { ["Row \($0)", "\($0 * 3)", "A comment for row \($0)"] }, width: 468)241 }242243 @Test func tablesSplitByRowsAndRepeatTheirHeader() {244 let t = bigTable(rows: 120)245 let doc = letterDoc([.table(t), para("after")])246 let l = Paginator.layout(doc)247 #expect(l.pageCount >= 3)248 var seen = 0249 for (pi, page) in l.pages.enumerated() {250 for f in page.tables {251 #expect(f.rows.lowerBound == seen)252 seen = f.rows.upperBound253 #expect(f.repeatedHeaderRows == (pi == 0 ? 0 : 1), "continuation pages repeat the header row")254 #expect(f.frame.maxY <= page.contentRect.maxY + 0.01 && f.frame.minY >= page.contentRect.minY - 0.01)255 }256 }257 #expect(seen == 121, "every row is placed exactly once")258 #expect(l.overflowingTableIDs.isEmpty)259 // Repeated header text is drawn but is not an editing target.260 let headerCell = ParaPath(block: 0, cell: CellPath(row: 0, cell: 0))261 #expect(l.fragments(story: .body, path: headerCell).count == 1)262 #expect(l.pages[1].texts.contains { $0.generated && $0.path == headerCell })263 }264265 @Test func cellTextStaysInsideItsCell() {266 let doc = letterDoc([.table(bigTable(rows: 8))])267 let l = Paginator.layout(doc)268 for f in l.pages[0].texts where f.path.cell != nil {269 let rect = l.cellRect(block: 0, row: f.path.cell!.row, cell: f.path.cell!.cell)!.rect270 #expect(rect.insetBy(dx: -0.5, dy: -0.5).contains(f.frame))271 }272 }273274 @Test func mergedCellsCoverTheirGrid() {275 var t = bigTable(rows: 3)276 t.rows[1].cells[0].colSpan = 2; t.rows[1].cells.remove(at: 1)277 t.rows[2].cells[2].vMerge = .restart; t.rows[3].cells[2].vMerge = .continue278 let l = Paginator.layout(letterDoc([.table(t)]))279 let tl = l.pages[0].tables[0].layout280 #expect(abs(tl.cells[1][0].width - 312) < 0.01)281 #expect(tl.cells[2][2].rowSpan == 2)282 let merged = l.cellRect(block: 0, row: 2, cell: 2)!.rect283 #expect(abs(merged.height - (tl.rowHeights[2] + tl.rowHeights[3])) < 0.01)284 }285286 @Test func aTableWiderThanTheColumnIsScaledAndReported() {287 let t = Table(strings: [["a", "b"]], width: 900)288 let l = Paginator.layout(letterDoc([.table(t)]))289 #expect(l.overflowingTableIDs == [t.id])290 #expect(abs(l.pages[0].tables[0].layout.width - 468) < 0.01)291 }292293 @Test func hitTestingFindsTheCellUnderThePoint() {294 let doc = letterDoc([.table(bigTable(rows: 4)), para("after")])295 let l = Paginator.layout(doc)296 let rect = l.cellRect(block: 0, row: 2, cell: 1)!.rect297 let hit = l.hitTest(page: 0, point: CGPoint(x: rect.midX, y: rect.midY))298 #expect(hit?.position.path == ParaPath(block: 0, cell: CellPath(row: 2, cell: 1, paragraph: 0)))299 }300}301302@Suite struct GeneratedContentTests {303 func report(chapters: Int) -> DocumentModel {304 var blocks: [Block] = [.toc(TOCBlock()), .pageBreak(BreakBlock())]305 for c in 1...chapters {306 blocks.append(para("Chapter \(c)", style: StyleID.heading(1), props: ParaProps(pageBreakBefore: c > 1)))307 for _ in 0..<5 { blocks.append(longPara(3)) }308 blocks.append(para("Section \(c).1", style: StyleID.heading(2)))309 blocks.append(longPara(2))310 }311 var doc = letterDoc(blocks)312 doc.pageSetup.footer.default = [Paragraph(style: StyleID.footer, runs: [Run("Page "), Run(inline: .field(.pageNumber)), Run(" of "), Run(inline: .field(.pageCount))])]313 doc.pageSetup.header.default = [Paragraph(style: StyleID.header, runs: [Run(inline: .field(.headingText(level: 1)))])]314 return doc315 }316317 @Test func contentsPageNumbersMatchWhereHeadingsLand() {318 let doc = report(chapters: 6)319 let l = Paginator.layout(doc)320 #expect(l.passes >= 2, "page numbers in the contents need a second pass")321 let toc = l.pages[0].texts.filter { $0.generated }322 let n = l.numbering323 #expect(toc.count == 1 + n.outline.count)324 for (entry, frag) in zip(n.outline, toc.dropFirst()) {325 let text = frag.layout.plainString326 #expect(text.hasPrefix(entry.text))327 #expect(text.hasSuffix("\t" + l.pageText(ofBlock: entry.id)!), "contents entry “\(entry.text)” shows the wrong page")328 }329 }330331 @Test func layoutIsStableWhenRunAgainFromItsOwnResult() {332 let doc = report(chapters: 5)333 let cache = LayoutCache()334 let first = Paginator.layout(doc, cache: cache)335 let second = Paginator.layout(doc, cache: cache, previous: first)336 #expect(second.passes == 1)337 #expect(second.pageCount == first.pageCount && second.pageOfBlock == first.pageOfBlock)338 }339340 @Test func headersAndFootersShowPageFieldsAndRunningHeads() {341 let doc = report(chapters: 3)342 let l = Paginator.layout(doc)343 for (pi, page) in l.pages.enumerated() {344 let footer = page.texts.first { if case .footer = $0.story { return true } else { return false } }!345 #expect(footer.layout.box(at: 5) != nil)346 #expect(footer.frame.maxY <= 792 - 36 + 0.01 && footer.frame.minY >= page.contentRect.maxY)347 let header = page.texts.first { if case .header = $0.story { return true } else { return false } }!348 #expect(header.frame.minY >= 36 - 0.01 && header.frame.maxY <= page.contentRect.minY)349 _ = pi350 }351 // The running head of a chapter's first page is that chapter's title.352 let pdf = PDFPublisher.publish(doc)353 #expect(pdf.pageCount == l.pageCount)354 }355356 @Test func differentFirstPageAndOddEvenVariants() {357 var doc = letterDoc((0..<40).map { _ in longPara(3) })358 doc.pageSetup.differentFirstPage = true359 doc.pageSetup.differentOddEven = true360 doc.pageSetup.header = HeaderFooter(default: [Paragraph("ODD", style: StyleID.header)], first: [], even: [Paragraph("EVEN", style: StyleID.header)])361 let l = Paginator.layout(doc)362 func headerText(_ p: PageLayout) -> String? { p.texts.first { if case .header = $0.story { return true } else { return false } }?.layout.plainString }363 #expect(headerText(l.pages[0]) == nil)364 #expect(headerText(l.pages[1]) == "EVEN" && headerText(l.pages[2]) == "ODD")365 }366367 @Test func crossReferenceToAPageResolves() {368 let target = Paragraph("Target heading", style: StyleID.heading(1), props: ParaProps(pageBreakBefore: true))369 let doc = letterDoc([.paragraph(Paragraph(runs: [Run("See page "), Run(inline: .crossRef(CrossRef(target: target.id, display: .page)))])), longPara(3), .paragraph(target)])370 let l = Paginator.layout(doc)371 let frag = l.fragments(story: .body, path: ParaPath(block: 0))[0].fragment372 guard case .text(let line, _)? = frag.layout.box(at: 9)?.content else { Issue.record("no box"); return }373 #expect(CTLineGetStringRange(line).length == 1 && l.pageText(ofBlock: target.id) == "2")374 }375}376377@Suite struct TypesettingTests {378 func layout(_ p: Paragraph, width: CGFloat = 300, theme: Theme = .classic) -> ParagraphLayout {379 ParagraphLayout(p, env: ParagraphEnvironment(styles: .standard(theme: theme), options: LayoutOptions(), width: width))380 }381382 @Test func alignmentPositionsLines() {383 let left = layout(Paragraph("short", props: ParaProps(alignment: .left))).lines[0]384 let center = layout(Paragraph("short", props: ParaProps(alignment: .center))).lines[0]385 let right = layout(Paragraph("short", props: ParaProps(alignment: .right))).lines[0]386 #expect(left.x == 0 && abs(center.x - (300 - center.width) / 2) < 0.01 && abs(right.x + right.width - 300) < 0.01)387 }388389 @Test func justifiedLinesFillTheMeasureExceptTheLast() {390 let l = layout(Paragraph(lorem + " " + lorem, props: ParaProps(alignment: .justified)))391 #expect(l.lines.count > 3)392 for line in l.lines.dropLast() { #expect(abs(line.width - CGFloat(CTLineGetTrailingWhitespaceWidth(line.line)) - 300) < 1.5) }393 #expect(l.lines.last!.width < 299)394 }395396 @Test func indentsAndHangingIndent() {397 let l = layout(Paragraph(lorem + " " + lorem, props: ParaProps(indentLeft: 40, indentRight: 30, firstLineIndent: -20)))398 #expect(abs(l.lines[0].x - 20) < 0.01 && abs(l.lines[1].x - 40) < 0.01)399 #expect(l.lines.allSatisfy { $0.x + $0.width - CGFloat(CTLineGetTrailingWhitespaceWidth($0.line)) <= 270.5 })400 }401402 @Test func lineSpacingModes() {403 let single = layout(Paragraph(lorem, props: ParaProps(lineSpacing: .multiple(1)))).lines[0].height404 let double = layout(Paragraph(lorem, props: ParaProps(lineSpacing: .multiple(2)))).lines[0].height405 let exact = layout(Paragraph(lorem, props: ParaProps(lineSpacing: .exact(30)))).lines[0].height406 #expect(abs(double - 2 * single) < 0.01 && exact == 30)407 }408409 @Test func hyphenationBreaksLongWordsOnlyWhenEnabled() {410 let text = "Internationalisation considerations notwithstanding, the characterisation of institutional responsibilities remains disproportionately misunderstood."411 let off = layout(Paragraph(text, props: ParaProps(hyphenate: false)), width: 150)412 let on = layout(Paragraph(text, props: ParaProps(hyphenate: true)), width: 150)413 #expect(!off.lines.contains { $0.hyphenated })414 #expect(on.lines.contains { $0.hyphenated })415 // Every character is still covered exactly once.416 #expect(on.lines.map(\.range.count).reduce(0, +) == (text as NSString).length)417 #expect(zip(on.lines, on.lines.dropFirst()).allSatisfy { $0.range.upperBound == $1.range.lowerBound })418 }419420 @Test func caretPositionsAreMonotonicAndRoundTripThroughHitTesting() {421 let l = layout(Paragraph("The quick brown fox jumps over the lazy dog near the river bank."))422 let line = l.lines[0]423 var last: CGFloat = -1424 for offset in line.range.lowerBound...line.range.upperBound - 1 {425 let x = line.xPosition(for: offset)426 #expect(x >= last)427 last = x428 #expect(line.offset(atX: x + 0.2) == offset)429 }430 }431432 @Test func complexScriptsLayOutAndMapBack() {433 for text in ["مرحبا بالعالم، هذا نص عربي للتجربة.", "שלום עולם, זהו טקסט בדיקה.", "日本語のテキストは単語の間に空白がありません。改行は文字単位で行われます。", "नमस्ते दुनिया, यह एक परीक्षण है।", "👨👩👧👦 family 🇨🇦 flag e\u{0301} accent 👍🏽"] {434 let l = layout(Paragraph(text), width: 160)435 #expect(l.lines.map(\.range.count).reduce(0, +) == (text as NSString).length, "\(text)")436 #expect(l.lines.allSatisfy { $0.height > 5 })437 // Caret offsets returned by hit testing always sit on composed-character boundaries.438 for line in l.lines {439 var x = line.x440 while x < line.x + line.width {441 let o = line.offset(atX: x)442 #expect(text.composedBoundary(atOrBefore: o) == o, "offset \(o) splits a character in \(text)")443 x += 3444 }445 }446 }447 }448449 @Test func rightToLeftParagraphsAlignRight() {450 let l = layout(Paragraph("مرحبا بالعالم", props: ParaProps(rightToLeft: true)))451 #expect(abs(l.lines[0].x + l.lines[0].width - 300) < 0.5)452 }453454 @Test func listLabelsHangInTheIndent() {455 var env = ParagraphEnvironment(styles: .standard(theme: .classic), options: LayoutOptions(), width: 300)456 env.listLabel = "1."; env.listLevel = ListLevel(format: .decimal, pattern: "%1.", indent: 36, hanging: 18)457 let l = ParagraphLayout(Paragraph(lorem), env: env)458 #expect(l.label?.x == 18 && l.lines.allSatisfy { abs($0.x - 36) < 0.01 })459 }460461 @Test func trackedDeletionsAreHiddenWithoutMarkup() {462 var p = Paragraph(runs: [Run("keep "), Run("gone ", revision: Revision(kind: .deletion, author: "A")), Run("end")])463 p.markRevision = nil464 var shown = ParagraphEnvironment(styles: .standard(theme: .classic), options: LayoutOptions(markup: .all), width: 300)465 shown.boxTexts = []466 let hidden = ParagraphEnvironment(styles: .standard(theme: .classic), options: LayoutOptions(markup: .none), width: 300)467 let a = ParagraphLayout(p, env: shown).lines[0], b = ParagraphLayout(p, env: hidden).lines[0]468 #expect(b.width < a.width - 10)469 #expect(abs(b.xPosition(for: 5) - b.xPosition(for: 10)) < 0.01, "hidden text takes no room")470 }471472 @Test func floatingObjectsNarrowTheLinesBesideThem() {473 let shape = ShapeObject(kind: .rectangle, width: 100, height: 60, placement: .floating(wrap: .square, align: .left, xOffset: 0, yOffset: 0))474 let p = Paragraph(runs: [Run(inline: .shape(shape)), Run(lorem + " " + lorem + " " + lorem)])475 let l = layout(p)476 #expect(l.floats.count == 1 && l.floats[0].rect == CGRect(x: 0, y: 0, width: 100, height: 60))477 let beside = l.lines.filter { $0.top < 60 }, below = l.lines.filter { $0.top >= 66 }478 #expect(!beside.isEmpty && !below.isEmpty)479 #expect(beside.allSatisfy { $0.x >= 108 } && below.allSatisfy { $0.x < 1 })480 }481482 @Test func dropCapNarrowsTheFollowingLines() {483 let l = layout(Paragraph(lorem + " " + lorem, props: ParaProps(dropCapLines: 3)))484 #expect(l.lines[1].x > 10 && l.lines[2].x > 10 && l.lines[3].x < 1)485 }486487 @Test func invalidEquationShowsItsSourceInsteadOfVanishing() {488 let p = Paragraph(runs: [Run("a "), Run(inline: .equation(Equation(latex: "\\frac{1}{"))), Run(" b")])489 let l = layout(p)490 guard case .equation(let m)? = l.box(at: 2)?.content else { Issue.record("no equation box"); return }491 #expect(m.error != nil && m.width > 10)492 }493}494495@Suite struct GeometryQueryTests {496 @Test func selectionRectanglesCoverEveryLineOfTheRange() {497 let doc = letterDoc([longPara(2), longPara(2), para("end")])498 let l = Paginator.layout(doc)499 let rects = l.selectionRects(story: .body, start: Position(block: 0, offset: 10), end: Position(block: 2, offset: 2), blocks: doc.body)500 let lines = l.fragments(story: .body, path: ParaPath(block: 0))[0].fragment.layout.lines.count + l.fragments(story: .body, path: ParaPath(block: 1))[0].fragment.layout.lines.count + 1501 #expect(rects.count == lines)502 #expect(rects.allSatisfy { $0.rect.width > 0 && $0.rect.height > 5 })503 }504505 @Test func verticalMovementKeepsTheColumnAndCrossesPages() {506 let doc = letterDoc((0..<30).map { _ in longPara(3) })507 let l = Paginator.layout(doc)508 var pos = Position(block: 0, offset: 20)509 let goal = l.caret(story: .body, position: pos, blocks: doc.body)!.rect.midX510 var pages = Set<Int>()511 var steps = 0512 while let next = l.verticalMove(story: .body, from: pos, goalX: goal, down: true), steps < 2000 {513 let c = l.caret(story: .body, position: next.position, blocks: doc.body, upstream: next.upstream)!514 #expect(abs(c.rect.midX - goal) < 12, "the caret drifted horizontally")515 pages.insert(c.page)516 #expect(next.position > pos)517 pos = next.position518 steps += 1519 }520 #expect(pages.count == l.pageCount && pos.path.block == 29)521 // And back up to the first line.522 while let prev = l.verticalMove(story: .body, from: pos, goalX: goal, down: false), steps < 5000 { pos = prev.position; steps += 1 }523 #expect(pos.path.block == 0 && pos.offset < 120)524 }525526 @Test func hitTestRoundTripsCaretPositions() {527 let doc = letterDoc([longPara(3), longPara(3)])528 let l = Paginator.layout(doc)529 for offset in stride(from: 0, to: doc.body[1].paragraph!.length, by: 37) {530 let pos = Position(block: 1, offset: offset)531 let c = l.caret(story: .body, position: pos, blocks: doc.body)!532 let hit = l.hitTest(page: c.page, point: CGPoint(x: c.rect.midX + 0.3, y: c.rect.midY))!533 #expect(hit.position == pos)534 }535 }536537 @Test func homeAndEndUseTheVisualLine() {538 let doc = letterDoc([longPara(3)])539 let l = Paginator.layout(doc)540 let second = l.fragments(story: .body, path: ParaPath(block: 0))[0].fragment.layout.lines[1].range541 let r = l.lineRange(story: .body, position: Position(block: 0, offset: second.lowerBound + 5))542 #expect(r == second)543 }544}545