rusdu 0.1.2

Rust rewrite of ncdu — NCurses Disk Usage analyzer
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
mod actions;
mod browser;
mod theme;

use crate::cli::Args;
use crate::tree::{NodeId, TreeArena};
use anyhow::Result;
use crossterm::event::{
    self, Event, KeyCode, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DriveInfo {
    pub name: String,
    pub mount_point: std::path::PathBuf,
    pub total_space: u64,
    pub available_space: u64,
}

pub struct AppState {
    pub arena: TreeArena,
    pub current_dir: NodeId,
    pub selected_idx: usize,
    pub scroll_offset: usize,
    pub history: Vec<(NodeId, usize)>, // Stack of (directory_node_id, selected_index)
    pub args: Args,

    // UI state toggles
    pub apparent_size: bool,
    pub si: bool,
    pub show_itemcount: bool,
    pub show_mtime: bool,
    pub show_hidden: bool,
    pub group_dirs_first: bool,
    pub graph_mode: GraphMode, // cycle: both, percent, graph, none
    pub shared_column_mode: SharedColumnMode, // off, shared, unique

    // Active dialogs
    pub active_dialog: Dialog,
    pub show_icons: bool,
    pub refreshing_rx: Option<std::sync::mpsc::Receiver<Result<TreeArena, String>>>,
    pub visible_children: Vec<NodeId>,

    // New features state
    pub custom_actions: std::collections::HashMap<char, String>,
    pub filter_query: Option<String>,
    pub show_preview: bool,
    pub fs_modified: bool,
    pub watcher: Option<notify::RecommendedWatcher>,
    pub watcher_rx: Option<std::sync::mpsc::Receiver<notify::Result<notify::Event>>>,
}

impl AppState {
    pub fn update_visible_children(&mut self) {
        self.visible_children = get_visible_children(self, self.current_dir);
    }

    pub fn setup_watcher(&mut self) {
        self.watcher = None;
        self.watcher_rx = None;
        self.fs_modified = false;

        let current_path = get_node_path(&self.arena, self.current_dir);
        if !current_path.exists() {
            return;
        }

        let (tx, rx) = std::sync::mpsc::channel();
        use notify::Watcher;
        let watcher_res = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
            let _ = tx.send(res);
        });

        if let Ok(mut w) = watcher_res {
            if w.watch(&current_path, notify::RecursiveMode::NonRecursive)
                .is_ok()
            {
                self.watcher = Some(w);
                self.watcher_rx = Some(rx);
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphMode {
    Both,
    Percent,
    Graph,
    None,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SharedColumnMode {
    Off,
    Shared,
    Unique,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dialog {
    None,
    Help(HelpPage),
    Info(NodeId),
    ConfirmDelete(NodeId),
    ConfirmQuit,
    FilterInput(String),
    FuzzySearch {
        query: String,
        results: Vec<(NodeId, String)>,
        selected_idx: usize,
    },
    DriveSelector {
        drives: Vec<DriveInfo>,
        selected_idx: usize,
    },
    ExtensionAnalytics {
        stats: Vec<(String, u64)>,
        selected_idx: usize,
        scroll_offset: usize,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HelpPage {
    Keys,
    Format,
    About,
}

pub fn run_tui(arena: TreeArena, args: Args) -> Result<()> {
    // Set up raw mode and alternate screen
    crossterm::terminal::enable_raw_mode()?;
    let mut stdout = std::io::stdout();
    crossterm::execute!(
        stdout,
        crossterm::terminal::EnterAlternateScreen,
        crossterm::cursor::Hide,
        crossterm::event::EnableMouseCapture
    )?;

    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut state = AppState {
        current_dir: arena.root,
        arena,
        selected_idx: 0,
        scroll_offset: 0,
        history: Vec::new(),
        apparent_size: args.apparent_size,
        si: args.si,
        show_itemcount: args.show_itemcount,
        show_mtime: args.show_mtime,
        show_hidden: args.show_hidden,
        group_dirs_first: args.group_directories_first,
        graph_mode: match (args.show_graph, args.show_percent) {
            (true, true) => GraphMode::Both,
            (false, true) => GraphMode::Percent,
            (true, false) => GraphMode::Graph,
            (false, false) => GraphMode::None,
        },
        shared_column_mode: match args.shared_column.as_str() {
            "off" => SharedColumnMode::Off,
            "unique" => SharedColumnMode::Unique,
            _ => SharedColumnMode::Shared,
        },
        active_dialog: Dialog::None,
        show_icons: args.icons,
        refreshing_rx: None,
        args,
        visible_children: Vec::new(),
        custom_actions: actions::load_custom_actions(),
        filter_query: None,
        show_preview: false,
        fs_modified: false,
        watcher: None,
        watcher_rx: None,
    };
    state.update_visible_children();
    state.setup_watcher();

    // Render loop
    loop {
        // Check filesystem watcher channel
        if let Some(ref rx) = state.watcher_rx {
            if let Ok(Ok(event)) = rx.try_recv() {
                if event.kind.is_modify() || event.kind.is_create() || event.kind.is_remove() {
                    state.fs_modified = true;
                }
            }
        }

        // Check background refresh channel
        if let Some(ref rx) = state.refreshing_rx {
            if let Ok(res) = rx.try_recv() {
                if let Ok(new_arena) = res {
                    state.arena.get_mut(state.current_dir).children =
                        new_arena.nodes[new_arena.root.0].children.clone();
                    if state.current_dir == state.arena.root {
                        state.arena = new_arena;
                        state.selected_idx = 0;
                        state.scroll_offset = 0;
                    }
                }
                state.refreshing_rx = None;
                state.update_visible_children();
                state.setup_watcher();
            }
        }

        terminal.draw(|f| browser::draw(f, &mut state))?;

        if event::poll(std::time::Duration::from_millis(100))? {
            let ev = event::read()?;
            if state.refreshing_rx.is_some() {
                continue;
            }
            match ev {
                Event::Key(key) => {
                    // Ignore key releases
                    if key.kind == event::KeyEventKind::Release {
                        continue;
                    }

                    // Global abort/exit checks
                    if key.modifiers.contains(KeyModifiers::CONTROL)
                        && key.code == KeyCode::Char('c')
                    {
                        break;
                    }

                    if state.active_dialog != Dialog::None {
                        if handle_dialog_keys(key.code, &mut state)? {
                            continue;
                        }
                    } else {
                        if handle_browser_keys(key, &mut state)? {
                            break;
                        }
                    }
                }
                Event::Mouse(mouse) => {
                    handle_mouse_event(mouse, &mut state)?;
                }
                _ => {}
            }
        }
    }

    // Restore terminal
    crossterm::terminal::disable_raw_mode()?;
    crossterm::execute!(
        terminal.backend_mut(),
        crossterm::terminal::LeaveAlternateScreen,
        crossterm::cursor::Show,
        crossterm::event::DisableMouseCapture
    )?;

    Ok(())
}

fn handle_mouse_event(mouse: MouseEvent, state: &mut AppState) -> Result<()> {
    if state.active_dialog != Dialog::None {
        return Ok(());
    }

    let visible_children = state.visible_children.clone();

    match mouse.kind {
        MouseEventKind::ScrollUp => {
            if state.selected_idx > 0 {
                state.selected_idx -= 1;
            }
        }
        MouseEventKind::ScrollDown => {
            if !visible_children.is_empty() && state.selected_idx < visible_children.len() - 1 {
                state.selected_idx += 1;
            }
        }
        MouseEventKind::Down(MouseButton::Left) => {
            let list_row = mouse.row as usize;
            if list_row >= 1 {
                let clicked_idx = state.scroll_offset + (list_row - 1);
                if clicked_idx < visible_children.len() {
                    if state.selected_idx == clicked_idx {
                        let selected_id = visible_children[state.selected_idx];
                        if state.arena.get(selected_id).is_dir() {
                            state.history.push((state.current_dir, state.selected_idx));
                            state.current_dir = selected_id;
                            state.selected_idx = 0;
                            state.scroll_offset = 0;
                            state.update_visible_children();
                        }
                    } else {
                        state.selected_idx = clicked_idx;
                    }
                }
            }
        }
        _ => {}
    }
    Ok(())
}

fn handle_dialog_keys(code: KeyCode, state: &mut AppState) -> Result<bool> {
    match &state.active_dialog {
        Dialog::Help(page) => match code {
            KeyCode::Char('q') | KeyCode::Esc | KeyCode::Char('?') => {
                state.active_dialog = Dialog::None;
            }
            KeyCode::Char('1') => {
                state.active_dialog = Dialog::Help(HelpPage::Keys);
            }
            KeyCode::Char('2') => {
                state.active_dialog = Dialog::Help(HelpPage::Format);
            }
            KeyCode::Char('3') => {
                state.active_dialog = Dialog::Help(HelpPage::About);
            }
            KeyCode::Left | KeyCode::Char('h') => {
                let prev_page = match page {
                    HelpPage::Keys => HelpPage::About,
                    HelpPage::Format => HelpPage::Keys,
                    HelpPage::About => HelpPage::Format,
                };
                state.active_dialog = Dialog::Help(prev_page);
            }
            KeyCode::Right | KeyCode::Char('l') => {
                let next_page = match page {
                    HelpPage::Keys => HelpPage::Format,
                    HelpPage::Format => HelpPage::About,
                    HelpPage::About => HelpPage::Keys,
                };
                state.active_dialog = Dialog::Help(next_page);
            }
            _ => {}
        },
        Dialog::Info(_) => match code {
            KeyCode::Char('q') | KeyCode::Esc | KeyCode::Char('i') | KeyCode::Enter => {
                state.active_dialog = Dialog::None;
            }
            _ => {}
        },
        Dialog::ConfirmDelete(node_id) => {
            let node_id = *node_id;
            match code {
                KeyCode::Char('y') | KeyCode::Enter => {
                    // Perform deletion
                    let item_path = get_node_path(&state.arena, node_id);
                    let read_only = state.args.read_only >= 1;
                    if let Err(e) = crate::delete::delete_item(
                        &item_path,
                        state.args.delete_command.as_deref(),
                        read_only,
                    ) {
                        log::error!("Delete failed: {}", e);
                    } else {
                        // Delete successfully from memory
                        state.arena.delete_node(node_id);
                        // Recalculate sizes
                        crate::tree::stats::recalculate_stats(&mut state.arena);
                        state.update_visible_children();
                        // Reset cursor if out of bounds
                        let items = &state.visible_children;
                        if state.selected_idx >= items.len() && !items.is_empty() {
                            state.selected_idx = items.len() - 1;
                        }
                    }
                    state.active_dialog = Dialog::None;
                }
                KeyCode::Char('n') | KeyCode::Esc | KeyCode::Char('q') => {
                    state.active_dialog = Dialog::None;
                }
                _ => {}
            }
        }
        Dialog::ConfirmQuit => {
            match code {
                KeyCode::Char('y') | KeyCode::Enter => {
                    return Ok(false); // Signal exit loop
                }
                KeyCode::Char('n') | KeyCode::Esc | KeyCode::Char('q') => {
                    state.active_dialog = Dialog::None;
                }
                _ => {}
            }
        }
        Dialog::FilterInput(query) => {
            let mut q = query.clone();
            match code {
                KeyCode::Esc => {
                    state.filter_query = None;
                    state.active_dialog = Dialog::None;
                    state.update_visible_children();
                }
                KeyCode::Enter => {
                    if q.trim().is_empty() {
                        state.filter_query = None;
                    } else {
                        state.filter_query = Some(q);
                    }
                    state.active_dialog = Dialog::None;
                    state.update_visible_children();
                }
                KeyCode::Backspace => {
                    q.pop();
                    state.active_dialog = Dialog::FilterInput(q);
                }
                KeyCode::Char(c) => {
                    q.push(c);
                    state.active_dialog = Dialog::FilterInput(q);
                }
                _ => {}
            }
        }
        Dialog::FuzzySearch {
            query,
            results,
            selected_idx,
        } => {
            let mut q = query.clone();
            let mut res = results.clone();
            let mut sel = *selected_idx;
            match code {
                KeyCode::Esc => {
                    state.active_dialog = Dialog::None;
                }
                KeyCode::Enter => {
                    if sel < res.len() {
                        let target_id = res[sel].0;
                        state.active_dialog = Dialog::None;
                        jump_to_node(state, target_id);
                    } else {
                        state.active_dialog = Dialog::None;
                    }
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    if sel > 0 {
                        sel -= 1;
                        state.active_dialog = Dialog::FuzzySearch {
                            query: q,
                            results: res,
                            selected_idx: sel,
                        };
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    if !res.is_empty() && sel < res.len() - 1 {
                        sel += 1;
                        state.active_dialog = Dialog::FuzzySearch {
                            query: q,
                            results: res,
                            selected_idx: sel,
                        };
                    }
                }
                KeyCode::Backspace => {
                    q.pop();
                    let updated_results = update_fuzzy_results(&state.arena, &q);
                    state.active_dialog = Dialog::FuzzySearch {
                        query: q,
                        results: updated_results,
                        selected_idx: 0,
                    };
                }
                KeyCode::Char(c) => {
                    q.push(c);
                    let updated_results = update_fuzzy_results(&state.arena, &q);
                    state.active_dialog = Dialog::FuzzySearch {
                        query: q,
                        results: updated_results,
                        selected_idx: 0,
                    };
                }
                _ => {}
            }
        }
        Dialog::DriveSelector {
            drives,
            selected_idx,
        } => {
            let mut sel = *selected_idx;
            match code {
                KeyCode::Esc | KeyCode::Char('q') => {
                    state.active_dialog = Dialog::None;
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    if sel > 0 {
                        sel -= 1;
                        state.active_dialog = Dialog::DriveSelector {
                            drives: drives.clone(),
                            selected_idx: sel,
                        };
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    if !drives.is_empty() && sel < drives.len() - 1 {
                        sel += 1;
                        state.active_dialog = Dialog::DriveSelector {
                            drives: drives.clone(),
                            selected_idx: sel,
                        };
                    }
                }
                KeyCode::Enter => {
                    if sel < drives.len() {
                        let path = drives[sel].mount_point.clone();
                        state.active_dialog = Dialog::None;
                        state.history.clear();
                        state.selected_idx = 0;
                        state.scroll_offset = 0;

                        // Spawn background rescan of this drive
                        let opts = crate::scan::ScanOptions {
                            one_file_system: state.args.one_file_system,
                            exclude_patterns: state.args.exclude.clone(),
                            exclude_from: state.args.exclude_from.clone(),
                            exclude_caches: state.args.exclude_caches,
                            exclude_kernfs: state.args.exclude_kernfs,
                            follow_symlinks: state.args.follow_symlinks,
                            threads: state.args.threads.unwrap_or(1),
                            extended: state.args.extended,
                        };
                        let (tx, rx) = std::sync::mpsc::channel();
                        std::thread::spawn(move || {
                            let res = crate::scan::scan_directory(
                                &path,
                                opts,
                                crate::scan::ProgressMode::Silent,
                            )
                            .map_err(|e| e.to_string());
                            let _ = tx.send(res);
                        });
                        state.refreshing_rx = Some(rx);
                    }
                }
                _ => {}
            }
        }
        Dialog::ExtensionAnalytics {
            stats,
            selected_idx,
            scroll_offset,
        } => {
            let mut sel = *selected_idx;
            let mut scroll = *scroll_offset;
            match code {
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Enter => {
                    state.active_dialog = Dialog::None;
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    if sel > 0 {
                        sel -= 1;
                        if sel < scroll {
                            scroll = sel;
                        }
                        state.active_dialog = Dialog::ExtensionAnalytics {
                            stats: stats.clone(),
                            selected_idx: sel,
                            scroll_offset: scroll,
                        };
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    if !stats.is_empty() && sel < stats.len() - 1 {
                        sel += 1;
                        if sel >= scroll + 10 {
                            scroll = sel - 10 + 1;
                        }
                        state.active_dialog = Dialog::ExtensionAnalytics {
                            stats: stats.clone(),
                            selected_idx: sel,
                            scroll_offset: scroll,
                        };
                    }
                }
                _ => {}
            }
        }
        Dialog::None => {}
    }
    Ok(true)
}

fn handle_browser_keys(key: event::KeyEvent, state: &mut AppState) -> Result<bool> {
    let visible_children = state.visible_children.clone();

    // Check Ctrl+F or 'f' for global fuzzy search
    let is_ctrl_f = key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('f');
    let is_f = key.code == KeyCode::Char('f');
    if is_ctrl_f || is_f {
        state.active_dialog = Dialog::FuzzySearch {
            query: String::new(),
            results: Vec::new(),
            selected_idx: 0,
        };
        return Ok(false);
    }

    match key.code {
        // Navigation keys
        KeyCode::Char('q') => {
            if state.args.confirm_quit {
                state.active_dialog = Dialog::ConfirmQuit;
            } else {
                return Ok(true); // Signal exit loop
            }
        }
        KeyCode::Up | KeyCode::Char('k') => {
            if state.selected_idx > 0 {
                state.selected_idx -= 1;
            }
        }
        KeyCode::Down | KeyCode::Char('j') => {
            if !visible_children.is_empty() && state.selected_idx < visible_children.len() - 1 {
                state.selected_idx += 1;
            }
        }
        KeyCode::PageUp => {
            if state.selected_idx > 10 {
                state.selected_idx -= 10;
            } else {
                state.selected_idx = 0;
            }
        }
        KeyCode::PageDown => {
            if !visible_children.is_empty() {
                if state.selected_idx + 10 < visible_children.len() {
                    state.selected_idx += 10;
                } else {
                    state.selected_idx = visible_children.len() - 1;
                }
            }
        }
        KeyCode::Home => {
            state.selected_idx = 0;
        }
        KeyCode::End => {
            if !visible_children.is_empty() {
                state.selected_idx = visible_children.len() - 1;
            }
        }
        KeyCode::Right | KeyCode::Char('l') | KeyCode::Enter => {
            if !visible_children.is_empty() {
                let selected_id = visible_children[state.selected_idx];
                if state.arena.get(selected_id).is_dir() {
                    state.history.push((state.current_dir, state.selected_idx));
                    state.current_dir = selected_id;
                    state.selected_idx = 0;
                    state.scroll_offset = 0;
                    state.update_visible_children();
                    state.setup_watcher();
                }
            }
        }
        KeyCode::Left | KeyCode::Char('h') | KeyCode::Backspace => {
            if let Some((parent_id, prev_idx)) = state.history.pop() {
                state.current_dir = parent_id;
                state.selected_idx = prev_idx;
                state.scroll_offset = 0;
                state.update_visible_children();
                state.setup_watcher();
            }
        }

        // Live filter
        KeyCode::Char('/') => {
            state.active_dialog = Dialog::FilterInput(String::new());
        }

        // Preview panel toggling
        KeyCode::Tab | KeyCode::Char('p') => {
            state.show_preview = !state.show_preview;
        }

        // Disk/Drive Selector
        KeyCode::Char('v') => {
            use sysinfo::Disks;
            let disks = Disks::new_with_refreshed_list();
            let mut drives = Vec::new();
            for disk in &disks {
                let name = disk.name().to_string_lossy().into_owned();
                let mount_point = disk.mount_point().to_path_buf();
                let total_space = disk.total_space();
                let available_space = disk.available_space();
                drives.push(DriveInfo {
                    name: if name.is_empty() {
                        "Local Disk".to_string()
                    } else {
                        name
                    },
                    mount_point,
                    total_space,
                    available_space,
                });
            }
            state.active_dialog = Dialog::DriveSelector {
                drives,
                selected_idx: 0,
            };
        }

        // Extension analytics
        KeyCode::Char('E') => {
            let stats = calculate_extension_stats(&state.arena, state.current_dir);
            state.active_dialog = Dialog::ExtensionAnalytics {
                stats,
                selected_idx: 0,
                scroll_offset: 0,
            };
        }

        // Sorting toggles
        KeyCode::Char('n') => {
            toggle_sort(state, "name");
            state.update_visible_children();
        }
        KeyCode::Char('s') => {
            toggle_sort(state, "disk-usage");
            state.update_visible_children();
        }
        KeyCode::Char('C') => {
            toggle_sort(state, "itemcount");
            state.update_visible_children();
        }
        KeyCode::Char('M') => {
            if state.args.extended {
                toggle_sort(state, "mtime");
                state.update_visible_children();
            }
        }
        KeyCode::Char('t') => {
            state.group_dirs_first = !state.group_dirs_first;
            state.update_visible_children();
        }

        // UI Toggles
        KeyCode::Char('a') => {
            state.apparent_size = !state.apparent_size;
            state.update_visible_children();
        }
        KeyCode::Char('g') => {
            state.graph_mode = match state.graph_mode {
                GraphMode::Both => GraphMode::Percent,
                GraphMode::Percent => GraphMode::Graph,
                GraphMode::Graph => GraphMode::None,
                GraphMode::None => GraphMode::Both,
            };
        }
        KeyCode::Char('u') => {
            state.shared_column_mode = match state.shared_column_mode {
                SharedColumnMode::Off => SharedColumnMode::Shared,
                SharedColumnMode::Shared => SharedColumnMode::Unique,
                SharedColumnMode::Unique => SharedColumnMode::Off,
            };
        }
        KeyCode::Char('c') => {
            state.show_itemcount = !state.show_itemcount;
        }
        KeyCode::Char('m') => {
            if state.args.extended {
                state.show_mtime = !state.show_mtime;
            }
        }
        KeyCode::Char('e') => {
            state.show_hidden = !state.show_hidden;
            state.update_visible_children();
        }

        // Dialogs & Actions
        KeyCode::Char('?') => {
            state.active_dialog = Dialog::Help(HelpPage::Keys);
        }
        KeyCode::Char('i') => {
            if !visible_children.is_empty() {
                state.active_dialog = Dialog::Info(visible_children[state.selected_idx]);
            }
        }
        KeyCode::Char('d') => {
            if !visible_children.is_empty() {
                let selected_id = visible_children[state.selected_idx];
                if state.args.confirm_delete {
                    state.active_dialog = Dialog::ConfirmDelete(selected_id);
                } else {
                    let item_path = get_node_path(&state.arena, selected_id);
                    let read_only = state.args.read_only >= 1;
                    let _ = crate::delete::delete_item(
                        &item_path,
                        state.args.delete_command.as_deref(),
                        read_only,
                    );
                    state.arena.delete_node(selected_id);
                    crate::tree::stats::recalculate_stats(&mut state.arena);
                    state.update_visible_children();
                }
            }
        }
        KeyCode::Char('b') => {
            let current_path = get_node_path(&state.arena, state.current_dir);
            let read_only = state.args.read_only >= 2;
            let _ = crate::shell::spawn_shell(&current_path, read_only);
        }
        KeyCode::Char('r') => {
            if state.args.read_only < 1 && state.refreshing_rx.is_none() {
                let current_path = get_node_path(&state.arena, state.current_dir);
                let opts = crate::scan::ScanOptions {
                    one_file_system: state.args.one_file_system,
                    exclude_patterns: state.args.exclude.clone(),
                    exclude_from: state.args.exclude_from.clone(),
                    exclude_caches: state.args.exclude_caches,
                    exclude_kernfs: state.args.exclude_kernfs,
                    follow_symlinks: state.args.follow_symlinks,
                    threads: state.args.threads.unwrap_or(1),
                    extended: state.args.extended,
                };
                let (tx, rx) = std::sync::mpsc::channel();
                std::thread::spawn(move || {
                    let res = crate::scan::scan_directory(
                        &current_path,
                        opts,
                        crate::scan::ProgressMode::Silent,
                    )
                    .map_err(|e| e.to_string());
                    let _ = tx.send(res);
                });
                state.refreshing_rx = Some(rx);
            }
        }
        KeyCode::Char(c) => {
            if let Some(cmd) = state.custom_actions.get(&c).cloned() {
                if !visible_children.is_empty() {
                    let selected_id = visible_children[state.selected_idx];
                    let selected_path = get_node_path(&state.arena, selected_id);
                    let _ = actions::execute_custom_action(&cmd, &selected_path);
                    state.update_visible_children();
                    state.setup_watcher();
                }
            }
        }
        _ => {}
    }
    Ok(false)
}

fn toggle_sort(state: &mut AppState, col: &str) {
    if state.args.sort.starts_with(col) {
        if state.args.sort.ends_with("-desc") {
            state.args.sort = format!("{}-asc", col);
        } else {
            state.args.sort = format!("{}-desc", col);
        }
    } else {
        state.args.sort = format!("{}-desc", col);
    }
}

pub fn get_visible_children(state: &AppState, dir_id: NodeId) -> Vec<NodeId> {
    let dir = state.arena.get(dir_id);
    let mut children = dir.children.clone();

    // Filter hidden/excluded if show_hidden is false
    if !state.show_hidden {
        children.retain(|&id| {
            let child = state.arena.get(id);
            !child.flags.contains(crate::tree::EntryFlags::EXCLUDED)
        });
    }

    // Filter by live query if active
    if let Some(ref query) = state.filter_query {
        let query_lower = query.to_lowercase();
        children.retain(|&id| {
            let child = state.arena.get(id);
            child.name.to_lowercase().contains(&query_lower)
        });
    }

    // Sort the list based on state.args.sort and state.group_dirs_first
    children.sort_by(|&a_id, &b_id| {
        let a = state.arena.get(a_id);
        let b = state.arena.get(b_id);

        if state.group_dirs_first {
            if a.is_dir() && !b.is_dir() {
                return std::cmp::Ordering::Less;
            }
            if !a.is_dir() && b.is_dir() {
                return std::cmp::Ordering::Greater;
            }
        }

        let is_desc = state.args.sort.ends_with("-desc");
        let sort_col = state.args.sort.split('-').next().unwrap_or("disk-usage");

        let ord = match sort_col {
            "name" => {
                if state.args.enable_natsort {
                    crate::natsort::natural_compare(&a.name, &b.name)
                } else {
                    a.name.cmp(&b.name)
                }
            }
            "apparent-size" => {
                let a_sz = if a.is_dir() {
                    a.stats.total_asize
                } else {
                    a.asize
                };
                let b_sz = if b.is_dir() {
                    b.stats.total_asize
                } else {
                    b.asize
                };
                a_sz.cmp(&b_sz)
            }
            "itemcount" => a.stats.item_count.cmp(&b.stats.item_count),
            "mtime" => {
                let a_time = a.extended.as_ref().map(|e| e.mtime).unwrap_or(0);
                let b_time = b.extended.as_ref().map(|e| e.mtime).unwrap_or(0);
                a_time.cmp(&b_time)
            }
            _ => {
                // Default: disk-usage
                let a_sz = if a.is_dir() {
                    a.stats.total_dsize
                } else {
                    a.dsize
                };
                let b_sz = if b.is_dir() {
                    b.stats.total_dsize
                } else {
                    b.dsize
                };
                a_sz.cmp(&b_sz)
            }
        };

        if is_desc {
            ord.reverse()
        } else {
            ord
        }
    });

    children
}

pub fn get_node_path(arena: &TreeArena, node_id: NodeId) -> std::path::PathBuf {
    let mut path_components = Vec::new();
    let mut curr = node_id;

    loop {
        let node = arena.get(curr);
        path_components.push(node.name.to_string());
        if let Some(p) = node.parent {
            curr = p;
        } else {
            break;
        }
    }

    path_components.reverse();

    // Join path components
    let mut path = std::path::PathBuf::new();
    for comp in path_components {
        path.push(comp);
    }
    path
}

fn fuzzy_match(text: &str, query: &str) -> bool {
    let mut text_chars = text.chars().flat_map(|c| c.to_lowercase());
    for q_char in query.chars().flat_map(|c| c.to_lowercase()) {
        if text_chars
            .by_ref()
            .find(|&t_char| t_char == q_char)
            .is_none()
        {
            return false;
        }
    }
    true
}

fn update_fuzzy_results(arena: &TreeArena, query: &str) -> Vec<(NodeId, String)> {
    if query.trim().is_empty() {
        return Vec::new();
    }
    let mut results = Vec::new();
    let mut stack = vec![(arena.root, String::new())];
    while let Some((node_id, parent_path)) = stack.pop() {
        let node = arena.get(node_id);

        let current_path = if parent_path.is_empty() {
            node.name.to_string()
        } else {
            format!("{}/{}", parent_path, node.name)
        };

        if fuzzy_match(&node.name, query) || fuzzy_match(&current_path, query) {
            results.push((node_id, current_path.clone()));
        }

        if node.is_dir() {
            for &child_id in &node.children {
                stack.push((child_id, current_path.clone()));
            }
        }
    }
    results.truncate(50);
    results
}

fn jump_to_node(state: &mut AppState, target_id: NodeId) {
    let mut path_nodes = Vec::new();
    let mut curr = target_id;

    loop {
        path_nodes.push(curr);
        if let Some(parent) = state.arena.get(curr).parent {
            curr = parent;
        } else {
            break;
        }
    }
    path_nodes.reverse();

    state.history.clear();
    state.current_dir = state.arena.root;
    state.selected_idx = 0;
    state.scroll_offset = 0;

    let (target_dir, focus_id) = if state.arena.get(target_id).is_dir() {
        (target_id, None)
    } else {
        let parent = state
            .arena
            .get(target_id)
            .parent
            .unwrap_or(state.arena.root);
        (parent, Some(target_id))
    };

    let mut curr_dir = state.arena.root;
    for &next_id in &path_nodes {
        if next_id == state.arena.root {
            continue;
        }
        if next_id == target_dir && focus_id.is_some() {
            break;
        }
        if state.arena.get(curr_dir).is_dir() {
            state.current_dir = curr_dir;
            state.update_visible_children();
            let children = state.visible_children.clone();
            if let Some(idx) = children.iter().position(|&id| id == next_id) {
                state.history.push((curr_dir, idx));
            }
            curr_dir = next_id;
        }
    }

    state.current_dir = target_dir;
    state.update_visible_children();
    if let Some(fid) = focus_id {
        if let Some(idx) = state.visible_children.iter().position(|&id| id == fid) {
            state.selected_idx = idx;
        } else {
            state.selected_idx = 0;
        }
    } else {
        state.selected_idx = 0;
    }
    state.scroll_offset = 0;
    state.setup_watcher();
}

fn calculate_extension_stats(arena: &TreeArena, dir_id: NodeId) -> Vec<(String, u64)> {
    let mut ext_sizes = std::collections::HashMap::new();
    let mut stack = vec![dir_id];
    while let Some(node_id) = stack.pop() {
        let node = arena.get(node_id);
        if node.is_dir() {
            for &child_id in &node.children {
                stack.push(child_id);
            }
        } else {
            let ext = std::path::Path::new(&*node.name)
                .extension()
                .map(|e| e.to_string_lossy().to_lowercase())
                .unwrap_or_else(|| "no extension".to_string());
            *ext_sizes.entry(ext).or_insert(0) += node.dsize as u64;
        }
    }
    let mut list: Vec<(String, u64)> = ext_sizes.into_iter().collect();
    list.sort_by(|a, b| b.1.cmp(&a.1));
    list
}