#if os(macOS) import AppKit extension NSAttributedString.Key { static let docsMarginBefore = NSAttributedString.Key("OficinaDocsMarginBefore") static let docsMarginAfter = NSAttributedString.Key("OficinaDocsMarginAfter") } /// The page breaks, for `DocsPageTextContainer.lineFragmentRect`: the /// absolute top of a block that starts a page, looked up by the character /// its first line starts at (nil for any other line). protocol DocsPageTops: AnyObject { /// Called by TextKit 1, which lays out on the main thread. nonisolated func top(at characterIndex: Int) -> CGFloat? } /// The measurement stack's container (§7 "Incremental pagination" 1): a /// rectangle as wide as the paper's text, so TextKit lays it out /// non-contiguously and shifts the lines after an edit instead of laying /// them out again (it does neither for a container that is not a simple /// rectangle, as the live one is not). It keeps the one rule of the live /// container that changes where a line wraps: a line starting with inline /// code is narrower by the code's padding. It never moves a line up or /// down; the live container's vertical rules (the top margin, the first /// block's margin, the breaks) are applied to the cached numbers instead. final class DocsMeasureTextContainer: NSTextContainer { override var isSimpleRectangularTextContainer: Bool { true } override func lineFragmentRect( forProposedRect proposedRect: CGRect, at characterIndex: Int, writingDirection baseWritingDirection: NSWritingDirection, remaining remainingRect: UnsafeMutablePointer? ) -> CGRect { #if DOCS_PROBES DocsProbes.measureLineRequests += 1 #endif var rect = super.lineFragmentRect(forProposedRect: proposedRect, at: characterIndex, writingDirection: baseWritingDirection, remaining: remainingRect) if let storage = layoutManager?.textStorage, characterIndex < storage.length { var range = NSRange() if let padding = storage.attribute(.docsCodeStart, at: characterIndex, effectiveRange: &range) as? CGFloat, range.location == characterIndex { rect.origin.x += padding rect.size.width = max(0, rect.width - padding) } } return rect } } /// Incremental pagination on the Mac (spec 2026-11-22 §7, "Incremental /// pagination"). Mirrors pages.mjs as `DocumentPageLayoutOracle` (today's /// measurement, now the tests' reference) does: top-level blocks are kept /// whole, and a separator goes before the next block whose bottom passes /// the 648pt text budget. Offsets are layout only; nothing is added to the /// document. /// /// - **A measurement stack on the same storage** (item 1): a second /// `DocsLayoutManager` with a rectangular container as wide as the paper's /// text (`DocsMeasureTextContainer`), attached to the live `NSTextStorage`. /// Its geometry is the natural one. It never draws, lays out /// non-contiguously, and edits reach it by themselves. /// - **Per-block caches** (item 2), one `Unit` per block run: its /// `advance` (first line's top to last line's bottom) and `usedBottom`, /// and its two margins. Natural tops are their prefix sums, so a Return, /// a deleted block or a paste is a splice. /// - **The full path** (item 3) measures every block: at open (the visible /// blocks at once, the rest in idle chunks of at most 8 ms a turn), on a width /// change, and when most blocks changed together. /// - **Per edit** (item 4) only the edited blocks are measured again; the /// break algorithm runs from the page holding the first of them until a /// break lands on the same block with the same `extra` as before. /// - **The break table** (item 5) is per block, and `top(at:)` gives the /// live container a break's absolute top, `topU + X`, which it takes as /// `max(proposed, top)`: idempotent however often TextKit proposes a line. /// - **Invalidation** (item 6) is from the first block whose top moved, and /// only the live layout manager's; the frame height (item 7) comes from /// the caches. /// /// A *unit* is a run of `.docsTopBlock` that starts a paragraph, with any /// run after it that does not (a Backspace at a block's start leaves one /// paragraph holding two runs until the publication merges them): a break /// can only go where a paragraph starts (§7 Design 4). A run of one id over /// several paragraphs (an optimistic Return, a list) is one unit. @MainActor final class DocsPagination: DocsPageTops { struct Unit { var id: String? var location: Int var length: Int var end: Int { location + length } var range: NSRange { NSRange(location: location, length: length) } /// Measured since its last edit. var measured = false /// From the first line's top to the last line fragment's bottom. var advance: CGFloat = 0 /// From the first line's top to the last line's used bottom. var usedBottom: CGFloat = 0 var before: CGFloat = 0 var after: CGFloat = 0 /// The page break before it: 0 for none. var extra: CGFloat = 0 /// The separator's distance above `top` (when `extra > 0`). var lift: CGFloat = 0 /// Its natural top, and where the live layout puts its first line /// (natural plus every `extra` at or before it). nil until known. var natural: CGFloat? var top: CGFloat? } /// The units, tiling the storage in order. private(set) var units: [Unit] = [] /// Every unit below it has been measured (until an edit marks one). private(set) var frontier = 0 private(set) var separators: [CGFloat] = [] /// The live layout's last line bottom, from the caches. private(set) var bottom: CGFloat = DocsPageGeometry.verticalMargin var paged = false { didSet { if oldValue != paged { markBreaks(from: 0) } } } let measurement = DocsLayoutManager() let container: DocsMeasureTextContainer private weak var storage: NSTextStorage? private weak var live: NSLayoutManager? /// The first and last unit whose breaks must be worked out again. private var breaksFrom: Int? private var breaksThrough = -1 private var full = true private var chunkScheduled = false private var wasEstimating = false /// Runs after a pass that moved the height (the text view lays itself /// out again) or lines at or above the visible bottom (it redraws). var changed: ((_ height: Bool, _ redraw: Bool) -> Void)? /// The live layout's visible bottom: lines below it moving need no redraw. var visibleBottom: () -> CGFloat = { .greatestFiniteMagnitude } /// Whether the measurement may continue in idle chunks (a window shows /// the text) or must finish at once (no window: tests, snapshots). var canDefer: () -> Bool = { false } /// Main-thread time an idle chunk may spend measuring (it measures at /// least one block). static var chunkBudget: Duration = .milliseconds(8) /// More edited blocks than this at once take the full path's order. static let staleLimit = 50 private(set) var geometry: DocsPageGeometry init(storage: NSTextStorage, live: NSLayoutManager, geometry: DocsPageGeometry) { self.storage = storage self.live = live self.geometry = geometry container = DocsMeasureTextContainer(size: CGSize(width: geometry.textWidth, height: 100_000_000)) container.lineFragmentPadding = 0 measurement.allowsNonContiguousLayout = true measurement.backgroundLayoutEnabled = false measurement.addTextContainer(container) storage.addLayoutManager(measurement) } /// The break table by block id: each break's `extra` (§7 item 5). var breaks: [String: CGFloat] { var breaks: [String: CGFloat] = [:] for unit in units where unit.extra > 0 { if let id = unit.id { breaks[id] = unit.extra } } return breaks } /// The breaks as the oracle states them: the live top of each break's /// block, by the character it starts at. var breakStarts: [Int: CGFloat] { var starts: [Int: CGFloat] = [:] for unit in units where unit.extra > 0 { if let top = unit.top { starts[unit.location] = top } } return starts } /// Whether every unit has been measured (the probe's flag for §7 item 10). var isComplete: Bool { frontier >= units.count && !units.contains { !$0.measured } } /// The paper's text width changed: everything is measured again. func setGeometry(_ geometry: DocsPageGeometry) { guard geometry != self.geometry else { return } self.geometry = geometry if container.size.width != geometry.textWidth { container.size = CGSize(width: geometry.textWidth, height: 100_000_000) } full = true } // MARK: - Edits /// The live layout manager saw an edit: `edited` is in the new text, /// `delta` the change in length. The units it touched (and their /// neighbours) are read again from the storage; the rest shift. Nothing /// is measured here: the measurement stack hears of the edit after this. func storageEdited(edited: NSRange, delta: Int) { // The full path reads every unit again anyway. guard !full else { return } guard let storage, !units.isEmpty, edited.location != NSNotFound else { full = true; return } let oldStart = edited.location, oldEnd = NSMaxRange(edited) - delta var first = firstUnit(endingAtOrAfter: oldStart) if first > 0 { first -= 1 } var last = first while last + 1 < units.count, units[last + 1].location <= oldEnd { last += 1 } if last + 1 < units.count { last += 1 } let start = units[first].location let end = units[last].end + delta guard start >= 0, end <= storage.length, start <= end else { full = true; return } var fresh = Self.units(in: storage, range: NSRange(location: start, length: end - start)) // Keep what is known of the units the edit left as they were (the // neighbours read again with it): same id, place and length, and // none of their characters in the edit. let old = units[first...last] var cursor = old.startIndex for index in fresh.indices { let unit = fresh[index] while cursor <= last { let candidate = old[cursor] let location = candidate.location >= oldEnd ? candidate.location + delta : candidate.location if location < unit.location { cursor += 1; continue } if location == unit.location, candidate.id == unit.id { // The same block where it was: its tops and break stay // until it is measured again (now, if the edit touched // it or its length changed). var kept = candidate kept.location = location kept.length = unit.length let untouched = candidate.end <= oldStart || candidate.location >= oldEnd if !untouched || candidate.length != unit.length || NSIntersectionRange(candidate.range, edited).length > 0 { kept.measured = false } fresh[index] = kept cursor += 1 } break } } for index in (last + 1).. last { frontier += shift } else if frontier > first { frontier = first } if breaksThrough > last { breaksThrough += shift } markBreaks(from: first, through: first + max(0, fresh.count - 1) + (first + fresh.count < units.count ? 1 : 0)) } private func markBreaks(from first: Int, through last: Int? = nil) { breaksFrom = min(breaksFrom ?? first, first) breaksThrough = max(breaksThrough, last ?? units.count - 1) } /// The units in `range` of `storage`, which starts at a unit's start /// (or 0) and ends at one's end (or the storage's). static func units(in storage: NSTextStorage, range: NSRange) -> [Unit] { var units: [Unit] = [] guard range.length > 0 else { return units } let characters = storage.mutableString storage.enumerateAttribute(.docsTopBlock, in: range) { value, found, _ in let id = value as? String let startsParagraph = found.location == 0 || Self.isParagraphEnd(characters.character(at: found.location - 1)) if let last = units.last, !startsParagraph || (last.id == id && last.end == found.location) { units[units.count - 1].length += found.length } else { units.append(Unit(id: id, location: found.location, length: found.length)) } } return units } static func isParagraphEnd(_ character: unichar) -> Bool { character == 10 || character == 13 || character == 0x2029 } private func firstUnit(endingAtOrAfter location: Int) -> Int { var low = 0, high = units.count - 1 while low < high { let middle = (low + high) / 2 if units[middle].end < location { low = middle + 1 } else { high = middle } } return low } // MARK: - The live container's lookup nonisolated func top(at characterIndex: Int) -> CGFloat? { MainActor.assumeIsolated { liveTop(at: characterIndex) } } private func liveTop(at characterIndex: Int) -> CGFloat? { var low = 0, high = units.count - 1 while low <= high { let middle = (low + high) / 2 let location = units[middle].location if location == characterIndex { return units[middle].extra > 0 ? units[middle].top : nil } if location < characterIndex { low = middle + 1 } else { high = middle - 1 } } return nil } // MARK: - Passes /// Brings the caches and the break table up to date: re-measures the /// edited units, measures on to `visibleBottom` (live coordinates) or /// `character`, works out the breaks that may have moved, and /// invalidates the live layout from the first unit whose top moved. /// Cheap when nothing changed. func update(visibleBottom: CGFloat, through character: Int? = nil, idle: Bool = false) { guard let storage else { return } if full { full = false units = Self.units(in: storage, range: NSRange(location: 0, length: storage.length)) frontier = 0 markBreaks(from: 0) } // Edited units below the frontier: measured again now, unless most // of the document changed (a font every block uses arrived), which // takes the full path's visible-first order instead. var stale = 0 var firstStale: Int? for index in 0.. Self.staleLimit, canDefer() { frontier = firstStale for index in firstStale.. 0 || wantsMore else { return } #if DOCS_PROBES let probeStart = DocsProbes.now() defer { DocsProbes.paginations += 1; DocsProbes.paginationMs += DocsProbes.ms(since: probeStart) } #endif for index in 0.. firstNew && started.duration(to: .now) >= Self.chunkBudget { break } } else if running > visibleBottom && units[frontier].location > targetCharacter { break } } measure(frontier) if frontier == 0 { running = units[0].natural ?? 0 } running += units[frontier].advance frontier += 1 } if frontier > firstNew { markBreaks(from: firstNew, through: frontier - 1) } finish() if frontier < units.count { scheduleChunk() } } /// Where the frontier's unit starts in the live layout, as far as the /// measured units say (breaks after the last pass not counted: a low /// estimate, so the frontier only ever goes further than needed). private func frontierTop() -> CGFloat { guard frontier > 0 else { return 0 } let previous = units[frontier - 1] return (previous.top ?? previous.natural ?? 0) + previous.advance } private func measure(_ index: Int) { guard let storage else { return } let unit = units[index] let glyphs = measurement.glyphRange(forCharacterRange: unit.range, actualCharacterRange: nil) var top = CGFloat.greatestFiniteMagnitude, rectBottom = -CGFloat.greatestFiniteMagnitude, usedBottom = -CGFloat.greatestFiniteMagnitude measurement.enumerateLineFragments(forGlyphRange: glyphs) { rect, used, _, _, _ in top = min(top, rect.minY); rectBottom = max(rectBottom, rect.maxY); usedBottom = max(usedBottom, used.maxY) } if top == .greatestFiniteMagnitude { units[index].advance = 0; units[index].usedBottom = 0 } else { units[index].advance = rectBottom - top units[index].usedBottom = usedBottom - top } if index == 0 { // The live container's two vertical rules for the first line: // the page's top margin, and the first block's own margin. let margin = storage.length > 0 ? storage.attribute(.docsFirstMargin, at: 0, effectiveRange: nil) as? CGFloat ?? 0 : 0 units[0].natural = DocsPageGeometry.verticalMargin + max(0, margin) } units[index].before = storage.attribute(.docsMarginBefore, at: unit.location, effectiveRange: nil) as? CGFloat ?? 0 units[index].after = storage.attribute(.docsMarginAfter, at: max(unit.location, unit.end - 1), effectiveRange: nil) as? CGFloat ?? 0 units[index].measured = true } /// The break algorithm from the page holding the first unit to work /// out, the prefix sums, the separators, the height, and the live /// layout's invalidation. private func finish() { let measured = min(frontier, units.count) if let from = breaksFrom, measured > 0 { breakPass(from: min(from, measured - 1), through: breaksThrough, limit: measured) } breaksFrom = nil; breaksThrough = -1 // Prefix sums: natural tops, the extras, the live tops. var natural = units.first?.natural ?? DocsPageGeometry.verticalMargin var added: CGFloat = 0 var firstMoved: Int? var movedY = CGFloat.greatestFiniteMagnitude var separators: [CGFloat] = [] var measuredAdvance: CGFloat = 0, measuredLength = 0 for index in units.indices { let known = index < measured if known { units[index].natural = natural added += units[index].extra let top = natural + added if units[index].extra > 0 { separators.append(top - units[index].lift) } if firstMoved == nil, units[index].top.map({ abs($0 - top) > 0.001 }) ?? true { firstMoved = index movedY = min(top, units[index].top ?? top) } units[index].top = top measuredAdvance += units[index].advance; measuredLength += units[index].length } else if units[index].top != nil { // Beyond the frontier: no top until measured, so TextKit // flows these lines on from the last measured one. if firstMoved == nil { firstMoved = index; movedY = units[index].top ?? movedY } units[index].top = nil; units[index].natural = nil } if known { natural += units[index].advance } } var bottom = units.isEmpty ? DocsPageGeometry.verticalMargin : natural + added if measured < units.count, measuredLength > 0 { // Below the frontier, an estimate from the average measured advance. let remaining = units[measured...].reduce(0) { $0 + $1.length } bottom += measuredAdvance / CGFloat(measuredLength) * CGFloat(remaining) } // Redraw only if something at or above the visible bottom moved: // while idle chunks measure below the screen, nothing there does. let shown = visibleBottom() let redraw = (firstMoved != nil && movedY <= shown) || separators.prefix { $0 <= shown } != self.separators.prefix { $0 <= shown } // While the frontier moves the bottom is an estimate: the frame // follows it only when it is off by a page or more, and exactly // once measuring is done. let estimating = measured < units.count let height = abs(bottom - self.bottom) > (estimating ? DocsPageGeometry.paperHeight : 0.001) if !height && estimating { bottom = self.bottom } if !estimating, wasEstimating, let storage { // Measuring done: fix the storage's attributes once, now. Typed // while the rest was being measured, a key joins its edit to the // storage's one range of attributes still to fix, which then // runs to the document's end, and every later key fixed all of // it again (7 ms a key at p200h, against 3.5). Once costs 0–30 ms. storage.ensureAttributesAreFixed(in: NSRange(location: 0, length: storage.length)) } wasEstimating = estimating self.separators = separators self.bottom = bottom if let firstMoved, let live, let storage, firstMoved < units.count { let location = units[firstMoved].location live.invalidateLayout(forCharacterRange: NSRange(location: location, length: storage.length - location), actualCharacterRange: nil) } #if DOCS_PROBES DocsProbes.measuring = measured < units.count #endif if height || redraw { changed?(height, redraw) } } /// Today's algorithm (DocumentPageLayoutOracle.measure) over the cached /// natural geometry, from the last break before `from` (whose page /// holds it), until a break past `through` lands where it was. private func breakPass(from: Int, through: Int, limit: Int) { guard paged else { for index in units.indices where units[index].extra != 0 { units[index].extra = 0; units[index].lift = 0 } return } // The page holding `from` starts at the last break before it. var start = from - 1 while start >= 0, units[start].extra == 0 { start -= 1 } var pageTop: CGFloat? var previousMargin: CGFloat = 0 var natural: CGFloat var index: Int if start >= 0, let top = units[start].natural { pageTop = top previousMargin = units[start].after natural = top + units[start].advance index = start + 1 } else { natural = units.first?.natural ?? DocsPageGeometry.verticalMargin index = 0 } while index < limit { let unit = units[index] var extra: CGFloat = 0, lift: CGFloat = 0 if unit.id != nil, unit.usedBottom > 0 { let top = natural, bottom = top + unit.usedBottom if let current = pageTop { if bottom - current > 648 { let collapsed = max(previousMargin, unit.before) extra = max(previousMargin, 12) + 18 + max(unit.before, 12) - collapsed lift = extra + collapsed - max(previousMargin, 12) pageTop = top } } else { pageTop = top } previousMargin = unit.after } let converged = index > through && extra > 0 && unit.extra == extra units[index].extra = extra units[index].lift = lift if converged { return } natural += unit.advance index += 1 } // Past the frontier nothing is known: no breaks there yet. for rest in limit..