Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,30 @@ public protocol LineFoldProvider: AnyObject {
/// The provider owns this string because it is the only part of the folding system the host application supplies,
/// so it is the only part that can reach the application's localized strings.
func foldPlaceholderLabel(for summary: FoldPlaceholderSummary) -> String

// A provider that finds every fold in one pass returns that pass here. The calculator runs it on a copy of the
// text off the main thread and skips the per-line walk, which has to stay on the main thread.
func documentFoldScanner() -> LineFoldDocumentScanner?
}

public extension LineFoldProvider {
func foldPlaceholderLabel(for summary: FoldPlaceholderSummary) -> String {
summary.previewText
}

func documentFoldScanner() -> LineFoldDocumentScanner? {
nil
}
}

public struct LineFoldProviderFold: Sendable, Equatable {
public let depth: Int
public let range: Range<Int>

public init(depth: Int, range: Range<Int>) {
self.depth = depth
self.range = range
}
}

public typealias LineFoldDocumentScanner = @Sendable (String) -> [LineFoldProviderFold]
Original file line number Diff line number Diff line change
Expand Up @@ -8,42 +8,57 @@
import AppKit
import TableProTextEngine

/// `LineFoldCalculator` receives text edits and rebuilds fold regions asynchronously.
///
/// This is an actor, all methods and modifications happen in isolation in it's async region. All text requests are
/// marked `@MainActor` for safety.
// Each pass carries the document version it read, so the model can drop a result for text that has since changed.
struct LineFoldPass: Sendable {
let storage: LineFoldStorage
let documentVersion: Int
}

@MainActor
final class LineFoldDocumentVersion {
private(set) var value = 0

func advance() {
value &+= 1
}
}

actor LineFoldCalculator {
weak var foldProvider: LineFoldProvider?
weak var controller: TextViewController?

var valueStream: AsyncStream<LineFoldStorage>
var valueStream: AsyncStream<LineFoldPass>

private var valueStreamContinuation: AsyncStream<LineFoldStorage>.Continuation
private var valueStreamContinuation: AsyncStream<LineFoldPass>.Continuation
private var textChangedTask: Task<Void, Never>?
private let documentVersion: LineFoldDocumentVersion

private struct PassStart: Sendable {
let documentRange: NSRange
let sizeLimit: Int
let documentVersion: Int
let scanner: LineFoldDocumentScanner?
let text: String?
}

/// Create a new calculator object that listens to a given stream for text changes.
/// - Parameters:
/// - foldProvider: The object to use to calculate fold regions.
/// - controller: The text controller to use for text and attachment fetching.
/// - textChangedStream: A stream of text changes, received as the document is edited.
init(
foldProvider: LineFoldProvider,
controller: TextViewController,
documentVersion: LineFoldDocumentVersion,
textChangedStream: AsyncStream<Void>
) {
// This could be grabbed from the controller, but Swift 6 doesn't like that (concurrency safety)
self.foldProvider = foldProvider
self.controller = controller
(valueStream, valueStreamContinuation) = AsyncStream<LineFoldStorage>.makeStream()
self.documentVersion = documentVersion
(valueStream, valueStreamContinuation) = AsyncStream<LineFoldPass>.makeStream()
Task { await listenToTextChanges(textChangedStream: textChangedStream) }
}

deinit {
textChangedTask?.cancel()
}

/// Sets up an attached task to listen to values on a stream of text changes.
/// - Parameter textChangedStream: A stream of text changes.
private func listenToTextChanges(textChangedStream: AsyncStream<Void>) {
textChangedTask = Task {
for await _ in textChangedStream {
Expand All @@ -52,18 +67,63 @@ actor LineFoldCalculator {
}
}

/// Build out the folds for the entire document.
///
/// For each line in the document, find the indentation level using the ``levelProvider``. At each line, if the
/// indent increases from the previous line, we start a new fold. If it decreases we end the fold we were in.
private func buildFoldsForDocument() async {
guard let controller = self.controller, let foldProvider = self.foldProvider else { return }
let documentRange = await controller.textView.documentRange
let sizeLimit = await controller.configuration.peripherals.foldingSizeLimit
guard documentRange.length <= sizeLimit else {
valueStreamContinuation.yield(LineFoldStorage(documentLength: documentRange.length))
let start = await Self.startPass(
controller: controller,
foldProvider: foldProvider,
documentVersion: documentVersion
)
guard start.documentRange.length <= start.sizeLimit else {
valueStreamContinuation.yield(
LineFoldPass(
storage: LineFoldStorage(documentLength: start.documentRange.length),
documentVersion: start.documentVersion
)
)
return
}

let folds: [LineFoldStorage.RawFold]
if let scanner = start.scanner, let text = start.text {
folds = scanner(text).map { LineFoldStorage.RawFold(depth: $0.depth, range: $0.range) }
} else {
folds = await walkLines(controller: controller, foldProvider: foldProvider, documentRange: start.documentRange)
}

await yieldNewStorage(
newFolds: folds,
controller: controller,
documentRange: start.documentRange,
documentVersion: start.documentVersion
)
}

// Bridging the storage's mutable string gives an immutable copy, so the scanner can read it from the calculator's
// own executor while the main thread goes on editing.
@MainActor
private static func startPass(
controller: TextViewController,
foldProvider: LineFoldProvider,
documentVersion: LineFoldDocumentVersion
) -> PassStart {
let documentRange = controller.textView.documentRange
let sizeLimit = controller.configuration.peripherals.foldingSizeLimit
let scanner = documentRange.length <= sizeLimit ? foldProvider.documentFoldScanner() : nil
return PassStart(
documentRange: documentRange,
sizeLimit: sizeLimit,
documentVersion: documentVersion.value,
scanner: scanner,
text: scanner == nil ? nil : controller.textView.textStorage.string
)
}

private func walkLines(
controller: TextViewController,
foldProvider: LineFoldProvider,
documentRange: NSRange
) async -> [LineFoldStorage.RawFold] {
var foldCache: [LineFoldStorage.RawFold] = []
// Depth: Open range
var openFolds: [Int: LineFoldStorage.RawFold] = [:]
Expand Down Expand Up @@ -109,19 +169,14 @@ actor LineFoldCalculator {
)
)
}

await yieldNewStorage(newFolds: foldCache, controller: controller, documentRange: documentRange)
return foldCache
}

/// Yield a new storage value on the value stream using a new set of folds.
/// - Parameters:
/// - newFolds: The new folds to yield with the storage value.
/// - controller: The text controller used for range and attachment fetching.
/// - documentRange: The total range of the current document.
private func yieldNewStorage(
newFolds: [LineFoldStorage.RawFold],
controller: TextViewController,
documentRange: NSRange
documentRange: NSRange,
documentVersion: Int
) async {
let attachments = await controller.textView.layoutManager.attachments
.getAttachmentsOverlapping(documentRange)
Expand All @@ -136,16 +191,17 @@ actor LineFoldCalculator {
documentLength: newFolds.max(
by: { $0.range.upperBound < $1.range.upperBound }
)?.range.upperBound ?? documentRange.length,
folds: newFolds.sorted(by: { $0.range.lowerBound < $1.range.lowerBound }),
// The store keeps the fold set last where two overlap, so of folds that start together the outermost goes
// last and is the one shown, whichever order the provider reported them in.
folds: newFolds.sorted {
$0.range.lowerBound == $1.range.lowerBound ? $0.depth > $1.depth : $0.range.lowerBound < $1.range.lowerBound
},
collapsedRanges: Set(attachments)
)
valueStreamContinuation.yield(storage)
valueStreamContinuation.yield(LineFoldPass(storage: storage, documentVersion: documentVersion))
}

/// Asynchronously gets more line information from the fold provider.
/// Runs on the main thread so all text-related calculations are safe with the main text storage.
///
/// Has to be an `AsyncSequence` so it can be main actor isolated.
// An `AsyncSequence` so the provider's per-line calls run on the main actor, where the text storage lives.
@MainActor
struct ChunkedLineIterator: AsyncSequence, AsyncIteratorProtocol {
var controller: TextViewController
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,34 +26,49 @@ class LineFoldModel: NSObject, NSTextStorageDelegate, ObservableObject {
@Published var foldCache = LineFoldStorage(documentLength: 0)
private var calculator: LineFoldCalculator

// StatementRunController's threshold and delay: below it a pass costs less than a keystroke, above it a pass on
// every key would keep a core busy while the user types.
static let immediateRecalculationLimit = 64_000
static let recalculationDelay: Duration = .milliseconds(150)

private var textChangedStream: AsyncStream<Void>
private var textChangedStreamContinuation: AsyncStream<Void>.Continuation
private var cacheListenTask: Task<Void, Never>?
private let documentVersion: LineFoldDocumentVersion
private let clock: any Clock<Duration>
private var pendingRecalculation: Task<Void, Never>?
private var pendingRestoreRanges: Set<Range<Int>>?
private var placeholderTracker: LineFoldPlaceholderTracker?

weak var controller: TextViewController?
weak var foldView: NSView?

init(controller: TextViewController, foldView: NSView) {
init(controller: TextViewController, foldView: NSView, clock: any Clock<Duration> = ContinuousClock()) {
self.controller = controller
self.foldView = foldView
self.clock = clock
(textChangedStream, textChangedStreamContinuation) = AsyncStream<Void>.makeStream(
bufferingPolicy: .bufferingNewest(1)
)
let documentVersion = LineFoldDocumentVersion()
self.documentVersion = documentVersion
self.calculator = LineFoldCalculator(
foldProvider: controller.foldProvider,
controller: controller,
documentVersion: documentVersion,
textChangedStream: textChangedStream
)
super.init()
controller.textView.addStorageDelegate(self)

let calculator = self.calculator
cacheListenTask = Task { @MainActor [weak self, weak foldView] in
for await newFolds in await calculator.valueStream {
for await pass in await calculator.valueStream {
guard let self else { return }
self.foldCache = newFolds
// An edit after the pass read the text queued another pass; until it lands `storageUpdated` keeps
// the current folds in step with the text.
guard pass.documentVersion == self.documentVersion.value else { continue }
self.foldCache = pass.storage
foldView?.needsDisplay = true
self.applyPendingRestoreIfPossible()
}
Expand All @@ -78,6 +93,7 @@ class LineFoldModel: NSObject, NSTextStorageDelegate, ObservableObject {
gutterHover = nil
placeholderHover = nil
hoveredFold = nil
documentVersion.advance()
foldCache = LineFoldStorage(documentLength: controller?.textView.documentRange.length ?? 0)
pendingRestoreRanges = nil
refresh()
Expand All @@ -93,6 +109,8 @@ class LineFoldModel: NSObject, NSTextStorageDelegate, ObservableObject {
placeholderTracker = nil
cacheListenTask?.cancel()
cacheListenTask = nil
pendingRecalculation?.cancel()
pendingRecalculation = nil
}

// MARK: - Collapse
Expand Down Expand Up @@ -256,11 +274,31 @@ class LineFoldModel: NSObject, NSTextStorageDelegate, ObservableObject {
)
}

/// Recomputes folds for the whole document. Used to catch up after the ribbon has been hidden and is shown again.
func refresh() {
pendingRecalculation?.cancel()
pendingRecalculation = nil
textChangedStreamContinuation.yield()
}

private func scheduleRecalculation(documentLength: Int) {
guard documentLength > Self.immediateRecalculationLimit else {
refresh()
return
}
pendingRecalculation?.cancel()
let clock = clock
pendingRecalculation = Task { [weak self] in
do {
try await clock.sleep(for: Self.recalculationDelay)
} catch {
return
}
guard let self, !Task.isCancelled else { return }
self.pendingRecalculation = nil
self.textChangedStreamContinuation.yield()
}
}

func textStorage(
_ textStorage: NSTextStorage,
didProcessEditing editedMask: NSTextStorageEditActions,
Expand All @@ -270,11 +308,12 @@ class LineFoldModel: NSObject, NSTextStorageDelegate, ObservableObject {
guard editedMask.contains(.editedCharacters) else {
return
}
documentVersion.advance()
foldCache.storageUpdated(editedRange: editedRange, changeInLength: delta)
// Recalculating folds walks the whole document. Skip it while the ribbon is hidden; `refresh()` rebuilds when
// it is shown again.
guard foldView?.isHidden != true else { return }
textChangedStreamContinuation.yield()
scheduleRecalculation(documentLength: textStorage.length)
}

/// Finds the deepest cached fold and depth of the fold for a line number.
Expand Down
Loading
Loading