Docs native S1b: time-boxed idle chunks, and no redraw for what is below the screen
Fable on #173, finding 2. - An idle chunk measures for at most 8 ms a turn (at least one block), not a fixed 50 blocks (31–45 ms a chunk at 200 pages under load). The "most of the document changed" threshold stays at 50 blocks. - A pass asks for a redraw only when a line or a separator at or above the visible bottom moved; while the chunks measure below the screen, nothing there does. Every chunk used to redraw the visible rect, its estimated bottom having moved. - While measuring, the frame follows the estimated height only when it is off by a page or more (and exactly once measuring is done), so the chunks do not lay the view out again every turn. Tests: with no time budget a chunk measures one block (it measured 50); measuring 200 pages below the screen redraws nothing (it redrew every chunk). New probe counter: pagination redraws, and whether measuring is still going on (the UI probe's open timing).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+87
−19
native/apple/Sources/DocsKit/DocsPagedTextView.swift+10 −4native/apple/Sources/DocsKit/DocsPagination.swift+42 −14native/apple/Sources/DocsKit/DocsProbes.swift+5 −1native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift+30 −0
diff --git a/native/apple/Sources/DocsKit/DocsPagedTextView.swift b/native/apple/Sources/DocsKit/DocsPagedTextView.swift| index 1cd4807..a63db50 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPagedTextView.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPagedTextView.swift |
| @@ -37,7 +37,8 @@ import AppKit |
| super.init(frame: frameRect, textContainer: pages) |
| pages.tops = pagination |
| pagination.canDefer = { [weak self] in self?.window != nil } |
| - pagination.changed = { [weak self] in self?.paginationChanged() } |
| + pagination.changed = { [weak self] height, redraw in self?.paginationChanged(height: height, redraw: redraw) } |
| + pagination.visibleBottom = { [weak self] in self?.visibleRect.maxY ?? .greatestFiniteMagnitude } |
| textContainerInset = .zero |
| // This view owns its paginated height; NSTextView auto-sizing uses a |
| // different used rect and briefly clips the current line during input. |
| @@ -78,9 +79,14 @@ import AppKit |
| pagination.setGeometry(pages.geometry) |
| pagination.update(visibleBottom: visibleRect.maxY, through: character) |
| } |
| - /// An idle chunk or a jump moved lines or the height outside layout(). |
| - private func paginationChanged() { |
| - if !updatingGeometry { needsLayout = true } |
| + /// A pass moved the height (the frame follows at the next layout) or |
| + /// lines on screen (redrawn). |
| + private func paginationChanged(height: Bool, redraw: Bool) { |
| + if height && !updatingGeometry { needsLayout = true } |
| + guard redraw else { return } |
| + #if DOCS_PROBES |
| + DocsProbes.paginationRedraws += 1 |
| + #endif |
| // Not plain setNeedsDisplay: NSTextView's lays the rect out at once. |
| setNeedsDisplay(visibleRect, avoidAdditionalLayout: true) |
| } |
diff --git a/native/apple/Sources/DocsKit/DocsPagination.swift b/native/apple/Sources/DocsKit/DocsPagination.swift| index 9e85689..48687ca 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPagination.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPagination.swift |
| @@ -63,7 +63,7 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| /// and its two margins. Natural tops are their prefix sums, so a Return, |
| /// a deleted block or a paste is a splice. |
| /// - **The full path** (item 3) measures every block: at open (the visible |
| -/// blocks at once, the rest in idle chunks of 50 a turn), on a width |
| +/// blocks at once, the rest in idle chunks of at most 8 ms a turn), on a width |
| /// change, and when most blocks changed together. |
| /// - **Per edit** (item 4) only the edited blocks are measured again; the |
| /// break algorithm runs from the page holding the first of them until a |
| @@ -123,14 +123,20 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| private var breaksThrough = -1 |
| private var full = true |
| private var chunkScheduled = false |
| - /// Runs after a pass that moved lines or the height (the text view |
| - /// lays itself out again). |
| - var changed: (() -> Void)? |
| + /// Runs after a pass that moved the height (the text view lays itself |
| + /// out again) or lines at or above the visible bottom (it redraws). |
| + var changed: ((_ height: Bool, _ redraw: Bool) -> Void)? |
| + /// The live layout's visible bottom: lines below it moving need no redraw. |
| + var visibleBottom: () -> CGFloat = { .greatestFiniteMagnitude } |
| /// Whether the measurement may continue in idle chunks (a window shows |
| /// the text) or must finish at once (no window: tests, snapshots). |
| var canDefer: () -> Bool = { false } |
| - static let chunk = 50 |
| + /// Main-thread time an idle chunk may spend measuring (it measures at |
| + /// least one block). |
| + static var chunkBudget: Duration = .milliseconds(8) |
| + /// More edited blocks than this at once take the full path's order. |
| + static let staleLimit = 50 |
| private(set) var geometry: DocsPageGeometry |
| @@ -281,7 +287,7 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| /// `character`, works out the breaks that may have moved, and |
| /// invalidates the live layout from the first unit whose top moved. |
| /// Cheap when nothing changed. |
| - func update(visibleBottom: CGFloat, through character: Int? = nil, chunk: Int = 0) { |
| + func update(visibleBottom: CGFloat, through character: Int? = nil, idle: Bool = false) { |
| guard let storage else { return } |
| if full { |
| full = false |
| @@ -298,12 +304,12 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| stale += 1 |
| if firstStale == nil { firstStale = index } |
| } |
| - if let firstStale, stale > Self.chunk, canDefer() { |
| + if let firstStale, stale > Self.staleLimit, canDefer() { |
| frontier = firstStale |
| for index in firstStale..<units.count { units[index].measured = false } |
| } |
| let deferring = canDefer() |
| - let wantsMore = frontier < units.count && (!deferring || chunk > 0 || frontierTop() <= visibleBottom |
| + let wantsMore = frontier < units.count && (!deferring || idle || frontierTop() <= visibleBottom |
| || units[frontier].location <= (character ?? -1)) |
| // In a window with more to measure and no chunk waiting (it was |
| // dropped while the view was out of its window): carry on. |
| @@ -318,8 +324,13 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| var running = frontierTop() |
| let targetCharacter = character ?? -1 |
| let firstNew = frontier |
| + let started = ContinuousClock.now |
| while frontier < units.count { |
| - if deferring && frontier - firstNew >= chunk && running > visibleBottom && units[frontier].location > targetCharacter { break } |
| + if deferring { |
| + if idle { |
| + if frontier > firstNew && started.duration(to: .now) >= Self.chunkBudget { break } |
| + } else if running > visibleBottom && units[frontier].location > targetCharacter { break } |
| + } |
| measure(frontier) |
| if frontier == 0 { running = units[0].natural ?? 0 } |
| running += units[frontier].advance |
| @@ -377,6 +388,7 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| var natural = units.first?.natural ?? DocsPageGeometry.verticalMargin |
| var added: CGFloat = 0 |
| var firstMoved: Int? |
| + var movedY = CGFloat.greatestFiniteMagnitude |
| var separators: [CGFloat] = [] |
| var measuredAdvance: CGFloat = 0, measuredLength = 0 |
| for index in units.indices { |
| @@ -386,13 +398,16 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| added += units[index].extra |
| let top = natural + added |
| if units[index].extra > 0 { separators.append(top - units[index].lift) } |
| - if firstMoved == nil, units[index].top.map({ abs($0 - top) > 0.001 }) ?? true { firstMoved = index } |
| + if firstMoved == nil, units[index].top.map({ abs($0 - top) > 0.001 }) ?? true { |
| + firstMoved = index |
| + movedY = min(top, units[index].top ?? top) |
| + } |
| units[index].top = top |
| measuredAdvance += units[index].advance; measuredLength += units[index].length |
| } else if units[index].top != nil { |
| // Beyond the frontier: no top until measured, so TextKit |
| // flows these lines on from the last measured one. |
| - if firstMoved == nil { firstMoved = index } |
| + if firstMoved == nil { firstMoved = index; movedY = units[index].top ?? movedY } |
| units[index].top = nil; units[index].natural = nil |
| } |
| if known { natural += units[index].advance } |
| @@ -403,14 +418,27 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| let remaining = units[measured...].reduce(0) { $0 + $1.length } |
| bottom += measuredAdvance / CGFloat(measuredLength) * CGFloat(remaining) |
| } |
| - let moved = separators != self.separators || abs(bottom - self.bottom) > 0.001 || firstMoved != nil |
| + // Redraw only if something at or above the visible bottom moved: |
| + // while idle chunks measure below the screen, nothing there does. |
| + let shown = visibleBottom() |
| + let redraw = (firstMoved != nil && movedY <= shown) |
| + || separators.prefix { $0 <= shown } != self.separators.prefix { $0 <= shown } |
| + // While the frontier moves the bottom is an estimate: the frame |
| + // follows it only when it is off by a page or more, and exactly |
| + // once measuring is done. |
| + let estimating = measured < units.count |
| + let height = abs(bottom - self.bottom) > (estimating ? DocsPageGeometry.paperHeight : 0.001) |
| + if !height && estimating { bottom = self.bottom } |
| self.separators = separators |
| self.bottom = bottom |
| if let firstMoved, let live, let storage, firstMoved < units.count { |
| let location = units[firstMoved].location |
| live.invalidateLayout(forCharacterRange: NSRange(location: location, length: storage.length - location), actualCharacterRange: nil) |
| } |
| - if moved { changed?() } |
| + #if DOCS_PROBES |
| + DocsProbes.measuring = measured < units.count |
| + #endif |
| + if height || redraw { changed?(height, redraw) } |
| } |
| /// Today's algorithm (DocumentPageLayoutOracle.measure) over the cached |
| @@ -475,7 +503,7 @@ final class DocsMeasureTextContainer: NSTextContainer { |
| // layout in a window picks it up. |
| guard self.frontier < self.units.count, self.canDefer() else { return } |
| // One chunk past the frontier, then the next turn. |
| - self.update(visibleBottom: -.greatestFiniteMagnitude, chunk: Self.chunk) |
| + self.update(visibleBottom: -.greatestFiniteMagnitude, idle: true) |
| } |
| } |
| RunLoop.main.add(timer, forMode: .common) |
diff --git a/native/apple/Sources/DocsKit/DocsProbes.swift b/native/apple/Sources/DocsKit/DocsProbes.swift| index e33bd25..f72da15 100644 |
| --- a/native/apple/Sources/DocsKit/DocsProbes.swift |
| +++ b/native/apple/Sources/DocsKit/DocsProbes.swift |
| @@ -44,6 +44,10 @@ public enum DocsProbes { |
| /// Mac pagination passes, and their main-thread time. |
| nonisolated(unsafe) public static var paginations = 0 |
| nonisolated(unsafe) public static var paginationMs = 0.0 |
| + /// Redraws of the visible rect a pagination pass asked for, and whether |
| + /// the last pass left measuring incomplete (the probe's open timing). |
| + nonisolated(unsafe) public static var paginationRedraws = 0 |
| + nonisolated(unsafe) public static var measuring = false |
| /// The text view's own layout (Mac `layout()`, iOS `layoutSubviews`). |
| nonisolated(unsafe) public static var textLayouts = 0 |
| nonisolated(unsafe) public static var textLayoutMs = 0.0 |
| @@ -61,7 +65,7 @@ public enum DocsProbes { |
| reconciles = 0; reconcileMs = 0; viewUpdates = 0; viewUpdateMs = 0 |
| hostBodies = 0; attributedTextAssignments = 0; publications = 0; publicationMs = 0 |
| workspaceBodies = 0; inspectorBodies = 0 |
| - lineRequests = 0; measureLineRequests = 0; paginations = 0; paginationMs = 0 |
| + lineRequests = 0; measureLineRequests = 0; paginations = 0; paginationMs = 0; paginationRedraws = 0 |
| textLayouts = 0; textLayoutMs = 0; draws = 0; drawMs = 0 |
| toolbarRefreshes = 0; toolbarRefreshMs = 0; commands = 0; commandMs = 0 |
| } |
diff --git a/native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift b/native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift| index f8bbf1b..6ac8d00 100644 |
| --- a/native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift |
| @@ -146,7 +146,37 @@ import XCTest |
| try await until("measuring resumes and completes") { view.pagination.isComplete } |
| } |
| + /// Idle chunks are time-boxed, not a fixed count of blocks (Fable on |
| + /// #173, finding 2): with no time to spend, a chunk measures one block. |
| + func testAnIdleChunkMeasuresWithinItsTimeBudget() async throws { |
| + DocsFonts.register() |
| + let budget = DocsPagination.chunkBudget |
| + DocsPagination.chunkBudget = .zero |
| + defer { DocsPagination.chunkBudget = budget } |
| + let document = Window(Self.pages(200)) |
| + defer { document.close() } |
| + let pagination = document.view.pagination |
| + let frontier = pagination.frontier |
| + XCTAssertLessThan(frontier, pagination.units.count) |
| + pagination.update(visibleBottom: -.greatestFiniteMagnitude, idle: true) |
| + XCTAssertEqual(pagination.frontier, frontier + 1, "a chunk with no time left measures one block") |
| + } |
| + |
| #if DOCS_PROBES |
| + /// While the idle chunks measure what is below the screen, nothing on |
| + /// screen moves, so nothing is redrawn (Fable on #173, finding 2: every |
| + /// chunk redrew the visible rect, its estimated bottom having moved). |
| + func testIdleChunksBelowTheScreenRedrawNothing() async throws { |
| + DocsFonts.register() |
| + let document = Window(Self.pages(200)) |
| + defer { document.close() } |
| + let view = document.view |
| + XCTAssertFalse(view.pagination.isComplete) |
| + let redraws = DocsProbes.paginationRedraws |
| + try await until("the idle chunks complete") { view.pagination.isComplete } |
| + XCTAssertEqual(DocsProbes.paginationRedraws - redraws, 0, "redraws while measuring below the screen") |
| + } |
| + |
| /// §7's line-fragment gate, per key at p20 and p200: TextKit's requests |
| /// to the live container (counted inside `lineFragmentRect`, so its own |
| /// re-layout counts) stay within the edited block's lines, the visible |