From 2e859b232ec304f22a69f4caf53d1acba08c842c Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 26 Nov 2026 03:18:42 +0700 Subject: [PATCH 1/2] perf(editor): redraw only the lines a caret move or edit changes A caret move invalidated the text view's bounds, the statement band's change redrew the whole view, and the gutter redrew every row on each selection change and edit. Now the selection manager invalidates the lines the selections left and the lines they are on, the band invalidates its old and new lines and draws only the lines in the dirty rect, and the gutter redraws the selection's old and new rows and, on an edit, the edited line or every line below it when lines move. The gutter's caret band is tested against the dirty rect instead of the visible text, selected line numbers after Select All come from the drawn lines only, and shaped line numbers are cached by number and colour. Fixes `didUpdate || reposition(...)`, which stopped repositioning carets after the first one that moved. --- .../TextViewController+TextViewDelegate.swift | 10 +- .../Controller/TextViewController.swift | 3 + .../TableProEditorKit/Gutter/GutterView.swift | 133 ++++++++++++++---- .../SourceEditorTextView.swift | 25 +++- .../TextSelectionManager+Draw.swift | 1 + .../TextSelectionManager+Move.swift | 2 +- .../TextSelectionManager+Update.swift | 3 + .../TextSelectionManager.swift | 65 ++++++++- .../GutterHighlightTests.swift | 14 ++ .../SelectionBehaviourTests.swift | 43 ++++++ .../SelectionGeometryTests.swift | 1 + 11 files changed, 266 insertions(+), 34 deletions(-) diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+TextViewDelegate.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+TextViewDelegate.swift index 522ee1b876..758dd177eb 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+TextViewDelegate.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+TextViewDelegate.swift @@ -11,6 +11,9 @@ import TextStory extension TextViewController: TextViewDelegate { public func textView(_ textView: TextView, willReplaceContentsIn range: NSRange, with string: String) { + pendingEditRemovesLineBreak = range.length > 0 + && (textView.textStorage.string as NSString) + .rangeOfCharacter(from: .newlines, options: [], range: range).location != NSNotFound for coordinator in self.textCoordinators.values() { if let coordinator = coordinator as? TextViewDelegate { coordinator.textView(textView, willReplaceContentsIn: range, with: string) @@ -19,7 +22,12 @@ extension TextViewController: TextViewDelegate { } public func textView(_ textView: TextView, didReplaceContentsIn range: NSRange, with string: String) { - gutterView.needsDisplay = true + gutterView.setNeedsDisplayForEdit( + at: range.location, + movesLinesBelow: wrapLines || pendingEditRemovesLineBreak + || (string as NSString).rangeOfCharacter(from: .newlines).location != NSNotFound + ) + pendingEditRemovesLineBreak = false snippetTextDidReplace(in: range, with: string) for coordinator in self.textCoordinators.values() { if let coordinator = coordinator as? TextViewDelegate { diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController.swift index 2e20435e8b..3c7232d4c0 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController.swift @@ -190,6 +190,9 @@ public class TextViewController: NSViewController { var textFilters: [TextFormation.Filter] = [] var isApplyingUnfilteredEdits = false + // Whether the edit in flight removes a line break, read before the text it removes is gone. + var pendingEditRemovesLineBreak = false + var cancellables = Set() var snippetSession: SnippetSession? diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Gutter/GutterView.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Gutter/GutterView.swift index 9157c23761..d219c48bab 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Gutter/GutterView.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Gutter/GutterView.swift @@ -45,6 +45,7 @@ public class GutterView: NSView { @Invalidating(.display) var font: NSFont = .systemFont(ofSize: 13) { didSet { + shapedLineNumbers.removeAll() updateFontLineHeight() lineNumberDigits = 0 updateWidthIfNeeded() @@ -151,6 +152,19 @@ public class GutterView: NSView { private(set) var selectionObserver: NSObjectProtocol? + // A number's shape depends only on the number, the font and the colour it is drawn in, and the same few dozen + // visible numbers are drawn on every scroll frame and every edit. + private struct ShapedLineNumberKey: Hashable { + let number: Int + let color: CGColor + } + + private var shapedLineNumbers: [ShapedLineNumberKey: CTLine] = [:] + private static let shapedLineNumberLimit = 4_096 + + // The rows the caret's band and the selected line numbers were last drawn on, redrawn when the selection leaves. + private var drawnSelectionRows: [CGRect] = [] + private func updateFontLineHeight() { let string = NSAttributedString(string: "0", attributes: [.font: font]) let typesetter = CTTypesetterCreateWithAttributedString(string) @@ -303,8 +317,59 @@ public class GutterView: NSView { object: controller.textView.selectionManager, queue: .main ) { [weak self] _ in - self?.needsDisplay = true + self?.setNeedsDisplayForSelection() + } + } + + /// Redraws the numbers an edit can change: its own line, or every line from it down when the edit adds or removes + /// a line, or can rewrap one, since each number below then moves. + func setNeedsDisplayForEdit(at location: Int, movesLinesBelow: Bool) { + guard let line = textView?.layoutManager.textLineForOffset(location) else { + needsDisplay = true + return } + let height = movesLinesBelow ? max(bounds.maxY - line.yPos, line.height) : line.height + setNeedsDisplay(CGRect(x: 0, y: line.yPos, width: frame.width, height: height)) + } + + /// Redraws the rows the selection was on and the rows it is on now: its band and its line numbers' colour. + func setNeedsDisplayForSelection() { + let current = selectionRows() + let dirty = drawnSelectionRows + current + drawnSelectionRows = current + for row in dirty { + setNeedsDisplay(row) + } + } + + // A layout pass can redraw the band on rows no selection change named, so a draw remembers where it put it. + private func noteSelectionDrawn(in rect: NSRect) { + for row in selectionRows() where row.intersects(rect) && !drawnSelectionRows.contains(row) { + drawnSelectionRows.append(row) + } + if drawnSelectionRows.count > 16 { + drawnSelectionRows = [drawnSelectionRows.reduce(CGRect.null) { $0.union($1) }] + } + } + + // Many carets, or a range, collapse to one rect spanning them, which is all one draw pass would cover anyway. + private func selectionRows() -> [CGRect] { + guard let textView, let selectionManager = textView.selectionManager else { return [] } + let layoutManager = textView.layoutManager + var top = CGFloat.greatestFiniteMagnitude + var bottom = -CGFloat.greatestFiniteMagnitude + var rows: [CGRect] = [] + for selection in selectionManager.textSelections { + guard let first = layoutManager?.textLineForOffset(selection.range.location) else { continue } + let last = selection.range.isEmpty + ? first + : layoutManager?.textLineForOffset(selection.range.max) ?? first + rows.append(CGRect(x: 0, y: first.yPos, width: frame.width, height: last.yPos + last.height - first.yPos)) + top = min(top, first.yPos) + bottom = max(bottom, last.yPos + last.height) + } + guard rows.count > 8 else { return rows } + return [CGRect(x: 0, y: top, width: frame.width, height: bottom - top)] } required init?(coder: NSCoder) { @@ -425,10 +490,12 @@ public class GutterView: NSView { /// Draws selected line backgrounds from the text view's selection manager into the gutter view, making the /// selection background appear seamless between the gutter and text view. /// - Parameter context: The drawing context to use. - private func drawSelectedLines(_ context: CGContext) { + /// + /// Tested against the rect being drawn rather than the visible text, so a scroll that brings the caret's line in + /// draws its band in the newly exposed rows without redrawing the rest of the gutter. + private func drawSelectedLines(_ context: CGContext, dirtyRect: NSRect) { guard let textView = textView, let selectionManager = textView.selectionManager, - let visibleRange = textView.visibleTextRange, highlightSelectedLines else { return } @@ -444,19 +511,13 @@ public class GutterView: NSView { for selection in selectionManager.textSelections where selection.range.isEmpty { guard let line = textView.layoutManager.textLineForOffset(selection.range.location), - visibleRange.intersection(line.range) != nil || selection.range.location == textView.length, !highlightedLines.contains(line.data.id) else { continue } + let band = CGRect(x: xPos, y: line.yPos, width: width, height: line.height).pixelAligned + guard band.intersects(dirtyRect) else { continue } highlightedLines.insert(line.data.id) - context.fill( - CGRect( - x: xPos, - y: line.yPos, - width: width, - height: line.height - ).pixelAligned - ) + context.fill(band) } context.restoreGState() @@ -466,7 +527,10 @@ public class GutterView: NSView { /// Empty (caret) selections route through `textLineForOffset` so the caret at the very end of /// the document still highlights the last line — the IndexSet path used for ranged selections /// is half-open and would otherwise drop that case. - internal func highlightedLineIDs() -> Set { + /// + /// A ranged selection contributes only the lines inside `drawnRange`, when given, so a draw after Select All + /// walks the lines it draws and not every line of the document. + internal func highlightedLineIDs(in drawnRange: NSRange? = nil) -> Set { guard let textView = textView, let selectionManager = textView.selectionManager else { return [] } var ids: Set = [] for selection in selectionManager.textSelections { @@ -475,7 +539,9 @@ public class GutterView: NSView { ids.insert(line.data.id) } } else { - for linePosition in textView.layoutManager.lineStorage.linesInRange(selection.range) { + let range = drawnRange.map { selection.range.intersection($0) } ?? selection.range + guard let range, range.length > 0 else { continue } + for linePosition in textView.layoutManager.lineStorage.linesInRange(range) { ids.insert(linePosition.data.id) } } @@ -489,23 +555,21 @@ public class GutterView: NSView { /// - dirtyRect: A rect to draw in, received from ``draw(_:)``. private func drawLineNumbers(_ context: CGContext, dirtyRect: NSRect) { guard let textView = textView else { return } - var attributes: [NSAttributedString.Key: Any] = [.font: font] - let highlightedIDs = highlightedLineIDs() + let highlightedIDs = highlightedLineIDs(in: textView.layoutManager.textRange(covering: dirtyRect)) + // Resolved once per pass in the drawing appearance, so a cached shape never carries another appearance's + // colour. + let numberColor = textColor.safeCGColor + let highlightedNumberColor = (selectedLineTextColor ?? textColor).safeCGColor context.saveGState() context.clip(to: dirtyRect) context.textMatrix = CGAffineTransform(scaleX: 1, y: -1) for linePosition in textView.layoutManager.linesStartingAt(dirtyRect.minY, until: dirtyRect.maxY) { - if highlightedIDs.contains(linePosition.data.id) { - attributes[.foregroundColor] = selectedLineTextColor ?? textColor - } else { - attributes[.foregroundColor] = textColor - } - - let ctLine = CTLineCreateWithAttributedString( - NSAttributedString(string: "\(linePosition.index + 1)", attributes: attributes) + let ctLine = shapedLineNumber( + linePosition.index + 1, + color: highlightedIDs.contains(linePosition.data.id) ? highlightedNumberColor : numberColor ) let fragment: LineFragment? = linePosition.data.lineFragments.first?.data var ascent: CGFloat = 0 @@ -525,6 +589,24 @@ public class GutterView: NSView { context.restoreGState() } + private func shapedLineNumber(_ number: Int, color: CGColor) -> CTLine { + let key = ShapedLineNumberKey(number: number, color: color) + if let shaped = shapedLineNumbers[key] { + return shaped + } + if shapedLineNumbers.count >= Self.shapedLineNumberLimit { + shapedLineNumbers.removeAll(keepingCapacity: true) + } + let shaped = CTLineCreateWithAttributedString( + NSAttributedString( + string: "\(number)", + attributes: [.font: font, .foregroundColor: NSColor(cgColor: color) ?? textColor] + ) + ) + shapedLineNumbers[key] = shaped + return shaped + } + override public func setNeedsDisplay(_ invalidRect: NSRect) { updateWidthIfNeeded() super.setNeedsDisplay(invalidRect) @@ -536,11 +618,12 @@ public class GutterView: NSView { } context.saveGState() drawBackground(context, dirtyRect: dirtyRect) - drawSelectedLines(context) + drawSelectedLines(context, dirtyRect: dirtyRect) if showLineNumbers { drawLineNumbers(context, dirtyRect: dirtyRect) } context.restoreGState() + noteSelectionDrawn(in: dirtyRect) } deinit { diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/SupportingViews/SourceEditorTextView.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/SupportingViews/SourceEditorTextView.swift index 3d1549cdfd..793bd633d0 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/SupportingViews/SourceEditorTextView.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/SupportingViews/SourceEditorTextView.swift @@ -16,7 +16,13 @@ final class SourceEditorTextView: TextView { var statementHighlightRange: NSRange? { didSet { guard statementHighlightRange != oldValue else { return } - needsDisplay = true + // Only the lines the band leaves and the lines it covers now change, as a caret move redraws only its + // own lines. A band over a 10,000-line statement is two line lookups here, not a walk of every line. + for range in [oldValue, statementHighlightRange].compactMap({ $0 }) { + if let rect = linesRect(covering: range) { + setNeedsDisplay(rect) + } + } } } @@ -123,14 +129,29 @@ final class SourceEditorTextView: TextView { return } + // Only the part of the statement on the lines being drawn, so a tile pays for its own lines and not for + // every line of a statement that runs far past it. + guard let drawnRange = layoutManager.textRange(covering: dirtyRect), + let visibleRange = range.intersection(drawnRange), + visibleRange.length > 0 else { + return + } + context.saveGState() context.setFillColor(statementHighlightColor.safeCGColor) - for rect in layoutManager.rectsFor(range: range) where rect.intersects(dirtyRect) { + for rect in layoutManager.rectsFor(range: visibleRange) where rect.intersects(dirtyRect) { context.fill(rect.pixelAligned) } context.restoreGState() } + // The full-width band of the lines a range starts and ends on, and every line between. + private func linesRect(covering range: NSRange) -> CGRect? { + guard let first = layoutManager.textLineForOffset(range.location) else { return nil } + let last = layoutManager.textLineForOffset(max(range.location, NSMaxRange(range) - 1)) ?? first + return CGRect(x: 0, y: first.yPos, width: frame.width, height: last.yPos + last.height - first.yPos) + } + private func drawExecutionLine(in dirtyRect: NSRect) { guard let executionLine, let line = layoutManager.textLineForIndex(executionLine - 1), diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Draw.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Draw.swift index 317c4b8c9f..702c663f1b 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Draw.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Draw.swift @@ -28,6 +28,7 @@ extension TextSelectionManager { } } context.restoreGState() + noteSelectionsDrawn(in: rect) } /// Draws a highlighted line in the given rect. diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Move.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Move.swift index 49b516b4a6..b574d0a0a6 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Move.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Move.swift @@ -30,7 +30,7 @@ extension TextSelectionManager { ) } updateSelectionViews() - delegate?.setNeedsDisplay() + setNeedsDisplayForSelections() notifySelectionChanged() } diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Update.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Update.swift index e884ddcca6..80cf6b4c3e 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Update.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager+Update.swift @@ -49,6 +49,9 @@ public extension TextSelectionManager { func notifyAfterEdit(force: Bool = false) { updateSelectionViews(force: force) + // An edit moves the selections whether or not a caret view moved, and a view that is not first responder has + // no caret view at all. + setNeedsDisplayForSelections() notifySelectionChanged() } } diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager.swift index 6a4114bb04..0ebc4e6a58 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextSelectionManager/TextSelectionManager.swift @@ -11,6 +11,8 @@ public protocol TextSelectionManagerDelegate: AnyObject { var visibleTextRange: NSRange? { get } func setNeedsDisplay() + /// Redraws one part of the view, as `NSView.setNeedsDisplay(_:)` does. + func setNeedsDisplay(_ invalidRect: NSRect) func estimatedLineHeight() -> CGFloat } @@ -73,6 +75,9 @@ public class TextSelectionManager: NSObject { weak var textView: TextView? weak var delegate: TextSelectionManagerDelegate? var cursorTimer: CursorTimer + // Where the selections last drew their caret line band or their fill, so a move redraws only there and where + // they are now, the way `NSTextView` redraws only the lines an insertion point leaves and enters. + private var drawnSelectionRects: [CGRect] = [] public init( layoutManager: TextLayoutManager, @@ -102,7 +107,7 @@ public class TextSelectionManager: NSObject { selection.suggestedXPos = layoutManager?.rectForOffset(range.location)?.minX textSelections = [selection] updateSelectionViews() - delegate?.setNeedsDisplay() + setNeedsDisplayForSelections() notifySelectionChanged() } @@ -125,7 +130,7 @@ public class TextSelectionManager: NSObject { return selection } updateSelectionViews() - delegate?.setNeedsDisplay() + setNeedsDisplayForSelections() if oldRanges != textSelections.map(\.range) { notifySelectionChanged() @@ -156,7 +161,7 @@ public class TextSelectionManager: NSObject { updateSelectionViews() notifySelectionChanged() - delegate?.setNeedsDisplay() + setNeedsDisplayForSelections() } /// The single place a selection change is announced, to observers and to assistive clients alike. @@ -185,7 +190,10 @@ public class TextSelectionManager: NSObject { for textSelection in textSelections { if textSelection.range.isEmpty { if showsInsertionPoint { - didUpdate = didUpdate || repositionCursorSelection(textSelection: textSelection) + // Repositioned before the result is folded in, or every caret after the first that moved would + // keep its old place. + let didReposition = repositionCursorSelection(textSelection: textSelection) + didUpdate = didUpdate || didReposition } else if textSelection.view != nil { textSelection.view?.removeFromSuperview() textSelection.view = nil @@ -199,7 +207,7 @@ public class TextSelectionManager: NSObject { } if didUpdate || force { - delegate?.setNeedsDisplay() + setNeedsDisplayForSelections() if !skipTimerReset { cursorTimer.resetTimer() resetSystemCursorTimers() @@ -290,6 +298,53 @@ public class TextSelectionManager: NSObject { /// The view reference is cleared as well as detached: `updateSelectionViews` only /// re-adds a cursor on the `view == nil` branch, so leaving a dangling reference here /// meant the caret never came back after the text view resigned first responder. + /// Redraws where the selections drew last time and where they draw now, and nothing else. + /// + /// A caret draws the band behind its whole line and a range fills the lines it covers, so each is bounded by the + /// full width of those lines. The text under them is drawn by the line fragment views, which a move leaves alone. + func setNeedsDisplayForSelections() { + let current = selectionRects() + guard let delegate else { + drawnSelectionRects = current + return + } + let dirty = drawnSelectionRects + current + drawnSelectionRects = current + guard dirty.count <= Self.separatelyInvalidatedRectLimit else { + delegate.setNeedsDisplay(dirty.reduce(CGRect.null) { $0.union($1) }) + return + } + for rect in dirty { + delegate.setNeedsDisplay(rect) + } + } + + // Past this many carets one rect covering them all costs AppKit less than tracking each one. + private static let separatelyInvalidatedRectLimit = 64 + + /// Remembers where a draw pass put the selections, which is not always where the last change left them: a layout + /// pass can move their lines and redraw them there without any selection changing. + func noteSelectionsDrawn(in rect: NSRect) { + for drawn in selectionRects() where drawn.intersects(rect) && !drawnSelectionRects.contains(drawn) { + drawnSelectionRects.append(drawn) + } + if drawnSelectionRects.count > Self.separatelyInvalidatedRectLimit { + drawnSelectionRects = [drawnSelectionRects.reduce(CGRect.null) { $0.union($1) }] + } + } + + private func selectionRects() -> [CGRect] { + guard let layoutManager else { return [] } + let width = max(textView?.frame.width ?? 0, layoutManager.maxLineWidth + layoutManager.edgeInsets.horizontal) + return textSelections.compactMap { selection in + guard let first = layoutManager.textLineForOffset(selection.range.location) else { return nil } + let last = selection.range.isEmpty + ? first + : layoutManager.textLineForOffset(selection.range.max) ?? first + return CGRect(x: 0, y: first.yPos, width: width, height: last.yPos + last.height - first.yPos) + } + } + func removeCursors() { cursorTimer.stopTimer() for textSelection in textSelections { diff --git a/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/GutterHighlightTests.swift b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/GutterHighlightTests.swift index 8714034878..334181bcb0 100644 --- a/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/GutterHighlightTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/GutterHighlightTests.swift @@ -60,4 +60,18 @@ struct GutterHighlightTests { #expect(highlighted.contains(firstID)) #expect(!highlighted.contains(lastID)) } + + @Test("A ranged selection marks only the lines being drawn") + func rangedSelectionIsBoundedToTheDrawnLines() throws { + let controller = Mock.loadedTextViewController() + setText((0..<2_000).map { "SELECT \($0);" }.joined(separator: "\n"), on: controller) + controller.textView.selectionManager.setSelectedRange(controller.textView.documentRange) + let tenthLine = try #require(controller.textView.layoutManager.textLineForIndex(9)) + + let drawn = NSRange(location: 0, length: tenthLine.range.max) + let highlighted = controller.gutterView.highlightedLineIDs(in: drawn) + + #expect(highlighted.count == 10) + #expect(controller.gutterView.highlightedLineIDs().count == 2_000) + } } diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SelectionBehaviourTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SelectionBehaviourTests.swift index 9346a0e56b..7cb560a72e 100644 --- a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SelectionBehaviourTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SelectionBehaviourTests.swift @@ -7,6 +7,7 @@ private final class InvalidationSpy: TextSelectionManagerDelegate { private(set) var setNeedsDisplayCount = 0 func setNeedsDisplay() { setNeedsDisplayCount += 1 } + func setNeedsDisplay(_ invalidRect: NSRect) { setNeedsDisplayCount += 1 } func estimatedLineHeight() -> CGFloat { 14.0 } } @@ -190,6 +191,48 @@ struct SelectionBehaviourTests { #expect(spy.setNeedsDisplayCount > afterThird) } + @Test("A caret move redraws the line it leaves and the line it enters, not the whole view") + func caretMoveRedrawsOnlyItsLines() throws { + let text = (0..<400).map { "SELECT column_\($0) FROM some_table;" }.joined(separator: "\n") + let textView = RecordingTextView(string: text) + textView.font = .monospacedSystemFont(ofSize: 14, weight: .regular) + textView.wrapLines = false + textView.frame = NSRect(x: 0, y: 0, width: 900, height: 6_000) + textView.updateFrameIfNeeded() + textView.layoutManager.invalidateLayoutForRange(textView.documentRange) + textView.layoutManager.layoutLines(in: NSRect(x: 0, y: 0, width: 900, height: 6_000)) + let manager: TextSelectionManager = textView.selectionManager + manager.setSelectedRange(NSRange(location: 3, length: 0)) + textView.invalidatedRects.removeAll() + + let target = try #require(textView.layoutManager.textLineForIndex(200)) + manager.setSelectedRange(NSRange(location: target.range.location + 2, length: 0)) + + let leftLine = try #require(textView.layoutManager.textLineForIndex(0)) + let lineHeight = leftLine.height + #expect(!textView.invalidatedRects.isEmpty) + #expect(textView.invalidatedRects.allSatisfy { $0.height <= lineHeight + 0.5 }) + #expect(textView.invalidatedRects.contains { $0.minY <= leftLine.yPos && $0.maxY >= leftLine.yPos + lineHeight }) + #expect(textView.invalidatedRects.contains { $0.minY <= target.yPos && $0.maxY >= target.yPos + target.height }) + } + + @Test("Moving several carets moves every one of them, not only the first that moved") + func everyCaretRepositions() throws { + let textView = makeLaidOutTextView("alpha beta gamma\ndelta epsilon zeta\neta theta iota") + textView.isFirstResponder = true + let manager: TextSelectionManager = textView.selectionManager + manager.setSelectedRanges([NSRange(location: 1, length: 0), NSRange(location: 20, length: 0)]) + + manager.moveSelections(direction: .forward, destination: .character) + + #expect(manager.textSelections.map(\.range.location) == [2, 21]) + for selection in manager.textSelections { + let view = try #require(selection.view) + let expected = try #require(textView.layoutManager.rectForOffset(selection.range.location)) + #expect(view.frame.origin == expected.origin) + } + } + @Test("Laying out a band that was never laid out invalidates the view that draws over it") func layoutInvalidatesTheLayoutView() { let text = (0..<400).map { "SELECT column_\($0) FROM some_table;" }.joined(separator: "\n") diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SelectionGeometryTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SelectionGeometryTests.swift index 73ea42510b..b66a52c64f 100644 --- a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SelectionGeometryTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SelectionGeometryTests.swift @@ -12,6 +12,7 @@ private final class FixedViewportDelegate: TextSelectionManagerDelegate { private(set) var setNeedsDisplayCount = 0 func setNeedsDisplay() { setNeedsDisplayCount += 1 } + func setNeedsDisplay(_ invalidRect: NSRect) { setNeedsDisplayCount += 1 } func estimatedLineHeight() -> CGFloat { 14.0 } } From 71f1f58cf7a43bbdddfb397cf1f0d3b619d88ce4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 26 Nov 2026 03:19:06 +0700 Subject: [PATCH 2/2] docs(changelog): add the fragment for #4570 --- apple/changelog.d/4570.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 apple/changelog.d/4570.fixed.md diff --git a/apple/changelog.d/4570.fixed.md b/apple/changelog.d/4570.fixed.md new file mode 100644 index 0000000000..0561720f66 --- /dev/null +++ b/apple/changelog.d/4570.fixed.md @@ -0,0 +1 @@ +With several carets in the SQL editor, moving them could leave every caret after the first drawn in its old place.