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
362 lines (327 loc) · 12.9 KB
/
RealtimeSuggestionController.swift
File metadata and controls
362 lines (327 loc) · 12.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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import AppKit
import CGEventObserver
import Foundation
import os.log
import QuartzCore
import SwiftUI
import XPCShared
public actor RealtimeSuggestionController {
public static let shared = RealtimeSuggestionController()
private var listeners = Set<AnyHashable>()
var eventObserver: CGEventObserverType = CGEventObserver(eventsOfInterest: [
.keyUp,
.keyDown,
.rightMouseDown,
.leftMouseDown,
])
private var task: Task<Void, Error>?
private var inflightPrefetchTask: Task<Void, Error>?
let realtimeSuggestionIndicatorController = RealtimeSuggestionIndicatorController()
private init() {
// Start the auto trigger if Xcode is running.
Task {
for xcode in await Environment.runningXcodes() {
await start(by: xcode.processIdentifier)
}
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didLaunchApplicationNotification)
for await notification in sequence {
try Task.checkCancellation()
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
else { continue }
guard app.bundleIdentifier == "com.apple.dt.Xcode" else { continue }
await start(by: app.processIdentifier)
}
}
// Remove listener if Xcode is terminated.
Task {
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didTerminateApplicationNotification)
for await notification in sequence {
try Task.checkCancellation()
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
else { continue }
guard app.bundleIdentifier == "com.apple.dt.Xcode" else { continue }
await stop(by: app.processIdentifier)
}
}
}
private func start(by listener: AnyHashable) {
os_log(.info, "Add auto trigger listener: %@.", listener as CVarArg)
listeners.insert(listener)
if task == nil {
task = Task { [stream = eventObserver.stream] in
for await event in stream {
await self.handleKeyboardEvent(event: event)
}
}
}
if eventObserver.activateIfPossible() {
realtimeSuggestionIndicatorController?.isObserving = true
}
}
private func stop(by listener: AnyHashable) {
os_log(.info, "Remove auto trigger listener: %@.", listener as CVarArg)
listeners.remove(listener)
guard listeners.isEmpty else { return }
os_log(.info, "Auto trigger is stopped.")
task?.cancel()
task = nil
eventObserver.deactivate()
realtimeSuggestionIndicatorController?.isObserving = false
}
func handleKeyboardEvent(event: CGEvent) async {
inflightPrefetchTask?.cancel()
if Task.isCancelled { return }
guard await Environment.isXcodeActive() else { return }
// cancel in-flight tasks
await withTaskGroup(of: Void.self) { group in
for (_, workspace) in await workspaces {
group.addTask {
await workspace.cancelInFlightRealtimeSuggestionRequests()
}
}
group.addTask {
await { @ServiceActor in
inflightRealtimeSuggestionsTasks.forEach { $0.cancel() }
inflightRealtimeSuggestionsTasks.removeAll()
}()
}
}
let escape = 0x35
let isEditing = await Environment.frontmostXcodeWindowIsEditor()
// if Xcode suggestion panel is presenting, and we are not trying to close it
// ignore this event.
if !isEditing, event.getIntegerValueField(.keyboardEventKeycode) != escape {
return
}
let shouldTrigger = {
// closing auto-complete panel
if isEditing, event.getIntegerValueField(.keyboardEventKeycode) == escape {
return true
}
// normally typing
if event.type == .keyUp,
event.getIntegerValueField(.keyboardEventKeycode) != escape
{
return true
}
return false
}()
guard shouldTrigger else { return }
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 }
os_log(.info, "Prefetch suggestions.")
realtimeSuggestionIndicatorController?.triggerPrefetchAnimation()
do {
try await Environment.triggerAction("Prefetch Suggestions")
} catch {
os_log(.info, "%@", error.localizedDescription)
}
}
}
}
/// Present a tiny dot next to mouse cursor if real-time suggestion is enabled.
final class RealtimeSuggestionIndicatorController {
class IndicatorContentViewModel: ObservableObject {
@Published var isPrefetching = false
private var prefetchTask: Task<Void, Error>?
@MainActor
func prefetch() {
prefetchTask?.cancel()
withAnimation(.easeIn(duration: 0.2)) {
isPrefetching = true
}
prefetchTask = Task {
try await Task.sleep(nanoseconds: 2 * 1_000_000_000)
withAnimation(.easeOut(duration: 0.2)) {
isPrefetching = false
}
}
}
}
struct IndicatorContentView: View {
@ObservedObject var viewModel: IndicatorContentViewModel
@State var progress: CGFloat = 1
var opacityA: CGFloat { min(progress, 0.7) }
var opacityB: CGFloat { 1 - progress }
var scaleA: CGFloat { progress / 2 + 0.5 }
var scaleB: CGFloat { max(1 - progress, 0.01) }
var body: some View {
Circle()
.fill(Color.accentColor.opacity(opacityA))
.scaleEffect(.init(width: scaleA, height: scaleA))
.frame(width: 8, height: 8)
.background(
Circle()
.fill(Color.white.opacity(viewModel.isPrefetching ? opacityB : 0))
.scaleEffect(.init(width: scaleB, height: scaleB))
.frame(width: 8, height: 8)
)
.onAppear {
Task {
await Task.yield() // to avoid unwanted translations.
withAnimation(.easeInOut(duration: 1).repeatForever(autoreverses: true)) {
progress = 0
}
}
}
}
}
class UserDefaultsObserver: NSObject {
var onChange: (() -> Void)?
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
onChange?()
}
}
private let viewModel = IndicatorContentViewModel()
private var displayLink: CVDisplayLink!
private var isDisplayLinkStarted: Bool = false
private var userDefaultsObserver = UserDefaultsObserver()
var isObserving = false {
didSet {
Task {
await updateIndicatorVisibility()
}
}
}
@MainActor
lazy var window = {
let it = NSWindow(
contentRect: .zero,
styleMask: .borderless,
backing: .buffered,
defer: false
)
it.isReleasedWhenClosed = false
it.isOpaque = false
it.backgroundColor = .white.withAlphaComponent(0)
it.level = .statusBar
it.contentView = NSHostingView(
rootView: IndicatorContentView(viewModel: self.viewModel)
.frame(minWidth: 10, minHeight: 10)
)
return it
}()
init?() {
_ = CVDisplayLinkCreateWithCGDisplay(CGMainDisplayID(), &displayLink)
guard displayLink != nil else { return nil }
CVDisplayLinkSetOutputHandler(displayLink) { [weak self] _, _, _, _, _ in
guard let self else { return kCVReturnSuccess }
self.updateIndicatorLocation()
return kCVReturnSuccess
}
Task {
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didActivateApplicationNotification)
for await notification in sequence {
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
else { continue }
guard app.bundleIdentifier == "com.apple.dt.Xcode" else { continue }
await updateIndicatorVisibility()
}
}
Task {
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didDeactivateApplicationNotification)
for await notification in sequence {
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
else { continue }
guard app.bundleIdentifier == "com.apple.dt.Xcode" else { continue }
await updateIndicatorVisibility()
}
}
Task {
userDefaultsObserver.onChange = { [weak self] in
Task { [weak self] in
await self?.updateIndicatorVisibility()
}
}
UserDefaults.shared.addObserver(
userDefaultsObserver,
forKeyPath: SettingsKey.realtimeSuggestionToggle,
options: .new,
context: nil
)
}
}
private func updateIndicatorVisibility() async {
let isVisible = await {
let isOn = UserDefaults.shared.bool(forKey: SettingsKey.realtimeSuggestionToggle)
let isXcodeActive = await Environment.isXcodeActive()
return isOn && isXcodeActive && isObserving
}()
await { @MainActor in
guard window.isVisible != isVisible else { return }
if isVisible {
CVDisplayLinkStart(self.displayLink)
} else {
CVDisplayLinkStop(self.displayLink)
}
window.setIsVisible(isVisible)
}()
}
private func updateIndicatorLocation() {
Task { @MainActor in
if !window.isVisible {
return
}
if let activeXcode = NSRunningApplication
.runningApplications(withBundleIdentifier: "com.apple.dt.Xcode")
.first(where: \.isActive)
{
let application = AXUIElementCreateApplication(activeXcode.processIdentifier)
if let focusElement: AXUIElement = try? application
.copyValue(key: kAXFocusedUIElementAttribute),
let selectedRange: AXValue = try? focusElement
.copyValue(key: kAXSelectedTextRangeAttribute),
let rect: AXValue = try? focusElement.copyParameterizedValue(
key: kAXBoundsForRangeParameterizedAttribute,
parameters: selectedRange
)
{
var frame: CGRect = .zero
let found = AXValueGetValue(rect, .cgRect, &frame)
let screen = NSScreen.screens.first
if found, let screen {
frame.origin = .init(
x: frame.maxX + 2,
y: screen.frame.height - frame.minY - 4
)
frame.size = .init(width: 10, height: 10)
window.setFrame(frame, display: false)
window.makeKey()
return
}
}
}
var frame = window.frame
let location = NSEvent.mouseLocation
frame.origin = .init(x: location.x + 15, y: location.y + 15)
frame.size = .init(width: 10, height: 10)
window.setFrame(frame, display: false)
window.makeKey()
}
}
func triggerPrefetchAnimation() {
Task { @MainActor in
viewModel.prefetch()
}
}
}