| 1 | import Foundation |
| 2 | #if os(macOS) |
| 3 | import AppKit |
| 4 | |
| 5 | @MainActor class DocsPagedTextView: NSTextView { |
| 6 | var paged = false { |
| 7 | didSet { |
| 8 | guard oldValue != paged else { return } |
| 9 | pagination.paged = paged |
| 10 | needsLayout = true; needsDisplay = true |
| 11 | } |
| 12 | } |
| 13 | private var updatingGeometry = false |
| 14 | /// The page plan (spec §7, "Incremental pagination"): a measurement |
| 15 | /// stack on this view's own storage, per-block caches, the break table |
| 16 | /// the container reads, and the frame height. |
| 17 | let pagination: DocsPagination |
| 18 | override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) { |
| 19 | let storage = NSTextStorage() |
| 20 | let manager = DocsLayoutManager() |
| 21 | manager.usesFontLeading = false |
| 22 | // Laid out where it is shown, never all of it (§7 items 6 and 8): |
| 23 | // contiguously, to the visible bottom (§7 "Fallback"). TextKit does |
| 24 | // not lay out a container that is not a simple rectangle |
| 25 | // non-contiguously, so the Mac takes the fallback; background layout |
| 26 | // would lay out the rest after every edit. |
| 27 | manager.allowsNonContiguousLayout = false |
| 28 | manager.backgroundLayoutEnabled = false |
| 29 | let size = CGSize(width: DocsDeskLayout.paperWidth, height: 1_000_000) |
| 30 | let pages = DocsPageTextContainer(size: size) |
| 31 | pages.lineFragmentPadding = 0 |
| 32 | let geometry = DocsPageGeometry(viewportWidth: DocsDeskLayout.paperWidth, paged: false) |
| 33 | pages.geometry = geometry |
| 34 | storage.addLayoutManager(manager) |
| 35 | manager.addTextContainer(pages) |
| 36 | pagination = DocsPagination(storage: storage, live: manager, geometry: geometry) |
| 37 | super.init(frame: frameRect, textContainer: pages) |
| 38 | pages.tops = pagination |
| 39 | pagination.canDefer = { [weak self] in self?.window != nil } |
| 40 | pagination.changed = { [weak self] height, redraw in self?.paginationChanged(height: height, redraw: redraw) } |
| 41 | pagination.visibleBottom = { [weak self] in self?.visibleRect.maxY ?? .greatestFiniteMagnitude } |
| 42 | textContainerInset = .zero |
| 43 | // This view owns its paginated height; NSTextView auto-sizing uses a |
| 44 | // different used rect and briefly clips the current line during input. |
| 45 | isVerticallyResizable = false |
| 46 | isHorizontallyResizable = false |
| 47 | drawsBackground = true |
| 48 | textColor = .black |
| 49 | } |
| 50 | override convenience init(frame: NSRect) { self.init(frame: frame, textContainer: nil) } |
| 51 | required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } |
| 52 | // Page margins are already part of DocsPageTextContainer's line geometry. |
| 53 | // NSTextView's inferred origin moves during incremental layout and can put |
| 54 | // its native insertion indicator at a different origin from the glyphs. |
| 55 | override var textContainerOrigin: NSPoint { .zero } |
| 56 | /// The live layout manager saw an edit (DocsLayoutManager): the units |
| 57 | /// shift now; the measuring waits for this view's next layout, before |
| 58 | /// anything is drawn. |
| 59 | func storageEdited(edited: NSRange, delta: Int) { |
| 60 | pagination.storageEdited(edited: edited, delta: delta) |
| 61 | needsLayout = true |
| 62 | } |
| 63 | override func didChangeText() { |
| 64 | // Size the document before AppKit scrolls the newly edited caret. |
| 65 | needsLayout = true |
| 66 | layoutSubtreeIfNeeded() |
| 67 | super.didChangeText() |
| 68 | } |
| 69 | /// A fixed paper band: the desk (DocsDeskView) places and centres it, so |
| 70 | /// a width change or the inspector never changes the text's geometry. |
| 71 | private var viewportWidth: CGFloat { DocsDeskLayout.paperWidth } |
| 72 | /// The plan, up to date to the visible bottom (and `character`). |
| 73 | func updatePagination(through character: Int? = nil) { |
| 74 | guard let pages = textContainer as? DocsPageTextContainer else { return } |
| 75 | let width = viewportWidth |
| 76 | let size = CGSize(width: width, height: 1_000_000) |
| 77 | if pages.size != size { pages.size = size } |
| 78 | pages.geometry = DocsPageGeometry(viewportWidth: width, paged: false) |
| 79 | pagination.setGeometry(pages.geometry) |
| 80 | pagination.update(visibleBottom: visibleRect.maxY, through: character) |
| 81 | } |
| 82 | /// A pass moved the height (the frame follows at the next layout) or |
| 83 | /// lines on screen (redrawn). |
| 84 | private func paginationChanged(height: Bool, redraw: Bool) { |
| 85 | if height && !updatingGeometry { needsLayout = true } |
| 86 | guard redraw else { return } |
| 87 | #if DOCS_PROBES |
| 88 | DocsProbes.paginationRedraws += 1 |
| 89 | #endif |
| 90 | // Not plain setNeedsDisplay: NSTextView's lays the rect out at once. |
| 91 | setNeedsDisplay(visibleRect, avoidAdditionalLayout: true) |
| 92 | } |
| 93 | override func layout() { |
| 94 | guard !updatingGeometry, let pages = textContainer as? DocsPageTextContainer else { return } |
| 95 | #if DOCS_PROBES |
| 96 | let probeStart = DocsProbes.now() |
| 97 | defer { DocsProbes.textLayouts += 1; DocsProbes.textLayoutMs += DocsProbes.ms(since: probeStart) } |
| 98 | #endif |
| 99 | updatingGeometry = true |
| 100 | defer { updatingGeometry = false } |
| 101 | // AppKit must only lay out the caret after final page coordinates exist. |
| 102 | updatePagination() |
| 103 | super.layout() |
| 104 | // The height from the caches (§7 item 7), never from laying out the |
| 105 | // last glyph; the caret's line is laid out by AppKit as it draws it. |
| 106 | let width = viewportWidth |
| 107 | let height = pages.geometry.documentHeight(usedHeight: pagination.bottom) |
| 108 | if abs(frame.width - width) > 0.5 || abs(frame.height - height) > 0.5 { |
| 109 | setFrameSize(CGSize(width: width, height: height)) |
| 110 | } |
| 111 | } |
| 112 | /// Scrolled or jumped past the measured frontier: measure to what is |
| 113 | /// about to be drawn first (§7 item 3, "a jump past the frontier"). |
| 114 | override func viewWillDraw() { |
| 115 | if !updatingGeometry { |
| 116 | updatingGeometry = true |
| 117 | pagination.update(visibleBottom: visibleRect.maxY) |
| 118 | updatingGeometry = false |
| 119 | let height = (textContainer as? DocsPageTextContainer)?.geometry.documentHeight(usedHeight: pagination.bottom) ?? frame.height |
| 120 | if abs(frame.height - height) > 0.5 { setFrameSize(CGSize(width: frame.width, height: height)) } |
| 121 | } |
| 122 | super.viewWillDraw() |
| 123 | } |
| 124 | override func scrollRangeToVisible(_ range: NSRange) { |
| 125 | if !updatingGeometry, range.location != NSNotFound { |
| 126 | updatingGeometry = true |
| 127 | pagination.update(visibleBottom: visibleRect.maxY, through: NSMaxRange(range)) |
| 128 | updatingGeometry = false |
| 129 | let height = (textContainer as? DocsPageTextContainer)?.geometry.documentHeight(usedHeight: pagination.bottom) ?? frame.height |
| 130 | if abs(frame.height - height) > 0.5 { setFrameSize(CGSize(width: frame.width, height: height)) } |
| 131 | } |
| 132 | super.scrollRangeToVisible(range) |
| 133 | } |
| 134 | #if DOCS_PROBES |
| 135 | override func draw(_ dirtyRect: NSRect) { |
| 136 | let probeStart = DocsProbes.now() |
| 137 | defer { DocsProbes.draws += 1; DocsProbes.drawMs += DocsProbes.ms(since: probeStart) } |
| 138 | super.draw(dirtyRect) |
| 139 | } |
| 140 | #endif |
| 141 | override func drawBackground(in dirtyRect: NSRect) { |
| 142 | NSGraphicsContext.saveGraphicsState() |
| 143 | defer { NSGraphicsContext.restoreGraphicsState() } |
| 144 | dirtyRect.clip() |
| 145 | NSColor.windowBackgroundColor.setFill() |
| 146 | dirtyRect.fill() |
| 147 | if let pages = textContainer as? DocsPageTextContainer { |
| 148 | let geometry = pages.geometry |
| 149 | NSColor.white.setFill() |
| 150 | CGRect(x: geometry.paperX, y: 0, width: geometry.paperWidth, height: bounds.height).fill() |
| 151 | if paged { |
| 152 | // NSTextView asks for its whole bounds and clips to what it |
| 153 | // draws: only the separators in the clip are drawn (each label |
| 154 | // is a string drawing; a 200-page document has 200 of them). |
| 155 | let clip = NSGraphicsContext.current?.cgContext.boundingBoxOfClipPath ?? dirtyRect |
| 156 | let shown = dirtyRect.intersection(clip) |
| 157 | let separators = pagination.separators |
| 158 | var low = 0, high = separators.count |
| 159 | while low < high { |
| 160 | let middle = (low + high) / 2 |
| 161 | if separators[middle] + 18 < shown.minY { low = middle + 1 } else { high = middle } |
| 162 | } |
| 163 | for index in low..<separators.count { |
| 164 | let y = separators[index] |
| 165 | guard y <= shown.maxY else { break } |
| 166 | NSColor.windowBackgroundColor.setFill() |
| 167 | CGRect(x: geometry.paperX, y: y, width: geometry.paperWidth, height: 18).fill() |
| 168 | let label = String(localized: "docs.editor.page.number", bundle: DocsResources.bundle) |
| 169 | .replacingOccurrences(of: "{n}", with: String(index + 2)) |
| 170 | (label as NSString).draw(at: CGPoint(x: geometry.paperX + geometry.paperWidth - 80, y: y + 3), |
| 171 | withAttributes: [.font: NSFont.systemFont(ofSize: 10), .foregroundColor: NSColor.darkGray]) |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | #else |
| 178 | import UIKit |
| 179 | |
| 180 | /// The iPhone's text view, on TextKit 2 (S3; spec 2026-11-22 §7 "iPhone |
| 181 | /// layout" and the S1b ruling on #173). TextKit 1 laid the whole document |
| 182 | /// out at open and again inside any edit that changed a line count (1.27 s |
| 183 | /// and 0.48 s at 200 pages); TextKit 2 lays out what is on screen, and an |
| 184 | /// edit lays out its own paragraph again. |
| 185 | /// |
| 186 | /// The container is a plain rectangle, as wide as the page's text: UIKit |
| 187 | /// runs a text view whose container overrides `lineFragmentRect` on |
| 188 | /// TextKit 1, so the page breaks are `DocsPhonePages`'s, per paragraph, made |
| 189 | /// by the layout fragments this view's layout delegate hands TextKit 2. |
| 190 | /// The paper is views behind the text, only the pages on screen. |
| 191 | /// |
| 192 | /// TextKit 1 also drew every line 72 pt above where its container placed it |
| 193 | /// (UIKit took the first line's origin as the text's top, dropping the top |
| 194 | /// margin the container added), so no iPhone page had a top margin and the |
| 195 | /// caret probe read 72.7 pt above its line (#173). The insets here carry |
| 196 | /// the margin instead. |
| 197 | /// |
| 198 | /// Nothing here may touch `layoutManager`: asking for it switches the view |
| 199 | /// back to TextKit 1 for good. |
| 200 | @MainActor class DocsPagedTextView: UITextView, @preconcurrency NSTextLayoutManagerDelegate { |
| 201 | var paged = false { didSet { if oldValue != paged { pagedChanged() } } } |
| 202 | /// The height above the first page: the iPhone's large title, hosted |
| 203 | /// in this scroll view (S3, spec §3), or nothing. |
| 204 | var headerHeight: CGFloat = 0 { didSet { if abs(oldValue - headerHeight) > 0.25 { applyInsets() } } } |
| 205 | /// What covers the bottom of the view (the Format sheet): the text can |
| 206 | /// scroll clear of it. |
| 207 | var bottomObstruction: CGFloat = 0 { didSet { if abs(oldValue - bottomObstruction) > 0.25 { setNeedsLayout() } } } |
| 208 | private(set) var geometry = DocsPageGeometry(viewportWidth: 402, paged: false) |
| 209 | let pages = DocsPhonePages() |
| 210 | private var firstMargin: CGFloat = 0 |
| 211 | private var pageViews: [Int: DocsPageView] = [:] |
| 212 | private var paginating = false |
| 213 | private var idle: Task<Void, Never>? |
| 214 | |
| 215 | /// The iPhone's large title, hosted above the text (S3); nil on iPad |
| 216 | /// and in tests. |
| 217 | var header: DocsPhoneHeaderHost? { |
| 218 | didSet { |
| 219 | oldValue?.view.removeFromSuperview() |
| 220 | guard let header else { headerHeight = 0; return } |
| 221 | addSubview(header.view) |
| 222 | header.heightChanged = { [weak self] height in |
| 223 | guard let self, abs(height - self.headerHeight) > 0.5 else { return } |
| 224 | self.headerHeight = height |
| 225 | } |
| 226 | headerHeight = header.height(forWidth: max(160, bounds.width)) |
| 227 | // A Dynamic Type change measures the title again (spec §9). |
| 228 | if headerTraits == nil { |
| 229 | headerTraits = registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) { (view: DocsPagedTextView, _: UITraitCollection) in |
| 230 | guard let header = view.header else { return } |
| 231 | view.headerHeight = header.height(forWidth: max(160, view.bounds.width)) |
| 232 | view.setNeedsLayout() |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | private var headerTraits: (any UITraitChangeRegistration)? |
| 238 | /// The keyboard bar (writers only, S3): shown above the keyboard while |
| 239 | /// the text view has it, and not while the Format sheet is open. |
| 240 | var keyboardBar: UIView? { didSet { updateAccessory() } } |
| 241 | var showsKeyboardBar = false { didSet { if oldValue != showsKeyboardBar { updateAccessory() } } } |
| 242 | /// The Format sheet is open: the keyboard goes but the text view keeps |
| 243 | /// first responder, so the selection stays visible above the sheet |
| 244 | /// (spec §3, "The selection stays visible"). |
| 245 | var keyboardSuppressed = false { |
| 246 | didSet { |
| 247 | guard oldValue != keyboardSuppressed else { return } |
| 248 | inputView = keyboardSuppressed ? UIView(frame: .zero) : nil |
| 249 | updateAccessory() |
| 250 | if isFirstResponder { reloadInputViews() } |
| 251 | } |
| 252 | } |
| 253 | private func updateAccessory() { |
| 254 | let wanted = showsKeyboardBar && !keyboardSuppressed ? keyboardBar : nil |
| 255 | guard inputAccessoryView !== wanted else { return } |
| 256 | inputAccessoryView = wanted |
| 257 | if isFirstResponder { reloadInputViews() } |
| 258 | } |
| 259 | |
| 260 | override func becomeFirstResponder() -> Bool { |
| 261 | let became = super.becomeFirstResponder() |
| 262 | if became { reportEditing(true) } |
| 263 | return became |
| 264 | } |
| 265 | override func resignFirstResponder() -> Bool { |
| 266 | let resigned = super.resignFirstResponder() |
| 267 | if resigned { reportEditing(false) } |
| 268 | releaseHeldBreaks() |
| 269 | return resigned |
| 270 | } |
| 271 | /// Told on the next turn: a responder change can happen inside a |
| 272 | /// SwiftUI update, where observed state must not change. |
| 273 | private func reportEditing(_ editing: Bool) { |
| 274 | guard let state = header?.state else { return } |
| 275 | DispatchQueue.main.async { if state.editing != editing { state.editing = editing } } |
| 276 | } |
| 277 | private func reportScroll() { |
| 278 | guard let state = header?.state else { return } |
| 279 | let past = contentOffset.y + adjustedContentInset.top > max(8, headerHeight - 8) |
| 280 | guard past != state.scrolledPast else { return } |
| 281 | DispatchQueue.main.async { if state.scrolledPast != past { state.scrolledPast = past } } |
| 282 | } |
| 283 | |
| 284 | init(frame: CGRect = .zero) { |
| 285 | let container = NSTextContainer(size: CGSize(width: max(160, frame.width), height: 0)) |
| 286 | container.lineFragmentPadding = 0 |
| 287 | container.widthTracksTextView = true |
| 288 | let layout = NSTextLayoutManager() |
| 289 | layout.textContainer = container |
| 290 | let content = NSTextContentStorage() |
| 291 | content.addTextLayoutManager(layout) |
| 292 | content.primaryTextLayoutManager = layout |
| 293 | super.init(frame: frame, textContainer: container) |
| 294 | pages.storage = textStorage |
| 295 | layout.delegate = self |
| 296 | backgroundColor = .systemGroupedBackground |
| 297 | textColor = .black |
| 298 | alwaysBounceVertical = true |
| 299 | applyInsets() |
| 300 | } |
| 301 | required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } |
| 302 | |
| 303 | // MARK: Geometry |
| 304 | |
| 305 | private func applyInsets() { |
| 306 | let width = max(160, bounds.width) |
| 307 | let left = geometry.textX |
| 308 | let right = max(0, width - geometry.textX - geometry.textWidth) |
| 309 | // The header, then the first page's top margin (and the first |
| 310 | // block's own), above the text; the page's bottom margin below it. |
| 311 | let insets = UIEdgeInsets(top: headerHeight + DocsPageGeometry.verticalMargin + firstMargin, left: left, |
| 312 | bottom: DocsPageGeometry.verticalMargin, right: right) |
| 313 | if insets != textContainerInset { textContainerInset = insets } |
| 314 | pages.origin = firstMargin |
| 315 | setNeedsLayout() |
| 316 | } |
| 317 | private func pagedChanged() { |
| 318 | pages.paged = paged |
| 319 | if paged { pages.restartSettling() } else { pages.clearBreaks() } |
| 320 | setNeedsLayout() |
| 321 | } |
| 322 | private func updateGeometry() { |
| 323 | let width = max(160, bounds.width) |
| 324 | let next = DocsPageGeometry(viewportWidth: width, paged: paged) |
| 325 | let margin = (textStorage.length > 0 ? textStorage.attribute(.docsFirstMargin, at: 0, effectiveRange: nil) as? CGFloat : nil) ?? 0 |
| 326 | guard next != geometry || abs(margin - firstMargin) > 0.01 else { return } |
| 327 | let widthChanged = next.textWidth != geometry.textWidth |
| 328 | geometry = next; firstMargin = margin |
| 329 | if let header { headerHeight = header.height(forWidth: width) } |
| 330 | applyInsets() |
| 331 | // The text's width changed: every paragraph wraps anew. |
| 332 | if widthChanged { pages.forgetMeasurements() } else { pages.restartSettling() } |
| 333 | } |
| 334 | |
| 335 | /// The text storage changed (DocumentSurface's storage delegate). |
| 336 | func storageEdited(_ edited: NSRange, delta: Int) { |
| 337 | pages.edited(edited, delta: delta) |
| 338 | if !pages.regenerating { |
| 339 | lastEdit = .now |
| 340 | releaseHeldBreaks() |
| 341 | if edited.location < screenTop { editedAboveScreen = true } |
| 342 | // The anchor moves with the text. |
| 343 | if var kept = anchor, edited.location < kept.offset { |
| 344 | let oldEnd = NSMaxRange(edited) - delta |
| 345 | kept.offset = kept.offset >= oldEnd ? kept.offset + delta : NSMaxRange(edited) |
| 346 | anchor = kept |
| 347 | } |
| 348 | } |
| 349 | setNeedsLayout() |
| 350 | } |
| 351 | |
| 352 | /// What the screen is kept on when an edit lands above it (a peer's): |
| 353 | /// the caret's character when the caret is on screen, else the one at |
| 354 | /// the screen's middle, and where its line was on screen (Fable's delta |
| 355 | /// review, F4). Taken at the end of every layout. |
| 356 | private var anchor: (offset: Int, y: CGFloat)? |
| 357 | /// The first character on screen at the last layout. |
| 358 | private var screenTop = 0 |
| 359 | private var editedAboveScreen = false |
| 360 | |
| 361 | private func recordAnchor() { |
| 362 | let top = contentOffset.y + adjustedContentInset.top |
| 363 | let bottom = contentOffset.y + bounds.height - adjustedContentInset.bottom |
| 364 | screenTop = character(atY: top) ?? 0 |
| 365 | var at: Int? |
| 366 | if isFirstResponder, let caret = lineTop(at: selectedRange.location), caret >= top, caret < bottom { at = selectedRange.location } |
| 367 | if at == nil { at = character(atY: (top + bottom) / 2) } |
| 368 | anchor = at.flatMap { offset in lineTop(at: offset).map { (offset, $0 - contentOffset.y) } } |
| 369 | } |
| 370 | |
| 371 | /// The screen scrolled so the anchor's line is where it was on screen: |
| 372 | /// an edit above (a peer's) moves nothing a person is reading. |
| 373 | private func keepAnchor() { |
| 374 | defer { editedAboveScreen = false } |
| 375 | guard editedAboveScreen, let kept = anchor, let y = lineTop(at: kept.offset) else { return } |
| 376 | let offset = y - kept.y |
| 377 | guard abs(offset - contentOffset.y) > 0.25 else { return } |
| 378 | contentOffset.y = offset |
| 379 | } |
| 380 | |
| 381 | /// The top of the line holding character `offset`, in the text view. |
| 382 | private func lineTop(at offset: Int) -> CGFloat? { |
| 383 | guard let layout = textLayoutManager, let content = layout.textContentManager, textStorage.length > 0 else { return nil } |
| 384 | let at = min(max(0, offset), textStorage.length - 1) |
| 385 | guard let location = content.location(content.documentRange.location, offsetBy: at), |
| 386 | let fragment = layout.textLayoutFragment(for: location) else { return nil } |
| 387 | let inner = at - content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location) |
| 388 | let line = fragment.textLineFragments.first { NSLocationInRange(inner, $0.characterRange) } ?? fragment.textLineFragments.last |
| 389 | return fragment.layoutFragmentFrame.minY + (line?.typographicBounds.minY ?? 0) + textContainerInset.top |
| 390 | } |
| 391 | |
| 392 | /// The first character of the line at `y` in the text view. |
| 393 | private func character(atY y: CGFloat) -> Int? { |
| 394 | guard let layout = textLayoutManager, let content = layout.textContentManager, |
| 395 | let fragment = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, y - textContainerInset.top))) else { return nil } |
| 396 | let base = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location) |
| 397 | let inner = y - textContainerInset.top - fragment.layoutFragmentFrame.minY |
| 398 | let line = fragment.textLineFragments.first { $0.typographicBounds.maxY > inner } ?? fragment.textLineFragments.last |
| 399 | return base + (line?.characterRange.location ?? 0) |
| 400 | } |
| 401 | |
| 402 | override func layoutSubviews() { |
| 403 | #if DOCS_PROBES |
| 404 | let probeStart = DocsProbes.now() |
| 405 | defer { DocsProbes.textLayouts += 1; DocsProbes.textLayoutMs += DocsProbes.ms(since: probeStart) } |
| 406 | #endif |
| 407 | updateGeometry() |
| 408 | restackEdits() |
| 409 | super.layoutSubviews() |
| 410 | paginate() |
| 411 | keepAnchor() |
| 412 | tilePages() |
| 413 | if let header { |
| 414 | let frame = CGRect(x: 0, y: 0, width: bounds.width, height: headerHeight) |
| 415 | if header.view.frame != frame { header.view.frame = frame } |
| 416 | reportScroll() |
| 417 | } |
| 418 | recordAnchor() |
| 419 | } |
| 420 | |
| 421 | /// An edit (a key, a peer's change) above the screen's end, before |
| 422 | /// UIKit lays the screen out: its paragraphs measured, the breaks |
| 423 | /// placed and rebuilt, and TextKit 2's fragments stacked again from the |
| 424 | /// top through the screen. Otherwise TextKit 2 places the screen at an |
| 425 | /// estimate and UIKit scrolls to keep it still, which then moves the |
| 426 | /// screen once the fragments are stacked (Fable on #180). |
| 427 | private func restackEdits() { |
| 428 | guard !paginating, let edited = pages.editedFrom, let layout = textLayoutManager, let content = layout.textContentManager, |
| 429 | let viewport = layout.textViewportLayoutController.viewportRange else { return } |
| 430 | let end = min(textStorage.length, content.offset(from: content.documentRange.location, to: viewport.endLocation)) |
| 431 | guard edited <= end, end <= pages.laidOutThrough else { return } |
| 432 | paginating = true |
| 433 | defer { paginating = false } |
| 434 | pages.rebuildIfStale() |
| 435 | let last = (pages.paragraph(at: end) ?? 0) + 1 |
| 436 | pages.measureHoles(through: last, in: layout) |
| 437 | pages.settle() |
| 438 | applyBreaks(through: last) |
| 439 | pages.ensureLayout(through: end, in: layout) |
| 440 | } |
| 441 | |
| 442 | /// The page breaks for what is on screen, before it is drawn: |
| 443 | /// - a screen past what is laid out (a jump) is laid out from the top |
| 444 | /// through its end (the spec's fallback, once per jump); |
| 445 | /// - what is on screen (and the paragraph after it) and not measured is |
| 446 | /// measured, a run at a time, so an edit far above is measured alone; |
| 447 | /// - the breaks are placed and those that moved rebuilt; |
| 448 | /// - TextKit 2's fragments are stacked again from the top through the |
| 449 | /// screen's end if an edit or a rebuilt break is above it, and the |
| 450 | /// screen laid out again. |
| 451 | /// The rest is measured while idle. |
| 452 | private func paginate() { |
| 453 | guard !paginating, let layout = textLayoutManager, let content = layout.textContentManager else { return } |
| 454 | paginating = true |
| 455 | defer { paginating = false } |
| 456 | pages.rebuildIfStale() |
| 457 | // Breaks moving the text can bring other paragraphs on screen: look |
| 458 | // again, a few times at most. |
| 459 | for _ in 0..<3 { |
| 460 | guard let viewport = layout.textViewportLayoutController.viewportRange else { break } |
| 461 | let start = content.offset(from: content.documentRange.location, to: viewport.location) |
| 462 | let end = content.offset(from: content.documentRange.location, to: viewport.endLocation) |
| 463 | if let span = pages.relayout(forScreenAt: start) { relay(span, through: end, in: layout) } |
| 464 | let last = (pages.paragraph(at: end) ?? 0) + 1 |
| 465 | pages.measureHoles(through: last, in: layout) |
| 466 | pages.settle() |
| 467 | // Breaks below the screen wait for idle. |
| 468 | let changed = pages.hasChanges(through: last) && markedTextRange == nil |
| 469 | applyBreaks(through: last) |
| 470 | let walked = pages.ensureLayout(through: end, in: layout) |
| 471 | guard changed || walked else { break } |
| 472 | layout.textViewportLayoutController.layoutViewport() |
| 473 | } |
| 474 | scheduleIdle() |
| 475 | } |
| 476 | |
| 477 | /// Everything from `span`'s start thrown away and laid out again from |
| 478 | /// the top through the screen's end, `end`. TextKit 2 keeps a fragment |
| 479 | /// it placed at an estimate as laid out: thrown away, the layout from |
| 480 | /// the top places it after what is exact. |
| 481 | private func relay(_ span: Range<Int>, through end: Int, in layout: NSTextLayoutManager) { |
| 482 | guard let content = layout.textContentManager, |
| 483 | let from = content.location(content.documentRange.location, offsetBy: span.lowerBound), |
| 484 | let range = NSTextRange(location: from, end: content.documentRange.endLocation) else { return } |
| 485 | #if DOCS_PROBES |
| 486 | DocsProbes.relaidParagraphs += (pages.paragraph(at: end) ?? 0) - (pages.paragraph(at: span.lowerBound) ?? 0) + 1 |
| 487 | #endif |
| 488 | layout.invalidateLayout(for: range) |
| 489 | applyBreaks() |
| 490 | pages.ensureLayout(through: end, in: layout) |
| 491 | layout.textViewportLayoutController.layoutViewport() |
| 492 | } |
| 493 | |
| 494 | /// The breaks that moved built again (through paragraph `limit`), unless |
| 495 | /// text is being composed: building one again is an attribute edit of |
| 496 | /// its paragraph, which may be the one an input method is composing in |
| 497 | /// (Fable on #180). They wait for the composition to end, which lays |
| 498 | /// out again (`DocsTextView`). |
| 499 | private func applyBreaks(through limit: Int = .max) { |
| 500 | guard markedTextRange == nil else { |
| 501 | if pages.hasChanges { breaksHeld = true } |
| 502 | return |
| 503 | } |
| 504 | pages.applyChanges(through: limit) |
| 505 | } |
| 506 | /// Breaks are waiting for a composition to end. |
| 507 | private var breaksHeld = false |
| 508 | /// A composition can end without `unmarkText` (the text view resigning, |
| 509 | /// the input method cancelling): on those, and on any text or selection |
| 510 | /// change, held breaks are built once nothing is marked (Fable's delta |
| 511 | /// review, F6). |
| 512 | func releaseHeldBreaks() { |
| 513 | guard breaksHeld, markedTextRange == nil else { return } |
| 514 | breaksHeld = false |
| 515 | setNeedsLayout() |
| 516 | } |
| 517 | |
| 518 | /// Whether the idle measuring is running (tests). |
| 519 | var isMeasuringWhileIdle: Bool { idle != nil } |
| 520 | |
| 521 | /// The rest of the document, a chunk per turn, while nothing else runs. |
| 522 | private func scheduleIdle() { |
| 523 | // Also for breaks a key left below the screen (Fable's delta review, |
| 524 | // F2), and for a restack to finish (F3). |
| 525 | guard idle == nil, pages.firstUnmeasured != nil || pages.settleFrom != nil |
| 526 | || (pages.hasChanges && markedTextRange == nil) || pages.editedFrom != nil else { return } |
| 527 | idle = Task { @MainActor [weak self] in |
| 528 | while !Task.isCancelled { |
| 529 | try? await Task.sleep(for: .milliseconds(2)) |
| 530 | guard let self, let layout = self.textLayoutManager else { return } |
| 531 | let before = (self.pages.firstUnmeasured, self.pages.settleFrom) |
| 532 | if let hole = self.pages.firstUnmeasured { |
| 533 | self.pages.measure(hole..<min(self.pages.paragraphs.count, hole + DocsPhonePages.chunk), in: layout) |
| 534 | } |
| 535 | self.pages.settle() |
| 536 | if self.pages.hasChanges && self.markedTextRange == nil { self.applyBreaks(); self.setNeedsLayout(); continue } |
| 537 | let progressed = (self.pages.firstUnmeasured, self.pages.settleFrom) != before |
| 538 | if progressed, self.pages.firstUnmeasured != nil || self.pages.settleFrom != nil { continue } |
| 539 | // Measured and placed, or nowhere to go (a paragraph that |
| 540 | // cannot be measured: an empty document; breaks held for a |
| 541 | // composition). An edit's restack is finished with one walk |
| 542 | // over everything laid out (F3), once typing pauses: until |
| 543 | // then each frame that scrolls past the last walk walks again. |
| 544 | if self.pages.editedFrom != nil, self.markedTextRange == nil { |
| 545 | let quiet = ContinuousClock.now - self.lastEdit |
| 546 | if quiet < Self.restackPause { try? await Task.sleep(for: Self.restackPause - quiet); continue } |
| 547 | self.pages.ensureLayout(through: self.pages.laidOutThrough, in: layout) |
| 548 | self.setNeedsLayout() |
| 549 | } |
| 550 | // Layout starts it again when there is something new, and so |
| 551 | // does a composition ending. |
| 552 | self.idle = nil |
| 553 | return |
| 554 | } |
| 555 | } |
| 556 | } |
| 557 | /// When the text last changed, and how long typing must pause before |
| 558 | /// idle walks everything laid out to finish a restack. |
| 559 | private var lastEdit = ContinuousClock.now |
| 560 | private static let restackPause = Duration.milliseconds(300) |
| 561 | |
| 562 | /// Measures and places every paragraph now (tests: a whole layout). |
| 563 | func paginateEverything() { |
| 564 | guard let layout = textLayoutManager else { return } |
| 565 | while let hole = pages.firstUnmeasured { |
| 566 | pages.measure(hole..<pages.paragraphs.count, in: layout) |
| 567 | if pages.firstUnmeasured == hole { break } |
| 568 | } |
| 569 | pages.settle() |
| 570 | applyBreaks() |
| 571 | pages.ensureLayout(through: textStorage.length, in: layout) |
| 572 | layout.textViewportLayoutController.layoutViewport() |
| 573 | setNeedsLayout(); layoutIfNeeded() |
| 574 | } |
| 575 | |
| 576 | |
| 577 | /// Where the last page's paper ends, when paged: the content is at |
| 578 | /// least this tall, so its bottom margin and number scroll into view. |
| 579 | private var pageFoot: CGFloat = 0 |
| 580 | override var contentSize: CGSize { |
| 581 | get { super.contentSize } |
| 582 | set { super.contentSize = CGSize(width: newValue.width, height: max(newValue.height, pageFoot)) } |
| 583 | } |
| 584 | |
| 585 | /// The pages on screen, behind the text: white paper on the desk, and |
| 586 | /// its number. Only the visible ones exist. The content reaches the |
| 587 | /// last page's foot, and clears whatever covers the bottom. |
| 588 | private func tilePages() { |
| 589 | let geometry = self.geometry |
| 590 | let paperTop = headerHeight |
| 591 | let used = textLayoutManager?.usageBoundsForTextContainer.maxY ?? 0 |
| 592 | let lastPage = paged ? geometry.page(at: max(0, firstMargin + used - 1) + DocsPageGeometry.verticalMargin) : 0 |
| 593 | let wantedHeight = paged ? paperTop + CGFloat(lastPage + 1) * DocsPageGeometry.paperHeight + CGFloat(lastPage) * DocsPageGeometry.gap |
| 594 | : max(contentSize.height, paperTop + DocsPageGeometry.paperHeight) |
| 595 | // Only what covers the bottom moves the inset: changing it re-lays |
| 596 | // out the whole screen, so it never follows TextKit 2's height |
| 597 | // estimate (which moves with every key). The content reaches the |
| 598 | // last page's foot through `contentSize` instead, which lays out |
| 599 | // nothing. |
| 600 | if abs(contentInset.bottom - bottomObstruction) > 0.5 { contentInset.bottom = bottomObstruction } |
| 601 | let foot = paged ? wantedHeight : 0 |
| 602 | if abs(foot - pageFoot) > 0.5 { |
| 603 | pageFoot = foot |
| 604 | // The text's own height, as the text view would set it. |
| 605 | contentSize = CGSize(width: contentSize.width, height: textContainerInset.top + used + textContainerInset.bottom) |
| 606 | } |
| 607 | if abs(verticalScrollIndicatorInsets.bottom - bottomObstruction) > 0.5 { verticalScrollIndicatorInsets.bottom = bottomObstruction } |
| 608 | let visible = CGRect(x: 0, y: contentOffset.y - paperTop, width: bounds.width, height: bounds.height) |
| 609 | var wanted: [Int: CGRect] = [:] |
| 610 | if paged { |
| 611 | let first = geometry.page(at: max(0, visible.minY)), last = min(lastPage, geometry.page(at: max(0, visible.maxY))) |
| 612 | if first <= last { for page in first...last { wanted[page] = geometry.pageRect(page).offsetBy(dx: 0, dy: paperTop) } } |
| 613 | } else { |
| 614 | wanted[0] = CGRect(x: geometry.paperX, y: paperTop, width: geometry.paperWidth, height: max(wantedHeight - paperTop, bounds.height)) |
| 615 | } |
| 616 | for (page, view) in pageViews where wanted[page] == nil { view.removeFromSuperview(); pageViews[page] = nil } |
| 617 | for (page, frame) in wanted { |
| 618 | let view = pageViews[page] ?? { |
| 619 | let made = DocsPageView() |
| 620 | insertSubview(made, at: 0) |
| 621 | pageViews[page] = made |
| 622 | return made |
| 623 | }() |
| 624 | if view.frame != frame { view.frame = frame } |
| 625 | view.number = paged ? page + 1 : nil |
| 626 | if subviews.first !== view { sendSubviewToBack(view) } |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | // MARK: TextKit 2 |
| 631 | |
| 632 | /// The layout fragments TextKit 2 makes: what laying out costs (spec §7's |
| 633 | /// line-request counter, in TextKit 2's unit: one per paragraph laid out). |
| 634 | func textLayoutManager(_ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: any NSTextLocation, |
| 635 | in textElement: NSTextElement) -> NSTextLayoutFragment { |
| 636 | #if DOCS_PROBES |
| 637 | DocsProbes.layoutFragments += 1 |
| 638 | #endif |
| 639 | guard paged, let content = textLayoutManager.textContentManager else { |
| 640 | return NSTextLayoutFragment(textElement: textElement, range: textElement.elementRange) |
| 641 | } |
| 642 | // A paragraph that starts a page carries the break's space (DocsPhonePages). |
| 643 | return pages.fragment(for: content.offset(from: content.documentRange.location, to: location), element: textElement) |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | /// One sheet of paper behind the text, with its page number. |
| 648 | final class DocsPageView: UIView { |
| 649 | var number: Int? { |
| 650 | didSet { |
| 651 | guard oldValue != number else { return } |
| 652 | label.text = number.map { String(localized: "docs.editor.page.number", bundle: DocsResources.bundle).replacingOccurrences(of: "{n}", with: String($0)) } |
| 653 | label.isHidden = number == nil |
| 654 | setNeedsLayout() |
| 655 | } |
| 656 | } |
| 657 | private let label = UILabel() |
| 658 | override init(frame: CGRect) { |
| 659 | super.init(frame: frame) |
| 660 | backgroundColor = .white |
| 661 | isUserInteractionEnabled = false |
| 662 | isAccessibilityElement = false |
| 663 | label.font = .systemFont(ofSize: 10) |
| 664 | label.textColor = .darkGray |
| 665 | label.isHidden = true |
| 666 | addSubview(label) |
| 667 | } |
| 668 | required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } |
| 669 | override func layoutSubviews() { |
| 670 | super.layoutSubviews() |
| 671 | label.sizeToFit() |
| 672 | label.frame.origin = CGPoint(x: bounds.width - 80, y: DocsPageGeometry.paperHeight - 35 - label.bounds.height / 2) |
| 673 | } |
| 674 | } |
| 675 | #endif |
| 676 | |