forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
226 lines (200 loc) · 7.26 KB
/
AppDelegate.swift
File metadata and controls
226 lines (200 loc) · 7.26 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
import AppKit
import Environment
import FileChangeChecker
import LaunchAgentManager
import Logger
import Preferences
import Service
import ServiceManagement
import ServiceUpdateMigration
import SwiftUI
import UpdateChecker
import UserDefaultsObserver
import UserNotifications
import XcodeInspector
let bundleIdentifierBase = Bundle.main
.object(forInfoDictionaryKey: "BUNDLE_IDENTIFIER_BASE") as! String
let serviceIdentifier = bundleIdentifierBase + ".ExtensionService"
@main
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
let scheduledCleaner = ScheduledCleaner()
private var statusBarItem: NSStatusItem!
private var xpcListener: (NSXPCListener, ServiceDelegate)?
private let updateChecker =
UpdateChecker(
hostBundle: locateHostBundleURL(url: Bundle.main.bundleURL)
.flatMap(Bundle.init(url:))
)
func applicationDidFinishLaunching(_: Notification) {
if ProcessInfo.processInfo.environment["IS_UNIT_TEST"] == "YES" { return }
_ = GraphicalUserInterfaceController.shared
_ = RealtimeSuggestionController.shared
_ = XcodeInspector.shared
AXIsProcessTrustedWithOptions([
kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true,
] as CFDictionary)
setupQuitOnUpdate()
setupQuitOnUserTerminated()
xpcListener = setupXPCListener()
Logger.service.info("XPC Service started.")
NSApp.setActivationPolicy(.accessory)
buildStatusBarMenu()
DependencyUpdater().update()
initializePython()
Task {
do {
try await ServiceUpdateMigrator().migrate()
} catch {
Logger.service.error(error.localizedDescription)
}
}
}
@objc private func buildStatusBarMenu() {
let statusBar = NSStatusBar.system
statusBarItem = statusBar.statusItem(
withLength: NSStatusItem.squareLength
)
statusBarItem.button?.image = NSImage(named: "MenuBarIcon")
let statusBarMenu = NSMenu(title: "Status Bar Menu")
statusBarItem.menu = statusBarMenu
let hostAppName = Bundle.main.object(forInfoDictionaryKey: "HOST_APP_NAME") as? String
?? "Copilot for Xcode"
let copilotName = NSMenuItem(
title: hostAppName,
action: nil,
keyEquivalent: ""
)
let checkForUpdate = NSMenuItem(
title: "Check for Updates",
action: #selector(checkForUpdate),
keyEquivalent: ""
)
let openCopilotForXcode = NSMenuItem(
title: "Open \(hostAppName)",
action: #selector(openCopilotForXcode),
keyEquivalent: ""
)
let openGlobalChat = NSMenuItem(
title: "Open Chat",
action: #selector(openGlobalChat),
keyEquivalent: ""
)
let quitItem = NSMenuItem(
title: "Quit",
action: #selector(quit),
keyEquivalent: ""
)
quitItem.target = self
statusBarMenu.addItem(copilotName)
statusBarMenu.addItem(openCopilotForXcode)
statusBarMenu.addItem(checkForUpdate)
statusBarMenu.addItem(.separator())
statusBarMenu.addItem(openGlobalChat)
statusBarMenu.addItem(.separator())
statusBarMenu.addItem(quitItem)
}
@objc func quit() {
Task { @MainActor in
await scheduledCleaner.closeAllChildProcesses()
exit(0)
}
}
@objc func openCopilotForXcode() {
let task = Process()
if let appPath = locateHostBundleURL(url: Bundle.main.bundleURL)?.absoluteString {
task.launchPath = "/usr/bin/open"
task.arguments = [appPath]
task.launch()
task.waitUntilExit()
}
}
@objc func openGlobalChat() {
Task { @MainActor in
let serviceGUI = GraphicalUserInterfaceController.shared
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 setupXPCListener() -> (NSXPCListener, ServiceDelegate) {
let listener = NSXPCListener(machServiceName: serviceIdentifier)
let delegate = ServiceDelegate()
listener.delegate = delegate
listener.resume()
return (listener, delegate)
}
func requestAccessoryAPIPermission() {
AXIsProcessTrustedWithOptions([
kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true,
] as NSDictionary)
}
@objc func checkForUpdate() {
updateChecker.checkForUpdates()
}
}
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("Copilot for Xcode Dev.app")
return devAppURL
}