oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1#if os(macOS)
2import AppKit
3
4extension NSAttributedString.Key {
5 static let docsMarginBefore = NSAttributedString.Key("OficinaDocsMarginBefore")
6 static let docsMarginAfter = NSAttributedString.Key("OficinaDocsMarginAfter")
7}
8
9/// The page breaks, for `DocsPageTextContainer.lineFragmentRect`: the
10/// absolute top of a block that starts a page, looked up by the character
11/// its first line starts at (nil for any other line).
12protocol DocsPageTops: AnyObject {
13 /// Called by TextKit 1, which lays out on the main thread.
14 nonisolated func top(at characterIndex: Int) -> CGFloat?
15}
16
17/// The measurement stack's container (§7 "Incremental pagination" 1): a
18/// rectangle as wide as the paper's text, so TextKit lays it out
19/// non-contiguously and shifts the lines after an edit instead of laying
20/// them out again (it does neither for a container that is not a simple
21/// rectangle, as the live one is not). It keeps the one rule of the live
22/// container that changes where a line wraps: a line starting with inline
23/// code is narrower by the code's padding. It never moves a line up or
24/// down; the live container's vertical rules (the top margin, the first
25/// block's margin, the breaks) are applied to the cached numbers instead.
26final class DocsMeasureTextContainer: NSTextContainer {
27 override var isSimpleRectangularTextContainer: Bool { true }
28 override func lineFragmentRect(
29 forProposedRect proposedRect: CGRect, at characterIndex: Int,
30 writingDirection baseWritingDirection: NSWritingDirection,
31 remaining remainingRect: UnsafeMutablePointer<CGRect>?
32 ) -> CGRect {
33 #if DOCS_PROBES
34 DocsProbes.measureLineRequests += 1
35 #endif
36 var rect = super.lineFragmentRect(forProposedRect: proposedRect, at: characterIndex, writingDirection: baseWritingDirection, remaining: remainingRect)
37 if let storage = layoutManager?.textStorage, characterIndex < storage.length {
38 var range = NSRange()
39 if let padding = storage.attribute(.docsCodeStart, at: characterIndex, effectiveRange: &range) as? CGFloat,
40 range.location == characterIndex {
41 rect.origin.x += padding
42 rect.size.width = max(0, rect.width - padding)
43 }
44 }
45 return rect
46 }
47}
48
49/// Incremental pagination on the Mac (spec 2026-11-22 §7, "Incremental
50/// pagination"). Mirrors pages.mjs as `DocumentPageLayoutOracle` (today's
51/// measurement, now the tests' reference) does: top-level blocks are kept
52/// whole, and a separator goes before the next block whose bottom passes
53/// the 648pt text budget. Offsets are layout only; nothing is added to the
54/// document.
55///
56/// - **A measurement stack on the same storage** (item 1): a second
57/// `DocsLayoutManager` with a rectangular container as wide as the paper's
58/// text (`DocsMeasureTextContainer`), attached to the live `NSTextStorage`.
59/// Its geometry is the natural one. It never draws, lays out
60/// non-contiguously, and edits reach it by themselves.
61/// - **Per-block caches** (item 2), one `Unit` per block run: its
62/// `advance` (first line's top to last line's bottom) and `usedBottom`,
63/// and its two margins. Natural tops are their prefix sums, so a Return,
64/// a deleted block or a paste is a splice.
65/// - **The full path** (item 3) measures every block: at open (the visible
66/// blocks at once, the rest in idle chunks of at most 8 ms a turn), on a width
67/// change, and when most blocks changed together.
68/// - **Per edit** (item 4) only the edited blocks are measured again; the
69/// break algorithm runs from the page holding the first of them until a
70/// break lands on the same block with the same `extra` as before.
71/// - **The break table** (item 5) is per block, and `top(at:)` gives the
72/// live container a break's absolute top, `topU + X`, which it takes as
73/// `max(proposed, top)`: idempotent however often TextKit proposes a line.
74/// - **Invalidation** (item 6) is from the first block whose top moved, and
75/// only the live layout manager's; the frame height (item 7) comes from
76/// the caches.
77///
78/// A *unit* is a run of `.docsTopBlock` that starts a paragraph, with any
79/// run after it that does not (a Backspace at a block's start leaves one
80/// paragraph holding two runs until the publication merges them): a break
81/// can only go where a paragraph starts (§7 Design 4). A run of one id over
82/// several paragraphs (an optimistic Return, a list) is one unit.
83@MainActor final class DocsPagination: DocsPageTops {
84 struct Unit {
85 var id: String?
86 var location: Int
87 var length: Int
88 var end: Int { location + length }
89 var range: NSRange { NSRange(location: location, length: length) }
90 /// Measured since its last edit.
91 var measured = false
92 /// From the first line's top to the last line fragment's bottom.
93 var advance: CGFloat = 0
94 /// From the first line's top to the last line's used bottom.
95 var usedBottom: CGFloat = 0
96 var before: CGFloat = 0
97 var after: CGFloat = 0
98 /// The page break before it: 0 for none.
99 var extra: CGFloat = 0
100 /// The separator's distance above `top` (when `extra > 0`).
101 var lift: CGFloat = 0
102 /// Its natural top, and where the live layout puts its first line
103 /// (natural plus every `extra` at or before it). nil until known.
104 var natural: CGFloat?
105 var top: CGFloat?
106 }
107
108 /// The units, tiling the storage in order.
109 private(set) var units: [Unit] = []
110 /// Every unit below it has been measured (until an edit marks one).
111 private(set) var frontier = 0
112 private(set) var separators: [CGFloat] = []
113 /// The live layout's last line bottom, from the caches.
114 private(set) var bottom: CGFloat = DocsPageGeometry.verticalMargin
115 var paged = false { didSet { if oldValue != paged { markBreaks(from: 0) } } }
116
117 let measurement = DocsLayoutManager()
118 let container: DocsMeasureTextContainer
119 private weak var storage: NSTextStorage?
120 private weak var live: NSLayoutManager?
121 /// The first and last unit whose breaks must be worked out again.
122 private var breaksFrom: Int?
123 private var breaksThrough = -1
124 private var full = true
125 private var chunkScheduled = false
126 private var wasEstimating = false
127 /// Runs after a pass that moved the height (the text view lays itself
128 /// out again) or lines at or above the visible bottom (it redraws).
129 var changed: ((_ height: Bool, _ redraw: Bool) -> Void)?
130 /// The live layout's visible bottom: lines below it moving need no redraw.
131 var visibleBottom: () -> CGFloat = { .greatestFiniteMagnitude }
132 /// Whether the measurement may continue in idle chunks (a window shows
133 /// the text) or must finish at once (no window: tests, snapshots).
134 var canDefer: () -> Bool = { false }
135
136 /// Main-thread time an idle chunk may spend measuring (it measures at
137 /// least one block).
138 static var chunkBudget: Duration = .milliseconds(8)
139 /// More edited blocks than this at once take the full path's order.
140 static let staleLimit = 50
141
142 private(set) var geometry: DocsPageGeometry
143
144 init(storage: NSTextStorage, live: NSLayoutManager, geometry: DocsPageGeometry) {
145 self.storage = storage
146 self.live = live
147 self.geometry = geometry
148 container = DocsMeasureTextContainer(size: CGSize(width: geometry.textWidth, height: 100_000_000))
149 container.lineFragmentPadding = 0
150 measurement.allowsNonContiguousLayout = true
151 measurement.backgroundLayoutEnabled = false
152 measurement.addTextContainer(container)
153 storage.addLayoutManager(measurement)
154 }
155
156 /// The break table by block id: each break's `extra` (§7 item 5).
157 var breaks: [String: CGFloat] {
158 var breaks: [String: CGFloat] = [:]
159 for unit in units where unit.extra > 0 { if let id = unit.id { breaks[id] = unit.extra } }
160 return breaks
161 }
162 /// The breaks as the oracle states them: the live top of each break's
163 /// block, by the character it starts at.
164 var breakStarts: [Int: CGFloat] {
165 var starts: [Int: CGFloat] = [:]
166 for unit in units where unit.extra > 0 { if let top = unit.top { starts[unit.location] = top } }
167 return starts
168 }
169
170 /// Whether every unit has been measured (the probe's flag for §7 item 10).
171 var isComplete: Bool { frontier >= units.count && !units.contains { !$0.measured } }
172
173 /// The paper's text width changed: everything is measured again.
174 func setGeometry(_ geometry: DocsPageGeometry) {
175 guard geometry != self.geometry else { return }
176 self.geometry = geometry
177 if container.size.width != geometry.textWidth { container.size = CGSize(width: geometry.textWidth, height: 100_000_000) }
178 full = true
179 }
180
181 // MARK: - Edits
182
183 /// The live layout manager saw an edit: `edited` is in the new text,
184 /// `delta` the change in length. The units it touched (and their
185 /// neighbours) are read again from the storage; the rest shift. Nothing
186 /// is measured here: the measurement stack hears of the edit after this.
187 func storageEdited(edited: NSRange, delta: Int) {
188 // The full path reads every unit again anyway.
189 guard !full else { return }
190 guard let storage, !units.isEmpty, edited.location != NSNotFound else { full = true; return }
191 let oldStart = edited.location, oldEnd = NSMaxRange(edited) - delta
192 var first = firstUnit(endingAtOrAfter: oldStart)
193 if first > 0 { first -= 1 }
194 var last = first
195 while last + 1 < units.count, units[last + 1].location <= oldEnd { last += 1 }
196 if last + 1 < units.count { last += 1 }
197 let start = units[first].location
198 let end = units[last].end + delta
199 guard start >= 0, end <= storage.length, start <= end else { full = true; return }
200 var fresh = Self.units(in: storage, range: NSRange(location: start, length: end - start))
201 // Keep what is known of the units the edit left as they were (the
202 // neighbours read again with it): same id, place and length, and
203 // none of their characters in the edit.
204 let old = units[first...last]
205 var cursor = old.startIndex
206 for index in fresh.indices {
207 let unit = fresh[index]
208 while cursor <= last {
209 let candidate = old[cursor]
210 let location = candidate.location >= oldEnd ? candidate.location + delta : candidate.location
211 if location < unit.location { cursor += 1; continue }
212 if location == unit.location, candidate.id == unit.id {
213 // The same block where it was: its tops and break stay
214 // until it is measured again (now, if the edit touched
215 // it or its length changed).
216 var kept = candidate
217 kept.location = location
218 kept.length = unit.length
219 let untouched = candidate.end <= oldStart || candidate.location >= oldEnd
220 if !untouched || candidate.length != unit.length || NSIntersectionRange(candidate.range, edited).length > 0 { kept.measured = false }
221 fresh[index] = kept
222 cursor += 1
223 }
224 break
225 }
226 }
227 for index in (last + 1)..<units.count { units[index].location += delta }
228 units.replaceSubrange(first...last, with: fresh)
229 let shift = fresh.count - (last - first + 1)
230 if frontier > last { frontier += shift } else if frontier > first { frontier = first }
231 if breaksThrough > last { breaksThrough += shift }
232 markBreaks(from: first, through: first + max(0, fresh.count - 1) + (first + fresh.count < units.count ? 1 : 0))
233 }
234
235 private func markBreaks(from first: Int, through last: Int? = nil) {
236 breaksFrom = min(breaksFrom ?? first, first)
237 breaksThrough = max(breaksThrough, last ?? units.count - 1)
238 }
239
240 /// The units in `range` of `storage`, which starts at a unit's start
241 /// (or 0) and ends at one's end (or the storage's).
242 static func units(in storage: NSTextStorage, range: NSRange) -> [Unit] {
243 var units: [Unit] = []
244 guard range.length > 0 else { return units }
245 let characters = storage.mutableString
246 storage.enumerateAttribute(.docsTopBlock, in: range) { value, found, _ in
247 let id = value as? String
248 let startsParagraph = found.location == 0 || Self.isParagraphEnd(characters.character(at: found.location - 1))
249 if let last = units.last, !startsParagraph || (last.id == id && last.end == found.location) {
250 units[units.count - 1].length += found.length
251 } else {
252 units.append(Unit(id: id, location: found.location, length: found.length))
253 }
254 }
255 return units
256 }
257 static func isParagraphEnd(_ character: unichar) -> Bool { character == 10 || character == 13 || character == 0x2029 }
258
259 private func firstUnit(endingAtOrAfter location: Int) -> Int {
260 var low = 0, high = units.count - 1
261 while low < high {
262 let middle = (low + high) / 2
263 if units[middle].end < location { low = middle + 1 } else { high = middle }
264 }
265 return low
266 }
267
268 // MARK: - The live container's lookup
269
270 nonisolated func top(at characterIndex: Int) -> CGFloat? {
271 MainActor.assumeIsolated { liveTop(at: characterIndex) }
272 }
273 private func liveTop(at characterIndex: Int) -> CGFloat? {
274 var low = 0, high = units.count - 1
275 while low <= high {
276 let middle = (low + high) / 2
277 let location = units[middle].location
278 if location == characterIndex { return units[middle].extra > 0 ? units[middle].top : nil }
279 if location < characterIndex { low = middle + 1 } else { high = middle - 1 }
280 }
281 return nil
282 }
283
284 // MARK: - Passes
285
286 /// Brings the caches and the break table up to date: re-measures the
287 /// edited units, measures on to `visibleBottom` (live coordinates) or
288 /// `character`, works out the breaks that may have moved, and
289 /// invalidates the live layout from the first unit whose top moved.
290 /// Cheap when nothing changed.
291 func update(visibleBottom: CGFloat, through character: Int? = nil, idle: Bool = false) {
292 guard let storage else { return }
293 if full {
294 full = false
295 units = Self.units(in: storage, range: NSRange(location: 0, length: storage.length))
296 frontier = 0
297 markBreaks(from: 0)
298 }
299 // Edited units below the frontier: measured again now, unless most
300 // of the document changed (a font every block uses arrived), which
301 // takes the full path's visible-first order instead.
302 var stale = 0
303 var firstStale: Int?
304 for index in 0..<min(frontier, units.count) where !units[index].measured {
305 stale += 1
306 if firstStale == nil { firstStale = index }
307 }
308 if let firstStale, stale > Self.staleLimit, canDefer() {
309 frontier = firstStale
310 for index in firstStale..<units.count { units[index].measured = false }
311 }
312 let deferring = canDefer()
313 let wantsMore = frontier < units.count && (!deferring || idle || frontierTop() <= visibleBottom
314 || units[frontier].location <= (character ?? -1))
315 // In a window with more to measure and no chunk waiting (it was
316 // dropped while the view was out of its window): carry on.
317 if deferring, frontier < units.count, !wantsMore { scheduleChunk() }
318 guard breaksFrom != nil || stale > 0 || wantsMore else { return }
319 #if DOCS_PROBES
320 let probeStart = DocsProbes.now()
321 defer { DocsProbes.paginations += 1; DocsProbes.paginationMs += DocsProbes.ms(since: probeStart) }
322 #endif
323 for index in 0..<min(frontier, units.count) where !units[index].measured { measure(index) }
324 // The frontier: to what is shown (or asked for), the rest later.
325 var running = frontierTop()
326 let targetCharacter = character ?? -1
327 let firstNew = frontier
328 let started = ContinuousClock.now
329 while frontier < units.count {
330 if deferring {
331 if idle {
332 if frontier > firstNew && started.duration(to: .now) >= Self.chunkBudget { break }
333 } else if running > visibleBottom && units[frontier].location > targetCharacter { break }
334 }
335 measure(frontier)
336 if frontier == 0 { running = units[0].natural ?? 0 }
337 running += units[frontier].advance
338 frontier += 1
339 }
340 if frontier > firstNew { markBreaks(from: firstNew, through: frontier - 1) }
341 finish()
342 if frontier < units.count { scheduleChunk() }
343 }
344
345 /// Where the frontier's unit starts in the live layout, as far as the
346 /// measured units say (breaks after the last pass not counted: a low
347 /// estimate, so the frontier only ever goes further than needed).
348 private func frontierTop() -> CGFloat {
349 guard frontier > 0 else { return 0 }
350 let previous = units[frontier - 1]
351 return (previous.top ?? previous.natural ?? 0) + previous.advance
352 }
353
354 private func measure(_ index: Int) {
355 guard let storage else { return }
356 let unit = units[index]
357 let glyphs = measurement.glyphRange(forCharacterRange: unit.range, actualCharacterRange: nil)
358 var top = CGFloat.greatestFiniteMagnitude, rectBottom = -CGFloat.greatestFiniteMagnitude, usedBottom = -CGFloat.greatestFiniteMagnitude
359 measurement.enumerateLineFragments(forGlyphRange: glyphs) { rect, used, _, _, _ in
360 top = min(top, rect.minY); rectBottom = max(rectBottom, rect.maxY); usedBottom = max(usedBottom, used.maxY)
361 }
362 if top == .greatestFiniteMagnitude {
363 units[index].advance = 0; units[index].usedBottom = 0
364 } else {
365 units[index].advance = rectBottom - top
366 units[index].usedBottom = usedBottom - top
367 }
368 if index == 0 {
369 // The live container's two vertical rules for the first line:
370 // the page's top margin, and the first block's own margin.
371 let margin = storage.length > 0 ? storage.attribute(.docsFirstMargin, at: 0, effectiveRange: nil) as? CGFloat ?? 0 : 0
372 units[0].natural = DocsPageGeometry.verticalMargin + max(0, margin)
373 }
374 units[index].before = storage.attribute(.docsMarginBefore, at: unit.location, effectiveRange: nil) as? CGFloat ?? 0
375 units[index].after = storage.attribute(.docsMarginAfter, at: max(unit.location, unit.end - 1), effectiveRange: nil) as? CGFloat ?? 0
376 units[index].measured = true
377 }
378
379 /// The break algorithm from the page holding the first unit to work
380 /// out, the prefix sums, the separators, the height, and the live
381 /// layout's invalidation.
382 private func finish() {
383 let measured = min(frontier, units.count)
384 if let from = breaksFrom, measured > 0 {
385 breakPass(from: min(from, measured - 1), through: breaksThrough, limit: measured)
386 }
387 breaksFrom = nil; breaksThrough = -1
388 // Prefix sums: natural tops, the extras, the live tops.
389 var natural = units.first?.natural ?? DocsPageGeometry.verticalMargin
390 var added: CGFloat = 0
391 var firstMoved: Int?
392 var movedY = CGFloat.greatestFiniteMagnitude
393 var separators: [CGFloat] = []
394 var measuredAdvance: CGFloat = 0, measuredLength = 0
395 for index in units.indices {
396 let known = index < measured
397 if known {
398 units[index].natural = natural
399 added += units[index].extra
400 let top = natural + added
401 if units[index].extra > 0 { separators.append(top - units[index].lift) }
402 if firstMoved == nil, units[index].top.map({ abs($0 - top) > 0.001 }) ?? true {
403 firstMoved = index
404 movedY = min(top, units[index].top ?? top)
405 }
406 units[index].top = top
407 measuredAdvance += units[index].advance; measuredLength += units[index].length
408 } else if units[index].top != nil {
409 // Beyond the frontier: no top until measured, so TextKit
410 // flows these lines on from the last measured one.
411 if firstMoved == nil { firstMoved = index; movedY = units[index].top ?? movedY }
412 units[index].top = nil; units[index].natural = nil
413 }
414 if known { natural += units[index].advance }
415 }
416 var bottom = units.isEmpty ? DocsPageGeometry.verticalMargin : natural + added
417 if measured < units.count, measuredLength > 0 {
418 // Below the frontier, an estimate from the average measured advance.
419 let remaining = units[measured...].reduce(0) { $0 + $1.length }
420 bottom += measuredAdvance / CGFloat(measuredLength) * CGFloat(remaining)
421 }
422 // Redraw only if something at or above the visible bottom moved:
423 // while idle chunks measure below the screen, nothing there does.
424 let shown = visibleBottom()
425 let redraw = (firstMoved != nil && movedY <= shown)
426 || separators.prefix { $0 <= shown } != self.separators.prefix { $0 <= shown }
427 // While the frontier moves the bottom is an estimate: the frame
428 // follows it only when it is off by a page or more, and exactly
429 // once measuring is done.
430 let estimating = measured < units.count
431 let height = abs(bottom - self.bottom) > (estimating ? DocsPageGeometry.paperHeight : 0.001)
432 if !height && estimating { bottom = self.bottom }
433 if !estimating, wasEstimating, let storage {
434 // Measuring done: fix the storage's attributes once, now. Typed
435 // while the rest was being measured, a key joins its edit to the
436 // storage's one range of attributes still to fix, which then
437 // runs to the document's end, and every later key fixed all of
438 // it again (7 ms a key at p200h, against 3.5). Once costs 0–30 ms.
439 storage.ensureAttributesAreFixed(in: NSRange(location: 0, length: storage.length))
440 }
441 wasEstimating = estimating
442 self.separators = separators
443 self.bottom = bottom
444 if let firstMoved, let live, let storage, firstMoved < units.count {
445 let location = units[firstMoved].location
446 live.invalidateLayout(forCharacterRange: NSRange(location: location, length: storage.length - location), actualCharacterRange: nil)
447 }
448 #if DOCS_PROBES
449 DocsProbes.measuring = measured < units.count
450 #endif
451 if height || redraw { changed?(height, redraw) }
452 }
453
454 /// Today's algorithm (DocumentPageLayoutOracle.measure) over the cached
455 /// natural geometry, from the last break before `from` (whose page
456 /// holds it), until a break past `through` lands where it was.
457 private func breakPass(from: Int, through: Int, limit: Int) {
458 guard paged else {
459 for index in units.indices where units[index].extra != 0 { units[index].extra = 0; units[index].lift = 0 }
460 return
461 }
462 // The page holding `from` starts at the last break before it.
463 var start = from - 1
464 while start >= 0, units[start].extra == 0 { start -= 1 }
465 var pageTop: CGFloat?
466 var previousMargin: CGFloat = 0
467 var natural: CGFloat
468 var index: Int
469 if start >= 0, let top = units[start].natural {
470 pageTop = top
471 previousMargin = units[start].after
472 natural = top + units[start].advance
473 index = start + 1
474 } else {
475 natural = units.first?.natural ?? DocsPageGeometry.verticalMargin
476 index = 0
477 }
478 while index < limit {
479 let unit = units[index]
480 var extra: CGFloat = 0, lift: CGFloat = 0
481 if unit.id != nil, unit.usedBottom > 0 {
482 let top = natural, bottom = top + unit.usedBottom
483 if let current = pageTop {
484 if bottom - current > 648 {
485 let collapsed = max(previousMargin, unit.before)
486 extra = max(previousMargin, 12) + 18 + max(unit.before, 12) - collapsed
487 lift = extra + collapsed - max(previousMargin, 12)
488 pageTop = top
489 }
490 } else { pageTop = top }
491 previousMargin = unit.after
492 }
493 let converged = index > through && extra > 0 && unit.extra == extra
494 units[index].extra = extra
495 units[index].lift = lift
496 if converged { return }
497 natural += unit.advance
498 index += 1
499 }
500 // Past the frontier nothing is known: no breaks there yet.
501 for rest in limit..<units.count where units[rest].extra != 0 { units[rest].extra = 0; units[rest].lift = 0 }
502 }
503
504 private func scheduleChunk() {
505 guard !chunkScheduled, canDefer() else { return }
506 chunkScheduled = true
507 let timer = Timer(timeInterval: 0, repeats: false) { [weak self] _ in
508 MainActor.assumeIsolated {
509 guard let self else { return }
510 self.chunkScheduled = false
511 // Out of a window (the view was removed with measuring still
512 // to do): never the whole rest in this one turn. The next
513 // layout in a window picks it up.
514 guard self.frontier < self.units.count, self.canDefer() else { return }
515 // One chunk past the frontier, then the next turn.
516 self.update(visibleBottom: -.greatestFiniteMagnitude, idle: true)
517 }
518 }
519 RunLoop.main.add(timer, forMode: .common)
520 }
521}
522#endif
523