forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSourceEditor.swift
More file actions
296 lines (264 loc) · 10.6 KB
/
SourceEditor.swift
File metadata and controls
296 lines (264 loc) · 10.6 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import AppKit
import AsyncPassthroughSubject
import AXNotificationStream
import Foundation
import Logger
import Status
import SuggestionBasic
/// 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
case evaluatedContentChanged
}
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()
public func getLatestEvaluatedContent() -> Content {
let selectionRange = element.selectedTextRange
let (content, lines, selections) = cache.latest()
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,
cursorOffset: selectionRange?.lowerBound ?? 0,
lineAnnotations: lineAnnotations
)
}
/// 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 = getElementValueAndRecordStatus()
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)
axNotifications.send(.init(kind: .evaluatedContentChanged, element: element))
return .init(
content: content,
lines: lines,
selections: selections,
cursorPosition: selections.first?.start ?? .outOfScope,
cursorOffset: selectionRange?.lowerBound ?? 0,
lineAnnotations: lineAnnotations
)
}
private func getElementValueAndRecordStatus() -> String {
do {
let value: String = try element.copyValue(key: kAXValueAttribute)
Task { await Status.shared.updateAXStatus(.granted) }
return value
} catch AXError.apiDisabled {
Task { await Status.shared.updateAXStatus(.notGranted) }
} catch {
// ignore
}
return ""
}
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)
}
}
func latest() -> (content: String, lines: [String], selections: [CursorRange]) {
Self.queue.sync {
(sourceContent ?? "", cachedLines, cachedSelections)
}
}
}
}
// 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.utf16.count
countE += line.utf16.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() {
if countS <= range.lowerBound,
// when equal, means the cursor is located at the lowerBound
range.lowerBound <= countS + line.utf16.count
{
cursorRange.start = .init(line: i, character: range.lowerBound - countS)
}
if countE <= range.upperBound,
range.upperBound < countE + line.utf16.count
{
cursorRange.end = .init(line: i, character: range.upperBound - countE)
break
}
countS += line.utf16.count
countE += line.utf16.count
}
if cursorRange.end == .outOfScope {
cursorRange.end = .init(
line: lines.endIndex - 1,
character: lines.last?.utf16.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)
}
}