//! Standalone terminal file browser built with the `tui` crate. use std::cell::Cell as StateCell; use std::collections::HashMap; use std::ffi::OsStr; use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::sync::{Mutex, PoisonError}; use std::time::SystemTime; use rustik::fmt; use rustik_tui as tui; use rustik_tui_termion as tui_termion; use tui::text; use tui::{ ActionBar, ActionList, App, Block, Border, Cell, Color, Control, Direction, Event, Frame, Key, Label, Length, Line, List, ListState, Mouse, MouseButton, Paint, Rect, ScrollMetrics, ScrollView, ScrollbarStyle, Size, StatefulWidget, Style, Table, TableOptions, TextArea, VStack, Widget, colors, }; const COLUMN_WIDTH: usize = 30; const PREVIEW_MIN_WIDTH: usize = 28; const ACTIVE_BORDER_COLOR: Color = Color::Blue; const INACTIVE_BORDER_COLOR: Color = colors::FAINT; const ACTIVE_SELECTION_BG_COLOR: Color = Color::Blue; const INACTIVE_SELECTION_BG_COLOR: Color = Color::Fixed(235); const DIRECTORY_COLOR: Color = Color::Cyan; const PREVIEW_TEXT_COLOR: Color = Color::Fixed(252); const METADATA_LABEL_COLOR: Color = Color::Fixed(240); const METADATA_VALUE_COLOR: Color = Color::Fixed(244); const HEADER_COLOR: Color = Color::White; const ERROR_COLOR: Color = Color::Red; const FOOTER_KEY_COLOR: Color = Color::Cyan; const FOOTER_KEY_TEXT_COLOR: Color = Color::Black; const FOOTER_ACTION_COLOR: Color = Color::Fixed(244); const SCROLLBAR_TRACK_COLOR: Color = Color::Fixed(238); const SCROLLBAR_ACTIVE_THUMB_COLOR: Color = Color::Blue; const SCROLLBAR_INACTIVE_THUMB_COLOR: Color = Color::Fixed(244); /// Runs the file browser from the provided root path or current directory. fn main() -> io::Result<()> { let root = std::env::args_os() .nth(1) .map(PathBuf::from) .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))); let mut app = Browser::new(root); tui_termion::run(&mut app) } #[derive(Debug)] struct Browser { root: PathBuf, columns: Vec, selections: HashMap, active: usize, focus: Focus, preview_offsets: HashMap, preview_view: StateCell, error: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Focus { Columns, Preview, } impl Browser { fn new(root: PathBuf) -> Self { let mut app = Self { root: root.clone(), columns: Vec::new(), selections: HashMap::new(), active: 0, focus: Focus::Columns, preview_offsets: HashMap::new(), preview_view: StateCell::new(ScrollMetrics::default()), error: None, }; app.push_column(root); app.update_trailing_columns(); app } fn selected_path(&self) -> Option<&Path> { self.columns .get(self.active) .and_then(Column::selected) .map(|entry| entry.path.as_path()) } fn selected_entry(&self) -> Option<&Entry> { self.columns.get(self.active).and_then(Column::selected) } fn preview_offset(&self) -> usize { self.selected_path() .and_then(|path| self.preview_offsets.get(path).copied()) .unwrap_or(0) } fn set_preview_offset(&mut self, offset: usize) { let Some(path) = self.selected_path().map(Path::to_path_buf) else { return; }; self.preview_offsets.insert(path, offset); } fn move_preview(&mut self, delta: isize) -> bool { if self.focus != Focus::Preview { return false; } let previous = self.preview_offset(); let max_offset = self.preview_max_offset(); let next = if delta.is_negative() { previous.saturating_sub(delta.unsigned_abs()) } else { previous.saturating_add(delta as usize) } .min(max_offset); self.set_preview_offset(next); next != previous } fn page_preview_half(&mut self) -> bool { if self.focus != Focus::Preview { return false; } let rows = (self.preview_view.get().visible_rows / 2).max(1); self.move_preview(rows as isize) } fn preview_max_offset(&self) -> usize { self.preview_view.get().max_offset() } fn focus_preview(&mut self) -> bool { if self.selected_entry().is_none() || self.focus == Focus::Preview { return false; } self.focus = Focus::Preview; true } fn focus_columns(&mut self) -> bool { if self.focus == Focus::Columns { return false; } self.focus = Focus::Columns; true } fn add_column(&mut self) -> bool { if self.focus == Focus::Preview { return false; } let Some(entry) = self.selected_entry() else { return false; }; if !entry.is_dir { self.columns.truncate(self.active.saturating_add(1)); return self.focus_preview(); } let path = entry.path.clone(); let next = self.active.saturating_add(1); if self .columns .get(next) .is_none_or(|column| column.path != path) { self.columns.truncate(next); self.push_column(path); } if self.columns.len() <= next { return false; } self.active = next; self.columns.truncate(next.saturating_add(1)); true } fn remove_column(&mut self) -> bool { if self.focus == Focus::Preview { return self.focus_columns(); } if self.active == 0 { let Some((parent, previous)) = self.columns.first().and_then(|column| { column .path .parent() .map(|parent| (parent.to_path_buf(), column.path.clone())) }) else { return false; }; self.columns.clear(); self.push_column(parent); if let Some(column) = self.columns.first_mut() { column.select_path(&previous); } self.remember_column_selection(0); self.update_trailing_columns(); return true; } self.columns.truncate(self.active); self.active = self.active.saturating_sub(1); self.update_trailing_columns(); true } fn push_column(&mut self, path: PathBuf) { match Column::read(path) { Ok(mut column) => { if let Some(selected) = self.selections.get(&column.path) { column.select_path(selected); } self.error = None; self.columns.push(column); } Err(err) => { self.error = Some(err.to_string()); } } } fn remember_column_selection(&mut self, index: usize) { let Some(column) = self.columns.get(index) else { return; }; if let Some(entry) = column.selected() { self.selections .insert(column.path.clone(), entry.path.clone()); } } fn active_column_mut(&mut self) -> Option<&mut Column> { self.columns.get_mut(self.active) } fn update_trailing_columns(&mut self) -> bool { let next = self.active.saturating_add(1); let Some(entry) = self.selected_entry() else { let changed = self.columns.len() > next; self.columns.truncate(next); return changed; }; if !entry.is_dir { let changed = self.columns.len() > next; self.columns.truncate(next); return changed; } let path = entry.path.clone(); if self .columns .get(next) .is_some_and(|column| column.path == path) { let changed = self.columns.len() > next.saturating_add(1); self.columns.truncate(next.saturating_add(1)); return changed; } self.columns.truncate(next); self.push_column(path); true } /// Applies an operation to the active column, syncing trailing state if it changed. fn with_active_column(&mut self, op: impl FnOnce(&mut Column) -> bool) -> bool { let Some(column) = self.active_column_mut() else { return false; }; if !op(column) { return false; } self.remember_column_selection(self.active); self.update_trailing_columns(); true } fn move_selection(&mut self, delta: isize) -> bool { if self.focus == Focus::Preview { return self.move_preview(delta); } self.with_active_column(|column| column.move_selection(delta)) } fn scroll(&mut self, delta: isize) -> bool { if self.focus == Focus::Preview { return self.move_preview(delta); } self.active_column_mut() .is_some_and(|column| column.scroll(delta)) } fn select_first(&mut self) -> bool { if self.focus == Focus::Preview { let changed = self.preview_offset() != 0; self.set_preview_offset(0); return changed; } self.with_active_column(Column::select_first) } fn select_last(&mut self) -> bool { if self.focus == Focus::Preview { let previous = self.preview_offset(); let next = self.preview_max_offset(); self.set_preview_offset(next); return previous != next; } self.with_active_column(Column::select_last) } } impl App for Browser { type Event = (); fn update(&mut self, event: Event) -> Control { let redraw = match event { Event::Key(Key::Char('q') | Key::Esc) | Event::Key(Key::Ctrl('c')) => { return Control::Quit; } Event::Key(Key::Down | Key::Char('j')) => self.move_selection(1), Event::Key(Key::Up | Key::Char('k')) => self.move_selection(-1), Event::Key(Key::PageDown) => self.move_selection(10), Event::Key(Key::PageUp) => self.move_selection(-10), Event::Key(Key::Char(' ')) => self.page_preview_half(), Event::Key(Key::Home) => self.select_first(), Event::Key(Key::End) => self.select_last(), Event::Key(Key::Right | Key::Enter | Key::Char('l')) => self.add_column(), Event::Key(Key::Left | Key::Backspace | Key::Char('h')) => self.remove_column(), Event::Mouse(Mouse::Press { button: MouseButton::WheelDown, .. }) => self.scroll(1), Event::Mouse(Mouse::Press { button: MouseButton::WheelUp, .. }) => self.scroll(-1), Event::Resize(_) => true, _ => false, }; if redraw { Control::Redraw } else { Control::Wait } } fn render(&mut self, frame: &mut Frame<'_>) { let area = frame.area; if area.rows < 3 || area.cols < 12 { frame.render_widget(Label::new("terminal too small"), area); return; } let [header, body, footer] = tui::layout::areas( area, Direction::Vertical, &[Length::Fixed(1), Length::Fill(1), Length::Fixed(1)], ); frame.render_widget(header_line(self), header); frame.render_widget(footer_line(self), footer); self.render_body(frame, body); } } impl Browser { fn render_body(&mut self, frame: &mut Frame<'_>, area: Rect) { if area.is_empty() { return; } let visible_columns = visible_column_count(area.cols, self.columns.len()); let hidden = self.columns.len().saturating_sub(visible_columns); let show_preview = self .columns .get(self.active) .and_then(Column::selected) .is_some_and(|entry| !entry.is_dir); let preview_width = if show_preview && area.cols >= visible_columns.saturating_mul(COLUMN_WIDTH) + PREVIEW_MIN_WIDTH { area.cols - visible_columns.saturating_mul(COLUMN_WIDTH) } else { 0 }; let mut lengths = vec![Length::Fixed(COLUMN_WIDTH); visible_columns]; if preview_width > 0 { lengths.push(Length::Fill(1)); } let chunks = tui::layout::split(area, Direction::Horizontal, &lengths); for (index, chunk) in chunks.iter().take(visible_columns).enumerate() { let column_index = hidden + index; let active = self.focus == Focus::Columns && column_index == self.active; if let Some(column) = self.columns.get_mut(column_index) { frame.render_widget(ColumnWidget { column, active }, *chunk); } } if show_preview && let (Some(preview), Some(entry)) = (chunks.get(visible_columns), self.selected_entry()) { let metrics = render_preview( entry, self.focus == Focus::Preview, self.preview_offset(), *preview, frame.buffer, ); self.preview_view.set(metrics); } else { self.preview_view.set(ScrollMetrics::default()); } } } #[derive(Debug)] struct Column { /// Directory path shown by this column. path: PathBuf, /// Directory entries in display order. entries: Vec, /// Selection and viewport state for the entry list. state: ListState, /// Rows available to the list in the last render pass. visible_rows: usize, } impl Column { fn read(path: PathBuf) -> io::Result { let mut entries = Vec::new(); for entry in fs::read_dir(&path)? { let entry = entry?; entries.push(Entry::read(entry.path())?); } entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then_with(|| a.name.cmp(&b.name))); Ok(Self { path, entries, state: ListState::new(), visible_rows: 1, }) } fn selected(&self) -> Option<&Entry> { self.entries.get(self.state.selected()) } fn scroll(&mut self, delta: isize) -> bool { self.state.scroll( tui::Scroll::Lines(delta), self.entries.len(), self.visible_rows, ) } fn select_path(&mut self, path: &Path) { if let Some(index) = self.entries.iter().position(|entry| entry.path == path) { self.state.select(index, self.entries.len()); } } fn move_selection(&mut self, delta: isize) -> bool { self.state.move_by(delta, self.entries.len()) } fn select_first(&mut self) -> bool { self.state.select_first() } fn select_last(&mut self) -> bool { self.state.select_last(self.entries.len()) } } #[derive(Debug)] struct Entry { path: PathBuf, name: String, is_dir: bool, len: u64, modified: Option, } impl Entry { fn read(path: PathBuf) -> io::Result { let metadata = fs::symlink_metadata(&path)?; let name = path .file_name() .and_then(OsStr::to_str) .unwrap_or("?") .to_owned(); Ok(Self { path, name, is_dir: metadata.is_dir(), len: metadata.len(), modified: metadata.modified().ok(), }) } fn kind(&self) -> &'static str { if self.is_dir { "directory" } else { "file" } } } #[derive(Debug)] struct ColumnWidget<'a> { column: &'a mut Column, active: bool, } impl Widget for ColumnWidget<'_> { fn size(&self, parent: tui::Constraint) -> Size { Size::new(COLUMN_WIDTH, parent.max.rows) } fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { let border = if self.active { ACTIVE_BORDER_COLOR } else { INACTIVE_BORDER_COLOR }; let title = title_for(&self.column.path); let body = ColumnBody { column: &mut *self.column, active: self.active, }; Block::new(body) .border_style(Border::new(border)) .title(Line::new(text::bold(title))) .render(area, buf); } } #[derive(Debug)] struct ColumnBody<'a> { column: &'a mut Column, active: bool, } impl Widget for ColumnBody<'_> { fn size(&self, parent: tui::Constraint) -> Size { Size::new(parent.max.cols, parent.max.rows) } fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { if area.rows == 0 { return; } self.column.visible_rows = area.rows; let lines = self.column.entries.iter().map(entry_line); let mut list = List::new(lines) .active(self.active) .selected_styles( Style::default().bg(ACTIVE_SELECTION_BG_COLOR), Style::default().bg(INACTIVE_SELECTION_BG_COLOR), ) .empty(Line::new(text::dim("empty directory")).style(Style::default().italic())) .placement(tui::viewport::Placement::Margin { before: 2, after: 2, }) .scrollbar(finder_scrollbar_style(self.active)); list.render_with_state(area, buf, &mut self.column.state); } } /// Builds the visible line for one directory entry. fn entry_line(entry: &Entry) -> Line { if entry.is_dir { Line::new(Paint::new(format!("{}/", entry.name)).fg(DIRECTORY_COLOR)) } else { Line::new(Paint::new(entry.name.as_str())) } } /// Creates the scrollbar style used by finder columns and preview panes. fn finder_scrollbar_style(active: bool) -> ScrollbarStyle { ScrollbarStyle::new( Cell::new('│', Style::new(SCROLLBAR_TRACK_COLOR)), Cell::new( '┃', Style::new(if active { SCROLLBAR_ACTIVE_THUMB_COLOR } else { SCROLLBAR_INACTIVE_THUMB_COLOR }), ), ) } /// Renders the preview pane for an entry and returns its scroll metrics. fn render_preview( entry: &Entry, active: bool, offset: usize, area: Rect, buf: &mut tui::Buffer, ) -> ScrollMetrics { let border = if active { ACTIVE_BORDER_COLOR } else { INACTIVE_BORDER_COLOR }; let metrics = Mutex::new(ScrollMetrics::default()); let mut stack = VStack::default() .bordered(Border::new(border)) .padding(1) .child(metadata_table(entry)); if let Some(preview) = file_preview(entry) { stack .divider_cell(Cell::new('─', Style::new(border))) .fill(PreviewScroll { preview: &preview, active, offset, metrics: &metrics, }) .render(area, buf); } else { stack.render(area, buf); } render_block_title(&entry.name, area, buf); metrics.into_inner().unwrap_or_else(PoisonError::into_inner) } /// A scrollable text body that records its scroll metrics as it renders. #[derive(Debug)] struct PreviewScroll<'a> { preview: &'a str, active: bool, offset: usize, metrics: &'a Mutex, } impl Widget for PreviewScroll<'_> { fn size(&self, parent: tui::Constraint) -> Size { Size::new(parent.max.cols, parent.max.rows) } fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { let mut scroll = ScrollView::new(area, self.offset, |cols| { preview_file_rows(self.preview, cols) }) .scrollbar(finder_scrollbar_style(self.active)); *self.metrics.lock().unwrap_or_else(PoisonError::into_inner) = scroll.metrics(area); scroll.render(area, buf); } } /// Renders a block title onto an existing border. fn render_block_title(title: &str, area: Rect, buf: &mut tui::Buffer) { if area.cols <= 4 { return; } let title = Line::new(text::bold(title)).truncated(area.cols.saturating_sub(4), "…"); buf.set_line(area.x + 2, area.y, &title); } /// Builds the scrollable file preview rows. fn preview_file_rows(preview: &str, cols: usize) -> Vec { TextArea::new(preview.to_owned()) .wrap(cols.saturating_sub(2)) .lines() .map(|line| Line::new(Paint::new(line).fg(PREVIEW_TEXT_COLOR)).inset(cols)) .collect() } /// Builds the metadata table for a previewed entry. fn metadata_table(entry: &Entry) -> Table<2, Line> { Table::new(TableOptions { spacing: 3, ..TableOptions::default() }) .row([ Line::new(Paint::new("kind").fg(METADATA_LABEL_COLOR)), Line::new(Paint::new(entry.kind()).fg(METADATA_VALUE_COLOR)), ]) .row([ Line::new(Paint::new("size").fg(METADATA_LABEL_COLOR)), Line::new(Paint::new(size_text(entry)).fg(METADATA_VALUE_COLOR)), ]) .row([ Line::new(Paint::new("modified").fg(METADATA_LABEL_COLOR)), Line::new(Paint::new(modified_text(entry.modified)).fg(METADATA_VALUE_COLOR)), ]) } /// Reads the text preview for a non-empty file entry. fn file_preview(entry: &Entry) -> Option { if entry.is_dir { return None; } let preview = fs::read_to_string(&entry.path).ok()?; if preview.is_empty() { None } else { Some(preview) } } /// Builds the top header line for the current root. fn header_line(app: &Browser) -> impl Widget { let current = app.root.display().to_string(); HeaderLine { current } } #[derive(Debug)] struct HeaderLine { current: String, } impl Widget for HeaderLine { fn size(&self, parent: tui::Constraint) -> Size { Size::new(parent.max.cols, 1) } fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { let style = Style::new(HEADER_COLOR).bold(); let line = Line::new(Paint::new(self.current.as_str()).with_style(style)) .truncated(area.cols, "…"); let x = area.right().saturating_sub(line.width()); buf.set_line(x, area.y, &line); } } /// Builds the footer line for current focus and error state. fn footer_line(app: &Browser) -> Line { if let Some(error) = app.error.as_deref() { return Line::new(Paint::new(error).fg(ERROR_COLOR)); } let mut actions = ActionList::new().action("q", "quit"); if app.focus == Focus::Preview { actions = actions .action("up/down", "scroll") .action("space", "half page") .action("left/backspace", "columns"); } else { actions = actions .action("up/down", "select") .action("right/enter", "open/preview") .action("left/backspace", "remove column"); } actions = actions.action("home/end", "jump"); ActionBar::new(actions) .cap_style(Style::new(FOOTER_KEY_COLOR)) .key_style( Style::new(FOOTER_KEY_TEXT_COLOR) .bg(FOOTER_KEY_COLOR) .bold(), ) .action_style(Style::new(FOOTER_ACTION_COLOR)) .line() } /// Returns how many browser columns fit beside the preview pane. fn visible_column_count(cols: usize, total: usize) -> usize { if total == 0 { return 0; } let cols_for_browser = cols.saturating_sub(PREVIEW_MIN_WIDTH); let fit = (cols_for_browser / COLUMN_WIDTH).max(1); fit.min(total) } /// Returns a display title for a path. fn title_for(path: &Path) -> String { let mut title = path .file_name() .and_then(OsStr::to_str) .map(str::to_owned) .unwrap_or_else(|| path.display().to_string()); if path.is_dir() && !title.ends_with('/') { title.push('/'); } title } /// Returns a display size for a directory entry. fn size_text(entry: &Entry) -> String { if entry.is_dir { return String::from("--"); } fmt::human_size(entry.len) } /// Returns a relative modified-time label. fn modified_text(modified: Option) -> String { let Some(modified) = modified else { return String::from("unknown"); }; fmt::relative_time(SystemTime::now(), modified) }