forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSourceEditor.swift
More file actions
254 lines (227 loc) · 9.18 KB
/
SourceEditor.swift
File metadata and controls
254 lines (227 loc) · 9.18 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import AppKit
import AsyncPassthroughSubject
import AXNotificationStream
import Foundation
import Logger
import SuggestionModel
/// Representing a source editor inside Xcode.
public class SourceEditor {
public typealias Content = EditorInformation.SourceEditorContent
public struct AXNotification: Hashable {
public var kind: AXNotificationKind
public var element: AXUIElement
public func hash(into hasher: inout Hasher) {
kind.hash(into: &hasher)
}
}
public enum AXNotificationKind: Hashable, Equatable {
case selectedTextChanged
case valueChanged
case scrollPositionChanged
}
let runningApplication: NSRunningApplication
public let element: AXUIElement
var observeAXNotificationsTask: Task<Void, Never>?
public let axNotifications = AsyncPassthroughSubject<AXNotification>()
/// To prevent expensive calculations in ``getContent()``.
private let cache = Cache()
/// Get the content of the source editor.
///
/// - note: This method is expensive. It needs to convert index based ranges to line based
/// ranges.
public func getContent() -> Content {
let content = element.value
let selectionRange = element.selectedTextRange
let (lines, selections) = cache.get(content: content, selectedTextRange: selectionRange)
let lineAnnotationElements = element.children.filter { $0.identifier == "Line Annotation" }
let lineAnnotations = lineAnnotationElements.map(\.description)
return .init(
content: content,
lines: lines,
selections: selections,
cursorPosition: selections.first?.start ?? .outOfScope,
lineAnnotations: lineAnnotations
)
}
public init(runningApplication: NSRunningApplication, element: AXUIElement) {
self.runningApplication = runningApplication
self.element = element
element.setMessagingTimeout(2)
observeAXNotifications()
}
private func observeAXNotifications() {
observeAXNotificationsTask?.cancel()
observeAXNotificationsTask = Task { @XcodeInspectorActor [weak self] in
guard let self else { return }
await withThrowingTaskGroup(of: Void.self) { [weak self] group in
guard let self else { return }
let editorNotifications = AXNotificationStream(
app: runningApplication,
element: element,
notificationNames:
kAXSelectedTextChangedNotification,
kAXValueChangedNotification
)
group.addTask { [weak self] in
for await notification in editorNotifications {
try Task.checkCancellation()
await Task.yield()
guard let self else { return }
if let kind: AXNotificationKind = {
switch notification.name {
case kAXSelectedTextChangedNotification: return .selectedTextChanged
case kAXValueChangedNotification: return .valueChanged
default: return nil
}
}() {
self.axNotifications.send(.init(
kind: kind,
element: notification.element
))
}
}
}
if let scrollView = element.parent, let scrollBar = scrollView.verticalScrollBar {
let scrollViewNotifications = AXNotificationStream(
app: runningApplication,
element: scrollBar,
notificationNames: kAXValueChangedNotification
)
group.addTask { [weak self] in
for await notification in scrollViewNotifications {
try Task.checkCancellation()
await Task.yield()
guard let self else { return }
self.axNotifications.send(.init(
kind: .scrollPositionChanged,
element: notification.element
))
}
}
}
try? await group.waitForAll()
}
}
}
}
extension SourceEditor {
final class Cache {
static let queue = DispatchQueue(label: "SourceEditor.Cache")
private var sourceContent: String?
private var cachedLines = [String]()
private var sourceSelectedTextRange: ClosedRange<Int>?
private var cachedSelections = [CursorRange]()
init(
sourceContent: String? = nil,
cachedLines: [String] = [String](),
sourceSelectedTextRange: ClosedRange<Int>? = nil,
cachedSelections: [CursorRange] = [CursorRange]()
) {
self.sourceContent = sourceContent
self.cachedLines = cachedLines
self.sourceSelectedTextRange = sourceSelectedTextRange
self.cachedSelections = cachedSelections
}
func get(content: String, selectedTextRange: ClosedRange<Int>?) -> (
lines: [String],
selections: [CursorRange]
) {
Self.queue.sync {
let contentMatch = content == sourceContent
let selectedRangeMatch = selectedTextRange == sourceSelectedTextRange
let lines: [String] = {
if contentMatch {
return cachedLines
}
return content.breakLines(appendLineBreakToLastLine: false)
}()
let selections: [CursorRange] = {
if contentMatch, selectedRangeMatch {
return cachedSelections
}
if let selectedTextRange {
return [SourceEditor.convertRangeToCursorRange(
selectedTextRange,
in: lines
)]
}
return []
}()
sourceContent = content
cachedLines = lines
sourceSelectedTextRange = selectedTextRange
cachedSelections = selections
return (lines, selections)
}
}
}
}
// MARK: - Helpers
public extension SourceEditor {
static func convertCursorRangeToRange(
_ cursorRange: CursorRange,
in lines: [String]
) -> CFRange {
var countS = 0
var countE = 0
var range = CFRange(location: 0, length: 0)
for (i, line) in lines.enumerated() {
if i == cursorRange.start.line {
countS = countS + cursorRange.start.character
range.location = countS
}
if i == cursorRange.end.line {
countE = countE + cursorRange.end.character
range.length = max(countE - range.location, 0)
break
}
countS += line.count
countE += line.count
}
return range
}
static func convertCursorRangeToRange(
_ cursorRange: CursorRange,
in content: String
) -> CFRange {
let lines = content.breakLines(appendLineBreakToLastLine: false)
return convertCursorRangeToRange(cursorRange, in: lines)
}
static func convertRangeToCursorRange(
_ range: ClosedRange<Int>,
in lines: [String]
) -> CursorRange {
guard !lines.isEmpty else { return CursorRange(start: .zero, end: .zero) }
var countS = 0
var countE = 0
var cursorRange = CursorRange(start: .zero, end: .outOfScope)
for (i, line) in lines.enumerated() {
// The range is counted in UTF8, which causes line endings like \r\n to be of length 2.
let lineEndingAddition = line.lineEnding.utf8.count - 1
if countS <= range.lowerBound,
range.lowerBound < countS + line.count + lineEndingAddition
{
cursorRange.start = .init(line: i, character: range.lowerBound - countS)
}
if countE <= range.upperBound,
range.upperBound < countE + line.count + lineEndingAddition
{
cursorRange.end = .init(line: i, character: range.upperBound - countE)
break
}
countS += line.count + lineEndingAddition
countE += line.count + lineEndingAddition
}
if cursorRange.end == .outOfScope {
cursorRange.end = .init(line: lines.endIndex - 1, character: lines.last?.count ?? 0)
}
return cursorRange
}
static func convertRangeToCursorRange(
_ range: ClosedRange<Int>,
in content: String
) -> CursorRange {
let lines = content.breakLines(appendLineBreakToLastLine: false)
return convertRangeToCursorRange(range, in: lines)
}
}