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
5 changes: 4 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ let package = Package(
],
targets: [
.target(name: "Runestone", dependencies: [
"TreeSitter"
"TreeSitter",
"TreeSitterSupport"
], resources: [
.copy("PrivacyInfo.xcprivacy"),
.process("TextView/Appearance/Theme.xcassets")
Expand All @@ -27,12 +28,14 @@ let package = Package(
publicHeadersPath: "include",
cSettings: [.headerSearchPath("src"), .define("_DARWIN_C_SOURCE")]
),
.target(name: "TreeSitterSupport", dependencies: ["TreeSitter"]),
.target(name: "TestTreeSitterLanguages", cSettings: [
.headerSearchPath("private"),
.unsafeFlags(["-w"])
]),
.testTarget(name: "RunestoneTests", dependencies: [
"Runestone",
"TreeSitterSupport",
"TestTreeSitterLanguages"
])
],
Expand Down
1 change: 1 addition & 0 deletions Sources/Runestone/Library/NSString+Helpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ extension NSString {
if didGetBytes {
return UnsafePointer<Int8>(buffer)
} else {
buffer.deallocate()
return nil
}
}
Expand Down
62 changes: 39 additions & 23 deletions Sources/Runestone/TextView/Core/LayoutManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,37 @@ final class LayoutManager {
}
}
/// The text covered by the fragments from the most recent viewport layout.
private(set) var visibleTextRange: NSRange?
var visibleTextRange: NSRange? {
visibleTextRanges.reduce(nil as NSRange?) { result, range in
result.map { NSUnionRange($0, range) } ?? range
}
}
/// Individual visible ranges avoid including hidden columns between long unwrapped lines.
private(set) var visibleTextRanges: [NSRange] = []
var visibleTextRanges: [NSRange] {
if let cachedVisibleTextRanges {
return cachedVisibleTextRanges
}
let ranges = visibleTextFragments.flatMap { snapshot in
let localRanges = snapshot.horizontalRange.map { horizontalRange in
LineFragmentRenderer.visibleCharacterRanges(in: horizontalRange, lineFragment: snapshot.fragment)
} ?? [snapshot.fragment.visibleRange]
return localRanges.map { localRange in
NSRange(location: snapshot.lineLocation + localRange.location, length: localRange.length)
}
}
cachedVisibleTextRanges = ranges
return ranges
}

// Freeze the completed layout's drawing objects and coordinates. Controllers
// can receive new fragments before the next layout; spelling must not mix them.
private struct VisibleTextFragment {
let fragment: LineFragment
let lineLocation: Int
let horizontalRange: ClosedRange<CGFloat>?
}
private var visibleTextFragments: [VisibleTextFragment] = []
private var cachedVisibleTextRanges: [NSRange]?

// MARK: - Views
let gutterContainerView = GutterContainerView()
Expand Down Expand Up @@ -576,8 +604,8 @@ extension LayoutManager {
private func layoutLinesInViewport() {
// Immediately bail out from generating lines in a viewport of zero size.
guard viewport.size.width > 0 && viewport.size.height > 0 else {
visibleTextRange = nil
visibleTextRanges = []
visibleTextFragments = []
cachedVisibleTextRanges = []
return
}
let highlightDestinationSynchronously = needsSynchronousDestinationHighlight
Expand All @@ -598,8 +626,7 @@ extension LayoutManager {
var nextLine = lineManager.line(containingYOffset: insetViewport.minY)
var appearedLineIDs: Set<DocumentLineNodeID> = []
var appearedLineFragmentIDs: Set<LineFragmentID> = []
var visibleRange: NSRange?
var visibleRanges: [NSRange] = []
var textFragments: [VisibleTextFragment] = []
var maxY = insetViewport.minY
while let line = nextLine, maxY < insetViewport.maxY, constrainingLineWidth > 0 {
appearedLineIDs.insert(line.id)
Expand Down Expand Up @@ -632,11 +659,10 @@ extension LayoutManager {
let lineFragment = lineFragmentController.lineFragment
var lineFragmentFrame: CGRect = .zero
appearedLineFragmentIDs.insert(lineFragment.id)
for localRange in visibleCharacterRanges(in: lineFragmentController) {
let documentRange = NSRange(location: line.location + localRange.location, length: localRange.length)
visibleRange = visibleRange.map { NSUnionRange($0, documentRange) } ?? documentRange
visibleRanges.append(documentRange)
}
let horizontalRange: ClosedRange<CGFloat>? = isLineWrappingEnabled ? nil
: (viewport.minX - leadingLineSpacing - 32) ... (viewport.maxX - leadingLineSpacing + 32)
textFragments.append(VisibleTextFragment(fragment: lineFragment, lineLocation: line.location,
horizontalRange: horizontalRange))
updateSpelling(on: lineFragmentController, lineLocation: line.location)
lineFragmentController.highlightedRangeFragments = highlightService.highlightedRangeFragments(for: lineFragment,
inLineWithID: line.id)
Expand Down Expand Up @@ -665,8 +691,8 @@ extension LayoutManager {
linesContainerView.frame = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)
// Update the visible lines and line fragments. Clean up everything that is not in the viewport anymore.
visibleLineIDs = appearedLineIDs
visibleTextRange = visibleRange
visibleTextRanges = visibleRanges
visibleTextFragments = textFragments
cachedVisibleTextRanges = nil
let disappearedLineIDs = oldVisibleLineIDs.subtracting(appearedLineIDs)
let disappearedLineFragmentIDs = oldVisibleLineFragmentIDs.subtracting(appearedLineFragmentIDs)
for disappearedLineID in disappearedLineIDs {
Expand Down Expand Up @@ -863,16 +889,6 @@ extension LayoutManager {

// MARK: - Spelling
private extension LayoutManager {
private func visibleCharacterRanges(in controller: LineFragmentController) -> [NSRange] {
if isLineWrappingEnabled {
return [controller.lineFragment.visibleRange]
}
// Include partially visible glyphs and a small margin; the spelling service expands to word boundaries.
let lowerBound = viewport.minX - leadingLineSpacing - 32
let upperBound = viewport.maxX - leadingLineSpacing + 32
return controller.visibleCharacterRanges(in: lowerBound ... upperBound)
}

private func updateSpellingOnVisibleLines() {
for lineID in visibleLineIDs {
guard let lineController = lineControllerStorage[lineID] else {
Expand Down
4 changes: 3 additions & 1 deletion Sources/Runestone/TextView/Core/TextInputView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2260,7 +2260,9 @@ extension TextInputView {
}

private func checkVisibleSpellingIfNeeded() {
let languages = resolvedSpellingLanguages
// Language discovery can contact system services. Disabled spelling only
// needs to clear an existing request, without discovering its languages.
let languages = isSpellCheckingEnabled ? resolvedSpellingLanguages : []
guard isSpellCheckingEnabled, !languages.isEmpty,
!layoutManager.visibleTextRanges.isEmpty else {
if lastSpellingRequest != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ final class LineFragmentRenderer {

/// A horizontally scrolled viewport can cover disjoint logical ranges in bidirectional text.
func visibleCharacterRanges(in horizontalRange: ClosedRange<CGFloat>) -> [NSRange] {
Self.visibleCharacterRanges(in: horizontalRange, lineFragment: lineFragment)
}

static func visibleCharacterRanges(in horizontalRange: ClosedRange<CGFloat>, lineFragment: LineFragment) -> [NSRange] {
let runs = CTLineGetGlyphRuns(lineFragment.line) as? [CTRun] ?? []
return runs.compactMap { run in
guard let bounds = horizontalBounds(of: run), bounds.overlaps(horizontalRange) else {
Expand Down Expand Up @@ -77,7 +81,7 @@ final class LineFragmentRenderer {
let stringRange = CTRunGetStringRange(run)
let runRange = NSRange(location: stringRange.location, length: stringRange.length)
let intersection = NSIntersectionRange(visibleRange, runRange)
guard intersection.length > 0, let bounds = horizontalBounds(of: run) else {
guard intersection.length > 0, let bounds = Self.horizontalBounds(of: run) else {
return nil
}
let runMinX = bounds.lowerBound
Expand Down Expand Up @@ -134,7 +138,7 @@ private extension LineFragmentRenderer {
}
}

private func horizontalBounds(of run: CTRun) -> ClosedRange<CGFloat>? {
private static func horizontalBounds(of run: CTRun) -> ClosedRange<CGFloat>? {
let count = CTRunGetGlyphCount(run)
guard count > 0 else {
return nil
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import Foundation

/// Owns document-sized resources while work is pending or awaiting main-thread
/// application. Queued closures hold this request weakly so cancellation can
/// release a completed snapshot without waiting for the main queue to drain.
final class TreeSitterHighlightRequest {
struct Completed {
let snapshot: TreeSitterHighlightSnapshot
let captures: [TreeSitterCapture]
}

private let lock = NSLock()
private let resourceDisposer: TreeSitterHighlightResourceDisposer
private var pendingSnapshot: TreeSitterHighlightSnapshot?
private var completed: Completed?
private var isCancelled = false

init(snapshot: TreeSitterHighlightSnapshot, resourceDisposer: TreeSitterHighlightResourceDisposer = .shared) {
pendingSnapshot = snapshot
self.resourceDisposer = resourceDisposer
}

func takeSnapshot() -> TreeSitterHighlightSnapshot? {
lock.lock()
defer { lock.unlock() }
let snapshot = pendingSnapshot
pendingSnapshot = nil
return snapshot
}

func complete(snapshot: TreeSitterHighlightSnapshot, captures: [TreeSitterCapture]) {
lock.lock()
defer { lock.unlock() }
guard !isCancelled else {
return
}
completed = Completed(snapshot: snapshot, captures: captures)
}

func takeCompleted() -> Completed? {
lock.lock()
defer { lock.unlock() }
let result = completed
completed = nil
return result
}

func cancel() {
lock.lock()
isCancelled = true
guard pendingSnapshot != nil || completed != nil else {
lock.unlock()
return
}
let resources = TreeSitterHighlightResources(snapshot: pendingSnapshot, completed: completed)
pendingSnapshot = nil
completed = nil
lock.unlock()
resourceDisposer.dispose(resources)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import Foundation

/// The wrapper owns canceled resources exclusively. Clearing its fields releases
/// them on the selected executor even if the wrapper itself still has a caller.
final class TreeSitterHighlightResources {
private var snapshot: TreeSitterHighlightSnapshot?
private var completed: TreeSitterHighlightRequest.Completed?

init(snapshot: TreeSitterHighlightSnapshot?, completed: TreeSitterHighlightRequest.Completed?) {
self.snapshot = snapshot
self.completed = completed
}

func clear() {
snapshot = nil
completed = nil
}
}

/// At most one canceled payload may await or undergo background destruction.
/// Bursts apply synchronous backpressure instead of retaining a queue of old
/// documents. This queue never owns an executing query's snapshot.
final class TreeSitterHighlightResourceDisposer {
static let shared = TreeSitterHighlightResourceDisposer(queue: {
let queue = OperationQueue()
queue.name = "Runestone.HighlightResourceDisposal"
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 1
return queue
}())

private let queue: OperationQueue
private let lock = NSLock()
private var isDisposing = false

// The executor must remain active. Production owns a dedicated private queue;
// injection lets lifetime tests suspend and drain their own isolated queue.
init(queue: OperationQueue) {
self.queue = queue
}

func dispose(_ resources: TreeSitterHighlightResources) {
lock.lock()
let canDisposeAsynchronously = !isDisposing
if canDisposeAsynchronously { isDisposing = true }
lock.unlock()

guard canDisposeAsynchronously else {
resources.clear()
return
}
queue.addOperation { [self, resources] in
autoreleasepool {
resources.clear()
}
// Release the slot only after the heavy fields have been cleared;
// the operation closure can outlive this point without retaining them.
lock.lock()
isDisposing = false
lock.unlock()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ private extension TreeSitterLanguageLayer {
injectionsQueryCursor.execute()
let captures = injectionsQueryCursor.validCaptures(in: stringView)
let injectedLanguages = injectedLanguages(from: captures)
let capturedIDs = injectedLanguages.map(\.id)
let capturedIDs = Set(injectedLanguages.map(\.id))
let currentIDs = childLanguageLayerStore.allIDs
for id in currentIDs {
if !capturedIDs.contains(id) {
Expand Down
Loading
Loading