Repository navigation
Expand file tree
/
Copy pathFileExplorerView.swift
More file actions
2173 lines (1929 loc) · 86.7 KB
/
Copy pathFileExplorerView.swift
File metadata and controls
2173 lines (1929 loc) · 86.7 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 Bonsplit
import Combine
import SwiftUI
#if DEBUG
private func fileExplorerDebugResponder(_ responder: NSResponder?) -> String {
guard let responder else { return "nil" }
return String(describing: type(of: responder))
}
#endif
// MARK: - File Explorer Panel (single NSViewRepresentable)
enum FileExplorerPanelPresentation: Equatable {
case files
case find
var rightSidebarMode: RightSidebarMode {
switch self {
case .files: return .files
case .find: return .find
}
}
}
/// The entire file explorer panel as one AppKit view hierarchy.
/// Contains the header bar (path + controls) and NSOutlineView, with no SwiftUI intermediaries.
struct FileExplorerPanelView: NSViewRepresentable {
@ObservedObject var store: FileExplorerStore
@ObservedObject var state: FileExplorerState
let onOpenFilePreview: (String) -> Void
var presentation: FileExplorerPanelPresentation = .files
func makeCoordinator() -> Coordinator {
Coordinator(store: store, state: state, onOpenFilePreview: onOpenFilePreview)
}
func makeNSView(context: Context) -> FileExplorerContainerView {
let container = FileExplorerContainerView(coordinator: context.coordinator, presentation: presentation)
context.coordinator.containerView = container
return container
}
func updateNSView(_ container: FileExplorerContainerView, context: Context) {
context.coordinator.store = store
context.coordinator.state = state
context.coordinator.onOpenFilePreview = onOpenFilePreview
container.updateHeader(store: store)
container.updatePresentation(presentation)
context.coordinator.reloadIfNeeded()
container.registerWithKeyboardFocusCoordinatorIfNeeded()
}
// MARK: - Coordinator
final class Coordinator: NSObject, NSOutlineViewDataSource, NSOutlineViewDelegate, NSMenuDelegate {
var store: FileExplorerStore
var state: FileExplorerState
var onOpenFilePreview: (String) -> Void
weak var containerView: FileExplorerContainerView?
weak var outlineView: NSOutlineView?
private var lastRootNodeCount: Int = -1
private var observationCancellable: AnyCancellable?
private var styleObserver: Any?
private var isUpdatingOutlineProgrammatically = false
init(
store: FileExplorerStore,
state: FileExplorerState,
onOpenFilePreview: @escaping (String) -> Void
) {
self.store = store
self.state = state
self.onOpenFilePreview = onOpenFilePreview
super.init()
observeStore()
styleObserver = NotificationCenter.default.addObserver(
forName: .fileExplorerStyleDidChange, object: nil, queue: .main
) { [weak self] _ in
guard let self, let outlineView = self.outlineView else { return }
let style = FileExplorerStyle.current
self.withProgrammaticOutlineUpdate {
outlineView.indentationPerLevel = style.indentation
outlineView.noteHeightOfRows(withIndexesChanged: IndexSet(0..<outlineView.numberOfRows))
outlineView.reloadData()
self.restoreExpansionState(self.store.expandedPaths, in: outlineView)
self.applyStoredSelection(in: outlineView, fallbackToFirstVisible: false, scroll: false)
}
}
}
deinit {
if let observer = styleObserver {
NotificationCenter.default.removeObserver(observer)
}
}
private func observeStore() {
observationCancellable = store.objectWillChange
.debounce(for: .milliseconds(50), scheduler: RunLoop.main)
.sink { [weak self] _ in
Task { @MainActor [weak self] in
self?.reloadIfNeeded()
}
}
}
@MainActor
func reloadIfNeeded() {
guard let outlineView else { return }
// Update empty state vs tree visibility
containerView?.updateVisibility(
hasContent: !store.rootPath.isEmpty,
isLoading: store.isRootLoading,
statusMessage: store.rootStatusMessage
)
let newCount = store.rootNodes.count
withProgrammaticOutlineUpdate {
if newCount != lastRootNodeCount {
lastRootNodeCount = newCount
let expandedPaths = store.expandedPaths
outlineView.reloadData()
restoreExpansionState(expandedPaths, in: outlineView)
} else {
refreshLoadedNodes(in: outlineView)
}
applyStoredSelection(in: outlineView, fallbackToFirstVisible: false, scroll: false)
}
}
private func restoreExpansionState(_ expandedPaths: Set<String>, in outlineView: NSOutlineView) {
for row in 0..<outlineView.numberOfRows {
guard let node = outlineView.item(atRow: row) as? FileExplorerNode else { continue }
if expandedPaths.contains(node.path) && outlineView.isExpandable(node) {
outlineView.expandItem(node)
}
}
}
private func refreshLoadedNodes(in outlineView: NSOutlineView) {
for row in 0..<outlineView.numberOfRows {
guard let node = outlineView.item(atRow: row) as? FileExplorerNode else { continue }
if node.isDirectory {
let isCurrentlyExpanded = outlineView.isItemExpanded(node)
let shouldBeExpanded = store.expandedPaths.contains(node.path)
if shouldBeExpanded && !isCurrentlyExpanded && node.children != nil {
outlineView.reloadItem(node, reloadChildren: true)
outlineView.expandItem(node)
} else if !shouldBeExpanded && isCurrentlyExpanded {
outlineView.collapseItem(node)
} else if node.children != nil {
outlineView.reloadItem(node, reloadChildren: true)
if shouldBeExpanded {
outlineView.expandItem(node)
}
}
}
}
}
// MARK: - NSOutlineViewDataSource
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return store.rootNodes.count
}
guard let node = item as? FileExplorerNode else { return 0 }
return node.sortedChildren?.count ?? 0
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item == nil {
return store.rootNodes[index]
}
guard let node = item as? FileExplorerNode,
let children = node.sortedChildren else {
return FileExplorerNode(name: "", path: "", isDirectory: false)
}
return children[index]
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
guard let node = item as? FileExplorerNode else { return false }
return node.isExpandable
}
// MARK: - NSOutlineViewDelegate
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let node = item as? FileExplorerNode else { return nil }
let identifier = NSUserInterfaceItemIdentifier("FileExplorerCell")
let cellView: FileExplorerCellView
if let existing = outlineView.makeView(withIdentifier: identifier, owner: nil) as? FileExplorerCellView {
cellView = existing
} else {
cellView = FileExplorerCellView(identifier: identifier)
}
let gitStatus = store.gitStatusByPath[node.path]
cellView.configure(with: node, gitStatus: gitStatus)
cellView.onHover = { [weak self] isHovering in
guard let self else { return }
if isHovering {
self.store.prefetchChildren(for: node)
} else {
self.store.cancelPrefetch(for: node)
}
}
return cellView
}
func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
guard let node = item as? FileExplorerNode, node.isDirectory else { return false }
store.expand(node: node)
return node.children != nil
}
func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
guard let node = item as? FileExplorerNode else { return false }
store.collapse(node: node)
return true
}
func outlineViewSelectionDidChange(_ notification: Notification) {
guard !isUpdatingOutlineProgrammatically,
let outlineView = notification.object as? NSOutlineView else {
return
}
let nodes = outlineView.selectedRowIndexes.compactMap { outlineView.item(atRow: $0) as? FileExplorerNode }
guard !nodes.isEmpty else { store.select(node: nil); return }
let anchor = outlineView.selectedRow >= 0 ? outlineView.item(atRow: outlineView.selectedRow) as? FileExplorerNode : nil
store.select(nodes: nodes, anchor: anchor ?? nodes.first)
}
func outlineViewItemDidExpand(_ notification: Notification) {
guard let node = notification.userInfo?["NSObject"] as? FileExplorerNode else { return }
if !store.isExpanded(node) {
store.expand(node: node)
}
}
func outlineViewItemDidCollapse(_ notification: Notification) {
guard let node = notification.userInfo?["NSObject"] as? FileExplorerNode else { return }
if store.isExpanded(node) {
store.collapse(node: node)
}
}
func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
FileExplorerRowView()
}
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
FileExplorerStyle.current.rowHeight
}
// MARK: - Path-Owned Navigation
func ensureSelection(in outlineView: NSOutlineView, fallbackToFirstVisible: Bool, scroll: Bool) {
withProgrammaticOutlineUpdate {
applyStoredSelection(in: outlineView, fallbackToFirstVisible: fallbackToFirstVisible, scroll: scroll)
}
}
func moveSelection(in outlineView: NSOutlineView, by delta: Int) {
guard outlineView.numberOfRows > 0 else {
store.select(node: nil)
return
}
let currentRow = resolvedSelectionRow(in: outlineView) ?? (delta >= 0 ? -1 : outlineView.numberOfRows)
let targetRow = min(max(currentRow + delta, 0), outlineView.numberOfRows - 1)
selectRow(targetRow, in: outlineView, scroll: true)
}
func performDisclosureAction(
_ action: RightSidebarKeyboardNavigation.DisclosureAction,
in outlineView: NSOutlineView
) {
switch action {
case .collapse:
collapseSelectedItemOrMoveToParent(in: outlineView)
case .expand:
expandSelectedItemOrMoveToChild(in: outlineView)
}
}
func selectBestQuickSearchMatch(in outlineView: NSOutlineView, query: String) {
let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedQuery.isEmpty, outlineView.numberOfRows > 0 else { return }
let lowerQuery = trimmedQuery.lowercased()
for row in 0..<outlineView.numberOfRows {
guard let node = outlineView.item(atRow: row) as? FileExplorerNode else { continue }
if node.name.lowercased().contains(lowerQuery) {
selectRow(row, in: outlineView, scroll: true)
return
}
}
}
private func expandSelectedItemOrMoveToChild(in outlineView: NSOutlineView) {
guard let row = resolvedSelectionRow(in: outlineView),
let node = outlineView.item(atRow: row) as? FileExplorerNode,
node.isDirectory else {
return
}
selectRow(row, in: outlineView, scroll: true)
if !store.isExpanded(node) {
outlineView.expandItem(node)
applyStoredSelection(in: outlineView, fallbackToFirstVisible: false, scroll: true)
return
}
guard node.children != nil else {
store.requestDescendIntoFirstChild(of: node)
return
}
if !outlineView.isItemExpanded(node) {
outlineView.expandItem(node)
}
selectFirstChild(of: node, in: outlineView)
}
private func collapseSelectedItemOrMoveToParent(in outlineView: NSOutlineView) {
guard let row = resolvedSelectionRow(in: outlineView),
let node = outlineView.item(atRow: row) as? FileExplorerNode else {
return
}
if node.isDirectory, outlineView.isItemExpanded(node) || store.isExpanded(node) {
if outlineView.isItemExpanded(node) {
outlineView.collapseItem(node)
} else {
store.collapse(node: node)
}
selectRow(row, in: outlineView, scroll: true)
return
}
selectParent(of: node, in: outlineView)
}
private func selectFirstChild(of node: FileExplorerNode, in outlineView: NSOutlineView) {
let parentRow = outlineView.row(forItem: node)
let childRow = parentRow + 1
guard parentRow >= 0,
childRow < outlineView.numberOfRows,
let child = outlineView.item(atRow: childRow) as? FileExplorerNode,
(outlineView.parent(forItem: child) as? FileExplorerNode) === node else {
return
}
selectRow(childRow, in: outlineView, scroll: true)
}
private func selectParent(of node: FileExplorerNode, in outlineView: NSOutlineView) {
guard let parentNode = outlineView.parent(forItem: node) as? FileExplorerNode else {
return
}
let parentRow = outlineView.row(forItem: parentNode)
guard parentRow >= 0 else { return }
selectRow(parentRow, in: outlineView, scroll: true)
}
private func applyStoredSelection(
in outlineView: NSOutlineView,
fallbackToFirstVisible: Bool,
scroll: Bool
) {
let exactRows = store.selectedPaths.reduce(into: IndexSet()) { if let resolution = selectionResolution(for: $1, in: outlineView), resolution.isExact { $0.insert(resolution.row) } }
if !exactRows.isEmpty {
withProgrammaticOutlineUpdate { outlineView.selectRowIndexes(exactRows, byExtendingSelection: false) }
let anchorRow = store.selectedPath.flatMap { selectionResolution(for: $0, in: outlineView)?.row }
if scroll, let row = FileExplorerSelectionRestoration.scrollRow(anchorRow: anchorRow, exactRows: exactRows) { outlineView.scrollRowToVisible(row) }; return
}
if let selectedPath = store.selectedPath,
let resolution = selectionResolution(for: selectedPath, in: outlineView) {
selectRow(
resolution.row,
in: outlineView,
scroll: scroll,
updateStore: resolution.isExact
)
return
}
guard fallbackToFirstVisible, outlineView.numberOfRows > 0 else { return }
selectRow(0, in: outlineView, scroll: scroll)
}
private func resolvedSelectionRow(in outlineView: NSOutlineView) -> Int? {
if let selectedPath = store.selectedPath,
let resolution = selectionResolution(for: selectedPath, in: outlineView) {
return resolution.row
}
guard outlineView.selectedRow >= 0,
outlineView.selectedRow < outlineView.numberOfRows,
let node = outlineView.item(atRow: outlineView.selectedRow) as? FileExplorerNode else {
return nil
}
store.select(node: node)
return outlineView.selectedRow
}
private struct SelectionResolution {
let row: Int
let isExact: Bool
}
private func selectionResolution(for path: String, in outlineView: NSOutlineView) -> SelectionResolution? {
var bestAncestor: (row: Int, pathLength: Int)?
for row in 0..<outlineView.numberOfRows {
guard let node = outlineView.item(atRow: row) as? FileExplorerNode else { continue }
if node.path == path {
return SelectionResolution(row: row, isExact: true)
}
if Self.path(node.path, isAncestorOf: path) {
let length = node.path.count
if bestAncestor == nil || length > bestAncestor!.pathLength {
bestAncestor = (row, length)
}
}
}
guard let bestAncestor else { return nil }
return SelectionResolution(row: bestAncestor.row, isExact: false)
}
private func selectRow(
_ row: Int,
in outlineView: NSOutlineView,
scroll: Bool,
updateStore: Bool = true
) {
guard row >= 0, row < outlineView.numberOfRows else { return }
let node = outlineView.item(atRow: row) as? FileExplorerNode
withProgrammaticOutlineUpdate {
if updateStore {
store.select(node: node)
}
outlineView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false)
if scroll {
outlineView.scrollRowToVisible(row)
}
}
}
private func withProgrammaticOutlineUpdate(_ body: () -> Void) {
let wasUpdating = isUpdatingOutlineProgrammatically
isUpdatingOutlineProgrammatically = true
defer { isUpdatingOutlineProgrammatically = wasUpdating }
body()
}
private static func path(_ ancestor: String, isAncestorOf descendant: String) -> Bool {
guard ancestor != descendant else { return false }
if ancestor == "/" {
return descendant.hasPrefix("/")
}
return descendant.hasPrefix(ancestor + "/")
}
// MARK: - Drag-to-Preview
func outlineView(_ outlineView: NSOutlineView, pasteboardWriterForItem item: Any) -> (any NSPasteboardWriting)? {
guard let node = item as? FileExplorerNode, !node.isDirectory else { return nil }
guard store.provider is LocalFileExplorerProvider else { return nil }
return FilePreviewDragPasteboardWriter(filePath: node.path, displayTitle: node.name)
}
func outlineView(
_ outlineView: NSOutlineView,
draggingSession session: NSDraggingSession,
endedAt screenPoint: NSPoint,
operation: NSDragOperation
) {
FilePreviewDragPasteboardWriter.discardRegisteredDrag(from: NSPasteboard(name: .drag))
}
@objc func handleDoubleClick(_ sender: NSOutlineView) {
let row = sender.clickedRow >= 0 ? sender.clickedRow : sender.selectedRow
guard row >= 0,
let node = sender.item(atRow: row) as? FileExplorerNode else { return }
if node.isDirectory {
if sender.isItemExpanded(node) {
sender.collapseItem(node)
} else if sender.isExpandable(node) {
sender.expandItem(node)
}
return
}
guard store.provider is LocalFileExplorerProvider else { return }
onOpenFilePreview(node.path)
}
// MARK: - Context Menu (NSMenuDelegate)
func menuNeedsUpdate(_ menu: NSMenu) {
menu.removeAllItems()
guard let outlineView else { return }
let clickedRow = outlineView.clickedRow
guard clickedRow >= 0,
let node = outlineView.item(atRow: clickedRow) as? FileExplorerNode else { return }
let isLocal = store.provider is LocalFileExplorerProvider
if !node.isDirectory && isLocal {
let openItem = NSMenuItem(
title: String(localized: "fileExplorer.contextMenu.openDefault", defaultValue: "Open in Default Editor"),
action: #selector(contextMenuOpenInDefaultEditor(_:)),
keyEquivalent: ""
)
openItem.target = self
openItem.representedObject = node
menu.addItem(openItem)
}
if isLocal {
let revealItem = NSMenuItem(
title: String(localized: "fileExplorer.contextMenu.revealInFinder", defaultValue: "Reveal in Finder"),
action: #selector(contextMenuRevealInFinder(_:)),
keyEquivalent: ""
)
revealItem.target = self
revealItem.representedObject = node
menu.addItem(revealItem)
menu.addItem(.separator())
}
menu.addFileExplorerInsertPathItems(target: self, representedObject: node, insertAction: #selector(contextMenuInsertPath(_:)), insertRelativeAction: #selector(contextMenuInsertRelativePath(_:)))
let copyPathItem = NSMenuItem(
title: String(localized: "fileExplorer.contextMenu.copyPath", defaultValue: "Copy Path"),
action: #selector(contextMenuCopyPath(_:)),
keyEquivalent: ""
)
copyPathItem.target = self
copyPathItem.representedObject = node
menu.addItem(copyPathItem)
let copyRelItem = NSMenuItem(
title: String(localized: "fileExplorer.contextMenu.copyRelativePath", defaultValue: "Copy Relative Path"),
action: #selector(contextMenuCopyRelativePath(_:)),
keyEquivalent: ""
)
copyRelItem.target = self
copyRelItem.representedObject = node
menu.addItem(copyRelItem)
}
@objc private func contextMenuOpenInDefaultEditor(_ sender: NSMenuItem) {
guard let node = sender.representedObject as? FileExplorerNode else { return }
NSWorkspace.shared.open(URL(fileURLWithPath: node.path))
}
@objc private func contextMenuRevealInFinder(_ sender: NSMenuItem) {
guard let node = sender.representedObject as? FileExplorerNode else { return }
NSWorkspace.shared.selectFile(node.path, inFileViewerRootedAtPath: "")
}
@objc private func contextMenuCopyPath(_ sender: NSMenuItem) {
guard let node = sender.representedObject as? FileExplorerNode else { return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(node.path, forType: .string)
}
@objc private func contextMenuCopyRelativePath(_ sender: NSMenuItem) {
guard let node = sender.representedObject as? FileExplorerNode else { return }
let relativePath = FileExplorerTerminalPathInsertion.relativePath(for: node.path, rootPath: store.rootPath)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(relativePath, forType: .string)
}
}
}
// MARK: - Container View (all-AppKit)
/// Pure AppKit container holding the header bar and outline view.
@MainActor
final class FileExplorerContainerView: NSView {
private let headerView: FileExplorerHeaderView
private let searchBarView: NSView
private let searchField: FileExplorerSearchField
private let searchStatusLabel: NSTextField
private let scrollView: NSScrollView
private let outlineView: FileExplorerNSOutlineView
private let searchScrollView: NSScrollView
let searchResultsView: FileExplorerSearchResultsTableView
private let emptyLabel: NSTextField
private let loadingIndicator: NSProgressIndicator
private let searchController: any FileSearchControlling
private var searchBarHeightConstraint: NSLayoutConstraint!
private(set) var searchSnapshot = FileSearchSnapshot.empty
private var currentRootPath = ""
private var currentProviderIsLocal = false
private var currentContentRevision = 0
private let searchDebounceSubject = PassthroughSubject<Int, Never>()
private var searchDebounceCancellable: AnyCancellable?
private var searchDebounceGeneration = 0
private var pendingSearchRefreshAfterSettled = false
private var isSearchVisible = false {
didSet {
if !isSearchVisible {
cancelPendingSearchRefresh()
pendingSearchRefreshAfterSettled = false
}
}
}
private var presentation: FileExplorerPanelPresentation
private let coordinator: FileExplorerPanelView.Coordinator
private let searchDebounceDelayMilliseconds = 200
private let searchBarVisibleHeight: CGFloat = 48
#if DEBUG
private var debugLastSearchTextChangeUptime: TimeInterval = 0
private var debugLastSearchLayoutFieldWidth: CGFloat = -1
private var debugLastSearchLayoutStatusWidth: CGFloat = -1
private var debugLastLoggedSearchResultCount = -1
private var debugLastLoggedSearchStatus = ""
#endif
init(
coordinator: FileExplorerPanelView.Coordinator,
presentation: FileExplorerPanelPresentation,
searchController: (any FileSearchControlling)? = nil
) {
headerView = FileExplorerHeaderView()
searchBarView = NSView()
searchField = FileExplorerSearchField()
searchStatusLabel = NSTextField(labelWithString: "")
scrollView = NSScrollView()
outlineView = FileExplorerNSOutlineView()
searchScrollView = NSScrollView()
searchResultsView = FileExplorerSearchResultsTableView()
emptyLabel = NSTextField(labelWithString: String(localized: "fileExplorer.empty", defaultValue: "No folder open"))
loadingIndicator = NSProgressIndicator()
self.searchController = searchController ?? FileSearchController()
self.presentation = presentation
self.coordinator = coordinator
super.init(frame: .zero)
configureSearchDebounce()
// Header
headerView.translatesAutoresizingMaskIntoConstraints = false
addSubview(headerView)
// Search bar
searchBarView.translatesAutoresizingMaskIntoConstraints = false
searchBarView.isHidden = true
addSubview(searchBarView)
searchField.translatesAutoresizingMaskIntoConstraints = false
searchField.setAccessibilityIdentifier("FileExplorerSearchField")
searchField.placeholderString = String(localized: "fileExplorer.search.placeholder", defaultValue: "Search files")
searchField.font = .systemFont(ofSize: 12, weight: .regular)
searchField.focusRingType = .none
searchField.cell?.usesSingleLineMode = true
searchField.cell?.isScrollable = true
searchField.cell?.lineBreakMode = .byClipping
searchField.setContentHuggingPriority(.defaultLow, for: .horizontal)
searchField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
searchField.delegate = self
searchField.onCancel = { [weak self] in
self?.closeSearchAndFocusOutline()
}
searchField.onMoveSelection = { [weak self] delta in
self?.moveSearchSelection(by: delta, focusResults: true)
}
searchField.onCommit = { [weak self] in
self?.openSelectedSearchResult()
}
searchField.onFocus = { [weak self] in
guard let self else { return }
self.isSearchVisible = true
if let window = self.window {
AppDelegate.shared?.noteRightSidebarKeyboardFocusIntent(mode: self.representedRightSidebarMode(), in: window)
}
self.updateSearchLayout()
}
searchBarView.addSubview(searchField)
searchStatusLabel.translatesAutoresizingMaskIntoConstraints = false
searchStatusLabel.font = .systemFont(ofSize: 11, weight: .medium)
searchStatusLabel.textColor = .secondaryLabelColor
searchStatusLabel.lineBreakMode = .byTruncatingTail
searchStatusLabel.maximumNumberOfLines = 1
searchStatusLabel.alignment = .left
searchStatusLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
searchStatusLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
searchBarView.addSubview(searchStatusLabel)
// Empty state label
emptyLabel.translatesAutoresizingMaskIntoConstraints = false
emptyLabel.font = .systemFont(ofSize: 13)
emptyLabel.textColor = .secondaryLabelColor
emptyLabel.alignment = .center
emptyLabel.isHidden = true
addSubview(emptyLabel)
// Loading indicator
loadingIndicator.translatesAutoresizingMaskIntoConstraints = false
loadingIndicator.style = .spinning
loadingIndicator.controlSize = .small
loadingIndicator.isHidden = true
addSubview(loadingIndicator)
// Outline view setup
outlineView.headerView = nil
outlineView.usesAlternatingRowBackgroundColors = false
outlineView.style = .plain
outlineView.selectionHighlightStyle = .regular
outlineView.rowSizeStyle = .default
outlineView.indentationPerLevel = FileExplorerStyle.current.indentation
outlineView.allowsMultipleSelection = true
outlineView.autoresizesOutlineColumn = true
outlineView.floatsGroupRows = false
outlineView.backgroundColor = .clear
outlineView.onQuickSearchChanged = { [weak self] query in
self?.headerView.updateQuickSearch(query: query)
}
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("name"))
column.isEditable = false
column.resizingMask = .autoresizingMask
outlineView.addTableColumn(column)
outlineView.outlineTableColumn = column
outlineView.dataSource = coordinator
outlineView.delegate = coordinator
outlineView.target = coordinator
outlineView.doubleAction = #selector(FileExplorerPanelView.Coordinator.handleDoubleClick(_:))
outlineView.setDraggingSourceOperationMask(.move, forLocal: true)
coordinator.outlineView = outlineView
// Context menu
let menu = NSMenu()
menu.delegate = coordinator
outlineView.menu = menu
// Scroll view
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = false
scrollView.horizontalScrollElasticity = .none
scrollView.autohidesScrollers = true
scrollView.borderType = .noBorder
scrollView.drawsBackground = false
scrollView.documentView = outlineView
addSubview(scrollView)
// Streaming search results
searchResultsView.headerView = nil
searchResultsView.usesAlternatingRowBackgroundColors = false
searchResultsView.style = .plain
searchResultsView.selectionHighlightStyle = .regular
searchResultsView.backgroundColor = .clear
searchResultsView.rowHeight = 46
searchResultsView.allowsMultipleSelection = true
searchResultsView.intercellSpacing = NSSize(width: 0, height: 0)
searchResultsView.onCancel = { [weak self] in
self?.closeSearchAndFocusOutline()
}
searchResultsView.onMoveSelection = { [weak self] delta in
self?.moveSearchSelection(by: delta, focusResults: false)
}
searchResultsView.onCommit = { [weak self] in
self?.openSelectedSearchResult()
}
searchResultsView.onFocus = { [weak self] in
guard let self, let window = self.window else { return }
AppDelegate.shared?.noteRightSidebarKeyboardFocusIntent(mode: self.representedRightSidebarMode(), in: window)
}
let searchColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("searchResult"))
searchColumn.isEditable = false
searchColumn.resizingMask = .autoresizingMask
searchResultsView.addTableColumn(searchColumn)
searchResultsView.dataSource = self
searchResultsView.delegate = self
searchResultsView.target = self
searchResultsView.doubleAction = #selector(openSelectedSearchResultFromTable(_:))
searchResultsView.setDraggingSourceOperationMask(.move, forLocal: true)
let searchMenu = NSMenu()
searchMenu.delegate = self
searchResultsView.menu = searchMenu
searchScrollView.translatesAutoresizingMaskIntoConstraints = false
searchScrollView.hasVerticalScroller = true
searchScrollView.hasHorizontalScroller = false
searchScrollView.horizontalScrollElasticity = .none
searchScrollView.autohidesScrollers = true
searchScrollView.borderType = .noBorder
searchScrollView.drawsBackground = false
searchScrollView.documentView = searchResultsView
searchScrollView.isHidden = true
addSubview(searchScrollView)
self.searchController.onSnapshotChanged = { [weak self] snapshot in
self?.applySearchSnapshot(snapshot)
}
searchBarHeightConstraint = searchBarView.heightAnchor.constraint(equalToConstant: 0)
NSLayoutConstraint.activate([
headerView.topAnchor.constraint(equalTo: topAnchor),
headerView.leadingAnchor.constraint(equalTo: leadingAnchor),
headerView.trailingAnchor.constraint(equalTo: trailingAnchor),
searchBarView.topAnchor.constraint(equalTo: headerView.bottomAnchor),
searchBarView.leadingAnchor.constraint(equalTo: leadingAnchor),
searchBarView.trailingAnchor.constraint(equalTo: trailingAnchor),
searchBarHeightConstraint,
searchField.leadingAnchor.constraint(equalTo: searchBarView.leadingAnchor, constant: 8),
searchField.trailingAnchor.constraint(equalTo: searchBarView.trailingAnchor, constant: -8),
searchField.topAnchor.constraint(equalTo: searchBarView.topAnchor, constant: 4),
searchField.heightAnchor.constraint(equalToConstant: 24),
searchField.widthAnchor.constraint(greaterThanOrEqualToConstant: 120),
searchStatusLabel.leadingAnchor.constraint(equalTo: searchField.leadingAnchor, constant: 4),
searchStatusLabel.trailingAnchor.constraint(equalTo: searchField.trailingAnchor),
searchStatusLabel.topAnchor.constraint(equalTo: searchField.bottomAnchor, constant: 2),
scrollView.topAnchor.constraint(equalTo: searchBarView.bottomAnchor),
scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: bottomAnchor),
searchScrollView.topAnchor.constraint(equalTo: searchBarView.bottomAnchor),
searchScrollView.leadingAnchor.constraint(equalTo: leadingAnchor),
searchScrollView.trailingAnchor.constraint(equalTo: trailingAnchor),
searchScrollView.bottomAnchor.constraint(equalTo: bottomAnchor),
emptyLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
emptyLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
loadingIndicator.centerXAnchor.constraint(equalTo: centerXAnchor),
loadingIndicator.centerYAnchor.constraint(equalTo: centerYAnchor),
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillMove(toWindow newWindow: NSWindow?) {
if newWindow == nil {
cancelPendingSearchRefresh()
searchController.cancel(clear: false)
}
super.viewWillMove(toWindow: newWindow)
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
guard let window else { return }
AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.registerFileExplorerHost(self)
#if DEBUG
dlog(
"file.focus.host.attach win=\(window.windowNumber) canAccept=\(cmuxCanAcceptRightSidebarKeyboardFocus ? 1 : 0) " +
"rows=\(outlineView.numberOfRows) hidden=\(isHiddenOrHasHiddenAncestor ? 1 : 0) " +
"fr=\(fileExplorerDebugResponder(window.firstResponder))"
)
#endif
}
func registerWithKeyboardFocusCoordinatorIfNeeded() {
guard let window else { return }
AppDelegate.shared?.keyboardFocusCoordinator(for: window)?.registerFileExplorerHost(self)
}
override func layout() {
#if DEBUG
let debugLayoutStart = ProcessInfo.processInfo.systemUptime
#endif
super.layout()
registerWithKeyboardFocusCoordinatorIfNeeded()
#if DEBUG
logSearchLayoutIfNeeded(startedAt: debugLayoutStart, reason: "layout")
#endif
}
func updateHeader(store: FileExplorerStore) {
let nextRootPath = store.rootPath
let nextProviderIsLocal = store.provider is LocalFileExplorerProvider
let nextContentRevision = store.contentRevision
let searchScopeChanged = nextRootPath != currentRootPath ||
nextProviderIsLocal != currentProviderIsLocal
let contentRevisionChanged = nextContentRevision != currentContentRevision
currentRootPath = nextRootPath
currentProviderIsLocal = nextProviderIsLocal
currentContentRevision = nextContentRevision
headerView.update(displayPath: store.displayRootPath)
if searchScopeChanged {
pendingSearchRefreshAfterSettled = false
refreshSearchIfNeeded()
} else if contentRevisionChanged {
refreshSearchAfterContentRevisionIfNeeded()
}
}
func representedRightSidebarMode() -> RightSidebarMode {
presentation.rightSidebarMode
}
func updatePresentation(_ nextPresentation: FileExplorerPanelPresentation) {
guard presentation != nextPresentation else {
if presentation == .find {
isSearchVisible = true
updateSearchLayout()
}
return
}
presentation = nextPresentation
switch presentation {
case .files:
isSearchVisible = false
searchController.cancel(clear: false)
case .find:
isSearchVisible = true
refreshSearchIfNeeded()
}
updateSearchLayout()
registerWithKeyboardFocusCoordinatorIfNeeded()
}
func updateVisibility(hasContent: Bool, isLoading: Bool, statusMessage: String?) {
let normalizedStatus = statusMessage?.trimmingCharacters(in: .whitespacesAndNewlines)
let hasStatus = normalizedStatus?.isEmpty == false
let canShowTree = hasContent && !hasStatus
headerView.isHidden = !hasContent && !hasStatus
updateSearchLayout(hasContent: canShowTree, isLoading: isLoading)
let searchCanShow = isSearchVisible && canShowTree && !isLoading
emptyLabel.stringValue = hasStatus
? normalizedStatus!
: String(localized: "fileExplorer.empty", defaultValue: "No folder open")
emptyLabel.isHidden = canShowTree || searchCanShow || isLoading
loadingIndicator.isHidden = !isLoading
if isLoading {
loadingIndicator.startAnimation(nil)
} else {
loadingIndicator.stopAnimation(nil)
}
}
@discardableResult
func focusSearchField() -> Bool {
guard let window, cmuxCanAcceptRightSidebarKeyboardFocus else {
#if DEBUG
dlog(
"file.focus.search.end result=0 reason=unavailable " +
"win=\(window?.windowNumber ?? -1) hidden=\(isHiddenOrHasHiddenAncestor ? 1 : 0)"
)
#endif
return false
}
isSearchVisible = true
updateSearchLayout()
refreshSearchIfNeeded()
let result = window.makeFirstResponder(searchField)
searchField.selectText(nil)
#if DEBUG
dlog(
"file.focus.search.end result=\(result ? 1 : 0) win=\(window.windowNumber) " +
"queryLen=\(searchField.stringValue.count) fr=\(fileExplorerDebugResponder(window.firstResponder))"
)
#endif
return result
}
@discardableResult
func focusOutline() -> Bool {
#if DEBUG
dlog(
"file.focus.outline.begin win=\(window?.windowNumber ?? -1) " +
"canAccept=\(cmuxCanAcceptRightSidebarKeyboardFocus ? 1 : 0) " +
"hostHidden=\(isHiddenOrHasHiddenAncestor ? 1 : 0) scrollHidden=\(scrollView.isHidden ? 1 : 0) " +
"outlineHidden=\(outlineView.isHiddenOrHasHiddenAncestor ? 1 : 0) " +
"rows=\(outlineView.numberOfRows) selected=\(outlineView.selectedRow) " +
"fr=\(fileExplorerDebugResponder(window?.firstResponder))"
)
#endif
guard let window, cmuxCanAcceptRightSidebarKeyboardFocus else {
#if DEBUG
dlog(
"file.focus.outline.end result=0 reason=unavailable " +
"win=\(window?.windowNumber ?? -1) hidden=\(isHiddenOrHasHiddenAncestor ? 1 : 0)"
)
#endif
return false
}
if isSearchVisible {
isSearchVisible = false