bmrk 0.4.0

A fast TUI for directory navigation and bookmark management
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
use crate::tree_node::{TreeNode, TreeNodeRef};
use anyhow::Result;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::rc::Rc;

/// Result of a recursive toggle search: distinguishes "not found" from "found".
enum ToggleResult {
    NotFound,
    Found(Option<String>),
}

/// Captured selection + tree-expansion state, taken when quick jump (`Tab`) activates, so `Esc`
/// can fully cancel the session and restore the tree exactly as it looked before `Tab` was
/// pressed. A confirmed exit (`Tab`/`Enter`/an arrow key) discards this instead of applying it,
/// so the auto-expansion trail persists in that case — see `.debug/BDP.md`.
struct ExpansionSnapshot {
    selected_path: Option<PathBuf>,
    expanded_paths: HashSet<PathBuf>,
}

/// Result of the last "copy path" action (`c` by default), shown in the header until the next
/// keypress clears it.
pub enum CopyFeedback {
    /// The selected item's path was copied to the clipboard successfully.
    Success,
    /// Copying failed; the short reason is included for display.
    Error(String),
}

/// Navigation logic for tree traversal and manipulation
pub struct Navigation {
    pub root: TreeNodeRef,
    pub flat_list: Vec<TreeNodeRef>,
    pub selected: usize,
    pub show_hidden: bool,
    pub follow_symlinks: bool,
    /// History stack of previously visited root paths for back-navigation (`u`).
    pub history: VecDeque<PathBuf>,
    /// Last navigation error message, shown in the UI header until the next successful navigation.
    pub nav_error: Option<String>,
    /// When `true` the renderer centers the selected item; `false` uses minimal (ensure-visible) scroll.
    /// Set to `true` by keyboard navigation, `false` by mouse actions.
    pub center_selection: bool,
    // Performance optimization: HashMap for O(1) path lookup
    path_to_index: HashMap<PathBuf, usize>,
    /// Set while a quick-jump session is in progress; `None` otherwise. See [`ExpansionSnapshot`].
    quick_jump_snapshot: Option<ExpansionSnapshot>,
    /// Result of the last "copy path" action, shown in the header until the next keypress.
    pub copy_feedback: Option<CopyFeedback>,
    /// Long-lived clipboard handle, created lazily on the first successful "copy path" action
    /// and kept open for the rest of the app's lifetime. On X11, `arboard`'s `Clipboard` hands
    /// its content off to a clipboard manager (if any) the moment it's *dropped* — creating and
    /// dropping a fresh instance on every keypress would lose the copied text the instant this
    /// function returns, before the user has a chance to switch windows and paste. Keeping one
    /// instance alive means the handoff only happens once, when the whole app exits.
    clipboard: Option<arboard::Clipboard>,
}

impl Navigation {
    pub fn new(
        start_path: PathBuf,
        show_files: bool,
        show_hidden: bool,
        follow_symlinks: bool,
    ) -> Result<Self> {
        let mut root = TreeNode::new(start_path, 0)?;
        root.load_children(show_files, show_hidden, follow_symlinks)?;
        // A childless (or unreadable) root has nothing to show as expanded — forcing this to
        // `true` regardless would leave `toggle_expand`'s leaf-directory guard unable to ever
        // flip it back off, permanently stuck.
        root.is_expanded = root.has_children == Some(true);
        let root = Rc::new(RefCell::new(root));

        let mut nav = Self {
            root,
            flat_list: Vec::new(),
            selected: 0,
            show_hidden,
            follow_symlinks,
            history: VecDeque::new(),
            nav_error: None,
            center_selection: true,
            path_to_index: HashMap::new(),
            quick_jump_snapshot: None,
            copy_feedback: None,
            clipboard: None,
        };

        nav.rebuild_flat_list();
        Ok(nav)
    }

    /// Rebuild flat list of visible nodes and update path index.
    ///
    /// Also re-clamps `selected` to the new list bounds: collapsing a node (e.g. via
    /// [`toggle_node`](Self::toggle_node)) can shrink the list out from under a `selected`
    /// index that pointed past the collapsed region, which would otherwise leave
    /// [`get_selected_node`](Self::get_selected_node) returning `None`.
    pub fn rebuild_flat_list(&mut self) {
        self.flat_list.clear();
        self.path_to_index.clear();
        Self::collect_visible_nodes(&self.root, &mut self.flat_list);

        // Build path → index mapping for O(1) lookups
        for (idx, node) in self.flat_list.iter().enumerate() {
            let path = node.borrow().path.clone();
            self.path_to_index.insert(path, idx);
        }

        if self.selected >= self.flat_list.len() {
            self.selected = self.flat_list.len().saturating_sub(1);
        }
    }

    fn collect_visible_nodes(node: &TreeNodeRef, result: &mut Vec<TreeNodeRef>) {
        result.push(Rc::clone(node));

        // Check if node is expanded and get children count
        let (is_expanded, children_count) = {
            let node_borrowed = node.borrow();
            (node_borrowed.is_expanded, node_borrowed.children.len())
        };

        if is_expanded {
            // Recursively collect children without cloning the entire vector
            for i in 0..children_count {
                let child = Rc::clone(&node.borrow().children[i]);
                Self::collect_visible_nodes(&child, result);
            }
        }
    }

    /// Get currently selected node
    pub fn get_selected_node(&self) -> Option<TreeNodeRef> {
        self.flat_list.get(self.selected).map(Rc::clone)
    }

    /// Move selection down
    pub fn move_down(&mut self) {
        if self.selected < self.flat_list.len().saturating_sub(1) {
            self.selected += 1;
        }
    }

    /// Move selection up
    pub fn move_up(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// Toggle node expansion at path.
    /// Returns `Some(error_message)` if the node has an error after toggle, `None` otherwise.
    pub fn toggle_node(&mut self, path: &Path, show_files: bool) -> Result<Option<String>> {
        // Fast path: use path index to toggle without walking the tree.
        if let Some(index) = self.path_to_index.get(path).copied() {
            if index < self.flat_list.len() {
                let error_msg = {
                    let mut node_borrowed = self.flat_list[index].borrow_mut();
                    node_borrowed.toggle_expand(
                        show_files,
                        self.show_hidden,
                        self.follow_symlinks,
                    )?;
                    if node_borrowed.has_error {
                        node_borrowed.error_message.clone()
                    } else {
                        None
                    }
                };
                self.rebuild_flat_list();
                return Ok(error_msg);
            }
        }

        // Fallback: walk the tree to find and toggle the node.
        let error_msg = match Self::toggle_node_recursive(
            &self.root,
            path,
            show_files,
            self.show_hidden,
            self.follow_symlinks,
        )? {
            ToggleResult::Found(msg) => msg,
            ToggleResult::NotFound => None,
        };
        self.rebuild_flat_list();
        Ok(error_msg)
    }

    fn toggle_node_recursive(
        node: &TreeNodeRef,
        target_path: &Path,
        show_files: bool,
        show_hidden: bool,
        follow_symlinks: bool,
    ) -> Result<ToggleResult> {
        // Check if this is the target node
        {
            let mut node_borrowed = node.borrow_mut();
            if node_borrowed.path == target_path {
                node_borrowed.toggle_expand(show_files, show_hidden, follow_symlinks)?;
                let error_msg = if node_borrowed.has_error {
                    node_borrowed.error_message.clone()
                } else {
                    None
                };
                return Ok(ToggleResult::Found(error_msg));
            }
        }

        // Recursively search children; stop as soon as the target is found.
        let children_count = node.borrow().children.len();
        for i in 0..children_count {
            let child = Rc::clone(&node.borrow().children[i]);
            if let ToggleResult::Found(msg) = Self::toggle_node_recursive(
                &child,
                target_path,
                show_files,
                show_hidden,
                follow_symlinks,
            )? {
                return Ok(ToggleResult::Found(msg));
            }
        }

        Ok(ToggleResult::NotFound)
    }

    /// Reload tree with new show_files setting
    #[allow(dead_code)]
    pub fn reload_tree(&mut self, show_files: bool) -> Result<()> {
        Self::reload_node_recursive(
            &self.root,
            show_files,
            self.show_hidden,
            self.follow_symlinks,
        )?;
        self.rebuild_flat_list();
        Ok(())
    }

    fn reload_node_recursive(
        node: &TreeNodeRef,
        show_files: bool,
        show_hidden: bool,
        follow_symlinks: bool,
    ) -> Result<()> {
        // Check if we need to reload this node
        let should_reload = {
            let node_borrowed = node.borrow();
            node_borrowed.is_expanded && node_borrowed.is_dir
        };

        if should_reload {
            // Clear children and reload with new mode
            {
                let mut node_borrowed = node.borrow_mut();
                node_borrowed.children.clear();
                node_borrowed.load_children(show_files, show_hidden, follow_symlinks)?;
            }

            // Recursively reload child nodes without cloning
            let children_count = node.borrow().children.len();
            for i in 0..children_count {
                let child = Rc::clone(&node.borrow().children[i]);
                Self::reload_node_recursive(&child, show_files, show_hidden, follow_symlinks)?;
            }
        }
        Ok(())
    }

    /// Move selection to the parent node within the current flat list.
    /// Returns true if a parent was found, false if already at depth 0.
    pub fn select_parent_node(&mut self) -> bool {
        if let Some(node) = self.flat_list.get(self.selected) {
            let depth = node.borrow().depth;
            if depth == 0 {
                return false;
            }
            let target_depth = depth - 1;
            for i in (0..self.selected).rev() {
                if self.flat_list[i].borrow().depth == target_depth {
                    self.selected = i;
                    return true;
                }
            }
        }
        false
    }

    /// Navigate to parent directory
    pub fn go_to_parent(&mut self, show_files: bool) -> Result<()> {
        let parent_path = {
            let root_borrowed = self.root.borrow();
            root_borrowed.path.parent().map(|p| p.to_path_buf())
        };

        if let Some(parent_path) = parent_path {
            let current_path = self.root.borrow().path.clone();

            let mut new_root = TreeNode::new(parent_path, 0)?;
            new_root.load_children(show_files, self.show_hidden, self.follow_symlinks)?;
            new_root.is_expanded = new_root.has_children == Some(true);

            if !new_root.is_dir || new_root.has_error {
                if let Some(ref msg) = new_root.error_message {
                    self.nav_error = Some(msg.clone());
                } else if !new_root.is_dir {
                    self.nav_error =
                        Some(format!("Directory not found: {}", new_root.path.display()));
                }
                return Ok(());
            }

            self.push_history(current_path.clone());
            self.root = Rc::new(RefCell::new(new_root));
            self.rebuild_flat_list();
            self.nav_error = None;

            // Find and select previous directory using HashMap (O(1) instead of O(n))
            if let Some(&idx) = self.path_to_index.get(&current_path) {
                self.selected = idx;
            }
        }

        Ok(())
    }

    /// Navigate back to the previous root in history.
    /// Returns `true` if navigation occurred, `false` if history is empty.
    pub fn go_back(&mut self, show_files: bool) -> Result<bool> {
        let Some(prev_path) = self.history.pop_back() else {
            return Ok(false);
        };

        let mut new_root = TreeNode::new(prev_path.clone(), 0)?;
        new_root.load_children(show_files, self.show_hidden, self.follow_symlinks)?;
        new_root.is_expanded = new_root.has_children == Some(true);

        if !new_root.is_dir || new_root.has_error {
            self.history.push_back(prev_path);
            if let Some(ref msg) = new_root.error_message {
                self.nav_error = Some(msg.clone());
            } else if !new_root.is_dir {
                self.nav_error = Some(format!("Directory not found: {}", new_root.path.display()));
            }
            return Ok(false);
        }

        self.nav_error = None;
        self.root = Rc::new(RefCell::new(new_root));
        self.rebuild_flat_list();
        self.selected = 0;
        Ok(true)
    }

    /// Push path to history, capping at 50 entries.
    fn push_history(&mut self, path: PathBuf) {
        if self.history.len() >= 50 {
            self.history.pop_front();
        }
        self.history.push_back(path);
    }

    /// Navigate to arbitrary directory (for bookmarks).
    ///
    /// Returns `Some(error_message)` when the path does not exist, is not a directory,
    /// or cannot be read. Returns `None` on success. The error is also stored in
    /// [`Navigation::nav_error`] and displayed in the UI header until the next
    /// successful navigation.
    pub fn go_to_directory(
        &mut self,
        target_path: PathBuf,
        show_files: bool,
    ) -> Result<Option<String>> {
        if !target_path.exists() {
            let msg = format!("Directory not found: {}", target_path.display());
            self.nav_error = Some(msg.clone());
            return Ok(Some(msg));
        }
        if !target_path.is_dir() {
            let msg = format!("Not a directory: {}", target_path.display());
            self.nav_error = Some(msg.clone());
            return Ok(Some(msg));
        }

        // Save current state in case we need to restore it
        let old_root = Rc::clone(&self.root);
        let old_selected = self.selected;

        let mut new_root = TreeNode::new(target_path, 0)?;
        new_root.load_children(show_files, self.show_hidden, self.follow_symlinks)?;
        new_root.is_expanded = new_root.has_children == Some(true);

        // Check if the new root is unusable (TOCTOU: path may have changed since pre-checks).
        if !new_root.is_dir || new_root.has_error {
            self.root = old_root;
            self.selected = old_selected;
            let msg = if !new_root.is_dir {
                let m = format!("Not a directory: {}", new_root.path.display());
                self.nav_error = Some(m.clone());
                Some(m)
            } else {
                let m = new_root.error_message.clone();
                if let Some(ref s) = m {
                    self.nav_error = Some(s.clone());
                }
                m
            };
            return Ok(msg);
        }

        // Success - record current root in history before switching
        let current_path = old_root.borrow().path.clone();
        self.push_history(current_path);

        self.nav_error = None;
        self.root = Rc::new(RefCell::new(new_root));
        self.rebuild_flat_list();
        self.selected = 0;

        Ok(None)
    }

    /// Expand path to node (for search results)
    pub fn expand_path_to_node(&mut self, target_path: &PathBuf, show_files: bool) -> Result<()> {
        Self::expand_path_recursive(
            &self.root,
            target_path,
            show_files,
            self.show_hidden,
            self.follow_symlinks,
        )?;
        self.rebuild_flat_list();

        self.nav_error = None;

        // Find and select element in tree using HashMap (O(1) instead of O(n))
        if let Some(&idx) = self.path_to_index.get(target_path) {
            self.selected = idx;
        }

        Ok(())
    }

    fn expand_path_recursive(
        node: &TreeNodeRef,
        target_path: &PathBuf,
        show_files: bool,
        show_hidden: bool,
        follow_symlinks: bool,
    ) -> Result<bool> {
        // Check if this is the target node or if target is a descendant
        {
            let mut node_borrowed = node.borrow_mut();

            // If this is the target node, do nothing
            if &node_borrowed.path == target_path {
                return Ok(true);
            }

            // Check if target_path is a descendant of current node
            if !target_path.starts_with(&node_borrowed.path) {
                return Ok(false);
            }

            // Load children if needed
            if node_borrowed.children.is_empty() && node_borrowed.is_dir {
                node_borrowed.load_children(show_files, show_hidden, follow_symlinks)?;
            }

            // Expand current node
            node_borrowed.is_expanded = true;
        }

        // Recursively search in children without cloning
        let children_count = node.borrow().children.len();
        for i in 0..children_count {
            let child = Rc::clone(&node.borrow().children[i]);
            if Self::expand_path_recursive(
                &child,
                target_path,
                show_files,
                show_hidden,
                follow_symlinks,
            )? {
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// Capture the current selection and tree-expansion state, to be restored by
    /// [`cancel_quick_jump`](Self::cancel_quick_jump) if the quick-jump session that's about to
    /// start gets cancelled via `Esc`. Call when quick jump activates (`Tab`).
    pub fn begin_quick_jump_snapshot(&mut self) {
        let mut expanded_paths = HashSet::new();
        Self::collect_expanded_paths(&self.root, &mut expanded_paths);
        self.quick_jump_snapshot = Some(ExpansionSnapshot {
            selected_path: self.get_selected_node().map(|n| n.borrow().path.clone()),
            expanded_paths,
        });
    }

    /// Discard the pending quick-jump snapshot without restoring anything. Call when the
    /// session ends by *confirming* a match (`Tab`/`Enter`/an arrow key) — the auto-expansion
    /// trail left behind is intentional in that case (see `.debug/BDP.md`).
    pub fn commit_quick_jump(&mut self) {
        self.quick_jump_snapshot = None;
    }

    /// Undo everything the quick-jump session did: collapses any node that became expanded
    /// since [`begin_quick_jump_snapshot`](Self::begin_quick_jump_snapshot) and restores the
    /// original selection. Call when the session is cancelled via `Esc`. A no-op if no
    /// snapshot is pending (e.g. quick jump was never activated).
    pub fn cancel_quick_jump(&mut self) {
        let Some(snapshot) = self.quick_jump_snapshot.take() else {
            return;
        };
        Self::apply_expansion_restore(&self.root, &snapshot.expanded_paths);
        self.rebuild_flat_list();
        if let Some(path) = &snapshot.selected_path {
            if let Some(&idx) = self.path_to_index.get(path) {
                self.selected = idx;
            }
        }
    }

    /// Expand `path` if it isn't already — a no-op if it's already open, unlike
    /// [`toggle_node`](Self::toggle_node), which would incorrectly collapse it. Used by quick
    /// jump's `/` narrowing (`.debug/BDP.md` Part 4) to physically reveal a locked folder's
    /// children without disturbing a folder the user had already expanded before entering quick
    /// jump. `path` must currently be visible (e.g. just landed on via a match) — if it isn't in
    /// the flat list, this is a no-op.
    pub fn ensure_expanded(&mut self, path: &Path, show_files: bool) -> Result<Option<String>> {
        let already_expanded = self
            .path_to_index
            .get(path)
            .and_then(|&idx| self.flat_list.get(idx))
            .map(|node| node.borrow().is_expanded)
            .unwrap_or(true);
        if already_expanded {
            return Ok(None);
        }
        self.toggle_node(path, show_files)
    }

    /// Returns `true` if `path` was **not** expanded when the current quick-jump session began —
    /// i.e. it became expanded during this session (via a match jump or
    /// [`ensure_expanded`](Self::ensure_expanded)) and is therefore safe to collapse without
    /// undoing state the user set up before `Tab`. Returns `true` (safe to collapse) when there
    /// is no active snapshot, since that means quick jump isn't running.
    pub fn expanded_during_quick_jump_session(&self, path: &Path) -> bool {
        match &self.quick_jump_snapshot {
            Some(snapshot) => !snapshot.expanded_paths.contains(path),
            None => true,
        }
    }

    fn collect_expanded_paths(node: &TreeNodeRef, result: &mut HashSet<PathBuf>) {
        let (path, is_expanded, children_count) = {
            let node_borrowed = node.borrow();
            (
                node_borrowed.path.clone(),
                node_borrowed.is_expanded,
                node_borrowed.children.len(),
            )
        };
        if is_expanded {
            result.insert(path);
        }
        for i in 0..children_count {
            let child = Rc::clone(&node.borrow().children[i]);
            Self::collect_expanded_paths(&child, result);
        }
    }

    /// Collapses every node that's expanded now but wasn't in `keep_expanded` — i.e. every
    /// node that got expanded after the snapshot was taken.
    fn apply_expansion_restore(node: &TreeNodeRef, keep_expanded: &HashSet<PathBuf>) {
        let (path, is_expanded, children_count) = {
            let node_borrowed = node.borrow();
            (
                node_borrowed.path.clone(),
                node_borrowed.is_expanded,
                node_borrowed.children.len(),
            )
        };
        if is_expanded && !keep_expanded.contains(&path) {
            node.borrow_mut().is_expanded = false;
        }
        for i in 0..children_count {
            let child = Rc::clone(&node.borrow().children[i]);
            Self::apply_expansion_restore(&child, keep_expanded);
        }
    }

    /// Copy the currently selected item's absolute path to the system clipboard. Sets
    /// [`copy_feedback`](Self::copy_feedback) to `Success` or `Error` depending on the outcome —
    /// never propagates the error, since a failed clipboard access (e.g. no display server, no
    /// clipboard utility available) is a display concern, not something that should interrupt
    /// navigation.
    pub fn copy_selected_path_to_clipboard(&mut self) {
        let Some(node) = self.get_selected_node() else {
            return;
        };
        let path = node.borrow().path.display().to_string();

        if self.clipboard.is_none() {
            if let Err(e) = arboard::Clipboard::new().map(|cb| self.clipboard = Some(cb)) {
                self.copy_feedback = Some(CopyFeedback::Error(e.to_string()));
                return;
            }
        }

        self.copy_feedback = match &mut self.clipboard {
            Some(cb) => match cb.set_text(path) {
                Ok(()) => Some(CopyFeedback::Success),
                Err(e) => Some(CopyFeedback::Error(e.to_string())),
            },
            None => None, // unreachable: the block above returns early on failure
        };
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn make_nav(path: PathBuf) -> Navigation {
        Navigation::new(path, false, false, false).expect("Navigation::new failed")
    }

    #[test]
    fn copy_selected_path_to_clipboard_sets_feedback() {
        let tmp = TempDir::new().unwrap();
        let mut nav = make_nav(tmp.path().to_path_buf());

        assert!(nav.copy_feedback.is_none());
        nav.copy_selected_path_to_clipboard();
        // Outcome depends on clipboard availability in the environment (e.g. a headless CI
        // box with no display server) — only the "some feedback was set, no panic" contract
        // is guaranteed, not which variant.
        assert!(
            nav.copy_feedback.is_some(),
            "copy_selected_path_to_clipboard must always set some feedback"
        );
    }

    #[test]
    fn copy_selected_path_to_clipboard_reuses_handle_across_calls() {
        // The clipboard handle must be created lazily once and kept alive for repeated copies
        // in the same session — recreating (and immediately dropping) a fresh one per call
        // would hand the content off to a clipboard manager (or lose it) between copies.
        let tmp = TempDir::new().unwrap();
        let child = tmp.path().join("child");
        std::fs::create_dir(&child).unwrap();
        let mut nav = make_nav(tmp.path().to_path_buf());

        nav.copy_selected_path_to_clipboard();
        assert!(nav.copy_feedback.is_some());

        nav.move_down();
        nav.copy_selected_path_to_clipboard();
        assert!(
            nav.copy_feedback.is_some(),
            "a second copy in the same session must also produce feedback"
        );
    }

    #[test]
    fn copy_selected_path_to_clipboard_is_noop_with_empty_flat_list() {
        let tmp = TempDir::new().unwrap();
        let mut nav = make_nav(tmp.path().to_path_buf());
        nav.flat_list.clear();

        nav.copy_selected_path_to_clipboard();
        assert!(
            nav.copy_feedback.is_none(),
            "must not set feedback when nothing is selected"
        );
    }

    // --- leaf-directory root: `is_expanded` must never be forced true with no children ---
    //
    // Regression coverage for the `h`-key deadlock: `TreeNode::toggle_expand` refuses to touch
    // `is_expanded` at all once `has_children == Some(false)` (see `tree_node.rs`), so if a new
    // root with no subdirectories were ever given `is_expanded = true` anyway, nothing could ever
    // flip it back to `false` again — `h` would stay stuck forever on such a root.

    #[test]
    fn new_leaf_root_starts_collapsed() {
        let tmp = TempDir::new().unwrap();
        // No children created under `tmp` — a genuine leaf directory.
        let nav = make_nav(tmp.path().to_path_buf());
        assert!(
            !nav.root.borrow().is_expanded,
            "a root with no children must not be marked expanded"
        );
    }

    #[test]
    fn new_root_with_children_starts_expanded() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir(tmp.path().join("child")).unwrap();
        let nav = make_nav(tmp.path().to_path_buf());
        assert!(
            nav.root.borrow().is_expanded,
            "a root with children must still start expanded, as before"
        );
    }

    #[test]
    fn go_to_directory_into_leaf_dir_starts_collapsed() {
        let tmp = TempDir::new().unwrap();
        let leaf = tmp.path().join("leaf");
        std::fs::create_dir(&leaf).unwrap();
        let mut nav = make_nav(tmp.path().to_path_buf());

        nav.go_to_directory(leaf, false).unwrap();
        assert!(!nav.root.borrow().is_expanded);
    }

    #[test]
    fn go_to_parent_into_dir_with_only_this_child_starts_expanded() {
        let tmp = TempDir::new().unwrap();
        let child = tmp.path().join("child");
        std::fs::create_dir(&child).unwrap();
        let mut nav = make_nav(child);

        nav.go_to_parent(false).unwrap();
        assert!(
            nav.root.borrow().is_expanded,
            "the parent has a child (the dir we came from), so it must still expand"
        );
    }

    #[test]
    fn go_back_into_leaf_dir_starts_collapsed() {
        let tmp = TempDir::new().unwrap();
        let leaf = tmp.path().join("leaf");
        std::fs::create_dir(&leaf).unwrap();
        // Start rooted at the leaf itself, then step up to its parent (which pushes the leaf
        // onto history) so `go_back` — a separate code path from `go_to_directory` — is the one
        // exercised when navigating back into it.
        let mut nav = make_nav(leaf.clone());
        nav.go_to_parent(false).unwrap();
        assert!(
            nav.root.borrow().is_expanded,
            "the parent has a child (`leaf`), so it must be expanded"
        );

        assert!(nav.go_back(false).unwrap());
        assert!(
            !nav.root.borrow().is_expanded,
            "going back into a leaf directory must not force it expanded"
        );
    }

    #[test]
    fn go_back_round_trips_after_go_to_directory() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();

        let mut nav = make_nav(root.clone());
        assert_eq!(nav.history.len(), 0);

        nav.go_to_directory(child.clone(), false).unwrap();
        assert_eq!(nav.root.borrow().path, child);
        assert_eq!(nav.history.len(), 1);
        assert_eq!(nav.history[0], root);

        let went_back = nav.go_back(false).unwrap();
        assert!(went_back);
        assert_eq!(nav.root.borrow().path, root);
        assert_eq!(nav.history.len(), 0);
    }

    #[test]
    fn failed_navigation_does_not_push_history() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let nonexistent = root.join("does_not_exist");

        let mut nav = make_nav(root.clone());
        let result = nav.go_to_directory(nonexistent.clone(), false).unwrap();

        assert!(
            result.is_some(),
            "must return an error message for nonexistent path"
        );
        let msg = result.unwrap();
        assert!(
            msg.contains(nonexistent.to_str().unwrap()),
            "error message must mention the path"
        );
        assert_eq!(nav.nav_error.as_deref(), Some(msg.as_str()));
        assert_eq!(nav.root.borrow().path, root, "root must not change");
        assert_eq!(nav.history.len(), 0, "history must not grow on failed nav");
    }

    #[test]
    fn successful_navigation_clears_nav_error() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();
        let nonexistent = root.join("does_not_exist");

        let mut nav = make_nav(root.clone());
        nav.go_to_directory(nonexistent, false).unwrap();
        assert!(
            nav.nav_error.is_some(),
            "error should be set after failed nav"
        );

        nav.go_to_directory(child.clone(), false).unwrap();
        assert!(
            nav.nav_error.is_none(),
            "error must be cleared after successful nav"
        );
    }

    #[test]
    fn go_back_does_not_push_history() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();

        let mut nav = make_nav(root.clone());
        nav.go_to_directory(child.clone(), false).unwrap();
        assert_eq!(nav.history.len(), 1);

        nav.go_back(false).unwrap();
        assert_eq!(nav.history.len(), 0, "go_back must not push to history");

        let went_back = nav.go_back(false).unwrap();
        assert!(!went_back, "go_back on empty history returns false");
    }

    #[test]
    fn go_to_parent_pushes_history() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();

        let mut nav = make_nav(child.clone());
        assert_eq!(nav.history.len(), 0);

        nav.go_to_parent(false).unwrap();
        assert_eq!(nav.history.len(), 1);
        assert_eq!(nav.history[0], child);
    }

    #[test]
    fn go_back_clears_nav_error() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();

        let mut nav = make_nav(root.clone());
        nav.go_to_directory(child, false).unwrap();
        nav.nav_error = Some("stale error".into());

        let went_back = nav.go_back(false).unwrap();
        assert!(went_back);
        assert!(
            nav.nav_error.is_none(),
            "go_back must clear nav_error on success"
        );
    }

    #[test]
    fn go_to_parent_clears_nav_error() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();

        let mut nav = make_nav(child.clone());
        nav.nav_error = Some("stale error".into());

        nav.go_to_parent(false).unwrap();
        assert!(
            nav.nav_error.is_none(),
            "go_to_parent must clear nav_error on success"
        );
    }

    #[test]
    fn expand_path_to_node_clears_nav_error() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();

        let mut nav = make_nav(root.clone());
        nav.nav_error = Some("stale error".into());

        nav.expand_path_to_node(&child, false).unwrap();
        assert!(
            nav.nav_error.is_none(),
            "expand_path_to_node must clear nav_error on success"
        );
    }

    #[test]
    fn go_to_directory_with_file_path_does_not_navigate() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let file = root.join("regular.txt");
        std::fs::write(&file, b"hello").unwrap();

        let mut nav = make_nav(root.clone());
        let result = nav.go_to_directory(file.clone(), false).unwrap();

        assert!(result.is_some(), "must return error for a file path");
        assert!(
            result.unwrap().contains(file.to_str().unwrap()),
            "error message must mention the path"
        );
        assert_eq!(nav.root.borrow().path, root, "root must not change");
        assert_eq!(nav.history.len(), 0, "history must not grow");
        assert!(nav.nav_error.is_some(), "nav_error must be set");
    }

    #[test]
    fn go_back_preserves_history_entry_when_target_inaccessible() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();

        let mut nav = make_nav(root.clone());
        nav.go_to_directory(child, false).unwrap();
        assert_eq!(nav.history.len(), 1);

        // Remove the previous root so go_back targets a missing directory
        std::fs::remove_dir_all(&root).unwrap();

        let went_back = nav.go_back(false).unwrap();
        assert!(
            !went_back,
            "go_back must return false for inaccessible directory"
        );
        assert_eq!(
            nav.history.len(),
            1,
            "history entry must be re-pushed on failure"
        );
        assert!(
            nav.nav_error.is_some(),
            "nav_error must be set when go_back fails"
        );
    }

    #[test]
    fn collapsing_a_node_clamps_selected_within_new_bounds() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let sub = root.join("sub");
        let leaf1 = sub.join("leaf1");
        let leaf2 = sub.join("leaf2");
        std::fs::create_dir(&sub).unwrap();
        std::fs::create_dir(&leaf1).unwrap();
        std::fs::create_dir(&leaf2).unwrap();

        let mut nav = make_nav(root.clone());
        // Expand "sub" so its children are visible: [root, sub, leaf1, leaf2].
        nav.toggle_node(&sub, false).unwrap();
        assert_eq!(nav.flat_list.len(), 4);

        // Select the last child, then collapse "sub" out from under it.
        nav.selected = 3;
        nav.toggle_node(&sub, false).unwrap();

        assert_eq!(
            nav.flat_list.len(),
            2,
            "children must be gone after collapse"
        );
        assert!(
            nav.selected < nav.flat_list.len(),
            "selected must be re-clamped to the shrunk list"
        );
        assert!(
            nav.get_selected_node().is_some(),
            "get_selected_node must not return None after collapse"
        );
    }

    #[test]
    #[cfg(unix)]
    fn go_to_parent_does_not_navigate_into_unreadable_directory() {
        use std::os::unix::fs::PermissionsExt;

        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        let child = root.join("child");
        std::fs::create_dir(&child).unwrap();

        // Strip read+execute from root so it cannot be listed as a parent.
        let original_perms = std::fs::metadata(&root).unwrap().permissions();
        std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o000)).unwrap();

        let mut nav = make_nav(child.clone());
        let result = nav.go_to_parent(false);

        // Restore permissions immediately so TempDir cleanup doesn't fail.
        std::fs::set_permissions(&root, original_perms).unwrap();

        result.unwrap();
        assert_eq!(
            nav.root.borrow().path,
            child,
            "root must not change when parent is unreadable"
        );
        assert_eq!(
            nav.history.len(),
            0,
            "history must not grow when navigation fails"
        );
        assert!(
            nav.nav_error.is_some(),
            "nav_error must be set when go_to_parent fails"
        );
    }
}