Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocLayout/DocumentLayout.swift3// Description: The paginated layout of a document: pages, placed text fragments, tables, floats and markers, plus the paragraph layout cache4// and table layout. Produced by the Paginator; consumed by the page renderer, the PDF publisher and the editor view.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreGraphics10import CoreText11import DocModel12import DocMath1314public struct FragmentKey: Hashable, Sendable {15 public var story: StoryID16 public var path: ParaPath17 public init(story: StoryID, path: ParaPath) { self.story = story; self.path = path }18}1920/// Consecutive lines of one paragraph placed on a page.21public struct TextFragment: Sendable {22 public let story: StoryID23 public let path: ParaPath24 public let layout: ParagraphLayout25 public let lines: Range<Int>26 /// Page coordinates of the column's left edge and of the top of the first line of this fragment.27 public let origin: CGPoint28 public let width: CGFloat29 /// Generated content (table of contents, bibliography, repeated table header rows): drawn, not editable.30 public let generated: Bool3132 public var height: CGFloat { layout.height(ofLines: lines) }33 public var frame: CGRect { CGRect(x: origin.x, y: origin.y, width: width, height: height) }34 public func top(ofLine i: Int) -> CGFloat { origin.y + layout.lines[i].top - layout.lines[lines.lowerBound].top }35 public func baseline(ofLine i: Int) -> CGFloat { origin.y + layout.lines[i].baseline - layout.lines[lines.lowerBound].top }36 /// Index of the line of this fragment at page y (clamped).37 public func line(atY y: CGFloat) -> Int {38 for i in lines where y < top(ofLine: i) + layout.lines[i].height { return i }39 return lines.upperBound - 140 }41}4243public struct CellLayout: Sendable {44 public let cellIndex: Int45 public let gridStart: Int46 public let span: Int47 public let x: CGFloat48 public let width: CGFloat49 public let paragraphs: [ParagraphLayout]50 public let contentHeight: CGFloat51 /// Number of rows covered (vertical merge), 1 otherwise.52 public var rowSpan = 153}5455public final class TableLayout: @unchecked Sendable {56 public let table: Table57 public let columnX: [CGFloat]58 public internal(set) var rowHeights: [CGFloat]59 public let cells: [[CellLayout]]60 public let width: CGFloat61 /// The table was wider than its column and has been scaled down to fit.62 public let scaled: Bool63 public let headerRows: Int6465 init(table: Table, columnX: [CGFloat], rowHeights: [CGFloat], cells: [[CellLayout]], scaled: Bool) {66 self.table = table; self.columnX = columnX; self.rowHeights = rowHeights; self.cells = cells67 self.width = columnX.last ?? 0; self.scaled = scaled68 var h = 069 for r in table.rows { if r.isHeader { h += 1 } else { break } }70 headerRows = h71 }7273 public func rowTop(_ r: Int, from first: Int) -> CGFloat { rowHeights[first..<r].reduce(0, +) }74 public func height(rows: Range<Int>) -> CGFloat { rowHeights[rows].reduce(0, +) }75}7677public struct TableFragment: Sendable {78 public let blockIndex: Int79 public let layout: TableLayout80 public let rows: Range<Int>81 /// Page position of the top-left corner of the first row of this fragment (repeated header rows are drawn above the first body row).82 public let origin: CGPoint83 /// Header rows repeated at the top of a continuation fragment.84 public let repeatedHeaderRows: Int85 public var height: CGFloat { layout.height(rows: rows) + (repeatedHeaderRows > 0 ? layout.height(rows: 0..<repeatedHeaderRows) : 0) }86 public var frame: CGRect { CGRect(x: origin.x, y: origin.y, width: layout.width, height: height) }8788 /// Rectangle of a cell in page coordinates, nil when the row is not in this fragment.89 public func cellRect(row: Int, cell: Int) -> CGRect? {90 guard rows.contains(row), layout.cells[row].indices.contains(cell) else { return nil }91 let c = layout.cells[row][cell]92 let headerH = repeatedHeaderRows > 0 ? layout.height(rows: 0..<repeatedHeaderRows) : 093 let y = origin.y + headerH + layout.rowTop(row, from: rows.lowerBound)94 let lastRow = min(rows.upperBound, row + c.rowSpan)95 return CGRect(x: origin.x + c.x, y: y, width: c.width, height: layout.height(rows: row..<lastRow))96 }97}9899public struct MarkerFragment: Sendable {100 public enum Kind: Sendable { case pageBreak, columnBreak, sectionBreak(SectionBreak.Kind) }101 public let blockIndex: Int102 public let kind: Kind103 public let rect: CGRect104}105106public struct FloatFragment: Sendable {107 public let box: FloatBox108 public let rect: CGRect109 public let story: StoryID110 public let path: ParaPath111}112113public struct PageLayout: Sendable {114 public let index: Int115 public let sectionIndex: Int116 public let setup: PageSetup117 public let size: CGSize118 public let number: Int119 public let numberText: String120 public let isFirstOfSection: Bool121 /// The area of the page given to body text (between header and footer, inside the margins).122 public let contentRect: CGRect123 public internal(set) var texts: [TextFragment] = []124 public internal(set) var tables: [TableFragment] = []125 public internal(set) var markers: [MarkerFragment] = []126 public internal(set) var floats: [FloatFragment] = []127 public internal(set) var footnoteRules: [CGRect] = []128 public internal(set) var columnRules: [CGRect] = []129 public internal(set) var headerVariant: HeaderFooterVariant = .default130 /// A page inserted to honour an odd/even section break.131 public internal(set) var isBlank = false132}133134/// Caches paragraph layouts between passes. A paragraph is typeset again only when it, its environment or the style sheet changed.135public final class LayoutCache: @unchecked Sendable {136 struct Entry {137 var paragraph: Paragraph138 var width: CGFloat139 var label: String?140 var level: ListLevel?141 var headingNumber: String?142 var boxTexts: [String]143 var exclusions: [Exclusion]144 var isHeaderFooter: Bool145 var color: RGBA?146 var options: LayoutOptions147 var typeface: MathTypeface148 var layout: ParagraphLayout149 var generation: Int150 }151 private var entries: [String: [Entry]] = [:]152 private var styles: StyleSheet?153 private var generation = 0154 public private(set) var hits = 0155 public private(set) var misses = 0156157 public init() {}158159 func beginPass(styles s: StyleSheet) {160 if styles != s { entries.removeAll(keepingCapacity: true); repeated.removeAll(keepingCapacity: true); styles = s }161 generation += 1162 }163164 /// Drops layouts of paragraphs that no longer exist.165 func endPass() {166 guard generation % 8 == 0 else { return }167 let g = generation168 entries = entries.compactMapValues { list in169 let kept = list.filter { g - $0.generation < 8 }170 return kept.isEmpty ? nil : kept171 }172 repeated = repeated.filter { g - $0.value.generation < 8 }173 }174175 /// Headers and footers are typeset once per distinct field content (page number, running head), not once per paragraph:176 /// the same paragraph appears on every page with different values.177 private var repeated: [String: Entry] = [:]178179 func layout(_ p: Paragraph, env: ParagraphEnvironment) -> ParagraphLayout {180 if env.isHeaderFooter {181 let key = p.id + "\u{1}" + env.boxTexts.joined(separator: "\u{1}") + "\u{1}\(env.width)"182 if var e = repeated[key], e.paragraph == p, e.options == env.options, e.typeface == env.mathTypeface {183 e.generation = generation184 repeated[key] = e185 hits += 1186 return e.layout187 }188 misses += 1189 let l = ParagraphLayout(p, env: env)190 repeated[key] = Entry(paragraph: p, width: env.width, label: nil, level: nil, headingNumber: nil, boxTexts: env.boxTexts, exclusions: [], isHeaderFooter: true,191 color: nil, options: env.options, typeface: env.mathTypeface, layout: l, generation: generation)192 return l193 }194 if var list = entries[p.id] {195 for i in list.indices {196 let e = list[i]197 if e.width == env.width, e.label == env.listLabel, e.level == env.listLevel, e.headingNumber == env.headingNumber, e.boxTexts == env.boxTexts,198 e.exclusions == env.exclusions, e.isHeaderFooter == env.isHeaderFooter, e.color == env.colorOverride, e.options == env.options,199 e.typeface == env.mathTypeface, e.paragraph == p {200 list[i].generation = generation201 entries[p.id] = list202 hits += 1203 return e.layout204 }205 }206 }207 misses += 1208 let l = ParagraphLayout(p, env: env)209 var list = entries[p.id] ?? []210 if list.count >= 3 { list.removeFirst() }211 list.append(Entry(paragraph: p, width: env.width, label: env.listLabel, level: env.listLevel, headingNumber: env.headingNumber, boxTexts: env.boxTexts,212 exclusions: env.exclusions, isHeaderFooter: env.isHeaderFooter, color: env.colorOverride, options: env.options, typeface: env.mathTypeface,213 layout: l, generation: generation))214 entries[p.id] = list215 return l216 }217218 public func removeAll() { entries.removeAll(); repeated.removeAll(); styles = nil }219}220221/// The result of pagination.222public final class DocumentLayout: @unchecked Sendable {223 public internal(set) var pages: [PageLayout] = []224 public let numbering: Numbering225 public let options: LayoutOptions226 /// Paragraph or block id → index of the page where it starts.227 public internal(set) var pageOfBlock: [String: Int] = [:]228 /// Paragraph or block id → page y of its first line (PDF destinations, outline navigation).229 public internal(set) var yOfBlock: [String: CGFloat] = [:]230 /// Tables that do not fit: wider than their column (scaled down) or holding a row taller than a page.231 public internal(set) var overflowingTableIDs: [String] = []232 /// Number of pagination passes needed for page references to settle.233 public internal(set) var passes = 1234 var index: [FragmentKey: [(page: Int, fragment: Int)]] = [:]235236 init(numbering: Numbering, options: LayoutOptions) { self.numbering = numbering; self.options = options }237238 public var pageCount: Int { pages.count }239240 public func pageText(ofBlock id: String) -> String? { pageOfBlock[id].map { pages[$0].numberText } }241242 func buildIndex() {243 index.removeAll(keepingCapacity: true)244 for (pi, page) in pages.enumerated() {245 for (fi, f) in page.texts.enumerated() where !f.generated || f.path.cell == nil {246 index[FragmentKey(story: f.story, path: f.path), default: []].append((pi, fi))247 }248 }249 }250251 /// Fragments of a paragraph, in page order. Headers and footers have one per page.252 public func fragments(story: StoryID, path: ParaPath) -> [(page: Int, fragment: TextFragment)] {253 (index[FragmentKey(story: story, path: path)] ?? []).map { ($0.page, pages[$0.page].texts[$0.fragment]) }254 }255}256