Add `rustik-files` crate
9b96e2768a91ea450a22d651112ee2d4495c3299
1 parent
9ef2bf5d
Cargo.lock
+9 -0
| 125 | 125 | "rustik-repo", |
|
| 126 | 126 | "rustik-tui", |
|
| 127 | 127 | "rustik-tui-termion", |
|
| 128 | 128 | ] |
|
| 129 | 129 | ||
| 130 | + | [[package]] |
|
| 131 | + | name = "rustik-files" |
|
| 132 | + | version = "0.1.0" |
|
| 133 | + | dependencies = [ |
|
| 134 | + | "rustik", |
|
| 135 | + | "rustik-tui", |
|
| 136 | + | "rustik-tui-termion", |
|
| 137 | + | ] |
|
| 138 | + | ||
| 130 | 139 | [[package]] |
|
| 131 | 140 | name = "rustik-highlight" |
|
| 132 | 141 | version = "0.2.0" |
|
| 133 | 142 | dependencies = [ |
|
| 134 | 143 | "microserde", |
Cargo.toml
+1 -0
| 1 | 1 | [workspace] |
|
| 2 | 2 | members = [ |
|
| 3 | 3 | "crates/diff", |
|
| 4 | + | "crates/files", |
|
| 4 | 5 | "crates/highlight", |
|
| 5 | 6 | "crates/repo", |
|
| 6 | 7 | "crates/signals", |
|
| 7 | 8 | "crates/tui", |
|
| 8 | 9 | "crates/tui-core", |
crates/files/Cargo.toml
added
+11 -0
| 1 | + | [package] |
|
| 2 | + | name = "rustik-files" |
|
| 3 | + | version = "0.1.0" |
|
| 4 | + | edition = "2024" |
|
| 5 | + | description = "Standalone terminal file browser." |
|
| 6 | + | license = "MIT" |
|
| 7 | + | ||
| 8 | + | [dependencies] |
|
| 9 | + | rustik = { path = "../.." } |
|
| 10 | + | rustik-tui = { workspace = true, features = ["widgets"] } |
|
| 11 | + | rustik-tui-termion.workspace = true |
crates/files/src/main.rs
added
+870 -0
| 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::atomic::{AtomicUsize, Ordering}; |
|
| 10 | + | use std::sync::{Mutex, PoisonError}; |
|
| 11 | + | use std::time::SystemTime; |
|
| 12 | + | ||
| 13 | + | use rustik::fmt; |
|
| 14 | + | use rustik_tui as tui; |
|
| 15 | + | use rustik_tui_termion as tui_termion; |
|
| 16 | + | use tui::text; |
|
| 17 | + | use tui::{ |
|
| 18 | + | App, Block, Border, Cell, Color, Control, Direction, Event, Frame, Key, Label, Length, Line, |
|
| 19 | + | List, Mouse, MouseButton, Paint, Rect, ScrollMetrics, ScrollView, ScrollbarStyle, Selection, |
|
| 20 | + | Size, Style, Table, TableOptions, TextArea, VStack, 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_SEPARATOR_COLOR: Color = Color::Fixed(244); |
|
| 36 | + | const FOOTER_KEY_COLOR: Color = Color::Cyan; |
|
| 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 active_column(&self) -> Option<&Column> { |
|
| 247 | + | self.columns.get(self.active) |
|
| 248 | + | } |
|
| 249 | + | ||
| 250 | + | fn update_trailing_columns(&mut self) -> bool { |
|
| 251 | + | let next = self.active.saturating_add(1); |
|
| 252 | + | let Some(entry) = self.selected_entry() else { |
|
| 253 | + | let changed = self.columns.len() > next; |
|
| 254 | + | self.columns.truncate(next); |
|
| 255 | + | return changed; |
|
| 256 | + | }; |
|
| 257 | + | if !entry.is_dir { |
|
| 258 | + | let changed = self.columns.len() > next; |
|
| 259 | + | self.columns.truncate(next); |
|
| 260 | + | return changed; |
|
| 261 | + | } |
|
| 262 | + | ||
| 263 | + | let path = entry.path.clone(); |
|
| 264 | + | if self |
|
| 265 | + | .columns |
|
| 266 | + | .get(next) |
|
| 267 | + | .is_some_and(|column| column.path == path) |
|
| 268 | + | { |
|
| 269 | + | let changed = self.columns.len() > next.saturating_add(1); |
|
| 270 | + | self.columns.truncate(next.saturating_add(1)); |
|
| 271 | + | return changed; |
|
| 272 | + | } |
|
| 273 | + | self.columns.truncate(next); |
|
| 274 | + | self.push_column(path); |
|
| 275 | + | true |
|
| 276 | + | } |
|
| 277 | + | ||
| 278 | + | /// Applies an operation to the active column, syncing trailing state if it changed. |
|
| 279 | + | fn with_active_column(&mut self, op: impl FnOnce(&mut Column) -> bool) -> bool { |
|
| 280 | + | let Some(column) = self.active_column_mut() else { |
|
| 281 | + | return false; |
|
| 282 | + | }; |
|
| 283 | + | if !op(column) { |
|
| 284 | + | return false; |
|
| 285 | + | } |
|
| 286 | + | self.remember_column_selection(self.active); |
|
| 287 | + | self.update_trailing_columns(); |
|
| 288 | + | true |
|
| 289 | + | } |
|
| 290 | + | ||
| 291 | + | fn move_selection(&mut self, delta: isize) -> bool { |
|
| 292 | + | if self.focus == Focus::Preview { |
|
| 293 | + | return self.move_preview(delta); |
|
| 294 | + | } |
|
| 295 | + | self.with_active_column(|column| column.move_selection(delta)) |
|
| 296 | + | } |
|
| 297 | + | ||
| 298 | + | fn scroll(&mut self, delta: isize) -> bool { |
|
| 299 | + | if self.focus == Focus::Preview { |
|
| 300 | + | return self.move_preview(delta); |
|
| 301 | + | } |
|
| 302 | + | ||
| 303 | + | self.active_column() |
|
| 304 | + | .is_some_and(|column| column.scroll(delta)) |
|
| 305 | + | } |
|
| 306 | + | ||
| 307 | + | fn select_first(&mut self) -> bool { |
|
| 308 | + | if self.focus == Focus::Preview { |
|
| 309 | + | let changed = self.preview_offset() != 0; |
|
| 310 | + | self.set_preview_offset(0); |
|
| 311 | + | return changed; |
|
| 312 | + | } |
|
| 313 | + | self.with_active_column(Column::select_first) |
|
| 314 | + | } |
|
| 315 | + | ||
| 316 | + | fn select_last(&mut self) -> bool { |
|
| 317 | + | if self.focus == Focus::Preview { |
|
| 318 | + | let previous = self.preview_offset(); |
|
| 319 | + | let next = self.preview_max_offset(); |
|
| 320 | + | self.set_preview_offset(next); |
|
| 321 | + | return previous != next; |
|
| 322 | + | } |
|
| 323 | + | self.with_active_column(Column::select_last) |
|
| 324 | + | } |
|
| 325 | + | } |
|
| 326 | + | ||
| 327 | + | impl App for Browser { |
|
| 328 | + | type Event = (); |
|
| 329 | + | ||
| 330 | + | fn update(&mut self, event: Event<Self::Event>) -> Control { |
|
| 331 | + | let redraw = match event { |
|
| 332 | + | Event::Key(Key::Char('q') | Key::Esc) | Event::Key(Key::Ctrl('c')) => { |
|
| 333 | + | return Control::Quit; |
|
| 334 | + | } |
|
| 335 | + | Event::Key(Key::Down | Key::Char('j')) => self.move_selection(1), |
|
| 336 | + | Event::Key(Key::Up | Key::Char('k')) => self.move_selection(-1), |
|
| 337 | + | Event::Key(Key::PageDown) => self.move_selection(10), |
|
| 338 | + | Event::Key(Key::PageUp) => self.move_selection(-10), |
|
| 339 | + | Event::Key(Key::Char(' ')) => self.page_preview_half(), |
|
| 340 | + | Event::Key(Key::Home) => self.select_first(), |
|
| 341 | + | Event::Key(Key::End) => self.select_last(), |
|
| 342 | + | Event::Key(Key::Right | Key::Enter | Key::Char('l')) => self.add_column(), |
|
| 343 | + | Event::Key(Key::Left | Key::Backspace | Key::Char('h')) => self.remove_column(), |
|
| 344 | + | Event::Mouse(Mouse::Press { |
|
| 345 | + | button: MouseButton::WheelDown, |
|
| 346 | + | .. |
|
| 347 | + | }) => self.scroll(1), |
|
| 348 | + | Event::Mouse(Mouse::Press { |
|
| 349 | + | button: MouseButton::WheelUp, |
|
| 350 | + | .. |
|
| 351 | + | }) => self.scroll(-1), |
|
| 352 | + | Event::Resize(_) => true, |
|
| 353 | + | _ => false, |
|
| 354 | + | }; |
|
| 355 | + | ||
| 356 | + | if redraw { |
|
| 357 | + | Control::Redraw |
|
| 358 | + | } else { |
|
| 359 | + | Control::Wait |
|
| 360 | + | } |
|
| 361 | + | } |
|
| 362 | + | ||
| 363 | + | fn render(&mut self, frame: &mut Frame<'_>) { |
|
| 364 | + | let area = frame.area; |
|
| 365 | + | if area.rows < 3 || area.cols < 12 { |
|
| 366 | + | frame.render_widget(Label::new("terminal too small"), area); |
|
| 367 | + | return; |
|
| 368 | + | } |
|
| 369 | + | ||
| 370 | + | let [header, body, footer] = tui::layout::areas( |
|
| 371 | + | area, |
|
| 372 | + | Direction::Vertical, |
|
| 373 | + | &[Length::Fixed(1), Length::Fill(1), Length::Fixed(1)], |
|
| 374 | + | ); |
|
| 375 | + | frame.render_widget(header_line(self), header); |
|
| 376 | + | frame.render_widget(footer_line(self), footer); |
|
| 377 | + | self.render_body(frame, body); |
|
| 378 | + | } |
|
| 379 | + | } |
|
| 380 | + | ||
| 381 | + | impl Browser { |
|
| 382 | + | fn render_body(&mut self, frame: &mut Frame<'_>, area: Rect) { |
|
| 383 | + | if area.is_empty() { |
|
| 384 | + | return; |
|
| 385 | + | } |
|
| 386 | + | ||
| 387 | + | let visible_columns = visible_column_count(area.cols, self.columns.len()); |
|
| 388 | + | let hidden = self.columns.len().saturating_sub(visible_columns); |
|
| 389 | + | let show_preview = self |
|
| 390 | + | .columns |
|
| 391 | + | .get(self.active) |
|
| 392 | + | .and_then(Column::selected) |
|
| 393 | + | .is_some_and(|entry| !entry.is_dir); |
|
| 394 | + | let preview_width = if show_preview |
|
| 395 | + | && area.cols >= visible_columns.saturating_mul(COLUMN_WIDTH) + PREVIEW_MIN_WIDTH |
|
| 396 | + | { |
|
| 397 | + | area.cols - visible_columns.saturating_mul(COLUMN_WIDTH) |
|
| 398 | + | } else { |
|
| 399 | + | 0 |
|
| 400 | + | }; |
|
| 401 | + | ||
| 402 | + | let mut lengths = vec![Length::Fixed(COLUMN_WIDTH); visible_columns]; |
|
| 403 | + | if preview_width > 0 { |
|
| 404 | + | lengths.push(Length::Fill(1)); |
|
| 405 | + | } |
|
| 406 | + | ||
| 407 | + | let chunks = tui::layout::split(area, Direction::Horizontal, &lengths); |
|
| 408 | + | for (index, chunk) in chunks.iter().take(visible_columns).enumerate() { |
|
| 409 | + | let column_index = hidden + index; |
|
| 410 | + | let active = self.focus == Focus::Columns && column_index == self.active; |
|
| 411 | + | if let Some(column) = self.columns.get(column_index) { |
|
| 412 | + | frame.render_widget(ColumnWidget { column, active }, *chunk); |
|
| 413 | + | } |
|
| 414 | + | } |
|
| 415 | + | ||
| 416 | + | if show_preview |
|
| 417 | + | && let (Some(preview), Some(entry)) = |
|
| 418 | + | (chunks.get(visible_columns), self.selected_entry()) |
|
| 419 | + | { |
|
| 420 | + | let metrics = render_preview( |
|
| 421 | + | entry, |
|
| 422 | + | self.focus == Focus::Preview, |
|
| 423 | + | self.preview_offset(), |
|
| 424 | + | *preview, |
|
| 425 | + | frame.buffer, |
|
| 426 | + | ); |
|
| 427 | + | self.preview_view.set(metrics); |
|
| 428 | + | } else { |
|
| 429 | + | self.preview_view.set(ScrollMetrics::default()); |
|
| 430 | + | } |
|
| 431 | + | } |
|
| 432 | + | } |
|
| 433 | + | ||
| 434 | + | #[derive(Debug)] |
|
| 435 | + | struct Column { |
|
| 436 | + | path: PathBuf, |
|
| 437 | + | entries: Vec<Entry>, |
|
| 438 | + | selection: Selection, |
|
| 439 | + | offset: AtomicUsize, |
|
| 440 | + | visible_rows: AtomicUsize, |
|
| 441 | + | } |
|
| 442 | + | ||
| 443 | + | impl Column { |
|
| 444 | + | fn read(path: PathBuf) -> io::Result<Self> { |
|
| 445 | + | let mut entries = Vec::new(); |
|
| 446 | + | for entry in fs::read_dir(&path)? { |
|
| 447 | + | let entry = entry?; |
|
| 448 | + | entries.push(Entry::read(entry.path())?); |
|
| 449 | + | } |
|
| 450 | + | entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then_with(|| a.name.cmp(&b.name))); |
|
| 451 | + | ||
| 452 | + | Ok(Self { |
|
| 453 | + | path, |
|
| 454 | + | entries, |
|
| 455 | + | selection: Selection::new(), |
|
| 456 | + | offset: AtomicUsize::new(0), |
|
| 457 | + | visible_rows: AtomicUsize::new(1), |
|
| 458 | + | }) |
|
| 459 | + | } |
|
| 460 | + | ||
| 461 | + | fn selected(&self) -> Option<&Entry> { |
|
| 462 | + | self.entries.get(self.selection.selected) |
|
| 463 | + | } |
|
| 464 | + | ||
| 465 | + | fn set_visible_rows(&self, rows: usize) { |
|
| 466 | + | self.visible_rows.store(rows, Ordering::Relaxed); |
|
| 467 | + | self.set_offset(self.offset()); |
|
| 468 | + | } |
|
| 469 | + | ||
| 470 | + | fn offset(&self) -> usize { |
|
| 471 | + | self.offset.load(Ordering::Relaxed) |
|
| 472 | + | } |
|
| 473 | + | ||
| 474 | + | fn set_offset(&self, offset: usize) -> bool { |
|
| 475 | + | let previous = self.offset(); |
|
| 476 | + | let next = offset.min(tui::viewport::max_offset( |
|
| 477 | + | self.entries.len(), |
|
| 478 | + | self.visible_rows.load(Ordering::Relaxed), |
|
| 479 | + | )); |
|
| 480 | + | self.offset.store(next, Ordering::Relaxed); |
|
| 481 | + | next != previous |
|
| 482 | + | } |
|
| 483 | + | ||
| 484 | + | fn scroll(&self, delta: isize) -> bool { |
|
| 485 | + | let previous = self.offset(); |
|
| 486 | + | let next = if delta.is_negative() { |
|
| 487 | + | previous.saturating_sub(delta.unsigned_abs()) |
|
| 488 | + | } else { |
|
| 489 | + | previous.saturating_add(delta as usize) |
|
| 490 | + | }; |
|
| 491 | + | self.set_offset(next) |
|
| 492 | + | } |
|
| 493 | + | ||
| 494 | + | fn show_selection(&self) { |
|
| 495 | + | self.set_offset( |
|
| 496 | + | self.selection |
|
| 497 | + | .view( |
|
| 498 | + | self.entries.len(), |
|
| 499 | + | self.visible_rows.load(Ordering::Relaxed), |
|
| 500 | + | tui::viewport::Placement::Margin { |
|
| 501 | + | before: 2, |
|
| 502 | + | after: 2, |
|
| 503 | + | }, |
|
| 504 | + | ) |
|
| 505 | + | .offset, |
|
| 506 | + | ); |
|
| 507 | + | } |
|
| 508 | + | ||
| 509 | + | fn select_path(&mut self, path: &Path) { |
|
| 510 | + | if let Some(index) = self.entries.iter().position(|entry| entry.path == path) { |
|
| 511 | + | self.selection.select(index, self.entries.len()); |
|
| 512 | + | self.show_selection(); |
|
| 513 | + | } |
|
| 514 | + | } |
|
| 515 | + | ||
| 516 | + | fn move_selection(&mut self, delta: isize) -> bool { |
|
| 517 | + | let changed = self.selection.move_by(delta, self.entries.len()); |
|
| 518 | + | if changed { |
|
| 519 | + | self.show_selection(); |
|
| 520 | + | } |
|
| 521 | + | changed |
|
| 522 | + | } |
|
| 523 | + | ||
| 524 | + | fn select_first(&mut self) -> bool { |
|
| 525 | + | let changed = self.selection.select_first(); |
|
| 526 | + | if changed { |
|
| 527 | + | self.show_selection(); |
|
| 528 | + | } |
|
| 529 | + | changed |
|
| 530 | + | } |
|
| 531 | + | ||
| 532 | + | fn select_last(&mut self) -> bool { |
|
| 533 | + | let changed = self.selection.select_last(self.entries.len()); |
|
| 534 | + | if changed { |
|
| 535 | + | self.show_selection(); |
|
| 536 | + | } |
|
| 537 | + | changed |
|
| 538 | + | } |
|
| 539 | + | } |
|
| 540 | + | ||
| 541 | + | #[derive(Debug)] |
|
| 542 | + | struct Entry { |
|
| 543 | + | path: PathBuf, |
|
| 544 | + | name: String, |
|
| 545 | + | is_dir: bool, |
|
| 546 | + | len: u64, |
|
| 547 | + | modified: Option<SystemTime>, |
|
| 548 | + | } |
|
| 549 | + | ||
| 550 | + | impl Entry { |
|
| 551 | + | fn read(path: PathBuf) -> io::Result<Self> { |
|
| 552 | + | let metadata = fs::symlink_metadata(&path)?; |
|
| 553 | + | let name = path |
|
| 554 | + | .file_name() |
|
| 555 | + | .and_then(OsStr::to_str) |
|
| 556 | + | .unwrap_or("?") |
|
| 557 | + | .to_owned(); |
|
| 558 | + | ||
| 559 | + | Ok(Self { |
|
| 560 | + | path, |
|
| 561 | + | name, |
|
| 562 | + | is_dir: metadata.is_dir(), |
|
| 563 | + | len: metadata.len(), |
|
| 564 | + | modified: metadata.modified().ok(), |
|
| 565 | + | }) |
|
| 566 | + | } |
|
| 567 | + | ||
| 568 | + | fn kind(&self) -> &'static str { |
|
| 569 | + | if self.is_dir { "directory" } else { "file" } |
|
| 570 | + | } |
|
| 571 | + | } |
|
| 572 | + | ||
| 573 | + | #[derive(Debug)] |
|
| 574 | + | struct ColumnWidget<'a> { |
|
| 575 | + | column: &'a Column, |
|
| 576 | + | active: bool, |
|
| 577 | + | } |
|
| 578 | + | ||
| 579 | + | impl Widget for ColumnWidget<'_> { |
|
| 580 | + | fn size(&self, parent: tui::Constraint) -> Size { |
|
| 581 | + | Size::new(COLUMN_WIDTH, parent.max.rows) |
|
| 582 | + | } |
|
| 583 | + | ||
| 584 | + | fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { |
|
| 585 | + | let border = if self.active { |
|
| 586 | + | ACTIVE_BORDER_COLOR |
|
| 587 | + | } else { |
|
| 588 | + | INACTIVE_BORDER_COLOR |
|
| 589 | + | }; |
|
| 590 | + | let title = title_for(&self.column.path); |
|
| 591 | + | let body = ColumnBody { |
|
| 592 | + | column: self.column, |
|
| 593 | + | active: self.active, |
|
| 594 | + | }; |
|
| 595 | + | Block::new(body) |
|
| 596 | + | .border_style(Border::new(border)) |
|
| 597 | + | .title(Line::new(text::bold(title))) |
|
| 598 | + | .render(area, buf); |
|
| 599 | + | } |
|
| 600 | + | } |
|
| 601 | + | ||
| 602 | + | #[derive(Debug)] |
|
| 603 | + | struct ColumnBody<'a> { |
|
| 604 | + | column: &'a Column, |
|
| 605 | + | active: bool, |
|
| 606 | + | } |
|
| 607 | + | ||
| 608 | + | impl Widget for ColumnBody<'_> { |
|
| 609 | + | fn size(&self, parent: tui::Constraint) -> Size { |
|
| 610 | + | Size::new(parent.max.cols, parent.max.rows) |
|
| 611 | + | } |
|
| 612 | + | ||
| 613 | + | fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { |
|
| 614 | + | if area.rows == 0 { |
|
| 615 | + | return; |
|
| 616 | + | } |
|
| 617 | + | self.column.set_visible_rows(area.rows); |
|
| 618 | + | ||
| 619 | + | let lines = self.column.entries.iter().map(entry_line); |
|
| 620 | + | List::new(lines) |
|
| 621 | + | .active(self.active) |
|
| 622 | + | .selected_styles( |
|
| 623 | + | Style::default().bg(ACTIVE_SELECTION_BG_COLOR), |
|
| 624 | + | Style::default().bg(INACTIVE_SELECTION_BG_COLOR), |
|
| 625 | + | ) |
|
| 626 | + | .selected(self.column.selection.selected) |
|
| 627 | + | .offset(self.column.offset()) |
|
| 628 | + | .empty(Line::new(text::dim("empty directory")).style(Style::default().italic())) |
|
| 629 | + | .placement(tui::viewport::Placement::Margin { |
|
| 630 | + | before: 2, |
|
| 631 | + | after: 2, |
|
| 632 | + | }) |
|
| 633 | + | .scrollbar(finder_scrollbar_style(self.active)) |
|
| 634 | + | .render(area, buf); |
|
| 635 | + | } |
|
| 636 | + | } |
|
| 637 | + | ||
| 638 | + | /// Builds the visible line for one directory entry. |
|
| 639 | + | fn entry_line(entry: &Entry) -> Line { |
|
| 640 | + | if entry.is_dir { |
|
| 641 | + | Line::new(Paint::new(format!("{}/", entry.name)).fg(DIRECTORY_COLOR)) |
|
| 642 | + | } else { |
|
| 643 | + | Line::new(Paint::new(entry.name.as_str())) |
|
| 644 | + | } |
|
| 645 | + | } |
|
| 646 | + | ||
| 647 | + | /// Creates the scrollbar style used by finder columns and preview panes. |
|
| 648 | + | fn finder_scrollbar_style(active: bool) -> ScrollbarStyle { |
|
| 649 | + | ScrollbarStyle::new( |
|
| 650 | + | Cell::new('โ', Style::new(SCROLLBAR_TRACK_COLOR)), |
|
| 651 | + | Cell::new( |
|
| 652 | + | 'โ', |
|
| 653 | + | Style::new(if active { |
|
| 654 | + | SCROLLBAR_ACTIVE_THUMB_COLOR |
|
| 655 | + | } else { |
|
| 656 | + | SCROLLBAR_INACTIVE_THUMB_COLOR |
|
| 657 | + | }), |
|
| 658 | + | ), |
|
| 659 | + | ) |
|
| 660 | + | } |
|
| 661 | + | ||
| 662 | + | /// Renders the preview pane for an entry and returns its scroll metrics. |
|
| 663 | + | fn render_preview( |
|
| 664 | + | entry: &Entry, |
|
| 665 | + | active: bool, |
|
| 666 | + | offset: usize, |
|
| 667 | + | area: Rect, |
|
| 668 | + | buf: &mut tui::Buffer, |
|
| 669 | + | ) -> ScrollMetrics { |
|
| 670 | + | let border = if active { |
|
| 671 | + | ACTIVE_BORDER_COLOR |
|
| 672 | + | } else { |
|
| 673 | + | INACTIVE_BORDER_COLOR |
|
| 674 | + | }; |
|
| 675 | + | let metrics = Mutex::new(ScrollMetrics::default()); |
|
| 676 | + | let mut stack = VStack::default() |
|
| 677 | + | .border(Some(Border::new(border))) |
|
| 678 | + | .padding(1) |
|
| 679 | + | .child(metadata_table(entry)); |
|
| 680 | + | ||
| 681 | + | if let Some(preview) = file_preview(entry) { |
|
| 682 | + | stack |
|
| 683 | + | .divider_cell(Cell::new('โ', Style::new(border))) |
|
| 684 | + | .fill(PreviewScroll { |
|
| 685 | + | preview: &preview, |
|
| 686 | + | active, |
|
| 687 | + | offset, |
|
| 688 | + | metrics: &metrics, |
|
| 689 | + | }) |
|
| 690 | + | .render(area, buf); |
|
| 691 | + | } else { |
|
| 692 | + | stack.render(area, buf); |
|
| 693 | + | } |
|
| 694 | + | render_block_title(&entry.name, area, buf); |
|
| 695 | + | metrics.into_inner().unwrap_or_else(PoisonError::into_inner) |
|
| 696 | + | } |
|
| 697 | + | ||
| 698 | + | /// A scrollable text body that records its scroll metrics as it renders. |
|
| 699 | + | #[derive(Debug)] |
|
| 700 | + | struct PreviewScroll<'a> { |
|
| 701 | + | preview: &'a str, |
|
| 702 | + | active: bool, |
|
| 703 | + | offset: usize, |
|
| 704 | + | metrics: &'a Mutex<ScrollMetrics>, |
|
| 705 | + | } |
|
| 706 | + | ||
| 707 | + | impl Widget for PreviewScroll<'_> { |
|
| 708 | + | fn size(&self, parent: tui::Constraint) -> Size { |
|
| 709 | + | Size::new(parent.max.cols, parent.max.rows) |
|
| 710 | + | } |
|
| 711 | + | ||
| 712 | + | fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { |
|
| 713 | + | let mut scroll = ScrollView::new(area, self.offset, |cols| { |
|
| 714 | + | preview_file_rows(self.preview, cols) |
|
| 715 | + | }) |
|
| 716 | + | .scrollbar(finder_scrollbar_style(self.active)); |
|
| 717 | + | *self.metrics.lock().unwrap_or_else(PoisonError::into_inner) = scroll.metrics(area); |
|
| 718 | + | scroll.render(area, buf); |
|
| 719 | + | } |
|
| 720 | + | } |
|
| 721 | + | ||
| 722 | + | /// Renders a block title onto an existing border. |
|
| 723 | + | fn render_block_title(title: &str, area: Rect, buf: &mut tui::Buffer) { |
|
| 724 | + | if area.cols <= 4 { |
|
| 725 | + | return; |
|
| 726 | + | } |
|
| 727 | + | let title = Line::new(text::bold(title)).truncated(area.cols.saturating_sub(4), "โฆ"); |
|
| 728 | + | buf.set_line(area.x + 2, area.y, &title); |
|
| 729 | + | } |
|
| 730 | + | ||
| 731 | + | /// Builds the scrollable file preview rows. |
|
| 732 | + | fn preview_file_rows(preview: &str, cols: usize) -> Vec<Line> { |
|
| 733 | + | TextArea::new(preview.to_owned()) |
|
| 734 | + | .wrap(cols.saturating_sub(2)) |
|
| 735 | + | .lines() |
|
| 736 | + | .map(|line| Line::new(Paint::new(line).fg(PREVIEW_TEXT_COLOR)).inset(cols)) |
|
| 737 | + | .collect() |
|
| 738 | + | } |
|
| 739 | + | ||
| 740 | + | /// Builds the metadata table for a previewed entry. |
|
| 741 | + | fn metadata_table(entry: &Entry) -> Table<2, Line> { |
|
| 742 | + | let mut table = Table::new(TableOptions { |
|
| 743 | + | spacing: 3, |
|
| 744 | + | ..TableOptions::default() |
|
| 745 | + | }); |
|
| 746 | + | table.push([ |
|
| 747 | + | Line::new(Paint::new("kind").fg(METADATA_LABEL_COLOR)), |
|
| 748 | + | Line::new(Paint::new(entry.kind()).fg(METADATA_VALUE_COLOR)), |
|
| 749 | + | ]); |
|
| 750 | + | table.push([ |
|
| 751 | + | Line::new(Paint::new("size").fg(METADATA_LABEL_COLOR)), |
|
| 752 | + | Line::new(Paint::new(size_text(entry)).fg(METADATA_VALUE_COLOR)), |
|
| 753 | + | ]); |
|
| 754 | + | table.push([ |
|
| 755 | + | Line::new(Paint::new("modified").fg(METADATA_LABEL_COLOR)), |
|
| 756 | + | Line::new(Paint::new(modified_text(entry.modified)).fg(METADATA_VALUE_COLOR)), |
|
| 757 | + | ]); |
|
| 758 | + | ||
| 759 | + | table |
|
| 760 | + | } |
|
| 761 | + | ||
| 762 | + | /// Reads the text preview for a non-empty file entry. |
|
| 763 | + | fn file_preview(entry: &Entry) -> Option<String> { |
|
| 764 | + | if entry.is_dir { |
|
| 765 | + | return None; |
|
| 766 | + | } |
|
| 767 | + | let preview = fs::read_to_string(&entry.path).ok()?; |
|
| 768 | + | if preview.is_empty() { |
|
| 769 | + | None |
|
| 770 | + | } else { |
|
| 771 | + | Some(preview) |
|
| 772 | + | } |
|
| 773 | + | } |
|
| 774 | + | ||
| 775 | + | /// Builds the top header line for the current root. |
|
| 776 | + | fn header_line(app: &Browser) -> impl Widget { |
|
| 777 | + | let current = app.root.display().to_string(); |
|
| 778 | + | ||
| 779 | + | HeaderLine { current } |
|
| 780 | + | } |
|
| 781 | + | ||
| 782 | + | #[derive(Debug)] |
|
| 783 | + | struct HeaderLine { |
|
| 784 | + | current: String, |
|
| 785 | + | } |
|
| 786 | + | ||
| 787 | + | impl Widget for HeaderLine { |
|
| 788 | + | fn size(&self, parent: tui::Constraint) -> Size { |
|
| 789 | + | Size::new(parent.max.cols, 1) |
|
| 790 | + | } |
|
| 791 | + | ||
| 792 | + | fn render(&mut self, area: Rect, buf: &mut tui::Buffer) { |
|
| 793 | + | let style = Style::new(HEADER_COLOR).bold(); |
|
| 794 | + | let line = Line::new(Paint::new(self.current.as_str()).with_style(style)) |
|
| 795 | + | .truncated(area.cols, "โฆ"); |
|
| 796 | + | let x = area.right().saturating_sub(line.width()); |
|
| 797 | + | buf.set_line(x, area.y, &line); |
|
| 798 | + | } |
|
| 799 | + | } |
|
| 800 | + | ||
| 801 | + | /// Builds the footer line for current focus and error state. |
|
| 802 | + | fn footer_line(app: &Browser) -> impl Widget { |
|
| 803 | + | if let Some(error) = app.error.as_deref() { |
|
| 804 | + | return Line::new(Paint::new(error).fg(ERROR_COLOR)); |
|
| 805 | + | } |
|
| 806 | + | ||
| 807 | + | let mut line = Line::default(); |
|
| 808 | + | footer_action(&mut line, "q", "quit"); |
|
| 809 | + | if app.focus == Focus::Preview { |
|
| 810 | + | footer_action(&mut line, "up/down", "scroll"); |
|
| 811 | + | footer_action(&mut line, "space", "half page"); |
|
| 812 | + | footer_action(&mut line, "left/backspace", "columns"); |
|
| 813 | + | } else { |
|
| 814 | + | footer_action(&mut line, "up/down", "select"); |
|
| 815 | + | footer_action(&mut line, "right/enter", "open/preview"); |
|
| 816 | + | footer_action(&mut line, "left/backspace", "remove column"); |
|
| 817 | + | } |
|
| 818 | + | footer_action(&mut line, "home/end", "jump"); |
|
| 819 | + | line |
|
| 820 | + | } |
|
| 821 | + | ||
| 822 | + | /// Appends one key/action pair to the footer line. |
|
| 823 | + | fn footer_action(line: &mut Line, key: &'static str, action: &'static str) { |
|
| 824 | + | if line.width() > 0 { |
|
| 825 | + | line.push(Paint::new(" ").fg(FOOTER_SEPARATOR_COLOR)); |
|
| 826 | + | } |
|
| 827 | + | line.push(Paint::new(key).fg(FOOTER_KEY_COLOR)); |
|
| 828 | + | line.push(Paint::new(" ").fg(FOOTER_SEPARATOR_COLOR)); |
|
| 829 | + | line.push(Paint::new(action).fg(FOOTER_ACTION_COLOR)); |
|
| 830 | + | } |
|
| 831 | + | ||
| 832 | + | /// Returns how many browser columns fit beside the preview pane. |
|
| 833 | + | fn visible_column_count(cols: usize, total: usize) -> usize { |
|
| 834 | + | if total == 0 { |
|
| 835 | + | return 0; |
|
| 836 | + | } |
|
| 837 | + | let cols_for_browser = cols.saturating_sub(PREVIEW_MIN_WIDTH); |
|
| 838 | + | let fit = (cols_for_browser / COLUMN_WIDTH).max(1); |
|
| 839 | + | ||
| 840 | + | fit.min(total) |
|
| 841 | + | } |
|
| 842 | + | ||
| 843 | + | /// Returns a display title for a path. |
|
| 844 | + | fn title_for(path: &Path) -> String { |
|
| 845 | + | let mut title = path |
|
| 846 | + | .file_name() |
|
| 847 | + | .and_then(OsStr::to_str) |
|
| 848 | + | .map(str::to_owned) |
|
| 849 | + | .unwrap_or_else(|| path.display().to_string()); |
|
| 850 | + | if path.is_dir() && !title.ends_with('/') { |
|
| 851 | + | title.push('/'); |
|
| 852 | + | } |
|
| 853 | + | title |
|
| 854 | + | } |
|
| 855 | + | ||
| 856 | + | /// Returns a display size for a directory entry. |
|
| 857 | + | fn size_text(entry: &Entry) -> String { |
|
| 858 | + | if entry.is_dir { |
|
| 859 | + | return String::from("--"); |
|
| 860 | + | } |
|
| 861 | + | fmt::human_size(entry.len) |
|
| 862 | + | } |
|
| 863 | + | ||
| 864 | + | /// Returns a relative modified-time label. |
|
| 865 | + | fn modified_text(modified: Option<SystemTime>) -> String { |
|
| 866 | + | let Some(modified) = modified else { |
|
| 867 | + | return String::from("unknown"); |
|
| 868 | + | }; |
|
| 869 | + | fmt::relative_time(SystemTime::now(), modified) |
|
| 870 | + | } |
crates/tui-core/src/app.rs
+3 -3
| 16 | 16 | ||
| 17 | 17 | /// Updates application state from an event. |
|
| 18 | 18 | fn update(&mut self, event: Event<Self::Event>) -> Control; |
|
| 19 | 19 | ||
| 20 | 20 | /// Renders application state. |
|
| 21 | - | fn render(&self, frame: &mut Frame<'_>); |
|
| 21 | + | fn render(&mut self, frame: &mut Frame<'_>); |
|
| 22 | 22 | } |
|
| 23 | 23 | ||
| 24 | 24 | /// Control returned by [`App::update`]. |
|
| 25 | 25 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
|
| 26 | 26 | pub enum Control { |
| 79 | 79 | Event::Key(Key::Esc) => Control::Quit, |
|
| 80 | 80 | _ => Control::Continue, |
|
| 81 | 81 | } |
|
| 82 | 82 | } |
|
| 83 | 83 | ||
| 84 | - | fn render(&self, frame: &mut Frame<'_>) { |
|
| 84 | + | fn render(&mut self, frame: &mut Frame<'_>) { |
|
| 85 | 85 | frame.render_widget(Label::from(Paint::new(self.value)), frame.area); |
|
| 86 | 86 | } |
|
| 87 | 87 | } |
|
| 88 | 88 | ||
| 89 | 89 | #[test] |
| 122 | 122 | _ => {} |
|
| 123 | 123 | } |
|
| 124 | 124 | Control::Wait |
|
| 125 | 125 | } |
|
| 126 | 126 | ||
| 127 | - | fn render(&self, frame: &mut Frame<'_>) { |
|
| 127 | + | fn render(&mut self, frame: &mut Frame<'_>) { |
|
| 128 | 128 | frame.render_widget(Label::new("r"), frame.area); |
|
| 129 | 129 | } |
|
| 130 | 130 | } |
|
| 131 | 131 | ||
| 132 | 132 | let backend = TestBackend::new(Size::new(2, 1)); |
crates/tui-termion/src/term.rs
+1 -1
| 226 | 226 | ||
| 227 | 227 | fn update(&mut self, _: Event<Self::Event>) -> Control { |
|
| 228 | 228 | Control::Continue |
|
| 229 | 229 | } |
|
| 230 | 230 | ||
| 231 | - | fn render(&self, frame: &mut tui_core::Frame<'_>) { |
|
| 231 | + | fn render(&mut self, frame: &mut tui_core::Frame<'_>) { |
|
| 232 | 232 | frame.render_widget(Label::new("x"), frame.area); |
|
| 233 | 233 | } |
|
| 234 | 234 | } |
|
| 235 | 235 | let mut app = ResizeAware; |
|
| 236 | 236 | let mut redraw = false; |
src/fmt.rs
added
+82 -0
| 1 | + | //! Plain string formatting helpers shared across Rustik crates. |
|
| 2 | + | ||
| 3 | + | use std::time::SystemTime; |
|
| 4 | + | ||
| 5 | + | /// Formats byte counts using compact binary units. |
|
| 6 | + | pub fn human_size(bytes: u64) -> String { |
|
| 7 | + | const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; |
|
| 8 | + | ||
| 9 | + | let mut value = bytes as f64; |
|
| 10 | + | let mut unit = 0; |
|
| 11 | + | while value >= 1024.0 && unit + 1 < UNITS.len() { |
|
| 12 | + | value /= 1024.0; |
|
| 13 | + | unit += 1; |
|
| 14 | + | } |
|
| 15 | + | if unit == 0 { |
|
| 16 | + | format!("{bytes} {}", UNITS[unit]) |
|
| 17 | + | } else { |
|
| 18 | + | format!("{value:.1} {}", UNITS[unit]) |
|
| 19 | + | } |
|
| 20 | + | } |
|
| 21 | + | ||
| 22 | + | /// Returns a relative time label from `now` to `time`. |
|
| 23 | + | pub fn relative_time(now: SystemTime, time: SystemTime) -> String { |
|
| 24 | + | let Ok(age) = now.duration_since(time) else { |
|
| 25 | + | return String::from("in the future"); |
|
| 26 | + | }; |
|
| 27 | + | let seconds = age.as_secs(); |
|
| 28 | + | if seconds < 60 { |
|
| 29 | + | String::from("just now") |
|
| 30 | + | } else if seconds < 60 * 60 { |
|
| 31 | + | format!("{}m ago", seconds / 60) |
|
| 32 | + | } else if seconds < 60 * 60 * 24 { |
|
| 33 | + | format!("{}h ago", seconds / 60 / 60) |
|
| 34 | + | } else { |
|
| 35 | + | format!("{}d ago", seconds / 60 / 60 / 24) |
|
| 36 | + | } |
|
| 37 | + | } |
|
| 38 | + | ||
| 39 | + | #[cfg(test)] |
|
| 40 | + | mod tests { |
|
| 41 | + | use super::*; |
|
| 42 | + | use std::time::Duration; |
|
| 43 | + | ||
| 44 | + | #[test] |
|
| 45 | + | fn human_size_formats_compact_binary_units() { |
|
| 46 | + | assert_eq!(human_size(0), "0 B"); |
|
| 47 | + | assert_eq!(human_size(999), "999 B"); |
|
| 48 | + | assert_eq!(human_size(1024), "1.0 KB"); |
|
| 49 | + | assert_eq!(human_size(1536), "1.5 KB"); |
|
| 50 | + | assert_eq!(human_size(1024 * 1024), "1.0 MB"); |
|
| 51 | + | assert_eq!(human_size(1024 * 1024 * 1024), "1.0 GB"); |
|
| 52 | + | } |
|
| 53 | + | ||
| 54 | + | #[test] |
|
| 55 | + | fn relative_time_formats_past_ranges() { |
|
| 56 | + | let now = SystemTime::UNIX_EPOCH + Duration::from_secs(60 * 60 * 24 * 2); |
|
| 57 | + | ||
| 58 | + | assert_eq!(relative_time(now, now), "just now"); |
|
| 59 | + | assert_eq!( |
|
| 60 | + | relative_time(now, now - Duration::from_secs(5 * 60)), |
|
| 61 | + | "5m ago" |
|
| 62 | + | ); |
|
| 63 | + | assert_eq!( |
|
| 64 | + | relative_time(now, now - Duration::from_secs(3 * 60 * 60)), |
|
| 65 | + | "3h ago" |
|
| 66 | + | ); |
|
| 67 | + | assert_eq!( |
|
| 68 | + | relative_time(now, now - Duration::from_secs(2 * 60 * 60 * 24)), |
|
| 69 | + | "2d ago" |
|
| 70 | + | ); |
|
| 71 | + | } |
|
| 72 | + | ||
| 73 | + | #[test] |
|
| 74 | + | fn relative_time_formats_future_times() { |
|
| 75 | + | let now = SystemTime::UNIX_EPOCH; |
|
| 76 | + | ||
| 77 | + | assert_eq!( |
|
| 78 | + | relative_time(now, now + Duration::from_secs(1)), |
|
| 79 | + | "in the future" |
|
| 80 | + | ); |
|
| 81 | + | } |
|
| 82 | + | } |
src/lib.rs
+3 -0
| 6 | 6 | //! |
|
| 7 | 7 | #![deny(unsafe_code)] |
|
| 8 | 8 | #![warn(missing_docs)] |
|
| 9 | 9 | #![warn(clippy::unwrap_used)] |
|
| 10 | 10 | ||
| 11 | + | /// Plain string formatting helpers. |
|
| 12 | + | pub mod fmt; |
|
| 13 | + | ||
| 11 | 14 | /// Re-export of the facade crate. |
|
| 12 | 15 | pub use rustik_tui as tui; |
|
| 13 | 16 | ||
| 14 | 17 | /// Re-export of the unified diff parser and viewer crate. |
|
| 15 | 18 | #[cfg(feature = "diff")] |