.cargo/
crates/
brain/
diff/
files/
src/
main.rs
24.1 KiB
Cargo.toml
290 B
highlight/
repo/
signals/
tui/
tui-core/
tui-termion/
tui-widgets/
scripts/
src/
.gitignore
30 B
.gitsigners
198 B
AGENTS.md
1.9 KiB
CONTRIBUTING
1.7 KiB
Cargo.lock
5.4 KiB
Cargo.toml
1.9 KiB
LICENSE
1.1 KiB
README.md
245 B
STYLE
3.7 KiB
clippy.toml
213 B
crates/files/src/main.rs
raw
| 1 | //! Standalone terminal file browser built with the `tui` crate. |
| 2 | |
| 3 | use std::cell::Cell as StateCell; |
| 4 | use std::collections::HashMap; |
| 5 | use std::ffi::OsStr; |
| 6 | use std::fs; |
| 7 | use std::io; |
| 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::sync::{Mutex, PoisonError}; |
| 10 | use std::time::SystemTime; |
| 11 | |
| 12 | use rustik::fmt; |
| 13 | use rustik_tui as tui; |
| 14 | use rustik_tui_termion as tui_termion; |
| 15 | use tui::text; |
| 16 | use tui::{ |
| 17 | ActionBar, ActionList, App, Block, Border, Cell, Color, Control, Direction, Event, Frame, Key, |
| 18 | Label, Length, Line, List, ListState, Mouse, MouseButton, Paint, Rect, ScrollMetrics, |
| 19 | ScrollView, ScrollbarStyle, Size, StatefulWidget, Style, Table, TableOptions, TextArea, VStack, |
| 20 | Widget, colors, |
| 21 | }; |
| 22 | |
| 23 | const COLUMN_WIDTH: usize = 30; |
| 24 | const PREVIEW_MIN_WIDTH: usize = 28; |
| 25 | const ACTIVE_BORDER_COLOR: Color = Color::Blue; |
| 26 | const INACTIVE_BORDER_COLOR: Color = colors::FAINT; |
| 27 | const ACTIVE_SELECTION_BG_COLOR: Color = Color::Blue; |
| 28 | const INACTIVE_SELECTION_BG_COLOR: Color = Color::Fixed(235); |
| 29 | const DIRECTORY_COLOR: Color = Color::Cyan; |
| 30 | const PREVIEW_TEXT_COLOR: Color = Color::Fixed(252); |
| 31 | const METADATA_LABEL_COLOR: Color = Color::Fixed(240); |
| 32 | const METADATA_VALUE_COLOR: Color = Color::Fixed(244); |
| 33 | const HEADER_COLOR: Color = Color::White; |
| 34 | const ERROR_COLOR: Color = Color::Red; |
| 35 | const FOOTER_KEY_COLOR: Color = Color::Cyan; |
| 36 | const FOOTER_KEY_TEXT_COLOR: Color = Color::Black; |
| 37 | const FOOTER_ACTION_COLOR: Color = Color::Fixed(244); |
| 38 | const SCROLLBAR_TRACK_COLOR: Color = Color::Fixed(238); |
| 39 | const SCROLLBAR_ACTIVE_THUMB_COLOR: Color = Color::Blue; |
| 40 | const SCROLLBAR_INACTIVE_THUMB_COLOR: Color = Color::Fixed(244); |
| 41 | |
| 42 | /// Runs the file browser from the provided root path or current directory. |
| 43 | fn main() -> io::Result<()> { |
| 44 | let root = std::env::args_os() |
| 45 | .nth(1) |
| 46 | .map(PathBuf::from) |
| 47 | .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))); |
| 48 | let mut app = Browser::new(root); |
| 49 | |
| 50 | tui_termion::run(&mut app) |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug)] |
| 54 | struct Browser { |
| 55 | root: PathBuf, |
| 56 | columns: Vec<Column>, |
| 57 | selections: HashMap<PathBuf, PathBuf>, |
| 58 | active: usize, |
| 59 | focus: Focus, |
| 60 | preview_offsets: HashMap<PathBuf, usize>, |
| 61 | preview_view: StateCell<ScrollMetrics>, |
| 62 | error: Option<String>, |
| 63 | } |
| 64 | |
| 65 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 66 | enum Focus { |
| 67 | Columns, |
| 68 | Preview, |
| 69 | } |
| 70 | |
| 71 | impl Browser { |
| 72 | fn new(root: PathBuf) -> Self { |
| 73 | let mut app = Self { |
| 74 | root: root.clone(), |
| 75 | columns: Vec::new(), |
| 76 | selections: HashMap::new(), |
| 77 | active: 0, |
| 78 | focus: Focus::Columns, |
| 79 | preview_offsets: HashMap::new(), |
| 80 | preview_view: StateCell::new(ScrollMetrics::default()), |
| 81 | error: None, |
| 82 | }; |
| 83 | app.push_column(root); |
| 84 | app.update_trailing_columns(); |
| 85 | app |
| 86 | } |
| 87 | |
| 88 | fn selected_path(&self) -> Option<&Path> { |
| 89 | self.columns |
| 90 | .get(self.active) |
| 91 | .and_then(Column::selected) |
| 92 | .map(|entry| entry.path.as_path()) |
| 93 | } |
| 94 | |
| 95 | fn selected_entry(&self) -> Option<&Entry> { |
| 96 | self.columns.get(self.active).and_then(Column::selected) |
| 97 | } |
| 98 | |
| 99 | fn preview_offset(&self) -> usize { |
| 100 | self.selected_path() |
| 101 | .and_then(|path| self.preview_offsets.get(path).copied()) |
| 102 | .unwrap_or(0) |
| 103 | } |
| 104 | |
| 105 | fn set_preview_offset(&mut self, offset: usize) { |
| 106 | let Some(path) = self.selected_path().map(Path::to_path_buf) else { |
| 107 | return; |
| 108 | }; |
| 109 | self.preview_offsets.insert(path, offset); |
| 110 | } |
| 111 | |
| 112 | fn move_preview(&mut self, delta: isize) -> bool { |
| 113 | if self.focus != Focus::Preview { |
| 114 | return false; |
| 115 | } |
| 116 | let previous = self.preview_offset(); |
| 117 | let max_offset = self.preview_max_offset(); |
| 118 | let next = if delta.is_negative() { |
| 119 | previous.saturating_sub(delta.unsigned_abs()) |
| 120 | } else { |
| 121 | previous.saturating_add(delta as usize) |
| 122 | } |
| 123 | .min(max_offset); |
| 124 | self.set_preview_offset(next); |
| 125 | next != previous |
| 126 | } |
| 127 | |
| 128 | fn page_preview_half(&mut self) -> bool { |
| 129 | if self.focus != Focus::Preview { |
| 130 | return false; |
| 131 | } |
| 132 | let rows = (self.preview_view.get().visible_rows / 2).max(1); |
| 133 | self.move_preview(rows as isize) |
| 134 | } |
| 135 | |
| 136 | fn preview_max_offset(&self) -> usize { |
| 137 | self.preview_view.get().max_offset() |
| 138 | } |
| 139 | |
| 140 | fn focus_preview(&mut self) -> bool { |
| 141 | if self.selected_entry().is_none() || self.focus == Focus::Preview { |
| 142 | return false; |
| 143 | } |
| 144 | self.focus = Focus::Preview; |
| 145 | true |
| 146 | } |
| 147 | |
| 148 | fn focus_columns(&mut self) -> bool { |
| 149 | if self.focus == Focus::Columns { |
| 150 | return false; |
| 151 | } |
| 152 | self.focus = Focus::Columns; |
| 153 | true |
| 154 | } |
| 155 | |
| 156 | fn add_column(&mut self) -> bool { |
| 157 | if self.focus == Focus::Preview { |
| 158 | return false; |
| 159 | } |
| 160 | let Some(entry) = self.selected_entry() else { |
| 161 | return false; |
| 162 | }; |
| 163 | if !entry.is_dir { |
| 164 | self.columns.truncate(self.active.saturating_add(1)); |
| 165 | return self.focus_preview(); |
| 166 | } |
| 167 | |
| 168 | let path = entry.path.clone(); |
| 169 | let next = self.active.saturating_add(1); |
| 170 | if self |
| 171 | .columns |
| 172 | .get(next) |
| 173 | .is_none_or(|column| column.path != path) |
| 174 | { |
| 175 | self.columns.truncate(next); |
| 176 | self.push_column(path); |
| 177 | } |
| 178 | if self.columns.len() <= next { |
| 179 | return false; |
| 180 | } |
| 181 | self.active = next; |
| 182 | self.columns.truncate(next.saturating_add(1)); |
| 183 | |
| 184 | true |
| 185 | } |
| 186 | |
| 187 | fn remove_column(&mut self) -> bool { |
| 188 | if self.focus == Focus::Preview { |
| 189 | return self.focus_columns(); |
| 190 | } |
| 191 | if self.active == 0 { |
| 192 | let Some((parent, previous)) = self.columns.first().and_then(|column| { |
| 193 | column |
| 194 | .path |
| 195 | .parent() |
| 196 | .map(|parent| (parent.to_path_buf(), column.path.clone())) |
| 197 | }) else { |
| 198 | return false; |
| 199 | }; |
| 200 | |
| 201 | self.columns.clear(); |
| 202 | self.push_column(parent); |
| 203 | if let Some(column) = self.columns.first_mut() { |
| 204 | column.select_path(&previous); |
| 205 | } |
| 206 | self.remember_column_selection(0); |
| 207 | self.update_trailing_columns(); |
| 208 | return true; |
| 209 | } |
| 210 | self.columns.truncate(self.active); |
| 211 | self.active = self.active.saturating_sub(1); |
| 212 | self.update_trailing_columns(); |
| 213 | |
| 214 | true |
| 215 | } |
| 216 | |
| 217 | fn push_column(&mut self, path: PathBuf) { |
| 218 | match Column::read(path) { |
| 219 | Ok(mut column) => { |
| 220 | if let Some(selected) = self.selections.get(&column.path) { |
| 221 | column.select_path(selected); |
| 222 | } |
| 223 | self.error = None; |
| 224 | self.columns.push(column); |
| 225 | } |
| 226 | Err(err) => { |
| 227 | self.error = Some(err.to_string()); |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | fn remember_column_selection(&mut self, index: usize) { |
| 233 | let Some(column) = self.columns.get(index) else { |
| 234 | return; |
| 235 | }; |
| 236 | if let Some(entry) = column.selected() { |
| 237 | self.selections |
| 238 | .insert(column.path.clone(), entry.path.clone()); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | fn active_column_mut(&mut self) -> Option<&mut Column> { |
| 243 | self.columns.get_mut(self.active) |
| 244 | } |
| 245 | |
| 246 | fn update_trailing_columns(&mut self) -> bool { |
| 247 | let next = self.active.saturating_add(1); |
| 248 | let Some(entry) = self.selected_entry() else { |
| 249 | let changed = self.columns.len() > next; |
| 250 | self.columns.truncate(next); |
| 251 | return changed; |
| 252 | }; |
| 253 | if !entry.is_dir { |
| 254 | let changed = self.columns.len() > next; |
| 255 | self.columns.truncate(next); |
| 256 | return changed; |
| 257 | } |
| 258 | |
| 259 | let path = entry.path.clone(); |
| 260 | if self |
| 261 | .columns |
| 262 | .get(next) |
| 263 | .is_some_and(|column| column.path == path) |
| 264 | { |
| 265 | let changed = self.columns.len() > next.saturating_add(1); |
| 266 | self.columns.truncate(next.saturating_add(1)); |
| 267 | return changed; |
| 268 | } |
| 269 | self.columns.truncate(next); |
| 270 | self.push_column(path); |
| 271 | true |
| 272 | } |
| 273 | |
| 274 | /// Applies an operation to the active column, syncing trailing state if it changed. |
| 275 | fn with_active_column(&mut self, op: impl FnOnce(&mut Column) -> bool) -> bool { |
| 276 | let Some(column) = self.active_column_mut() else { |
| 277 | return false; |
| 278 | }; |
| 279 | if !op(column) { |
| 280 | return false; |
| 281 | } |
| 282 | self.remember_column_selection(self.active); |
| 283 | self.update_trailing_columns(); |
| 284 | true |
| 285 | } |
| 286 | |
| 287 | fn move_selection(&mut self, delta: isize) -> bool { |
| 288 | if self.focus == Focus::Preview { |
| 289 | return self.move_preview(delta); |
| 290 | } |
| 291 | self.with_active_column(|column| column.move_selection(delta)) |
| 292 | } |
| 293 | |
| 294 | fn scroll(&mut self, delta: isize) -> bool { |
| 295 | if self.focus == Focus::Preview { |
| 296 | return self.move_preview(delta); |
| 297 | } |
| 298 | |
| 299 | self.active_column_mut() |
| 300 | .is_some_and(|column| column.scroll(delta)) |
| 301 | } |
| 302 | |
| 303 | fn select_first(&mut self) -> bool { |
| 304 | if self.focus == Focus::Preview { |
| 305 | let changed = self.preview_offset() != 0; |
| 306 | self.set_preview_offset(0); |
| 307 | return changed; |
| 308 | } |
| 309 | self.with_active_column(Column::select_first) |
| 310 | } |
| 311 | |
| 312 | fn select_last(&mut self) -> bool { |
| 313 | if self.focus == Focus::Preview { |
| 314 | let previous = self.preview_offset(); |
| 315 | let next = self.preview_max_offset(); |
| 316 | self.set_preview_offset(next); |
| 317 | return previous != next; |
| 318 | } |
| 319 | self.with_active_column(Column::select_last) |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | impl App for Browser { |
| 324 | type Event = (); |
| 325 | |
| 326 | fn update(&mut self, event: Event<Self::Event>) -> Control { |
| 327 | let redraw = match event { |
| 328 | Event::Key(Key::Char('q') | Key::Esc) | Event::Key(Key::Ctrl('c')) => { |
| 329 | return Control::Quit; |
| 330 | } |
| 331 | Event::Key(Key::Down | Key::Char('j')) => self.move_selection(1), |
| 332 | Event::Key(Key::Up | Key::Char('k')) => self.move_selection(-1), |
| 333 | Event::Key(Key::PageDown) => self.move_selection(10), |
| 334 | Event::Key(Key::PageUp) => self.move_selection(-10), |
| 335 | Event::Key(Key::Char(' ')) => self.page_preview_half(), |
| 336 | Event::Key(Key::Home) => self.select_first(), |
| 337 | Event::Key(Key::End) => self.select_last(), |
| 338 | Event::Key(Key::Right | Key::Enter | Key::Char('l')) => self.add_column(), |
| 339 | Event::Key(Key::Left | Key::Backspace | Key::Char('h')) => self.remove_column(), |
| 340 | Event::Mouse(Mouse::Press { |
| 341 | button: MouseButton::WheelDown, |
| 342 | .. |
| 343 | }) => self.scroll(1), |
| 344 | Event::Mouse(Mouse::Press { |
| 345 | button: MouseButton::WheelUp, |
| 346 | .. |
| 347 | }) => self.scroll(-1), |
| 348 | Event::Resize(_) => true, |
| 349 | _ => false, |
| 350 | }; |
| 351 | |
| 352 | if redraw { |
| 353 | Control::Redraw |
| 354 | } else { |
| 355 | Control::Wait |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | fn render(&mut self, frame: &mut Frame<'_>) { |
| 360 | let area = frame.area; |
| 361 | if area.rows < 3 || area.cols < 12 { |
| 362 | frame.render_widget(Label::new("terminal too small"), area); |
| 363 | return; |
| 364 | } |
| 365 | |
| 366 | let [header, body, footer] = tui::layout::areas( |
| 367 | area, |
| 368 | Direction::Vertical, |
| 369 | &[Length::Fixed(1), Length::Fill(1), Length::Fixed(1)], |
| 370 | ); |
| 371 | frame.render_widget(header_line(self), header); |
| 372 | frame.render_widget(footer_line(self), footer); |
| 373 | self.render_body(frame, body); |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | impl Browser { |
| 378 | fn render_body(&mut self, frame: &mut Frame<'_>, area: Rect) { |
| 379 | if area.is_empty() { |
| 380 | return; |
| 381 | } |
| 382 | |
| 383 | let visible_columns = visible_column_count(area.cols, self.columns.len()); |
| 384 | let hidden = self.columns.len().saturating_sub(visible_columns); |
| 385 | let show_preview = self |
| 386 | .columns |
| 387 | .get(self.active) |
| 388 | .and_then(Column::selected) |
| 389 | .is_some_and(|entry| !entry.is_dir); |
| 390 | let preview_width = if show_preview |
| 391 | && area.cols >= visible_columns.saturating_mul(COLUMN_WIDTH) + PREVIEW_MIN_WIDTH |
| 392 | { |
| 393 | area.cols - visible_columns.saturating_mul(COLUMN_WIDTH) |
| 394 | } else { |
| 395 | 0 |
| 396 | }; |
| 397 | |
| 398 | let mut lengths = vec![Length::Fixed(COLUMN_WIDTH); visible_columns]; |
| 399 | if preview_width > 0 { |
| 400 | lengths.push(Length::Fill(1)); |
| 401 | } |
| 402 | |
| 403 | let chunks = tui::layout::split(area, Direction::Horizontal, &lengths); |
| 404 | for (index, chunk) in chunks.iter().take(visible_columns).enumerate() { |
| 405 | let column_index = hidden + index; |
| 406 | let active = self.focus == Focus::Columns && column_index == self.active; |
| 407 | if let Some(column) = self.columns.get_mut(column_index) { |
| 408 | frame.render_widget(ColumnWidget { column, active }, *chunk); |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | if show_preview |
| 413 | && let (Some(preview), Some(entry)) = |
| 414 | (chunks.get(visible_columns), self.selected_entry()) |
| 415 | { |
| 416 | let metrics = render_preview( |
| 417 | entry, |
| 418 | self.focus == Focus::Preview, |
| 419 | self.preview_offset(), |
| 420 | *preview, |
| 421 | frame.buffer, |
| 422 | ); |
| 423 | self.preview_view.set(metrics); |
| 424 | } else { |
| 425 | self.preview_view.set(ScrollMetrics::default()); |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | #[derive(Debug)] |
| 431 | struct Column { |
| 432 | /// Directory path shown by this column. |
| 433 | path: PathBuf, |
| 434 | /// Directory entries in display order. |
| 435 | entries: Vec<Entry>, |
| 436 | /// Selection and viewport state for the entry list. |
| 437 | state: ListState, |
| 438 | /// Rows available to the list in the last render pass. |
| 439 | visible_rows: usize, |
| 440 | } |
| 441 | |
| 442 | impl Column { |
| 443 | fn read(path: PathBuf) -> io::Result<Self> { |
| 444 | let mut entries = Vec::new(); |
| 445 | for entry in fs::read_dir(&path)? { |
| 446 | let entry = entry?; |
| 447 | entries.push(Entry::read(entry.path())?); |
| 448 | } |
| 449 | entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then_with(|| a.name.cmp(&b.name))); |
| 450 | |
| 451 | Ok(Self { |
| 452 | path, |
| 453 | entries, |
| 454 | state: ListState::new(), |
| 455 | visible_rows: 1, |
| 456 | }) |
| 457 | } |
| 458 | |
| 459 | fn selected(&self) -> Option<&Entry> { |
| 460 | self.entries.get(self.state.selected()) |
| 461 | } |
| 462 | |
| 463 | fn scroll(&mut self, delta: isize) -> bool { |
| 464 | self.state.scroll( |
| 465 | tui::Scroll::Lines(delta), |
| 466 | self.entries.len(), |
| 467 | self.visible_rows, |
| 468 | ) |
| 469 | } |
| 470 | |
| 471 | fn select_path(&mut self, path: &Path) { |
| 472 | if let Some(index) = self.entries.iter().position(|entry| entry.path == path) { |
| 473 | self.state.select(index, self.entries.len()); |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | fn move_selection(&mut self, delta: isize) -> bool { |
| 478 | self.state.move_by(delta, self.entries.len()) |
| 479 | } |
| 480 | |
| 481 | fn select_first(&mut self) -> bool { |
| 482 | self.state.select_first() |
| 483 | } |
| 484 | |
| 485 | fn select_last(&mut self) -> bool { |
| 486 | self.state.select_last(self.entries.len()) |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | #[derive(Debug)] |
| 491 | struct Entry { |
| 492 | path: PathBuf, |
| 493 | name: String, |
| 494 | is_dir: bool, |
| 495 | len: u64, |
| 496 | modified: Option<SystemTime>, |
| 497 | } |
| 498 | |
| 499 | impl Entry { |
| 500 | fn read(path: PathBuf) -> io::Result<Self> { |
| 501 | let metadata = fs::symlink_metadata(&path)?; |
| 502 | let name = path |
| 503 | .file_name() |
| 504 | .and_then(OsStr::to_str) |
| 505 | .unwrap_or("?") |
| 506 | .to_owned(); |
| 507 | |
| 508 | Ok(Self { |
| 509 | path, |
| 510 | name, |
| 511 | is_dir: metadata.is_dir(), |
| 512 | len: metadata.len(), |
| 513 | modified: metadata.modified().ok(), |
| 514 | }) |
| 515 | } |
| 516 | |
| 517 | fn kind(&self) -> &'static str { |
| 518 | if self.is_dir { "directory" } else { "file" } |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | #[derive(Debug)] |
| 523 | struct ColumnWidget<'a> { |
| 524 | column: &'a mut Column, |
| 525 | active: bool, |
| 526 | } |
| 527 | |
| 528 | impl Widget for ColumnWidget<'_> { |
| 529 | fn size(&self, parent: tui::Constraint) -> Size { |
| 530 | Size::new(COLUMN_WIDTH, parent.max.rows) |
| 531 | } |
| 532 | |
| 533 | fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { |
| 534 | let border = if self.active { |
| 535 | ACTIVE_BORDER_COLOR |
| 536 | } else { |
| 537 | INACTIVE_BORDER_COLOR |
| 538 | }; |
| 539 | let title = title_for(&self.column.path); |
| 540 | let body = ColumnBody { |
| 541 | column: &mut *self.column, |
| 542 | active: self.active, |
| 543 | }; |
| 544 | Block::new(body) |
| 545 | .border_style(Border::new(border)) |
| 546 | .title(Line::new(text::bold(title))) |
| 547 | .render(area, buf); |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | #[derive(Debug)] |
| 552 | struct ColumnBody<'a> { |
| 553 | column: &'a mut Column, |
| 554 | active: bool, |
| 555 | } |
| 556 | |
| 557 | impl Widget for ColumnBody<'_> { |
| 558 | fn size(&self, parent: tui::Constraint) -> Size { |
| 559 | Size::new(parent.max.cols, parent.max.rows) |
| 560 | } |
| 561 | |
| 562 | fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { |
| 563 | if area.rows == 0 { |
| 564 | return; |
| 565 | } |
| 566 | self.column.visible_rows = area.rows; |
| 567 | |
| 568 | let lines = self.column.entries.iter().map(entry_line); |
| 569 | let mut list = List::new(lines) |
| 570 | .active(self.active) |
| 571 | .selected_styles( |
| 572 | Style::default().bg(ACTIVE_SELECTION_BG_COLOR), |
| 573 | Style::default().bg(INACTIVE_SELECTION_BG_COLOR), |
| 574 | ) |
| 575 | .empty(Line::new(text::dim("empty directory")).style(Style::default().italic())) |
| 576 | .placement(tui::viewport::Placement::Margin { |
| 577 | before: 2, |
| 578 | after: 2, |
| 579 | }) |
| 580 | .scrollbar(finder_scrollbar_style(self.active)); |
| 581 | list.render_with_state(area, buf, &mut self.column.state); |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | /// Builds the visible line for one directory entry. |
| 586 | fn entry_line(entry: &Entry) -> Line { |
| 587 | if entry.is_dir { |
| 588 | Line::new(Paint::new(format!("{}/", entry.name)).fg(DIRECTORY_COLOR)) |
| 589 | } else { |
| 590 | Line::new(Paint::new(entry.name.as_str())) |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | /// Creates the scrollbar style used by finder columns and preview panes. |
| 595 | fn finder_scrollbar_style(active: bool) -> ScrollbarStyle { |
| 596 | ScrollbarStyle::new( |
| 597 | Cell::new('│', Style::new(SCROLLBAR_TRACK_COLOR)), |
| 598 | Cell::new( |
| 599 | '┃', |
| 600 | Style::new(if active { |
| 601 | SCROLLBAR_ACTIVE_THUMB_COLOR |
| 602 | } else { |
| 603 | SCROLLBAR_INACTIVE_THUMB_COLOR |
| 604 | }), |
| 605 | ), |
| 606 | ) |
| 607 | } |
| 608 | |
| 609 | /// Renders the preview pane for an entry and returns its scroll metrics. |
| 610 | fn render_preview( |
| 611 | entry: &Entry, |
| 612 | active: bool, |
| 613 | offset: usize, |
| 614 | area: Rect, |
| 615 | buf: &mut tui::Buffer, |
| 616 | ) -> ScrollMetrics { |
| 617 | let border = if active { |
| 618 | ACTIVE_BORDER_COLOR |
| 619 | } else { |
| 620 | INACTIVE_BORDER_COLOR |
| 621 | }; |
| 622 | let metrics = Mutex::new(ScrollMetrics::default()); |
| 623 | let mut stack = VStack::default() |
| 624 | .bordered(Border::new(border)) |
| 625 | .padding(1) |
| 626 | .child(metadata_table(entry)); |
| 627 | |
| 628 | if let Some(preview) = file_preview(entry) { |
| 629 | stack |
| 630 | .divider_cell(Cell::new('─', Style::new(border))) |
| 631 | .fill(PreviewScroll { |
| 632 | preview: &preview, |
| 633 | active, |
| 634 | offset, |
| 635 | metrics: &metrics, |
| 636 | }) |
| 637 | .render(area, buf); |
| 638 | } else { |
| 639 | stack.render(area, buf); |
| 640 | } |
| 641 | render_block_title(&entry.name, area, buf); |
| 642 | metrics.into_inner().unwrap_or_else(PoisonError::into_inner) |
| 643 | } |
| 644 | |
| 645 | /// A scrollable text body that records its scroll metrics as it renders. |
| 646 | #[derive(Debug)] |
| 647 | struct PreviewScroll<'a> { |
| 648 | preview: &'a str, |
| 649 | active: bool, |
| 650 | offset: usize, |
| 651 | metrics: &'a Mutex<ScrollMetrics>, |
| 652 | } |
| 653 | |
| 654 | impl Widget for PreviewScroll<'_> { |
| 655 | fn size(&self, parent: tui::Constraint) -> Size { |
| 656 | Size::new(parent.max.cols, parent.max.rows) |
| 657 | } |
| 658 | |
| 659 | fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { |
| 660 | let mut scroll = ScrollView::new(area, self.offset, |cols| { |
| 661 | preview_file_rows(self.preview, cols) |
| 662 | }) |
| 663 | .scrollbar(finder_scrollbar_style(self.active)); |
| 664 | *self.metrics.lock().unwrap_or_else(PoisonError::into_inner) = scroll.metrics(area); |
| 665 | scroll.render(area, buf); |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | /// Renders a block title onto an existing border. |
| 670 | fn render_block_title(title: &str, area: Rect, buf: &mut tui::Buffer) { |
| 671 | if area.cols <= 4 { |
| 672 | return; |
| 673 | } |
| 674 | let title = Line::new(text::bold(title)).truncated(area.cols.saturating_sub(4), "…"); |
| 675 | buf.set_line(area.x + 2, area.y, &title); |
| 676 | } |
| 677 | |
| 678 | /// Builds the scrollable file preview rows. |
| 679 | fn preview_file_rows(preview: &str, cols: usize) -> Vec<Line> { |
| 680 | TextArea::new(preview.to_owned()) |
| 681 | .wrap(cols.saturating_sub(2)) |
| 682 | .lines() |
| 683 | .map(|line| Line::new(Paint::new(line).fg(PREVIEW_TEXT_COLOR)).inset(cols)) |
| 684 | .collect() |
| 685 | } |
| 686 | |
| 687 | /// Builds the metadata table for a previewed entry. |
| 688 | fn metadata_table(entry: &Entry) -> Table<2, Line> { |
| 689 | Table::new(TableOptions { |
| 690 | spacing: 3, |
| 691 | ..TableOptions::default() |
| 692 | }) |
| 693 | .row([ |
| 694 | Line::new(Paint::new("kind").fg(METADATA_LABEL_COLOR)), |
| 695 | Line::new(Paint::new(entry.kind()).fg(METADATA_VALUE_COLOR)), |
| 696 | ]) |
| 697 | .row([ |
| 698 | Line::new(Paint::new("size").fg(METADATA_LABEL_COLOR)), |
| 699 | Line::new(Paint::new(size_text(entry)).fg(METADATA_VALUE_COLOR)), |
| 700 | ]) |
| 701 | .row([ |
| 702 | Line::new(Paint::new("modified").fg(METADATA_LABEL_COLOR)), |
| 703 | Line::new(Paint::new(modified_text(entry.modified)).fg(METADATA_VALUE_COLOR)), |
| 704 | ]) |
| 705 | } |
| 706 | |
| 707 | /// Reads the text preview for a non-empty file entry. |
| 708 | fn file_preview(entry: &Entry) -> Option<String> { |
| 709 | if entry.is_dir { |
| 710 | return None; |
| 711 | } |
| 712 | let preview = fs::read_to_string(&entry.path).ok()?; |
| 713 | if preview.is_empty() { |
| 714 | None |
| 715 | } else { |
| 716 | Some(preview) |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | /// Builds the top header line for the current root. |
| 721 | fn header_line(app: &Browser) -> impl Widget { |
| 722 | let current = app.root.display().to_string(); |
| 723 | |
| 724 | HeaderLine { current } |
| 725 | } |
| 726 | |
| 727 | #[derive(Debug)] |
| 728 | struct HeaderLine { |
| 729 | current: String, |
| 730 | } |
| 731 | |
| 732 | impl Widget for HeaderLine { |
| 733 | fn size(&self, parent: tui::Constraint) -> Size { |
| 734 | Size::new(parent.max.cols, 1) |
| 735 | } |
| 736 | |
| 737 | fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { |
| 738 | let style = Style::new(HEADER_COLOR).bold(); |
| 739 | let line = Line::new(Paint::new(self.current.as_str()).with_style(style)) |
| 740 | .truncated(area.cols, "…"); |
| 741 | let x = area.right().saturating_sub(line.width()); |
| 742 | buf.set_line(x, area.y, &line); |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | /// Builds the footer line for current focus and error state. |
| 747 | fn footer_line(app: &Browser) -> Line { |
| 748 | if let Some(error) = app.error.as_deref() { |
| 749 | return Line::new(Paint::new(error).fg(ERROR_COLOR)); |
| 750 | } |
| 751 | |
| 752 | let mut actions = ActionList::new().action("q", "quit"); |
| 753 | if app.focus == Focus::Preview { |
| 754 | actions = actions |
| 755 | .action("up/down", "scroll") |
| 756 | .action("space", "half page") |
| 757 | .action("left/backspace", "columns"); |
| 758 | } else { |
| 759 | actions = actions |
| 760 | .action("up/down", "select") |
| 761 | .action("right/enter", "open/preview") |
| 762 | .action("left/backspace", "remove column"); |
| 763 | } |
| 764 | actions = actions.action("home/end", "jump"); |
| 765 | |
| 766 | ActionBar::new(actions) |
| 767 | .cap_style(Style::new(FOOTER_KEY_COLOR)) |
| 768 | .key_style( |
| 769 | Style::new(FOOTER_KEY_TEXT_COLOR) |
| 770 | .bg(FOOTER_KEY_COLOR) |
| 771 | .bold(), |
| 772 | ) |
| 773 | .action_style(Style::new(FOOTER_ACTION_COLOR)) |
| 774 | .line() |
| 775 | } |
| 776 | |
| 777 | /// Returns how many browser columns fit beside the preview pane. |
| 778 | fn visible_column_count(cols: usize, total: usize) -> usize { |
| 779 | if total == 0 { |
| 780 | return 0; |
| 781 | } |
| 782 | let cols_for_browser = cols.saturating_sub(PREVIEW_MIN_WIDTH); |
| 783 | let fit = (cols_for_browser / COLUMN_WIDTH).max(1); |
| 784 | |
| 785 | fit.min(total) |
| 786 | } |
| 787 | |
| 788 | /// Returns a display title for a path. |
| 789 | fn title_for(path: &Path) -> String { |
| 790 | let mut title = path |
| 791 | .file_name() |
| 792 | .and_then(OsStr::to_str) |
| 793 | .map(str::to_owned) |
| 794 | .unwrap_or_else(|| path.display().to_string()); |
| 795 | if path.is_dir() && !title.ends_with('/') { |
| 796 | title.push('/'); |
| 797 | } |
| 798 | title |
| 799 | } |
| 800 | |
| 801 | /// Returns a display size for a directory entry. |
| 802 | fn size_text(entry: &Entry) -> String { |
| 803 | if entry.is_dir { |
| 804 | return String::from("--"); |
| 805 | } |
| 806 | fmt::human_size(entry.len) |
| 807 | } |
| 808 | |
| 809 | /// Returns a relative modified-time label. |
| 810 | fn modified_text(modified: Option<SystemTime>) -> String { |
| 811 | let Some(modified) = modified else { |
| 812 | return String::from("unknown"); |
| 813 | }; |
| 814 | fmt::relative_time(SystemTime::now(), modified) |
| 815 | } |