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(iOS)
2import UIKit
3
4/// The iPhone's page breaks on TextKit 2 (S3; spec 2026-11-22 §7 "iPhone
5/// layout", S1b ruling #173).
6///
7/// TextKit 1 paginated by line in the text container's `lineFragmentRect`.
8/// UIKit runs any view whose container does that on TextKit 1 (a container
9/// that is not a plain rectangle switches it back), and TextKit 2's own
10/// exclusion paths lay the whole document out on open and on every key
11/// (1.27 s and 0.53 s at 200 pages). So the breaks are by paragraph, as the
12/// Mac's are by block: a paragraph that would cross a page's bottom margin
13/// starts on the next page instead. The space before it is display-only: the
14/// layout fragment of the paragraph before it is that much taller at the
15/// bottom (`DocsPageBreakFragment`), so TextKit 2 stacks the next one lower,
16/// and the text storage, which the surface reconciles against the replica,
17/// never holds it. (Neither the content storage's delegate, which
18/// `UITextView` does not ask about list items, nor a fragment's `topMargin`,
19/// which stacking ignores, can do it.)
20///
21/// Positions come from each paragraph's own measurements, cached: the space
22/// above its first line and below its last inside its layout fragment, and
23/// its lines' span. They come from a layout of the paragraph alone, never
24/// from where TextKit 2 placed it, and none depends on the breaks. The breaks are then arithmetic over the cache, from the
25/// first paragraph that changed until a paragraph lands where it was.
26/// Measuring is TextKit 2 layout, so it is done a few paragraphs at a time:
27/// the ones on screen as they are drawn, the rest in idle chunks, and, on a
28/// jump past what is measured, everything up to the target at once (spec §7
29/// "Fallback": once per jump, never per key).
30///
31/// A paragraph taller than a page's body cannot fit one: it starts at a page
32/// top and runs over the gap (rare; TextKit 2 offers no line-level break
33/// that keeps layout lazy).
34@MainActor final class DocsPhonePages: NSObject {
35 struct Paragraph: Equatable {
36 var length: Int
37 /// Inside its layout fragment: the space above its first line, its
38 /// lines' span, and the space below its last line (less any break
39 /// space it carries). TextKit 2 stacks fragments frame to frame, so
40 /// a paragraph's lead is the one before's `tail` plus its `head`:
41 /// all local to the fragments, never their positions, which TextKit
42 /// 2 leaves stale after a paragraph above changes size.
43 var head: CGFloat?
44 var height: CGFloat?
45 var tail: CGFloat?
46 /// The space added before it to start it on a new page.
47 var extra: CGFloat = 0
48 /// Its last line's bottom, as the breaks place it.
49 var bottom: CGFloat?
50 }
51 private(set) var paragraphs: [Paragraph] = []
52 private var startsCache: [Int]?
53 var paged = false
54 /// Where the text container's top sits below the first page's body top
55 /// (the first block's own top margin, `docsFirstMargin`).
56 var origin: CGFloat = 0
57 /// The first paragraph whose position may have changed, nil when every
58 /// measured paragraph is placed.
59 private(set) var settleFrom: Int?
60 /// The last paragraph measured (or edited) since it was placed: placing
61 /// may stop once a paragraph lands where it was only past this one, as
62 /// the ones up to it were never placed from their new measurements.
63 private var settleThrough = -1
64 /// Paragraphs whose extra changed and whose element TextKit 2 must build again.
65 private var changed = IndexSet()
66 /// True while the pages ask TextKit 2 to build paragraphs again (an
67 /// attribute-only edit of nothing): those edits are not text changes.
68 private(set) var regenerating = false
69 /// TextKit 2's layout is contiguous from the top through this character.
70 private(set) var laidOutThrough = 0
71 /// The first character below which TextKit 2's laid-out fragments may
72 /// sit away from where they belong, since an edit or a rebuilt break.
73 /// TextKit 2 does not move the fragments below one that changed (and
74 /// until it does, places a screen there at an estimate); it stacks them
75 /// again on a walk from the top. A walk over what is laid out lays out
76 /// no line again (an edit's own paragraph aside), so it costs
77 /// milliseconds at 200 pages, where throwing the layout below an edit
78 /// away and laying it out again cost half a second (Fable on #180).
79 private(set) var editedFrom: Int?
80 weak var storage: NSTextStorage?
81 /// Chunk size for the idle measurement.
82 static let chunk = 40
83
84 static let stride = DocsPageGeometry.paperHeight + DocsPageGeometry.gap
85 static let body = DocsPageGeometry.paperHeight - DocsPageGeometry.verticalMargin * 2
86
87 // MARK: Paragraphs
88
89 var starts: [Int] {
90 if let startsCache { return startsCache }
91 var at = 0, made: [Int] = []
92 made.reserveCapacity(paragraphs.count)
93 for paragraph in paragraphs { made.append(at); at += paragraph.length }
94 startsCache = made
95 return made
96 }
97 /// The paragraph holding character `location` (the last for the end).
98 func paragraph(at location: Int) -> Int? {
99 guard !paragraphs.isEmpty else { return nil }
100 let starts = self.starts
101 var low = 0, high = starts.count - 1
102 while low < high {
103 let mid = (low + high + 1) / 2
104 if starts[mid] <= location { low = mid } else { high = mid - 1 }
105 }
106 return low
107 }
108 func range(of index: Int) -> NSRange { NSRange(location: starts[index], length: paragraphs[index].length) }
109
110 static func lengths(in string: NSString, range: NSRange) -> [Int] {
111 var lengths: [Int] = []
112 string.enumerateSubstrings(in: range, options: [.byParagraphs, .substringNotRequired]) { _, _, enclosing, _ in
113 lengths.append(enclosing.length)
114 }
115 return lengths
116 }
117
118 /// The paragraphs no longer add up to the text: an edit nobody reported
119 /// (a text view with no surface), so everything again.
120 func rebuildIfStale() {
121 let total = (starts.last ?? 0) + (paragraphs.last?.length ?? 0)
122 if paragraphs.isEmpty || total != (storage?.length ?? 0) { rebuild() }
123 }
124
125 /// Everything again (a new text, a new width): nothing is measured.
126 func rebuild() {
127 let string = (storage?.string ?? "") as NSString
128 paragraphs = Self.lengths(in: string, range: NSRange(location: 0, length: string.length)).map { Paragraph(length: $0) }
129 if paragraphs.isEmpty { paragraphs = [Paragraph(length: 0)] }
130 startsCache = nil
131 settleFrom = 0
132 settleThrough = -1
133 changed = IndexSet()
134 laidOutThrough = 0; editedFrom = nil
135 }
136
137 /// Forgets every measurement (the text's width changed), keeping the
138 /// paragraphs and their breaks until they are measured again.
139 func forgetMeasurements() {
140 for index in paragraphs.indices { paragraphs[index].head = nil; paragraphs[index].height = nil; paragraphs[index].tail = nil }
141 settleFrom = 0
142 laidOutThrough = 0; editedFrom = nil
143 }
144
145 /// The storage's characters changed in `edited` (after the edit), by
146 /// `delta`: the paragraphs it touched are split again and measured
147 /// again, with the one after them (its lead depends on its neighbour).
148 func edited(_ edited: NSRange, delta: Int) {
149 guard !regenerating, let storage else { return }
150 let string = storage.string as NSString
151 let oldTotal = (starts.last ?? 0) + (paragraphs.last?.length ?? 0)
152 guard !paragraphs.isEmpty, oldTotal == string.length - delta else { rebuild(); return }
153 // The old paragraphs the edit touched (old coordinates), through
154 // the one its end falls in: deleting a paragraph's end joins it to
155 // the next.
156 let oldStart = edited.location, oldEnd = NSMaxRange(edited) - delta
157 guard let first = paragraph(at: oldStart), let last = paragraph(at: oldEnd) else { rebuild(); return }
158 let from = starts[first]
159 let oldTo = starts[last] + paragraphs[last].length
160 let to = oldTo + delta
161 guard from <= to, to <= string.length else { rebuild(); return }
162 // What is laid out moves with the text; below the edit it waits for
163 // a walk from the top.
164 func moved(_ offset: Int) -> Int { offset <= from ? offset : offset >= oldTo ? offset + delta : from }
165 laidOutThrough = moved(laidOutThrough)
166 editedFrom = min(editedFrom.map(moved) ?? from, from)
167 var replacement = Self.lengths(in: string, range: NSRange(location: from, length: to - from)).map { Paragraph(length: $0) }
168 if replacement.isEmpty { replacement = [Paragraph(length: 0)] }
169 // The old breaks and bottoms, kept where the paragraphs line up, so
170 // settling can tell where the shift stops.
171 for index in replacement.indices where first + index <= last {
172 replacement[index].bottom = paragraphs[first + index].bottom
173 replacement[index].extra = paragraphs[first + index].extra
174 }
175 paragraphs.replaceSubrange(first...last, with: replacement)
176 let after = first + replacement.count
177 startsCache = nil
178 settleFrom = min(settleFrom ?? first, first)
179 settleThrough = max(settleThrough + (replacement.count - (last - first + 1)), after)
180 }
181
182 // MARK: Measuring
183
184 /// The first paragraph not yet measured, if any.
185 var firstUnmeasured: Int? { paragraphs.firstIndex { $0.height == nil || $0.head == nil || $0.tail == nil } }
186
187 /// Measures every paragraph not measured through paragraph `index`, a
188 /// run at a time: an edited paragraph above the screen is measured on
189 /// its own, never with everything between it and the screen.
190 func measureHoles(through index: Int, in layout: NSTextLayoutManager) {
191 var at = firstUnmeasured
192 while let hole = at, hole <= index {
193 var end = hole + 1
194 while end < paragraphs.count, end <= index + 1, paragraphs[end].height == nil || paragraphs[end].head == nil || paragraphs[end].tail == nil { end += 1 }
195 measure(hole..<end, in: layout)
196 at = paragraphs[end...].firstIndex { $0.height == nil || $0.head == nil || $0.tail == nil }
197 if at == hole { break }
198 }
199 }
200
201 /// Lays out paragraphs `range` (and the one before, for the lead) and
202 /// records what it measures. Its measures are its own (fragment-local),
203 /// so a paragraph laid out already and laid out again on its own (an
204 /// edited one) is measured where it is.
205 func measure(_ indices: Range<Int>, in layout: NSTextLayoutManager) {
206 guard let content = layout.textContentManager, !indices.isEmpty, paragraphs.indices.contains(indices.lowerBound) else { return }
207 let lower = max(0, indices.lowerBound - 1)
208 let upper = min(paragraphs.count, indices.upperBound)
209 let first = starts[lower]
210 let last = starts[upper - 1] + paragraphs[upper - 1].length
211 guard let start = content.location(content.documentRange.location, offsetBy: first),
212 content.location(content.documentRange.location, offsetBy: last) != nil else { return }
213 #if DOCS_PROBES
214 let made = DocsProbes.layoutFragments
215 defer { DocsProbes.measureFragments += DocsProbes.layoutFragments - made }
216 #endif
217 // Past what is laid out, from the document's start: TextKit 2 places
218 // a range laid out on its own at an estimate, and only a layout of
219 // everything above it is exact. Within it, the walk below lays out
220 // only what an edit invalidated, after the paragraph before it.
221 ensureLayout(through: last, in: layout)
222 layout.enumerateTextLayoutFragments(from: start, options: [.ensuresLayout]) { fragment in
223 let offset = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location)
224 guard let at = self.paragraph(at: offset), at < upper else { return false }
225 let lines = fragment.textLineFragments
226 guard let top = lines.first?.typographicBounds.minY, let bottom = lines.last?.typographicBounds.maxY else { return true }
227 let space = (fragment as? DocsPageBreakFragment)?.space ?? 0
228 self.paragraphs[at].head = top
229 self.paragraphs[at].height = bottom - top
230 self.paragraphs[at].tail = fragment.layoutFragmentFrame.height - space - bottom
231 return true
232 }
233 if indices.lowerBound < (settleFrom ?? .max) { settleFrom = indices.lowerBound }
234 settleThrough = max(settleThrough, upper - 1)
235 }
236
237 // MARK: Breaks
238
239 /// Places paragraphs from `settleFrom` on: each starts where the one
240 /// before ends plus its lead, or at the next page's top if it would
241 /// cross this page's bottom margin. Stops at a paragraph not measured,
242 /// or once one lands where it was (everything after is unchanged).
243 func settle() {
244 guard let from = settleFrom else { return }
245 var index = from
246 var bottom: CGFloat = index == 0 ? 0 : (paragraphs[index - 1].bottom ?? 0)
247 if index > 0 && paragraphs[index - 1].bottom == nil { settleFrom = 0; index = 0; bottom = 0 }
248 while index < paragraphs.count {
249 guard let head = paragraphs[index].head, let height = paragraphs[index].height,
250 let before = index == 0 ? 0 : paragraphs[index - 1].tail else { settleFrom = index; return }
251 let lead = before + head
252 let natural = bottom + lead
253 var extra: CGFloat = 0
254 if paged {
255 // In the pages' coordinates: 0 is the first page's body top.
256 let y = natural + origin
257 let page = max(0, (y / Self.stride).rounded(.down))
258 let pageTop = page * Self.stride - origin, bodyBottom = pageTop + Self.body
259 if natural > bodyBottom + 0.01 { extra = pageTop + Self.stride - natural }
260 else if natural + height > bodyBottom + 0.01 && natural > pageTop + 0.5 { extra = pageTop + Self.stride - natural }
261 }
262 let newBottom = natural + extra + height
263 let old = paragraphs[index]
264 if abs(old.extra - extra) > 0.01 { paragraphs[index].extra = extra; changed.insert(index) }
265 paragraphs[index].bottom = newBottom
266 if index > from, index > settleThrough, abs(old.extra - extra) <= 0.01, let oldBottom = old.bottom, abs(oldBottom - newBottom) <= 0.01 {
267 settleFrom = nil
268 settleThrough = -1
269 return
270 }
271 bottom = newBottom
272 index += 1
273 }
274 settleFrom = nil
275 settleThrough = -1
276 }
277
278 /// What a screen starting at `start` needs thrown away and laid out
279 /// again from the top: past what is laid out (a jump), TextKit 2 placed
280 /// it at an estimate, and keeps what it placed so as laid out. Nil when
281 /// it is laid out.
282 func relayout(forScreenAt start: Int) -> Range<Int>? {
283 start > laidOutThrough ? laidOutThrough..<Int.max : nil
284 }
285
286 /// Lays out from the document's top through character `offset`, when
287 /// that is past what is laid out or below an edit. TextKit
288 /// 2 places a range laid out on its own at an estimate (and keeps it
289 /// so): only a layout from the top is exact. What is laid out already
290 /// costs only the walk, which stacks it again. False when there was
291 /// nothing to do.
292 @discardableResult func ensureLayout(through offset: Int, in layout: NSTextLayoutManager) -> Bool {
293 guard offset > laidOutThrough || (editedFrom.map { $0 < offset } ?? false), let content = layout.textContentManager,
294 let end = content.location(content.documentRange.location, offsetBy: offset) ?? Optional(content.documentRange.endLocation),
295 let range = NSTextRange(location: content.documentRange.location, end: end) else { return false }
296 #if DOCS_PROBES
297 if offset <= laidOutThrough { DocsProbes.restackWalks += 1 }
298 #endif
299 layout.ensureLayout(for: range)
300 // Restacked through `offset`; what is laid out below it is not.
301 if let edited = editedFrom, edited < offset { editedFrom = offset < laidOutThrough ? offset : nil }
302 laidOutThrough = max(laidOutThrough, offset)
303 return true
304 }
305
306 /// TextKit 2 builds again the paragraphs before those whose extra
307 /// changed. Nothing is laid out here: whoever draws or measures lays out
308 /// from the top through what it needs (`ensureLayout(through:in:)`),
309 /// which places everything after a rebuilt paragraph from its new size.
310 /// Only those through paragraph `limit` when given (a key: what is
311 /// below the screen waits for idle, so a break cascading down the
312 /// document costs what is above the screen's end).
313 func applyChanges(through limit: Int = .max) {
314 guard !changed.isEmpty, let storage else { return }
315 let indices = limit == .max ? changed : changed.filteredIndexSet { $0 <= limit }
316 guard !indices.isEmpty else { return }
317 changed.subtract(indices)
318 #if DOCS_PROBES
319 DocsProbes.pageBreakChanges += indices.count
320 #endif
321 // The paragraphs before them get new fragments
322 // (`fragment(for:element:)`), with the new space below. TextKit 2
323 // makes a new fragment only for a new element, and builds one for a
324 // paragraph whose attributes were edited: an edit of nothing does it
325 // (invalidating the layout keeps the old fragment).
326 // What follows them waits for a walk from the top.
327 if let first = indices.first(where: { $0 > 0 && $0 < paragraphs.count }) { editedFrom = min(editedFrom ?? .max, starts[first - 1]) }
328 regenerating = true
329 storage.beginEditing()
330 for index in indices where index > 0 && index < paragraphs.count {
331 let span = range(of: index - 1)
332 if span.length > 0 { storage.edited(.editedAttributes, range: span, changeInLength: 0) }
333 }
334 storage.endEditing()
335 regenerating = false
336 }
337
338 var hasChanges: Bool { !changed.isEmpty }
339 func hasChanges(through limit: Int) -> Bool { changed.contains { $0 <= limit } }
340 /// Every measured paragraph is placed again (the pages' origin moved).
341 func restartSettling() { settleFrom = 0; settleThrough = paragraphs.count }
342
343 /// Paged off: every extra goes.
344 func clearBreaks() {
345 for index in paragraphs.indices where paragraphs[index].extra != 0 { paragraphs[index].extra = 0; changed.insert(index) }
346 settleFrom = 0
347 settleThrough = paragraphs.count
348 }
349
350 // MARK: Fragments
351
352 /// The layout fragment for the paragraph at `location`: one that is
353 /// taller by the next paragraph's break space, when the next starts a page.
354 /// (A fragment's space cannot change where it is: TextKit 2 stacks what
355 /// follows a fragment again only after laying it out again, so a break
356 /// that moves builds its fragment again.)
357 func fragment(for location: Int, element: NSTextElement) -> NSTextLayoutFragment {
358 guard paged, let index = paragraph(at: location), starts[index] == location, index + 1 < paragraphs.count,
359 paragraphs[index + 1].extra > 0, let range = element.elementRange else {
360 return NSTextLayoutFragment(textElement: element, range: element.elementRange)
361 }
362 #if DOCS_PROBES
363 DocsProbes.breakParagraphs += 1
364 #endif
365 let fragment = DocsPageBreakFragment(textElement: element, range: range)
366 fragment.space = paragraphs[index + 1].extra
367 return fragment
368 }
369}
370
371/// The paragraph before one that starts a page: the break's space below
372/// its lines, which TextKit 2 stacks the next paragraph after. Its own lines
373/// do not move.
374final class DocsPageBreakFragment: NSTextLayoutFragment {
375 var space: CGFloat = 0
376 override var layoutFragmentFrame: CGRect {
377 var frame = super.layoutFragmentFrame
378 frame.size.height += space
379 return frame
380 }
381}
382#endif
383