From 2a995b349eab532a77a29aa1c2f8002e010fdea8 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 10:46:04 +0700 Subject: [PATCH 1/5] perf(editor): lay out only the first band, count AX characters in UTF-16, defer hidden find, reuse the band's statement index --- .../SQLCompletionWindow.swift | 34 ++- .../SQLCompletionWindowTests.swift | 115 +++++++++ .../Find/FindViewController+Toggle.swift | 1 + .../FindPanelViewModel+Emphasis.swift | 2 + .../ViewModel/FindPanelViewModel+Find.swift | 38 ++- .../ViewModel/FindPanelViewModel+Move.swift | 1 + .../FindPanelViewModel+Replace.swift | 3 + .../Find/ViewModel/FindPanelViewModel.swift | 14 +- .../TextView/TextView+Accessibility.swift | 2 +- .../TextView/TextView.swift | 3 +- .../Utils/ViewReuseQueue.swift | 41 ++- ...TextViewControllerOpeningLayoutTests.swift | 58 +++++ .../FindPanelHiddenSearchTests.swift | 127 ++++++++++ .../AccessibilityTests.swift | 10 + .../EmphasisGeometryUpdateTests.swift | 6 +- .../TextLayoutManagerFragmentViewTests.swift | 21 ++ .../ViewReuseQueueTests.swift | 69 +++++ .../Mongo/MongoCompletionService.swift | 8 +- .../Autocomplete/QueryCompletionService.swift | 13 +- .../Autocomplete/SQLCompletionService.swift | 17 +- .../Views/Editor/EditorEventRouter.swift | 21 ++ .../Views/Editor/QueryCompletionAdapter.swift | 11 +- .../Views/Editor/SQLEditorController.swift | 3 + .../Views/Editor/SQLEditorCoordinator.swift | 26 ++ .../Views/Editor/StatementRunController.swift | 78 +++--- ...ainContentCoordinator+AIQueryActions.swift | 31 ++- ...SQLCompletionServiceEmptyPrefixTests.swift | 10 +- ...LCompletionServiceStatementHintTests.swift | 68 +++++ ...QueryCompletionAdapterLifecycleTests.swift | 139 +++++++++- .../Editor/QueryCompletionRankingTests.swift | 6 +- .../Editor/StatementAtCaretRoutingTests.swift | 239 ++++++++++++++++++ .../Editor/StatementRunControllerTests.swift | 135 ++++++++++ 32 files changed, 1245 insertions(+), 105 deletions(-) create mode 100644 apple/Packages/TableProEditor/Tests/TableProEditorKitTests/Controller/TextViewControllerOpeningLayoutTests.swift create mode 100644 apple/Packages/TableProEditor/Tests/TableProEditorKitTests/FindPanelHiddenSearchTests.swift create mode 100644 apple/Packages/TableProEditor/Tests/TableProTextEngineTests/ViewReuseQueueTests.swift create mode 100644 apple/TableProTests/Core/Autocomplete/SQLCompletionServiceStatementHintTests.swift create mode 100644 apple/TableProTests/Views/Editor/StatementAtCaretRoutingTests.swift diff --git a/apple/Packages/TableProCore/Sources/TableProAutocomplete/SQLCompletionWindow.swift b/apple/Packages/TableProCore/Sources/TableProAutocomplete/SQLCompletionWindow.swift index 88fe08e063..b98b40e69e 100644 --- a/apple/Packages/TableProCore/Sources/TableProAutocomplete/SQLCompletionWindow.swift +++ b/apple/Packages/TableProCore/Sources/TableProAutocomplete/SQLCompletionWindow.swift @@ -33,21 +33,43 @@ public enum SQLCompletionWindow { let located = SQLStatementScanner.locatedStatementAtCursor( in: source as String, cursorPosition: caret, grammar: grammar ) - let end = max(caret, min(NSMaxRange(located.range), caret + radius)) - var start = min(located.offset, caret) + return cut(source, around: caret, statement: located.range, grammar: grammar) + } + + // For a caller that already holds the caret's statement, located on this text with this grammar. + @concurrent + public static func cut( + _ text: String, + around offset: Int, + statement: NSRange, + grammar: SQLLexicalGrammar + ) async -> (text: String, start: Int)? { + cut(text as NSString, around: offset, statement: statement, grammar: grammar) + } + + // Costs the statement up to the end of the cut, not the document before it. + public static func cut( + _ text: NSString, + around offset: Int, + statement: NSRange, + grammar: SQLLexicalGrammar + ) -> (text: String, start: Int)? { + let length = text.length + let caret = min(max(offset, 0), length) + let end = max(caret, min(NSMaxRange(statement), caret + radius, length)) + var start = min(max(statement.location, 0), caret) if caret - start > radius { - guard let resumed = codeStart(in: source, units: units, from: start, around: caret, grammar: grammar) else { + guard let resumed = codeStart(in: text, from: start, around: caret, grammar: grammar) else { return nil } start = resumed } - return (source.substring(with: NSRange(location: start, length: end - start)), start) + return (text.substring(with: NSRange(location: start, length: end - start)), start) } // A start glued to the word before it is passed over: `E'` and `$$` read differently with nothing in front. private static func codeStart( in text: NSString, - units: [UInt16], from statementStart: Int, around caret: Int, grammar: SQLLexicalGrammar @@ -58,7 +80,7 @@ public enum SQLCompletionWindow { while index < caret { if index >= target { if firstCodePosition == nil { firstCodePosition = index } - if !SqlDollarQuote.isIdentifierContinuation(units[index - 1]) { return index } + if !SqlDollarQuote.isIdentifierContinuation(text.character(at: index - 1)) { return index } } guard let span = SQLNonCodeSpan.span(at: index, in: text, grammar: grammar), span.kind != .executableComment else { diff --git a/apple/Packages/TableProCore/Tests/TableProAutocompleteTests/SQLCompletionWindowTests.swift b/apple/Packages/TableProCore/Tests/TableProAutocompleteTests/SQLCompletionWindowTests.swift index 8246cab6d2..8c67992d96 100644 --- a/apple/Packages/TableProCore/Tests/TableProAutocompleteTests/SQLCompletionWindowTests.swift +++ b/apple/Packages/TableProCore/Tests/TableProAutocompleteTests/SQLCompletionWindowTests.swift @@ -9,6 +9,45 @@ struct LongSpanCase: Sendable, CustomTestStringConvertible { let engine: String } +struct LocatedCutCase: Sendable, CustomTestStringConvertible { + let testDescription: String + let text: String + let engine: String +} + +private final class CountingString: NSString { + private let base: NSString + private(set) var unitsRead = 0 + + init(_ string: String) { + base = string as NSString + super.init() + } + + override init() { + base = "" + super.init() + } + + required init?(coder: NSCoder) { + nil + } + + override var length: Int { + base.length + } + + override func character(at index: Int) -> unichar { + unitsRead += 1 + return base.character(at: index) + } + + override func getCharacters(_ buffer: UnsafeMutablePointer, range: NSRange) { + unitsRead += range.length + base.getCharacters(buffer, range: range) + } +} + struct SQLCompletionWindowTests { static let notes = String(repeating: "notes about the nightly load and its retries\n", count: 140) static let body = String(repeating: " PERFORM pg_sleep(0);\n", count: 300) @@ -132,4 +171,80 @@ struct SQLCompletionWindowTests { func statementBreak(text: String, offset: Int, suppressed: Bool) { #expect(SQLCompletionTriggerPolicy.suppressesAfterStatementBreak(in: text as NSString, at: offset) == suppressed) } + + static let locatedCutCases: [LocatedCutCase] = [ + LocatedCutCase(testDescription: "short text", text: "SELECT * FROM or", engine: "ANSI"), + LocatedCutCase(testDescription: "long statement", text: String(repeating: "x", count: 12_000), engine: "ANSI"), + LocatedCutCase( + testDescription: "last of many statements", + text: "SELECT 1;\n" + String(repeating: "SELECT 2;\n", count: 2_000) + "SELECT * FROM or", + engine: "ANSI" + ), + LocatedCutCase( + testDescription: "token boundary", + text: "SELECT " + String(repeating: "alpha, ", count: 1_000) + "o FROM t WHERE x", + engine: "ANSI" + ), + LocatedCutCase( + testDescription: "quoted name", + text: "SELECT * FROM \"" + String(repeating: "n", count: 6_000) + " Det", + engine: "PostgreSQL" + ), + LocatedCutCase(testDescription: "long block comment", text: "/*\n" + notes + "SELECT * FROM or", engine: "PostgreSQL"), + LocatedCutCase( + testDescription: "dollar body", + text: "CREATE FUNCTION f() RETURNS void AS $$\nBEGIN\n" + body + " SELECT * FROM or", + engine: "PostgreSQL" + ), + LocatedCutCase(testDescription: "open string", text: "INSERT INTO notes VALUES ('" + notes + "SELECT * FROM or", engine: "MySQL"), + LocatedCutCase( + testDescription: "code after a dollar body", + text: "CREATE FUNCTION f() RETURNS void AS $$\nBEGIN\n" + body + "END\n$$ LANGUAGE plpgsql;\nSELECT * FROM or", + engine: "PostgreSQL" + ), + LocatedCutCase( + testDescription: "code after a closed string", + text: "INSERT INTO notes VALUES ('" + notes + "');\nSELECT * FROM or", + engine: "MySQL" + ), + LocatedCutCase( + testDescription: "comment across the cut", + text: "SELECT a, /* " + notes + " it's */ b FROM orders WHERE st", + engine: "PostgreSQL" + ), + LocatedCutCase( + testDescription: "MySQL delimiter", + text: "DELIMITER //\nCREATE PROCEDURE p() BEGIN SELECT 1; END //\nDELIMITER ;\nSELECT * FROM or", + engine: "MySQL" + ) + ] + + @Test("A cut from the located statement equals a cut from the whole text", arguments: locatedCutCases) + func cutFromALocatedStatementEqualsTheWholeTextCut(_ example: LocatedCutCase) { + let text = example.text as NSString + let grammar = SQLLexicalGrammar.engine(example.engine) + let carets = Set([0, text.length / 3, text.length / 2, text.length - 1, text.length].filter { $0 >= 0 }) + for caret in carets.sorted() { + let located = SQLStatementScanner.locatedStatementAtCursor( + in: example.text, cursorPosition: caret, grammar: grammar + ) + let whole = SQLCompletionWindow.cut(text, around: caret, grammar: grammar) + let fromStatement = SQLCompletionWindow.cut(text, around: caret, statement: located.range, grammar: grammar) + #expect(fromStatement?.text == whole?.text, "caret \(caret)") + #expect(fromStatement?.start == whole?.start, "caret \(caret)") + } + } + + @Test("A cut from the located statement near the end of a long script reads only that statement and the radius") + func cutFromALocatedStatementReadsOnlyItsStatement() { + let script = String(repeating: "SELECT id, name FROM users WHERE id = 1;\n", count: 10_000) + "SELECT * FROM or" + let text = CountingString(script) + let caret = text.length + let located = SQLStatementScanner.locatedStatementAtCursor(in: script, cursorPosition: caret, grammar: .ansi) + + let window = SQLCompletionWindow.cut(text, around: caret, statement: located.range, grammar: .ansi) + + #expect(window?.text == "\nSELECT * FROM or") + #expect(text.unitsRead <= located.range.length + SQLCompletionWindow.radius) + } } diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/FindViewController+Toggle.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/FindViewController+Toggle.swift index 504634c73a..a5577240f1 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/FindViewController+Toggle.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/FindViewController+Toggle.swift @@ -36,6 +36,7 @@ extension FindViewController { // Smooth out the animation by placing the find panel just outside the correct position before animating. installFindPanel().isHidden = false + viewModel.refreshMatchesIfStale() findPanelVerticalConstraint?.constant = resolvedTopPadding - viewModel.panelHeight view.layoutSubtreeIfNeeded() diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Emphasis.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Emphasis.swift index 56006a71ee..faba510d50 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Emphasis.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Emphasis.swift @@ -12,6 +12,7 @@ extension FindPanelViewModel { guard let target = target, let emphasisManager = target.textView.emphasisManager else { return } + refreshMatchesIfStale() // Clear existing emphases emphasisManager.removeEmphases(for: EmphasisGroup.find) @@ -32,6 +33,7 @@ extension FindPanelViewModel { } func flashCurrentMatch() { + refreshMatchesIfStale() guard let target = target, let emphasisManager = target.textView.emphasisManager, let currentFindMatchIndex else { diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Find.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Find.swift index 89e3f3c878..73e8f53b83 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Find.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Find.swift @@ -13,10 +13,11 @@ extension FindPanelViewModel { /// Performs a find operation on the find target and updates both the ``findMatches`` array and the emphasis /// manager's emphases. func find() { + staleMatchesCaret = nil findMatches = searchResults().map(\.range) // Find the nearest match to the current cursor position - currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches) + currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches, caret: caretLocation) // Only add emphasis layers if the find panel is focused if isFocused { @@ -28,8 +29,36 @@ extension FindPanelViewModel { /// so the stored matches would otherwise point into text that is gone. func documentDidReplace() { clearMatchEmphases() + if defersSearch, !findText.isEmpty { + staleMatchesCaret = StaleMatchesCaret(location: caretLocation) + return + } + staleMatchesCaret = nil findMatches = searchResults().map(\.range) - currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches) + currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches, caret: caretLocation) + } + + func findAfterEdit() { + if defersSearch { + staleMatchesCaret = StaleMatchesCaret(location: caretLocation) + } else { + find() + } + } + + func refreshMatchesIfStale() { + guard let stale = staleMatchesCaret else { return } + staleMatchesCaret = nil + findMatches = searchResults().map(\.range) + currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches, caret: stale.location) + } + + private var defersSearch: Bool { + !isShowingFindPanel && !isFocused + } + + private var caretLocation: Int? { + target?.cursorPositions.first?.range.location } /// The find text's matches in the document as it is now. Empty when there is no target, no find text, or a @@ -81,13 +110,12 @@ extension FindPanelViewModel { // MARK: - Get Nearest Emphasis Index - private func getNearestEmphasisIndex(matchRanges: [NSRange]) -> Int? { + private func getNearestEmphasisIndex(matchRanges: [NSRange], caret: Int?) -> Int? { // order the array as follows // Found: 1 -> 2 -> 3 -> 4 // Cursor: | // Result: 3 -> 4 -> 1 -> 2 - guard let cursorPosition = target?.cursorPositions.first else { return nil } - let start = cursorPosition.range.location + guard let start = caret else { return nil } var left = 0 var right = matchRanges.count - 1 diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Move.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Move.swift index cc53f77551..765eb58156 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Move.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Move.swift @@ -18,6 +18,7 @@ extension FindPanelViewModel { private func moveMatch(forwards: Bool) { guard let target = target else { return } + refreshMatchesIfStale() guard !findMatches.isEmpty else { showWrapNotification(forwards: forwards, error: true, targetView: target.findPanelTargetView) diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Replace.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Replace.swift index 7ab66e3231..7f4062fd54 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Replace.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel+Replace.swift @@ -15,6 +15,7 @@ extension FindPanelViewModel { /// Matches are searched for again after the edit rather than shifted by hand: a pattern can stop or start matching /// around the replacement, and a stored range past the end of the text is a crash in the text storage. func replace() { + refreshMatchesIfStale() guard let target, canReplace, let index = currentFindMatchIndex, findMatches.indices.contains(index) else { return @@ -52,6 +53,8 @@ extension FindPanelViewModel { /// match is replaced once, so text a replacement inserts is never searched again. func replaceAll() { guard let target, canReplace else { return } + // All searches the text it edits, so matches the panel never showed need no search of their own. + staleMatchesCaret = nil let text = target.textView.string let replacements = searchResults().map { diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel.swift index 6dab00e743..142b9c0180 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Find/ViewModel/FindPanelViewModel.swift @@ -47,6 +47,14 @@ class FindPanelViewModel: ObservableObject { /// Set while Replace or All edits the document, which searches once when the edit is done. var isReplacingMatches = false + // Set when the document changed while the panel was hidden and unfocused. Nothing shows the matches then, so the + // search waits for the next command that reads them and uses the caret the edit left. + var staleMatchesCaret: StaleMatchesCaret? + + struct StaleMatchesCaret { + let location: Int? + } + /// Replace is withheld from a document that is read-only, as the native find bar withholds it. With no target /// there is nothing to edit either way, and Replace and All already do nothing. var canReplace: Bool { @@ -95,11 +103,9 @@ class FindPanelViewModel: ObservableObject { // MARK: - Text Listeners - /// Find target's text content changed, we need to re-search the contents and emphasize results. @objc private func textDidChange() { - // Only update if we have find text if !findText.isEmpty, !isReplacingMatches, !isReplayingUndo { - find() + findAfterEdit() } } @@ -112,7 +118,7 @@ class FindPanelViewModel: ObservableObject { !findText.isEmpty else { return } - find() + findAfterEdit() } private var isReplayingUndo: Bool { diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView+Accessibility.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView+Accessibility.swift index 9158f00fbe..450c7721d4 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView+Accessibility.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView+Accessibility.swift @@ -120,7 +120,7 @@ extension TextView { // MARK: Text Ranges override open func accessibilityNumberOfCharacters() -> Int { - string.count + textStorage.length } override open func accessibilityRange(forLine line: Int) -> NSRange { diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView.swift index de478877c1..ea7eefcd5c 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/TextView/TextView.swift @@ -370,7 +370,8 @@ open class TextView: NSView, NSTextContent { editorUndoManager = CEUndoManager(textView: self) - layoutManager.layoutLines() + // Unhosted, `visibleRect` is infinite, so the default band would be the whole document. + layoutManager.layoutLines(in: bounds) setUpDragGesture() } diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/Utils/ViewReuseQueue.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/Utils/ViewReuseQueue.swift index 8e47af9b3d..0870ce066a 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/Utils/ViewReuseQueue.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/Utils/ViewReuseQueue.swift @@ -45,34 +45,23 @@ public class ViewReuseQueue { usedViews[key] } - /// Removes a view for the given key and enqueues it for reuse. - /// - Parameter key: The key for the view to reuse. - public func enqueueView(forKey key: Key) { - guard let view = usedViews[key] else { return } - if queuedViews.count < usedViews.count { - queuedViews.append(view) - view.frame = .zero - view.isHidden = true - } else { - view.removeFromSuperviewWithoutNeedingDisplay() - } - usedViews.removeValue(forKey: key) - } - - /// Enqueues all views not in the given set. - /// - Parameter outsideSet: The keys who's views should not be enqueued for reuse. + // A queued view stays a hidden subview, so the queue keeps no more views than the pass left in use. Bounded by + // the views in use while they are still being released, a pass that drops most of them kept half. public func enqueueViews(notInSet keys: Set) { - // Get all keys that are currently in "use" but not in the given set, and enqueue them for reuse. - for key in Set(usedViews.keys).subtracting(keys) { - enqueueView(forKey: key) + let released = usedViews.keys.filter { !keys.contains($0) } + let capacity = usedViews.count - released.count + for key in released { + guard let view = usedViews.removeValue(forKey: key) else { continue } + if queuedViews.count < capacity { + queuedViews.append(view) + view.frame = .zero + view.isHidden = true + } else { + view.removeFromSuperviewWithoutNeedingDisplay() + } } - } - - /// Enqueues all views keyed by the given set. - /// - Parameter keys: The keys for all the views that should be enqueued. - public func enqueueViews(in keys: Set) { - for key in keys { - enqueueView(forKey: key) + while queuedViews.count > capacity, let view = queuedViews.popLast() { + view.removeFromSuperviewWithoutNeedingDisplay() } } diff --git a/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/Controller/TextViewControllerOpeningLayoutTests.swift b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/Controller/TextViewControllerOpeningLayoutTests.swift new file mode 100644 index 0000000000..deae37404b --- /dev/null +++ b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/Controller/TextViewControllerOpeningLayoutTests.swift @@ -0,0 +1,58 @@ +import AppKit +@testable import TableProEditorKit +import TableProTextEngine +import Testing + +@MainActor +struct TextViewControllerOpeningLayoutTests { + private let script = (0..<20_000) + .map { "SELECT * FROM table_\($0) WHERE id = \($0);" } + .joined(separator: "\n") + + private func lineFragmentViews(of controller: TextViewController) -> [LineFragmentView] { + controller.textView.subviews.compactMap { $0 as? LineFragmentView } + } + + private func linesInBand(of textView: TextView) -> Int { + guard let manager = textView.layoutManager else { return 0 } + let visible = textView.visibleRect + let minY = max(visible.minY - manager.verticalLayoutPadding, 0) + let maxY = visible.maxY + manager.verticalLayoutPadding + return manager.linesStartingAt(minY, until: maxY).filter { $0.yPos < maxY }.count + } + + // SQLEditorCoordinator loads the view inside the controller's init, before any frame is set. + @Test + func loadingAroundALongScriptLaysOutOnlyTheFirstScreen() { + let controller = TextViewController( + string: script, + language: .sql, + configuration: Mock.config(), + cursorPositions: [], + highlightProviders: [] + ) + + controller.loadView() + + #expect(lineFragmentViews(of: controller).count < 100) + } + + @Test + func sizingTheLoadedEditorKeepsViewsToTheBand() { + let controller = TextViewController( + string: script, + language: .sql, + configuration: Mock.config(), + cursorPositions: [], + highlightProviders: [] + ) + controller.loadView() + + controller.view.frame = NSRect(x: 0, y: 0, width: 1_000, height: 1_000) + controller.view.layoutSubtreeIfNeeded() + + let bandLines = linesInBand(of: controller.textView) + #expect(bandLines > 0) + #expect(lineFragmentViews(of: controller).count <= bandLines * 2) + } +} diff --git a/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/FindPanelHiddenSearchTests.swift b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/FindPanelHiddenSearchTests.swift new file mode 100644 index 0000000000..df3d14bd1a --- /dev/null +++ b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/FindPanelHiddenSearchTests.swift @@ -0,0 +1,127 @@ +import AppKit +import Combine +@testable import TableProEditorKit +import TableProTextEngine +import Testing + +// A term kept after the panel closes used to search the whole document on every edit and every document swap. +@MainActor +struct FindPanelHiddenSearchTests { + private final class SearchCounter { + var count = 0 + private var observation: AnyCancellable? + + init(_ model: FindPanelViewModel) { + observation = model.$findMatches.dropFirst().sink { [weak self] _ in self?.count += 1 } + } + } + + private func editor(_ text: String, find term: String, caret: Int = 0) throws -> (TextViewController, FindPanelViewModel) { + let controller = Mock.loadedTextViewController(string: text) + controller.setCursorPositions([CursorPosition(range: NSRange(location: caret, length: 0))]) + let model = try #require(controller.findViewController?.viewModel) + model.findText = term + model.find() + return (controller, model) + } + + private func append(_ text: String, to controller: TextViewController) { + let end = (controller.textView.string as NSString).length + controller.textView.replaceCharacters(in: NSRange(location: end, length: 0), with: text) + } + + private func selection(_ controller: TextViewController) -> [NSRange] { + controller.textView.selectionManager.textSelections.map(\.range) + } + + private func drainMainQueue() async { + await withCheckedContinuation { continuation in + DispatchQueue.main.async { continuation.resume() } + } + } + + @Test + func editsWithThePanelHiddenRunNoSearch() throws { + let (controller, model) = try editor("a a a", find: "a") + let searches = SearchCounter(model) + + for _ in 0..<100 { + append(" a", to: controller) + } + + #expect(searches.count == 0) + + model.moveToNextMatch() + + #expect(searches.count == 1) + #expect(model.matchCount == 103) + } + + @Test + func undoWithThePanelHiddenRunsNoSearch() throws { + let (controller, model) = try editor("a a a", find: "a") + append(" a", to: controller) + let searches = SearchCounter(model) + + controller.textView.undoManager?.undo() + + #expect(controller.textView.string == "a a a") + #expect(searches.count == 0) + } + + // The search a hidden edit skipped picks its current match from the caret that edit left, as it did when it ran + // on the edit, so a caret moved since then does not change where Find Next goes. + @Test + func findNextAfterHiddenEditsGoesOnFromTheCaretTheEditLeft() throws { + let (controller, model) = try editor("a a a a", find: "a", caret: 0) + for _ in 0..<10 { + append(" b", to: controller) + } + let end = (controller.textView.string as NSString).length + controller.setCursorPositions([CursorPosition(range: NSRange(location: end, length: 0))]) + + model.moveToNextMatch() + + #expect(model.currentFindMatchIndex == 1) + #expect(selection(controller) == [NSRange(location: 2, length: 1)]) + } + + @Test + func showingThePanelAfterHiddenEditsCountsTheTextAsItIs() throws { + let (controller, model) = try editor("a a a", find: "a") + for _ in 0..<5 { + append(" a", to: controller) + } + + controller.findViewController?.showFindPanel(animated: false) + + #expect(model.matchCount == 8) + } + + @Test + func replacingTheDocumentWithThePanelHiddenRunsNoSearch() async throws { + let (controller, model) = try editor("a a a", find: "a") + let searches = SearchCounter(model) + + controller.setText("a b a b") + await drainMainQueue() + + #expect(searches.count == 0) + + controller.findViewController?.showFindPanel(animated: false) + + #expect(model.matchCount == 2) + } + + @Test + func editsWithThePanelShownStillSearch() throws { + let (controller, model) = try editor("a a a", find: "a") + controller.findViewController?.showFindPanel(animated: false) + let searches = SearchCounter(model) + + append(" a", to: controller) + + #expect(searches.count == 1) + #expect(model.matchCount == 4) + } +} diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/AccessibilityTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/AccessibilityTests.swift index dc2643ba23..246732ebef 100644 --- a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/AccessibilityTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/AccessibilityTests.swift @@ -69,6 +69,16 @@ struct AccessibilityTests { #expect(textView.accessibilityNumberOfCharacters() == sampleText.count) } + @Test + func accessibilityNumberOfCharactersCountsUTF16Units() { + let text = "a\u{1F600}e\u{0301}" + let view = TextView(string: text) + let count = view.accessibilityNumberOfCharacters() + #expect(count == (text as NSString).length) + #expect(count == 5) + #expect(view.accessibilityString(for: NSRange(location: 0, length: count)) == text) + } + @Test func accessibilityStringForRange() { let range = NSRange(location: 0, length: 6) diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/EmphasisGeometryUpdateTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/EmphasisGeometryUpdateTests.swift index 77c78c441b..d135a61204 100644 --- a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/EmphasisGeometryUpdateTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/EmphasisGeometryUpdateTests.swift @@ -255,10 +255,8 @@ struct EmphasisGeometryUpdateTests { return scrollView } - /// A text view with no scroll view, holding text none of which has been laid out yet. - /// - /// `visibleRect` is infinite without a scroll view, so a text view built around its text lays all of it out on - /// the spot. The text has to arrive after the frame does for any of it to be left unlaid. + // A text view built around its text lays out its first band in init, so the text arrives after the frame to + // leave every line unlaid. private func makeTallTextView(string: String) -> TextView { let textView = TextView(string: "", wrapLines: false) textView.frame = NSRect(x: 0, y: 0, width: 1_000, height: 20_000) diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/LayoutManager/TextLayoutManagerFragmentViewTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/LayoutManager/TextLayoutManagerFragmentViewTests.swift index 21079ffe1d..f9ae224688 100644 --- a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/LayoutManager/TextLayoutManagerFragmentViewTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/LayoutManager/TextLayoutManagerFragmentViewTests.swift @@ -183,6 +183,27 @@ struct TextLayoutManagerFragmentViewTests { } } + // Unhosted, `visibleRect` is infinite, so a text view built around its text used to lay out every line. + @Test + func aTextViewBuiltAroundALongDocumentLaysOutOnlyTheFirstBand() throws { + let text = (0..<5_000).map { "SELECT * FROM table_\($0) WHERE id = \($0);" }.joined(separator: "\n") + let view = TextView(string: text, wrapLines: false) + let manager = try #require(view.layoutManager) + let firstBand = layoutBand(for: .zero, of: manager) + + expectViewsMatchBand(firstBand, of: manager, in: view) + #expect(fragmentViews(of: view).count == fragments(in: firstBand, of: manager).count) + + let scrollView = NSScrollView(frame: NSRect(origin: .zero, size: Self.viewportSize)) + scrollView.documentView = view + view.updateFrameIfNeeded() + view.layout() + + let band = layoutBand(for: view.visibleRect, of: manager) + expectViewsMatchBand(band, of: manager, in: view) + #expect(fragmentViews(of: view).count <= fragments(in: band, of: manager).count * 2) + } + /// A document that does not wrap keeps one view per line in the band, and those views follow their lines when an /// edit above the viewport moves them. @Test diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/ViewReuseQueueTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/ViewReuseQueueTests.swift new file mode 100644 index 0000000000..5051564907 --- /dev/null +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/ViewReuseQueueTests.swift @@ -0,0 +1,69 @@ +import AppKit +@testable import TableProTextEngine +import Testing + +@MainActor +struct ViewReuseQueueTests { + private let superview = NSView() + private let queue = ViewReuseQueue() + + private func place(_ keys: Range) { + for key in keys { + let view = queue.getOrCreateView(forKey: key) { NSView() } + if view.superview == nil { + superview.addSubview(view) + } + } + } + + @Test + func releasingMostViewsQueuesOnlyAsManyAsStayInUse() { + place(0..<1_000) + + queue.enqueueViews(notInSet: Set(0..<10)) + + #expect(queue.usedViews.count == 10) + #expect(queue.queuedViews.count <= 10) + #expect(superview.subviews.count <= 20) + #expect(queue.queuedViews.allSatisfy { $0.isHidden && $0.superview === superview }) + } + + @Test + func theNextPassReusesTheQueuedViews() { + place(0..<1_000) + queue.enqueueViews(notInSet: Set(0..<10)) + let queued = Set(queue.queuedViews.map { ObjectIdentifier($0) }) + #expect(!queued.isEmpty) + + place(1_000..<(1_000 + queued.count)) + + let reused = (1_000..<(1_000 + queued.count)).compactMap { queue.getView(forKey: $0) } + #expect(Set(reused.map { ObjectIdentifier($0) }) == queued) + #expect(reused.allSatisfy { !$0.isHidden }) + #expect(queue.queuedViews.isEmpty) + } + + @Test + func keepingEveryViewReleasesNone() { + place(0..<100) + + queue.enqueueViews(notInSet: Set(0..<100)) + + #expect(queue.usedViews.count == 100) + #expect(queue.queuedViews.isEmpty) + #expect(superview.subviews.count == 100) + } + + @Test + func aQueueLeftFromATallerBandShrinksToTheViewsInUse() { + place(0..<100) + queue.enqueueViews(notInSet: Set(0..<50)) + #expect(queue.queuedViews.count == 50) + + queue.enqueueViews(notInSet: Set(0..<5)) + + #expect(queue.usedViews.count == 5) + #expect(queue.queuedViews.count <= 5) + #expect(superview.subviews.count <= 10) + } +} diff --git a/apple/TablePro/Core/Autocomplete/Mongo/MongoCompletionService.swift b/apple/TablePro/Core/Autocomplete/Mongo/MongoCompletionService.swift index 5cde1cf616..a107f1122a 100644 --- a/apple/TablePro/Core/Autocomplete/Mongo/MongoCompletionService.swift +++ b/apple/TablePro/Core/Autocomplete/Mongo/MongoCompletionService.swift @@ -45,7 +45,13 @@ final class MongoCompletionService: QueryCompletionService { filter(items, prefix: prefix) } - func completions(in text: NSString, at offset: Int, isManualTrigger: Bool) async -> QueryCompletionSession? { + func completions( + in text: NSString, + at offset: Int, + statement: QueryStatementHint?, + isManualTrigger: Bool + ) async -> QueryCompletionSession? { + _ = statement // A cut would start the scan inside whatever string or comment it fell in, so the scan reads the whole text. let context = await MongoContextAnalyzer.analyze(text as String, cursor: offset) diff --git a/apple/TablePro/Core/Autocomplete/QueryCompletionService.swift b/apple/TablePro/Core/Autocomplete/QueryCompletionService.swift index 64056e5c4f..cc7a097d32 100644 --- a/apple/TablePro/Core/Autocomplete/QueryCompletionService.swift +++ b/apple/TablePro/Core/Autocomplete/QueryCompletionService.swift @@ -14,11 +14,22 @@ struct QueryCompletionSession { var candidatesTruncated = false } +// The caret's statement as the editor's index found it on the same text, and the grammar that split it. +struct QueryStatementHint: Equatable { + let range: NSRange + let grammar: SQLLexicalGrammar +} + @MainActor protocol QueryCompletionService: AnyObject { var triggerCharacters: Set { get } - func completions(in text: NSString, at offset: Int, isManualTrigger: Bool) async -> QueryCompletionSession? + func completions( + in text: NSString, + at offset: Int, + statement: QueryStatementHint?, + isManualTrigger: Bool + ) async -> QueryCompletionSession? func rank(_ items: [SQLCompletionItem], prefix: String) -> [SQLCompletionItem] func tokenStart(in text: NSString, endingAt offset: Int) -> Int func updateFavoriteKeywords(_ keywords: [String: (name: String, query: String)]) diff --git a/apple/TablePro/Core/Autocomplete/SQLCompletionService.swift b/apple/TablePro/Core/Autocomplete/SQLCompletionService.swift index b6a44f0c22..ad7aa91f2e 100644 --- a/apple/TablePro/Core/Autocomplete/SQLCompletionService.swift +++ b/apple/TablePro/Core/Autocomplete/SQLCompletionService.swift @@ -63,9 +63,14 @@ final class SQLCompletionService: QueryCompletionService { ) } - func completions(in text: NSString, at offset: Int, isManualTrigger: Bool) async -> QueryCompletionSession? { + func completions( + in text: NSString, + at offset: Int, + statement: QueryStatementHint?, + isManualTrigger: Bool + ) async -> QueryCompletionSession? { guard !SQLCompletionTriggerPolicy.suppressesAfterStatementBreak(in: text, at: offset), - let window = await SQLCompletionWindow.cut(text as String, around: offset, grammar: grammar), + let window = await cut(text, around: offset, statement: statement), let result = await engine.getCompletions( text: window.text, cursorPosition: offset - window.start, @@ -89,4 +94,12 @@ final class SQLCompletionService: QueryCompletionService { candidatesTruncated: result.candidatesTruncated ) } + + // A statement split with another grammar can end somewhere else, so only a matching one skips the scan. + private func cut(_ text: NSString, around offset: Int, statement: QueryStatementHint?) async -> (text: String, start: Int)? { + guard let statement, statement.grammar == grammar else { + return await SQLCompletionWindow.cut(text as String, around: offset, grammar: grammar) + } + return await SQLCompletionWindow.cut(text as String, around: offset, statement: statement.range, grammar: grammar) + } } diff --git a/apple/TablePro/Views/Editor/EditorEventRouter.swift b/apple/TablePro/Views/Editor/EditorEventRouter.swift index 187d6ffbff..5f981b6df4 100644 --- a/apple/TablePro/Views/Editor/EditorEventRouter.swift +++ b/apple/TablePro/Views/Editor/EditorEventRouter.swift @@ -5,6 +5,7 @@ @preconcurrency import AppKit import TableProEditorKit +import TableProSQLGrammar import TableProTextEngine @MainActor @@ -173,6 +174,26 @@ internal final class EditorEventRouter { return false } + // Several editors can be registered for one tab; the one holding exactly `text` answers. + internal func statement( + at cursor: Int, + in text: String, + forTab tabId: UUID, + connectionId: UUID, + model: QueryStatementModel, + grammar: SQLLexicalGrammar + ) -> SQLStatementScanner.LocatedStatement? { + for ref in editors.values { + guard let coordinator = ref.coordinator, + coordinator.tabID == tabId, coordinator.connectionId == connectionId, + let statement = coordinator.indexedStatement(at: cursor, in: text, model: model, grammar: grammar) else { + continue + } + return statement + } + return nil + } + // Clear Selection chosen with the pointer: AppKit never sends a bare Escape as a key equivalent (measured, macOS 26). // True when the editor consumed it, so the caller skips the grid's fallback. @discardableResult diff --git a/apple/TablePro/Views/Editor/QueryCompletionAdapter.swift b/apple/TablePro/Views/Editor/QueryCompletionAdapter.swift index 47b6006597..3f6cc7fdc3 100644 --- a/apple/TablePro/Views/Editor/QueryCompletionAdapter.swift +++ b/apple/TablePro/Views/Editor/QueryCompletionAdapter.swift @@ -48,6 +48,8 @@ final class QueryCompletionAdapter: CodeSuggestionDelegate { private var service: QueryCompletionService private var configuration: Configuration? + // The caret's statement from the index the editor keeps, read on the request's own text. + var statementLocator: (@MainActor (_ text: String, _ offset: Int, _ storage: NSTextStorage) -> QueryStatementHint?)? private var favoriteKeywords: [String: (name: String, query: String)] = [:] private var session: Session? @@ -122,16 +124,21 @@ final class QueryCompletionAdapter: CodeSuggestionDelegate { guard !textView.textView.hasMarkedText() else { return nil } let liveCursorPosition = textView.cursorPositions.first ?? cursorPosition - // A copy: the storage string keeps changing during the request, and the response names the prefix it ranked. - let text = NSString(string: textView.textView.textStorage?.string ?? "") + // Bridging makes an immutable copy that shares the storage's buffer: the storage keeps changing during the + // request, and the response names the prefix it ranked. + let storage = textView.textView.textStorage + let snapshot = storage?.string ?? "" + let text = snapshot as NSString let offset = liveCursorPosition.range.location guard offset >= 0, offset <= text.length else { return nil } let localStart = service.tokenStart(in: text, endingAt: offset) + let statement = storage.flatMap { statementLocator?(snapshot, offset, $0) } guard let result = await service.completions( in: text, at: offset, + statement: statement, isManualTrigger: isManualTrigger ), !Task.isCancelled else { return nil diff --git a/apple/TablePro/Views/Editor/SQLEditorController.swift b/apple/TablePro/Views/Editor/SQLEditorController.swift index 1e88ef5b96..572178f244 100644 --- a/apple/TablePro/Views/Editor/SQLEditorController.swift +++ b/apple/TablePro/Views/Editor/SQLEditorController.swift @@ -86,6 +86,9 @@ final class SQLEditorController { observeEditorSettings() observeVimMode() observeSessionChanges() + completionAdapter.statementLocator = { [weak coordinator] text, offset, storage in + coordinator?.maintainedStatement(at: offset, in: text, storage: storage) + } configureCompletion() setupFavoritesObserver() subscribeToCompletionRevision() diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index 0cff4ab7fb..33a8c57da4 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -397,6 +397,32 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie statementRunController.moveCursor(direction, in: controller) } + // Nil unless this editor holds exactly `text` and splits it the way the caller does, so the answer is a fresh scan's. + func indexedStatement( + at cursor: Int, + in text: String, + model: QueryStatementModel, + grammar: SQLLexicalGrammar + ) -> SQLStatementScanner.LocatedStatement? { + guard hasInstalledEditorServices, !isDestroyed, + statementRunController.statementModel == model, statementRunController.grammar == grammar, + let storage = controller?.textView?.textStorage else { + return nil + } + let snapshot = storage.string + guard (snapshot as NSString).isEqual(to: text) else { return nil } + return statementRunController.statement(at: cursor, in: snapshot, storage: storage) + } + + func maintainedStatement(at offset: Int, in text: String, storage: NSTextStorage) -> QueryStatementHint? { + guard hasInstalledEditorServices, !isDestroyed, + storage === controller?.textView?.textStorage, + let found = statementRunController.maintainedStatement(at: offset, in: text, storage: storage) else { + return nil + } + return QueryStatementHint(range: found.statement.range, grammar: found.grammar) + } + // Matched against the text this editor shows, which the tab's binding can lag; an edited-away statement resolves to nothing. @discardableResult func jumpToStatement(_ anchor: StatementAnchor) -> Bool { diff --git a/apple/TablePro/Views/Editor/StatementRunController.swift b/apple/TablePro/Views/Editor/StatementRunController.swift index b7b0acef3c..4a565a9bff 100644 --- a/apple/TablePro/Views/Editor/StatementRunController.swift +++ b/apple/TablePro/Views/Editor/StatementRunController.swift @@ -39,7 +39,12 @@ final class StatementRunController { var sizeLimit = StatementRunController.defaultSizeLimit var grammar: SQLLexicalGrammar = .ansi { - didSet { if grammar != oldValue { caretIndex = nil } } + didSet { + if grammar != oldValue { + caretIndex = nil + rememberedStatement = nil + } + } } /// How the document divides into statements. JavaScript engines do not end a statement at every @@ -49,6 +54,7 @@ final class StatementRunController { if statementModel != oldValue { caretIndex = nil caretTable = nil + rememberedStatement = nil } } } @@ -58,6 +64,8 @@ final class StatementRunController { private var caretTable: QueryStatementCaretTable? private weak var caretIndexStorage: NSTextStorage? private var caretIndexEdits: StorageEditObservation? + // Completion asks for the caret the band just resolved, so a long statement is not scanned twice per key. + private var rememberedStatement: (cursor: Int, statement: SQLStatementScanner.LocatedStatement)? var caretIndexUnitsScanned: Int { caretIndex?.unitsScanned ?? 0 @@ -190,16 +198,11 @@ final class StatementRunController { guard (text as NSString).length <= sizeLimit else { return nil } guard let selection = controller.cursorPositions.first, selection.range.length == 0 else { return nil } - let statement = QueryStatementScanner.locatedStatementAtCursor( - in: text, - cursorPosition: selection.range.location, - model: statementModel, - grammar: grammar - ) - guard statement.hasContent, statement.contentRange.length > 0 else { return nil } + let located = statement(at: selection.range.location, in: text, storage: textView.textStorage) + guard located.hasContent, located.contentRange.length > 0 else { return nil } return ( - (text as NSString).substring(with: statement.contentRange), - statement.contentRange.location + (text as NSString).substring(with: located.contentRange), + located.contentRange.location ) } @@ -212,6 +215,26 @@ final class StatementRunController { } } + // `text` is the storage's text as it is now. + func statement(at cursor: Int, in text: String, storage: NSTextStorage?) -> SQLStatementScanner.LocatedStatement { + guard let storage else { + return QueryStatementScanner.locatedStatementAtCursor( + in: text, cursorPosition: cursor, model: statementModel, grammar: grammar + ) + } + return indexedStatement(at: cursor, in: text, storage: storage) + } + + // Only where the band keeps the index warm at the caret. `text` is the storage's text as it is now. + func maintainedStatement( + at cursor: Int, + in text: String, + storage: NSTextStorage + ) -> (statement: SQLStatementScanner.LocatedStatement, grammar: SQLLexicalGrammar)? { + guard statementModel == .sql, isHighlightEnabled, (text as NSString).length <= sizeLimit else { return nil } + return (indexedStatement(at: cursor, in: text, storage: storage), grammar) + } + /// Moves the band to the statement the caret is in. Call after the selection changes. func refreshHighlight(in controller: TextViewController?) { guard let controller else { return } @@ -223,6 +246,7 @@ final class StatementRunController { pendingRefresh = nil caretIndex = nil caretTable = nil + rememberedStatement = nil caretIndexStorage = nil caretIndexEdits = nil controller?.runnableStatements = [] @@ -248,12 +272,7 @@ final class StatementRunController { return } - let resolved = QueryStatementScanner.locatedStatementAtCursor( - in: text, - cursorPosition: statement.range.location, - model: statementModel, - grammar: grammar - ) + let resolved = self.statement(at: statement.range.location, in: text, storage: textView.textStorage) guard resolved.hasContent, resolved.contentRange == statement.range else { refreshControls(in: controller) return @@ -277,19 +296,9 @@ final class StatementRunController { let text = textView.string guard (text as NSString).length <= sizeLimit else { return nil } - let statement: SQLStatementScanner.LocatedStatement - if let storage = textView.textStorage { - statement = indexedStatement(at: selection.range.location, in: text, storage: storage) - } else { - statement = QueryStatementScanner.locatedStatementAtCursor( - in: text, - cursorPosition: selection.range.location, - model: statementModel, - grammar: grammar - ) - } - guard statement.hasContent, statement.contentRange.length > 0 else { return nil } - return statement.contentRange + let located = statement(at: selection.range.location, in: text, storage: textView.textStorage) + guard located.hasContent, located.contentRange.length > 0 else { return nil } + return located.contentRange } private func indexedStatement( @@ -304,6 +313,15 @@ final class StatementRunController { if storage.editedMask.contains(.editedCharacters) { textDidChange(at: storage.editedRange.location) } + if let remembered = rememberedStatement, remembered.cursor == cursor { + return remembered.statement + } + let statement = resolvedStatement(at: cursor, in: text) + rememberedStatement = (cursor, statement) + return statement + } + + private func resolvedStatement(at cursor: Int, in text: String) -> SQLStatementScanner.LocatedStatement { guard statementModel == .sql else { if caretTable == nil { caretTable = QueryStatementCaretTable(text: text, model: statementModel) @@ -324,11 +342,13 @@ final class StatementRunController { private func textDidChange(at location: Int) { caretIndex?.textDidChange(at: location) caretTable = nil + rememberedStatement = nil } private func observeEdits(on storage: NSTextStorage) { caretIndex = nil caretTable = nil + rememberedStatement = nil caretIndexStorage = storage // Every way the text changes passes through the storage, including the ones that skip the editor's delegate. let token = NotificationCenter.default.addObserver( diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+AIQueryActions.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+AIQueryActions.swift index 8217b45be3..98462721ab 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+AIQueryActions.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+AIQueryActions.swift @@ -114,13 +114,8 @@ extension MainContentCoordinator { case .selectionOrStatementAtCursor: return selectionOrStatementAtCursor(in: fullQuery) case .statement(let offset): - let statement = QueryStatementScanner.locatedStatementAtCursor( - in: fullQuery, - cursorPosition: min(max(0, offset), (fullQuery as NSString).length), - model: statementModel, - grammar: lexicalGrammar - ) - return (statement.sql, statement.offset) + let located = statement(at: min(max(0, offset), (fullQuery as NSString).length), in: fullQuery) + return (located.sql, located.offset) } } @@ -130,13 +125,23 @@ extension MainContentCoordinator { let clampedRange = NSIntersectionRange(firstCursor.range, NSRange(location: 0, length: nsQuery.length)) return (nsQuery.substring(with: clampedRange), clampedRange.location) } - let statement = QueryStatementScanner.locatedStatementAtCursor( - in: fullQuery, - cursorPosition: cursorPositions.first?.range.location ?? 0, - model: statementModel, - grammar: lexicalGrammar + let located = statement(at: cursorPositions.first?.range.location ?? 0, in: fullQuery) + return (located.sql, located.offset) + } + + // The selected tab's editor answers from the index it keeps when it holds the same text, else the text is scanned. + private func statement(at cursor: Int, in fullQuery: String) -> SQLStatementScanner.LocatedStatement { + let model = statementModel + let grammar = lexicalGrammar + if let tabId = tabManager.selectedTabId, + let indexed = EditorEventRouter.shared.statement( + at: cursor, in: fullQuery, forTab: tabId, connectionId: connectionId, model: model, grammar: grammar + ) { + return indexed + } + return QueryStatementScanner.locatedStatementAtCursor( + in: fullQuery, cursorPosition: cursor, model: model, grammar: grammar ) - return (statement.sql, statement.offset) } func applyAISuggestion(_ afterSQL: String, replacing beforeSQL: String, source: QueryEditorAnchor?) { diff --git a/apple/TableProTests/Core/Autocomplete/SQLCompletionServiceEmptyPrefixTests.swift b/apple/TableProTests/Core/Autocomplete/SQLCompletionServiceEmptyPrefixTests.swift index 50e9ae9469..6cbeb7f29f 100644 --- a/apple/TableProTests/Core/Autocomplete/SQLCompletionServiceEmptyPrefixTests.swift +++ b/apple/TableProTests/Core/Autocomplete/SQLCompletionServiceEmptyPrefixTests.swift @@ -41,7 +41,7 @@ struct SQLCompletionServiceEmptyPrefixTests { @Test("A PostgreSQL cast opens the type list with nothing typed") func castTargetOpensOnAnEmptyPrefix() async { let text = "SELECT id::" as NSString - let session = await Self.makeService().completions(in: text, at: text.length, isManualTrigger: false) + let session = await Self.makeService().completions(in: text, at: text.length, statement: nil, isManualTrigger: false) #expect(session != nil) #expect(session?.items.contains { $0.label == "jsonb" } == true) @@ -51,7 +51,7 @@ struct SQLCompletionServiceEmptyPrefixTests { @Test("A partly typed cast still completes") func castTargetCompletesATypedPrefix() async { let text = "SELECT id::js" as NSString - let session = await Self.makeService().completions(in: text, at: text.length, isManualTrigger: false) + let session = await Self.makeService().completions(in: text, at: text.length, statement: nil, isManualTrigger: false) #expect(session?.items.first?.label == "jsonb") } @@ -69,10 +69,10 @@ struct SQLCompletionServiceEmptyPrefixTests { let text = query as NSString let service = Self.makeService() - let automatic = await service.completions(in: text, at: text.length, isManualTrigger: false) + let automatic = await service.completions(in: text, at: text.length, statement: nil, isManualTrigger: false) #expect(automatic == nil) - let manual = await service.completions(in: text, at: text.length, isManualTrigger: true) + let manual = await service.completions(in: text, at: text.length, statement: nil, isManualTrigger: true) #expect(manual != nil) } @@ -80,7 +80,7 @@ struct SQLCompletionServiceEmptyPrefixTests { @Test("FROM still opens with nothing typed") func fromOpensOnAnEmptyPrefix() async { let text = "SELECT * FROM " as NSString - let session = await Self.makeService().completions(in: text, at: text.length, isManualTrigger: false) + let session = await Self.makeService().completions(in: text, at: text.length, statement: nil, isManualTrigger: false) #expect(session != nil) } diff --git a/apple/TableProTests/Core/Autocomplete/SQLCompletionServiceStatementHintTests.swift b/apple/TableProTests/Core/Autocomplete/SQLCompletionServiceStatementHintTests.swift new file mode 100644 index 0000000000..cc53d7f04d --- /dev/null +++ b/apple/TableProTests/Core/Autocomplete/SQLCompletionServiceStatementHintTests.swift @@ -0,0 +1,68 @@ +import Foundation +@testable import TablePro +import TableProAutocomplete +import TableProPluginKit +import TableProSQLGrammar +import Testing + +@MainActor +struct SQLCompletionServiceStatementHintTests { + private struct Summary: Equatable { + let labels: [String] + let replacementRange: NSRange + } + + private func summary(_ session: QueryCompletionSession?) -> Summary? { + session.map { Summary(labels: $0.items.map(\.label), replacementRange: $0.replacementRange) } + } + + // With no database type the editor's band splits as MySQL and completion as ANSI. + @Test + func aHintSplitWithAnotherGrammarGivesTheSessionNoHintGives() async throws { + let text = "SELECT 1 # note ; FROM t\nSELECT * FROM or" as NSString + let caret = text.length + let mysql = DatabaseType.mysql.lexicalGrammar + let mysqlStatement = SQLStatementScanner.locatedStatementAtCursor(in: text as String, cursorPosition: caret, grammar: mysql) + let ansiStatement = SQLStatementScanner.locatedStatementAtCursor(in: text as String, cursorPosition: caret, grammar: .ansi) + try #require(mysqlStatement.range != ansiStatement.range) + let service = SQLCompletionService(schemaProvider: nil, databaseType: nil) + + let hinted = await service.completions( + in: text, + at: caret, + statement: QueryStatementHint(range: mysqlStatement.range, grammar: mysql), + isManualTrigger: true + ) + let plain = await service.completions(in: text, at: caret, statement: nil, isManualTrigger: true) + + #expect(summary(hinted) == summary(plain)) + } + + @Test( + arguments: [ + ("SELECT 1;\nSELECT * FROM or", -1), + ("SELECT id, na FROM users WHERE id = 1;\nSELECT 2;", 12), + ("SELECT 'a;b' AS x;\nUPDATE t SET c = 1 WHERE ", -1), + ("CREATE FUNCTION f() RETURNS int AS $$ SELECT 1; $$ LANGUAGE sql;\nSELECT * FROM ", -1), + ("/* ; */ SELECT * FROM t JOIN ", -1), + ("SELECT 1; -- done\n", -1), + ] + ) + func aMatchingHintGivesTheSessionNoHintGives(script: String, caretOrEnd: Int) async { + let text = script as NSString + let caret = caretOrEnd < 0 ? text.length : caretOrEnd + let grammar = DatabaseType.postgresql.lexicalGrammar + let statement = SQLStatementScanner.locatedStatementAtCursor(in: script, cursorPosition: caret, grammar: grammar) + let service = SQLCompletionService(schemaProvider: nil, databaseType: .postgresql) + + let hinted = await service.completions( + in: text, + at: caret, + statement: QueryStatementHint(range: statement.range, grammar: grammar), + isManualTrigger: true + ) + let plain = await service.completions(in: text, at: caret, statement: nil, isManualTrigger: true) + + #expect(summary(hinted) == summary(plain)) + } +} diff --git a/apple/TableProTests/Views/Editor/QueryCompletionAdapterLifecycleTests.swift b/apple/TableProTests/Views/Editor/QueryCompletionAdapterLifecycleTests.swift index 370ebc103f..7a317b4c71 100644 --- a/apple/TableProTests/Views/Editor/QueryCompletionAdapterLifecycleTests.swift +++ b/apple/TableProTests/Views/Editor/QueryCompletionAdapterLifecycleTests.swift @@ -5,11 +5,13 @@ // caused the original dropout is an AppKit lifecycle behaviour and is not // deterministically unit-testable; these tests cover the logic the fix relies on. +import AppKit import Foundation @testable import TablePro @testable import TableProAutocomplete import TableProEditorKit import TableProPluginKit +import TableProSQLGrammar import TableProTextEngine import Testing @@ -519,6 +521,104 @@ extension GlobalStateSuites { #expect(controller.textView.selectionManager.textSelections.map { $0.range } == [NSRange(location: 21, length: 0)]) } + // MARK: - The band's statement + + @MainActor + private func locator(for band: StatementRunController) -> @MainActor (String, Int, NSTextStorage) -> QueryStatementHint? { + { text, offset, storage in + band.maintainedStatement(at: offset, in: text, storage: storage).map { + QueryStatementHint(range: $0.statement.range, grammar: $0.grammar) + } + } + } + + @MainActor + @Test("typing at the end of a long script hands completion the statement the band resolved, with no scan of its own") + func longScriptCompletionReadsTheBandStatement() async throws { + let grammar = DatabaseType.mysql.lexicalGrammar + let controller = EditorControllerFixture.make( + string: String(repeating: "SELECT id FROM t WHERE id = 1;\n", count: 10_000) + ) + let band = StatementRunController() + band.grammar = grammar + band.install(on: controller) + let service = StatementRecordingCompletionService() + let adapter = QueryCompletionAdapter(serviceForTesting: service) + adapter.statementLocator = locator(for: band) + let keys = 30 + var scannedByCompletion = 0 + let documentEnd = controller.textView.textStorage.length + controller.setCursorPositions([CursorPosition(range: NSRange(location: documentEnd, length: 0))]) + band.refreshHighlight(in: controller) + let scannedBeforeTyping = band.caretIndexUnitsScanned + + for _ in 0.. QueryCompletionSession? { - _ = isManualTrigger + _ = (statement, isManualTrigger) let start = tokenStart(in: text, endingAt: offset) whileAnswering?() return QueryCompletionSession( @@ -622,9 +723,10 @@ private final class RankingInputRecordingCompletionService: QueryCompletionServi func completions( in text: NSString, at offset: Int, + statement: QueryStatementHint?, isManualTrigger: Bool ) async -> QueryCompletionSession? { - _ = (text, offset, isManualTrigger) + _ = (text, offset, statement, isManualTrigger) return QueryCompletionSession( items: Array(items.prefix(40)), candidates: Array(items.prefix(poolLimit)), @@ -647,3 +749,36 @@ private final class RankingInputRecordingCompletionService: QueryCompletionServi _ = keywords } } + +@MainActor +private final class StatementRecordingCompletionService: QueryCompletionService { + private(set) var statements: [QueryStatementHint?] = [] + + var triggerCharacters: Set { [] } + + func completions( + in text: NSString, + at offset: Int, + statement: QueryStatementHint?, + isManualTrigger: Bool + ) async -> QueryCompletionSession? { + _ = (text, isManualTrigger) + statements.append(statement) + let item = SQLCompletionItem.keyword("SELECT") + return QueryCompletionSession(items: [item], candidates: [item], replacementRange: NSRange(location: offset, length: 0)) + } + + func rank(_ items: [SQLCompletionItem], prefix: String) -> [SQLCompletionItem] { + _ = prefix + return items + } + + func tokenStart(in text: NSString, endingAt offset: Int) -> Int { + _ = text + return offset + } + + func updateFavoriteKeywords(_ keywords: [String: (name: String, query: String)]) { + _ = keywords + } +} diff --git a/apple/TableProTests/Views/Editor/QueryCompletionRankingTests.swift b/apple/TableProTests/Views/Editor/QueryCompletionRankingTests.swift index a3df0e5a57..051bd7896d 100644 --- a/apple/TableProTests/Views/Editor/QueryCompletionRankingTests.swift +++ b/apple/TableProTests/Views/Editor/QueryCompletionRankingTests.swift @@ -112,7 +112,7 @@ struct QueryCompletionRankingTests { let service = MongoCompletionService(schemaProvider: nil, databaseType: .mongodb) let text = "db.orders.aggregate([{ $" as NSString - let session = await service.completions(in: text, at: text.length, isManualTrigger: true) + let session = await service.completions(in: text, at: text.length, statement: nil, isManualTrigger: true) #expect(session != nil) #expect((session?.candidates.count ?? 0) <= 400) @@ -127,8 +127,8 @@ struct QueryCompletionRankingTests { let inComment = "/*\n" + notes + "db.ord" as NSString let afterComment = "/*\n" + notes + "it's done */\ndb.ord" as NSString - let silent = await service.completions(in: inComment, at: inComment.length, isManualTrigger: true) - let completed = await service.completions(in: afterComment, at: afterComment.length, isManualTrigger: true) + let silent = await service.completions(in: inComment, at: inComment.length, statement: nil, isManualTrigger: true) + let completed = await service.completions(in: afterComment, at: afterComment.length, statement: nil, isManualTrigger: true) #expect(silent == nil) #expect(completed != nil) diff --git a/apple/TableProTests/Views/Editor/StatementAtCaretRoutingTests.swift b/apple/TableProTests/Views/Editor/StatementAtCaretRoutingTests.swift new file mode 100644 index 0000000000..be60701185 --- /dev/null +++ b/apple/TableProTests/Views/Editor/StatementAtCaretRoutingTests.swift @@ -0,0 +1,239 @@ +import AppKit +import Foundation +import SwiftUI +@testable import TablePro +import TableProEditorKit +import TableProPluginKit +import TableProSQLGrammar +import TableProTestSupport +import TableProTextEngine +import Testing + +// Cmd-Return, Explain and the AI actions read the caret's statement from the mounted editor's index, and only when that +// editor holds the same text split the same way. +@MainActor +struct StatementAtCaretRoutingTests { + private final class Model { + var text: String + var cursorPositions: [CursorPosition] = [] + + init(text: String) { + self.text = text + } + } + + private struct Mounted { + let editor: SQLEditorController + let window: NSWindow + let model: Model + + func unmount() { + window.orderOut(nil) + editor.teardown() + } + } + + private let router = EditorEventRouter.shared + + private func mount(_ text: String, type: DatabaseType = .mysql, tabID: UUID, connectionId: UUID) async throws -> Mounted { + let model = Model(text: text) + let editor = SQLEditorController(input: SQLEditorInput( + text: Binding(get: { model.text }, set: { model.text = $0 }), + cursorPositions: Binding(get: { model.cursorPositions }, set: { model.cursorPositions = $0 }), + databaseType: type, + connectionId: connectionId, + tabID: tabID + )) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = editor.textViewController.view + let mounted = Mounted(editor: editor, window: window, model: model) + let grammar = SQLLexicalResolver.executionGrammar(for: type, connectionId: connectionId) + let statementModel = QueryStatementModel.forDatabaseType(type) + try await waitUntil { + window.contentView?.layoutSubtreeIfNeeded() + return self.router.statement( + at: 0, in: text, forTab: tabID, connectionId: connectionId, model: statementModel, grammar: grammar + ) != nil + } + return mounted + } + + private func expectFreshScan( + _ statement: SQLStatementScanner.LocatedStatement?, + at caret: Int, + in text: String, + model: QueryStatementModel, + grammar: SQLLexicalGrammar, + sourceLocation: SourceLocation = #_sourceLocation + ) { + let fresh = QueryStatementScanner.locatedStatementAtCursor( + in: text, cursorPosition: caret, model: model, grammar: grammar + ) + #expect(statement?.range == fresh.range, "caret \(caret)", sourceLocation: sourceLocation) + #expect(statement?.sql == fresh.sql, "caret \(caret)", sourceLocation: sourceLocation) + #expect(statement?.hasContent == fresh.hasContent, "caret \(caret)", sourceLocation: sourceLocation) + } + + @Test + func aMountedLongScriptAnswersWhatAFreshScanAnswers() async throws { + let tabID = UUID() + let connectionId = UUID() + let script = (0..<10_000).map { "SELECT \($0) FROM t WHERE c = 'x;y';" }.joined(separator: "\n") + let mounted = try await mount(script, tabID: tabID, connectionId: connectionId) + defer { mounted.unmount() } + let grammar = SQLLexicalResolver.executionGrammar(for: .mysql, connectionId: connectionId) + let length = (script as NSString).length + var seed: UInt64 = 0x2545_F491_4F6C_DD1D + + for _ in 0..<50 { + seed = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 + let caret = Int((seed >> 33) % UInt64(length + 1)) + let statement = router.statement( + at: caret, in: script, forTab: tabID, connectionId: connectionId, model: .sql, grammar: grammar + ) + #expect(statement != nil) + expectFreshScan(statement, at: caret, in: script, model: .sql, grammar: grammar) + } + } + + @Test + func aTabWithNoMountedEditorGetsNoAnswer() { + let statement = router.statement( + at: 0, in: "SELECT 1;", forTab: UUID(), connectionId: UUID(), model: .sql, grammar: .ansi + ) + #expect(statement == nil) + } + + @Test + func textOfTheSameLengthThatDiffersGetsNoAnswer() async throws { + let tabID = UUID() + let connectionId = UUID() + let mounted = try await mount("SELECT 1;\nSELECT 2;", tabID: tabID, connectionId: connectionId) + defer { mounted.unmount() } + let grammar = SQLLexicalResolver.executionGrammar(for: .mysql, connectionId: connectionId) + + let statement = router.statement( + at: 12, in: "SELECT 3;\nSELECT 4;", forTab: tabID, connectionId: connectionId, model: .sql, grammar: grammar + ) + + #expect(statement == nil) + } + + @Test + func anotherGrammarGetsNoAnswer() async throws { + let tabID = UUID() + let connectionId = UUID() + let text = "SELECT 1 # note ; still the note\nSELECT 2;" + let mounted = try await mount(text, tabID: tabID, connectionId: connectionId) + defer { mounted.unmount() } + let grammar = SQLLexicalResolver.executionGrammar(for: .mysql, connectionId: connectionId) + try #require(grammar != .ansi) + + let statement = router.statement(at: 20, in: text, forTab: tabID, connectionId: connectionId, model: .sql, grammar: .ansi) + + #expect(statement == nil) + } + + @Test + func withTwoEditorsOnOneTabTheOneHoldingTheTextAnswers() async throws { + let tabID = UUID() + let connectionId = UUID() + let first = "SELECT 1;\nSELECT 2;" + let second = "UPDATE t SET a = 1;\nDELETE FROM t WHERE a = 2;" + let mountedFirst = try await mount(first, tabID: tabID, connectionId: connectionId) + defer { mountedFirst.unmount() } + let mountedSecond = try await mount(second, tabID: tabID, connectionId: connectionId) + defer { mountedSecond.unmount() } + let grammar = SQLLexicalResolver.executionGrammar(for: .mysql, connectionId: connectionId) + + for (text, caret) in [(second, 30), (first, 12), (second, 2)] { + let statement = router.statement( + at: caret, in: text, forTab: tabID, connectionId: connectionId, model: .sql, grammar: grammar + ) + #expect(statement != nil) + expectFreshScan(statement, at: caret, in: text, model: .sql, grammar: grammar) + } + } + + @Test(arguments: [ + (DatabaseType.redis, "SET a 1\nGET a\nHSET h f \"v;w\"\n"), + (DatabaseType.mongodb, "db.a.find({ x: \"1;2\" })\ndb.b.insertOne({ y: 2 });\ndb.c.countDocuments()\n"), + ]) + func redisAndJavaScriptTabsAnswerAsTheirSplitterDoes(type: DatabaseType, text: String) async throws { + let tabID = UUID() + let connectionId = UUID() + let mounted = try await mount(text, type: type, tabID: tabID, connectionId: connectionId) + defer { mounted.unmount() } + let grammar = SQLLexicalResolver.executionGrammar(for: type, connectionId: connectionId) + let model = QueryStatementModel.forDatabaseType(type) + + for caret in stride(from: 0, through: (text as NSString).length, by: 7) { + let statement = router.statement( + at: caret, in: text, forTab: tabID, connectionId: connectionId, model: model, grammar: grammar + ) + #expect(statement != nil) + expectFreshScan(statement, at: caret, in: text, model: model, grammar: grammar) + } + } + + @Test + func runAtTheCaretUsesTheTabTextWhenTheEditorHoldsOther() async throws { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(QueryTab(title: "Query 1", query: "SELECT 3;\nSELECT 4;", tabType: .query)) + let mounted = try await mount( + "SELECT 1;\nSELECT 2;", type: fixture.connection.type, tabID: tab.id, connectionId: fixture.connection.id + ) + defer { mounted.unmount() } + fixture.coordinator.cursorPositions = [CursorPosition(range: NSRange(location: 12, length: 0))] + + let target = fixture.coordinator.selectionOrStatementAtCursor(in: tab.content.query) + let fresh = QueryStatementScanner.locatedStatementAtCursor( + in: tab.content.query, + cursorPosition: 12, + model: fixture.coordinator.statementModel, + grammar: fixture.coordinator.lexicalGrammar + ) + + #expect(target.sql == fresh.sql) + #expect(target.offset == fresh.offset) + #expect(target.sql.contains("SELECT 4;")) + } + + @Test + func runAtTheCaretReadsTheMountedEditorHoldingTheTabText() async throws { + let fixture = CoordinatorFixture() + let query = (0..<2_000).map { "SELECT \($0);" }.joined(separator: "\n") + let tab = fixture.addTab(QueryTab(title: "Query 1", query: query, tabType: .query)) + let mounted = try await mount(query, type: fixture.connection.type, tabID: tab.id, connectionId: fixture.connection.id) + defer { mounted.unmount() } + let caret = (query as NSString).range(of: "SELECT 1500;").location + 3 + fixture.coordinator.cursorPositions = [CursorPosition(range: NSRange(location: caret, length: 0))] + + let indexed = router.statement( + at: caret, + in: query, + forTab: tab.id, + connectionId: fixture.connection.id, + model: fixture.coordinator.statementModel, + grammar: fixture.coordinator.lexicalGrammar + ) + #expect(indexed != nil) + + let target = fixture.coordinator.selectionOrStatementAtCursor(in: query) + let fresh = QueryStatementScanner.locatedStatementAtCursor( + in: query, + cursorPosition: caret, + model: fixture.coordinator.statementModel, + grammar: fixture.coordinator.lexicalGrammar + ) + + #expect(target.sql == fresh.sql) + #expect(target.offset == fresh.offset) + } +} diff --git a/apple/TableProTests/Views/Editor/StatementRunControllerTests.swift b/apple/TableProTests/Views/Editor/StatementRunControllerTests.swift index 70fe90613f..353599db44 100644 --- a/apple/TableProTests/Views/Editor/StatementRunControllerTests.swift +++ b/apple/TableProTests/Views/Editor/StatementRunControllerTests.swift @@ -314,4 +314,139 @@ struct StatementRunControllerTests { #expect(controller.textView.string == threeStatements, "result \(index)") } } + + // MARK: - Completion's statement + + private static let mixedScript = """ + SELECT 'a;b' FROM t; + -- a note; still a comment + INSERT INTO t VALUES (1); + /* block ; */ UPDATE t SET x = "q;" WHERE y = 1; + CREATE PROCEDURE p() BEGIN SELECT 1; END; + SELECT $$ dollar ; body $$; + SELECT 1 # hash ; comment + ; + + """ + + private static let completionGrammars: [SQLLexicalGrammar] = [ + TestGrammar.standard, TestGrammar.mysql, TestGrammar.postgres, TestGrammar.sqlite, + TestGrammar.sqlServer, TestGrammar.oracle, + ] + + private func expectFreshScan( + _ statement: SQLStatementScanner.LocatedStatement?, + at caret: Int, + in text: String, + grammar: SQLLexicalGrammar, + sourceLocation: SourceLocation = #_sourceLocation + ) { + let fresh = SQLStatementScanner.locatedStatementAtCursor(in: text, cursorPosition: caret, grammar: grammar) + #expect(statement?.range == fresh.range, "caret \(caret)", sourceLocation: sourceLocation) + #expect(statement?.hasContent == fresh.hasContent, "caret \(caret)", sourceLocation: sourceLocation) + } + + @Test("Completion's statement equals a fresh scan at any caret, across edits", arguments: 0..<6) + func maintainedStatementEqualsAFreshScan(grammarIndex: Int) throws { + let grammar = Self.completionGrammars[grammarIndex] + let controller = makeController(text: String(repeating: Self.mixedScript, count: 30)) + let subject = makeSubject(grammar: grammar) + subject.install(on: controller) + let storage = try #require(controller.textView.textStorage) + let insertions = ["x", ";", "'", "\n", "--", "/*", "*/", " ", "$$", "#"] + var seed: UInt64 = 0x9E37_79B9_7F4A_7C15 &+ UInt64(grammarIndex) + func next(_ bound: Int) -> Int { + seed = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 + return Int((seed >> 33) % UInt64(max(bound, 1))) + } + + for _ in 0..<40 { + let length = storage.length + if next(3) == 0, length > 3 { + controller.textView.replaceCharacters(in: NSRange(location: next(length - 3), length: next(3) + 1), with: "") + } else { + controller.textView.replaceCharacters( + in: NSRange(location: next(length + 1), length: 0), + with: insertions[next(insertions.count)] + ) + } + let text = controller.textView.string + for _ in 0..<5 { + let caret = next((text as NSString).length + 1) + if next(2) == 0 { + _ = band(at: caret, in: controller, subject: subject) + } + let found = subject.maintainedStatement(at: caret, in: text, storage: storage) + #expect(found?.grammar == grammar) + expectFreshScan(found?.statement, at: caret, in: text, grammar: grammar) + } + } + } + + @Test("Completion gets no statement where the band does not keep the index") + func maintainedStatementOnlyWhereTheBandKeepsTheIndex() throws { + let controller = makeController(text: threeStatements) + let storage = try #require(controller.textView.textStorage) + let text = controller.textView.string + + for model in [QueryStatementModel.redis, .javascript] { + let subject = makeSubject() + subject.statementModel = model + subject.install(on: controller) + #expect(subject.maintainedStatement(at: 3, in: text, storage: storage) == nil) + } + + let bandOff = makeSubject() + bandOff.isHighlightEnabled = false + #expect(bandOff.maintainedStatement(at: 3, in: text, storage: storage) == nil) + + let tooLong = makeSubject(sizeLimit: 10) + #expect(tooLong.maintainedStatement(at: 3, in: text, storage: storage) == nil) + + #expect(makeSubject().maintainedStatement(at: 3, in: text, storage: storage) != nil) + } + + @Test("Asking for the caret the band just resolved scans nothing") + func secondAskForTheSameCaretScansNothing() throws { + let controller = makeController(text: String(repeating: "SELECT 1;\n", count: 5_000) + "SELECT * FROM t WHERE ") + let subject = makeSubject() + subject.install(on: controller) + let storage = try #require(controller.textView.textStorage) + let text = controller.textView.string + let caret = storage.length + + _ = band(at: caret, in: controller, subject: subject) + let scanned = subject.caretIndexUnitsScanned + let found = subject.maintainedStatement(at: caret, in: text, storage: storage) + + #expect(subject.caretIndexUnitsScanned == scanned) + expectFreshScan(found?.statement, at: caret, in: text, grammar: TestGrammar.standard) + } + + @Test("An edit, a grammar change and another storage each drop the remembered statement") + func rememberedStatementIsDroppedWhenTheTextOrSplitChanges() throws { + let script = "SELECT 1 # note ; still the note\nSELECT 2;\nSELECT * FROM t" + let controller = makeController(text: script) + let subject = makeSubject(grammar: TestGrammar.mysql) + subject.install(on: controller) + let storage = try #require(controller.textView.textStorage) + let caret = (script as NSString).range(of: "still").location + + let first = subject.maintainedStatement(at: caret, in: controller.textView.string, storage: storage) + expectFreshScan(first?.statement, at: caret, in: controller.textView.string, grammar: TestGrammar.mysql) + + subject.grammar = TestGrammar.standard + let regrammared = subject.maintainedStatement(at: caret, in: controller.textView.string, storage: storage) + expectFreshScan(regrammared?.statement, at: caret, in: controller.textView.string, grammar: TestGrammar.standard) + #expect(regrammared?.statement.range != first?.statement.range) + + controller.textView.replaceCharacters(in: NSRange(location: 0, length: 0), with: "SELECT 0;") + let edited = subject.maintainedStatement(at: caret, in: controller.textView.string, storage: storage) + expectFreshScan(edited?.statement, at: caret, in: controller.textView.string, grammar: TestGrammar.standard) + + let other = makeController(text: "SELECT 9;\nSELECT 8; SELECT 7; SELECT 6; SELECT 5; SELECT 4;") + let otherStorage = try #require(other.textView.textStorage) + let swapped = subject.maintainedStatement(at: caret, in: other.textView.string, storage: otherStorage) + expectFreshScan(swapped?.statement, at: caret, in: other.textView.string, grammar: TestGrammar.standard) + } } From f0f166eb316c5d956cf31babe8a995c2b3899e97 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 10:51:16 +0700 Subject: [PATCH 2/5] test(editor): name the hidden-find search counter --- .../SQLCompletionWindowTests.swift | 2 +- .../FindPanelHiddenSearchTests.swift | 22 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/apple/Packages/TableProCore/Tests/TableProAutocompleteTests/SQLCompletionWindowTests.swift b/apple/Packages/TableProCore/Tests/TableProAutocompleteTests/SQLCompletionWindowTests.swift index 8c67992d96..5d7d690eee 100644 --- a/apple/Packages/TableProCore/Tests/TableProAutocompleteTests/SQLCompletionWindowTests.swift +++ b/apple/Packages/TableProCore/Tests/TableProAutocompleteTests/SQLCompletionWindowTests.swift @@ -219,7 +219,7 @@ struct SQLCompletionWindowTests { ) ] - @Test("A cut from the located statement equals a cut from the whole text", arguments: locatedCutCases) + @Test("A cut from the located statement equals a cut from the whole text", arguments: SQLCompletionWindowTests.locatedCutCases) func cutFromALocatedStatementEqualsTheWholeTextCut(_ example: LocatedCutCase) { let text = example.text as NSString let grammar = SQLLexicalGrammar.engine(example.engine) diff --git a/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/FindPanelHiddenSearchTests.swift b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/FindPanelHiddenSearchTests.swift index df3d14bd1a..de7c9efbf0 100644 --- a/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/FindPanelHiddenSearchTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/FindPanelHiddenSearchTests.swift @@ -8,11 +8,11 @@ import Testing @MainActor struct FindPanelHiddenSearchTests { private final class SearchCounter { - var count = 0 + var searches = 0 private var observation: AnyCancellable? init(_ model: FindPanelViewModel) { - observation = model.$findMatches.dropFirst().sink { [weak self] _ in self?.count += 1 } + observation = model.$findMatches.dropFirst().sink { [weak self] _ in self?.searches += 1 } } } @@ -43,17 +43,17 @@ struct FindPanelHiddenSearchTests { @Test func editsWithThePanelHiddenRunNoSearch() throws { let (controller, model) = try editor("a a a", find: "a") - let searches = SearchCounter(model) + let counter = SearchCounter(model) for _ in 0..<100 { append(" a", to: controller) } - #expect(searches.count == 0) + #expect(counter.searches == 0) model.moveToNextMatch() - #expect(searches.count == 1) + #expect(counter.searches == 1) #expect(model.matchCount == 103) } @@ -61,12 +61,12 @@ struct FindPanelHiddenSearchTests { func undoWithThePanelHiddenRunsNoSearch() throws { let (controller, model) = try editor("a a a", find: "a") append(" a", to: controller) - let searches = SearchCounter(model) + let counter = SearchCounter(model) controller.textView.undoManager?.undo() #expect(controller.textView.string == "a a a") - #expect(searches.count == 0) + #expect(counter.searches == 0) } // The search a hidden edit skipped picks its current match from the caret that edit left, as it did when it ran @@ -101,12 +101,12 @@ struct FindPanelHiddenSearchTests { @Test func replacingTheDocumentWithThePanelHiddenRunsNoSearch() async throws { let (controller, model) = try editor("a a a", find: "a") - let searches = SearchCounter(model) + let counter = SearchCounter(model) controller.setText("a b a b") await drainMainQueue() - #expect(searches.count == 0) + #expect(counter.searches == 0) controller.findViewController?.showFindPanel(animated: false) @@ -117,11 +117,11 @@ struct FindPanelHiddenSearchTests { func editsWithThePanelShownStillSearch() throws { let (controller, model) = try editor("a a a", find: "a") controller.findViewController?.showFindPanel(animated: false) - let searches = SearchCounter(model) + let counter = SearchCounter(model) append(" a", to: controller) - #expect(searches.count == 1) + #expect(counter.searches == 1) #expect(model.matchCount == 4) } } From ea48f7c91d59260d270c4eb6d96fa6cd56c68b6f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 11:45:16 +0700 Subject: [PATCH 3/5] test(editor): run the mounted-editor helper on the main actor --- .../Views/Editor/StatementAtCaretRoutingTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/apple/TableProTests/Views/Editor/StatementAtCaretRoutingTests.swift b/apple/TableProTests/Views/Editor/StatementAtCaretRoutingTests.swift index be60701185..317b3497a2 100644 --- a/apple/TableProTests/Views/Editor/StatementAtCaretRoutingTests.swift +++ b/apple/TableProTests/Views/Editor/StatementAtCaretRoutingTests.swift @@ -22,6 +22,7 @@ struct StatementAtCaretRoutingTests { } } + @MainActor private struct Mounted { let editor: SQLEditorController let window: NSWindow From fb7b5f3dc70dabc38942c7e1cdd0e2e42dc0cab8 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 12:54:54 +0700 Subject: [PATCH 4/5] perf(editor): warm the statement index off the main thread where the band does not keep it --- .../Mongo/MongoCompletionService.swift | 2 + .../Autocomplete/QueryCompletionService.swift | 2 + .../Autocomplete/SQLCompletionService.swift | 1 + .../Views/Editor/QueryCompletionAdapter.swift | 12 ++- .../Views/Editor/SQLEditorController.swift | 4 +- .../Views/Editor/SQLEditorCoordinator.swift | 16 ++- .../Views/Editor/StatementRunController.swift | 91 ++++++++++++++++- ...QueryCompletionAdapterLifecycleTests.swift | 61 +++++++++++- .../Editor/StatementRunControllerTests.swift | 97 +++++++++++++++++++ 9 files changed, 268 insertions(+), 18 deletions(-) diff --git a/apple/TablePro/Core/Autocomplete/Mongo/MongoCompletionService.swift b/apple/TablePro/Core/Autocomplete/Mongo/MongoCompletionService.swift index a107f1122a..3557ec86d0 100644 --- a/apple/TablePro/Core/Autocomplete/Mongo/MongoCompletionService.swift +++ b/apple/TablePro/Core/Autocomplete/Mongo/MongoCompletionService.swift @@ -1,6 +1,7 @@ import Foundation import TableProAutocomplete import TableProPluginKit +import TableProSQLGrammar @MainActor final class MongoCompletionService: QueryCompletionService { @@ -16,6 +17,7 @@ final class MongoCompletionService: QueryCompletionService { } var triggerCharacters: Set { [".", "$", "{", "[", "\"", "'", ":", " "] } + var statementGrammar: SQLLexicalGrammar? { nil } func updateFavoriteKeywords(_ keywords: [String: (name: String, query: String)]) { favoriteKeywords = keywords diff --git a/apple/TablePro/Core/Autocomplete/QueryCompletionService.swift b/apple/TablePro/Core/Autocomplete/QueryCompletionService.swift index cc7a097d32..8deb3043f7 100644 --- a/apple/TablePro/Core/Autocomplete/QueryCompletionService.swift +++ b/apple/TablePro/Core/Autocomplete/QueryCompletionService.swift @@ -23,6 +23,8 @@ struct QueryStatementHint: Equatable { @MainActor protocol QueryCompletionService: AnyObject { var triggerCharacters: Set { get } + // The grammar a statement hint has to be split with; nil when the service reads no statement. + var statementGrammar: SQLLexicalGrammar? { get } func completions( in text: NSString, diff --git a/apple/TablePro/Core/Autocomplete/SQLCompletionService.swift b/apple/TablePro/Core/Autocomplete/SQLCompletionService.swift index ad7aa91f2e..052cca400c 100644 --- a/apple/TablePro/Core/Autocomplete/SQLCompletionService.swift +++ b/apple/TablePro/Core/Autocomplete/SQLCompletionService.swift @@ -35,6 +35,7 @@ final class SQLCompletionService: QueryCompletionService { } var triggerCharacters: Set { [".", " ", ":", "(", ","] } + var statementGrammar: SQLLexicalGrammar? { grammar } // Read per request, so a changed setting applies to the next keystroke rather than the next connection. private var keywordCase: SQLKeywordCase { AppSettingsManager.shared.editor.keywordCase } diff --git a/apple/TablePro/Views/Editor/QueryCompletionAdapter.swift b/apple/TablePro/Views/Editor/QueryCompletionAdapter.swift index 3f6cc7fdc3..7ae26f1fb1 100644 --- a/apple/TablePro/Views/Editor/QueryCompletionAdapter.swift +++ b/apple/TablePro/Views/Editor/QueryCompletionAdapter.swift @@ -49,7 +49,10 @@ final class QueryCompletionAdapter: CodeSuggestionDelegate { private var service: QueryCompletionService private var configuration: Configuration? // The caret's statement from the index the editor keeps, read on the request's own text. - var statementLocator: (@MainActor (_ text: String, _ offset: Int, _ storage: NSTextStorage) -> QueryStatementHint?)? + var statementLocator: ( + @MainActor (_ text: String, _ offset: Int, _ storage: NSTextStorage, _ grammar: SQLLexicalGrammar) async + -> QueryStatementHint? + )? private var favoriteKeywords: [String: (name: String, query: String)] = [:] private var session: Session? @@ -132,8 +135,13 @@ final class QueryCompletionAdapter: CodeSuggestionDelegate { let offset = liveCursorPosition.range.location guard offset >= 0, offset <= text.length else { return nil } + let service = service let localStart = service.tokenStart(in: text, endingAt: offset) - let statement = storage.flatMap { statementLocator?(snapshot, offset, $0) } + var statement: QueryStatementHint? + if let storage, let grammar = service.statementGrammar, let locate = statementLocator { + statement = await locate(snapshot, offset, storage, grammar) + guard !Task.isCancelled else { return nil } + } guard let result = await service.completions( in: text, diff --git a/apple/TablePro/Views/Editor/SQLEditorController.swift b/apple/TablePro/Views/Editor/SQLEditorController.swift index 572178f244..f63b9c8f50 100644 --- a/apple/TablePro/Views/Editor/SQLEditorController.swift +++ b/apple/TablePro/Views/Editor/SQLEditorController.swift @@ -86,8 +86,8 @@ final class SQLEditorController { observeEditorSettings() observeVimMode() observeSessionChanges() - completionAdapter.statementLocator = { [weak coordinator] text, offset, storage in - coordinator?.maintainedStatement(at: offset, in: text, storage: storage) + completionAdapter.statementLocator = { [weak coordinator] text, offset, storage, grammar in + await coordinator?.completionStatement(at: offset, in: text, storage: storage, grammar: grammar) } configureCompletion() setupFavoritesObserver() diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index 33a8c57da4..b9d496379d 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -414,13 +414,19 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie return statementRunController.statement(at: cursor, in: snapshot, storage: storage) } - func maintainedStatement(at offset: Int, in text: String, storage: NSTextStorage) -> QueryStatementHint? { - guard hasInstalledEditorServices, !isDestroyed, - storage === controller?.textView?.textStorage, - let found = statementRunController.maintainedStatement(at: offset, in: text, storage: storage) else { + func completionStatement( + at offset: Int, + in text: String, + storage: NSTextStorage, + grammar: SQLLexicalGrammar + ) async -> QueryStatementHint? { + guard hasInstalledEditorServices, !isDestroyed, storage === controller?.textView?.textStorage, + let statement = await statementRunController.warmedStatement( + at: offset, in: text, storage: storage, grammar: grammar + ) else { return nil } - return QueryStatementHint(range: found.statement.range, grammar: found.grammar) + return QueryStatementHint(range: statement.range, grammar: grammar) } // Matched against the text this editor shows, which the tab's binding can lag; an edited-away statement resolves to nothing. diff --git a/apple/TablePro/Views/Editor/StatementRunController.swift b/apple/TablePro/Views/Editor/StatementRunController.swift index 4a565a9bff..2ec81e9216 100644 --- a/apple/TablePro/Views/Editor/StatementRunController.swift +++ b/apple/TablePro/Views/Editor/StatementRunController.swift @@ -42,7 +42,7 @@ final class StatementRunController { didSet { if grammar != oldValue { caretIndex = nil - rememberedStatement = nil + dropRememberedStatement() } } } @@ -54,7 +54,7 @@ final class StatementRunController { if statementModel != oldValue { caretIndex = nil caretTable = nil - rememberedStatement = nil + dropRememberedStatement() } } } @@ -66,6 +66,12 @@ final class StatementRunController { private var caretIndexEdits: StorageEditObservation? // Completion asks for the caret the band just resolved, so a long statement is not scanned twice per key. private var rememberedStatement: (cursor: Int, statement: SQLStatementScanner.LocatedStatement)? + // An index warmed off the main thread comes back after the text may have moved on. `indexEpoch` moves when the + // index is dropped; the edits since the warm began trim it to the text as it is now. + private var indexEpoch = 0 + private var editSerial = 0 + private var recentEditLocations: [Int] = [] + private static let recentEditLimit = 512 var caretIndexUnitsScanned: Int { caretIndex?.unitsScanned ?? 0 @@ -235,6 +241,72 @@ final class StatementRunController { return (indexedStatement(at: cursor, in: text, storage: storage), grammar) } + // A document the band does not keep is scanned off the main thread on the caller's snapshot. The index the scan + // leaves is kept for the next request, trimmed to any edit made while it ran. + func warmedStatement( + at cursor: Int, + in text: String, + storage: NSTextStorage, + grammar requested: SQLLexicalGrammar + ) async -> SQLStatementScanner.LocatedStatement? { + guard statementModel == .sql, grammar == requested else { return nil } + if let maintained = maintainedStatement(at: cursor, in: text, storage: storage) { + return maintained.statement + } + let ticket = beginWarm(storage: storage) + if let remembered = rememberedStatement, remembered.cursor == cursor { + return remembered.statement + } + let (statement, warmed) = await Self.locate(cursor, in: text, using: ticket.index) + finishWarm(ticket, warmed: warmed, cursor: cursor, statement: statement) + return statement + } + + struct WarmTicket { + let epoch: Int + let serial: Int + let index: SQLStatementCursorIndex + } + + func beginWarm(storage: NSTextStorage) -> WarmTicket { + if caretIndexStorage !== storage { + observeEdits(on: storage) + } + if storage.editedMask.contains(.editedCharacters) { + textDidChange(at: storage.editedRange.location) + } + return WarmTicket(epoch: indexEpoch, serial: editSerial, index: caretIndex ?? SQLStatementCursorIndex(grammar: grammar)) + } + + // Dropped when the index was dropped meanwhile, or when more edits came in than are remembered. + func finishWarm( + _ ticket: WarmTicket, + warmed: SQLStatementCursorIndex, + cursor: Int, + statement: SQLStatementScanner.LocatedStatement + ) { + let missed = editSerial - ticket.serial + guard ticket.epoch == indexEpoch, missed <= recentEditLocations.count else { return } + var index = warmed + if let floor = recentEditLocations.suffix(missed).min() { + index.textDidChange(at: floor) + } else { + rememberedStatement = (cursor, statement) + } + caretIndex = index + } + + @concurrent + nonisolated private static func locate( + _ cursor: Int, + in text: String, + using index: SQLStatementCursorIndex + ) async -> (SQLStatementScanner.LocatedStatement, SQLStatementCursorIndex) { + var index = index + let statement = index.statementAtCursor(cursor, in: text) + return (statement, index) + } + /// Moves the band to the statement the caret is in. Call after the selection changes. func refreshHighlight(in controller: TextViewController?) { guard let controller else { return } @@ -246,7 +318,7 @@ final class StatementRunController { pendingRefresh = nil caretIndex = nil caretTable = nil - rememberedStatement = nil + dropRememberedStatement() caretIndexStorage = nil caretIndexEdits = nil controller?.runnableStatements = [] @@ -343,12 +415,23 @@ final class StatementRunController { caretIndex?.textDidChange(at: location) caretTable = nil rememberedStatement = nil + editSerial += 1 + recentEditLocations.append(location) + if recentEditLocations.count > Self.recentEditLimit { + recentEditLocations.removeFirst(recentEditLocations.count - Self.recentEditLimit) + } + } + + private func dropRememberedStatement() { + rememberedStatement = nil + indexEpoch &+= 1 + recentEditLocations.removeAll() } private func observeEdits(on storage: NSTextStorage) { caretIndex = nil caretTable = nil - rememberedStatement = nil + dropRememberedStatement() caretIndexStorage = storage // Every way the text changes passes through the storage, including the ones that skip the editor's delegate. let token = NotificationCenter.default.addObserver( diff --git a/apple/TableProTests/Views/Editor/QueryCompletionAdapterLifecycleTests.swift b/apple/TableProTests/Views/Editor/QueryCompletionAdapterLifecycleTests.swift index 7a317b4c71..2149b672fe 100644 --- a/apple/TableProTests/Views/Editor/QueryCompletionAdapterLifecycleTests.swift +++ b/apple/TableProTests/Views/Editor/QueryCompletionAdapterLifecycleTests.swift @@ -524,10 +524,12 @@ extension GlobalStateSuites { // MARK: - The band's statement @MainActor - private func locator(for band: StatementRunController) -> @MainActor (String, Int, NSTextStorage) -> QueryStatementHint? { - { text, offset, storage in - band.maintainedStatement(at: offset, in: text, storage: storage).map { - QueryStatementHint(range: $0.statement.range, grammar: $0.grammar) + private func locator( + for band: StatementRunController + ) -> @MainActor (String, Int, NSTextStorage, SQLLexicalGrammar) async -> QueryStatementHint? { + { text, offset, storage, grammar in + await band.warmedStatement(at: offset, in: text, storage: storage, grammar: grammar).map { + QueryStatementHint(range: $0.range, grammar: grammar) } } } @@ -597,7 +599,49 @@ extension GlobalStateSuites { #expect(service.statements == [nil]) } - // The band reads MySQL with no database type while completion reads ANSI, so the band's statement goes unused. + @MainActor + @Test("with the band off, completion still reads the caret's statement and rescans only near the caret") + func bandOffCompletionWarmsTheIndex() async throws { + let grammar = DatabaseType.mysql.lexicalGrammar + let controller = EditorControllerFixture.make( + string: String(repeating: "SELECT id FROM t WHERE id = 1;\n", count: 10_000) + ) + let band = StatementRunController() + band.grammar = grammar + band.isHighlightEnabled = false + band.install(on: controller) + let service = StatementRecordingCompletionService(grammar: grammar) + let adapter = QueryCompletionAdapter(serviceForTesting: service) + adapter.statementLocator = locator(for: band) + let first = CursorPosition(range: NSRange(location: controller.textView.textStorage.length, length: 0)) + controller.setCursorPositions([first]) + _ = await adapter.completionSuggestionsRequested(textView: controller, cursorPosition: first, isManualTrigger: true) + let scannedAfterWarming = band.caretIndexUnitsScanned + let keys = 20 + + for _ in 0.. 0) + #expect( + band.caretIndexUnitsScanned - scannedAfterWarming + <= keys * (SQLStatementCursorIndex.defaultCheckpointSpacing + 40) + ) + } + + // The band reads MySQL with no database type while completion reads ANSI, so no statement is passed. @MainActor @Test("an editor with no database type completes as it does with no statement passed") func editorWithNoDatabaseTypeCompletesAsWithoutAStatement() async { @@ -668,6 +712,7 @@ private extension Trait where Self == AppSettingsTrait { private final class TokenBoundCompletionService: QueryCompletionService { private let items: [SQLCompletionItem] var whileAnswering: (@MainActor () -> Void)? + var statementGrammar: SQLLexicalGrammar? { nil } init(labels: [String]) { items = labels.map { SQLCompletionItem.keyword($0) } @@ -712,6 +757,7 @@ private final class RankingInputRecordingCompletionService: QueryCompletionServi private let items: [SQLCompletionItem] private let poolLimit: Int private(set) var rankingInputCounts: [Int] = [] + var statementGrammar: SQLLexicalGrammar? { nil } init(items: [SQLCompletionItem], poolLimit: Int) { self.items = items @@ -753,6 +799,11 @@ private final class RankingInputRecordingCompletionService: QueryCompletionServi @MainActor private final class StatementRecordingCompletionService: QueryCompletionService { private(set) var statements: [QueryStatementHint?] = [] + let statementGrammar: SQLLexicalGrammar? + + init(grammar: SQLLexicalGrammar? = DatabaseType.mysql.lexicalGrammar) { + statementGrammar = grammar + } var triggerCharacters: Set { [] } diff --git a/apple/TableProTests/Views/Editor/StatementRunControllerTests.swift b/apple/TableProTests/Views/Editor/StatementRunControllerTests.swift index 353599db44..57b41976b7 100644 --- a/apple/TableProTests/Views/Editor/StatementRunControllerTests.swift +++ b/apple/TableProTests/Views/Editor/StatementRunControllerTests.swift @@ -449,4 +449,101 @@ struct StatementRunControllerTests { let swapped = subject.maintainedStatement(at: caret, in: other.textView.string, storage: otherStorage) expectFreshScan(swapped?.statement, at: caret, in: other.textView.string, grammar: TestGrammar.standard) } + + // MARK: - Completion's statement where the band does not keep the index + + @Test("Past the size limit completion's statement is warmed off the main thread and equals a fresh scan") + func warmedStatementPastTheSizeLimitEqualsAFreshScan() async throws { + let controller = makeController(text: String(repeating: Self.mixedScript, count: 30)) + let subject = makeSubject(grammar: TestGrammar.mysql, sizeLimit: 100) + subject.install(on: controller) + let storage = try #require(controller.textView.textStorage) + var seed: UInt64 = 0x51_7CC1_B727_220A + func next(_ bound: Int) -> Int { + seed = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 + return Int((seed >> 33) % UInt64(max(bound, 1))) + } + + for _ in 0..<20 { + controller.textView.replaceCharacters( + in: NSRange(location: next(storage.length + 1), length: 0), + with: [";", "'", "x", "\n", "#"][next(5)] + ) + let text = controller.textView.string + for _ in 0..<3 { + let caret = next((text as NSString).length + 1) + let statement = await subject.warmedStatement( + at: caret, in: text, storage: storage, grammar: TestGrammar.mysql + ) + expectFreshScan(statement, at: caret, in: text, grammar: TestGrammar.mysql) + } + } + } + + @Test("A warmed index is kept, so the next request near the caret rescans only near it") + func warmedIndexIsKeptForTheNextRequest() async throws { + let controller = makeController(text: String(repeating: "SELECT 1;\n", count: 5_000)) + let subject = makeSubject(sizeLimit: 100) + subject.install(on: controller) + let storage = try #require(controller.textView.textStorage) + _ = await subject.warmedStatement( + at: storage.length, in: controller.textView.string, storage: storage, grammar: TestGrammar.standard + ) + let warmed = subject.caretIndexUnitsScanned + #expect(warmed >= storage.length) + + controller.textView.replaceCharacters(in: NSRange(location: storage.length, length: 0), with: "SELECT ") + let text = controller.textView.string + let statement = await subject.warmedStatement( + at: storage.length, in: text, storage: storage, grammar: TestGrammar.standard + ) + + expectFreshScan(statement, at: storage.length, in: text, grammar: TestGrammar.standard) + #expect(subject.caretIndexUnitsScanned - warmed <= SQLStatementCursorIndex.defaultCheckpointSpacing + 40) + } + + @Test("An edit made while a warm runs trims the index it leaves to the text as it is now") + func editDuringAWarmTrimsTheIndex() throws { + let script = String(repeating: "SELECT 1;\n", count: 3_000) + let controller = makeController(text: script) + let subject = makeSubject(sizeLimit: 100) + subject.install(on: controller) + let storage = try #require(controller.textView.textStorage) + let caret = storage.length + + let ticket = subject.beginWarm(storage: storage) + var warmed = ticket.index + let statement = warmed.statementAtCursor(caret, in: script) + controller.textView.replaceCharacters(in: NSRange(location: 15_000, length: 0), with: "/*") + subject.finishWarm(ticket, warmed: warmed, cursor: caret, statement: statement) + + let text = controller.textView.string + let ends = [storage.length, 20_000, 14_000] + for end in ends { + expectFreshScan( + subject.statement(at: end, in: text, storage: storage), + at: end, in: text, grammar: TestGrammar.standard + ) + } + } + + @Test("A warm that comes back after the grammar changed is not kept, and another grammar gets no statement") + func warmAcrossAGrammarChangeIsDropped() async throws { + let controller = makeController(text: String(repeating: "SELECT 1;\n", count: 1_000)) + let subject = makeSubject(sizeLimit: 100) + subject.install(on: controller) + let storage = try #require(controller.textView.textStorage) + + let ticket = subject.beginWarm(storage: storage) + var warmed = ticket.index + let statement = warmed.statementAtCursor(storage.length, in: controller.textView.string) + subject.grammar = TestGrammar.mysql + subject.finishWarm(ticket, warmed: warmed, cursor: storage.length, statement: statement) + + #expect(subject.caretIndexUnitsScanned == 0) + let other = await subject.warmedStatement( + at: 0, in: controller.textView.string, storage: storage, grammar: TestGrammar.standard + ) + #expect(other == nil) + } } From fcf6c32e750d93297bd3bb3e32d431d40035f838 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 13:27:19 +0700 Subject: [PATCH 5/5] docs(changelog): editor perf fixes --- apple/changelog.d/4428.fixed.1.md | 1 + apple/changelog.d/4428.fixed.2.md | 1 + apple/changelog.d/4428.fixed.md | 1 + 3 files changed, 3 insertions(+) create mode 100644 apple/changelog.d/4428.fixed.1.md create mode 100644 apple/changelog.d/4428.fixed.2.md create mode 100644 apple/changelog.d/4428.fixed.md diff --git a/apple/changelog.d/4428.fixed.1.md b/apple/changelog.d/4428.fixed.1.md new file mode 100644 index 0000000000..b0d464d6b3 --- /dev/null +++ b/apple/changelog.d/4428.fixed.1.md @@ -0,0 +1 @@ +Typing, completion and running the statement at the caret got slower as a script grew. diff --git a/apple/changelog.d/4428.fixed.2.md b/apple/changelog.d/4428.fixed.2.md new file mode 100644 index 0000000000..5a046956a7 --- /dev/null +++ b/apple/changelog.d/4428.fixed.2.md @@ -0,0 +1 @@ +Accessibility apps read a wrong character count from the query editor when the text held emoji. diff --git a/apple/changelog.d/4428.fixed.md b/apple/changelog.d/4428.fixed.md new file mode 100644 index 0000000000..8e0999638d --- /dev/null +++ b/apple/changelog.d/4428.fixed.md @@ -0,0 +1 @@ +Opening a long script in a window's first editor took seconds and gigabytes of memory.