forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkspace.swift
More file actions
481 lines (410 loc) · 16.2 KB
/
Workspace.swift
File metadata and controls
481 lines (410 loc) · 16.2 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import ChatService
import Environment
import Foundation
import GitHubCopilotService
import Logger
import Preferences
import SuggestionInjector
import SuggestionModel
import SuggestionService
import UserDefaultsObserver
import XcodeInspector
import XPCShared
// MARK: - Filespace
@ServiceActor
final class Filespace {
struct Snapshot: Equatable {
var linesHash: Int
var cursorPosition: CursorPosition
}
let fileURL: URL
private(set) lazy var language: String = languageIdentifierFromFileURL(fileURL).rawValue
var suggestions: [CodeSuggestion] = [] {
didSet { refreshUpdateTime() }
}
// stored for pseudo command handler
var uti: String?
var tabSize: Int?
var indentSize: Int?
var usesTabsForIndentation: Bool?
// ---------------------------------
var suggestionIndex: Int = 0
var suggestionSourceSnapshot: Snapshot = .init(linesHash: -1, cursorPosition: .outOfScope)
var presentingSuggestion: CodeSuggestion? {
guard suggestions.endIndex > suggestionIndex, suggestionIndex >= 0 else { return nil }
return suggestions[suggestionIndex]
}
private(set) var lastSuggestionUpdateTime: Date = Environment.now()
var isExpired: Bool {
Environment.now().timeIntervalSince(lastSuggestionUpdateTime) > 60 * 3
}
let fileSaveWatcher: FileSaveWatcher
fileprivate init(fileURL: URL, onSave: @escaping (Filespace) -> Void) {
self.fileURL = fileURL
fileSaveWatcher = .init(fileURL: fileURL)
fileSaveWatcher.changeHandler = { [weak self] in
guard let self else { return }
onSave(self)
}
}
func reset(resetSnapshot: Bool = true) {
suggestions = []
suggestionIndex = 0
if resetSnapshot {
suggestionSourceSnapshot = .init(linesHash: -1, cursorPosition: .outOfScope)
}
}
func refreshUpdateTime() {
lastSuggestionUpdateTime = Environment.now()
}
/// Validate the suggestion is still valid.
/// - Parameters:
/// - lines: lines of the file
/// - cursorPosition: cursor position
/// - Returns: `true` if the suggestion is still valid
func validateSuggestions(lines: [String], cursorPosition: CursorPosition) -> Bool {
guard let presentingSuggestion else { return false }
// cursor has moved to another line
if cursorPosition.line != presentingSuggestion.position.line {
reset()
return false
}
// the cursor position is valid
guard cursorPosition.line >= 0, cursorPosition.line < lines.count else {
reset()
return false
}
let editingLine = lines[cursorPosition.line].dropLast(1) // dropping \n
let suggestionLines = presentingSuggestion.text.split(separator: "\n")
let suggestionFirstLine = suggestionLines.first ?? ""
// the line content doesn't match the suggestion
if cursorPosition.character > 0,
!suggestionFirstLine.hasPrefix(editingLine[..<(editingLine.index(
editingLine.startIndex,
offsetBy: cursorPosition.character,
limitedBy: editingLine.endIndex
) ?? editingLine.endIndex)])
{
reset()
return false
}
// finished typing the whole suggestion when the suggestion has only one line
if editingLine.hasPrefix(suggestionFirstLine), suggestionLines.count <= 1 {
reset()
return false
}
// undo to a state before the suggestion was generated
if editingLine.count < presentingSuggestion.position.character {
reset()
return false
}
return true
}
}
// MARK: - Workspace
@ServiceActor
final class Workspace {
struct SuggestionFeatureDisabledError: Error, LocalizedError {
var errorDescription: String? {
"Suggestion feature is disabled for this project."
}
}
struct UnsupportedFileError: Error, LocalizedError {
var extensionName: String
var errorDescription: String? {
"File type \(extensionName) unsupported."
}
}
let projectRootURL: URL
let openedFileRecoverableStorage: OpenedFileRecoverableStorage
var lastSuggestionUpdateTime = Environment.now()
var isExpired: Bool {
Environment.now().timeIntervalSince(lastSuggestionUpdateTime) > 60 * 60 * 1
}
private(set) var filespaces = [URL: Filespace]()
var isRealtimeSuggestionEnabled: Bool {
UserDefaults.shared.value(for: \.realtimeSuggestionToggle)
}
let userDefaultsObserver = UserDefaultsObserver(
object: UserDefaults.shared, forKeyPaths: [
UserDefaultPreferenceKeys().suggestionFeatureEnabledProjectList.key,
UserDefaultPreferenceKeys().disableSuggestionFeatureGlobally.key,
], context: nil
)
private var _suggestionService: SuggestionServiceType?
private var suggestionService: SuggestionServiceType? {
// Check if the workspace is disabled.
let isSuggestionDisabledGlobally = UserDefaults.shared
.value(for: \.disableSuggestionFeatureGlobally)
if isSuggestionDisabledGlobally {
let enabledList = UserDefaults.shared.value(for: \.suggestionFeatureEnabledProjectList)
if !enabledList.contains(where: { path in projectRootURL.path.hasPrefix(path) }) {
// If it's disable, remove the service
_suggestionService = nil
return nil
}
}
if _suggestionService == nil {
_suggestionService = SuggestionService(projectRootURL: projectRootURL) {
[weak self] _ in
guard let self else { return }
for (_, filespace) in filespaces {
notifyOpenFile(filespace: filespace)
}
}
}
return _suggestionService
}
var isSuggestionFeatureEnabled: Bool {
let isSuggestionDisabledGlobally = UserDefaults.shared
.value(for: \.disableSuggestionFeatureGlobally)
if isSuggestionDisabledGlobally {
let enabledList = UserDefaults.shared.value(for: \.suggestionFeatureEnabledProjectList)
if !enabledList.contains(where: { path in projectRootURL.path.hasPrefix(path) }) {
return false
}
}
return true
}
private init(projectRootURL: URL) {
self.projectRootURL = projectRootURL
openedFileRecoverableStorage = .init(projectRootURL: projectRootURL)
userDefaultsObserver.onChange = { [weak self] in
guard let self else { return }
_ = self.suggestionService
}
let openedFiles = openedFileRecoverableStorage.openedFiles
for fileURL in openedFiles {
_ = createFilespaceIfNeeded(fileURL: fileURL)
}
}
func refreshUpdateTime() {
lastSuggestionUpdateTime = Environment.now()
}
func canAutoTriggerGetSuggestions(
forFileAt fileURL: URL,
lines: [String],
cursorPosition: CursorPosition
) -> Bool {
guard isRealtimeSuggestionEnabled else { return false }
guard let filespace = filespaces[fileURL] else { return true }
if lines.hashValue != filespace.suggestionSourceSnapshot.linesHash { return true }
if cursorPosition != filespace.suggestionSourceSnapshot.cursorPosition { return true }
return false
}
/// This is the only way to create a workspace and a filespace.
static func fetchOrCreateWorkspaceIfNeeded(fileURL: URL) async throws
-> (workspace: Workspace, filespace: Filespace)
{
let ignoreFileExtensions = ["mlmodel"]
if ignoreFileExtensions.contains(fileURL.pathExtension) {
throw UnsupportedFileError(extensionName: fileURL.pathExtension)
}
// If we know which project is opened.
if let currentProjectURL = try await Environment.fetchCurrentProjectRootURLFromXcode() {
if let existed = workspaces[currentProjectURL] {
let filespace = existed.createFilespaceIfNeeded(fileURL: fileURL)
return (existed, filespace)
}
let new = Workspace(projectRootURL: currentProjectURL)
workspaces[currentProjectURL] = new
let filespace = new.createFilespaceIfNeeded(fileURL: fileURL)
return (new, filespace)
}
// If not, we try to reuse a filespace if found.
//
// Sometimes, we can't get the project root path from Xcode window, for example, when the
// quick open window in displayed.
for workspace in workspaces.values {
if let filespace = workspace.filespaces[fileURL] {
return (workspace, filespace)
}
}
// If we can't find an existed one, we will try to guess it.
// Most of the time we won't enter this branch, just incase.
let workspaceURL = try await Environment.guessProjectRootURLForFile(fileURL)
let workspace = {
if let existed = workspaces[workspaceURL] {
return existed
}
// Reuse existed workspace if possible
for (_, workspace) in workspaces {
if fileURL.path.hasPrefix(workspace.projectRootURL.path) {
return workspace
}
}
return Workspace(projectRootURL: workspaceURL)
}()
let filespace = workspace.createFilespaceIfNeeded(fileURL: fileURL)
workspaces[workspaceURL] = workspace
workspace.refreshUpdateTime()
return (workspace, filespace)
}
private func createFilespaceIfNeeded(fileURL: URL) -> Filespace {
let existedFilespace = filespaces[fileURL]
let filespace = existedFilespace ?? .init(fileURL: fileURL, onSave: { [weak self]
filespace in
guard let self else { return }
notifySaveFile(filespace: filespace)
})
if filespaces[fileURL] == nil {
filespaces[fileURL] = filespace
}
if existedFilespace == nil {
notifyOpenFile(filespace: filespace)
} else {
filespace.refreshUpdateTime()
}
return filespace
}
}
// MARK: - Suggestion
extension Workspace {
@discardableResult
func generateSuggestions(
forFileAt fileURL: URL,
editor: EditorContent
) async throws -> [CodeSuggestion] {
refreshUpdateTime()
let filespace = createFilespaceIfNeeded(fileURL: fileURL)
if !editor.uti.isEmpty {
filespace.uti = editor.uti
filespace.tabSize = editor.tabSize
filespace.indentSize = editor.indentSize
filespace.usesTabsForIndentation = editor.usesTabsForIndentation
}
let snapshot = Filespace.Snapshot(
linesHash: editor.lines.hashValue,
cursorPosition: editor.cursorPosition
)
filespace.suggestionSourceSnapshot = snapshot
guard let suggestionService else { throw SuggestionFeatureDisabledError() }
let completions = try await suggestionService.getSuggestions(
fileURL: fileURL,
content: editor.lines.joined(separator: ""),
cursorPosition: editor.cursorPosition,
tabSize: editor.tabSize,
indentSize: editor.indentSize,
usesTabsForIndentation: editor.usesTabsForIndentation,
ignoreSpaceOnlySuggestions: true
)
filespace.suggestions = completions
filespace.suggestionIndex = 0
return completions
}
func selectNextSuggestion(forFileAt fileURL: URL) {
refreshUpdateTime()
guard let filespace = filespaces[fileURL],
filespace.suggestions.count > 1
else { return }
filespace.suggestionIndex += 1
if filespace.suggestionIndex >= filespace.suggestions.endIndex {
filespace.suggestionIndex = 0
}
}
func selectPreviousSuggestion(forFileAt fileURL: URL) {
refreshUpdateTime()
guard let filespace = filespaces[fileURL],
filespace.suggestions.count > 1
else { return }
filespace.suggestionIndex -= 1
if filespace.suggestionIndex < 0 {
filespace.suggestionIndex = filespace.suggestions.endIndex - 1
}
}
func rejectSuggestion(forFileAt fileURL: URL, editor: EditorContent?) {
refreshUpdateTime()
if let editor, !editor.uti.isEmpty {
filespaces[fileURL]?.uti = editor.uti
filespaces[fileURL]?.tabSize = editor.tabSize
filespaces[fileURL]?.indentSize = editor.indentSize
filespaces[fileURL]?.usesTabsForIndentation = editor.usesTabsForIndentation
}
Task {
await suggestionService?.notifyRejected(filespaces[fileURL]?.suggestions ?? [])
}
filespaces[fileURL]?.reset(resetSnapshot: false)
}
func acceptSuggestion(forFileAt fileURL: URL, editor: EditorContent?) -> CodeSuggestion? {
refreshUpdateTime()
guard let filespace = filespaces[fileURL],
!filespace.suggestions.isEmpty,
filespace.suggestionIndex >= 0,
filespace.suggestionIndex < filespace.suggestions.endIndex
else { return nil }
if let editor, !editor.uti.isEmpty {
filespaces[fileURL]?.uti = editor.uti
filespaces[fileURL]?.tabSize = editor.tabSize
filespaces[fileURL]?.indentSize = editor.indentSize
filespaces[fileURL]?.usesTabsForIndentation = editor.usesTabsForIndentation
}
var allSuggestions = filespace.suggestions
let suggestion = allSuggestions.remove(at: filespace.suggestionIndex)
Task {
await suggestionService?.notifyAccepted(suggestion)
await suggestionService?.notifyRejected(allSuggestions)
}
filespaces[fileURL]?.reset()
return suggestion
}
func notifyOpenFile(filespace: Filespace) {
refreshUpdateTime()
openedFileRecoverableStorage.openFile(fileURL: filespace.fileURL)
Task {
// check if file size is larger than 15MB, if so, return immediately
if let attrs = try? FileManager.default
.attributesOfItem(atPath: filespace.fileURL.path),
let fileSize = attrs[FileAttributeKey.size] as? UInt64,
fileSize > 15 * 1024 * 1024
{ return }
try await suggestionService?.notifyOpenTextDocument(
fileURL: filespace.fileURL,
content: try String(contentsOf: filespace.fileURL, encoding: .utf8)
)
}
}
func notifyUpdateFile(filespace: Filespace, content: String) {
filespace.refreshUpdateTime()
refreshUpdateTime()
Task {
try await suggestionService?.notifyChangeTextDocument(
fileURL: filespace.fileURL,
content: content
)
}
}
func notifySaveFile(filespace: Filespace) {
filespace.refreshUpdateTime()
refreshUpdateTime()
Task {
try await suggestionService?.notifySaveTextDocument(fileURL: filespace.fileURL)
}
}
}
// MARK: - Cleanup
extension Workspace {
func cleanUp(availableTabs: Set<String>) {
for (fileURL, _) in filespaces {
if isFilespaceExpired(fileURL: fileURL, availableTabs: availableTabs) {
Task {
try await suggestionService?.notifyCloseTextDocument(fileURL: fileURL)
}
openedFileRecoverableStorage.closeFile(fileURL: fileURL)
filespaces[fileURL] = nil
}
}
}
func isFilespaceExpired(fileURL: URL, availableTabs: Set<String>) -> Bool {
let filename = fileURL.lastPathComponent
if availableTabs.contains(filename) { return false }
guard let filespace = filespaces[fileURL] else { return true }
return filespace.isExpired
}
func cancelInFlightRealtimeSuggestionRequests() async {
guard let suggestionService else { return }
await suggestionService.cancelRequest()
}
func terminateSuggestionService() async {
await _suggestionService?.terminate()
}
}