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
255 lines (227 loc) · 8.5 KB
/
AppDelegate.swift
File metadata and controls
255 lines (227 loc) · 8.5 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
import AppKit
import FileChangeChecker
import LaunchAgentManager
import Logger
import Preferences
import Service
import ServiceManagement
import SwiftUI
import UpdateChecker
import UserNotifications
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 let userDefaultsObserver = UserDefaultsObserver()
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
UserDefaults.setupDefaultSettings()
setupQuitOnUpdate()
setupQuitOnUserTerminated()
xpcListener = setupXPCListener()
Logger.service.info("XPC Service started.")
NSApp.setActivationPolicy(.prohibited)
buildStatusBarMenu()
}
@objc private func buildStatusBarMenu() {
let statusBar = NSStatusBar.system
statusBarItem = statusBar.statusItem(
withLength: NSStatusItem.squareLength
)
statusBarItem.button?.image = NSImage(
systemSymbolName: "steeringwheel",
accessibilityDescription: nil
)
let statusBarMenu = NSMenu(title: "Status Bar Menu")
statusBarItem.menu = statusBarMenu
#if DEBUG
let copilotName = NSMenuItem(
title: "Copilot for Xcode - DEBUG",
action: nil,
keyEquivalent: ""
)
#else
let copilotName = NSMenuItem(
title: "Copilot for Xcode",
action: nil,
keyEquivalent: ""
)
#endif
let checkForUpdate = NSMenuItem(
title: "Check for Updates",
action: #selector(checkForUpdate),
keyEquivalent: ""
)
let toggleRealtimeSuggestions = NSMenuItem(
title: "Real-time Suggestions",
action: #selector(toggleRealtimeSuggestions),
keyEquivalent: ""
)
toggleRealtimeSuggestions.state = UserDefaults.shared
.value(for: \.realtimeSuggestionToggle) ? .on : .off
toggleRealtimeSuggestions.target = self
let quitItem = NSMenuItem(
title: "Quit",
action: #selector(quit),
keyEquivalent: ""
)
quitItem.target = self
statusBarMenu.addItem(copilotName)
statusBarMenu.addItem(checkForUpdate)
statusBarMenu.addItem(.separator())
statusBarMenu.addItem(toggleRealtimeSuggestions)
statusBarMenu.addItem(.separator())
statusBarMenu.addItem(quitItem)
userDefaultsObserver.onChange = { key in
switch key {
case UserDefaultPreferenceKeys().realtimeSuggestionToggle.key:
toggleRealtimeSuggestions.state = UserDefaults.shared
.value(for: \.realtimeSuggestionToggle) ? .on : .off
default:
break
}
}
}
@objc func quit() {
exit(0)
}
@objc func toggleRealtimeSuggestions() {
let isOn = !UserDefaults.shared.value(for: \.realtimeSuggestionToggle)
if isOn {
if !AXIsProcessTrusted() {
let alert = NSAlert()
let image = NSImage(
systemSymbolName: "exclamationmark.triangle.fill",
accessibilityDescription: nil
)
var config = NSImage.SymbolConfiguration(
textStyle: .body,
scale: .large
)
config = config.applying(.init(hierarchicalColor: .systemYellow))
alert.icon = image?.withSymbolConfiguration(config)
alert.messageText = "Accessibility API Permission Required"
alert.informativeText =
"Permission not granted to use Accessibility API. Please turn in on in System Settings.app."
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
alert.alertStyle = .warning
alert.runModal()
return
}
}
UserDefaults.shared.set(isOn, for: \.realtimeSuggestionToggle)
}
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
exit(0)
#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
}
exit(0)
}
}
}
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()
}
}
private class UserDefaultsObserver: NSObject {
var onChange: ((String?) -> Void)?
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
onChange?(keyPath)
}
override init() {
super.init()
observe(keyPath: UserDefaultPreferenceKeys().realtimeSuggestionToggle.key)
}
func observe(keyPath: String) {
UserDefaults.shared.addObserver(self, forKeyPath: keyPath, options: .new, context: nil)
}
}
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
}