forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPseudoCommandHandler.swift
More file actions
348 lines (323 loc) · 12.4 KB
/
PseudoCommandHandler.swift
File metadata and controls
348 lines (323 loc) · 12.4 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import ActiveApplicationMonitor
import AppKit
import Environment
import Preferences
import SuggestionInjector
import SuggestionModel
import XcodeInspector
import XPCShared
/// It's used to run some commands without really triggering the menu bar item.
///
/// For example, we can use it to generate real-time suggestions without Apple Scripts.
struct PseudoCommandHandler {
func presentPreviousSuggestion() async {
let handler = WindowBaseCommandHandler()
_ = try? await handler.presentPreviousSuggestion(editor: .init(
content: "",
lines: [],
uti: "",
cursorPosition: .outOfScope,
selections: [],
tabSize: 0,
indentSize: 0,
usesTabsForIndentation: false
))
}
func presentNextSuggestion() async {
let handler = WindowBaseCommandHandler()
_ = try? await handler.presentNextSuggestion(editor: .init(
content: "",
lines: [],
uti: "",
cursorPosition: .outOfScope,
selections: [],
tabSize: 0,
indentSize: 0,
usesTabsForIndentation: false
))
}
func generateRealtimeSuggestions(sourceEditor: SourceEditor?) async {
// Can't use handler if content is not available.
guard
let editor = await getEditorContent(sourceEditor: sourceEditor),
let filespace = await getFilespace()
else { return }
if await filespace.validateSuggestions(
lines: editor.lines,
cursorPosition: editor.cursorPosition
) {
return
} else {
PresentInWindowSuggestionPresenter().discardSuggestion(fileURL: filespace.fileURL)
}
// Otherwise, get it from pseudo handler directly.
let mode = UserDefaults.shared.value(for: \.suggestionPresentationMode)
switch mode {
case .comment:
let handler = CommentBaseCommandHandler()
_ = try? await handler.generateRealtimeSuggestions(editor: editor)
case .floatingWidget:
let handler = WindowBaseCommandHandler()
_ = try? await handler.generateRealtimeSuggestions(editor: editor)
}
}
func invalidateRealtimeSuggestionsIfNeeded(sourceEditor: SourceEditor) async {
guard let fileURL = try? await Environment.fetchCurrentFileURL(),
let (_, filespace) = try? await Workspace
.fetchOrCreateWorkspaceIfNeeded(fileURL: fileURL) else { return }
if await !filespace.validateSuggestions(
lines: sourceEditor.content.lines,
cursorPosition: sourceEditor.content.cursorPosition
) {
PresentInWindowSuggestionPresenter().discardSuggestion(fileURL: fileURL)
}
}
func rejectSuggestions() async {
let handler = WindowBaseCommandHandler()
_ = try? await handler.rejectSuggestion(editor: .init(
content: "",
lines: [],
uti: "",
cursorPosition: .outOfScope,
selections: [],
tabSize: 0,
indentSize: 0,
usesTabsForIndentation: false
))
}
func handleCustomCommand(_ command: CustomCommand) async {
guard let editor = await {
if let it = await getEditorContent(sourceEditor: nil) {
return it
}
switch command.feature {
// editor content is not required.
case .customChat, .chatWithSelection:
return .init(
content: "",
lines: [],
uti: "",
cursorPosition: .outOfScope,
selections: [],
tabSize: 0,
indentSize: 0,
usesTabsForIndentation: false
)
// editor content is required.
case .promptToCode:
return nil
}
}() else {
do {
try await Environment.triggerAction(command.name)
} catch {
let presenter = PresentInWindowSuggestionPresenter()
presenter.presentError(error)
}
return
}
let handler = WindowBaseCommandHandler()
do {
try await handler.handleCustomCommand(id: command.id, editor: editor)
} catch {
let presenter = PresentInWindowSuggestionPresenter()
presenter.presentError(error)
}
}
func acceptSuggestion() async {
if UserDefaults.shared.value(for: \.acceptSuggestionWithAccessibilityAPI) {
guard let xcode = ActiveApplicationMonitor.activeXcode ?? ActiveApplicationMonitor
.latestXcode else { return }
let application = AXUIElementCreateApplication(xcode.processIdentifier)
guard let focusElement = application.focusedElement,
focusElement.description == "Source Editor"
else { return }
guard let (content, lines, _, cursorPosition) = await getFileContent(sourceEditor: nil)
else {
PresentInWindowSuggestionPresenter()
.presentErrorMessage("Unable to get file content.")
return
}
let handler = WindowBaseCommandHandler()
do {
guard let result = try await handler.acceptSuggestion(editor: .init(
content: content,
lines: lines,
uti: "",
cursorPosition: cursorPosition,
selections: [],
tabSize: 0,
indentSize: 0,
usesTabsForIndentation: false
)) else { return }
let oldPosition = focusElement.selectedTextRange
let oldScrollPosition = focusElement.parent?.verticalScrollBar?.doubleValue
let error = AXUIElementSetAttributeValue(
focusElement,
kAXValueAttribute as CFString,
result.content as CFTypeRef
)
if error != AXError.success {
PresentInWindowSuggestionPresenter()
.presentErrorMessage("Fail to set editor content.")
}
if let selection = result.newSelection {
var range = convertCursorRangeToRange(selection, in: result.content)
if let value = AXValueCreate(.cfRange, &range) {
AXUIElementSetAttributeValue(
focusElement,
kAXSelectedTextRangeAttribute as CFString,
value
)
}
} else if let oldPosition {
var range = CFRange(
location: oldPosition.lowerBound,
length: 0
)
if let value = AXValueCreate(.cfRange, &range) {
AXUIElementSetAttributeValue(
focusElement,
kAXSelectedTextRangeAttribute as CFString,
value
)
}
}
if let oldScrollPosition, let scrollBar = focusElement.parent?.verticalScrollBar {
AXUIElementSetAttributeValue(
scrollBar,
kAXValueAttribute as CFString,
oldScrollPosition as CFTypeRef
)
}
} catch {
PresentInWindowSuggestionPresenter().presentError(error)
}
} else {
do {
try await Environment.triggerAction("Accept Suggestion")
return
} catch {
PresentInWindowSuggestionPresenter().presentError(error)
}
}
}
}
extension PseudoCommandHandler {
func getFileContent(sourceEditor: AXUIElement?) async
-> (
content: String,
lines: [String],
selections: [CursorRange],
cursorPosition: CursorPosition
)?
{
guard let xcode = ActiveApplicationMonitor.activeXcode
?? ActiveApplicationMonitor.latestXcode else { return nil }
let application = AXUIElementCreateApplication(xcode.processIdentifier)
guard let focusElement = sourceEditor ?? application.focusedElement,
focusElement.description == "Source Editor"
else { return nil }
guard let selectionRange = focusElement.selectedTextRange else { return nil }
let content = focusElement.value
let split = content.breakLines()
let range = convertRangeToCursorRange(selectionRange, in: content)
return (content, split, [range], range.start)
}
func getFileURL() async -> URL? {
try? await Environment.fetchCurrentFileURL()
}
@ServiceActor
func getFilespace() async -> Filespace? {
guard
let fileURL = await getFileURL(),
let (_, filespace) = try? await Workspace
.fetchOrCreateWorkspaceIfNeeded(fileURL: fileURL)
else { return nil }
return filespace
}
@ServiceActor
func getEditorContent(sourceEditor: SourceEditor?) async -> EditorContent? {
guard let filespace = await getFilespace(), let sourceEditor else { return nil }
let content = sourceEditor.content
let uti = filespace.uti ?? ""
let tabSize = filespace.tabSize ?? 4
let indentSize = filespace.indentSize ?? 4
let usesTabsForIndentation = filespace.usesTabsForIndentation ?? false
return .init(
content: content.content,
lines: content.lines,
uti: uti,
cursorPosition: content.cursorPosition,
selections: content.selections.map {
.init(start: $0.start, end: $0.end)
},
tabSize: tabSize,
indentSize: indentSize,
usesTabsForIndentation: usesTabsForIndentation
)
}
func convertCursorRangeToRange(
_ cursorRange: CursorRange,
in content: String
) -> CFRange {
let lines = content.breakLines()
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
}
func convertRangeToCursorRange(
_ range: ClosedRange<Int>,
in content: String
) -> CursorRange {
let lines = content.breakLines()
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, range.lowerBound < countS + line.count {
cursorRange.start = .init(line: i, character: range.lowerBound - countS)
}
if countE <= range.upperBound, range.upperBound < countE + line.count {
cursorRange.end = .init(line: i, character: range.upperBound - countE)
break
}
countS += line.count
countE += line.count
}
if cursorRange.end == .outOfScope {
cursorRange.end = .init(line: lines.endIndex - 1, character: lines.last?.count ?? 0)
}
return cursorRange
}
}
public extension String {
/// Break a string into lines.
func breakLines() -> [String] {
let lines = split(separator: "\n", omittingEmptySubsequences: false)
var all = [String]()
for (index, line) in lines.enumerated() {
if index == lines.endIndex - 1 {
all.append(String(line))
} else {
all.append(String(line) + "\n")
}
}
return all
}
}