forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXPCExtensionService.swift
More file actions
321 lines (289 loc) · 10.3 KB
/
XPCExtensionService.swift
File metadata and controls
321 lines (289 loc) · 10.3 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
import Foundation
import Logger
import Status
public enum XPCExtensionServiceError: Swift.Error, LocalizedError {
case failedToGetServiceEndpoint
case failedToCreateXPCConnection
case xpcServiceError(Error)
public var errorDescription: String? {
switch self {
case .failedToGetServiceEndpoint:
return "Waiting for service to connect to the communication bridge."
case .failedToCreateXPCConnection:
return "Failed to create XPC connection."
case let .xpcServiceError(error):
return "Connection to extension service error: \(error.localizedDescription)"
}
}
}
public class XPCExtensionService {
@XPCServiceActor
var service: XPCService?
@XPCServiceActor
var connection: NSXPCConnection? { service?.connection }
let logger: Logger
let bridge: XPCCommunicationBridge
public nonisolated
init(logger: Logger) {
self.logger = logger
bridge = XPCCommunicationBridge(logger: logger)
}
/// Launches the extension service if it's not running, returns true if the service has finished
/// launching and the communication becomes available.
@XPCServiceActor
public func launchIfNeeded() async throws -> Bool {
try await bridge.launchExtensionServiceIfNeeded() != nil
}
public func getXPCServiceVersion() async throws -> (version: String, build: String) {
try await withXPCServiceConnected {
service, continuation in
service.getXPCServiceVersion { version, build in
continuation.resume((version, build))
}
}
}
public func getXPCServiceAccessibilityPermission() async throws -> ObservedAXStatus {
try await withXPCServiceConnected {
service, continuation in
service.getXPCServiceAccessibilityPermission { isGranted in
continuation.resume(isGranted)
}
}
}
public func getXPCServiceExtensionPermission() async throws -> ExtensionPermissionStatus {
try await withXPCServiceConnected {
service, continuation in
service.getXPCServiceExtensionPermission { isGranted in
continuation.resume(isGranted)
}
}
}
public func getSuggestedCode(editorContent: EditorContent) async throws -> UpdatedContent? {
try await suggestionRequest(
editorContent,
{ $0.getSuggestedCode }
)
}
public func getNextSuggestedCode(editorContent: EditorContent) async throws -> UpdatedContent? {
try await suggestionRequest(
editorContent,
{ $0.getNextSuggestedCode }
)
}
public func getPreviousSuggestedCode(editorContent: EditorContent) async throws
-> UpdatedContent?
{
try await suggestionRequest(
editorContent,
{ $0.getPreviousSuggestedCode }
)
}
public func getSuggestionAcceptedCode(editorContent: EditorContent) async throws
-> UpdatedContent?
{
try await suggestionRequest(
editorContent,
{ $0.getSuggestionAcceptedCode }
)
}
public func getSuggestionRejectedCode(editorContent: EditorContent) async throws
-> UpdatedContent?
{
try await suggestionRequest(
editorContent,
{ $0.getSuggestionRejectedCode }
)
}
public func getRealtimeSuggestedCode(editorContent: EditorContent) async throws
-> UpdatedContent?
{
try await suggestionRequest(
editorContent,
{ $0.getRealtimeSuggestedCode }
)
}
public func getPromptToCodeAcceptedCode(editorContent: EditorContent) async throws
-> UpdatedContent?
{
try await suggestionRequest(
editorContent,
{ $0.getPromptToCodeAcceptedCode }
)
}
public func toggleRealtimeSuggestion() async throws {
try await withXPCServiceConnected {
service, continuation in
service.toggleRealtimeSuggestion { error in
if let error {
continuation.reject(error)
return
}
continuation.resume(())
}
} as Void
}
public func prefetchRealtimeSuggestions(editorContent: EditorContent) async {
guard let data = try? JSONEncoder().encode(editorContent) else { return }
try? await withXPCServiceConnected { service, continuation in
service.prefetchRealtimeSuggestions(editorContent: data) {
continuation.resume(())
}
}
}
public func openChat(editorContent: EditorContent) async throws -> UpdatedContent? {
try await suggestionRequest(
editorContent,
{ $0.openChat }
)
}
public func promptToCode(editorContent: EditorContent) async throws -> UpdatedContent? {
try await suggestionRequest(
editorContent,
{ $0.promptToCode }
)
}
public func customCommand(
id: String,
editorContent: EditorContent
) async throws -> UpdatedContent? {
try await suggestionRequest(
editorContent,
{ service in { service.customCommand(id: id, editorContent: $0, withReply: $1) } }
)
}
public func quitService() async throws {
try await withXPCServiceConnectedWithoutLaunching {
service, continuation in
service.quit {
continuation.resume(())
}
}
}
public func postNotification(name: String) async throws {
try await withXPCServiceConnected {
service, continuation in
service.postNotification(name: name) {
continuation.resume(())
}
}
}
public func send<M: ExtensionServiceRequestType>(
requestBody: M
) async throws -> M.ResponseBody {
try await withXPCServiceConnected { service, continuation in
do {
let requestBodyData = try JSONEncoder().encode(requestBody)
service.send(endpoint: M.endpoint, requestBody: requestBodyData) { data, error in
if let error {
continuation.reject(error)
} else {
do {
guard let data = data else {
continuation.reject(NoDataError())
return
}
let responseBody = try JSONDecoder().decode(
M.ResponseBody.self,
from: data
)
continuation.resume(responseBody)
} catch {
continuation.reject(error)
}
}
}
} catch {
continuation.reject(error)
}
}
}
}
extension XPCExtensionService: XPCServiceDelegate {
public func connectionDidInterrupt() async {
Task { @XPCServiceActor in
service = nil
}
}
public func connectionDidInvalidate() async {
Task { @XPCServiceActor in
service = nil
}
}
}
extension XPCExtensionService {
@XPCServiceActor
private func updateEndpoint(_ endpoint: NSXPCListenerEndpoint) {
service = XPCService(
kind: .anonymous(endpoint: endpoint),
interface: NSXPCInterface(with: XPCServiceProtocol.self),
logger: logger,
delegate: self
)
}
@XPCServiceActor
private func withXPCServiceConnected<T>(
_ fn: @escaping (XPCServiceProtocol, AutoFinishContinuation<T>) -> Void
) async throws -> T {
if let service, let connection = service.connection {
do {
return try await XPCShared.withXPCServiceConnected(connection: connection, fn)
} catch {
throw XPCExtensionServiceError.xpcServiceError(error)
}
} else {
guard let endpoint = try await bridge.launchExtensionServiceIfNeeded()
else { throw XPCExtensionServiceError.failedToGetServiceEndpoint }
updateEndpoint(endpoint)
if let service, let connection = service.connection {
do {
return try await XPCShared.withXPCServiceConnected(connection: connection, fn)
} catch {
throw XPCExtensionServiceError.xpcServiceError(error)
}
} else {
throw XPCExtensionServiceError.failedToCreateXPCConnection
}
}
}
@XPCServiceActor
private func withXPCServiceConnectedWithoutLaunching<T>(
_ fn: @escaping (XPCServiceProtocol, AutoFinishContinuation<T>) -> Void
) async throws -> T {
if let service, let connection = service.connection {
do {
return try await XPCShared.withXPCServiceConnected(connection: connection, fn)
} catch {
throw XPCExtensionServiceError.xpcServiceError(error)
}
}
throw XPCExtensionServiceError.failedToCreateXPCConnection
}
@XPCServiceActor
private func suggestionRequest(
_ editorContent: EditorContent,
_ fn: @escaping (any XPCServiceProtocol) -> (Data, @escaping (Data?, Error?) -> Void)
-> Void
) async throws -> UpdatedContent? {
let data = try JSONEncoder().encode(editorContent)
return try await withXPCServiceConnected {
service, continuation in
fn(service)(data) { updatedData, error in
if let error {
continuation.reject(error)
return
}
do {
if let updatedData {
let updatedContent = try JSONDecoder()
.decode(UpdatedContent.self, from: updatedData)
continuation.resume(updatedContent)
} else {
continuation.resume(nil)
}
} catch {
continuation.reject(error)
}
}
}
}
}