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
238 lines (206 loc) · 9 KB
/
RealtimeSuggestionController.swift
File metadata and controls
238 lines (206 loc) · 9 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
import ActiveApplicationMonitor
import AppKit
import AsyncAlgorithms
import AXExtension
import AXNotificationStream
import CGEventObserver
import Environment
import Foundation
import Logger
import Preferences
import QuartzCore
import XcodeInspector
@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?
private var sourceEditor: SourceEditor?
private nonisolated init() {
Task { [weak self] in
if let app = ActiveApplicationMonitor.activeXcode {
await self?.handleXcodeChanged(app)
await self?.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)
}
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
focusedUIElement = focusElement
Task { // Notify suggestion service for open file.
try await Task.sleep(nanoseconds: 500_000_000)
let fileURL = try await Environment.fetchCurrentFileURL()
_ = try await Workspace.fetchOrCreateWorkspaceIfNeeded(fileURL: fileURL)
}
guard focusElementType == "Source Editor" else { return }
sourceEditor = SourceEditor(runningApplication: activeXcode, element: focusElement)
editorObservationTask?.cancel()
editorObservationTask = nil
editorObservationTask = Task { [weak self] in
let notificationsFromEditor = AXNotificationStream(
app: activeXcode,
element: focusElement,
notificationNames: kAXValueChangedNotification, kAXSelectedTextChangedNotification
)
for await notification in notificationsFromEditor {
guard let self else { return }
try Task.checkCancellation()
switch notification.name {
case kAXValueChangedNotification:
await cancelInFlightTasks()
self.triggerPrefetchDebounced()
await self.notifyEditingFileChange(editor: focusElement)
case kAXSelectedTextChangedNotification:
guard let sourceEditor else { continue }
await PseudoCommandHandler()
.invalidateRealtimeSuggestionsIfNeeded(sourceEditor: sourceEditor)
default:
continue
}
}
}
Task { // Get cache ready for real-time suggestions.
guard UserDefaults.shared.value(for: \.preCacheOnFileOpen) else { return }
let fileURL = try await Environment.fetchCurrentFileURL()
let (_, filespace) = try await Workspace
.fetchOrCreateWorkspaceIfNeeded(fileURL: fileURL)
if filespace.uti == nil {
Logger.service.info("Generate cache for file.")
// avoid the command get called twice
filespace.uti = ""
do {
try await Environment.triggerAction("Real-time Suggestions")
} catch {
if filespace.uti?.isEmpty ?? true {
filespace.uti = nil
}
}
}
}
}
func handleHIDEvent(event: CGEvent) async {
guard await Environment.isXcodeActive() else { return }
let keycode = Int(event.getIntegerValueField(.keyboardEventKeycode))
let escape = 0x35
// 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()
}
}
}
func triggerPrefetchDebounced(force: Bool = false) {
inflightPrefetchTask = Task { @ServiceActor in
try? await Task.sleep(nanoseconds: UInt64((
UserDefaults.shared.value(for: \.realtimeSuggestionDebounce)
) * 1_000_000_000))
guard UserDefaults.shared.value(for: \.realtimeSuggestionToggle)
else { return }
if UserDefaults.shared.value(for: \.disableSuggestionFeatureGlobally),
let fileURL = try? await Environment.fetchCurrentFileURL(),
let (workspace, _) = try? await Workspace
.fetchOrCreateWorkspaceIfNeeded(fileURL: fileURL)
{
let isEnabled = workspace.isSuggestionFeatureEnabled
if !isEnabled { return }
}
if Task.isCancelled { return }
// Logger.service.info("Prefetch suggestions.")
// So the editor won't be blocked (after information are cached)!
await PseudoCommandHandler().generateRealtimeSuggestions(sourceEditor: sourceEditor)
}
}
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()
}
}
}
}
/// 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
}
func notifyEditingFileChange(editor: AXUIElement) async {
guard let fileURL = try? await Environment.fetchCurrentFileURL(),
let (workspace, filespace) = try? await Workspace
.fetchOrCreateWorkspaceIfNeeded(fileURL: fileURL)
else { return }
workspace.notifyUpdateFile(filespace: filespace, content: editor.value)
}
}