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
244 lines (228 loc) · 8.47 KB
/
PseudoCommandHandler.swift
File metadata and controls
244 lines (228 loc) · 8.47 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
import ActiveApplicationMonitor
import AppKit
import CopilotModel
import Environment
import Preferences
import SuggestionInjector
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() async {
guard let editor = await getEditorContent() else {
try? await Environment.triggerAction("Prefetch Suggestions")
return
}
let mode = UserDefaults.shared.value(for: \.suggestionPresentationMode)
let handler: SuggestionCommandHandler = {
switch mode {
case .comment:
return CommentBaseCommandHandler()
case .floatingWidget:
return WindowBaseCommandHandler()
}
}()
_ = try? await handler.generateRealtimeSuggestions(editor: editor)
}
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 acceptSuggestion() async {
if UserDefaults.shared.value(for: \.acceptSuggestionWithAccessibilityAPI) {
guard let xcode = ActiveApplicationMonitor.activeXcode 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() else {
PresentInWindowSuggestionPresenter()
.presentErrorMessage("Unable to get file content.")
return
}
let handler = CommentBaseCommandHandler()
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 error = AXUIElementSetAttributeValue(
focusElement,
kAXValueAttribute as CFString,
result.content as CFTypeRef
)
if error != AXError.success {
PresentInWindowSuggestionPresenter()
.presentErrorMessage("Fail to set editor content.")
}
if let cursor = result.newCursor {
var range = convertCursorPositionToRange(cursor, 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
)
}
}
} catch {
PresentInWindowSuggestionPresenter().presentError(error)
}
} else {
do {
try await Environment.triggerAction("Accept Suggestion")
return
} catch {
PresentInWindowSuggestionPresenter().presentError(error)
}
}
}
}
private extension PseudoCommandHandler {
func getFileContent() async
-> (content: String, lines: [String], cursorPosition: CursorPosition)?
{
guard let xcode = ActiveApplicationMonitor.activeXcode
?? ActiveApplicationMonitor.latestXcode else { return nil }
let application = AXUIElementCreateApplication(xcode.processIdentifier)
guard let focusElement = 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 selectedPosition = selectionRange.upperBound
// find row and col from content at selected position
var rowIndex = 0
var count = 0
var colIndex = 0
for (i, row) in split.enumerated() {
if count + row.count > selectedPosition {
rowIndex = i
colIndex = selectedPosition - count
break
}
count += row.count
}
return (content, split, CursorPosition(line: rowIndex, character: colIndex))
}
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() async -> EditorContent? {
guard
let filespace = await getFilespace(),
let content = await getFileContent()
else { return nil }
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: [],
tabSize: tabSize,
indentSize: indentSize,
usesTabsForIndentation: usesTabsForIndentation
)
}
// a function to convert CursorPosition(line:character:) into a Range(location:length) in given
// content
func convertCursorPositionToRange(
_ cursorPosition: CursorPosition,
in content: String
) -> CFRange {
let lines = content.breakLines()
var count = 0
for (i, line) in lines.enumerated() {
if i == cursorPosition.line {
return CFRange(location: count + cursorPosition.character, length: 0)
}
count += line.count
}
return CFRange(location: count, length: 0)
}
}
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
}
}