forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRealtimeSuggestionController.swift
More file actions
239 lines (209 loc) · 8.61 KB
/
RealtimeSuggestionController.swift
File metadata and controls
239 lines (209 loc) · 8.61 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
import ActiveApplicationMonitor
import AppKit
import AsyncAlgorithms
import AXExtension
import AXNotificationStream
import CGEventObserver
import Environment
import Foundation
import Logger
import QuartzCore
import XPCShared
@ServiceActor
public class RealtimeSuggestionController {
public nonisolated static let shared = RealtimeSuggestionController()
var eventObserver: CGEventObserverType = CGEventObserver(eventsOfInterest: [
.keyUp,
.keyDown,
.rightMouseDown,
.leftMouseDown,
])
private var task: Task<Void, Error>?
private var inflightPrefetchTask: Task<Void, Error>?
private var windowChangeObservationTask: Task<Void, Error>?
private var activeApplicationMonitorTask: Task<Void, Error>?
private var editorObservationTask: Task<Void, Error>?
private var focusedUIElement: AXUIElement?
var isCommentMode: Bool {
PresentationMode(
rawValue: UserDefaults.shared
.integer(forKey: SettingsKey.suggestionPresentationMode)
) == .comment
}
private nonisolated init() {
Task { [weak self] in
if let app = ActiveApplicationMonitor.activeXcode {
await self?.handleXcodeChanged(app)
await startHIDObservation(by: 1)
}
var previousApp = ActiveApplicationMonitor.activeXcode
for await app in ActiveApplicationMonitor.createStream() {
guard let self else { return }
try Task.checkCancellation()
defer { previousApp = app }
if let app = ActiveApplicationMonitor.activeXcode, app != previousApp {
await self.handleXcodeChanged(app)
}
#warning(
"TOOD: Is it possible to get rid of hid event observation with only AXObserver?"
)
if ActiveApplicationMonitor.activeXcode != nil {
await startHIDObservation(by: 1)
} else {
await stopHIDObservation(by: 1)
}
}
}
}
private func startHIDObservation(by listener: AnyHashable) {
Logger.service.info("Add auto trigger listener: \(listener).")
if task == nil {
task = Task { [weak self, eventObserver] in
for await event in eventObserver.createStream() {
guard let self else { return }
await self.handleHIDEvent(event: event)
}
}
}
eventObserver.activateIfPossible()
}
private func stopHIDObservation(by listener: AnyHashable) {
Logger.service.info("Remove auto trigger listener: \(listener).")
task?.cancel()
task = nil
eventObserver.deactivate()
}
private func handleXcodeChanged(_ app: NSRunningApplication) {
windowChangeObservationTask?.cancel()
windowChangeObservationTask = nil
observeXcodeWindowChangeIfNeeded(app)
}
private func observeXcodeWindowChangeIfNeeded(_ app: NSRunningApplication) {
guard windowChangeObservationTask == nil else { return }
handleFocusElementChange()
windowChangeObservationTask = Task { [weak self] in
let notifications = AXNotificationStream(
app: app,
notificationNames: kAXFocusedUIElementChangedNotification,
kAXMainWindowChangedNotification
)
for await _ in notifications {
guard let self else { return }
try Task.checkCancellation()
self.handleFocusElementChange()
}
}
}
private func handleFocusElementChange() {
guard let activeXcode = ActiveApplicationMonitor.activeXcode else { return }
let application = AXUIElementCreateApplication(activeXcode.processIdentifier)
guard let focusElement = application.focusedElement else { return }
let focusElementType = focusElement.description
guard focusElementType == "Source Editor" else { return }
focusedUIElement = focusElement
editorObservationTask?.cancel()
editorObservationTask = nil
editorObservationTask = Task { [weak self] in
let notificationsFromEditor = AXNotificationStream(
app: activeXcode,
element: focusElement,
notificationNames: kAXValueChangedNotification
)
for await notification in notificationsFromEditor {
guard let self else { return }
try Task.checkCancellation()
await cancelInFlightTasks()
switch notification.name {
case kAXValueChangedNotification:
self.triggerPrefetchDebounced()
default:
continue
}
}
}
}
func handleHIDEvent(event: CGEvent) async {
guard await Environment.isXcodeActive() else { return }
// Mouse clicks should cancel in-flight tasks.
if [CGEventType.rightMouseDown, .leftMouseDown].contains(event.type) {
await cancelInFlightTasks()
return
}
let keycode = Int(event.getIntegerValueField(.keyboardEventKeycode))
let escape = 0x35
let arrowKeys = [0x7B, 0x7C, 0x7D, 0x7E]
// Arrow keys should cancel in-flight tasks.
if arrowKeys.contains(keycode) {
await cancelInFlightTasks()
return
}
// Escape should cancel in-flight tasks.
// Except that when the completion panel is presented, it should trigger prefetch instead.
if keycode == escape {
if event.type == .keyDown {
await cancelInFlightTasks()
} else {
let task = Task {
#warning(
"TODO: Any method to avoid using AppleScript to check that completion panel is presented?"
)
if isCommentMode, await Environment.frontmostXcodeWindowIsEditor() {
if Task.isCancelled { return }
self.triggerPrefetchDebounced(force: true)
}
}
inflightRealtimeSuggestionsTasks.insert(task)
}
}
}
func triggerPrefetchDebounced(force: Bool = false) {
inflightPrefetchTask = Task { @ServiceActor in
try? await Task.sleep(nanoseconds: UInt64((
UserDefaults.shared
.value(forKey: SettingsKey.realtimeSuggestionDebounce) as? Double
?? 0.7
) * 1_000_000_000))
guard UserDefaults.shared.bool(forKey: SettingsKey.realtimeSuggestionToggle)
else { return }
if Task.isCancelled { return }
Logger.service.info("Prefetch suggestions.")
if !force, isCommentMode, await !Environment.frontmostXcodeWindowIsEditor() {
Logger.service.info("Completion panel is open, blocked.")
return
}
// So the editor won't be blocked (after information are cached)!
await PseudoCommandHandler().generateRealtimeSuggestions()
}
}
func cancelInFlightTasks(excluding: Task<Void, Never>? = nil) async {
inflightPrefetchTask?.cancel()
// cancel in-flight tasks
await withTaskGroup(of: Void.self) { group in
for (_, workspace) in workspaces {
group.addTask {
await workspace.cancelInFlightRealtimeSuggestionRequests()
}
}
group.addTask {
await { @ServiceActor in
inflightRealtimeSuggestionsTasks.forEach {
if $0 == excluding { return }
$0.cancel()
}
inflightRealtimeSuggestionsTasks.removeAll()
if let excluded = excluding {
inflightRealtimeSuggestionsTasks.insert(excluded)
}
}()
}
}
}
/// This method will still return true if the completion panel is hidden by esc.
/// Looks like the Xcode will keep the panel around until content is changed,
/// not sure how to observe that it's hidden.
func isCompletionPanelPresenting() -> Bool {
guard let activeXcode = ActiveApplicationMonitor.activeXcode else { return false }
let application = AXUIElementCreateApplication(activeXcode.processIdentifier)
return application.focusedWindow?.child(identifier: "_XC_COMPLETION_TABLE_") != nil
}
}