Skip to main content

file_browser/
file_browser.rs

1//! A file browser: folders in a tree on the left, the current folder's files in a table on the
2//! right (sortable by any column, by several with Shift), and the folder's path in an editable
3//! bar above both. Double-click enters a folder; a file opens in the system's program for it.
4//!   cargo run -p taut --example file_browser [-- <folder>]
5//! Keys: Enter opens the focused row, Backspace goes up, Alt+Left back, Ctrl+L to the path, F5
6//! refreshes.
7#![windows_subsystem = "windows"]
8use std::path::{Path, PathBuf};
9use std::time::UNIX_EPOCH;
10use taut::{Align, Column, Date, Icon, Key, Length, Mods, Selection, Table, Ui, Window};
11
12const UP: Icon = Icon::line("M8 12.5v-9M4 7.5l4-4 4 4");
13const BACK: Icon = Icon::line("M12.5 8h-9M7.5 4l-4 4 4 4");
14const FOLDER: Icon = Icon::line("M2 4.5a1 1 0 0 1 1-1h3l1.5 1.5H13a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1z");
15const FILE: Icon = Icon::line("M4 2h5l3 3v9H4zM9 2v3h3");
16
17/// A file or a folder in the folder that is shown.
18pub struct Entry {
19    name: String,
20    folder: bool,
21    /// How many bytes it holds (nought for a folder), and the day it was last changed.
22    size: u64,
23    changed: Option<Date>,
24}
25
26/// A folder in the tree: the tree is a list, each folder after the one it is in, and how
27/// deep it is says which that is.
28pub struct TreeFolder {
29    path: PathBuf,
30    depth: usize,
31    open: bool,
32    /// The folders in it have been read, and follow it in the list.
33    read: bool,
34}
35
36/// Everything the browser keeps.
37pub struct Browser {
38    tree: Vec<TreeFolder>,
39    /// The folder that is shown, what is in it, in the order the table asks for, and what
40    /// the person did to the table and which rows are selected.
41    folder: PathBuf,
42    entries: Vec<Entry>,
43    table: Table,
44    selection: Selection,
45    /// What the path bar holds, and what is wrong with it.
46    path: String,
47    wrong: Option<String>,
48    /// The folders that were shown before this one, to go back to.
49    before: Vec<PathBuf>,
50    /// How wide the tree is.
51    side: f32,
52    /// A file to open in the system's program for it: `main` does that after the run.
53    opened: Option<PathBuf>,
54}
55
56impl Browser {
57    /// A browser that shows `folder`, with the tree starting there.
58    pub fn new(folder: PathBuf) -> Browser {
59        let tree = vec![TreeFolder { path: folder.clone(), depth: 0, open: true, read: false }];
60        let mut browser = Browser {
61            tree,
62            folder: PathBuf::new(),
63            entries: Vec::new(),
64            table: Table::default(),
65            selection: Selection::default(),
66            path: String::new(),
67            wrong: None,
68            before: Vec::new(),
69            side: 200.0,
70            opened: None,
71        };
72        browser.read_branch(0);
73        browser.go(folder);
74        browser.before.clear();
75        browser
76    }
77
78    /// Shows another folder; where it is no folder, says so and stays.
79    fn go(&mut self, folder: PathBuf) {
80        let Ok(list) = std::fs::read_dir(&folder) else {
81            self.wrong = Some(format!("{} is not a folder that can be read", folder.display()));
82            return;
83        };
84        self.entries = list.flatten().filter_map(|entry| entry_of(&entry)).collect();
85        sort(&mut self.entries, &self.table.sort);
86        let gone = std::mem::replace(&mut self.folder, folder);
87        if !gone.as_os_str().is_empty() && gone != self.folder {
88            self.before.push(gone);
89        }
90        (self.path, self.wrong, self.selection) = (self.folder.display().to_string(), None, Selection::default());
91    }
92
93    /// Reads the folders in the tree folder at `at` into the tree, after it.
94    fn read_branch(&mut self, at: usize) {
95        let (depth, mut inside) = (self.tree[at].depth + 1, Vec::new());
96        for entry in std::fs::read_dir(&self.tree[at].path).into_iter().flatten().flatten() {
97            if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
98                inside.push(TreeFolder { path: entry.path(), depth, open: false, read: false });
99            }
100        }
101        inside.sort_by_key(|folder| name_of(&folder.path).to_lowercase());
102        self.tree.splice(at + 1..at + 1, inside);
103        self.tree[at].read = true;
104    }
105
106    /// Opens what is in the row `row`: goes into a folder, has the system open a file.
107    fn open(&mut self, row: usize) {
108        let (path, folder) = (self.folder.join(&self.entries[row].name), self.entries[row].folder);
109        if folder {
110            self.go(path);
111        } else {
112            self.opened = Some(path);
113        }
114    }
115}
116
117/// What the browser shows of a file or a folder; nothing for what cannot be read.
118fn entry_of(entry: &std::fs::DirEntry) -> Option<Entry> {
119    let about = entry.metadata().ok()?;
120    let days = about.modified().ok()?.duration_since(UNIX_EPOCH).ok().map(|since| Date::from_days((since.as_secs() / 86_400) as i64));
121    Some(Entry { name: entry.file_name().to_string_lossy().into_owned(), folder: about.is_dir(), size: if about.is_dir() { 0 } else { about.len() }, changed: days })
122}
123
124/// Puts the entries in the order the table asks for: folders first, then by each column it
125/// is sorted by, the first counting most; by name where it says nothing.
126fn sort(entries: &mut [Entry], by: &[(usize, bool)]) {
127    entries.sort_by(|a, b| {
128        let mut order = b.folder.cmp(&a.folder);
129        for (column, down) in by.iter().chain([&(0, false)]) {
130            let one = match column {
131                1 => a.size.cmp(&b.size),
132                2 => a.changed.map(Date::days).cmp(&b.changed.map(Date::days)),
133                3 => kind(a).cmp(&kind(b)),
134                _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
135            };
136            order = order.then(if *down { one.reverse() } else { one });
137        }
138        order
139    });
140}
141
142/// The last part of a path: the name of a file or a folder.
143fn name_of(path: &Path) -> String {
144    path.file_name().map_or_else(|| path.display().to_string(), |name| name.to_string_lossy().into_owned())
145}
146
147/// What kind of file it is, by its ending.
148fn kind(entry: &Entry) -> String {
149    match (entry.folder, entry.name.rsplit_once('.')) {
150        (true, _) => "Folder".into(),
151        (false, Some((before, ending))) if !before.is_empty() => ending.to_uppercase(),
152        _ => "File".into(),
153    }
154}
155
156/// A size as people read it.
157fn size(bytes: u64) -> String {
158    match bytes {
159        0..1_000 => format!("{bytes} B"),
160        1_000..1_000_000 => format!("{:.1} KB", bytes as f64 / 1e3),
161        1_000_000..1_000_000_000 => format!("{:.1} MB", bytes as f64 / 1e6),
162        _ => format!("{:.1} GB", bytes as f64 / 1e9),
163    }
164}
165
166pub fn describe(app: &mut Browser, ui: &mut Ui) {
167    let t = ui.theme;
168    ui.column().grow().open();
169    path_bar(app, ui);
170    ui.row().grow().open();
171    ui.column().w(Length::Px(app.side)).h(Length::Grow(1.0)).scroll().pad(6.0).open();
172    tree(app, ui);
173    ui.close();
174    ui.splitter(&mut app.side, 120.0, 400.0);
175    ui.column().grow().open();
176    table(app, ui);
177    ui.row().h(Length::Px(24.0)).pad((10.0, 0.0)).fill(t.panel).align(Align::Start, Align::Center).open();
178    ui.note(&format!("{} items, {} picked", app.entries.len(), app.selection.iter().count()));
179    ui.close();
180    ui.close();
181    ui.close();
182    ui.close();
183
184    // The keys that work wherever the keyboard is but in a box that is typed into.
185    if ui.keys("Alt+Left")
186        && let Some(folder) = app.before.pop()
187    {
188        app.go(folder);
189        app.before.pop(); // (going back is not one more step to go back from)
190        ui.rerun();
191    }
192    if ui.keys("F5") {
193        app.go(app.folder.clone());
194        app.before.pop();
195        ui.rerun();
196    }
197}
198
199/// The bar over everything: back, up, and the path, which is typed into to go there.
200fn path_bar(app: &mut Browser, ui: &mut Ui) {
201    let t = ui.theme;
202    ui.row().pad(6.0).gap(6.0).fill(t.panel).align(Align::Start, Align::Center).open();
203    ui.set_enabled(!app.before.is_empty());
204    let back = ui.icon_button(BACK, "Back").clicked;
205    ui.set_enabled(app.folder.parent().is_some());
206    let up = ui.icon_button(UP, "Up a folder").clicked;
207    ui.set_enabled(true);
208    let bar = ui.text_box(&mut app.path, "Path");
209    ui.close();
210    if let Some(wrong) = &app.wrong {
211        ui.row().pad((10.0, 4.0)).fill(t.red.with_alpha(0.15)).open();
212        ui.text(wrong, t.small_font, t.red);
213        ui.close();
214    }
215    if ui.keys("Ctrl+L") {
216        ui.set_focus(bar.id);
217        ui.select_all();
218    }
219    let parent = app.folder.parent().map(Path::to_path_buf);
220    let typed = bar.focused && ui.key(Key::Enter, Mods::NONE);
221    let backspace = !bar.focused && ui.key(Key::Backspace, Mods::NONE);
222    match (back, up || backspace, typed) {
223        (true, ..) => {
224            let folder = app.before.pop().unwrap_or_else(|| app.folder.clone());
225            app.go(folder);
226            app.before.pop();
227        }
228        (_, true, _) if parent.is_some() => app.go(parent.unwrap_or_default()),
229        (.., true) => app.go(PathBuf::from(app.path.trim())),
230        _ => return,
231    }
232    ui.rerun();
233}
234
235/// The tree of folders, the one shown selected. A press on a folder's heading shows it, and
236/// opens or folds what is in it; the arrows open and fold it without going there.
237fn tree(app: &mut Browser, ui: &mut Ui) {
238    // How deep each folder that is open in the window is: each is closed once the folders
239    // in it have been described. And how deep the folded one is whose folders are skipped.
240    let (mut open, mut folded, mut clicked, mut opened) = (Vec::new(), usize::MAX, None, None);
241    for at in 0..app.tree.len() {
242        let depth = app.tree[at].depth;
243        while open.last().is_some_and(|inner| *inner >= depth) {
244            open.pop();
245            ui.close();
246        }
247        if depth > folded {
248            continue;
249        }
250        let (name, shown) = (name_of(&app.tree[at].path), app.tree[at].path == app.folder);
251        let heading = ui.selectable_tree(&mut app.tree[at].open, &name, shown);
252        folded = if app.tree[at].open { usize::MAX } else { depth };
253        open.extend((folded == usize::MAX).then_some(depth));
254        clicked = clicked.or(heading.clicked.then(|| app.tree[at].path.clone()));
255        opened = opened.or((heading.changed && app.tree[at].open && !app.tree[at].read).then_some(at));
256    }
257    open.iter().for_each(|_| ui.close());
258    // (A folder that was opened has the folders in it read; a press shows it too.)
259    if let Some(at) = opened {
260        app.read_branch(at);
261        ui.rerun();
262    }
263    if let Some(folder) = clicked {
264        app.go(folder);
265        ui.rerun();
266    }
267}
268
269/// The table of what is in the folder that is shown.
270fn table(app: &mut Browser, ui: &mut Ui) {
271    let t = ui.theme;
272    // Each column as wide as its widest cell can be, in the letters of the day (they are the
273    // system's, at the size the person set); the name has what is left.
274    let mut wide = |widest: &str| ui.text_width(widest, t.font).ceil() + 4.0;
275    let columns = [Column::new("Name"), Column::new("Size").px(wide("999.9 KB")).align(Align::End), Column::new("Modified").px(wide("2026-12-31")), Column::new("Kind").px(wide("Folder"))];
276    let table = ui.table(&mut app.table, &columns);
277    if table.changed {
278        sort(&mut app.entries, &app.table.sort);
279        app.selection = Selection::default();
280    }
281    // (Enter on the table opens the row its cell is on.)
282    let mut opened = app.table.focused_cell.filter(|_| table.focused && ui.key(Key::Enter, Mods::NONE)).map(|[row, _]| row);
283    for row in ui.rows(app.entries.len(), 26.0) {
284        let entry = &app.entries[row];
285        let response = ui.selectable_row(row, app.selection.contains(row));
286        if response.clicked {
287            app.selection.click(row, ui.mods());
288        }
289        opened = opened.or(response.double_clicked.then_some(row));
290        ui.row().gap(6.0).align(Align::Start, Align::Center).open();
291        ui.el().icon(if entry.folder { FOLDER } else { FILE }, 16.0, if entry.folder { t.accent } else { t.text_dim }).show();
292        ui.label(&entry.name);
293        ui.close();
294        ui.label(&if entry.folder { String::new() } else { size(entry.size) });
295        ui.label(&entry.changed.map_or(String::new(), |day| day.to_string()));
296        ui.label(&kind(entry));
297        ui.close();
298    }
299    ui.close();
300    ui.close();
301    if let Some(row) = opened {
302        app.open(row);
303        ui.rerun();
304    }
305}
306
307fn main() {
308    let start = std::env::args_os().nth(1).map(PathBuf::from).or_else(std::env::home_dir).unwrap_or_else(|| PathBuf::from("."));
309    let mut app = Browser::new(start);
310    let window = Window { title: "Files", width: 860.0, height: 540.0, min_width: 420.0, min_height: 260.0, ..Default::default() };
311    taut::run(window, move |ui| {
312        describe(&mut app, ui);
313        // (A file is opened in the program the system has for files of its kind.)
314        if let Some(file) = app.opened.take() {
315            taut::open_with_system(file);
316        }
317    });
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use std::fs::{File, create_dir_all, write};
324    use std::time::{Duration, SystemTime};
325    use taut::Role;
326    use taut::testing::Trial;
327
328    /// A folder of known things: two folders, one with a folder in it, and three files of
329    /// known sizes, all last changed on known days.
330    fn made() -> PathBuf {
331        let home = std::env::temp_dir().join(format!("taut-files-{}", std::process::id())).join("home");
332        _ = std::fs::remove_dir_all(&home);
333        for folder in ["docs/old", "pictures"] {
334            create_dir_all(home.join(folder)).unwrap();
335        }
336        let day = |days: u64| SystemTime::UNIX_EPOCH + Duration::from_secs(days * 86_400 + 43_200);
337        for (name, bytes, days) in [("notes.txt", 3_400, 20_400), ("report.pdf", 120_000, 20_000), ("todo.txt", 12, 20_405), ("docs/plan.txt", 800, 20_401)] {
338            write(home.join(name), vec![b'x'; bytes]).unwrap();
339            File::options().write(true).open(home.join(name)).unwrap().set_modified(day(days)).unwrap();
340        }
341        home
342    }
343
344    #[test]
345    fn folders_are_gone_into_files_sorted_and_opened() {
346        let home = made();
347        let mut trial = Trial::new(Browser::new(home.clone()), describe);
348        trial.resize(760.0, 420.0, 1.0);
349        let names = |trial: &Trial<Browser>| trial.app.entries.iter().map(|entry| entry.name.clone()).collect::<Vec<_>>();
350        assert_eq!(names(&trial), ["docs", "pictures", "notes.txt", "report.pdf", "todo.txt"], "folders first, then by name");
351        assert!(trial.has(Role::Cell, "3.4 KB") && trial.has(Role::Cell, "2025-11-08"));
352
353        // By size, then the other way round: the folders stay first.
354        trial.press(Role::ColumnHeader, "Size");
355        assert_eq!(names(&trial)[2..], ["todo.txt", "notes.txt", "report.pdf"]);
356        trial.press(Role::ColumnHeader, "Size");
357        assert_eq!(names(&trial)[2..], ["report.pdf", "notes.txt", "todo.txt"]);
358        trial.save_png(std::env::temp_dir().join("taut-looks").join("files-sorted.png"));
359
360        // A double click on a folder goes into it; Backspace comes back up.
361        let docs = trial.center_of(Role::Cell, "docs");
362        trial.double_click(docs);
363        assert_eq!(trial.app.folder, home.join("docs"));
364        assert_eq!(names(&trial), ["old", "plan.txt"]);
365        assert_eq!(trial.find(Role::TextBox, "Path").value, home.join("docs").display().to_string());
366        trial.key("Backspace");
367        assert_eq!(trial.app.folder, home);
368
369        // A folder of the tree shows it, selected, and opens to show the folders in it.
370        trial.press(Role::TreeItem, "docs");
371        assert_eq!(trial.app.folder, home.join("docs"));
372        assert!(trial.has(Role::TreeItem, "old") && trial.find(Role::TreeItem, "docs").on == Some(true), "{}", trial.dump());
373        // The arrows fold and open it, and go nowhere.
374        trial.key("Left");
375        assert!(!trial.has(Role::TreeItem, "old") && trial.app.folder == home.join("docs"));
376        trial.key("Right");
377        assert!(trial.has(Role::TreeItem, "old") && trial.app.folder == home.join("docs"));
378        trial.key("Alt+Left");
379        assert_eq!(trial.app.folder, home);
380
381        // The path is typed into to go there; a path that is no folder is said to be one.
382        trial.fill("Path", &home.join("pictures").display().to_string());
383        trial.key("Enter");
384        assert_eq!(trial.app.folder, home.join("pictures"));
385        trial.fill("Path", "no such folder");
386        trial.key("Enter");
387        assert_eq!(trial.app.folder, home.join("pictures"));
388        assert!(trial.has(Role::Text, "no such folder is not a folder that can be read"));
389        trial.press(Role::Button, "Up a folder");
390        assert!(trial.app.wrong.is_none());
391
392        // A file is opened in the system's program for it: by a double click, and by Enter
393        // on the row that is selected.
394        let report = trial.center_of(Role::Cell, "report.pdf");
395        trial.double_click(report);
396        assert_eq!(trial.app.opened.take(), Some(home.join("report.pdf")));
397        trial.press(Role::Cell, "todo.txt");
398        trial.key("Enter");
399        assert_eq!(trial.app.opened.take(), Some(home.join("todo.txt")));
400        trial.save_png(std::env::temp_dir().join("taut-looks").join("files-opened.png"));
401        _ = std::fs::remove_dir_all(home.parent().unwrap());
402    }
403}