-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathCursorPositionTracker.swift
More file actions
53 lines (46 loc) · 1.57 KB
/
CursorPositionTracker.swift
File metadata and controls
53 lines (46 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import Combine
import Foundation
import Perception
import SuggestionBasic
import XcodeInspector
@Perceptible
final class CursorPositionTracker {
@MainActor
var cursorPosition: CursorPosition = .zero
@PerceptionIgnored var editorObservationTask: Set<AnyCancellable> = []
@PerceptionIgnored var eventObservationTask: Task<Void, Never>?
init() {
observeAppChange()
}
deinit {
eventObservationTask?.cancel()
}
private func observeAppChange() {
editorObservationTask = []
Task {
await XcodeInspector.shared.safe.$focusedEditor.sink { [weak self] editor in
guard let editor, let self else { return }
Task { @MainActor in
self.observeAXNotifications(editor)
}
}.store(in: &editorObservationTask)
}
}
private func observeAXNotifications(_ editor: SourceEditor) {
eventObservationTask?.cancel()
let content = editor.getLatestEvaluatedContent()
Task { @MainActor in
self.cursorPosition = content.cursorPosition
}
eventObservationTask = Task { [weak self] in
for await event in await editor.axNotifications.notifications() {
guard let self else { return }
guard event.kind == .evaluatedContentChanged else { continue }
let content = editor.getLatestEvaluatedContent()
Task { @MainActor in
self.cursorPosition = content.cursorPosition
}
}
}
}
}