tui-file-explorer 0.9.8

A self-contained, keyboard-driven file-browser widget for Ratatui
Documentation
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
//! # options — DualPane explorer with a live options sidebar
//!
//! Demonstrates how to build a settings panel alongside the file explorer,
//! with options grouped into bordered category cells.
//!
//! ## Groups
//!
//! ```text
//! ╭─ ⚙ Options ──────────────────────╮
//!   Shift + O close                  │
//! ╰───────────────────────────────────╯
//!   View
//! ╭───────────────────────────────────╮
//! │ h   hidden files      ○ off      │
//! │ w   single pane       ○ off      │
//! ╰───────────────────────────────────╯
//!   Sort
//! ╭───────────────────────────────────╮
//! │ s   sort mode         name       │
//! ╰───────────────────────────────────╯
//!   Theme
//! ╭───────────────────────────────────╮
//! │ t         cycle          Default │
//! │ Tab       active pane    left    │
//! ╰───────────────────────────────────╯
//! ```
//!
//! ## Usage
//!
//! ```bash
//! cargo run --example options
//! ```
//!
//! ## Key bindings
//!
//! | Key              | Action                              |
//! |------------------|-------------------------------------|
//! | `Shift + O`      | Toggle options panel                |
//! | `h`              | Toggle hidden files  (panel open)   |
//! | `s`              | Cycle sort mode      (panel open)   |
//! | `w`              | Toggle single pane   (panel open)   |
//! | `t`              | Cycle theme          (panel open)   |
//! | `Tab`            | Switch active pane                  |
//! | `↑` / `k`        | Move cursor up                      |
//! | `↓` / `j`        | Move cursor down                    |
//! | `Enter`          | Descend / select file               |
//! | `Backspace`      | Ascend                              |
//! | `Esc` / `q`      | Quit                                |
//!
//! On selection the chosen path is printed to stdout and the process exits 0.
//! On dismissal (`Esc` / `q`) the process exits 1.

use std::{
    io::{self, stdout},
    path::PathBuf,
    process,
};

use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Paragraph},
    Frame, Terminal,
};
use tui_file_explorer::{
    render_dual_pane_themed, DualPane, DualPaneActive, DualPaneOutcome, SortMode, Theme,
};

// ── Editor ────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq, Default)]
enum Editor {
    #[default]
    None,
    Helix,
    Neovim,
    Vim,
    Nano,
    Micro,
}

impl Editor {
    fn label(&self) -> &'static str {
        match self {
            Editor::None => "none",
            Editor::Helix => "helix",
            Editor::Neovim => "nvim",
            Editor::Vim => "vim",
            Editor::Nano => "nano",
            Editor::Micro => "micro",
        }
    }

    fn binary(&self) -> Option<&'static str> {
        match self {
            Editor::None => None,
            Editor::Helix => Some("hx"),
            Editor::Neovim => Some("nvim"),
            Editor::Vim => Some("vim"),
            Editor::Nano => Some("nano"),
            Editor::Micro => Some("micro"),
        }
    }

    fn cycle(&self) -> Editor {
        match self {
            Editor::None => Editor::Helix,
            Editor::Helix => Editor::Neovim,
            Editor::Neovim => Editor::Vim,
            Editor::Vim => Editor::Nano,
            Editor::Nano => Editor::Micro,
            Editor::Micro => Editor::None,
        }
    }
}

// ── App state ─────────────────────────────────────────────────────────────────

struct App {
    dual: DualPane,
    themes: Vec<(&'static str, &'static str, Theme)>,
    theme_idx: usize,
    show_hidden: bool,
    sort_mode: SortMode,
    single_pane: bool,
    show_options: bool,
    editor: Editor,
    status: String,
}

impl App {
    fn new() -> Self {
        let start = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
        let themes = Theme::all_presets();
        Self {
            dual: DualPane::builder(start).build(),
            themes,
            theme_idx: 0,
            show_hidden: false,
            sort_mode: SortMode::Name,
            single_pane: false,
            show_options: true,
            editor: Editor::default(),
            status: String::new(),
        }
    }

    fn theme(&self) -> &Theme {
        &self.themes[self.theme_idx].2
    }

    fn theme_name(&self) -> &'static str {
        self.themes[self.theme_idx].0
    }

    fn cycle_theme(&mut self) {
        self.theme_idx = (self.theme_idx + 1) % self.themes.len();
    }

    fn cycle_sort(&mut self) {
        self.sort_mode = self.sort_mode.next();
        self.dual.left.set_sort_mode(self.sort_mode);
        self.dual.right.set_sort_mode(self.sort_mode);
    }

    fn toggle_hidden(&mut self) {
        self.show_hidden = !self.show_hidden;
        self.dual.left.set_show_hidden(self.show_hidden);
        self.dual.right.set_show_hidden(self.show_hidden);
    }

    fn toggle_single_pane(&mut self) {
        self.single_pane = !self.single_pane;
        self.dual.single_pane = self.single_pane;
    }

    fn cycle_editor(&mut self) {
        self.editor = self.editor.cycle();
    }

    fn active_label(&self) -> &'static str {
        match self.dual.active_side {
            DualPaneActive::Left => "left",
            DualPaneActive::Right => "right",
        }
    }
}

// ── Entry point ───────────────────────────────────────────────────────────────

fn main() {
    match run() {
        Ok(Some(path)) => {
            println!("{}", path.display());
            process::exit(0);
        }
        Ok(None) => process::exit(1),
        Err(e) => {
            eprintln!("error: {e}");
            process::exit(2);
        }
    }
}

fn run() -> io::Result<Option<PathBuf>> {
    let mut app = App::new();

    enable_raw_mode()?;
    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let result = event_loop(&mut terminal, &mut app);

    let _ = disable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture,
    );
    let _ = terminal.show_cursor();

    result
}

// ── Event loop ────────────────────────────────────────────────────────────────

fn event_loop(
    terminal: &mut Terminal<CrosstermBackend<std::io::Stdout>>,
    app: &mut App,
) -> io::Result<Option<PathBuf>> {
    loop {
        terminal.draw(|frame| draw(frame, app))?;

        let Event::Key(key) = event::read()? else {
            continue;
        };

        if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
            return Ok(None);
        }

        // Shift + O — toggle options panel (always active).
        if key.code == KeyCode::Char('O') && key.modifiers.is_empty() {
            app.show_options = !app.show_options;
            continue;
        }

        // Keys that only fire while the options panel is visible.
        if app.show_options {
            match key.code {
                KeyCode::Char('h') if key.modifiers.is_empty() => {
                    app.toggle_hidden();
                    continue;
                }
                KeyCode::Char('s') if key.modifiers.is_empty() => {
                    app.cycle_sort();
                    continue;
                }
                KeyCode::Char('w') if key.modifiers.is_empty() => {
                    app.toggle_single_pane();
                    continue;
                }
                KeyCode::Char('t') if key.modifiers.is_empty() => {
                    app.cycle_theme();
                    continue;
                }
                KeyCode::Char('e') if key.modifiers.is_empty() => {
                    app.cycle_editor();
                    continue;
                }
                _ => {}
            }
        }

        // e when panel is closed — open current file in configured editor.
        if key.code == KeyCode::Char('e') && key.modifiers.is_empty() && !app.show_options {
            if let Some(binary) = app.editor.binary() {
                let active = match app.dual.active_side {
                    DualPaneActive::Left => &app.dual.left,
                    DualPaneActive::Right => &app.dual.right,
                };
                if let Some(entry) = active.current_entry() {
                    if !entry.path.is_dir() {
                        let path = entry.path.clone();
                        open_in_editor(terminal, binary, &path)?;
                        app.dual.left.reload();
                        app.dual.right.reload();
                        let fname = path
                            .file_name()
                            .unwrap_or_default()
                            .to_string_lossy()
                            .into_owned();
                        app.status = format!("returned from {}{fname}", app.editor.label());
                        continue;
                    }
                }
            }
            // No editor configured — tell the user how to set one.
            app.status = "No editor set — open Options (O) and press e to pick one".into();
            continue;
        }

        match app.dual.handle_key(key) {
            DualPaneOutcome::Selected(path) => {
                // If a file (not a dir) is selected and an editor is set,
                // open it instead of exiting.
                if !path.is_dir() {
                    if let Some(binary) = app.editor.binary() {
                        open_in_editor(terminal, binary, &path)?;
                        app.dual.left.reload();
                        app.dual.right.reload();
                        let fname = path
                            .file_name()
                            .unwrap_or_default()
                            .to_string_lossy()
                            .into_owned();
                        app.status = format!("returned from {}{fname}", app.editor.label());
                        continue;
                    }
                    // No editor configured — stay in TUI and tell the user.
                    app.status = "No editor set — open Options (O) and press e to pick one".into();
                    continue;
                }
                return Ok(Some(path));
            }
            DualPaneOutcome::Dismissed => return Ok(None),
            DualPaneOutcome::MkdirCreated(path) => {
                let name = path
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .into_owned();
                app.status = format!("📂 Created folder '{name}'");
            }
            DualPaneOutcome::TouchCreated(path) => {
                let name = path
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .into_owned();
                app.status = format!("📄 Created file '{name}'");
            }
            DualPaneOutcome::RenameCompleted(path) => {
                let name = path
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .into_owned();
                app.status = format!("✏️  Renamed to '{name}'");
            }
            DualPaneOutcome::Pending | DualPaneOutcome::Unhandled => {}
        }
    }
}

/// Tear down the TUI, run `binary path`, then restore the TUI.
fn open_in_editor(
    terminal: &mut Terminal<CrosstermBackend<std::io::Stdout>>,
    binary: &str,
    path: &std::path::Path,
) -> io::Result<()> {
    use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
    use crossterm::execute;
    use crossterm::terminal::{
        disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
    };

    let _ = disable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    );

    let _status = {
        #[cfg(unix)]
        {
            let tty = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .open("/dev/tty");
            let mut cmd = std::process::Command::new(binary);
            cmd.arg(path);
            if let Ok(tty_file) = tty {
                use std::os::unix::io::{FromRawFd, IntoRawFd};
                let tty_fd = tty_file.into_raw_fd();
                unsafe {
                    let stdin_tty = std::fs::File::from_raw_fd(libc::dup(tty_fd));
                    let stdout_tty = std::fs::File::from_raw_fd(libc::dup(tty_fd));
                    let stderr_tty = std::fs::File::from_raw_fd(tty_fd);
                    cmd.stdin(stdin_tty).stdout(stdout_tty).stderr(stderr_tty);
                }
            }
            cmd.status()
        }
        #[cfg(not(unix))]
        {
            std::process::Command::new(binary).arg(path).status()
        }
    };

    let _ = enable_raw_mode();
    let _ = execute!(
        terminal.backend_mut(),
        EnterAlternateScreen,
        EnableMouseCapture
    );
    let _ = terminal.clear();
    Ok(())
}

// ── Drawing ───────────────────────────────────────────────────────────────────

fn draw(frame: &mut Frame, app: &mut App) {
    let theme = app.theme().clone();
    let area = frame.area();

    // Vertical split: main area (fill) | status bar (3 rows) when a status exists.
    let (main_area, status_area) = if app.status.is_empty() {
        (area, None)
    } else {
        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(0), Constraint::Length(3)])
            .split(area);
        (rows[0], Some(rows[1]))
    };

    let chunks = if app.show_options {
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Min(0), Constraint::Length(42)])
            .split(main_area)
    } else {
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Min(0)])
            .split(main_area)
    };

    render_dual_pane_themed(&mut app.dual, frame, chunks[0], &theme);

    if app.show_options {
        render_options(frame, chunks[1], app, &theme);
    }

    if let Some(slot) = status_area {
        let status_para = Paragraph::new(Span::styled(
            format!(" {}", app.status),
            Style::default().fg(theme.success),
        ))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme.dim)),
        );
        frame.render_widget(status_para, slot);
    }
}

// ── Options panel ─────────────────────────────────────────────────────────────

fn render_options(frame: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    let on_style = Style::default()
        .fg(theme.success)
        .add_modifier(Modifier::BOLD);
    let off_style = Style::default().fg(theme.dim);
    let key_style = Style::default()
        .fg(theme.accent)
        .add_modifier(Modifier::BOLD);
    let label_style = Style::default().fg(theme.fg);
    let dim_style = Style::default().fg(theme.dim);
    let title_style = Style::default()
        .fg(theme.brand)
        .add_modifier(Modifier::BOLD);

    // Slots (top → bottom):
    //  [0]  hints header          2 rows  (top border: title, bottom border: o close)
    //  [1]  gap                   1 row
    //  [2]  "View" title          1 row
    //  [3]  View group cell       5 rows  (h + w + Tab, three inner rows)
    //  [4]  gap                   1 row
    //  [5]  "Sort" title          1 row
    //  [6]  Sort group cell       3 rows  (s, one inner row)
    //  [7]  gap                   1 row
    //  [8]  "Theme" title         1 row
    //  [9]  Theme group cell      3 rows  (t, one inner row)
    //  [10] gap                   1 row
    //  [11] "Editor" title        1 row
    //  [12] Editor group cell     3 rows  (e, one inner row)
    //  [13] slack
    let slots = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(2), // [0] hints header (border-only, no body)
            Constraint::Length(1), // [1] gap
            Constraint::Length(1), // [2] "View" title
            Constraint::Length(5), // [3] View group  (border + 3 rows + border)
            Constraint::Length(1), // [4] gap
            Constraint::Length(1), // [5] "Sort" title
            Constraint::Length(3), // [6] Sort group  (border + 1 row + border)
            Constraint::Length(1), // [7] gap
            Constraint::Length(1), // [8] "Theme" title
            Constraint::Length(3), // [9] Theme group (border + 1 row + border)
            Constraint::Length(1), // [10] gap
            Constraint::Length(1), // [11] "Editor" title
            Constraint::Length(3), // [12] Editor group (border + 1 row + border)
            Constraint::Min(0),    // [13] slack
        ])
        .split(area);

    // ── Hints header ─────────────────────────────────────────────────────────
    // Title sits on the top border line; hints sit on the bottom border line.
    // No body row is needed — the block is just 2 rows (top + bottom borders).
    let header = Block::default()
        .title(Span::styled(" ⚙ Options ", title_style))
        .title_bottom(Line::from(vec![
            Span::styled(" Shift + O ", key_style),
            Span::styled("close", dim_style),
        ]))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.accent));
    frame.render_widget(header, slots[0]);

    // ── Helper: floating section title ────────────────────────────────────────
    // Renders " Label ────────" in dim, no border.
    let section_title = |frame: &mut Frame, slot: Rect, label: &str| {
        let dashes = "".repeat((slot.width as usize).saturating_sub(label.len() + 2));
        let para = Paragraph::new(Line::from(vec![
            Span::styled(format!(" {label} "), dim_style),
            Span::styled(dashes, dim_style),
        ]));
        frame.render_widget(para, slot);
    };

    // ── Helper: one row inside a group cell ───────────────────────────────────
    // Returns a Line with key (left-padded), label, and value span.
    let option_row = |key: &str, label: &str, value: Span<'static>| -> Line {
        Line::from(vec![
            Span::raw(" "),
            Span::styled(format!("{key:<12}"), key_style),
            Span::styled(format!("{label:<16}"), label_style),
            value,
        ])
    };

    // ── Helper: bool value span ───────────────────────────────────────────────
    let bool_span = |on: bool| -> Span {
        if on {
            Span::styled("● on", on_style)
        } else {
            Span::styled("○ off", off_style)
        }
    };

    // ── View group ────────────────────────────────────────────────────────────
    section_title(frame, slots[2], "View");

    let view_rows = vec![
        option_row("h", "hidden files", bool_span(app.show_hidden)),
        option_row("w", "single pane", bool_span(app.single_pane)),
        option_row(
            "Tab",
            "switch pane",
            Span::styled(app.active_label(), on_style),
        ),
    ];
    let view_cell = Paragraph::new(view_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(view_cell, slots[3]);

    // ── Sort group ────────────────────────────────────────────────────────────
    section_title(frame, slots[5], "Sort");

    let sort_rows = vec![option_row(
        "s",
        "sort mode",
        Span::styled(app.sort_mode.label(), on_style),
    )];
    let sort_cell = Paragraph::new(sort_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(sort_cell, slots[6]);

    // ── Theme group ───────────────────────────────────────────────────────────
    section_title(frame, slots[8], "Theme");

    let theme_rows = vec![option_row(
        "t",
        "cycle theme",
        Span::styled(app.theme_name(), on_style),
    )];
    let theme_cell = Paragraph::new(theme_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(theme_cell, slots[9]);

    // ── Editor group ──────────────────────────────────────────────────────────
    section_title(frame, slots[11], "Editor");

    let editor_val_style = if app.editor == Editor::None {
        off_style
    } else {
        on_style
    };
    let editor_rows = vec![option_row(
        "e",
        "open with",
        Span::styled(app.editor.label(), editor_val_style),
    )];
    let editor_cell = Paragraph::new(editor_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(editor_cell, slots[12]);
}