#if os(iOS) import UIKit /// The iPhone's page breaks on TextKit 2 (S3; spec 2026-11-22 §7 "iPhone /// layout", S1b ruling #173). /// /// TextKit 1 paginated by line in the text container's `lineFragmentRect`. /// UIKit runs any view whose container does that on TextKit 1 (a container /// that is not a plain rectangle switches it back), and TextKit 2's own /// exclusion paths lay the whole document out on open and on every key /// (1.27 s and 0.53 s at 200 pages). So the breaks are by paragraph, as the /// Mac's are by block: a paragraph that would cross a page's bottom margin /// starts on the next page instead. The space before it is display-only: the /// layout fragment of the paragraph before it is that much taller at the /// bottom (`DocsPageBreakFragment`), so TextKit 2 stacks the next one lower, /// and the text storage, which the surface reconciles against the replica, /// never holds it. (Neither the content storage's delegate, which /// `UITextView` does not ask about list items, nor a fragment's `topMargin`, /// which stacking ignores, can do it.) /// /// Positions come from each paragraph's own measurements, cached: the space /// above its first line and below its last inside its layout fragment, and /// its lines' span. They come from a layout of the paragraph alone, never /// from where TextKit 2 placed it, and none depends on the breaks. The breaks are then arithmetic over the cache, from the /// first paragraph that changed until a paragraph lands where it was. /// Measuring is TextKit 2 layout, so it is done a few paragraphs at a time: /// the ones on screen as they are drawn, the rest in idle chunks, and, on a /// jump past what is measured, everything up to the target at once (spec §7 /// "Fallback": once per jump, never per key). /// /// A paragraph taller than a page's body cannot fit one: it starts at a page /// top and runs over the gap (rare; TextKit 2 offers no line-level break /// that keeps layout lazy). @MainActor final class DocsPhonePages: NSObject { struct Paragraph: Equatable { var length: Int /// Inside its layout fragment: the space above its first line, its /// lines' span, and the space below its last line (less any break /// space it carries). TextKit 2 stacks fragments frame to frame, so /// a paragraph's lead is the one before's `tail` plus its `head`: /// all local to the fragments, never their positions, which TextKit /// 2 leaves stale after a paragraph above changes size. var head: CGFloat? var height: CGFloat? var tail: CGFloat? /// The space added before it to start it on a new page. var extra: CGFloat = 0 /// Its last line's bottom, as the breaks place it. var bottom: CGFloat? } private(set) var paragraphs: [Paragraph] = [] private var startsCache: [Int]? var paged = false /// Where the text container's top sits below the first page's body top /// (the first block's own top margin, `docsFirstMargin`). var origin: CGFloat = 0 /// The first paragraph whose position may have changed, nil when every /// measured paragraph is placed. private(set) var settleFrom: Int? /// The last paragraph measured (or edited) since it was placed: placing /// may stop once a paragraph lands where it was only past this one, as /// the ones up to it were never placed from their new measurements. private var settleThrough = -1 /// Paragraphs whose extra changed and whose element TextKit 2 must build again. private var changed = IndexSet() /// True while the pages ask TextKit 2 to build paragraphs again (an /// attribute-only edit of nothing): those edits are not text changes. private(set) var regenerating = false /// TextKit 2's layout is contiguous from the top through this character. private(set) var laidOutThrough = 0 /// The first character below which TextKit 2's laid-out fragments may /// sit away from where they belong, since an edit or a rebuilt break. /// TextKit 2 does not move the fragments below one that changed (and /// until it does, places a screen there at an estimate); it stacks them /// again on a walk from the top. A walk over what is laid out lays out /// no line again (an edit's own paragraph aside), so it costs /// milliseconds at 200 pages, where throwing the layout below an edit /// away and laying it out again cost half a second (Fable on #180). private(set) var editedFrom: Int? weak var storage: NSTextStorage? /// Chunk size for the idle measurement. static let chunk = 40 static let stride = DocsPageGeometry.paperHeight + DocsPageGeometry.gap static let body = DocsPageGeometry.paperHeight - DocsPageGeometry.verticalMargin * 2 // MARK: Paragraphs var starts: [Int] { if let startsCache { return startsCache } var at = 0, made: [Int] = [] made.reserveCapacity(paragraphs.count) for paragraph in paragraphs { made.append(at); at += paragraph.length } startsCache = made return made } /// The paragraph holding character `location` (the last for the end). func paragraph(at location: Int) -> Int? { guard !paragraphs.isEmpty else { return nil } let starts = self.starts var low = 0, high = starts.count - 1 while low < high { let mid = (low + high + 1) / 2 if starts[mid] <= location { low = mid } else { high = mid - 1 } } return low } func range(of index: Int) -> NSRange { NSRange(location: starts[index], length: paragraphs[index].length) } static func lengths(in string: NSString, range: NSRange) -> [Int] { var lengths: [Int] = [] string.enumerateSubstrings(in: range, options: [.byParagraphs, .substringNotRequired]) { _, _, enclosing, _ in lengths.append(enclosing.length) } return lengths } /// The paragraphs no longer add up to the text: an edit nobody reported /// (a text view with no surface), so everything again. func rebuildIfStale() { let total = (starts.last ?? 0) + (paragraphs.last?.length ?? 0) if paragraphs.isEmpty || total != (storage?.length ?? 0) { rebuild() } } /// Everything again (a new text, a new width): nothing is measured. func rebuild() { let string = (storage?.string ?? "") as NSString paragraphs = Self.lengths(in: string, range: NSRange(location: 0, length: string.length)).map { Paragraph(length: $0) } if paragraphs.isEmpty { paragraphs = [Paragraph(length: 0)] } startsCache = nil settleFrom = 0 settleThrough = -1 changed = IndexSet() laidOutThrough = 0; editedFrom = nil } /// Forgets every measurement (the text's width changed), keeping the /// paragraphs and their breaks until they are measured again. func forgetMeasurements() { for index in paragraphs.indices { paragraphs[index].head = nil; paragraphs[index].height = nil; paragraphs[index].tail = nil } settleFrom = 0 laidOutThrough = 0; editedFrom = nil } /// The storage's characters changed in `edited` (after the edit), by /// `delta`: the paragraphs it touched are split again and measured /// again, with the one after them (its lead depends on its neighbour). func edited(_ edited: NSRange, delta: Int) { guard !regenerating, let storage else { return } let string = storage.string as NSString let oldTotal = (starts.last ?? 0) + (paragraphs.last?.length ?? 0) guard !paragraphs.isEmpty, oldTotal == string.length - delta else { rebuild(); return } // The old paragraphs the edit touched (old coordinates), through // the one its end falls in: deleting a paragraph's end joins it to // the next. let oldStart = edited.location, oldEnd = NSMaxRange(edited) - delta guard let first = paragraph(at: oldStart), let last = paragraph(at: oldEnd) else { rebuild(); return } let from = starts[first] let oldTo = starts[last] + paragraphs[last].length let to = oldTo + delta guard from <= to, to <= string.length else { rebuild(); return } // What is laid out moves with the text; below the edit it waits for // a walk from the top. func moved(_ offset: Int) -> Int { offset <= from ? offset : offset >= oldTo ? offset + delta : from } laidOutThrough = moved(laidOutThrough) editedFrom = min(editedFrom.map(moved) ?? from, from) var replacement = Self.lengths(in: string, range: NSRange(location: from, length: to - from)).map { Paragraph(length: $0) } if replacement.isEmpty { replacement = [Paragraph(length: 0)] } // The old breaks and bottoms, kept where the paragraphs line up, so // settling can tell where the shift stops. for index in replacement.indices where first + index <= last { replacement[index].bottom = paragraphs[first + index].bottom replacement[index].extra = paragraphs[first + index].extra } paragraphs.replaceSubrange(first...last, with: replacement) let after = first + replacement.count startsCache = nil settleFrom = min(settleFrom ?? first, first) settleThrough = max(settleThrough + (replacement.count - (last - first + 1)), after) } // MARK: Measuring /// The first paragraph not yet measured, if any. var firstUnmeasured: Int? { paragraphs.firstIndex { $0.height == nil || $0.head == nil || $0.tail == nil } } /// Measures every paragraph not measured through paragraph `index`, a /// run at a time: an edited paragraph above the screen is measured on /// its own, never with everything between it and the screen. func measureHoles(through index: Int, in layout: NSTextLayoutManager) { var at = firstUnmeasured while let hole = at, hole <= index { var end = hole + 1 while end < paragraphs.count, end <= index + 1, paragraphs[end].height == nil || paragraphs[end].head == nil || paragraphs[end].tail == nil { end += 1 } measure(hole.., in layout: NSTextLayoutManager) { guard let content = layout.textContentManager, !indices.isEmpty, paragraphs.indices.contains(indices.lowerBound) else { return } let lower = max(0, indices.lowerBound - 1) let upper = min(paragraphs.count, indices.upperBound) let first = starts[lower] let last = starts[upper - 1] + paragraphs[upper - 1].length guard let start = content.location(content.documentRange.location, offsetBy: first), content.location(content.documentRange.location, offsetBy: last) != nil else { return } #if DOCS_PROBES let made = DocsProbes.layoutFragments defer { DocsProbes.measureFragments += DocsProbes.layoutFragments - made } #endif // Past what is laid out, from the document's start: TextKit 2 places // a range laid out on its own at an estimate, and only a layout of // everything above it is exact. Within it, the walk below lays out // only what an edit invalidated, after the paragraph before it. ensureLayout(through: last, in: layout) layout.enumerateTextLayoutFragments(from: start, options: [.ensuresLayout]) { fragment in let offset = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location) guard let at = self.paragraph(at: offset), at < upper else { return false } let lines = fragment.textLineFragments guard let top = lines.first?.typographicBounds.minY, let bottom = lines.last?.typographicBounds.maxY else { return true } let space = (fragment as? DocsPageBreakFragment)?.space ?? 0 self.paragraphs[at].head = top self.paragraphs[at].height = bottom - top self.paragraphs[at].tail = fragment.layoutFragmentFrame.height - space - bottom return true } if indices.lowerBound < (settleFrom ?? .max) { settleFrom = indices.lowerBound } settleThrough = max(settleThrough, upper - 1) } // MARK: Breaks /// Places paragraphs from `settleFrom` on: each starts where the one /// before ends plus its lead, or at the next page's top if it would /// cross this page's bottom margin. Stops at a paragraph not measured, /// or once one lands where it was (everything after is unchanged). func settle() { guard let from = settleFrom else { return } var index = from var bottom: CGFloat = index == 0 ? 0 : (paragraphs[index - 1].bottom ?? 0) if index > 0 && paragraphs[index - 1].bottom == nil { settleFrom = 0; index = 0; bottom = 0 } while index < paragraphs.count { guard let head = paragraphs[index].head, let height = paragraphs[index].height, let before = index == 0 ? 0 : paragraphs[index - 1].tail else { settleFrom = index; return } let lead = before + head let natural = bottom + lead var extra: CGFloat = 0 if paged { // In the pages' coordinates: 0 is the first page's body top. let y = natural + origin let page = max(0, (y / Self.stride).rounded(.down)) let pageTop = page * Self.stride - origin, bodyBottom = pageTop + Self.body if natural > bodyBottom + 0.01 { extra = pageTop + Self.stride - natural } else if natural + height > bodyBottom + 0.01 && natural > pageTop + 0.5 { extra = pageTop + Self.stride - natural } } let newBottom = natural + extra + height let old = paragraphs[index] if abs(old.extra - extra) > 0.01 { paragraphs[index].extra = extra; changed.insert(index) } paragraphs[index].bottom = newBottom if index > from, index > settleThrough, abs(old.extra - extra) <= 0.01, let oldBottom = old.bottom, abs(oldBottom - newBottom) <= 0.01 { settleFrom = nil settleThrough = -1 return } bottom = newBottom index += 1 } settleFrom = nil settleThrough = -1 } /// What a screen starting at `start` needs thrown away and laid out /// again from the top: past what is laid out (a jump), TextKit 2 placed /// it at an estimate, and keeps what it placed so as laid out. Nil when /// it is laid out. func relayout(forScreenAt start: Int) -> Range? { start > laidOutThrough ? laidOutThrough.. Bool { guard offset > laidOutThrough || (editedFrom.map { $0 < offset } ?? false), let content = layout.textContentManager, let end = content.location(content.documentRange.location, offsetBy: offset) ?? Optional(content.documentRange.endLocation), let range = NSTextRange(location: content.documentRange.location, end: end) else { return false } #if DOCS_PROBES if offset <= laidOutThrough { DocsProbes.restackWalks += 1 } #endif layout.ensureLayout(for: range) // Restacked through `offset`; what is laid out below it is not. if let edited = editedFrom, edited < offset { editedFrom = offset < laidOutThrough ? offset : nil } laidOutThrough = max(laidOutThrough, offset) return true } /// TextKit 2 builds again the paragraphs before those whose extra /// changed. Nothing is laid out here: whoever draws or measures lays out /// from the top through what it needs (`ensureLayout(through:in:)`), /// which places everything after a rebuilt paragraph from its new size. /// Only those through paragraph `limit` when given (a key: what is /// below the screen waits for idle, so a break cascading down the /// document costs what is above the screen's end). func applyChanges(through limit: Int = .max) { guard !changed.isEmpty, let storage else { return } let indices = limit == .max ? changed : changed.filteredIndexSet { $0 <= limit } guard !indices.isEmpty else { return } changed.subtract(indices) #if DOCS_PROBES DocsProbes.pageBreakChanges += indices.count #endif // The paragraphs before them get new fragments // (`fragment(for:element:)`), with the new space below. TextKit 2 // makes a new fragment only for a new element, and builds one for a // paragraph whose attributes were edited: an edit of nothing does it // (invalidating the layout keeps the old fragment). // What follows them waits for a walk from the top. if let first = indices.first(where: { $0 > 0 && $0 < paragraphs.count }) { editedFrom = min(editedFrom ?? .max, starts[first - 1]) } regenerating = true storage.beginEditing() for index in indices where index > 0 && index < paragraphs.count { let span = range(of: index - 1) if span.length > 0 { storage.edited(.editedAttributes, range: span, changeInLength: 0) } } storage.endEditing() regenerating = false } var hasChanges: Bool { !changed.isEmpty } func hasChanges(through limit: Int) -> Bool { changed.contains { $0 <= limit } } /// Every measured paragraph is placed again (the pages' origin moved). func restartSettling() { settleFrom = 0; settleThrough = paragraphs.count } /// Paged off: every extra goes. func clearBreaks() { for index in paragraphs.indices where paragraphs[index].extra != 0 { paragraphs[index].extra = 0; changed.insert(index) } settleFrom = 0 settleThrough = paragraphs.count } // MARK: Fragments /// The layout fragment for the paragraph at `location`: one that is /// taller by the next paragraph's break space, when the next starts a page. /// (A fragment's space cannot change where it is: TextKit 2 stacks what /// follows a fragment again only after laying it out again, so a break /// that moves builds its fragment again.) func fragment(for location: Int, element: NSTextElement) -> NSTextLayoutFragment { guard paged, let index = paragraph(at: location), starts[index] == location, index + 1 < paragraphs.count, paragraphs[index + 1].extra > 0, let range = element.elementRange else { return NSTextLayoutFragment(textElement: element, range: element.elementRange) } #if DOCS_PROBES DocsProbes.breakParagraphs += 1 #endif let fragment = DocsPageBreakFragment(textElement: element, range: range) fragment.space = paragraphs[index + 1].extra return fragment } } /// The paragraph before one that starts a page: the break's space below /// its lines, which TextKit 2 stacks the next paragraph after. Its own lines /// do not move. final class DocsPageBreakFragment: NSTextLayoutFragment { var space: CGFloat = 0 override var layoutFragmentFrame: CGRect { var frame = super.layoutFragmentFrame frame.size.height += space return frame } } #endif