From 6188aad4aeea0cc128f0aff440b8bef71e9b6f92 Mon Sep 17 00:00:00 2001 From: 1024jp <1024jp@wolfrosch.com> Date: Tue, 12 Mar 2024 13:38:42 +1100 Subject: [PATCH] Refactor timing to cancel document analysis --- CotEditor/Sources/Document.swift | 1 + CotEditor/Sources/DocumentAnalyzer.swift | 15 ++++++++------- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/CotEditor/Sources/Document.swift b/CotEditor/Sources/Document.swift index df08f712d..ee4437da1 100644 --- a/CotEditor/Sources/Document.swift +++ b/CotEditor/Sources/Document.swift @@ -132,6 +132,7 @@ final class Document: NSDocument, AdditionalDocumentPreparing, EncodingChanging deinit { self.syntaxParser.cancel() + self.analyzer.cancel() self.urlDetector.cancel() } diff --git a/CotEditor/Sources/DocumentAnalyzer.swift b/CotEditor/Sources/DocumentAnalyzer.swift index 318131f9b..84683f4f3 100644 --- a/CotEditor/Sources/DocumentAnalyzer.swift +++ b/CotEditor/Sources/DocumentAnalyzer.swift @@ -57,14 +57,15 @@ final class DocumentAnalyzer { } - deinit { - self.task?.cancel() - } - - // MARK: Public Methods + /// Cancels all remaining tasks. + func cancel() { + + self.task?.cancel() + } + /// Updates editor info (only if really needed). /// /// - Parameter onlySelection: `true` to invalidate only the selection. @@ -91,7 +92,7 @@ final class DocumentAnalyzer { let delay: Duration = .milliseconds(self.needsCountWholeText ? 10 : 200) self.task?.cancel() - self.task = Task { [weak self, weak textView] in + self.task = Task { [weak textView] in try await Task.sleep(for: delay, tolerance: .milliseconds(10)) // debounce guard let textView else { return } @@ -104,7 +105,7 @@ final class DocumentAnalyzer { try Task.checkCancellation() // selectedRanges can be empty when the document is already closed - guard !selectedRanges.isEmpty, let self else { return } + guard !selectedRanges.isEmpty else { return } let countsWholeText = self.needsCountWholeText let counter = EditorCounter(string: string, selectedRanges: selectedRanges, requiredInfo: self.requiredInfoTypes, countsWholeText: countsWholeText)