forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRealtimeSuggestionIndicatorController.swift
More file actions
213 lines (195 loc) · 7.32 KB
/
RealtimeSuggestionIndicatorController.swift
File metadata and controls
213 lines (195 loc) · 7.32 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
import AppKit
import DisplayLink
import Environment
import QuartzCore
import SwiftUI
import XPCShared
/// 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 userDefaultsObserver = UserDefaultsObserver()
var isObserving = false {
didSet {
Task {
await updateIndicatorVisibility()
}
}
}
private var displayLinkTask: Task<Void, Never>?
@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() {
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 {
if displayLinkTask == nil {
displayLinkTask = Task {
for await _ in DisplayLink.createStream() {
self.updateIndicatorLocation()
}
}
}
} else {
displayLinkTask?.cancel()
displayLinkTask = nil
}
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.alphaValue = 1
window.setFrame(frame, display: false, animate: true)
return
}
}
}
window.alphaValue = 0
}
}
func triggerPrefetchAnimation() {
Task { @MainActor in
viewModel.prefetch()
}
}
}