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
//! Source-neutral tree model at the center of the application. Filesystem and
//! JSON adapters build its flat node arena; `app` navigates it and `ui` renders
//! it through the `tui_treelistview::TreeModel` implementation.
//!
//! Consumers read nodes only through `Tree` accessors. The stored representation
//! is private so source-specific payloads—including filesystem names and spans
//! into retained JSON—can change without touching the app, renderer, or picker.
//! Accessors return owned values because those values may be derived on demand.
use std::ffi::OsString;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tui_treelistview::{TreeChildren, TreeModel, TreeRevision};
pub type NodeId = usize;
/// Values used when the focused node is accepted or passed to a shell binding.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ActionValues {
/// Text written to stdout when the node is accepted.
pub output: OsString,
/// Text written to stdout by the alternate accept action.
pub alternate_output: OsString,
/// Value exported to shell bindings as `$path`.
pub path: OsString,
/// Value exported to shell bindings as `$relpath`.
pub relpath: OsString,
}
impl ActionValues {
pub fn new(
output: impl Into<OsString>,
path: impl Into<OsString>,
relpath: impl Into<OsString>,
) -> Self {
let output = output.into();
Self {
alternate_output: output.clone(),
output,
path: path.into(),
relpath: relpath.into(),
}
}
pub fn with_alternate_output(mut self, output: impl Into<OsString>) -> Self {
self.alternate_output = output.into();
self
}
}
/// Display and action values stored verbatim.
#[derive(Debug)]
struct Explicit {
name: String,
detail: Option<String>,
action: ActionValues,
}
/// How a JSON node is addressed within its parent.
#[derive(Clone, Debug)]
pub(crate) enum JsonKey {
/// The synthetic `$` root of a single-rooted document.
Root,
/// The synthetic root of a JSONL document: the virtual array of records.
JsonlRoot,
/// An object member; the span covers the raw key token, quotes included.
Member { key_span: Range<u32> },
/// An array element.
Index(u32),
}
/// Per-node data that differs by source.
#[derive(Debug)]
enum Payload {
/// Stored verbatim (tests, transitional). Boxed so the variant does not
/// inflate every filesystem or JSON node.
Explicit(Box<Explicit>),
/// A filesystem entry's final path component. Kept as raw `OsString` so
/// non-UTF-8 names survive into the derived paths handed to shell
/// bindings; only the displayed name goes through `to_string_lossy`.
Fs { file_name: OsString },
/// A JSON value: its byte span in the retained input plus how it is
/// addressed within its parent. Everything else is derived.
/// `child_count` is the immediate-child count discovered when the parent
/// was scanned; `None` until known (unvalidated JSONL records).
Json {
span: Range<u32>,
key: JsonKey,
child_count: Option<u32>,
},
/// A span that failed to scan (a corrupt JSONL record): kept selectable,
/// rendered as an error leaf whose raw text is the alternate output.
JsonError { span: Range<u32>, key: JsonKey },
}
#[derive(Debug)]
struct Node {
parent: Option<NodeId>,
children: Vec<NodeId>,
is_container: bool,
depth: usize,
/// False while the node's children (or, for a pending scalar record, its
/// validation) have not been computed yet.
children_loaded: bool,
payload: Payload,
}
#[derive(Debug, Default)]
pub struct Tree {
nodes: Vec<Node>,
roots: Vec<NodeId>,
view_root: Option<NodeId>,
revision: TreeRevision,
/// The scanned directory (canonicalized) filesystem paths derive from.
fs_root: Option<PathBuf>,
/// Whether the scan ignores ignore-files; lazy walks must match.
fs_no_ignore: bool,
/// The raw JSON input document that `Payload::Json` spans index into.
/// Shared so materialization can read it while appending nodes.
json_source: Option<Arc<Vec<u8>>>,
/// Nodes whose children/validation are still pending.
unloaded: usize,
/// Arena-order sweep position for [`Tree::index_some`].
cursor: NodeId,
/// Messages for spans that failed to scan, for the banner and exit report.
errors: Vec<String>,
}
impl Tree {
pub fn new() -> Self {
Self::default()
}
/// A tree over a directory scan rooted at `root` (canonicalized);
/// filesystem nodes derive their paths from it and lazy directory walks
/// reuse the scan's ignore setting.
pub(crate) fn new_fs(root: PathBuf, no_ignore: bool) -> Self {
Self {
fs_root: Some(root),
fs_no_ignore: no_ignore,
..Self::default()
}
}
pub(crate) fn fs_no_ignore(&self) -> bool {
self.fs_no_ignore
}
pub fn push(
&mut self,
parent: Option<NodeId>,
name: impl Into<String>,
is_container: bool,
action: ActionValues,
) -> NodeId {
self.push_with_detail(parent, name, None, is_container, action)
}
pub fn push_with_detail(
&mut self,
parent: Option<NodeId>,
name: impl Into<String>,
detail: Option<String>,
is_container: bool,
action: ActionValues,
) -> NodeId {
self.push_node(
parent,
is_container,
true,
Payload::Explicit(Box::new(Explicit {
name: name.into(),
detail,
action,
})),
)
}
/// Append a filesystem entry; its action values are derived on demand.
/// Directories start unloaded — their contents come from a lazy walk.
pub(crate) fn push_fs(
&mut self,
parent: Option<NodeId>,
file_name: impl Into<OsString>,
is_container: bool,
) -> NodeId {
self.push_node(
parent,
is_container,
!is_container,
Payload::Fs {
file_name: file_name.into(),
},
)
}
/// Append a JSON value node; its display and action values are derived on
/// demand from the retained input bytes.
pub(crate) fn push_json(
&mut self,
parent: Option<NodeId>,
span: Range<u32>,
key: JsonKey,
is_container: bool,
child_count: Option<u32>,
children_loaded: bool,
) -> NodeId {
self.push_node(
parent,
is_container,
children_loaded,
Payload::Json {
span,
key,
child_count,
},
)
}
/// Attach the input document the JSON spans index into.
pub(crate) fn set_json_source(&mut self, bytes: Arc<Vec<u8>>) {
self.json_source = Some(bytes);
}
/// Drop every node with id >= `len` (discarding a partially scanned JSONL
/// record); nodes below `len` and their order are untouched.
pub(crate) fn truncate(&mut self, len: usize) {
for node in &self.nodes[len.min(self.nodes.len())..] {
if !node.children_loaded {
self.unloaded -= 1;
}
}
self.nodes.truncate(len);
self.roots.retain(|&id| id < len);
for node in &mut self.nodes {
node.children.retain(|&id| id < len);
}
self.cursor = self.cursor.min(len);
}
fn json_bytes(&self) -> &[u8] {
self.json_source
.as_ref()
.map_or(&[], |bytes| bytes.as_slice())
}
/// The shared input document, for materialization to read while pushing.
pub(crate) fn json_source_arc(&self) -> Option<Arc<Vec<u8>>> {
self.json_source.clone()
}
/// The byte span of a JSON (or error) node.
pub(crate) fn json_span(&self, id: NodeId) -> Option<Range<u32>> {
match &self.node(id).payload {
Payload::Json { span, .. } | Payload::JsonError { span, .. } => Some(span.clone()),
_ => None,
}
}
fn push_node(
&mut self,
parent: Option<NodeId>,
is_container: bool,
children_loaded: bool,
payload: Payload,
) -> NodeId {
let id = self.nodes.len();
let depth = parent.map_or(0, |id| self.nodes[id].depth + 1);
self.nodes.push(Node {
parent,
children: Vec::new(),
is_container,
depth,
children_loaded,
payload,
});
if !children_loaded {
self.unloaded += 1;
}
match parent {
Some(parent) => self.nodes[parent].children.push(id),
None => self.roots.push(id),
}
id
}
/// Materialize the node's pending children (or validate a pending scalar
/// record). Returns true when work was actually done.
pub(crate) fn ensure_children(&mut self, id: NodeId) -> bool {
if self.nodes[id].children_loaded {
return false;
}
match self.nodes[id].payload {
Payload::Json { .. } => crate::json_tree::materialize(self, id),
Payload::Fs { .. } => crate::fstree::materialize(self, id),
_ => self.mark_children_loaded(id),
}
self.revision.advance();
true
}
/// Flip a node to loaded, keeping the pending-work counter accurate.
pub(crate) fn mark_children_loaded(&mut self, id: NodeId) {
if !self.nodes[id].children_loaded {
self.nodes[id].children_loaded = true;
self.unloaded -= 1;
}
}
/// Convert a node whose span failed to scan into a selectable error leaf
/// and record the message for the banner and the exit report.
pub(crate) fn set_json_error(&mut self, id: NodeId, message: String) {
let (span, key) = match &self.nodes[id].payload {
Payload::Json { span, key, .. } => (span.clone(), key.clone()),
_ => return,
};
self.nodes[id].payload = Payload::JsonError { span, key };
self.nodes[id].is_container = false;
self.mark_children_loaded(id);
self.errors.push(message);
self.revision.advance();
}
/// Advance the arena-order sweep, loading up to `budget` pending nodes.
/// Returns true when any work was done. The sweep together with
/// on-demand loading eventually visits every node, so a fully swept tree
/// has validated every byte of the input.
pub(crate) fn index_some(&mut self, budget: usize) -> bool {
let mut done = 0;
while done < budget && self.cursor < self.nodes.len() {
if self.nodes[self.cursor].children_loaded {
self.cursor += 1;
} else {
self.ensure_children(self.cursor);
done += 1;
}
}
done > 0
}
/// Run the sweep to completion (startup `--expand`, and tests).
pub(crate) fn index_all(&mut self) {
while self.index_some(usize::MAX) {}
}
/// True once every node's children are loaded and every span validated;
/// the jump picker requires this.
pub fn fully_indexed(&self) -> bool {
self.unloaded == 0
}
/// Nodes whose children/validation are still pending (progress display).
pub fn pending(&self) -> usize {
self.unloaded
}
/// Messages for spans that failed to scan, in discovery order.
pub fn errors(&self) -> &[String] {
&self.errors
}
/// Record a non-fatal source error (an unreadable directory) for the
/// banner and the exit report.
pub(crate) fn record_error(&mut self, message: String) {
self.errors.push(message);
self.revision.advance();
}
fn node(&self, id: NodeId) -> &Node {
&self.nodes[id]
}
/// The node's display name.
pub fn name(&self, id: NodeId) -> String {
let node = self.node(id);
match &node.payload {
Payload::Explicit(explicit) => explicit.name.clone(),
Payload::Fs { file_name } => file_name.to_string_lossy().into_owned(),
Payload::Json {
span,
key,
child_count,
} => {
let bytes = self.json_bytes();
let prefix = match key {
JsonKey::Root | JsonKey::JsonlRoot => "$".to_owned(),
JsonKey::Member { key_span } => crate::json_tree::key_text(bytes, key_span),
JsonKey::Index(index) => format!("[{index}]"),
};
if node.is_container {
// Loaded containers count their children; unloaded ones
// fall back to the count discovered when their parent was
// scanned, and show `…` when even that is pending
// (unvalidated JSONL records).
let count = if node.children_loaded {
Some(node.children.len() as u32)
} else {
*child_count
};
// The JSONL root is a virtual array whatever its first
// record's first byte happens to be.
let object =
!matches!(key, JsonKey::JsonlRoot) && bytes[span.start as usize] == b'{';
match (object, count) {
(true, Some(0)) => format!("{prefix} {{}}"),
(true, Some(count)) => format!("{prefix} {{{count}}}"),
(true, None) => format!("{prefix} {{…}}"),
(false, Some(0)) => format!("{prefix} []"),
(false, Some(count)) => format!("{prefix} [{count}]"),
(false, None) => format!("{prefix} […]"),
}
} else {
format!("{prefix}: {}", crate::json_tree::value_text(bytes, span))
}
}
Payload::JsonError { key, .. } => {
let prefix = match key {
JsonKey::Root | JsonKey::JsonlRoot => "$".to_owned(),
JsonKey::Member { key_span } => {
crate::json_tree::key_text(self.json_bytes(), key_span)
}
JsonKey::Index(index) => format!("[{index}]"),
};
format!("{prefix} âš ")
}
}
}
/// Optional secondary text rendered after the name.
pub fn detail(&self, id: NodeId) -> Option<String> {
let node = self.node(id);
match &node.payload {
Payload::Explicit(explicit) => explicit.detail.clone(),
Payload::Fs { .. } => None,
Payload::Json { span, .. } => {
let bytes = self.json_bytes();
if !node.is_container || bytes.get(span.start as usize) != Some(&b'{') {
return None;
}
let members = node.children.iter().map(|&child| {
let child = self.node(child);
match &child.payload {
Payload::Json {
span,
key: JsonKey::Member { key_span },
..
} if !child.is_container => Some((key_span.clone(), span.clone())),
_ => None,
}
});
crate::json_tree::object_preview(bytes, members)
}
Payload::JsonError { span, .. } => {
let mut text = crate::json_tree::raw_text(self.json_bytes(), span);
if text.len() > 512 {
let mut end = 512;
while !text.is_char_boundary(end) {
end -= 1;
}
text.truncate(end);
}
Some(text)
}
}
}
pub fn parent(&self, id: NodeId) -> Option<NodeId> {
self.node(id).parent
}
/// 0 for roots.
pub fn depth(&self, id: NodeId) -> usize {
self.node(id).depth
}
/// Whether the node represents a container, including an empty one.
pub fn is_container(&self, id: NodeId) -> bool {
self.node(id).is_container
}
/// The node's children, in display order.
pub fn children_of(&self, id: NodeId) -> &[NodeId] {
&self.node(id).children
}
/// Text written to stdout when the node is accepted.
pub fn output(&self, id: NodeId) -> OsString {
match &self.node(id).payload {
Payload::Explicit(explicit) => explicit.action.output.clone(),
Payload::Fs { .. } => self.fs_path(id),
Payload::Json { .. } | Payload::JsonError { .. } => {
self.json_pointer_from(id, false).into()
}
}
}
/// Text written to stdout by the alternate accept action.
pub fn alternate_output(&self, id: NodeId) -> OsString {
match &self.node(id).payload {
Payload::Explicit(explicit) => explicit.action.alternate_output.clone(),
Payload::Fs { file_name } => file_name.clone(),
Payload::Json { span, .. } => {
crate::json_tree::value_text(self.json_bytes(), span).into()
}
Payload::JsonError { span, .. } => {
crate::json_tree::raw_text(self.json_bytes(), span).into()
}
}
}
/// Value exported to shell bindings as `$path`.
pub fn path(&self, id: NodeId) -> OsString {
match &self.node(id).payload {
Payload::Explicit(explicit) => explicit.action.path.clone(),
Payload::Fs { .. } => self.fs_path(id),
Payload::Json { .. } | Payload::JsonError { .. } => {
self.json_pointer_from(id, false).into()
}
}
}
/// The node's location in the host filesystem, when it has one. JSON nodes
/// are addressed by pointer within a document, so nothing outside ite can
/// open them.
pub fn filesystem_path(&self, id: NodeId) -> Option<OsString> {
match &self.node(id).payload {
Payload::Explicit(explicit) => Some(explicit.action.path.clone()),
Payload::Fs { .. } => Some(self.fs_path(id)),
Payload::Json { .. } | Payload::JsonError { .. } => None,
}
}
/// Value exported to shell bindings as `$relpath`: the address within the
/// source's natural unit — the scan root for directories, the document
/// for JSON, the containing record for JSONL (the record itself is "").
pub fn relpath(&self, id: NodeId) -> OsString {
match &self.node(id).payload {
Payload::Explicit(explicit) => explicit.action.relpath.clone(),
Payload::Fs { .. } => self.fs_relpath(id).into_os_string(),
Payload::Json { .. } | Payload::JsonError { .. } => {
self.json_pointer_from(id, true).into()
}
}
}
/// The text the jump picker matches and displays: the node's
/// document-global address. Coincides with `relpath` for directory scans
/// and JSON documents; JSONL diverges, since a record-relative `relpath`
/// repeats across records.
pub fn jump_key(&self, id: NodeId) -> String {
match &self.node(id).payload {
Payload::Json { .. } | Payload::JsonError { .. } => self.json_pointer_from(id, false),
_ => self.relpath(id).to_string_lossy().into_owned(),
}
}
/// Root-relative path of a filesystem node: ancestor file names joined.
fn fs_relpath(&self, id: NodeId) -> PathBuf {
let mut components = Vec::new();
let mut cursor = Some(id);
while let Some(current) = cursor {
let node = self.node(current);
if let Payload::Fs { file_name } = &node.payload {
components.push(file_name.as_os_str());
}
cursor = node.parent;
}
components.iter().rev().collect()
}
/// Absolute path of a filesystem node: the scan root plus [`Self::fs_relpath`].
fn fs_path(&self, id: NodeId) -> OsString {
let root = self.fs_root.as_deref().unwrap_or(Path::new(""));
root.join(self.fs_relpath(id)).into_os_string()
}
/// Canonical JSON Pointer of a JSON node, assembled from its ancestor
/// keys. Synthetic roots contribute no token, so a single-rooted
/// document's root is the empty (whole-document) pointer. With
/// `within_record` the walk stops at the containing JSONL record, whose
/// own token is excluded — the record-relative address.
fn json_pointer_from(&self, id: NodeId, within_record: bool) -> String {
let mut tokens = Vec::new();
let mut cursor = Some(id);
while let Some(current) = cursor {
let node = self.node(current);
let (Payload::Json { key, .. } | Payload::JsonError { key, .. }) = &node.payload else {
break;
};
if within_record && self.is_jsonl_record(current) {
break;
}
match key {
JsonKey::Root | JsonKey::JsonlRoot => {}
JsonKey::Member { key_span } => {
tokens.push(crate::json_tree::key_text(self.json_bytes(), key_span));
}
JsonKey::Index(index) => tokens.push(index.to_string()),
}
cursor = node.parent;
}
let mut pointer = String::new();
for token in tokens.iter().rev() {
pointer = crate::json_tree::append_pointer(&pointer, token);
}
pointer
}
/// Whether the node is a JSONL record: a direct child of the virtual
/// array root.
fn is_jsonl_record(&self, id: NodeId) -> bool {
self.node(id).parent.is_some_and(|parent| {
matches!(
&self.node(parent).payload,
Payload::Json {
key: JsonKey::JsonlRoot,
..
}
)
})
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub fn root_ids(&self) -> &[NodeId] {
&self.roots
}
/// The temporary root used by the tree view, if it has been narrowed.
pub(crate) fn view_root(&self) -> Option<NodeId> {
self.view_root
}
/// Narrow the tree model to one subtree, or restore the original forest.
pub(crate) fn set_view_root(&mut self, root: Option<NodeId>) {
if self.view_root != root {
self.view_root = root;
self.revision.advance();
}
}
/// The node's parent in the current view. A temporary root has no parent.
pub(crate) fn view_parent(&self, id: NodeId) -> Option<NodeId> {
if self.view_root == Some(id) {
None
} else {
self.nodes[id].parent
}
}
/// Whether a node belongs to the subtree exposed by the current view.
pub(crate) fn is_in_view(&self, id: NodeId) -> bool {
let Some(root) = self.view_root else {
return true;
};
let mut cursor = Some(id);
while let Some(current) = cursor {
if current == root {
return true;
}
cursor = self.nodes[current].parent;
}
false
}
/// True when the node cannot be expanded. Containers are never leaves:
/// an empty directory is still a directory and `{}`/`[]` are still
/// containers — they simply open to nothing.
pub fn is_leaf(&self, id: NodeId) -> bool {
!self.node(id).is_container
}
/// All expandable nodes as `(id, parent)` pairs, in tree order.
pub fn branches(&self) -> impl Iterator<Item = (NodeId, Option<NodeId>)> + '_ {
self.nodes
.iter()
.enumerate()
.filter(|(id, _)| !self.is_leaf(*id))
.map(|(id, node)| (id, node.parent))
}
/// Reorder every sibling list (roots included) to put containers first,
/// keeping the existing relative order within each group.
pub(crate) fn containers_first(&mut self) {
let containers_first = |nodes: &[Node], ids: &mut Vec<NodeId>| {
ids.sort_by_key(|&id| !nodes[id].is_container);
};
let mut roots = std::mem::take(&mut self.roots);
containers_first(&self.nodes, &mut roots);
self.roots = roots;
for id in 0..self.nodes.len() {
let mut children = std::mem::take(&mut self.nodes[id].children);
containers_first(&self.nodes, &mut children);
self.nodes[id].children = children;
}
}
/// Reorder one node's children to put containers first (lazy directory
/// walks sort each sibling list as it materializes).
pub(crate) fn containers_first_children(&mut self, id: NodeId) {
let mut children = std::mem::take(&mut self.nodes[id].children);
children.sort_by_key(|&child| !self.nodes[child].is_container);
self.nodes[id].children = children;
}
}
impl TreeModel for Tree {
type Id = NodeId;
fn roots(&self) -> impl Iterator<Item = NodeId> + '_ {
self.roots
.iter()
.copied()
.filter(|_| self.view_root.is_none())
.chain(self.view_root)
}
fn children(&self, id: NodeId) -> TreeChildren<'_, NodeId> {
let node = &self.nodes[id];
if node.is_container && node.children.is_empty() {
// `Unloaded` rather than an empty slice (which the widget
// normalizes to `Leaf`): a childless container — unwalked,
// unvalidated, or genuinely empty — must stay a branch.
TreeChildren::Unloaded
} else {
TreeChildren::loaded(&node.children)
}
}
fn revision(&self) -> TreeRevision {
self.revision
}
fn size_hint(&self) -> usize {
self.nodes.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsStr;
fn sample() -> (Tree, NodeId, NodeId, NodeId) {
let mut tree = Tree::new();
let dir = tree.push(
None,
"dir",
true,
ActionValues::new("dir", "/abs/dir", "dir"),
);
let file = tree.push_with_detail(
Some(dir),
"file",
Some("hint".to_owned()),
false,
ActionValues::new("dir/file", "/abs/dir/file", "dir/file")
.with_alternate_output("file"),
);
let leaf = tree.push(
None,
"leaf",
false,
ActionValues::new("leaf", "/abs/leaf", "leaf"),
);
(tree, dir, file, leaf)
}
#[test]
fn accessors_expose_hierarchy_and_display_data() {
let (tree, dir, file, leaf) = sample();
assert_eq!(tree.name(dir), "dir");
assert_eq!(tree.detail(dir), None);
assert_eq!(tree.detail(file).as_deref(), Some("hint"));
assert_eq!(tree.parent(dir), None);
assert_eq!(tree.parent(file), Some(dir));
assert_eq!(tree.depth(dir), 0);
assert_eq!(tree.depth(file), 1);
assert!(tree.is_container(dir));
assert!(!tree.is_container(leaf));
assert_eq!(tree.children_of(dir), [file]);
assert!(tree.children_of(leaf).is_empty());
}
#[test]
fn accessors_expose_action_values() {
let (tree, _, file, _) = sample();
assert_eq!(tree.output(file), OsStr::new("dir/file"));
assert_eq!(tree.alternate_output(file), OsStr::new("file"));
assert_eq!(tree.path(file), OsStr::new("/abs/dir/file"));
assert_eq!(tree.relpath(file), OsStr::new("dir/file"));
}
#[test]
fn jump_key_is_the_relpath_text_today() {
let (tree, dir, file, _) = sample();
assert_eq!(tree.jump_key(dir), "dir");
assert_eq!(tree.jump_key(file), "dir/file");
}
#[test]
fn fs_nodes_derive_action_values_from_the_hierarchy() {
let mut tree = Tree::new_fs("/scan/root".into(), false);
let dir = tree.push_fs(None, "b-dir", true);
let file = tree.push_fs(Some(dir), "inner.txt", false);
assert_eq!(tree.name(file), "inner.txt");
assert_eq!(tree.detail(file), None);
assert_eq!(tree.path(dir), OsStr::new("/scan/root/b-dir"));
assert_eq!(tree.path(file), OsStr::new("/scan/root/b-dir/inner.txt"));
assert_eq!(tree.relpath(file), OsStr::new("b-dir/inner.txt"));
assert_eq!(tree.output(file), tree.path(file));
assert_eq!(tree.alternate_output(file), OsStr::new("inner.txt"));
assert_eq!(tree.jump_key(file), "b-dir/inner.txt");
assert!(tree.is_container(dir));
assert!(!tree.is_container(file));
}
#[test]
fn only_filesystem_backed_nodes_have_a_filesystem_path() {
let mut tree = Tree::new_fs("/scan/root".into(), false);
let dir = tree.push_fs(None, "b-dir", true);
let file = tree.push_fs(Some(dir), "inner.txt", false);
assert_eq!(
tree.filesystem_path(file),
Some(OsString::from("/scan/root/b-dir/inner.txt"))
);
let json = crate::json_tree::from_reader(r#"{"a": 1}"#.as_bytes()).unwrap();
let member = json.root_ids()[0];
// A JSON node is addressed by pointer, not by a path anything can open.
assert!(!json.path(member).is_empty());
assert_eq!(json.filesystem_path(member), None);
}
#[test]
fn containers_first_reorders_every_sibling_list_stably() {
let mut tree = Tree::new();
let a = tree.push(None, "a-file", false, ActionValues::new("", "", ""));
let b = tree.push(None, "b-dir", true, ActionValues::new("", "", ""));
let c = tree.push(None, "c-file", false, ActionValues::new("", "", ""));
let d = tree.push(None, "d-dir", true, ActionValues::new("", "", ""));
let inner_file = tree.push(Some(b), "x-file", false, ActionValues::new("", "", ""));
let inner_dir = tree.push(Some(b), "y-dir", true, ActionValues::new("", "", ""));
tree.containers_first();
assert_eq!(tree.root_ids(), [b, d, a, c]);
assert_eq!(tree.children_of(b), [inner_dir, inner_file]);
}
}