Repository navigation
Expand file tree
/
Copy pathFileExplorerStore.swift
More file actions
1292 lines (1145 loc) · 44.9 KB
/
Copy pathFileExplorerStore.swift
File metadata and controls
1292 lines (1145 loc) · 44.9 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AppKit
import Combine
import Foundation
import QuartzCore
import SwiftUI
// MARK: - Explorer Visual Style
enum FileExplorerStyle: Int, CaseIterable {
case liquidGlass = 0
case highDensity = 1
case terminalStealth = 2
case proStudio = 3
case finder = 4
var label: String {
switch self {
case .liquidGlass: return "Liquid Glass"
case .highDensity: return "High-Density IDE"
case .terminalStealth: return "Terminal Stealth"
case .proStudio: return "Pro Studio"
case .finder: return "Finder"
}
}
var rowHeight: CGFloat {
switch self {
case .liquidGlass: return 28
case .highDensity: return 20
case .terminalStealth: return 24
case .proStudio: return 32
case .finder: return 26
}
}
var indentation: CGFloat {
switch self {
case .liquidGlass: return 16
case .highDensity: return 12
case .terminalStealth: return 14
case .proStudio: return 20
case .finder: return 18
}
}
var iconSize: CGFloat {
switch self {
case .liquidGlass: return 16
case .highDensity: return 14
case .terminalStealth: return 12
case .proStudio: return 18
case .finder: return 18
}
}
var iconWeight: NSFont.Weight {
switch self {
case .liquidGlass: return .regular
case .highDensity: return .regular
case .terminalStealth: return .light
case .proStudio: return .regular
case .finder: return .medium
}
}
var nameFont: NSFont {
switch self {
case .liquidGlass: return .systemFont(ofSize: 13, weight: .medium)
case .highDensity: return .systemFont(ofSize: 11, weight: .regular)
case .terminalStealth: return .monospacedSystemFont(ofSize: 12, weight: .regular)
case .proStudio: return .systemFont(ofSize: 14, weight: .semibold)
case .finder: return .systemFont(ofSize: 13, weight: .regular)
}
}
var iconToTextSpacing: CGFloat {
switch self {
case .liquidGlass: return 8
case .highDensity: return 4
case .terminalStealth: return 6
case .proStudio: return 12
case .finder: return 6
}
}
var selectionInset: CGFloat {
switch self {
case .liquidGlass: return 8
case .highDensity: return 0
case .terminalStealth: return 0
case .proStudio: return 4
case .finder: return 4
}
}
var selectionRadius: CGFloat {
switch self {
case .liquidGlass: return 6
case .highDensity: return 0
case .terminalStealth: return 0
case .proStudio: return 8
case .finder: return 5
}
}
var selectionColor: NSColor {
switch self {
case .liquidGlass: return .controlAccentColor.withAlphaComponent(0.15)
case .highDensity: return .selectedContentBackgroundColor
case .terminalStealth: return .controlAccentColor
case .proStudio: return .controlAccentColor
case .finder: return .controlAccentColor.withAlphaComponent(0.15)
}
}
var hoverColor: NSColor {
switch self {
case .liquidGlass: return .labelColor.withAlphaComponent(0.05)
case .highDensity: return .white.withAlphaComponent(0.05)
case .terminalStealth: return .white.withAlphaComponent(0.03)
case .proStudio: return .white.withAlphaComponent(0.1)
case .finder: return .labelColor.withAlphaComponent(0.04)
}
}
var usesBorderSelection: Bool {
self == .terminalStealth
}
var fileIconTint: NSColor {
switch self {
case .liquidGlass: return .secondaryLabelColor
case .highDensity: return .secondaryLabelColor
case .terminalStealth: return .tertiaryLabelColor
case .proStudio: return .secondaryLabelColor
case .finder: return NSColor(white: 0.55, alpha: 1.0)
}
}
var folderIconTint: NSColor {
switch self {
case .liquidGlass: return .systemBlue
case .highDensity: return .secondaryLabelColor
case .terminalStealth: return .tertiaryLabelColor
case .proStudio: return .systemBlue
case .finder: return .systemBlue
}
}
func gitColor(for status: GitFileStatus) -> NSColor {
switch self {
case .liquidGlass:
switch status {
case .modified: return .systemOrange
case .added: return .systemTeal
case .deleted: return .systemRed
case .renamed: return .systemPurple
case .untracked: return .quaternaryLabelColor
}
case .highDensity:
switch status {
case .modified: return .systemYellow
case .added: return .systemGreen
case .deleted: return .systemRed
case .renamed: return .systemBlue
case .untracked: return .tertiaryLabelColor
}
case .terminalStealth:
switch status {
case .modified: return NSColor(red: 0.8, green: 0.7, blue: 0.4, alpha: 1.0)
case .added: return NSColor(red: 0.5, green: 0.8, blue: 0.5, alpha: 1.0)
case .deleted: return NSColor(red: 0.8, green: 0.4, blue: 0.4, alpha: 1.0)
case .renamed: return NSColor(red: 0.5, green: 0.7, blue: 0.9, alpha: 1.0)
case .untracked: return NSColor(white: 0.5, alpha: 1.0)
}
case .proStudio:
switch status {
case .modified: return .systemYellow
case .added: return .systemGreen
case .deleted: return .systemPink
case .renamed: return .systemCyan
case .untracked: return .systemGray
}
case .finder:
switch status {
case .modified: return .systemOrange
case .added: return .systemGreen
case .deleted: return .systemRed
case .renamed: return .systemBlue
case .untracked: return .tertiaryLabelColor
}
}
}
static var current: FileExplorerStyle {
let defaults = UserDefaults.standard
if defaults.object(forKey: "fileExplorer.style") == nil {
return .highDensity
}
return FileExplorerStyle(rawValue: defaults.integer(forKey: "fileExplorer.style")) ?? .highDensity
}
}
// MARK: - Models
struct FileExplorerEntry: Sendable {
let name: String
let path: String
let isDirectory: Bool
}
final class FileExplorerNode: Identifiable {
let id: String
let name: String
let path: String
let isDirectory: Bool
var children: [FileExplorerNode]?
var isLoading: Bool = false
var error: String?
init(name: String, path: String, isDirectory: Bool) {
self.id = path
self.name = name
self.path = path
self.isDirectory = isDirectory
}
var isExpandable: Bool { isDirectory }
var sortedChildren: [FileExplorerNode]? {
children?.sorted { a, b in
if a.isDirectory != b.isDirectory { return a.isDirectory }
return a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending
}
}
}
// MARK: - Root Resolver
enum FileExplorerRootResolver {
static func displayPath(for fullPath: String, homePath: String?) -> String {
guard let home = homePath, !home.isEmpty else { return fullPath }
let normalizedHome = home.hasSuffix("/") ? String(home.dropLast()) : home
let normalizedPath = fullPath.hasSuffix("/") ? String(fullPath.dropLast()) : fullPath
if normalizedPath == normalizedHome {
return "~"
}
let homePrefix = normalizedHome + "/"
if normalizedPath.hasPrefix(homePrefix) {
return "~/" + normalizedPath.dropFirst(homePrefix.count)
}
return fullPath
}
}
// MARK: - Provider Protocol
protocol FileExplorerProvider: AnyObject {
func listDirectory(path: String, showHidden: Bool) async throws -> [FileExplorerEntry]
var homePath: String { get }
var isAvailable: Bool { get }
}
struct SSHFileExplorerConnection: Equatable, Sendable {
let destination: String
let port: Int?
let identityFile: String?
let sshOptions: [String]
}
protocol SSHFileExplorerTransport: AnyObject {
nonisolated func resolveHomePath(connection: SSHFileExplorerConnection) async throws -> String
nonisolated func listDirectory(
path: String,
connection: SSHFileExplorerConnection,
showHidden: Bool
) async throws -> [FileExplorerEntry]
}
enum FileExplorerWorkspaceRoot: Equatable {
case none
case local(path: String)
case remoteSSH(
workspaceId: UUID,
connection: SSHFileExplorerConnection,
displayTarget: String,
isAvailable: Bool,
unavailableDetail: String?
)
}
// MARK: - Local Provider
final class LocalFileExplorerProvider: FileExplorerProvider {
var homePath: String { NSHomeDirectory() }
var isAvailable: Bool { true }
func listDirectory(path: String, showHidden: Bool) async throws -> [FileExplorerEntry] {
let fm = FileManager.default
let contents = try fm.contentsOfDirectory(atPath: path)
return contents.compactMap { name in
guard showHidden || !name.hasPrefix(".") else { return nil }
let fullPath = (path as NSString).appendingPathComponent(name)
var isDir: ObjCBool = false
guard fm.fileExists(atPath: fullPath, isDirectory: &isDir) else { return nil }
return FileExplorerEntry(name: name, path: fullPath, isDirectory: isDir.boolValue)
}
}
}
// MARK: - SSH Provider
// Captured by async SSH tasks; mutable availability/root state is guarded by stateLock.
final class SSHFileExplorerProvider: FileExplorerProvider, @unchecked Sendable {
private struct State: Sendable {
var homePath: String
var isAvailable: Bool
}
let connection: SSHFileExplorerConnection
let displayTarget: String
private let transport: SSHFileExplorerTransport
private let stateLock = NSLock()
private var state: State
var homePath: String {
stateLock.lock()
defer { stateLock.unlock() }
return state.homePath
}
var isAvailable: Bool {
stateLock.lock()
defer { stateLock.unlock() }
return state.isAvailable
}
var destination: String { connection.destination }
var port: Int? { connection.port }
var identityFile: String? { connection.identityFile }
var sshOptions: [String] { connection.sshOptions }
init(
destination: String,
port: Int?,
identityFile: String?,
sshOptions: [String],
displayTarget: String? = nil,
homePath: String,
isAvailable: Bool,
transport: SSHFileExplorerTransport = ProcessSSHFileExplorerTransport.shared
) {
self.connection = SSHFileExplorerConnection(
destination: destination,
port: port,
identityFile: identityFile,
sshOptions: sshOptions
)
self.displayTarget = displayTarget ?? {
guard let port else { return destination }
return "\(destination):\(port)"
}()
self.transport = transport
self.state = State(homePath: homePath, isAvailable: isAvailable)
}
init(
connection: SSHFileExplorerConnection,
displayTarget: String,
homePath: String,
isAvailable: Bool,
transport: SSHFileExplorerTransport = ProcessSSHFileExplorerTransport.shared
) {
self.connection = connection
self.displayTarget = displayTarget
self.transport = transport
self.state = State(homePath: homePath, isAvailable: isAvailable)
}
func updateAvailability(_ available: Bool, homePath: String?) {
stateLock.lock()
defer { stateLock.unlock() }
state.isAvailable = available
if let homePath {
state.homePath = homePath
}
}
func resolveHomePath() async throws -> String {
guard isAvailable else {
throw FileExplorerError.providerUnavailable
}
let home = try await transport.resolveHomePath(connection: connection)
guard !home.isEmpty else {
throw FileExplorerError.sshCommandFailed("remote HOME was empty")
}
return home
}
func listDirectory(path: String, showHidden: Bool) async throws -> [FileExplorerEntry] {
guard isAvailable else {
throw FileExplorerError.providerUnavailable
}
return try await transport.listDirectory(path: path, connection: connection, showHidden: showHidden)
}
}
final class ProcessSSHFileExplorerTransport: SSHFileExplorerTransport {
static let shared = ProcessSSHFileExplorerTransport()
nonisolated func resolveHomePath(connection: SSHFileExplorerConnection) async throws -> String {
let output = try await Self.runSSHCommand(
connection: connection,
command: #"printf '%s\n' "$HOME""#
)
return output.trimmingCharacters(in: .whitespacesAndNewlines)
}
nonisolated func listDirectory(
path: String,
connection: SSHFileExplorerConnection,
showHidden: Bool
) async throws -> [FileExplorerEntry] {
try await Self.runSSHListCommand(path: path, connection: connection, showHidden: showHidden)
}
private struct SSHCommandResult: Sendable {
let stdout: String
let stderr: String
let terminationStatus: Int32
}
// Keeps the child process reachable from the cancellation handler while
// the blocking wait runs off Swift's cooperative executor.
private final class SSHCommandProcess: @unchecked Sendable {
private let process = Process()
private let outPipe = Pipe()
private let errPipe = Pipe()
private let lock = NSLock()
private var cancelled = false
init(connection: SSHFileExplorerConnection, command: String) {
process.executableURL = URL(fileURLWithPath: "/usr/bin/ssh")
process.arguments = ProcessSSHFileExplorerTransport.sshArguments(connection: connection, command: command)
process.standardOutput = outPipe
process.standardError = errPipe
}
func run() throws -> SSHCommandResult {
lock.lock()
let wasCancelled = cancelled
lock.unlock()
if wasCancelled {
throw CancellationError()
}
try process.run()
lock.lock()
let shouldTerminate = cancelled && process.isRunning
lock.unlock()
if shouldTerminate {
process.terminate()
}
let data = outPipe.fileHandleForReading.readDataToEndOfFile()
let stderrData = errPipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
return SSHCommandResult(
stdout: String(data: data, encoding: .utf8) ?? "",
stderr: String(data: stderrData, encoding: .utf8) ?? "",
terminationStatus: process.terminationStatus
)
}
func terminate() {
lock.lock()
cancelled = true
let isRunning = process.isRunning
lock.unlock()
if isRunning {
process.terminate()
}
}
}
private static func runSSHCommand(connection: SSHFileExplorerConnection, command: String) async throws -> String {
let commandProcess = SSHCommandProcess(connection: connection, command: command)
let result = try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
continuation.resume(with: Result { try commandProcess.run() })
}
}
} onCancel: {
commandProcess.terminate()
}
guard result.terminationStatus == 0 else {
throw FileExplorerError.sshCommandFailed(result.stderr)
}
return result.stdout
}
private static func sshArguments(connection: SSHFileExplorerConnection, command: String) -> [String] {
var args: [String] = []
if let port = connection.port {
args += ["-p", String(port)]
}
if let identityFile = connection.identityFile {
args += ["-i", identityFile]
}
for option in connection.sshOptions {
args += ["-o", option]
}
// Batch mode, no TTY, connection timeout
args += ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "-T"]
args += [connection.destination, command]
return args
}
private static func runSSHListCommand(
path: String,
connection: SSHFileExplorerConnection,
showHidden: Bool
) async throws -> [FileExplorerEntry] {
// Escape single quotes in path for shell safety
let escapedPath = path.replacingOccurrences(of: "'", with: "'\\''")
let lsFlags = showHidden ? "-1paFA" : "-1paF"
let output = try await runSSHCommand(
connection: connection,
command: "ls \(lsFlags) '\(escapedPath)' 2>/dev/null"
)
let normalizedPath = path.hasSuffix("/") ? path : path + "/"
return output.split(separator: "\n", omittingEmptySubsequences: true).compactMap { line in
let entry = String(line)
// Skip . and .. entries
guard entry != "./" && entry != "../" else { return nil }
let isDir = entry.hasSuffix("/")
let name = isDir ? String(entry.dropLast()) : entry
guard showHidden || !name.hasPrefix(".") else { return nil }
// Strip type indicators from -F flag (*, @, =, |) for files
let cleanName: String
if !isDir, let last = name.last, "*@=|".contains(last) {
cleanName = String(name.dropLast())
} else {
cleanName = name
}
let fullPath = normalizedPath + cleanName
return FileExplorerEntry(name: cleanName, path: fullPath, isDirectory: isDir)
}
}
}
enum FileExplorerError: LocalizedError {
case providerUnavailable
case sshCommandFailed(String)
var errorDescription: String? {
switch self {
case .providerUnavailable:
return String(localized: "fileExplorer.error.unavailable", defaultValue: "File explorer is not available")
case .sshCommandFailed(let detail):
return String(localized: "fileExplorer.error.sshFailed", defaultValue: "SSH command failed: \(detail)")
}
}
}
// MARK: - Selection Restoration
enum FileExplorerSelectionRestoration {
static func scrollRow(anchorRow: Int?, exactRows: IndexSet) -> Int? {
if let anchorRow, exactRows.contains(anchorRow) {
return anchorRow
}
return exactRows.first
}
}
// MARK: - Store
/// All access must happen on the main thread. Properties are not marked @MainActor
/// because NSOutlineView data source/delegate methods are called on the main thread
/// but are not annotated @MainActor.
final class FileExplorerStore: ObservableObject {
@Published var rootPath: String = ""
@Published var rootNodes: [FileExplorerNode] = []
@Published private(set) var isRootLoading: Bool = false
@Published private(set) var gitStatusByPath: [String: GitFileStatus] = [:]
@Published private(set) var contentRevision = 0
@Published private(set) var rootStatusMessage: String?
var provider: FileExplorerProvider?
/// Whether hidden files are shown. Set from FileExplorerState externally.
var showHiddenFiles: Bool = false
/// Watches the root directory for filesystem changes (local only).
private var directoryWatcher: FileExplorerDirectoryWatcher?
/// Paths that are logically expanded (persisted across provider changes)
private(set) var expandedPaths: Set<String> = []
/// Stable navigation selection. The outline view mirrors this path after reloads.
private(set) var selectedPath: String?
/// Stable multi-selection. `selectedPath` remains the keyboard/navigation anchor.
private(set) var selectedPaths: Set<String> = []
/// Folder path whose first child should be selected once its async load completes.
private var pendingDescendIntoFirstChildPath: String?
/// Paths currently being loaded
private(set) var loadingPaths: Set<String> = []
/// In-flight load tasks keyed by path
private var loadTasks: [String: Task<Void, Never>] = [:]
/// Cache of path -> node for quick lookup
private var nodesByPath: [String: FileExplorerNode] = [:]
/// Prefetch debounce: path -> work item
private var prefetchWorkItems: [String: DispatchWorkItem] = [:]
private var remoteHomeResolutionTask: Task<Void, Never>?
private var remoteHomeResolutionKey: String?
var displayRootPath: String {
if let sshProvider = provider as? SSHFileExplorerProvider {
guard !rootPath.isEmpty else {
return "ssh://\(sshProvider.displayTarget)"
}
return "ssh://\(sshProvider.displayTarget):\(rootPath)"
}
return FileExplorerRootResolver.displayPath(for: rootPath, homePath: provider?.homePath)
}
// MARK: - Public API
func applyWorkspaceRoot(
_ request: FileExplorerWorkspaceRoot,
sshTransport: SSHFileExplorerTransport = ProcessSSHFileExplorerTransport.shared
) {
switch request {
case .none:
cancelRemoteHomeResolution()
setRootStatusMessage(nil)
if provider != nil {
setProvider(nil, reloadIfAvailable: false)
}
setRootPath("")
case .local(let path):
cancelRemoteHomeResolution()
setRootStatusMessage(nil)
if !(provider is LocalFileExplorerProvider) {
setRootPath("")
setProvider(LocalFileExplorerProvider(), reloadIfAvailable: false)
}
setRootPath(path)
case .remoteSSH(let workspaceId, let connection, let displayTarget, let isAvailable, let unavailableDetail):
applyRemoteSSHWorkspaceRoot(
workspaceId: workspaceId,
connection: connection,
displayTarget: displayTarget,
isAvailable: isAvailable,
unavailableDetail: unavailableDetail,
sshTransport: sshTransport
)
}
}
func setRootPath(_ path: String) {
guard path != rootPath else {
#if DEBUG
NSLog("[FileExplorer] setRootPath skipped (same path): \(path)")
#endif
return
}
#if DEBUG
NSLog("[FileExplorer] setRootPath: \(rootPath) -> \(path)")
#endif
if let selectedPath, !Self.path(selectedPath, isContainedIn: path) {
self.selectedPath = nil
selectedPaths = []
pendingDescendIntoFirstChildPath = nil
}
rootPath = path
reload()
refreshGitStatus()
updateDirectoryWatcher()
}
func refreshGitStatus() {
guard !rootPath.isEmpty else {
gitStatusByPath = [:]
return
}
let path = rootPath
if let sshProvider = provider as? SSHFileExplorerProvider {
let dest = sshProvider.destination
let port = sshProvider.port
let identity = sshProvider.identityFile
let opts = sshProvider.sshOptions
DispatchQueue.global(qos: .utility).async {
let status = GitStatusProvider.fetchStatusSSH(
directory: path, destination: dest, port: port,
identityFile: identity, sshOptions: opts
)
DispatchQueue.main.async { [weak self] in
self?.gitStatusByPath = status
}
}
} else {
DispatchQueue.global(qos: .utility).async {
let status = GitStatusProvider.fetchStatus(directory: path)
DispatchQueue.main.async { [weak self] in
self?.gitStatusByPath = status
}
}
}
}
private func updateDirectoryWatcher() {
if provider is LocalFileExplorerProvider, !rootPath.isEmpty {
if directoryWatcher == nil {
directoryWatcher = FileExplorerDirectoryWatcher { [weak self] in
self?.reload()
self?.refreshGitStatus()
}
}
directoryWatcher?.watch(path: rootPath)
} else {
directoryWatcher?.stop()
}
}
private func setProvider(_ newProvider: FileExplorerProvider?, reloadIfAvailable: Bool = true) {
#if DEBUG
NSLog("[FileExplorer] setProvider: \(type(of: newProvider).self) available=\(newProvider?.isAvailable ?? false)")
#endif
provider = newProvider
// Re-expand previously expanded nodes if provider becomes available
if reloadIfAvailable, newProvider?.isAvailable == true {
reload()
}
}
#if DEBUG
func setProviderForTesting(_ newProvider: FileExplorerProvider?, reloadIfAvailable: Bool = true) {
setProvider(newProvider, reloadIfAvailable: reloadIfAvailable)
}
#endif
func reload() {
#if DEBUG
NSLog("[FileExplorer] reload() path=\(rootPath) provider=\(type(of: provider).self)")
#endif
contentRevision &+= 1
cancelAllLoads()
rootNodes = []
nodesByPath = [:]
guard !rootPath.isEmpty, provider != nil else { return }
isRootLoading = true
let path = rootPath
let task = Task { [weak self] in
guard let self else { return }
await self.loadChildren(for: nil, at: path)
}
loadTasks[rootPath] = task
}
func expand(node: FileExplorerNode) {
guard node.isDirectory else { return }
expandedPaths.insert(node.path)
if node.children == nil, loadTasks[node.path] == nil, !loadingPaths.contains(node.path) {
node.isLoading = true
node.error = nil
objectWillChange.send()
let nodePath = node.path
let task = Task { [weak self] in
guard let self else { return }
await self.loadChildren(for: node, at: nodePath)
}
loadTasks[node.path] = task
}
}
func collapse(node: FileExplorerNode) {
expandedPaths.remove(node.path)
if pendingDescendIntoFirstChildPath == node.path {
pendingDescendIntoFirstChildPath = nil
}
objectWillChange.send()
}
func isExpanded(_ node: FileExplorerNode) -> Bool {
expandedPaths.contains(node.path)
}
func select(node: FileExplorerNode?) {
let path = node?.path
let paths = path.map { Set([$0]) } ?? []
guard selectedPath != path || selectedPaths != paths else { return }
selectedPath = path
selectedPaths = paths
if path != pendingDescendIntoFirstChildPath {
pendingDescendIntoFirstChildPath = nil
}
}
func select(nodes: [FileExplorerNode], anchor: FileExplorerNode?) {
let paths = Set(nodes.map(\.path))
let path = anchor?.path ?? nodes.first?.path
guard selectedPath != path || selectedPaths != paths else { return }
selectedPath = path
selectedPaths = paths
if path != pendingDescendIntoFirstChildPath {
pendingDescendIntoFirstChildPath = nil
}
}
func requestDescendIntoFirstChild(of node: FileExplorerNode) {
guard node.isDirectory else { return }
selectedPath = node.path
selectedPaths = [node.path]
pendingDescendIntoFirstChildPath = node.path
expand(node: node)
}
func prefetchChildren(for node: FileExplorerNode) {
guard node.isDirectory, node.children == nil, !loadingPaths.contains(node.path) else { return }
// Debounce: only prefetch if hover persists for 200ms
let path = node.path
prefetchWorkItems[path]?.cancel()
let workItem = DispatchWorkItem { [weak self] in
Task { @MainActor [weak self] in
guard let self, node.children == nil, !self.loadingPaths.contains(path) else { return }
// Silent prefetch: don't show loading indicator
await self.loadChildren(for: node, at: path, silent: true)
}
}
prefetchWorkItems[path] = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: workItem)
}
func cancelPrefetch(for node: FileExplorerNode) {
prefetchWorkItems[node.path]?.cancel()
prefetchWorkItems.removeValue(forKey: node.path)
}
/// Called when SSH provider becomes available after being unavailable.
/// Re-hydrates expanded nodes that were waiting.
func hydrateExpandedNodes() {
guard let provider, provider.isAvailable, !expandedPaths.isEmpty else { return }
#if DEBUG
NSLog("[FileExplorer] hydrateExpandedNodes: \(expandedPaths.count) paths to hydrate")
#endif
reload()
}
// MARK: - Private
@MainActor
private func loadChildren(for parentNode: FileExplorerNode?, at path: String, silent: Bool = false) async {
guard let provider else { return }
if !silent {
loadingPaths.insert(path)
parentNode?.error = nil
objectWillChange.send()
}
do {
let entries = try await provider.listDirectory(path: path, showHidden: showHiddenFiles)
try Task.checkCancellation()
let children = entries.map { entry in
let node = FileExplorerNode(name: entry.name, path: entry.path, isDirectory: entry.isDirectory)
nodesByPath[entry.path] = node
return node
}.sorted { a, b in
if a.isDirectory != b.isDirectory { return a.isDirectory }
return a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending
}
if let parentNode {
parentNode.children = children
parentNode.isLoading = false
parentNode.error = nil
if pendingDescendIntoFirstChildPath == parentNode.path {
let path = children.first?.path ?? parentNode.path
selectedPath = path
selectedPaths = [path]
pendingDescendIntoFirstChildPath = nil
}
} else {
rootNodes = children
isRootLoading = false
setRootStatusMessage(nil)
if selectedPath == nil {
selectedPath = children.first?.path
selectedPaths = selectedPath.map { Set([$0]) } ?? []
}
}
loadingPaths.remove(path)
loadTasks.removeValue(forKey: path)
objectWillChange.send()
// Auto-expand children that were previously expanded
for child in children where child.isDirectory && expandedPaths.contains(child.path) {
child.isLoading = true
objectWillChange.send()
let childPath = child.path
let childTask = Task { [weak self] in
guard let self else { return }
await self.loadChildren(for: child, at: childPath)
}
loadTasks[child.path] = childTask
}
} catch {
if !Task.isCancelled {
if let parentNode {
parentNode.isLoading = false
parentNode.error = error.localizedDescription
} else {
isRootLoading = false
setRootStatusMessage(error.localizedDescription)
}
loadingPaths.remove(path)
loadTasks.removeValue(forKey: path)
objectWillChange.send()
}
}
}
private func cancelAllLoads() {
for (_, task) in loadTasks {
task.cancel()
}
loadTasks.removeAll()
loadingPaths.removeAll()
pendingDescendIntoFirstChildPath = nil
for (_, item) in prefetchWorkItems {
item.cancel()
}
prefetchWorkItems.removeAll()
isRootLoading = false
}
private func applyRemoteSSHWorkspaceRoot(
workspaceId: UUID,
connection: SSHFileExplorerConnection,
displayTarget: String,
isAvailable: Bool,
unavailableDetail: String?,
sshTransport: SSHFileExplorerTransport
) {
let existingProvider = provider as? SSHFileExplorerProvider
let sshProvider: SSHFileExplorerProvider
if let existingProvider,
existingProvider.connection == connection,
existingProvider.displayTarget == displayTarget {
sshProvider = existingProvider
sshProvider.updateAvailability(isAvailable, homePath: nil)
} else {
cancelRemoteHomeResolution()
setRootPath("")
sshProvider = SSHFileExplorerProvider(
connection: connection,
displayTarget: displayTarget,
homePath: "",
isAvailable: isAvailable,
transport: sshTransport
)
setProvider(sshProvider, reloadIfAvailable: false)
}
guard isAvailable else {
cancelRemoteHomeResolution()
setRootPath("")
let detail = unavailableDetail?.trimmingCharacters(in: .whitespacesAndNewlines)
if let detail, !detail.isEmpty {
setRootStatusMessage(
String(
localized: "fileExplorer.status.sshUnavailableWithDetail",
defaultValue: "SSH files unavailable: \(detail)"
)
)
} else {
setRootStatusMessage(
String(localized: "fileExplorer.status.sshUnavailable", defaultValue: "SSH files unavailable")
)
}
return
}