Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocLayout/Paginator.swift3// Description: The pagination engine. Flows blocks into columns and pages: sections, page and column breaks, widow/orphan control,4// keep-with-next, keep-lines, footnotes at the column foot, tables split by rows with repeated header rows, floating objects,5// generated lists (contents, figures, tables), the bibliography, endnotes, headers and footers.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import CoreGraphics11import CoreText12import DocModel13import DocMath1415public enum Paginator {16 /// Lays out a document. Page-dependent text (contents page numbers, page cross-references) needs the previous result:17 /// passes repeat until those references are stable (at most four).18 public static func layout(_ doc: DocumentModel, citations: (any CitationFormatting)? = nil, options: LayoutOptions = LayoutOptions(),19 cache: LayoutCache = LayoutCache(), previous: DocumentLayout? = nil) -> DocumentLayout {20 let numbering = Numbering(doc)21 var refs: [String: String] = [:]22 var count = previous?.pageCount ?? 023 if let previous { for (id, page) in previous.pageOfBlock { refs[id] = previous.pages[page].numberText } }24 var result: DocumentLayout!25 for passIndex in 1...4 {26 let pass = Pass(doc: doc, numbering: numbering, citations: citations, options: options, cache: cache, pageRefs: refs, pageCount: count)27 pass.run()28 result = pass.result29 result.passes = passIndex30 var stable = result.pageCount == count || !pass.usedPageCount31 for (id, used) in pass.usedRefs where result.pageText(ofBlock: id) != used { stable = false; break }32 if stable { break }33 refs.removeAll(keepingCapacity: true)34 for (id, page) in result.pageOfBlock { refs[id] = result.pages[page].numberText }35 count = result.pageCount36 }37 return result38 }39}4041final class Pass {42 let doc: DocumentModel43 let numbering: Numbering44 let citations: (any CitationFormatting)?45 let options: LayoutOptions46 let cache: LayoutCache47 let pageRefs: [String: String]48 let previousPageCount: Int49 let result: DocumentLayout50 var usedRefs: [String: String?] = [:]51 var usedPageCount = false52 let typeface: MathTypeface5354 // Flow state55 var pages: [PageLayout] = []56 var section = 057 var setup: PageSetup58 var col = 059 var y: CGFloat = 060 var bandTop: CGFloat = 061 var bandMaxY: CGFloat = 062 var atColumnTop = true63 var pageNoteReserve: CGFloat = 064 var bandNoteReserve: CGFloat = 065 var noteHeight: CGFloat = 066 var pendingNotes: [String] = []67 var placedNotes = Set<String>()68 var noteLayouts: [String: (layouts: [ParagraphLayout], height: CGFloat)] = [:]69 var exclusions: [(y0: CGFloat, y1: CGFloat, left: CGFloat, right: CGFloat)] = []70 var lastNumber = 071 var pendingRestart: Int?72 var sectionStartsPage = true73 var headerHeights: [String: CGFloat] = [:]74 let noteSeparator: CGFloat = 107576 init(doc: DocumentModel, numbering: Numbering, citations: (any CitationFormatting)?, options: LayoutOptions, cache: LayoutCache, pageRefs: [String: String], pageCount: Int) {77 self.doc = doc; self.numbering = numbering; self.citations = citations; self.options = options; self.cache = cache78 self.pageRefs = pageRefs; self.previousPageCount = pageCount79 self.setup = doc.pageSetup80 self.result = DocumentLayout(numbering: numbering, options: options)81 self.typeface = MathTypeface.matching(textFamily: doc.styles.defaultChar.fontFamily ?? "")82 self.pendingRestart = doc.pageSetup.pageNumberStart83 }8485 // MARK: Geometry8687 var page: PageLayout { get { pages[pages.count - 1] } set { pages[pages.count - 1] = newValue } }88 var colWidth: CGFloat { setup.columnWidth }89 var colX: CGFloat { setup.margins.left + CGFloat(col) * (colWidth + setup.columnGap) }90 var colBottom: CGFloat { page.contentRect.maxY - pageNoteReserve }91 var remaining: CGFloat { colBottom - noteHeight - y }92 var columnCapacity: CGFloat { colBottom - bandTop }9394 func pageRef(_ id: String) -> String? {95 let v = pageRefs[id]96 usedRefs[id] = v97 return v98 }99100 // MARK: Paragraph environments101102 struct FieldContext {103 var pageNumber: String?104 var pageCount: String105 var heading: (Int) -> String106 }107108 func boxTexts(_ p: Paragraph, fields: FieldContext?) -> [String] {109 var out: [String] = []110 var seq = 0111 for r in p.runs {112 guard let inline = r.inline else { continue }113 if options.markup == .none, r.isDeleted { continue }114 switch inline {115 case .note(let ref): out.append(numbering.noteMark(ref))116 case .citation(let c):117 out.append(citations?.citationText(c, document: doc, numbering: numbering) ?? "[" + c.items.map(\.key).joined(separator: "; ") + "]")118 case .crossRef(let ref): out.append(numbering.crossRefText(ref, pageOf: { self.pageRef(self.numbering.bookmarks[$0] ?? $0) }))119 case .field(let f):120 switch f {121 case .sequence:122 let values = numbering.sequences[p.id] ?? []123 out.append(seq < values.count ? String(values[seq]) : "?")124 seq += 1125 case .pageNumber: out.append(fields?.pageNumber ?? pageRef(p.id) ?? "#")126 case .pageCount:127 if let f = fields { out.append(f.pageCount) } else { usedPageCount = true; out.append(previousPageCount > 0 ? String(previousPageCount) : "#") }128 case .headingText(let level): out.append(fields?.heading(level) ?? "")129 default: out.append(numbering.staticFieldText(f, document: doc) ?? "")130 }131 default: break132 }133 }134 return out135 }136137 func environment(_ p: Paragraph, width: CGFloat, fields: FieldContext? = nil, headerFooter: Bool = false, color: RGBA? = nil, at top: CGFloat? = nil) -> ParagraphEnvironment {138 var env = ParagraphEnvironment(styles: doc.styles, options: options, width: width, language: doc.meta.language)139 env.boxTexts = p.runs.contains(where: { $0.inline != nil }) ? boxTexts(p, fields: fields) : []140 if let li = p.list, let def = doc.list(li.listID), let label = numbering.listLabels[p.id], !def.levels.isEmpty {141 env.listLabel = label142 env.listLevel = def.levels[max(0, min(def.levels.count - 1, li.level))]143 } else if let n = numbering.headingNumbers[p.id] {144 env.headingNumber = n145 }146 env.isHeaderFooter = headerFooter147 env.mathTypeface = typeface148 env.colorOverride = color149 if let top, !exclusions.isEmpty {150 env.exclusions = exclusions.filter { $0.y1 > top }.map { Exclusion(y0: $0.y0 - top, y1: $0.y1 - top, left: $0.left, right: $0.right) }151 }152 return env153 }154155 // MARK: Pages and columns156157 func headerFooterParagraphs(_ hf: HeaderFooter, _ v: HeaderFooterVariant) -> [Paragraph] {158 switch v {159 case .default: return hf.default160 case .first: return hf.first161 case .even: return hf.even.isEmpty ? hf.default : hf.even162 }163 }164165 func variant(for setup: PageSetup, first: Bool, number: Int) -> HeaderFooterVariant {166 if setup.differentFirstPage && first { return .first }167 if setup.differentOddEven && number % 2 == 0 { return .even }168 return .default169 }170171 func measure(_ paragraphs: [Paragraph], width: CGFloat, key: String) -> CGFloat {172 if let h = headerHeights[key] { return h }173 let placeholder = FieldContext(pageNumber: "000", pageCount: "000", heading: { _ in "Heading" })174 var h: CGFloat = 0175 for (i, p) in paragraphs.enumerated() {176 let l = cache.layout(p, env: environment(p, width: width, fields: placeholder, headerFooter: true))177 h += l.height + (i > 0 ? l.spaceBefore : 0) + (i < paragraphs.count - 1 ? l.spaceAfter : 0)178 }179 headerHeights[key] = h180 return h181 }182183 func newPage(blank: Bool = false) {184 if !pages.isEmpty { closeBand() }185 let number = pendingRestart ?? (lastNumber + 1)186 pendingRestart = nil187 lastNumber = number188 let first = sectionStartsPage189 sectionStartsPage = false190 let v = variant(for: setup, first: first, number: number)191 let hh = measure(headerFooterParagraphs(setup.header, v), width: setup.contentWidth, key: "h\(section)\(v.rawValue)")192 let fh = measure(headerFooterParagraphs(setup.footer, v), width: setup.contentWidth, key: "f\(section)\(v.rawValue)")193 let top = max(setup.margins.top, setup.headerDistance + hh + (hh > 0 ? 8 : 0))194 let bottom = setup.pageHeight - max(setup.margins.bottom, setup.footerDistance + fh + (fh > 0 ? 8 : 0))195 var p = PageLayout(index: pages.count, sectionIndex: section, setup: setup, size: CGSize(width: setup.pageWidth, height: setup.pageHeight),196 number: number, numberText: setup.pageNumberFormat.string(number), isFirstOfSection: first,197 contentRect: CGRect(x: setup.margins.left, y: top, width: setup.contentWidth, height: max(40, bottom - top)))198 p.headerVariant = v199 p.isBlank = blank200 pages.append(p)201 col = 0202 bandTop = top; y = top; bandMaxY = top203 pageNoteReserve = 0204 bandNoteReserve = 0205 atColumnTop = true206 exclusions.removeAll()207 }208209 func noteParagraphs(_ id: String, width: CGFloat) -> (layouts: [ParagraphLayout], height: CGFloat) {210 if let n = noteLayouts[id] { return n }211 guard let note = doc.notes[id] else { return ([], 0) }212 var layouts: [ParagraphLayout] = []213 var h: CGFloat = 0214 let mark = numbering.noteMark(NoteRef(kind: note.kind, id: id))215 for (i, p) in note.paragraphs.enumerated() {216 var env = environment(p, width: width)217 if env.listLabel == nil {218 env.listLevel = ListLevel(format: .decimal, pattern: "", indent: 13, hanging: 13)219 env.listLabel = i == 0 ? mark : ""220 env.headingNumber = nil221 }222 let l = cache.layout(p, env: env)223 layouts.append(l)224 h += l.height + l.spaceAfter225 }226 noteLayouts[id] = (layouts, h)227 return (layouts, h)228 }229230 /// Places the footnotes gathered for the current column at its foot.231 func closeColumn() {232 bandMaxY = max(bandMaxY, y)233 guard !pendingNotes.isEmpty else { return }234 let x = colX235 var yy = colBottom - noteHeight236 page.footnoteRules.append(CGRect(x: x, y: yy + 3.5, width: min(colWidth, 120), height: 0.5))237 yy += noteSeparator238 for id in pendingNotes {239 let n = noteParagraphs(id, width: colWidth)240 for (i, l) in n.layouts.enumerated() {241 emit(story: .note(id), path: ParaPath(block: i), layout: l, lines: 0..<l.lines.count, x: x, y: yy, width: colWidth, generated: false)242 yy += l.height + l.spaceAfter243 }244 }245 bandNoteReserve = max(bandNoteReserve, noteHeight)246 pendingNotes.removeAll()247 noteHeight = 0248 }249250 /// Ends the current set of columns (before a continuous section break or at the end of the page).251 func closeBand() {252 closeColumn()253 // Only what follows this band (a continuous section on the same page) must stay clear of its footnotes.254 pageNoteReserve = max(pageNoteReserve, bandNoteReserve)255 bandNoteReserve = 0256 if setup.columnRule, setup.columns > 1, bandMaxY > bandTop + 1 {257 for c in 1..<setup.columns {258 let x = setup.margins.left + CGFloat(c) * (colWidth + setup.columnGap) - setup.columnGap / 2259 page.columnRules.append(CGRect(x: x, y: bandTop, width: 0.5, height: bandMaxY - bandTop))260 }261 }262 }263264 func nextColumn() {265 if col + 1 < setup.columns {266 closeColumn()267 col += 1268 y = bandTop269 atColumnTop = true270 exclusions.removeAll()271 } else {272 newPage()273 }274 }275276 func emit(story: StoryID, path: ParaPath, layout: ParagraphLayout, lines: Range<Int>, x: CGFloat, y: CGFloat, width: CGFloat, generated: Bool) {277 page.texts.append(TextFragment(story: story, path: path, layout: layout, lines: lines, origin: CGPoint(x: x, y: y), width: width, generated: generated))278 if story == .body, lines.lowerBound == 0, result.pageOfBlock[layout.paragraphID] == nil {279 result.pageOfBlock[layout.paragraphID] = pages.count - 1280 result.yOfBlock[layout.paragraphID] = y281 }282 }283284 func mark(_ id: String) {285 if result.pageOfBlock[id] == nil { result.pageOfBlock[id] = pages.count - 1; result.yOfBlock[id] = y }286 }287288 // MARK: Paragraphs289290 func newNotes(in l: ParagraphLayout, line: Int) -> [String] {291 guard !l.footnoteRefs.isEmpty else { return [] }292 let r = l.lines[line].range293 return l.footnoteRefs.filter { r.contains($0.offset) && !placedNotes.contains($0.id) && !pendingNotes.contains($0.id) }.map(\.id)294 }295296 func noteCost(_ ids: [String], alreadyAdding: Bool) -> CGFloat {297 guard !ids.isEmpty else { return 0 }298 var h: CGFloat = pendingNotes.isEmpty && !alreadyAdding ? noteSeparator : 0299 for id in ids { h += noteParagraphs(id, width: colWidth).height }300 return h301 }302303 func place(_ p: Paragraph, story: StoryID, path: ParaPath, generated: Bool = false) {304 if pages.isEmpty { newPage() }305 var l = cache.layout(p, env: environment(p, width: colWidth, at: exclusions.isEmpty ? nil : y))306 if l.para.pageBreakBefore, !(atColumnTop && col == 0 && bandTop == page.contentRect.minY) { newPage(); l = cache.layout(p, env: environment(p, width: colWidth)) }307 // A floating object that cannot fit in what is left of the column moves with its paragraph.308 if !atColumnTop, l.floatBottom > remaining, l.floatBottom <= columnCapacity { nextColumn(); l = cache.layout(p, env: environment(p, width: colWidth)) }309 let n = l.lines.count310 var first = 0311 var guardCount = 0312 while first < n {313 guardCount += 1314 if !exclusions.isEmpty || guardCount > 1 {315 // Floats and column widths can differ after a break: typeset against the place the lines will really occupy.316 let sbGuess = first == 0 && !atColumnTop ? l.spaceBefore : 0317 let fresh = cache.layout(p, env: environment(p, width: colWidth, at: exclusions.isEmpty ? nil : y + sbGuess - (first > 0 ? l.lines[first].top : 0)))318 if fresh.lines.count == n { l = fresh }319 }320 let sb = first == 0 && !atColumnTop ? l.spaceBefore : 0321 let avail = remaining - sb322 var k = 0323 var used: CGFloat = 0324 var notesAdd: CGFloat = 0325 for li in first..<n {326 let h = l.lines[li].height327 let add = noteCost(newNotes(in: l, line: li), alreadyAdding: notesAdd > 0)328 if used + h + notesAdd + add > avail + 0.01 { break }329 used += h; notesAdd += add; k += 1330 }331 var take = k332 let rest = n - first333 if take < rest {334 if l.para.keepLinesTogether, first == 0, l.height <= columnCapacity { take = 0 }335 else if l.para.widowControl, rest > 1 {336 if take == 1, first == 0 { take = 0 } // orphan: a lone first line at the foot337 if rest - take == 1 { take -= 1 } // widow: a lone last line at the head338 if take == 1, first == 0 { take = 0 }339 }340 }341 if take <= 0 {342 if atColumnTop { take = max(1, min(rest, k)) } else { nextColumn(); continue }343 }344 let top = y + sb345 emit(story: story, path: path, layout: l, lines: first..<(first + take), x: colX, y: top, width: colWidth, generated: generated)346 for li in first..<(first + take) {347 for id in newNotes(in: l, line: li) {348 noteHeight += noteCost([id], alreadyAdding: false)349 pendingNotes.append(id)350 placedNotes.insert(id)351 }352 }353 if first == 0 {354 for f in l.floats {355 let rect = f.rect.offsetBy(dx: colX, dy: top)356 page.floats.append(FloatFragment(box: f, rect: rect, story: story, path: path))357 switch f.wrap {358 case .square:359 if f.rect.midX < colWidth * 0.4 { exclusions.append((rect.minY - 2, rect.maxY + 4, f.rect.maxX + 9, 0)) }360 else if f.rect.midX > colWidth * 0.6 { exclusions.append((rect.minY - 2, rect.maxY + 4, 0, colWidth - f.rect.minX + 9)) }361 else { exclusions.append((rect.minY - 2, rect.maxY + 6, colWidth, 0)) }362 case .topAndBottom: exclusions.append((rect.minY - 2, rect.maxY + 6, colWidth, 0))363 default: break364 }365 }366 }367 y = top + l.height(ofLines: first..<(first + take))368 atColumnTop = false369 first += take370 if first < n { nextColumn() }371 if guardCount > 10_000 { break }372 }373 y += min(l.spaceAfter, max(0, remaining))374 }375376 /// Height a block needs at the head of a column so that it is not stranded (keep-with-next look-ahead).377 func leadHeight(_ block: Block) -> CGFloat {378 switch block {379 case .paragraph(let p):380 let l = cache.layout(p, env: environment(p, width: colWidth))381 let lines = l.para.keepLinesTogether ? l.lines.count : min(2, l.lines.count)382 return l.spaceBefore + l.height(ofLines: 0..<lines)383 case .table(let t):384 let tl = tableLayout(t, width: colWidth)385 return 4 + tl.height(rows: 0..<min(tl.rowHeights.count, tl.headerRows + 1))386 default: return 0387 }388 }389390 // MARK: Tables391392 func tableLayout(_ t: Table, width avail: CGFloat) -> TableLayout {393 let total = max(1, t.totalWidth)394 let scale = total > avail + 0.5 ? avail / total : 1395 var xs: [CGFloat] = [0]396 for w in t.columnWidths { xs.append(xs[xs.count - 1] + w * scale) }397 let pad = t.style.cellPadding398 var cells: [[CellLayout]] = []399 var heights: [CGFloat] = []400 for row in t.rows {401 var g = 0402 var rowCells: [CellLayout] = []403 var h: CGFloat = row.minHeight ?? 0404 for (ci, cell) in row.cells.enumerated() {405 let g1 = min(xs.count - 1, g), g2 = min(xs.count - 1, g + cell.colSpan)406 let x = xs[g1], w = max(12, xs[g2] - xs[g1])407 var layouts: [ParagraphLayout] = []408 var content: CGFloat = 0409 if cell.vMerge != .continue {410 let inner = max(10, w - pad.left - pad.right)411 for (pi, p) in cell.paragraphs.enumerated() {412 let l = cache.layout(p, env: environment(p, width: inner, color: row.isHeader ? t.style.headerTextColor : nil))413 layouts.append(l)414 content += l.height + (pi > 0 ? l.spaceBefore : 0) + (pi < cell.paragraphs.count - 1 ? l.spaceAfter : 0)415 }416 if cell.vMerge == .none { h = max(h, content + pad.top + pad.bottom) }417 }418 rowCells.append(CellLayout(cellIndex: ci, gridStart: g, span: cell.colSpan, x: x, width: w, paragraphs: layouts, contentHeight: content))419 g += cell.colSpan420 }421 cells.append(rowCells)422 heights.append(max(h, 14))423 }424 // Vertically merged cells: count the rows they cover and make sure those rows are tall enough together.425 for r in t.rows.indices {426 for ci in t.rows[r].cells.indices where t.rows[r].cells[ci].vMerge == .restart {427 let g = cells[r][ci].gridStart428 var end = r + 1429 while end < t.rows.count, let cj = cells[end].firstIndex(where: { $0.gridStart == g }), t.rows[end].cells[cj].vMerge == .continue { end += 1 }430 cells[r][ci].rowSpan = end - r431 let have = heights[r..<end].reduce(0, +)432 let need = cells[r][ci].contentHeight + pad.top + pad.bottom433 if need > have { heights[end - 1] += need - have }434 }435 }436 return TableLayout(table: t, columnX: xs, rowHeights: heights, cells: cells, scaled: scale < 1)437 }438439 func emitRow(_ tl: TableLayout, row r: Int, blockIndex: Int, tableX: CGFloat, top: CGFloat, generated: Bool) {440 let pad = tl.table.style.cellPadding441 for cell in tl.cells[r] where tl.table.rows[r].cells[cell.cellIndex].vMerge != .continue {442 let model = tl.table.rows[r].cells[cell.cellIndex]443 let cellHeight = tl.height(rows: r..<min(tl.rowHeights.count, r + cell.rowSpan))444 var cy = top + pad.top445 let free = max(0, cellHeight - pad.top - pad.bottom - cell.contentHeight)446 switch model.vAlign {447 case .top: break448 case .center: cy += free / 2449 case .bottom: cy += free450 }451 for (pi, l) in cell.paragraphs.enumerated() {452 if pi > 0 { cy += l.spaceBefore }453 emit(story: .body, path: ParaPath(block: blockIndex, cell: CellPath(row: r, cell: cell.cellIndex, paragraph: pi)), layout: l, lines: 0..<l.lines.count,454 x: tableX + cell.x + pad.left, y: cy, width: max(10, cell.width - pad.left - pad.right), generated: generated)455 cy += l.height + l.spaceAfter456 }457 }458 }459460 func rowNotes(_ tl: TableLayout, row r: Int) -> [String] {461 var ids: [String] = []462 for cell in tl.cells[r] { for l in cell.paragraphs { for ref in l.footnoteRefs where !placedNotes.contains(ref.id) && !pendingNotes.contains(ref.id) { ids.append(ref.id) } } }463 return ids464 }465466 func place(_ t: Table, blockIndex: Int) {467 if pages.isEmpty { newPage() }468 let tl = tableLayout(t, width: colWidth)469 if tl.scaled { result.overflowingTableIDs.append(t.id) }470 if !atColumnTop { y += 4 }471 func tableX() -> CGFloat {472 switch t.alignment {473 case .left: return colX474 case .center: return colX + max(0, (colWidth - tl.width) / 2)475 case .right: return colX + max(0, colWidth - tl.width)476 }477 }478 var fragStart = 0479 var fragY = y480 var repeated = 0481 func close(_ end: Int) {482 if end > fragStart {483 page.tables.append(TableFragment(blockIndex: blockIndex, layout: tl, rows: fragStart..<end, origin: CGPoint(x: tableX(), y: fragY), repeatedHeaderRows: repeated))484 }485 }486 for r in tl.rowHeights.indices {487 let h = tl.rowHeights[r]488 let notes = rowNotes(tl, row: r)489 let cost = noteCost(notes, alreadyAdding: false)490 if h + cost > remaining + 0.01, !(atColumnTop && r == fragStart) {491 close(r)492 nextColumn()493 fragStart = r; fragY = y; repeated = 0494 if r >= tl.headerRows, tl.headerRows > 0 {495 let hh = tl.height(rows: 0..<tl.headerRows)496 if hh + h <= remaining {497 var hy = y498 for hr in 0..<tl.headerRows { emitRow(tl, row: hr, blockIndex: blockIndex, tableX: tableX(), top: hy, generated: true); hy += tl.rowHeights[hr] }499 repeated = tl.headerRows500 y += hh501 }502 }503 }504 if h > columnCapacity, !result.overflowingTableIDs.contains(t.id) { result.overflowingTableIDs.append(t.id) }505 if r == 0 { mark(t.id) }506 emitRow(tl, row: r, blockIndex: blockIndex, tableX: tableX(), top: y, generated: false)507 for id in notes { noteHeight += noteCost([id], alreadyAdding: false); pendingNotes.append(id); placedNotes.insert(id) }508 y += h509 atColumnTop = false510 }511 close(tl.rowHeights.count)512 y += min(8, max(0, remaining))513 }514515 // MARK: Generated content516517 func tocParagraphs(_ t: TOCBlock) -> [Paragraph] {518 var out: [Paragraph] = []519 if let title = t.title, !title.isEmpty { out.append(Paragraph(id: t.id + "-title", style: StyleID.tocHeading, runs: [Run(title)])) }520 let tab = [TabStop(position: colWidth - 0.5, kind: .right, leader: .dots)]521 func entry(_ id: String, level: Int, text: String) -> Paragraph {522 Paragraph(id: "\(t.id)-\(id)", style: StyleID.toc(level), props: ParaProps(tabs: tab),523 runs: [Run(text, props: CharProps(link: "#" + id)), Run("\t"), Run(pageRef(id) ?? "–", props: CharProps(bold: false))])524 }525 switch t.kind {526 case .contents:527 for e in numbering.outline where e.level <= t.maxLevel {528 out.append(entry(e.id, level: e.level, text: (e.number.map { $0 + "\u{2002}" } ?? "") + e.text))529 }530 case .figures, .tables:531 let prefix = t.kind == .figures ? "fig" : "tab"532 for (id, c) in numbering.captions.sorted(by: { $0.value.blockIndex < $1.value.blockIndex }) where c.label.lowercased().hasPrefix(prefix) {533 out.append(entry(id, level: 1, text: c.text))534 }535 }536 if out.count == (t.title?.isEmpty == false ? 1 : 0) {537 let hint = t.kind == .contents ? "No headings yet. Apply a heading style and the contents will appear here." : "No captions of this kind yet."538 out.append(Paragraph(id: t.id + "-empty", style: StyleID.toc(1), runs: [Run(hint, props: CharProps(bold: false, italic: true, color: RGBA(hex: 0x8A8F9C)))]))539 }540 return out541 }542543 func bibliographyParagraphs(_ b: BibliographyBlock) -> [Paragraph] {544 var out: [Paragraph] = []545 if let title = b.title, !title.isEmpty { out.append(Paragraph(id: b.id + "-title", style: StyleID.tocHeading, runs: [Run(title)])) }546 let entries = citations?.bibliographyParagraphs(document: doc, numbering: numbering) ?? []547 for (i, e) in entries.enumerated() { var p = e; p.id = "\(b.id)-\(i)"; out.append(p) }548 if entries.isEmpty {549 out.append(Paragraph(id: b.id + "-empty", style: StyleID.bibliography,550 runs: [Run("No works cited yet. Insert a citation and its reference will be listed here.", props: CharProps(italic: true, color: RGBA(hex: 0x8A8F9C)))]))551 }552 return out553 }554555 // MARK: Main loop556557 func marker(_ kind: MarkerFragment.Kind, blockIndex: Int, id: String) {558 if pages.isEmpty { newPage() }559 mark(id)560 var height = max(0, min(14, remaining))561 if case .sectionBreak(.continuous) = kind { height = min(height, 6) }562 page.markers.append(MarkerFragment(blockIndex: blockIndex, kind: kind, rect: CGRect(x: colX, y: y, width: colWidth, height: height)))563 }564565 func run() {566 cache.beginPass(styles: doc.styles)567 newPage()568 let body = doc.body569 var i = 0570 while i < body.count {571 let block = body[i]572 // Keep with next: a chain of such paragraphs must be followed, in the same column, by the start of the block after it.573 if case .paragraph(let p) = block, !atColumnTop {574 let pl = cache.layout(p, env: environment(p, width: colWidth))575 let chainStart = i == 0 || !(body[i - 1].paragraph.map { doc.styles.paraProps(style: $0.style, direct: $0.props).keepWithNext } ?? false)576 if pl.para.keepWithNext, chainStart {577 var need = pl.spaceBefore + pl.height + pl.spaceAfter578 var j = i + 1579 while j < body.count, j - i < 6, case .paragraph(let q) = body[j], doc.styles.paraProps(style: q.style, direct: q.props).keepWithNext {580 let ql = cache.layout(q, env: environment(q, width: colWidth))581 need += ql.spaceBefore + ql.height + ql.spaceAfter582 j += 1583 }584 if j < body.count { need += leadHeight(body[j]) }585 if need > remaining, need <= columnCapacity { nextColumn() }586 }587 }588 switch block {589 case .paragraph(let p):590 place(p, story: .body, path: ParaPath(block: i))591 case .table(let t):592 place(t, blockIndex: i)593 case .pageBreak(let b):594 marker(b.kind == .page ? .pageBreak : .columnBreak, blockIndex: i, id: b.id)595 if b.kind == .page { newPage() } else { nextColumn() }596 case .sectionBreak(let s):597 marker(.sectionBreak(s.kind), blockIndex: i, id: s.id)598 let old = setup599 section += 1600 let sameGeometry = old.paper == s.setup.paper && old.landscape == s.setup.landscape && old.margins == s.setup.margins601 if s.kind == .continuous, sameGeometry {602 closeBand()603 setup = s.setup604 if let start = s.setup.pageNumberStart { pendingRestart = start }605 bandTop = min(bandMaxY + (bandMaxY > page.contentRect.minY ? 7 : 0), colBottom)606 col = 0; y = bandTop; bandMaxY = bandTop607 atColumnTop = true608 exclusions.removeAll()609 if remaining < 30 { sectionStartsPage = true; newPage() }610 } else {611 setup = s.setup612 if let start = s.setup.pageNumberStart { pendingRestart = start }613 sectionStartsPage = true614 let next = pendingRestart ?? (lastNumber + 1)615 if (s.kind == .oddPage && next % 2 == 0) || (s.kind == .evenPage && next % 2 == 1) {616 // A blank page keeps the parity; it belongs to the section that ends.617 let keep = (setup, pendingRestart)618 setup = old; pendingRestart = nil; sectionStartsPage = false619 newPage(blank: true)620 setup = keep.0621 pendingRestart = keep.1 == nil ? nil : keep.1622 sectionStartsPage = true623 }624 newPage()625 }626 case .toc(let t):627 mark(t.id)628 for p in tocParagraphs(t) { place(p, story: .body, path: ParaPath(block: i), generated: true) }629 case .bibliography(let b):630 mark(b.id)631 for p in bibliographyParagraphs(b) { place(p, story: .body, path: ParaPath(block: i), generated: true) }632 }633 i += 1634 }635 // Endnotes follow the body.636 if !numbering.endnoteOrder.isEmpty {637 let title = doc.meta.language.hasPrefix("fr") ? "Notes de fin" : "Notes"638 place(Paragraph(id: "endnotes-title", style: StyleID.tocHeading, runs: [Run(title)]), story: .body, path: ParaPath(block: body.count - 1), generated: true)639 for id in numbering.endnoteOrder {640 guard let note = doc.notes[id] else { continue }641 let mark = numbering.noteMark(NoteRef(kind: .endnote, id: id))642 for (pi, p) in note.paragraphs.enumerated() {643 var env = environment(p, width: colWidth)644 if env.listLabel == nil { env.listLevel = ListLevel(format: .lowerRoman, pattern: "", indent: 18, hanging: 18); env.listLabel = pi == 0 ? mark + "." : ""; env.headingNumber = nil }645 let l = cache.layout(p, env: env)646 var first = 0647 while first < l.lines.count {648 var k = 0649 var used: CGFloat = 0650 for li in first..<l.lines.count { if used + l.lines[li].height > remaining + 0.01 { break }; used += l.lines[li].height; k += 1 }651 if k == 0 { if atColumnTop { k = 1 } else { nextColumn(); continue } }652 emit(story: .note(id), path: ParaPath(block: pi), layout: l, lines: first..<(first + k), x: colX, y: y, width: colWidth, generated: false)653 y += l.height(ofLines: first..<(first + k))654 atColumnTop = false655 first += k656 if first < l.lines.count { nextColumn() }657 }658 y += min(l.spaceAfter, max(0, remaining))659 }660 }661 }662 closeBand()663 placeHeadersAndFooters()664 result.pages = pages665 result.buildIndex()666 cache.endPass()667 }668669 // MARK: Headers and footers670671 func placeHeadersAndFooters() {672 let total = String(pages.count)673 // Running heads: for each page and level, the first heading that starts on the page, otherwise the last one before it.674 var firstOnPage: [Int: [Int: String]] = [:]675 var lastByPage: [[Int: String]] = Array(repeating: [:], count: pages.count)676 var current: [Int: String] = [:]677 var entriesByPage: [Int: [OutlineEntry]] = [:]678 for e in numbering.outline { if let p = result.pageOfBlock[e.id] { entriesByPage[p, default: []].append(e) } }679 for pi in pages.indices {680 for e in entriesByPage[pi] ?? [] {681 if firstOnPage[pi]?[e.level] == nil { firstOnPage[pi, default: [:]][e.level] = e.text }682 current[e.level] = e.text683 for deeper in (e.level + 1)...10 { current[deeper] = nil }684 }685 lastByPage[pi] = current686 }687 let setups = doc.sectionSetups688 for pi in pages.indices {689 let pg = pages[pi]690 if pg.isBlank { continue }691 let su = setups[min(pg.sectionIndex, setups.count - 1)]692 let v = pg.headerVariant693 let fields = FieldContext(pageNumber: pg.numberText, pageCount: total, heading: { level in694 firstOnPage[pi]?[level] ?? (pi > 0 ? lastByPage[pi - 1][level] : nil) ?? lastByPage[pi][level] ?? ""695 })696 func lay(_ paragraphs: [Paragraph], story: StoryID, startY: (CGFloat) -> CGFloat) {697 guard !paragraphs.isEmpty else { return }698 let layouts = paragraphs.map { cache.layout($0, env: environment($0, width: su.contentWidth, fields: fields, headerFooter: true)) }699 var h: CGFloat = 0700 for (i, l) in layouts.enumerated() { h += l.height + (i > 0 ? l.spaceBefore : 0) + (i < layouts.count - 1 ? l.spaceAfter : 0) }701 var yy = startY(h)702 for (i, l) in layouts.enumerated() {703 if i > 0 { yy += l.spaceBefore }704 pages[pi].texts.append(TextFragment(story: story, path: ParaPath(block: i), layout: l, lines: 0..<l.lines.count, origin: CGPoint(x: su.margins.left, y: yy), width: su.contentWidth, generated: false))705 yy += l.height + l.spaceAfter706 }707 }708 // The story is the stored variant: `.even` falls back to the default paragraphs when it is empty.709 let headerVariant: HeaderFooterVariant = v == .even && su.header.even.isEmpty ? .default : v710 let footerVariant: HeaderFooterVariant = v == .even && su.footer.even.isEmpty ? .default : v711 lay(headerFooterParagraphs(su.header, v), story: .header(section: pg.sectionIndex, variant: headerVariant), startY: { _ in CGFloat(su.headerDistance) })712 lay(headerFooterParagraphs(su.footer, v), story: .footer(section: pg.sectionIndex, variant: footerVariant), startY: { h in CGFloat(su.pageHeight - su.footerDistance) - h })713 }714 }715}716