-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
253 lines (231 loc) · 8.42 KB
/
AppDelegate.swift
File metadata and controls
253 lines (231 loc) · 8.42 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
import Combine
import FileChangeChecker
import GitHubCopilotService
import LaunchAgentManager
import Logger
import Preferences
import Service
import ServiceManagement
import Status
import SwiftUI
import UpdateChecker
import UserDefaultsObserver
import UserNotifications
import XcodeInspector
import XPCShared
let bundleIdentifierBase = Bundle.main
.object(forInfoDictionaryKey: "BUNDLE_IDENTIFIER_BASE") as! String
let serviceIdentifier = bundleIdentifierBase + ".ExtensionService"
class ExtensionUpdateCheckerDelegate: UpdateCheckerDelegate {
func prepareForRelaunch(finish: @escaping () -> Void) {
Task {
await Service.shared.prepareForExit()
finish()
}
}
}
@main
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
let service = Service.shared
var statusBarItem: NSStatusItem!
var statusMenuItem: NSMenuItem!
var xpcController: XPCController?
let updateChecker =
UpdateChecker(
hostBundle: Bundle(url: locateHostBundleURL(url: Bundle.main.bundleURL)),
checkerDelegate: ExtensionUpdateCheckerDelegate()
)
let statusChecker: AuthStatusChecker = AuthStatusChecker()
var xpcExtensionService: XPCExtensionService?
private var cancellables = Set<AnyCancellable>()
private var progressView: NSProgressIndicator?
private var idleIcon = NSImage(named: "MenuBarIcon")
func applicationDidFinishLaunching(_: Notification) {
if ProcessInfo.processInfo.environment["IS_UNIT_TEST"] == "YES" { return }
_ = XcodeInspector.shared
service.markAsProcessing = { [weak self] in
guard let self = self else { return }
self.markAsProcessing($0)
}
service.start()
AXIsProcessTrustedWithOptions([
kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true,
] as CFDictionary)
setupQuitOnUpdate()
setupQuitOnUserTerminated()
xpcController = .init()
Logger.service.info("XPC Service started.")
NSApp.setActivationPolicy(.accessory)
buildStatusBarMenu()
watchServiceStatus()
watchAXStatus()
updateStatusBarItem() // set the initial status
}
@objc func quit() {
Task { @MainActor in
await service.prepareForExit()
await xpcController?.quit()
NSApp.terminate(self)
}
}
@objc func openCopilotForXcode() {
let task = Process()
let appPath = locateHostBundleURL(url: Bundle.main.bundleURL)
task.launchPath = "/usr/bin/open"
task.arguments = [appPath.absoluteString]
task.launch()
task.waitUntilExit()
}
@objc func openGlobalChat() {
Task { @MainActor in
let serviceGUI = Service.shared.guiController
serviceGUI.openGlobalChat()
}
}
func setupQuitOnUpdate() {
Task {
guard let url = Bundle.main.executableURL else { return }
let checker = await FileChangeChecker(fileURL: url)
// If Xcode or Copilot for Xcode is made active, check if the executable of this program
// is changed. If changed, quit this program.
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didActivateApplicationNotification)
for await notification in sequence {
try Task.checkCancellation()
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
app.isUserOfService
else { continue }
guard await checker.checkIfChanged() else {
Logger.service.info("Extension Service is not updated, no need to quit.")
continue
}
Logger.service.info("Extension Service will quit.")
#if DEBUG
#else
quit()
#endif
}
}
}
func setupQuitOnUserTerminated() {
Task {
// Whenever Xcode or the host application quits, check if any of the two is running.
// If none, quit the XPC service.
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didTerminateApplicationNotification)
for await notification in sequence {
try Task.checkCancellation()
guard UserDefaults.shared.value(for: \.quitXPCServiceOnXcodeAndAppQuit)
else { continue }
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
app.isUserOfService
else { continue }
if NSWorkspace.shared.runningApplications.contains(where: \.isUserOfService) {
continue
}
quit()
}
}
}
func requestAccessoryAPIPermission() {
AXIsProcessTrustedWithOptions([
kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true,
] as NSDictionary)
}
@objc func checkForUpdate() {
guard let updateChecker = updateChecker else {
Logger.service.error("Unable to check for updates: updateChecker is nil.")
return
}
updateChecker.checkForUpdates()
}
func getXPCExtensionService() -> XPCExtensionService {
if let service = xpcExtensionService { return service }
let service = XPCExtensionService(logger: .service)
xpcExtensionService = service
return service
}
func watchServiceStatus() {
let notifications = NotificationCenter.default.notifications(named: .serviceStatusDidChange)
Task { [weak self] in
for await _ in notifications {
guard let self else { return }
self.updateStatusBarItem()
}
}
}
func watchAXStatus() {
let osNotifications = DistributedNotificationCenter.default().notifications(named: NSNotification.Name("com.apple.accessibility.api"))
Task { [weak self] in
for await _ in osNotifications {
guard let self else { return }
self.updateStatusBarItem()
}
}
}
func updateStatusBarItem() {
Task { @MainActor in
let status = await Status.shared.getStatus()
let image = if status.system {
NSImage(systemSymbolName: status.icon, accessibilityDescription: nil)
} else {
NSImage(named: status.icon)
}
idleIcon = image
self.statusBarItem.button?.image = image
if let message = status.message {
// TODO switch to attributedTitle to enable line breaks and color.
self.statusMenuItem.title = message
self.statusMenuItem.isHidden = false
self.statusMenuItem.isEnabled = status.url != nil
} else {
self.statusMenuItem.isHidden = true
}
}
}
func markAsProcessing(_ isProcessing: Bool) {
if !isProcessing {
// No longer in progress
progressView?.removeFromSuperview()
progressView = nil
statusBarItem.button?.image = idleIcon
return
}
if progressView != nil {
// Already in progress
return
}
let progress = NSProgressIndicator()
progress.style = .spinning
progress.sizeToFit()
progress.frame = statusBarItem.button?.bounds ?? .zero
progress.isIndeterminate = true
progress.startAnimation(nil)
statusBarItem.button?.addSubview(progress)
statusBarItem.button?.image = nil
progressView = progress
}
}
extension NSRunningApplication {
var isUserOfService: Bool {
[
"com.apple.dt.Xcode",
bundleIdentifierBase,
].contains(bundleIdentifier)
}
}
func locateHostBundleURL(url: URL) -> URL {
var nextURL = url
while nextURL.path != "/" {
nextURL = nextURL.deletingLastPathComponent()
if nextURL.lastPathComponent.hasSuffix(".app") {
return nextURL
}
}
let devAppURL = url
.deletingLastPathComponent()
.appendingPathComponent("GitHub Copilot for Xcode Dev.app")
return devAppURL
}