The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(tui): Open dialog, built-in text editor and explorer title buttons
bubu-dudu4450cac956f0
diff --git a/tui/README.md b/tui/README.mdindex 5ad6b21ed..ea4bc18d1 100644--- a/tui/README.md+++ b/tui/README.md@@ -34,7 +34,11 @@ systems. Installing or updating hn alone does not turn a computer into Harness OHarness OS also has a file manager, only there: `hn files [folder]` (Super+E) fills a terminal ofits own with a folder as big tiles or a list (`v`), its folder tree to the left, and VS Code'sexplorer menu on a right click: new files and folders, cut, copy, paste, duplicate, rename, and-delete to the Trash. Inside hn on the OS, `choose-file [-t pane] [folder]` shows it over a pane.+delete to the Trash. A text file opens in its own editor (Ctrl+S saves, Esc closes; `e` uses+`$EDITOR`). `hn files --open [folder]` (Super+O) is an Open dialog in+the Mac's manner: places, folders as columns with a preview, Search, Cancel and Open. A folder+opens in an explorer of its own kept inside it (`hn files --root DIR`), a text file in the+editor alone (`hn files --edit FILE`), each through `$HARNESS_FILES_LAUNCH` when it is set. Inside hn on the OS, `choose-file [-t pane] [folder]` shows it over a pane.Ordinary hn refuses both.diff --git a/tui/src/files.rs b/tui/src/files.rsindex 090bae50c..0cc77d402 100644--- a/tui/src/files.rs+++ b/tui/src/files.rs@@ -10,6 +10,8 @@//! are shown. A file opened goes to $EDITOR in a terminal split beside the pane. `hn files` is the//! same view filling a terminal of its own (standalone, at the end), the editor in that terminal.+mod dialog;+mod editor;mod ops;use std::collections::{HashMap, HashSet};@@ -119,9 +121,27 @@ impl Target {}}+/// The explorer title's buttons, as VS Code's: New File, New Folder, Refresh, Collapse All.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Head { NewFile, NewFolder, Refresh, Collapse }++impl Head {+ const ALL: [Head; 4] = [Head::NewFile, Head::NewFolder, Head::Refresh, Head::Collapse];+ /// Its icon: a Nerd Font codicon (nf-cod-new_file, new_folder, refresh, collapse_all), else letters.+ fn icon(self, nerd: bool) -> &'static str {+ match (self, nerd) {+ (Head::NewFile, true) => "\u{ea7f}", (Head::NewFolder, true) => "\u{ea80}", (Head::Refresh, true) => "\u{eb37}", (Head::Collapse, true) => "\u{eac5}",+ (Head::NewFile, false) => "+F", (Head::NewFolder, false) => "+D", (Head::Refresh, false) => "R", (Head::Collapse, false) => "-",+ }+ }+ fn tip(self) -> &'static str {+ match self { Head::NewFile => "New File…", Head::NewFolder => "New Folder…", Head::Refresh => "Refresh (C-r, F5)", Head::Collapse => "Collapse Folders in Explorer" }+ }+}+/// The context menu's actions.#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum Act { Open, NewFile, NewFolder, Terminal, Cut, Copy, Paste, Duplicate, CopyPath, CopyRelative, Rename, Delete, Hidden, View }+enum Act { Open, External, NewFile, NewFolder, Terminal, Cut, Copy, Paste, Duplicate, CopyPath, CopyRelative, Rename, Delete, Hidden, View }#[derive(Clone, Debug, PartialEq, Eq)]struct Item { label: String, key: &'static str, act: Act, on: bool }@@ -249,6 +269,16 @@ pub struct Files {confirm: Option<Confirm>,/// Where deleted things go: the home Trash.trash: PathBuf,+ /// Files open in the built-in editor (`hn files`), filling the view while one is; else (a+ /// pane's mode) in $EDITOR beside it.+ builtin: bool,+ editor: Option<Box<editor::Editor>>,+ /// `hn files --edit`: the editor alone, the program ending with it.+ exit_on_close: bool,+ /// The explorer's title button under the mouse: lit, and what it does said in the footer.+ head_hover: Option<Head>,+ /// `hn files --root` (what the Open dialog opens a folder in): kept inside its root.+ bounded: bool,}impl Files {@@ -257,7 +287,7 @@ impl Files {root: dir.clone(), cwd: dir.clone(), hidden: false, nerd, view: View::Gallery, listing: Listing::default(), counts: HashMap::new(),selected: 0, scroll: 0, focus: Focus::Grid, expanded: HashSet::new(), rows: Vec::new(), tree_sel: 0, tree_scroll: 0,follow: true, tree_follow: true, standalone: false, message: None, clip: None, menu: None, prompt: None, confirm: None,- trash: ops::trash_home(),+ trash: ops::trash_home(), builtin: false, editor: None, exit_on_close: false, head_hover: None, bounded: false,};f.go(dir, None);f@@ -271,7 +301,7 @@ impl Files {self.selected = select.and_then(|n| self.listing.entries.iter().position(|e| e.name == n)).unwrap_or(0);self.scroll = 0;self.follow = true;- if !dir.starts_with(&self.root) { self.root = dir.clone() }+ if !dir.starts_with(&self.root) && !self.bounded { self.root = dir.clone() }let mut up = Some(dir.as_path());while let Some(p) = up {self.expanded.insert(p.to_path_buf());@@ -315,6 +345,7 @@ impl Files {}fn up(&mut self) {+ if self.bounded && self.cwd == self.root { self.message = Some(format!("This is the top of '{}'", name_of(&self.root))); return }let from = name_of(&self.cwd);if let Some(parent) = self.cwd.parent().map(Path::to_path_buf) { self.go(parent, Some(&from)) }}@@ -323,7 +354,32 @@ impl Files {fn open_selected(&mut self) -> Outcome {let Some(e) = self.listing.entries.get(self.selected) else { return Outcome::None };let path = self.cwd.join(&e.name);- if e.dir { self.go(path, None); Outcome::None } else { Outcome::Edit(path) }+ if e.dir { self.go(path, None); Outcome::None } else { self.open_file(path) }+ }++ /// A file opened: in the built-in editor when it is text (else the footer says why not), or+ /// in $EDITOR beside a pane's view.+ fn open_file(&mut self, path: PathBuf) -> Outcome {+ if !self.builtin { return Outcome::Edit(path) }+ let name = name_of(&path);+ let title = path.strip_prefix(&self.root).ok().filter(|r| !r.as_os_str().is_empty()).map(|r| r.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string_lossy().into_owned());+ match editor::Editor::open(&path, title) {+ Ok(e) => self.editor = Some(Box::new(e)),+ Err(editor::Refusal::NotText) => self.message = Some(format!("Can't open '{name}': not a text file")),+ Err(editor::Refusal::TooLarge) => self.message = Some(format!("Can't open '{name}': too large to open here (e opens it in $EDITOR)")),+ Err(editor::Refusal::Unreadable(e)) => self.message = Some(format!("Can't open '{name}': {e}")),+ }+ Outcome::None+ }++ /// The editor's key, click or wheel done; closed, the folder read again.+ fn edited(&mut self, out: editor::EdOut) -> Outcome {+ match out {+ editor::EdOut::None => Outcome::None,+ editor::EdOut::Clipboard(t) => Outcome::Clipboard(t),+ editor::EdOut::Close if self.exit_on_close => Outcome::Exit,+ editor::EdOut::Close => { self.editor = None; self.reload(); Outcome::None }+ }}/// What the keys act on: the explorer's folder with it in focus, else the grid's entry — the@@ -379,6 +435,7 @@ impl Files {/// A key: to the confirmation, the name prompt or the menu while one is up, else the view's.fn press(&mut self, k: Chord, g: Geom) -> Outcome {self.message = None;+ if let Some(e) = self.editor.as_mut() { let out = e.key(k); return self.edited(out) }let out = if self.confirm.is_some() { self.confirm_key(k) }else if self.prompt.is_some() { self.prompt_key(k) }else if self.menu.is_some() { self.menu_key(k) }@@ -392,6 +449,7 @@ impl Files {let item = matches!(self.key_target(), Target::Item { .. });match () {_ if is_char(&k, 'q') || k.code == KeyCode::Esc || ctrl('g') => Outcome::Exit,+ _ if is_char(&k, 'e') && matches!(self.key_target(), Target::Item { dir: false, .. }) => self.act(Act::External, self.key_target()),_ if k.code == KeyCode::Tab || k.code == KeyCode::BackTab => {self.focus = if self.focus == Focus::Grid { Focus::Tree } else { Focus::Grid };self.tree_follow = true;@@ -409,6 +467,7 @@ impl Files {_ if ctrl('x') && item => self.act(Act::Cut, self.key_target()),_ if ctrl('d') && item => self.act(Act::Duplicate, self.key_target()),// (Pasted into the folder on show; with the explorer's keys, into its folder.)+ _ if ctrl('r') || k.code == KeyCode::F(5) => { self.head(Head::Refresh); Outcome::None }_ if ctrl('v') => {let t = if self.focus == Focus::Tree { self.key_target() } else { Target::Space(self.cwd.clone()) };self.act(Act::Paste, t)@@ -478,9 +537,10 @@ impl Files {let item = match &t { Target::Item { path, dir } => Some((path.clone(), *dir)), Target::Space(_) => None };match act {Act::Open => match t {- Target::Item { path, dir: false } => return Outcome::Edit(path),+ Target::Item { path, dir: false } => return self.open_file(path),Target::Item { path, .. } | Target::Space(path) => self.go(path, None),},+ Act::External => { if let Some((path, false)) = item { return Outcome::Edit(path) } }Act::NewFile | Act::NewFolder => {let ask = if act == Act::NewFile { Ask::NewFile } else { Ask::NewFolder };self.prompt = Some(Prompt { ask, dir: t.folder(), text: Vec::new(), cursor: 0, mark: None });@@ -570,10 +630,12 @@ impl Files {let it = |label: &str, key: &'static str, act: Act, on: bool| Some(Item { label: label.into(), key, act, on });let paste = self.clip.is_some();// (The root of the disk has no folder to be renamed or deleted from.)- let movable = matches!(t, Target::Item { path, .. } if path.parent().is_some());- match t {+ let movable = matches!(t, Target::Item { path, .. } if path.parent().is_some() && !(self.bounded && *path == self.root));+ // (Open in Editor is Open itself where files open in $EDITOR.)+ let items = match t {Target::Item { dir: false, .. } => vec![- it("Open", "Enter", Act::Open, true), it("Open in Terminal", "t", Act::Terminal, true), None,+ it("Open", "Enter", Act::Open, true), it("Open in Editor ($EDITOR)", "e", Act::External, true),+ it("Open in Terminal", "t", Act::Terminal, true), None,it("Cut", "C-x", Act::Cut, true), it("Copy", "C-c", Act::Copy, true), it("Paste", "C-v", Act::Paste, paste), it("Duplicate", "C-d", Act::Duplicate, true), None,it("Copy Path", "y", Act::CopyPath, true), it("Copy Relative Path", "", Act::CopyRelative, true), None,it("Rename…", "F2", Act::Rename, movable), it("Delete", "Del", Act::Delete, movable),@@ -591,7 +653,8 @@ impl Files {it(if self.hidden { "Hide Hidden Files" } else { "Show Hidden Files" }, ".", Act::Hidden, true),it(if self.view == View::Gallery { "View as List" } else { "View as Gallery" }, "v", Act::View, true),],- }+ };+ items.into_iter().filter(|i| self.builtin || i.as_ref().is_none_or(|i| i.act != Act::External)).collect()}/// The menu for [t] with its corner at (x, y), kept inside the view; [keys]: its first item@@ -645,8 +708,49 @@ impl Files {(x > r.x && x + 1 < r.x + r.width && y > r.y && y + 1 < r.y + r.height).then(|| (y - r.y - 1) as usize)}+ /// The explorer title's buttons at its right: each one's columns and what it is — none when+ /// the explorer is too narrow for them (the title gives way to them first).+ fn heads(&self, g: Geom) -> Vec<(u16, u16, Head)> {+ let t = g.tree;+ let widths: Vec<u16> = Head::ALL.iter().map(|h| h.icon(self.nerd).width() as u16).collect();+ let total = widths.iter().sum::<u16>() + widths.len() as u16 - 1;+ if t.width < total + 2 { return Vec::new() }+ let mut x = t.x + t.width - 1 - total;+ Head::ALL.iter().zip(widths).map(|(h, w)| { let b = (x, x + w, *h); x += w + 1; b }).collect()+ }++ /// A title button: New File and New Folder ask for a name in the explorer's selected folder+ /// (with it in focus), else the folder on show; Refresh reads everything shown again; Collapse+ /// All closes every folder but the root.+ fn head(&mut self, h: Head) {+ let t = if self.focus == Focus::Tree { self.key_target() } else { Target::Space(self.cwd.clone()) };+ match h {+ Head::NewFile => { self.act(Act::NewFile, t); }+ Head::NewFolder => { self.act(Act::NewFolder, t); }+ Head::Refresh => {+ let keep = self.rows.get(self.tree_sel).map(|r| r.path.clone());+ self.reload();+ if let Some(i) = keep.and_then(|p| self.rows.iter().position(|r| !r.note && r.path == p)) { self.tree_sel = i }+ self.message = Some("Refreshed".into());+ }+ Head::Collapse => {+ let root = self.root.clone();+ self.expanded.retain(|p| *p == root);+ self.build_tree();+ (self.tree_sel, self.tree_scroll, self.tree_follow) = (0, 0, false);+ }+ }+ }++ /// A drag with the button down: in the editor, a selection.+ fn drag(&mut self, x: u16, y: u16) { if let Some(e) = self.editor.as_mut() { e.click(x, y, true) } }+/// The mouse over the menu: the item under it lit (none on a rule or a dimmed one).- fn hover(&mut self, x: u16, y: u16) {+ fn hover(&mut self, x: u16, y: u16, g: Geom) {+ self.head_hover = None;+ if self.menu.is_none() && self.editor.is_none() && y == 0 {+ self.head_hover = self.heads(g).into_iter().find(|(a, z, _)| x >= *a && x < *z).map(|(.., h)| h);+ }let at = self.menu_at(x, y);if let Some(m) = self.menu.as_mut() { m.sel = at.filter(|i| m.items.get(*i).is_some_and(|it| it.as_ref().is_some_and(|it| it.on))) }}@@ -738,6 +842,7 @@ impl Files {/// folder is shown and opened or closed (its chevron only that).fn click(&mut self, x: u16, y: u16, double: bool, g: Geom) -> Outcome {self.message = None;+ if let Some(e) = self.editor.as_mut() { e.click(x, y, false); return Outcome::None }let g = geom(g.size.0, g.size.1, self.view);let out = self.click_at(x, y, double, g);self.fit(g);@@ -757,6 +862,10 @@ impl Files {if self.menu.is_some() {return match self.menu_at(x, y) { Some(i) => self.choose(i), None => { if !self.menu.as_ref().is_some_and(|m| contains(menu_box(m), x, y)) { self.menu = None } Outcome::None } };}+ if y == 0 && g.in_tree(x) && let Some((.., h)) = self.heads(g).into_iter().find(|(a, z, _)| x >= *a && x < *z) {+ if !double { self.head(h) }+ return Outcome::None;+ }if g.in_tree(x) {self.focus = Focus::Tree;// (Its first click has done what a double one would.)@@ -792,7 +901,7 @@ impl Files {/// folder, an entry, else the folder's empty space (the explorer's: its root).fn right_click(&mut self, x: u16, y: u16, g: Geom) {self.message = None;- if self.confirm.is_some() || self.prompt.is_some() { return }+ if self.editor.is_some() || self.confirm.is_some() || self.prompt.is_some() { return }self.menu = None;let g = geom(g.size.0, g.size.1, self.view);let t = if g.in_tree(x) {@@ -831,6 +940,7 @@ impl Files {/// The wheel: the explorer's rows three at a time under the mouse there, else the grid's (the/// list's three). A menu up closes.fn wheel(&mut self, x: u16, down: bool, g: Geom) {+ if let Some(e) = self.editor.as_mut() { return e.wheel(down) }if self.confirm.is_some() || self.prompt.is_some() { return }self.menu = None;let step = if g.in_tree(x) || self.view == View::List { 3 } else { 1 };@@ -857,7 +967,9 @@ impl Files {let switch = self.switch(g).first().map(|(a, ..)| g.grid.x + g.grid.width - a + 1).unwrap_or(0);let width = g.grid.width.saturating_sub(switch);let home = home();- let (mut at, mut parts) = if home != Path::new("/") && self.cwd.starts_with(&home) { (home.clone(), vec![("~".to_string(), home)]) }+ // (A bounded explorer's from its root, nothing above it.)+ let (mut at, mut parts) = if self.bounded { (self.root.clone(), vec![(name_of(&self.root), self.root.clone())]) }+ else if home != Path::new("/") && self.cwd.starts_with(&home) { (home.clone(), vec![("~".to_string(), home)]) }else { (PathBuf::from("/"), vec![("/".to_string(), PathBuf::from("/"))]) };let rest = self.cwd.strip_prefix(&at).map(Path::to_path_buf).unwrap_or_default();for c in rest.components() { at.push(c); parts.push((c.as_os_str().to_string_lossy().into_owned(), at.clone())) }@@ -877,6 +989,7 @@ impl Files {}fn draw(&mut self, buf: &mut Buffer, area: Rect, look: &Look) {+ if let Some(e) = self.editor.as_mut() { return e.draw(buf, area, look) }let g = geom(area.width, area.height, self.view);self.fit(g);for y in area.top()..area.bottom() { for x in area.left()..area.right() { if let Some(c) = buf.cell_mut((x, y)) { c.set_symbol(" "); } } }@@ -894,8 +1007,9 @@ impl Files {}for (a, z, v, s) in self.switch(g) { put(buf, ox + a, oy, z - a, s, if v == self.view { look.mode } else { look.muted }); }let harness = if self.standalone { "" } else { " · n harness" };+ let edit = if self.builtin { " · e $EDITOR" } else { "" };let hint = match self.focus {- Focus::Grid => format!("Enter open · Backspace up · Tab explorer · v view · . hidden{harness} · t terminal · F2 rename · Del trash · C-c C-x C-v · right-click for more · q close"),+ Focus::Grid => format!("Enter open{edit} · Backspace up · Tab explorer · v view · . hidden{harness} · t terminal · F2 rename · Del trash · C-c C-x C-v · right-click for more · q close"),Focus::Tree => format!("Enter show · ←→ close/open · Tab grid · v view · . hidden{harness} · t terminal · F2 rename · Del trash · right-click for more · q close"),};put(buf, ox + gx + 1, oy + 1, gw.saturating_sub(2), &fit(&hint, gw.saturating_sub(2) as usize), look.muted);@@ -932,19 +1046,7 @@ impl Files {/// short as `shorten` does); all of it lit when it is the grid's selection (only its name/// marked while the explorer has the keys).fn draw_tile(&self, buf: &mut Buffer, x: u16, y: u16, e: &Entry, selected: bool, look: &Look) {- let w = TILE_W - 2;- let st = if e.dir { look.accent } else { file_style(&e.name, look) };- for (dy, line) in art(e).iter().enumerate() {- put(buf, x + w.saturating_sub(line.width() as u16) / 2, y + dy as u16, w, line, st);- }- let name = shorten(&e.name, e.dir, w as usize);- let name_st = if selected && self.focus == Focus::Tree { look.text.add_modifier(Modifier::BOLD | Modifier::UNDERLINED) } else { look.text };- put(buf, x + (w.saturating_sub(name.width() as u16)) / 2, y + 4, w, &name, name_st);- if selected && self.focus == Focus::Grid {- // (The picture keeps its colour on the selection's background; the name takes both.)- let bg = look.mode.bg.map(|b| Style::default().bg(b)).unwrap_or(look.mode);- for dy in 0..TILE_H - 1 { for dx in 0..w { if let Some(c) = buf.cell_mut((x + dx, y + dy)) { c.set_style(if dy < 4 { bg } else { look.mode }); } } }- }+ tile(buf, x, y, e, selected && self.focus == Focus::Grid, selected && self.focus == Focus::Tree, look)}/// The list: a header, then a row each — icon, name, size (a folder's items), when it was@@ -1002,7 +1104,7 @@ impl Files {if self.hidden { text.push_str(" · hidden shown") }if let Some((paths, cut)) = &self.clip { text.push_str(&format!(" · {} {} to paste", paths.len(), if *cut { "cut" } else { "copied" })) }let st = if self.message.is_some() { look.accent } else { look.muted };- if let Some(m) = &self.message { text = m.clone() }+ if let Some(m) = &self.message { text = m.clone() } else if let Some(h) = self.head_hover { text = h.tip().to_string() }let (x, y, w) = (area.x + r.x + 1, area.y + g.footer, r.width.saturating_sub(2));let used = put(buf, x, y, w, &fit(&text, w as usize), st);if self.listing.more > 0 && self.message.is_none() {@@ -1017,7 +1119,10 @@ impl Files {if t.width == 0 { return }let (ox, oy) = (area.x, area.y);for y in 0..t.height { put(buf, ox + t.x + t.width, oy + y, 1, "│", look.muted); }- put(buf, ox + t.x + 1, oy, t.width.saturating_sub(2), "EXPLORER", look.muted.add_modifier(Modifier::BOLD));+ let heads = self.heads(g);+ let title_room = heads.first().map(|(a, ..)| a.saturating_sub(t.x + 2)).unwrap_or(t.width.saturating_sub(2));+ if title_room >= 8 { put(buf, ox + t.x + 1, oy, title_room, "EXPLORER", look.muted.add_modifier(Modifier::BOLD)); }+ for (a, z, h) in heads { put(buf, ox + a, oy, z - a, h.icon(self.nerd), if self.head_hover == Some(h) { look.mode } else { look.text }); }let shown = t.height.saturating_sub(1) as usize;for (k, row) in self.rows.iter().enumerate().skip(self.tree_scroll).take(shown) {let y = oy + 1 + (k - self.tree_scroll) as u16;@@ -1141,6 +1246,23 @@ impl Target {}}+/// A tile at (x, y): its picture over its name; all of it lit when [lit] (the picture keeping its+/// colour on the selection's background), only its name marked when [marked].+fn tile(buf: &mut Buffer, x: u16, y: u16, e: &Entry, lit: bool, marked: bool, look: &Look) {+ let w = TILE_W - 2;+ let st = if e.dir { look.accent } else { file_style(&e.name, look) };+ for (dy, line) in art(e).iter().enumerate() {+ put(buf, x + w.saturating_sub(line.width() as u16) / 2, y + dy as u16, w, line, st);+ }+ let name = shorten(&e.name, e.dir, w as usize);+ let name_st = if marked { look.text.add_modifier(Modifier::BOLD | Modifier::UNDERLINED) } else { look.text };+ put(buf, x + (w.saturating_sub(name.width() as u16)) / 2, y + 4, w, &name, name_st);+ if lit {+ let bg = look.mode.bg.map(|b| Style::default().bg(b)).unwrap_or(look.mode);+ for dy in 0..TILE_H - 1 { for dx in 0..w { if let Some(c) = buf.cell_mut((x + dx, y + dy)) { c.set_style(if dy < 4 { bg } else { look.mode }); } } }+ }+}+/// A big picture for a tile: a folder; a page with its extension on it.fn art(e: &Entry) -> [String; 4] {if e.dir { return [" ▄▄▄▄ ".into(), "██████████".into(), "██████████".into(), "▀▀▀▀▀▀▀▀▀▀".into()] }@@ -1329,7 +1451,7 @@ pub fn key(app: &mut App, pane: u64, chord: Chord, m: Option<&crate::mouse::Even// (The root table's MouseDown3Pane sends a right click on to a pane in a mode other than// copy mode: it is this menu's, not the pane menu's.)(Some((MouseKind::Down, 3, _)), Some((x, y))) => { f.right_click(x, y, g); Outcome::None }- (Some((MouseKind::Move, ..)), Some((x, y))) => { f.hover(x, y); Outcome::None }+ (Some((MouseKind::Move, ..)), Some((x, y))) => { f.hover(x, y, g); Outcome::None }(Some((MouseKind::WheelUp, ..)), at) => { f.wheel(at.map(|a| a.0).unwrap_or(0), false, g); Outcome::None }(Some((MouseKind::WheelDown, ..)), at) => { f.wheel(at.map(|a| a.0).unwrap_or(0), true, g); Outcome::None }(Some(_), _) => Outcome::None,@@ -1389,19 +1511,124 @@ impl Drop for Screen { fn drop(&mut self) { Screen::give_back() } }/// `hn files [DIR]`: the file manager filling this terminal, a program of its own — no daemon,/// no hn client or server needed (the OS's Super+E runs it in a window of its own). DIR: `~`-/// home, a relative one from here; home without one. Its exit code.+/// home, a relative one from here; home without one. And its other ways, each in a window of+/// its own: `--open [DIR]` the Open dialog (Super+O), `--root DIR` an explorer kept inside DIR+/// (what the dialog opens a folder in), `--edit FILE` the editor on FILE alone. Its exit code.pub fn standalone(args: &[String]) -> i32 {if !on_the_os(std::env::var("HARNESS_OS").ok().as_deref()) { eprintln!("hn files: available on the Harness operating system only."); return 2 }- let dir = match args.first() { None => Ok(home()), Some(d) => folder(Path::new(d), std::env::current_dir().ok()) };- let dir = match dir { Ok(d) => d, Err(e) => { eprintln!("hn files: {e}"); return 1 } };+ let mode = args.first().map(String::as_str).filter(|a| matches!(*a, "--open" | "--root" | "--edit"));+ let rest = if mode.is_some() { &args[1..] } else { args };+ let here = std::env::current_dir().ok();// Nerd Font icons: $HN_NERD_FONT on or off, else on in Harness OS (its terminal's font has them).let nerd = match std::env::var("HN_NERD_FONT") {Ok(v) if !v.is_empty() => matches!(v.as_str(), "on" | "1" | "yes" | "true"),_ => std::env::var("HARNESS_OS").is_ok_and(|v| v == "1"),};- let mut f = Files::new(dir, nerd);+ let fail = |e: String| { eprintln!("hn files: {e}"); 1 };+ let start = if mode == Some("--edit") {+ let Some(file) = rest.first() else { return fail("--edit needs a file".into()) };+ let file = clean(&here.clone().unwrap_or_else(home).join(match Path::new(file).strip_prefix("~") { Ok(r) => home().join(r), Err(_) => PathBuf::from(file) }));+ Start::Edit(file)+ } else {+ let dir = match rest.first() { None => Ok(home()), Some(d) => folder(Path::new(d), here) };+ match dir { Ok(d) if mode == Some("--open") => Start::Open(d), Ok(d) if mode == Some("--root") => Start::Root(d), Ok(d) => Start::Explore(d), Err(e) => return fail(e) }+ };+ let launcher = std::env::var("HARNESS_FILES_LAUNCH").ok();+ match run_start(start, nerd, launcher.as_deref(), &mut launch) { Ok(()) => 0, Err(e) => fail(e) }+}++/// What `hn files` starts as.+#[derive(Debug, PartialEq, Eq)]+enum Start { Explore(PathBuf), Open(PathBuf), Root(PathBuf), Edit(PathBuf) }++/// The file manager for [start]: an explorer (kept inside its root with `--root`), the editor+/// alone, or the Open dialog and then what it opened.+fn run_start(start: Start, nerd: bool, launcher: Option<&str>, spawn: &mut dyn FnMut(&str, &[String]) -> std::io::Result<()>) -> Result<(), String> {+ let io = |e: std::io::Error| e.to_string();+ let next = match start {+ Start::Open(dir) => {+ let mut d = dialog::Dialog::new(dir, nerd, dialog::recent_home());+ match run_dialog(&mut d).map_err(io)? {+ None => return Ok(()),+ Some((path, folder)) => match opened(path, folder, launcher, spawn)? { None => return Ok(()), Some(s) => s },+ }+ }+ s => s,+ };+ let mut f = match next {+ Start::Explore(dir) => Files::new(dir, nerd),+ Start::Root(dir) => { let mut f = Files::new(dir, nerd); f.bounded = true; f }+ Start::Edit(file) => {+ let mut f = Files::new(file.parent().map(Path::to_path_buf).unwrap_or_else(home), nerd);+ f.builtin = true;+ f.open_file(file);+ if f.editor.is_none() { return Err(f.message.unwrap_or_else(|| "nothing to edit".into())) }+ f.exit_on_close = true;+ f+ }+ Start::Open(_) => unreachable!(),+ };f.standalone = true;- match run_standalone(&mut f) { Ok(()) => 0, Err(e) => { eprintln!("hn files: {e}"); 1 } }+ f.builtin = true;+ run_standalone(&mut f).map_err(io)+}++/// What the Open dialog chose, opened: in a window of its own through $HARNESS_FILES_LAUNCH+/// (`--root DIR`, `--edit FILE`), this one then done (None); without it, in this window.+fn opened(path: PathBuf, folder: bool, launcher: Option<&str>, spawn: &mut dyn FnMut(&str, &[String]) -> std::io::Result<()>) -> Result<Option<Start>, String> {+ match launcher.map(str::trim).filter(|l| !l.is_empty()) {+ Some(l) => {+ let args = vec![if folder { "--root" } else { "--edit" }.to_string(), path.to_string_lossy().into_owned()];+ spawn(l, &args).map(|_| None).map_err(|e| format!("couldn't open {}: {e}", path.display()))+ }+ None => Ok(Some(if folder { Start::Root(path) } else { Start::Edit(path) })),+ }+}++/// [program] started on its own (its own session, nothing of this terminal's), not waited for.+fn launch(program: &str, args: &[String]) -> std::io::Result<()> {+ use std::os::unix::process::CommandExt;+ use std::process::{Command, Stdio};+ let mut words = program.split_whitespace();+ let mut c = Command::new(words.next().unwrap_or(program));+ c.args(words).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());+ // SAFETY: setsid only, between fork and exec.+ unsafe { c.pre_exec(|| { libc::setsid(); Ok(()) }); }+ c.spawn().map(|_| ())+}++/// The Open dialog in this terminal until it is cancelled (None) or opens something.+fn run_dialog(d: &mut dialog::Dialog) -> std::io::Result<Option<(PathBuf, bool)>> {+ use crossterm::event::{Event, KeyEventKind, MouseButton, MouseEventKind};+ let look = Look::default();+ let hook = std::panic::take_hook();+ std::panic::set_hook(Box::new(move |info| { Screen::give_back(); hook(info) }));+ Screen::take()?;+ let _screen = Screen;+ let mut term = ratatui::Terminal::new(ratatui::backend::CrosstermBackend::new(std::io::stdout()))?;+ let mut last_click: Option<(std::time::Instant, u16, u16)> = None;+ loop {+ term.draw(|frame| { let area = frame.area(); d.draw(frame.buffer_mut(), area, &look) })?;+ let out = match crossterm::event::read()? {+ Event::Key(k) if k.kind != KeyEventKind::Release => d.key(keys::of(&k)),+ Event::Mouse(m) => match m.kind {+ MouseEventKind::Down(MouseButton::Left) => {+ let double = last_click.is_some_and(|(at, x, y)| at.elapsed() < DOUBLE_CLICK && (x, y) == (m.column, m.row));+ last_click = (!double).then(|| (std::time::Instant::now(), m.column, m.row));+ d.click(m.column, m.row, double)+ }+ MouseEventKind::ScrollUp => { d.wheel(m.column, false); dialog::DOut::None }+ MouseEventKind::ScrollDown => { d.wheel(m.column, true); dialog::DOut::None }+ _ => dialog::DOut::None,+ },+ _ => dialog::DOut::None,+ };+ match out {+ dialog::DOut::None => {}+ dialog::DOut::Cancel => return Ok(None),+ dialog::DOut::Open(p, folder) => return Ok(Some((p, folder))),+ }+ }}/// Whether `hn files` runs: on Harness OS ($HARNESS_OS=1), as hn's OS session is decided.@@ -1431,7 +1658,8 @@ fn run_standalone(f: &mut Files) -> std::io::Result<()> {f.click(m.column, m.row, double, g)}MouseEventKind::Down(MouseButton::Right) => { f.right_click(m.column, m.row, g); Outcome::None }- MouseEventKind::Moved => { f.hover(m.column, m.row); Outcome::None }+ MouseEventKind::Drag(MouseButton::Left) => { f.drag(m.column, m.row); Outcome::None }+ MouseEventKind::Moved => { f.hover(m.column, m.row, g); Outcome::None }MouseEventKind::ScrollUp => { f.wheel(m.column, false, g); Outcome::None }MouseEventKind::ScrollDown => { f.wheel(m.column, true, g); Outcome::None }_ => Outcome::None,@@ -1663,6 +1891,88 @@ mod tests {assert!(!text.lines().nth(g.items_y as usize + 5).unwrap().contains("version"), "no second line");}+ #[test]+ fn the_explorer_title_has_new_file_new_folder_refresh_and_collapse_buttons() {+ let s = Scratch::new(&["a/b/", "c/"]);+ let mut f = files(&s);+ let g = gal(120, 40);+ let area = Rect::new(0, 0, 120, 40);+ let mut buf = Buffer::empty(area);+ f.draw(&mut buf, area, &Look::default());+ let top = contents(&buf).lines().next().unwrap().to_string();+ assert!(top.starts_with(" EXPLORER") && top[..top.find('│').unwrap()].trim_end().ends_with("+F +D R -"), "{top}");+ let heads = f.heads(g);+ let at = |h: Head| heads.iter().find(|b| b.2 == h).map(|b| b.0).unwrap();+ // New File with the grid's keys: in the folder on show.+ f.click(at(Head::NewFile), 0, false, g);+ assert_eq!(f.prompt.as_ref().map(|p| (p.ask.clone(), p.dir.clone())), Some((Ask::NewFile, s.0.clone())));+ press(&mut f, KeyCode::Esc);+ // New Folder with the explorer's: in its selected folder, then selected there, its parent open.+ press(&mut f, KeyCode::Tab);+ f.tree_sel = f.rows.iter().position(|r| r.path == s.0.join("c")).unwrap();+ f.click(at(Head::NewFolder), 0, false, g);+ assert_eq!(f.prompt.as_ref().map(|p| p.dir.clone()), Some(s.0.join("c")));+ for ch in "new".chars() { press(&mut f, KeyCode::Char(ch)); }+ press(&mut f, KeyCode::Enter);+ assert!(s.0.join("c/new").is_dir() && f.expanded.contains(&s.0.join("c")));+ assert_eq!(names(&f)[f.selected], "new");+ // Refresh: what was made meanwhile is there, the selection kept.+ std::fs::write(s.0.join("c/later.txt"), "").unwrap();+ f.tree_sel = 0;+ f.click(at(Head::Refresh), 0, false, g);+ assert!(names(&f).contains(&"later.txt") && f.tree_sel == 0);+ f.go(s.0.join("a/b"), None);+ f.press(Chord::normal(KeyCode::F(5), KeyModifiers::NONE), g);+ assert_eq!(f.message.as_deref(), Some("Refreshed"));+ // Collapse All: only the root open, the grid where it was.+ f.click(at(Head::Collapse), 0, false, g);+ assert_eq!(f.expanded.iter().collect::<Vec<_>>(), [&s.0]);+ assert_eq!((f.cwd.clone(), f.tree_scroll), (s.0.join("a/b"), 0));+ // Narrow: the title gives way, then the buttons.+ assert!(f.heads(geom(60, 30, View::Gallery)).len() == 4 && f.heads(geom(45, 30, View::Gallery)).len() == 4);+ assert!(f.heads(geom(30, 30, View::Gallery)).is_empty());+ }++ #[test]+ fn what_the_open_dialog_chose_opens_in_its_own_window_or_in_this_one() {+ let mut spawned: Vec<(String, Vec<String>)> = Vec::new();+ let mut spawn = |p: &str, a: &[String]| -> std::io::Result<()> { spawned.push((p.to_string(), a.to_vec())); Ok(()) };+ assert_eq!(opened(PathBuf::from("/w/app"), true, Some("/usr/lib/harness-os/files"), &mut spawn), Ok(None));+ assert_eq!(opened(PathBuf::from("/w/a.md"), false, Some("/usr/lib/harness-os/files"), &mut spawn), Ok(None));+ assert_eq!(spawned, [("/usr/lib/harness-os/files".to_string(), vec!["--root".to_string(), "/w/app".to_string()]), ("/usr/lib/harness-os/files".to_string(), vec!["--edit".to_string(), "/w/a.md".to_string()])]);+ let mut none = |_: &str, _: &[String]| -> std::io::Result<()> { panic!("no launcher: nothing started") };+ assert_eq!(opened(PathBuf::from("/w/app"), true, None, &mut none), Ok(Some(Start::Root(PathBuf::from("/w/app")))));+ assert_eq!(opened(PathBuf::from("/w/a.md"), false, Some(" "), &mut none), Ok(Some(Start::Edit(PathBuf::from("/w/a.md")))));+ }++ #[test]+ fn root_keeps_the_explorer_inside_its_folder_and_edit_is_the_editor_alone() {+ let s = Scratch::new(&["me/app/src/main.py"]);+ let app = s.0.join("me/app");+ let mut f = Files::new(app.clone(), false);+ f.bounded = true;+ let g = gal(120, 40);+ assert_eq!(f.rows[0].name, "app");+ assert_eq!(f.crumbs(g).1.iter().map(|c| c.3.as_str()).collect::<Vec<_>>(), ["app"]);+ press(&mut f, KeyCode::Backspace);+ assert_eq!((f.cwd.clone(), f.message.as_deref()), (app.clone(), Some("This is the top of 'app'")));+ press(&mut f, KeyCode::Enter);+ assert_eq!(f.crumbs(g).1.iter().map(|c| c.3.as_str()).collect::<Vec<_>>(), ["app", "src"]);+ assert_eq!(f.act(Act::CopyRelative, Target::Item { path: app.join("src/main.py"), dir: false }), Outcome::Clipboard("src/main.py".into()));+ press(&mut f, KeyCode::Backspace);+ press(&mut f, KeyCode::Backspace);+ assert_eq!(f.cwd, app, "up to its root, no further");+ // --edit: the editor at once; closed, the program ends.+ let mut e = Files::new(app.join("src"), false);+ (e.builtin, e.exit_on_close) = (true, true);+ e.open_file(app.join("src/main.py"));+ assert!(e.editor.is_some());+ assert_eq!(press(&mut e, KeyCode::Esc), Outcome::Exit);+ // A picture is no text: --edit says so.+ std::fs::write(app.join("x.png"), b"PNG").unwrap();+ assert_eq!(run_start(Start::Edit(app.join("x.png")), false, None, &mut |_: &str, _: &[String]| Ok(())), Err("Can't open 'x.png': not a text file".into()));+ }+#[test]fn hn_files_runs_on_harness_os_alone() {assert!(on_the_os(Some("1")));diff --git a/tui/src/files/dialog.rs b/tui/src/files/dialog.rsnew file mode 100644index 000000000..80c5d29ad--- /dev/null+++ b/tui/src/files/dialog.rs@@ -0,0 +1,821 @@+//! `hn files --open` (Harness OS's Super+O): an Open dialog as the Mac's Open panel is — a box+//! with its toolbar (back and forward, Columns or Icons, the folder's path popup, Search), a+//! sidebar of places (Favorites, Recent, Locations), the folders as Miller columns with a preview+//! of the file selected, and Cancel and Open. What it opens it hands on: a folder to an explorer+//! of its own (`--root`), a text file to the editor (`--edit`); then it ends.++use std::path::{Path, PathBuf};+use std::time::SystemTime;++use crossterm::event::{KeyCode, KeyModifiers};+use ratatui::buffer::Buffer;+use ratatui::layout::Rect;+use ratatui::style::Modifier;+use unicode_width::UnicodeWidthStr;++use super::{art, editor, file_style, fit, frame, home, icon, list, name_of, ops, put, shorten, tile, Entry, Look, TILE_H, TILE_W};+use crate::keys::Chord;++/// The sidebar's width, and a column's (its separator in it).+const SIDE_W: u16 = 22;+const COL_W: u16 = 30;+/// How many places Recent lists, and how many it keeps.+const RECENT_SHOWN: usize = 5;+const RECENT_KEPT: usize = 20;++/// A column: a folder's entries (those the search leaves, in the deepest one), the one selected+/// and the first shown.+#[derive(Clone, Debug)]+struct Col { dir: PathBuf, entries: Vec<Entry>, error: Option<String>, rows: Vec<usize>, sel: Option<usize>, scroll: usize }++impl Col {+ fn new(dir: PathBuf) -> Col {+ let l = list(&dir, false, false);+ let rows = (0..l.entries.len()).collect();+ Col { dir, entries: l.entries, error: l.error, rows, sel: None, scroll: 0 }+ }+ /// Its rows: the entries whose names have [q] in them, whatever the case.+ fn filter(&mut self, q: &str) {+ let q = q.to_lowercase();+ self.rows = (0..self.entries.len()).filter(|i| q.is_empty() || self.entries[*i].name.to_lowercase().contains(&q)).collect();+ }+ fn selected(&self) -> Option<&Entry> { self.sel.and_then(|i| self.entries.get(i)) }+ /// The selected entry's place among the rows.+ fn at(&self) -> Option<usize> { self.sel.and_then(|s| self.rows.iter().position(|r| *r == s)) }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum DView { Columns, Icons }++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Focus { Sidebar, Columns, Buttons, Search }++/// A place in the sidebar: its section, words, icon and path.+#[derive(Clone, Debug, PartialEq, Eq)]+struct Place { section: usize, label: String, icon: &'static str, path: PathBuf }++const SECTIONS: [&str; 3] = ["Favorites", "Recent", "Locations"];++/// The toolbar's parts.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Tool { Back, Forward, Columns, Icons, Path, Search }++/// What the dialog asks of the program: nothing yet, to end, or to open what was chosen.+#[derive(Debug, PartialEq, Eq)]+pub(super) enum DOut { None, Cancel, Open(PathBuf, bool) }++/// Where a dialog's things are at a size: its sidebar, main area and bottom row.+#[derive(Clone, Copy, Debug)]+struct Layout { side: Rect, main: Rect, bottom: u16 }++fn layout(w: u16, h: u16) -> Layout {+ let side_w = SIDE_W.min(w / 4);+ let body_h = h.saturating_sub(6);+ Layout { side: Rect::new(1, 3, side_w, body_h), main: Rect::new(2 + side_w, 3, w.saturating_sub(3 + side_w), body_h), bottom: h.saturating_sub(2) }+}++/// A history entry: the columns' folders and which one is active.+type Spot = (Vec<PathBuf>, usize);++#[derive(Debug)]+pub(super) struct Dialog {+ cols: Vec<Col>,+ active: usize,+ pub(super) view: DView,+ back: Vec<Spot>,+ fwd: Vec<Spot>,+ places: Vec<Place>,+ side_sel: usize,+ focus: Focus,+ search: String,+ /// The path popup: the folders above the one on show, and the one the keys are on.+ popup: Option<(Vec<PathBuf>, usize)>,+ /// Cancel (0) or Open (1), with the keys on the buttons.+ button: usize,+ pub(super) message: Option<String>,+ nerd: bool,+ recent_file: PathBuf,+ size: (u16, u16),+ /// The selected file's first lines (None: not text), read once.+ preview: Option<(PathBuf, Option<Vec<String>>)>,+ /// The selection moved: brought into view at the next draw.+ follow: bool,+}++/// Where Recent is kept: $XDG_STATE_HOME (else ~/.local/state)/harness-os/open-recent.json.+pub(super) fn recent_home() -> PathBuf {+ std::env::var_os("XDG_STATE_HOME").map(PathBuf::from).filter(|p| p.is_absolute()).unwrap_or_else(|| home().join(".local/state")).join("harness-os/open-recent.json")+}++/// What was opened through the dialog, the latest first.+fn load_recent(file: &Path) -> Vec<PathBuf> {+ std::fs::read_to_string(file).ok().and_then(|t| serde_json::from_str::<Vec<String>>(&t).ok()).unwrap_or_default().into_iter().map(PathBuf::from).collect()+}++/// [path] the latest opened: first in Recent, once, RECENT_KEPT kept.+fn push_recent(file: &Path, path: &Path) {+ let mut all = load_recent(file);+ all.retain(|p| p != path);+ all.insert(0, path.to_path_buf());+ all.truncate(RECENT_KEPT);+ let list: Vec<String> = all.iter().map(|p| p.to_string_lossy().into_owned()).collect();+ if let Some(dir) = file.parent() { let _ = std::fs::create_dir_all(dir); }+ let _ = std::fs::write(file, serde_json::to_string(&list).unwrap_or_default());+}++/// The sidebar's places: home's usual folders that are there, what Recent has that is still+/// there, the computer and the drives mounted for this user.+fn places(recent_file: &Path, nerd: bool) -> Vec<Place> {+ let h = home();+ let glyph = |n: &'static str, p: &'static str| if nerd { n } else { p };+ let mut out = vec![Place { section: 0, label: "Home".into(), icon: glyph("\u{f015}", "~"), path: h.clone() }];+ for (name, label, n) in [("Desktop", "Desktop", "\u{f108}"), ("Documents", "Documents", "\u{f15c}"), ("Downloads", "Downloads", "\u{f019}"), ("Pictures", "Pictures", "\u{f03e}"), ("projects", "projects", "\u{f07b}")] {+ if h.join(name).is_dir() { out.push(Place { section: 0, label: label.into(), icon: glyph(n, "▸"), path: h.join(name) }) }+ }+ for p in load_recent(recent_file).into_iter().filter(|p| p.exists()).take(RECENT_SHOWN) {+ let dir = p.is_dir();+ out.push(Place { section: 1, label: name_of(&p), icon: if dir { glyph("\u{f07b}", "▸") } else { glyph("\u{f15b}", "·") }, path: p });+ }+ out.push(Place { section: 2, label: "Computer".into(), icon: glyph("\u{f108}", "/"), path: PathBuf::from("/") });+ let user = std::env::var("USER").unwrap_or_default();+ for base in [format!("/run/media/{user}"), format!("/media/{user}")] {+ if user.is_empty() { break }+ let Ok(rd) = std::fs::read_dir(&base) else { continue };+ let mut vols: Vec<PathBuf> = rd.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.is_dir()).collect();+ vols.sort();+ for v in vols { out.push(Place { section: 2, label: name_of(&v), icon: glyph("\u{f0a0}", "□"), path: v }) }+ }+ out+}++impl Dialog {+ pub(super) fn new(dir: PathBuf, nerd: bool, recent_file: PathBuf) -> Dialog {+ let places = places(&recent_file, nerd);+ let mut d = Dialog {+ cols: Vec::new(), active: 0, view: DView::Columns, back: Vec::new(), fwd: Vec::new(), places, side_sel: 0, focus: Focus::Columns,+ search: String::new(), popup: None, button: 1, message: None, nerd, recent_file, size: (130, 34), preview: None, follow: true,+ };+ d.set_spot((vec![dir], 0));+ d+ }++ /// The folder on show: the active column's.+ pub(super) fn current(&self) -> PathBuf { self.cols[self.active].dir.clone() }++ fn spot(&self) -> Spot { (self.cols.iter().map(|c| c.dir.clone()).collect(), self.active) }++ /// The columns for [spot]'s folders, each selecting the next.+ fn set_spot(&mut self, (dirs, active): Spot) {+ self.cols = dirs.iter().map(|d| Col::new(d.clone())).collect();+ for i in 0..self.cols.len().saturating_sub(1) {+ let next = name_of(&dirs[i + 1]);+ self.cols[i].sel = self.cols[i].entries.iter().position(|e| e.name == next);+ }+ self.active = active.min(self.cols.len() - 1);+ self.refilter();+ self.follow = true;+ }++ /// A move that changes the folder on show: where it was, for Back.+ fn moved_from(&mut self, before: Spot) {+ if before.0.get(before.1) != Some(&self.current()) { self.back.push(before); self.fwd.clear() }+ }++ /// Back ([back]) or Forward through the folders shown.+ fn history(&mut self, back: bool) {+ let from = if back { self.back.pop() } else { self.fwd.pop() };+ let Some(spot) = from else { return };+ let now = self.spot();+ if back { self.fwd.push(now) } else { self.back.push(now) }+ self.set_spot(spot);+ }++ /// [dir] shown as the first column (a place, a folder from the path popup).+ fn show(&mut self, dir: PathBuf, select: Option<String>) {+ let before = self.spot();+ self.search.clear();+ self.set_spot((vec![dir], 0));+ if let Some(n) = select { let c = &mut self.cols[0]; c.sel = c.entries.iter().position(|e| e.name == n); self.open_next(0) }+ self.moved_from(before);+ }++ /// The search applied to the deepest column, the others whole; the preview read again.+ fn refilter(&mut self) {+ let last = self.cols.len() - 1;+ for (i, c) in self.cols.iter_mut().enumerate() { c.filter(if i == last { &self.search } else { "" }) }+ }++ /// Entry [i] of column [c] selected: the columns after it gone, its own shown when a folder.+ fn select(&mut self, c: usize, i: usize) {+ let before = self.spot();+ self.cols.truncate(c + 1);+ self.cols[c].sel = Some(i);+ self.active = c;+ self.open_next(c);+ self.refilter();+ self.follow = true;+ self.moved_from(before);+ }++ fn open_next(&mut self, c: usize) {+ self.cols.truncate(c + 1);+ if let Some(e) = self.cols[c].selected().filter(|e| e.dir) { let p = self.cols[c].dir.join(&e.name); self.cols.push(Col::new(p)) }+ }++ /// What Open takes: the active column's selection, else the folder on show.+ pub(super) fn target(&self) -> (PathBuf, bool) {+ let c = &self.cols[self.active];+ c.selected().map(|e| (c.dir.join(&e.name), e.dir)).unwrap_or_else(|| (c.dir.clone(), true))+ }++ /// Open: a folder as it is; a file when it is text (else why not, the dialog staying). Kept+ /// in Recent.+ fn open(&mut self, what: (PathBuf, bool)) -> DOut {+ let (path, dir) = what;+ if !dir {+ let name = name_of(&path);+ match editor::Editor::open(&path, name.clone()) {+ Ok(_) => {}+ Err(editor::Refusal::NotText) => { self.message = Some(format!("Can't open '{name}': not a text file")); return DOut::None }+ Err(editor::Refusal::TooLarge) => { self.message = Some(format!("Can't open '{name}': too large to open here")); return DOut::None }+ Err(editor::Refusal::Unreadable(e)) => { self.message = Some(format!("Can't open '{name}': {e}")); return DOut::None }+ }+ }+ push_recent(&self.recent_file, &path);+ DOut::Open(path, dir)+ }++ fn rows(&self) -> usize { layout(self.size.0, self.size.1).main.height.max(1) as usize }++ // ── keys ─────────────────────────────────────────────────────────────────++ pub(super) fn key(&mut self, k: Chord) -> DOut {+ self.message = None;+ let (ctrl, alt, plain) = (k.mods.contains(KeyModifiers::CONTROL), k.mods.contains(KeyModifiers::ALT), !k.mods.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER));+ if let Some((items, sel)) = self.popup.as_mut() {+ match k.code {+ KeyCode::Up => *sel = sel.saturating_sub(1),+ KeyCode::Down => *sel = (*sel + 1).min(items.len() - 1),+ KeyCode::Enter => { let p = items[*sel].clone(); self.popup = None; self.show(p, None) }+ _ => self.popup = None,+ }+ return DOut::None;+ }+ if self.focus == Focus::Search {+ match k.code {+ KeyCode::Esc => { self.search.clear(); self.focus = Focus::Columns }+ KeyCode::Enter | KeyCode::Down | KeyCode::Tab => self.focus = Focus::Columns,+ KeyCode::Backspace => { self.search.pop(); }+ KeyCode::Char(c) if plain => self.search.push(if k.mods.contains(KeyModifiers::SHIFT) { c.to_uppercase().next().unwrap_or(c) } else { c }),+ _ => {}+ }+ self.refilter();+ return DOut::None;+ }+ match k.code {+ KeyCode::Esc if !self.search.is_empty() => { self.search.clear(); self.refilter() }+ KeyCode::Esc => return DOut::Cancel,+ KeyCode::Char('f') if ctrl => self.focus = Focus::Search,+ KeyCode::Char('/') if plain => self.focus = Focus::Search,+ KeyCode::Tab => self.focus = match self.focus { Focus::Sidebar => Focus::Columns, Focus::Columns => Focus::Buttons, _ => Focus::Sidebar },+ KeyCode::BackTab => self.focus = match self.focus { Focus::Sidebar => Focus::Buttons, Focus::Columns => Focus::Sidebar, _ => Focus::Columns },+ KeyCode::Left if alt => self.history(true),+ KeyCode::Right if alt => self.history(false),+ _ => return match self.focus {+ Focus::Sidebar => self.side_key(k),+ Focus::Buttons => self.button_key(k),+ _ => self.column_key(k),+ },+ }+ DOut::None+ }++ fn side_key(&mut self, k: Chord) -> DOut {+ let n = self.places.len();+ match k.code {+ KeyCode::Up => self.side_sel = self.side_sel.saturating_sub(1),+ KeyCode::Down => self.side_sel = (self.side_sel + 1).min(n.saturating_sub(1)),+ KeyCode::Enter | KeyCode::Right => { self.go_place(self.side_sel); self.focus = Focus::Columns }+ _ => {}+ }+ DOut::None+ }++ /// A place shown: a folder as the first column; a file in its folder, selected.+ fn go_place(&mut self, i: usize) {+ let Some(p) = self.places.get(i).map(|p| p.path.clone()) else { return };+ self.side_sel = i;+ if p.is_dir() { self.show(p, None) } else if let Some(parent) = p.parent() { self.show(parent.to_path_buf(), Some(name_of(&p))) }+ }++ fn button_key(&mut self, k: Chord) -> DOut {+ match k.code {+ KeyCode::Left | KeyCode::Right => self.button ^= 1,+ KeyCode::Enter => return if self.button == 1 { self.open(self.target()) } else { DOut::Cancel },+ _ => {}+ }+ DOut::None+ }++ fn column_key(&mut self, k: Chord) -> DOut {+ let c = self.active;+ let col = &self.cols[c];+ let (at, n) = (col.at(), col.rows.len());+ let icons = self.view == DView::Icons;+ let across = if icons { (layout(self.size.0, self.size.1).main.width / TILE_W).max(1) as usize } else { 1 };+ let page = if icons { across * (self.rows() / TILE_H as usize).max(1) } else { self.rows() };+ let step = |d: isize| -> Option<usize> {+ if n == 0 { return None }+ Some(match at { None => 0, Some(a) => (a as isize + d).clamp(0, n as isize - 1) as usize })+ };+ let row = match k.code {+ KeyCode::Up => step(-(across as isize)),+ KeyCode::Down => step(across as isize),+ KeyCode::PageUp => step(-(page as isize)),+ KeyCode::PageDown => step(page as isize),+ KeyCode::Home => step(-(n as isize)),+ KeyCode::End => step(n as isize),+ KeyCode::Left if icons => step(-1),+ KeyCode::Right if icons => step(1),+ KeyCode::Right => {+ // Into the selected folder's column, its first entry selected.+ if col.selected().is_some_and(|e| e.dir) && self.cols.len() > c + 1 {+ let before = self.spot();+ self.active = c + 1;+ if let Some(&first) = self.cols[c + 1].rows.first() { self.cols.truncate(c + 2); self.cols[c + 1].sel = Some(first); self.open_next(c + 1); self.refilter() }+ self.moved_from(before);+ }+ None+ }+ KeyCode::Left | KeyCode::Backspace if c > 0 => {+ let before = self.spot();+ self.cols.truncate(c + 1);+ self.cols[c].sel = None;+ self.active = c - 1;+ self.refilter();+ self.moved_from(before);+ None+ }+ KeyCode::Backspace => {+ // Above the first column: its folder's parent, the folder selected in it.+ let dir = self.cols[0].dir.clone();+ if let Some(parent) = dir.parent() { self.show(parent.to_path_buf(), Some(name_of(&dir))) }+ None+ }+ KeyCode::Enter => return self.open(self.target()),+ // Type to select: the next entry from here whose name starts with the letter.+ KeyCode::Char(ch) if !k.mods.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => {+ let ch = ch.to_lowercase().next().unwrap_or(ch);+ let from = at.map(|a| a + 1).unwrap_or(0);+ (0..n).map(|k| (from + k) % n.max(1)).find(|r| col.entries[col.rows[*r]].name.to_lowercase().starts_with(ch))+ }+ _ => None,+ };+ if let Some(r) = row { let i = self.cols[c].rows[r]; self.select(c, i) }+ DOut::None+ }++ // ── the mouse ────────────────────────────────────────────────────────────++ /// The toolbar's parts: each one's columns and what it is.+ fn tools(&self) -> Vec<(u16, u16, Tool)> {+ let w = self.size.0;+ let mut out = vec![(2, 3, Tool::Back), (4, 5, Tool::Forward)];+ let mut x = 7;+ for (label, t) in [(" ▥ Columns ", Tool::Columns), (" ▦ Icons ", Tool::Icons)] { let lw = label.width() as u16; out.push((x, x + lw, t)); x += lw + 1 }+ let search_w = 24.min(w / 4);+ let name_w = (self.path_label().width() as u16).min(w.saturating_sub(x + 2 + search_w + 3));+ out.push((x + 1, x + 1 + name_w, Tool::Path));+ out.push((w.saturating_sub(search_w + 2), w.saturating_sub(2), Tool::Search));+ out+ }++ fn path_label(&self) -> String { format!("{} {} ▾", if self.nerd { "\u{f07b}" } else { "▸" }, name_of(&self.current())) }++ /// The sidebar's rows: each section's title, its places, a blank between.+ fn side_rows(&self) -> Vec<Option<Result<&'static str, usize>>> {+ let mut out = Vec::new();+ for (s, title) in SECTIONS.iter().enumerate() {+ let here: Vec<usize> = (0..self.places.len()).filter(|i| self.places[*i].section == s).collect();+ if here.is_empty() { continue }+ if !out.is_empty() { out.push(None) }+ out.push(Some(Ok(*title)));+ out.extend(here.into_iter().map(|i| Some(Err(i))));+ }+ out+ }++ /// Which columns are shown in the main area (the active one and the one after it kept in+ /// view), from which, and how many there are with the preview.+ fn shown(&self, main_w: u16) -> (usize, usize, usize) {+ let total = self.cols.len() + self.preview_entry().is_some() as usize;+ let fit = (main_w / COL_W).max(1) as usize;+ let need = (self.active + 1).min(total - 1);+ let start = (need + 1).saturating_sub(fit);+ (start, fit.min(total - start), total)+ }++ /// The file the preview is of: the deepest column's selection, when a file.+ fn preview_entry(&self) -> Option<(PathBuf, &Entry)> {+ let c = self.cols.last()?;+ c.selected().filter(|e| !e.dir).map(|e| (c.dir.join(&e.name), e))+ }++ /// The buttons at the right of the bottom row: Cancel, Open.+ fn buttons(&self) -> [(u16, u16, &'static str); 2] {+ let right = self.size.0.saturating_sub(2);+ let open = "[ Open ]";+ let cancel = "[ Cancel ]";+ let ox = right - open.width() as u16;+ let cx = ox - 2 - cancel.width() as u16;+ [(cx, cx + cancel.width() as u16, cancel), (ox, right, open)]+ }++ /// A click at (x, y), a [double] one opening what it is on.+ pub(super) fn click(&mut self, x: u16, y: u16, double: bool) -> DOut {+ self.message = None;+ let l = layout(self.size.0, self.size.1);+ if let Some((items, _)) = self.popup.clone() {+ self.popup = None;+ let (px, py, pw) = self.popup_at();+ if x >= px && x < px + pw && y > py && y <= py + items.len() as u16 { self.show(items[(y - py - 1) as usize].clone(), None) }+ return DOut::None;+ }+ if y == 1 {+ match self.tools().into_iter().find(|(a, z, _)| x >= *a && x < *z).map(|t| t.2) {+ Some(Tool::Back) => self.history(true),+ Some(Tool::Forward) => self.history(false),+ Some(Tool::Columns) => self.view = DView::Columns,+ Some(Tool::Icons) => self.view = DView::Icons,+ Some(Tool::Path) => { let cur = self.current(); self.popup = Some((cur.ancestors().map(Path::to_path_buf).collect(), 0)) }+ Some(Tool::Search) => self.focus = Focus::Search,+ None => {}+ }+ return DOut::None;+ }+ if y == l.bottom {+ match self.buttons().iter().position(|(a, z, _)| x >= *a && x < *z) { Some(0) => return DOut::Cancel, Some(_) => return self.open(self.target()), None => {} }+ return DOut::None;+ }+ if contains(l.side, x, y) {+ self.focus = Focus::Sidebar;+ if let Some(Some(Err(i))) = self.side_rows().get((y - l.side.y) as usize).cloned() { self.go_place(i) }+ return DOut::None;+ }+ if !contains(l.main, x, y) { return DOut::None }+ self.focus = Focus::Columns;+ let (c, r) = match self.view {+ DView::Icons => {+ let across = (l.main.width / TILE_W).max(1);+ let (col, row) = ((x - l.main.x) / TILE_W, (y - l.main.y) / TILE_H);+ if col >= across { return DOut::None }+ let c = &self.cols[self.active];+ (self.active, c.scroll + (row * across + col) as usize)+ }+ DView::Columns => {+ let (start, n, _) = self.shown(l.main.width);+ let k = ((x - l.main.x) / COL_W) as usize;+ if k >= n || start + k >= self.cols.len() { return DOut::None }+ let c = start + k;+ (c, self.cols[c].scroll + (y - l.main.y) as usize)+ }+ };+ let Some(&i) = self.cols[c].rows.get(r) else { return DOut::None };+ let e = self.cols[c].entries[i].clone();+ if double && self.view == DView::Icons && e.dir {+ // (In Icons, a folder double-clicked is gone into, as a grid of icons does.)+ self.select(c, i);+ let before = self.spot();+ self.active = (c + 1).min(self.cols.len() - 1);+ self.moved_from(before);+ return DOut::None;+ }+ if double { return self.open((self.cols[c].dir.join(&e.name), e.dir)) }+ self.select(c, i);+ DOut::None+ }++ /// The wheel over the column (or the sidebar) under the pointer.+ pub(super) fn wheel(&mut self, x: u16, down: bool) {+ let l = layout(self.size.0, self.size.1);+ let c = match self.view {+ DView::Columns if x >= l.main.x => { let (start, _, _) = self.shown(l.main.width); start + ((x - l.main.x) / COL_W) as usize }+ _ => self.active,+ };+ let step = if self.view == DView::Icons { (l.main.width / TILE_W).max(1) as usize } else { 3 };+ if let Some(col) = self.cols.get_mut(c) {+ let max = col.rows.len().saturating_sub(1);+ col.scroll = if down { (col.scroll + step).min(max) } else { col.scroll.saturating_sub(step) };+ }+ }++ /// Where the path popup is: under the folder's name, as wide as its longest.+ fn popup_at(&self) -> (u16, u16, u16) {+ let x = self.tools().iter().find(|t| t.2 == Tool::Path).map(|t| t.0).unwrap_or(2);+ let w = self.popup.as_ref().map(|(items, _)| items.iter().map(|p| p.to_string_lossy().width()).max().unwrap_or(1)).unwrap_or(10) as u16 + 4;+ (x.saturating_sub(1), 2, w.min(self.size.0.saturating_sub(x)))+ }++ // ── drawing ──────────────────────────────────────────────────────────────++ /// Each column's selection brought into view when it moved (the wheel scrolls past it).+ fn fit(&mut self) {+ let l = layout(self.size.0, self.size.1);+ let rows = l.main.height.max(1) as usize;+ let (across, tiles_down) = ((l.main.width / TILE_W).max(1) as usize, (l.main.height / TILE_H).max(1) as usize);+ let (follow, icons, active) = (std::mem::take(&mut self.follow), self.view == DView::Icons, self.active);+ for (i, c) in self.cols.iter_mut().enumerate() {+ c.scroll = c.scroll.min(c.rows.len().saturating_sub(1));+ let Some(at) = c.at().filter(|_| follow) else { continue };+ if icons && i == active {+ let (r, top) = (at / across, c.scroll / across);+ let top = if r < top { r } else if r >= top + tiles_down { r + 1 - tiles_down } else { top };+ c.scroll = top * across;+ } else if at < c.scroll { c.scroll = at } else if at >= c.scroll + rows { c.scroll = at + 1 - rows }+ }+ }++ pub(super) fn draw(&mut self, buf: &mut Buffer, area: Rect, look: &Look) {+ self.size = (area.width, area.height);+ self.fit();+ let l = layout(area.width, area.height);+ let (ox, oy) = (area.x, area.y);+ let at = |x: u16, y: u16| (ox + x, oy + y);+ frame(buf, area, look.muted);+ let title = " Open ";+ put(buf, ox + (area.width.saturating_sub(title.width() as u16)) / 2, oy, title.width() as u16, title, look.text.add_modifier(Modifier::BOLD));+ // Rules under the toolbar and over the buttons, and between the sidebar and the columns.+ for y in [2, l.bottom.saturating_sub(1)] { put(buf, ox, oy + y, area.width, &format!("├{}┤", "─".repeat(area.width.saturating_sub(2) as usize)), look.muted); }+ for y in l.side.y..l.side.y + l.side.height { let (x, y) = at(l.side.x + l.side.width, y); put(buf, x, y, 1, "│", look.muted); }+ self.draw_toolbar(buf, area, look);+ self.draw_sidebar(buf, area, l, look);+ match self.view { DView::Columns => self.draw_columns(buf, area, l, look), DView::Icons => self.draw_icons(buf, area, l, look) }+ // The bottom row: what was said, else the keys; Cancel and Open.+ let buttons = self.buttons();+ let room = buttons[0].0.saturating_sub(3);+ let (text, st) = match &self.message { Some(m) => (m.clone(), look.warn), None => ("Enter open · Esc cancel · Tab sidebar/columns/buttons · / search".to_string(), look.muted) };+ put(buf, ox + 2, oy + l.bottom, room, &fit(&text, room as usize), st);+ for (b, (a, _, label)) in buttons.iter().enumerate() {+ let mut st = if b == 1 { look.mode.add_modifier(Modifier::BOLD) } else { look.text };+ if self.focus == Focus::Buttons && self.button == b { st = st.add_modifier(Modifier::UNDERLINED | Modifier::BOLD) }+ put(buf, ox + a, oy + l.bottom, label.width() as u16, label, st);+ }+ if let Some((items, sel)) = &self.popup {+ let (px, py, pw) = self.popup_at();+ let r = Rect::new(ox + px, oy + py, pw, items.len() as u16 + 2).intersection(area);+ frame(buf, r, look.muted);+ for (i, p) in items.iter().enumerate() {+ let label = if p == Path::new("/") { "/".to_string() } else { name_of(p) };+ put(buf, r.x + 1, r.y + 1 + i as u16, pw.saturating_sub(2), &format!(" {:<w$}", label, w = pw.saturating_sub(3) as usize), if i == *sel { look.mode } else { look.text });+ }+ }+ }++ fn draw_toolbar(&self, buf: &mut Buffer, area: Rect, look: &Look) {+ let (ox, oy) = (area.x, area.y + 1);+ for (a, z, t) in self.tools() {+ let (text, st) = match t {+ Tool::Back => ("◀".to_string(), if self.back.is_empty() { look.muted } else { look.text }),+ Tool::Forward => ("▶".to_string(), if self.fwd.is_empty() { look.muted } else { look.text }),+ Tool::Columns => (" ▥ Columns ".to_string(), if self.view == DView::Columns { look.mode } else { look.muted }),+ Tool::Icons => (" ▦ Icons ".to_string(), if self.view == DView::Icons { look.mode } else { look.muted }),+ Tool::Path => (fit(&self.path_label(), (z - a) as usize), look.text.add_modifier(Modifier::BOLD)),+ Tool::Search => {+ let w = (z - a) as usize;+ let (q, st) = if self.search.is_empty() && self.focus != Focus::Search { ("Search".to_string(), look.muted) } else { (format!("{}{}", self.search, if self.focus == Focus::Search { "▏" } else { "" }), look.text) };+ (format!("⌕ {:<w$}", fit(&q, w.saturating_sub(2)), w = w.saturating_sub(2)), st.add_modifier(Modifier::UNDERLINED))+ }+ };+ put(buf, ox + a, oy, z - a, &text, st);+ }+ }++ fn draw_sidebar(&self, buf: &mut Buffer, area: Rect, l: Layout, look: &Look) {+ let (ox, oy, w) = (area.x + l.side.x, area.y + l.side.y, l.side.width);+ let first = self.cols[0].dir.clone();+ for (k, row) in self.side_rows().into_iter().enumerate().take(l.side.height as usize) {+ let y = oy + k as u16;+ match row {+ None => {}+ Some(Ok(title)) => { put(buf, ox + 1, y, w.saturating_sub(1), title, look.muted.add_modifier(Modifier::BOLD)); }+ Some(Err(i)) => {+ let p = &self.places[i];+ let on = p.path == first;+ let st = if self.focus == Focus::Sidebar && self.side_sel == i { look.mode } else if on { look.accent.add_modifier(Modifier::BOLD) } else { look.text };+ put(buf, ox + 1, y, w.saturating_sub(1), &format!(" {} {:<n$}", p.icon, fit(&p.label, w.saturating_sub(5) as usize), n = w.saturating_sub(5) as usize), st);+ }+ }+ }+ }++ fn draw_columns(&mut self, buf: &mut Buffer, area: Rect, l: Layout, look: &Look) {+ let (start, n, total) = self.shown(l.main.width);+ let (ox, oy) = (area.x, area.y);+ for k in 0..n {+ let c = start + k;+ let x = ox + l.main.x + k as u16 * COL_W;+ // The last one takes what is left (the preview the most of it).+ let w = if k + 1 == n { (l.main.x + l.main.width).saturating_sub(l.main.x + k as u16 * COL_W) } else { COL_W - 1 };+ if c == self.cols.len() && c + 1 == total { self.draw_preview(buf, Rect::new(x, oy + l.main.y, w, l.main.height), look); continue }+ let col = &self.cols[c];+ if k + 1 < n { for y in 0..l.main.height { put(buf, x + COL_W - 1, oy + l.main.y + y, 1, "│", look.muted); } }+ if let Some(e) = &col.error { put(buf, x + 1, oy + l.main.y, w.saturating_sub(2), &fit(e, w.saturating_sub(2) as usize), look.warn); continue }+ if col.rows.is_empty() { put(buf, x + 1, oy + l.main.y, w.saturating_sub(2), if self.search.is_empty() { "Empty" } else { "No matches" }, look.muted); continue }+ for (r, &i) in col.rows.iter().enumerate().skip(col.scroll).take(l.main.height as usize) {+ let e = &col.entries[i];+ let y = oy + l.main.y + (r - col.scroll) as u16;+ let selected = col.sel == Some(i);+ let st = if !selected { look.text } else if c == self.active && self.focus != Focus::Sidebar { look.mode } else { look.text.add_modifier(Modifier::REVERSED | Modifier::DIM) };+ let icon_st = if selected { st } else if e.dir { look.accent } else { file_style(&e.name, look) };+ put(buf, x, y, w, &" ".repeat(w as usize), st);+ let iw = put(buf, x + 1, y, 3, icon(e, self.nerd), icon_st);+ let name_w = w.saturating_sub(iw + 5);+ put(buf, x + 2 + iw, y, name_w, &shorten(&e.name, e.dir, name_w as usize), st);+ if e.dir { put(buf, x + w.saturating_sub(2), y, 1, "›", st); }+ }+ }+ }++ /// The preview of the file selected: its picture, name, kind, size and date, and the first+ /// lines of a text file.+ fn draw_preview(&mut self, buf: &mut Buffer, r: Rect, look: &Look) {+ let Some((path, e)) = self.preview_entry().map(|(p, e)| (p, e.clone())) else { return };+ if self.preview.as_ref().map(|p| &p.0) != Some(&path) {+ let lines = std::fs::File::open(&path).ok().and_then(|f| {+ use std::io::Read;+ let mut head = Vec::new();+ f.take(8192).read_to_end(&mut head).ok()?;+ // (A UTF-8 character the 8 KB cut in two is not a reason to call it binary.)+ let text = match std::str::from_utf8(&head) { Ok(t) => t.to_string(), Err(err) if err.error_len().is_none() => String::from_utf8_lossy(&head[..err.valid_up_to()]).into_owned(), Err(_) => return None };+ editor::is_text(&e.name, text.as_bytes()).then(|| text.lines().take(10).map(|l| l.replace('\t', " ")).collect())+ });+ self.preview = Some((path.clone(), lines));+ }+ let x = r.x + 2;+ let w = r.width.saturating_sub(4);+ let st = file_style(&e.name, look);+ for (dy, line) in art(&e).iter().enumerate() { put(buf, x + w.saturating_sub(line.width() as u16) / 2, r.y + 1 + dy as u16, w, line, st); }+ let name = shorten(&e.name, false, w as usize);+ put(buf, x + w.saturating_sub(name.width() as u16) / 2, r.y + 6, w, &name, look.text.add_modifier(Modifier::BOLD));+ let when = e.modified.map(|t| ops::when(t, SystemTime::now())).unwrap_or_else(|| "—".into());+ for (k, (label, value)) in [("Kind", ops::kind(&e.name, false)), ("Size", ops::human_size(e.size)), ("Modified", when)].into_iter().enumerate() {+ let y = r.y + 8 + k as u16;+ put(buf, x, y, 9, label, look.muted);+ put(buf, x + 10, y, w.saturating_sub(10), &value, look.text);+ }+ if let Some((_, Some(lines))) = &self.preview {+ for (k, line) in lines.iter().enumerate() {+ let y = r.y + 12 + k as u16;+ if y >= r.y + r.height { break }+ put(buf, x, y, w, &fit(line, w as usize), look.muted);+ }+ }+ }++ fn draw_icons(&self, buf: &mut Buffer, area: Rect, l: Layout, look: &Look) {+ let col = &self.cols[self.active];+ let across = (l.main.width / TILE_W).max(1) as usize;+ let down = (l.main.height / TILE_H) as usize;+ for (k, &i) in col.rows.iter().enumerate().skip(col.scroll).take(across * down) {+ let k = k - col.scroll;+ let (x, y) = (area.x + l.main.x + (k % across) as u16 * TILE_W + 1, area.y + l.main.y + (k / across) as u16 * TILE_H);+ tile(buf, x, y, &col.entries[i], col.sel == Some(i), false, look);+ }+ if col.rows.is_empty() { put(buf, area.x + l.main.x + 1, area.y + l.main.y, l.main.width, if self.search.is_empty() { "Empty" } else { "No matches" }, look.muted); }+ }+}++fn contains(r: Rect, x: u16, y: u16) -> bool { super::contains(r, x, y) }++#[cfg(test)]+mod tests {+ use super::*;++ struct Scratch(PathBuf);+ impl Scratch {+ fn new(files: &[(&str, &str)]) -> Scratch {+ let root = std::env::temp_dir().join(format!("hn-dialog-{}", uuid::Uuid::new_v4()));+ for (f, body) in files {+ let p = root.join(f);+ if f.ends_with('/') { std::fs::create_dir_all(&p).unwrap() } else { std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(&p, body).unwrap() }+ }+ Scratch(root)+ }+ fn dialog(&self) -> Dialog { let mut d = Dialog::new(self.0.join("me"), false, self.0.join("state/open-recent.json")); d.size = (130, 34); d }+ }+ impl Drop for Scratch { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } }++ fn k(code: KeyCode) -> Chord { Chord::normal(code, KeyModifiers::NONE) }+ fn text(d: &mut Dialog, w: u16, h: u16) -> String {+ let area = Rect::new(0, 0, w, h);+ let mut buf = Buffer::empty(area);+ d.draw(&mut buf, area, &Look::default());+ (0..h).map(|y| (0..w).map(|x| buf[(x, y)].symbol()).collect::<String>()).collect::<Vec<_>>().join("\n")+ }+ fn row_of(d: &Dialog, c: usize, name: &str) -> u16 { layout(d.size.0, d.size.1).main.y + d.cols[c].rows.iter().position(|i| d.cols[c].entries[*i].name == name).unwrap() as u16 }+ fn col_x(d: &Dialog, c: usize) -> u16 { let l = layout(d.size.0, d.size.1); l.main.x + (c - d.shown(l.main.width).0) as u16 * COL_W + 4 }++ #[test]+ fn the_dialog_has_its_toolbar_sidebar_columns_preview_and_buttons_in_a_box() {+ let s = Scratch::new(&[("me/projects/app/main.py", "import os\nprint('xin chào')\n"), ("me/notes.md", "# hi\n")]);+ let mut d = s.dialog();+ let x = col_x(&d, 0);+ d.click(x, row_of(&d, 0, "projects"), false);+ assert_eq!(d.cols.len(), 2, "a folder clicked shows its column");+ d.click(col_x(&d, 1), row_of(&d, 1, "app"), false);+ d.key(k(KeyCode::Right));+ assert_eq!(d.active, 2);+ assert!(d.preview_entry().is_some_and(|(p, _)| p.ends_with("app/main.py")), "its first entry, a file, previewed");+ let t = text(&mut d, 130, 34);+ let lines: Vec<&str> = t.lines().collect();+ assert!(lines[0].starts_with('╭') && lines[0].contains(" Open ") && lines[33].starts_with('╰'), "{t}");+ assert!(lines[1].contains("◀ ▶") && lines[1].contains("Columns") && lines[1].contains("Icons") && lines[1].contains("app ▾") && lines[1].contains("⌕ Search"), "{}", lines[1]);+ assert!(t.contains("Favorites") && t.contains("Home") && t.contains("Locations") && t.contains("Computer"), "{t}");+ assert!(t.contains("[/] app") && t.contains("main.py") && t.contains("Python script") && t.contains("print('xin chào')"), "{t}");+ assert!(lines[32].contains("[ Cancel ]") && lines[32].contains("[ Open ]"));+ // It fits a small window too.+ let small = text(&mut d, 90, 24);+ assert!(small.lines().nth(22).unwrap().contains("[ Open ]") && small.contains("main.py"), "{small}");+ }++ #[test]+ fn left_right_back_forward_and_the_path_popup() {+ let s = Scratch::new(&[("me/a/b/c.txt", "x"), ("me/z/", "")]);+ let mut d = s.dialog();+ d.key(k(KeyCode::Down));+ assert_eq!(d.cols[0].selected().map(|e| e.name.as_str()), Some("a"));+ d.key(k(KeyCode::Right));+ d.key(k(KeyCode::Right));+ assert_eq!((d.active, d.current()), (2, s.0.join("me/a/b")));+ d.key(k(KeyCode::Left));+ assert_eq!(d.current(), s.0.join("me/a"));+ d.key(Chord::normal(KeyCode::Left, KeyModifiers::ALT));+ assert_eq!(d.current(), s.0.join("me/a/b"), "Back to where it was");+ d.key(Chord::normal(KeyCode::Right, KeyModifiers::ALT));+ assert_eq!(d.current(), s.0.join("me/a"));+ // The path popup: the folders above, one chosen shown first.+ let (px, ..) = d.tools().into_iter().find(|t| t.2 == Tool::Path).unwrap();+ d.click(px, 1, false);+ let items = d.popup.as_ref().unwrap().0.clone();+ assert_eq!(&items[..3], [s.0.join("me/a"), s.0.join("me"), s.0.clone()]);+ let (x, y, _) = d.popup_at();+ d.click(x + 1, y + 2, false);+ assert_eq!((d.cols.len(), d.current()), (1, s.0.join("me")));+ // Backspace above the first column: its parent, the folder selected.+ d.key(k(KeyCode::Backspace));+ assert_eq!(d.cols[0].dir, s.0);+ assert_eq!(d.cols[0].selected().map(|e| e.name.as_str()), Some("me"));+ }++ #[test]+ fn search_filters_the_deepest_column_and_esc_clears_it() {+ let s = Scratch::new(&[("me/Report.md", ""), ("me/notes.txt", ""), ("me/report-2.md", "")]);+ let mut d = s.dialog();+ d.key(k(KeyCode::Char('/')));+ for c in "rep".chars() { d.key(k(KeyCode::Char(c))); }+ assert_eq!(d.cols[0].rows.len(), 2);+ d.key(k(KeyCode::Enter));+ d.key(k(KeyCode::Esc));+ assert_eq!((d.cols[0].rows.len(), d.search.as_str()), (3, ""), "Esc clears the search first");+ assert_eq!(d.key(k(KeyCode::Esc)), DOut::Cancel);+ }++ #[test]+ fn open_takes_a_folder_or_a_text_file_and_keeps_it_in_recent() {+ let s = Scratch::new(&[("me/app/main.py", "print(1)\n"), ("me/logo.png", "\u{0}PNG")]);+ let mut d = s.dialog();+ // A picture: said, still open.+ d.click(col_x(&d, 0), row_of(&d, 0, "logo.png"), true);+ assert_eq!(d.message.as_deref(), Some("Can't open 'logo.png': not a text file"));+ // A folder double-clicked: opened.+ assert_eq!(d.click(col_x(&d, 0), row_of(&d, 0, "app"), true), DOut::Open(s.0.join("me/app"), true));+ // Enter on a text file; Open with nothing selected: the folder on show.+ d.click(col_x(&d, 0), row_of(&d, 0, "app"), false);+ d.key(k(KeyCode::Right));+ assert_eq!(d.key(k(KeyCode::Enter)), DOut::Open(s.0.join("me/app/main.py"), false));+ let mut e = s.dialog();+ let (ox, ..) = e.buttons()[1];+ assert_eq!(e.click(ox + 1, layout(130, 34).bottom, false), DOut::Open(s.0.join("me"), true));+ // Recent: the latest first, once each, those still there.+ let recent = load_recent(&s.0.join("state/open-recent.json"));+ assert_eq!(recent, [s.0.join("me"), s.0.join("me/app/main.py"), s.0.join("me/app")]);+ for i in 0..30 { push_recent(&s.0.join("state/open-recent.json"), &s.0.join(format!("x{i}"))) }+ assert_eq!(load_recent(&s.0.join("state/open-recent.json")).len(), RECENT_KEPT);+ let d2 = s.dialog();+ assert!(d2.places.iter().filter(|p| p.section == 1).count() <= RECENT_SHOWN);+ }++ #[test]+ fn icons_view_is_the_folder_as_tiles_a_folder_double_clicked_gone_into() {+ let s = Scratch::new(&[("me/app/x.txt", ""), ("me/b.txt", "")]);+ let mut d = s.dialog();+ let (ix, ..) = d.tools().into_iter().find(|t| t.2 == Tool::Icons).unwrap();+ d.click(ix + 1, 1, false);+ assert_eq!(d.view, DView::Icons);+ let l = layout(130, 34);+ d.click(l.main.x + 3, l.main.y + 1, true);+ assert_eq!(d.current(), s.0.join("me/app"));+ let t = text(&mut d, 130, 34);+ assert!(t.contains("x.txt"), "{t}");+ }+}diff --git a/tui/src/files/editor.rs b/tui/src/files/editor.rsnew file mode 100644index 000000000..9c2116d0f--- /dev/null+++ b/tui/src/files/editor.rs@@ -0,0 +1,721 @@+//! The file manager's own text editor (`hn files`): a text file filling the window — its name and+//! whether it changed, line numbers, the text (tabs four wide, scrolled sideways rather than+//! wrapped), and a status row — edited as a desktop editor does: arrows (Shift selecting, Ctrl by+//! word), cut, copy and paste, undo and redo, find, go to line, and Ctrl+S saving in place+//! atomically with the file's own line endings, final newline, byte-order mark and permissions.++use std::path::{Path, PathBuf};++use crossterm::event::{KeyCode, KeyModifiers};+use ratatui::buffer::Buffer;+use ratatui::layout::Rect;+use ratatui::style::{Modifier, Style};+use unicode_segmentation::UnicodeSegmentation;+use unicode_width::UnicodeWidthStr;++use super::{frame, name_of, put, Look};+use crate::keys::Chord;++/// The largest file opened here.+pub(super) const MAX_SIZE: u64 = 10 * 1000 * 1000;+const TAB: usize = 4;+/// How many changes undo goes back.+const HISTORY: usize = 200;+const BOM: &str = "\u{feff}";++/// Why a file can't be opened here, as the footer says it.+#[derive(Debug, PartialEq, Eq)]+pub(super) enum Refusal { NotText, TooLarge, Unreadable(String) }++/// Whether [bytes] (a file's first, or all of it) are text: no NUL in the first 8 KB, UTF-8 (a+/// byte-order mark allowed). [name]'s extension refuses the plainly binary ones first.+pub(super) fn is_text(name: &str, bytes: &[u8]) -> bool {+ const BINARY: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "tif", "tiff", "pdf", "zip", "gz", "tgz", "xz", "bz2", "zst", "7z", "rar", "tar",+ "exe", "dll", "so", "dylib", "o", "a", "class", "jar", "wasm", "mp3", "wav", "flac", "ogg", "m4a", "mp4", "mkv", "webm", "mov", "avi", "iso", "img", "deb", "rpm", "woff", "woff2", "ttf", "otf", "sqlite", "db"];+ let ext = name.rsplit_once('.').filter(|(s, _)| !s.is_empty()).map(|(_, x)| x.to_ascii_lowercase()).unwrap_or_default();+ if BINARY.contains(&ext.as_str()) { return false }+ if bytes[..bytes.len().min(8192)].contains(&0) { return false }+ std::str::from_utf8(bytes.strip_prefix(BOM.as_bytes()).unwrap_or(bytes)).is_ok()+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]+pub(super) struct Pos { pub line: usize, pub col: usize }++/// A state undo goes back to: the text, the cursor, and which version of the text it was.+#[derive(Clone, Debug)]+struct Snap { lines: Vec<String>, cur: Pos, version: u64 }++/// What a run of keys changes, for undo to take back as one: typing, deleting, or anything else.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Kind { Type, Delete, Other }++/// What the editor's bottom row is asking for, when it is: a word to find, a line to go to.+#[derive(Clone, Debug, PartialEq, Eq)]+enum Bar { Find(String), Line(String) }++/// What a key asks of the window: the editor closed, or text for the clipboard.+#[derive(Debug, PartialEq, Eq)]+pub(super) enum EdOut { None, Close, Clipboard(String) }++#[derive(Debug)]+pub(super) struct Editor {+ path: PathBuf,+ title: String,+ pub(super) lines: Vec<String>,+ crlf: bool,+ bom: bool,+ newline_at_end: bool,+ pub(super) readonly: bool,+ pub(super) cur: Pos,+ /// Where the selection started: it runs from here to the cursor.+ pub(super) anchor: Option<Pos>,+ /// The column up and down keep to across shorter lines.+ want: Option<usize>,+ top: usize,+ left: usize,+ version: u64,+ next_version: u64,+ saved: u64,+ undo: Vec<Snap>,+ redo: Vec<Snap>,+ last: Option<Kind>,+ clip: String,+ bar: Option<Bar>,+ /// The last word found, lit where it is.+ find: String,+ /// "Save changes?": which of Save, Don't save and Cancel has the keys.+ pub(super) asking: Option<usize>,+ pub(super) message: Option<String>,+ size: (u16, u16),+}++impl Editor {+ /// [path] read to be edited, [title] its name as shown; why not, when it can't be.+ pub(super) fn open(path: &Path, title: String) -> Result<Editor, Refusal> {+ let meta = std::fs::metadata(path).map_err(|e| Refusal::Unreadable(e.to_string()))?;+ if !meta.is_file() { return Err(Refusal::NotText) }+ if meta.len() > MAX_SIZE { return Err(Refusal::TooLarge) }+ let bytes = std::fs::read(path).map_err(|e| Refusal::Unreadable(e.to_string()))?;+ if !is_text(&name_of(path), &bytes) { return Err(Refusal::NotText) }+ let text = String::from_utf8(bytes).map_err(|_| Refusal::NotText)?;+ let bom = text.starts_with(BOM);+ let text = text.strip_prefix(BOM).unwrap_or(&text);+ let crlf = text.find('\n').is_some_and(|i| i > 0 && text.as_bytes()[i - 1] == b'\r');+ let newline_at_end = text.ends_with('\n');+ let mut lines: Vec<String> = text.split('\n').map(|l| if crlf { l.strip_suffix('\r').unwrap_or(l).to_string() } else { l.to_string() }).collect();+ if newline_at_end { lines.pop(); }+ if lines.is_empty() { lines.push(String::new()) }+ let readonly = meta.permissions().readonly() || !writable(path);+ Ok(Editor {+ path: path.to_path_buf(), title, lines, crlf, bom, newline_at_end, readonly, cur: Pos::default(), anchor: None, want: None, top: 0, left: 0,+ version: 0, next_version: 1, saved: 0, undo: Vec::new(), redo: Vec::new(), last: None, clip: String::new(), bar: None, find: String::new(),+ asking: None, message: None, size: (80, 24),+ })+ }++ pub(super) fn modified(&self) -> bool { self.version != self.saved }++ /// The file's text as it would be saved.+ pub(super) fn text(&self) -> String {+ let mut out = String::from(if self.bom { BOM } else { "" });+ out.push_str(&self.lines.join(if self.crlf { "\r\n" } else { "\n" }));+ if self.newline_at_end { out.push_str(if self.crlf { "\r\n" } else { "\n" }) }+ out+ }++ /// Ctrl+S: written beside the file and renamed over it (never half written), its permissions+ /// kept. What went wrong, if it did.+ pub(super) fn save(&mut self) -> Result<(), String> {+ use std::io::Write;+ if self.readonly { return Err("read-only: this file can't be saved here".into()) }+ let dir = self.path.parent().unwrap_or(Path::new("/"));+ let tmp = dir.join(format!(".{}.hn-save-{}", name_of(&self.path), std::process::id()));+ let perms = std::fs::metadata(&self.path).map(|m| m.permissions()).ok();+ let write = || -> std::io::Result<()> {+ let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;+ f.write_all(self.text().as_bytes())?;+ f.sync_all()?;+ if let Some(p) = perms.clone() { std::fs::set_permissions(&tmp, p)? }+ std::fs::rename(&tmp, &self.path)+ };+ match write() {+ Ok(()) => { self.saved = self.version; Ok(()) }+ Err(e) => { let _ = std::fs::remove_file(&tmp); Err(format!("Couldn't save: {e}")) }+ }+ }++ // ── positions ────────────────────────────────────────────────────────────++ fn line(&self) -> &str { &self.lines[self.cur.line] }++ /// The selection, start first, when there is one.+ pub(super) fn selection(&self) -> Option<(Pos, Pos)> { self.anchor.filter(|a| *a != self.cur).map(|a| (a.min(self.cur), a.max(self.cur))) }++ fn selected_text(&self) -> Option<String> {+ let (a, b) = self.selection()?;+ if a.line == b.line { return Some(self.lines[a.line][a.col..b.col].to_string()) }+ let mut out = self.lines[a.line][a.col..].to_string();+ for l in &self.lines[a.line + 1..b.line] { out.push('\n'); out.push_str(l) }+ out.push('\n');+ out.push_str(&self.lines[b.line][..b.col]);+ Some(out)+ }++ /// A move: the selection grown with [extend] (Shift), else gone; an edit run ended.+ fn go(&mut self, to: Pos, extend: bool, keep_want: bool) {+ if extend { if self.anchor.is_none() { self.anchor = Some(self.cur) } } else { self.anchor = None }+ self.cur = to;+ if !keep_want { self.want = None }+ self.last = None;+ }++ fn left_of(&self, p: Pos) -> Pos {+ if p.col > 0 { return Pos { line: p.line, col: prev(&self.lines[p.line], p.col) } }+ if p.line > 0 { return Pos { line: p.line - 1, col: self.lines[p.line - 1].len() } }+ p+ }++ fn right_of(&self, p: Pos) -> Pos {+ let l = &self.lines[p.line];+ if p.col < l.len() { return Pos { line: p.line, col: next(l, p.col) } }+ if p.line + 1 < self.lines.len() { return Pos { line: p.line + 1, col: 0 } }+ p+ }++ /// Ctrl+Left / Ctrl+Right: to the start of this word or the last, the end of this one or the next.+ fn word(&self, p: Pos, forward: bool) -> Pos {+ let l = &self.lines[p.line];+ let gs: Vec<(usize, &str)> = l.grapheme_indices(true).collect();+ let is_word = |g: &str| g.chars().next().is_some_and(|c| c.is_alphanumeric() || c == '_');+ let mut i = gs.iter().position(|(b, _)| *b >= p.col).unwrap_or(gs.len());+ if forward {+ if i >= gs.len() { return self.right_of(p) }+ while i < gs.len() && !is_word(gs[i].1) { i += 1 }+ while i < gs.len() && is_word(gs[i].1) { i += 1 }+ Pos { line: p.line, col: gs.get(i).map(|g| g.0).unwrap_or(l.len()) }+ } else {+ if i == 0 { return self.left_of(p) }+ while i > 0 && !is_word(gs[i - 1].1) { i -= 1 }+ while i > 0 && is_word(gs[i - 1].1) { i -= 1 }+ Pos { line: p.line, col: gs.get(i).map(|g| g.0).unwrap_or(0) }+ }+ }++ /// Up or down [n] lines, at the column it was at.+ fn vertical(&mut self, n: isize, extend: bool) {+ let want = self.want.unwrap_or_else(|| col_of(self.line(), self.cur.col));+ let line = (self.cur.line as isize + n).clamp(0, self.lines.len() as isize - 1) as usize;+ let col = byte_at(&self.lines[line], want);+ self.go(Pos { line, col }, extend, true);+ self.want = Some(want);+ }++ // ── changes ──────────────────────────────────────────────────────────────++ /// Before a change of [kind]: the state kept for undo, unless it continues a run of the same.+ fn change(&mut self, kind: Kind) {+ if self.last != Some(kind) || kind == Kind::Other {+ self.undo.push(Snap { lines: self.lines.clone(), cur: self.cur, version: self.version });+ if self.undo.len() > HISTORY { self.undo.remove(0); }+ }+ self.redo.clear();+ self.last = Some(kind);+ self.version = self.next_version;+ self.next_version += 1;+ self.want = None;+ }++ fn remove(&mut self, a: Pos, b: Pos) {+ if a.line == b.line { self.lines[a.line].replace_range(a.col..b.col, ""); } else {+ let tail = self.lines[b.line][b.col..].to_string();+ self.lines[a.line].truncate(a.col);+ self.lines[a.line].push_str(&tail);+ self.lines.drain(a.line + 1..=b.line);+ }+ self.cur = a;+ self.anchor = None;+ }++ fn delete_selection(&mut self) -> bool {+ let Some((a, b)) = self.selection() else { self.anchor = None; return false };+ self.remove(a, b);+ true+ }++ fn insert(&mut self, text: &str) {+ let tail = self.lines[self.cur.line].split_off(self.cur.col);+ let mut parts = text.split('\n');+ self.lines[self.cur.line].push_str(parts.next().unwrap_or(""));+ let mut at = self.cur.line;+ for p in parts { at += 1; self.lines.insert(at, p.to_string()); }+ self.cur = Pos { line: at, col: self.lines[at].len() };+ self.lines[at].push_str(&tail);+ }++ /// [text] typed (or pasted) in place of the selection.+ fn type_text(&mut self, text: &str, kind: Kind) {+ if self.refuse() { return }+ let kind = if self.selection().is_some() { Kind::Other } else { kind };+ self.change(kind);+ self.delete_selection();+ self.insert(text);+ }++ fn refuse(&mut self) -> bool {+ if self.readonly { self.message = Some("read-only: this file can't be changed here".into()) }+ self.readonly+ }++ /// Backspace ([back]) or Delete: the selection, else the character before or after.+ fn delete(&mut self, back: bool) {+ if self.refuse() { return }+ if self.selection().is_some() { self.change(Kind::Other); self.delete_selection(); return }+ let (a, b) = if back { (self.left_of(self.cur), self.cur) } else { (self.cur, self.right_of(self.cur)) };+ if a == b { return }+ self.change(Kind::Delete);+ self.remove(a, b);+ }++ fn undo_redo(&mut self, back: bool) {+ let (from, to) = if back { (&mut self.undo, &mut self.redo) } else { (&mut self.redo, &mut self.undo) };+ let Some(s) = from.pop() else { return };+ to.push(Snap { lines: std::mem::replace(&mut self.lines, s.lines), cur: self.cur, version: self.version });+ self.cur = s.cur;+ self.version = s.version;+ self.anchor = None;+ self.last = None;+ self.cur.line = self.cur.line.min(self.lines.len() - 1);+ self.cur.col = self.cur.col.min(self.lines[self.cur.line].len());+ }++ // ── find ─────────────────────────────────────────────────────────────────++ /// The next (else the last) place [find] is, from the cursor round; selected.+ fn find_next(&mut self, forward: bool) {+ if self.find.is_empty() { return }+ let n = self.lines.len();+ let start = self.selection().map(|(a, b)| if forward { b } else { a }).unwrap_or(self.cur);+ for k in 0..=n {+ let line = if forward { (start.line + k) % n } else { (start.line + n * 2 - k) % n };+ let l = &self.lines[line];+ let hit = if forward {+ let from = if k == 0 { start.col } else { 0 };+ l.get(from..).and_then(|s| s.find(&self.find)).map(|i| i + from)+ } else {+ let to = if k == 0 { start.col } else { l.len() };+ l.get(..to).and_then(|s| s.rfind(&self.find))+ };+ if let Some(i) = hit {+ self.anchor = Some(Pos { line, col: i });+ self.cur = Pos { line, col: i + self.find.len() };+ self.message = None;+ return;+ }+ }+ self.message = Some(format!("'{}' isn't in this file", self.find));+ }++ // ── keys and the mouse ───────────────────────────────────────────────────++ pub(super) fn key(&mut self, k: Chord) -> EdOut {+ self.message = None;+ if let Some(focus) = self.asking { return self.ask_key(k, focus) }+ if self.bar.is_some() { self.bar_key(k); self.fit(); return EdOut::None }+ let (shift, ctrl) = (k.mods.contains(KeyModifiers::SHIFT), k.mods.contains(KeyModifiers::CONTROL));+ let ctrl_is = |c: char| ctrl && matches!(k.code, KeyCode::Char(x) if x.eq_ignore_ascii_case(&c));+ let page = self.size.1.saturating_sub(3).max(1) as isize;+ let mut out = EdOut::None;+ match k.code {+ KeyCode::Esc => return self.close(),+ _ if ctrl_is('q') || ctrl_is('w') => return self.close(),+ _ if ctrl_is('s') => { self.message = Some(match self.save() { Ok(()) => format!("Saved {}", self.title), Err(e) => e }) }+ _ if ctrl_is('z') && shift => self.undo_redo(false),+ _ if ctrl_is('z') => self.undo_redo(true),+ _ if ctrl_is('y') => self.undo_redo(false),+ _ if ctrl_is('a') => { self.anchor = Some(Pos::default()); let l = self.lines.len() - 1; self.cur = Pos { line: l, col: self.lines[l].len() } }+ _ if ctrl_is('c') || ctrl_is('x') => {+ if let Some(t) = self.selected_text() {+ self.clip = t.clone();+ if ctrl_is('x') && !self.refuse() { self.change(Kind::Other); self.delete_selection(); }+ out = EdOut::Clipboard(t);+ }+ }+ _ if ctrl_is('v') => { if !self.clip.is_empty() { let t = self.clip.clone(); self.type_text(&t, Kind::Other) } }+ _ if ctrl_is('f') => self.bar = Some(Bar::Find(self.selected_text().filter(|t| !t.contains('\n')).unwrap_or_else(|| self.find.clone()))),+ _ if ctrl_is('g') => self.bar = Some(Bar::Line(String::new())),+ KeyCode::F(3) => self.find_next(!shift),+ KeyCode::Left if ctrl => { let p = self.word(self.cur, false); self.go(p, shift, false) }+ KeyCode::Right if ctrl => { let p = self.word(self.cur, true); self.go(p, shift, false) }+ KeyCode::Left => { let p = match self.selection() { Some((a, _)) if !shift => a, _ => self.left_of(self.cur) }; self.go(p, shift, false) }+ KeyCode::Right => { let p = match self.selection() { Some((_, b)) if !shift => b, _ => self.right_of(self.cur) }; self.go(p, shift, false) }+ KeyCode::Up => self.vertical(-1, shift),+ KeyCode::Down => self.vertical(1, shift),+ KeyCode::PageUp => self.vertical(-page, shift),+ KeyCode::PageDown => self.vertical(page, shift),+ KeyCode::Home if ctrl => self.go(Pos::default(), shift, false),+ KeyCode::End if ctrl => { let l = self.lines.len() - 1; self.go(Pos { line: l, col: self.lines[l].len() }, shift, false) }+ KeyCode::Home => {+ // To the line's first non-blank, then (again) its very start.+ let indent = self.line().len() - self.line().trim_start().len();+ let col = if self.cur.col == indent { 0 } else { indent };+ self.go(Pos { line: self.cur.line, col }, shift, false)+ }+ KeyCode::End => self.go(Pos { line: self.cur.line, col: self.line().len() }, shift, false),+ KeyCode::Enter => {+ // A new line indented as this one is.+ let indent: String = self.line().chars().take_while(|c| *c == ' ' || *c == '\t').collect();+ self.type_text(&format!("\n{indent}"), Kind::Other)+ }+ KeyCode::Backspace => self.delete(true),+ KeyCode::Delete => self.delete(false),+ KeyCode::Tab => self.type_text("\t", Kind::Type),+ KeyCode::Char(c) if !k.mods.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER) => {+ // (hn spells a capital as its letter with S-.)+ let c = if shift { c.to_uppercase().next().unwrap_or(c) } else { c };+ self.type_text(&c.to_string(), if c == ' ' { Kind::Other } else { Kind::Type })+ }+ _ => {}+ }+ self.fit();+ out+ }++ /// Esc, Ctrl+Q, Ctrl+W: closed — after asking, when there are changes to lose.+ fn close(&mut self) -> EdOut {+ if self.modified() { self.asking = Some(0); EdOut::None } else { EdOut::Close }+ }++ /// The "Save changes?" question's keys: Left/Right/Tab between its buttons, Enter, Esc cancels.+ fn ask_key(&mut self, k: Chord, focus: usize) -> EdOut {+ match k.code {+ KeyCode::Left | KeyCode::BackTab => self.asking = Some((focus + 2) % 3),+ KeyCode::Right | KeyCode::Tab => self.asking = Some((focus + 1) % 3),+ KeyCode::Esc => self.asking = None,+ KeyCode::Enter => return self.answer(focus),+ _ => {}+ }+ EdOut::None+ }++ /// Save (0), Don't save (1) or Cancel (2).+ fn answer(&mut self, button: usize) -> EdOut {+ self.asking = None;+ match button {+ 0 => match self.save() { Ok(()) => EdOut::Close, Err(e) => { self.message = Some(e); EdOut::None } },+ 1 => EdOut::Close,+ _ => EdOut::None,+ }+ }++ /// The find bar's and go-to-line's keys: typed into, Enter (F3) the next, Shift+F3 the last, Esc closed.+ fn bar_key(&mut self, k: Chord) {+ let shift = k.mods.contains(KeyModifiers::SHIFT);+ let Some(bar) = self.bar.as_mut() else { return };+ let text = match bar { Bar::Find(t) | Bar::Line(t) => t };+ match k.code {+ KeyCode::Esc => { self.bar = None; self.find.clear() }+ KeyCode::Backspace => { text.pop(); }+ KeyCode::Char(c) if !k.mods.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => text.push(if shift { c.to_uppercase().next().unwrap_or(c) } else { c }),+ KeyCode::Enter | KeyCode::F(3) => match bar.clone() {+ Bar::Find(t) => { self.find = t; self.find_next(!(shift && k.code == KeyCode::F(3))) }+ Bar::Line(t) => {+ self.bar = None;+ match t.trim().parse::<usize>() {+ Ok(n) if n >= 1 => { let line = (n - 1).min(self.lines.len() - 1); self.go(Pos { line, col: 0 }, false, false) }+ _ => self.message = Some("Go to line: a line number".into()),+ }+ }+ },+ _ => {}+ }+ if let Some(Bar::Find(t)) = &self.bar { self.find = t.clone() }+ }++ /// The text's area: the rows between the title and the status, right of the line numbers.+ fn text_area(&self) -> (u16, Rect) {+ let gutter = self.lines.len().to_string().len().max(3) as u16 + 2;+ (gutter, Rect::new(gutter, 1, self.size.0.saturating_sub(gutter), self.size.1.saturating_sub(2)))+ }++ /// A click (or a drag, [drag]) at (x, y): the cursor there; a drag selects from where it went down.+ pub(super) fn click(&mut self, x: u16, y: u16, drag: bool) {+ if let Some(focus) = self.asking {+ let (_, buttons, by) = self.ask_layout();+ if let Some(b) = buttons.iter().position(|(a, z, _)| y == by && x >= *a && x < *z) { let _ = self.answer(b); } else { self.asking = Some(focus) }+ return;+ }+ let (_, r) = self.text_area();+ if y < r.y || y >= r.y + r.height { return }+ let line = (self.top + (y - r.y) as usize).min(self.lines.len() - 1);+ let col = byte_at(&self.lines[line], (x.saturating_sub(r.x) as usize) + self.left);+ let p = Pos { line, col };+ if drag { if self.anchor.is_none() { self.anchor = Some(self.cur) } self.cur = p } else { self.anchor = Some(p); self.cur = p }+ self.want = None;+ self.last = None;+ self.fit();+ }++ pub(super) fn wheel(&mut self, down: bool) {+ let max = self.lines.len().saturating_sub(1);+ self.top = if down { (self.top + 3).min(max) } else { self.top.saturating_sub(3) };+ }++ /// The cursor kept on screen.+ fn fit(&mut self) {+ let (_, r) = self.text_area();+ let (rows, cols) = (r.height.max(1) as usize, r.width.max(1) as usize);+ if self.cur.line < self.top { self.top = self.cur.line } else if self.cur.line >= self.top + rows { self.top = self.cur.line + 1 - rows }+ let x = col_of(self.line(), self.cur.col);+ if x < self.left { self.left = x } else if x >= self.left + cols { self.left = x + 1 - cols }+ }++ // ── drawing ──────────────────────────────────────────────────────────────++ pub(super) fn draw(&mut self, buf: &mut Buffer, area: Rect, look: &Look) {+ let resized = self.size != (area.width, area.height);+ self.size = (area.width, area.height);+ if resized { self.fit() }+ for y in area.top()..area.bottom() { for x in area.left()..area.right() { if let Some(c) = buf.cell_mut((x, y)) { c.reset(); } } }+ let (ox, oy, w) = (area.x, area.y, area.width);+ // The title: the file, ● when it has changes, read-only when it can't have any.+ let mut x = ox + 1 + put(buf, ox + 1, oy, w.saturating_sub(2), &self.title, look.text.add_modifier(Modifier::BOLD));+ if self.modified() { put(buf, x + 1, oy, 2, "●", look.accent); x += 2 }+ if self.readonly { put(buf, x + 1, oy, w.saturating_sub(x + 1), "read-only", look.warn); }+ let (gutter, r) = self.text_area();+ let sel = self.selection();+ for row in 0..r.height {+ let i = self.top + row as usize;+ let y = oy + r.y + row;+ let Some(line) = self.lines.get(i) else { break };+ let num = format!("{:>w$} ", i + 1, w = gutter as usize - 2);+ put(buf, ox, y, gutter, &num, if i == self.cur.line { look.text } else { look.muted });+ // Where the word found is on this line, to light.+ let hits: Vec<(usize, usize)> = if self.find.is_empty() { Vec::new() } else { line.match_indices(&self.find).map(|(b, s)| (b, b + s.len())).collect() };+ let mut col = 0;+ for (b, g) in line.grapheme_indices(true) {+ let gw = width(g, col);+ let (start, end) = (col, col + gw);+ col = end;+ if end <= self.left { continue }+ if start >= self.left + r.width as usize { break }+ let selected = sel.is_some_and(|(a, z)| Pos { line: i, col: b } >= a && Pos { line: i, col: b } < z);+ let st = if selected { look.mode } else if hits.iter().any(|(a, z)| b >= *a && b < *z) { look.text.add_modifier(Modifier::REVERSED) } else { look.text };+ let sx = ox + r.x + start.saturating_sub(self.left) as u16;+ let shown = if g == "\t" || start < self.left { " ".repeat(end - start.max(self.left)) } else { g.to_string() };+ if g == "\t" || start < self.left {+ put(buf, sx, y, (end - start.max(self.left)) as u16, &shown, st);+ } else if let Some(c) = buf.cell_mut((sx, y)) { c.set_symbol(&shown).set_style(st); }+ }+ // (A selected line break: one cell of it after the text.)+ if sel.is_some_and(|(a, z)| a.line <= i && i < z.line) && col >= self.left && col < self.left + r.width as usize+ && let Some(c) = buf.cell_mut((ox + r.x + (col - self.left) as u16, y)) { c.set_style(look.mode); }+ }+ // The cursor: its cell reversed.+ let cx = col_of(self.line(), self.cur.col);+ if self.cur.line >= self.top && self.cur.line < self.top + r.height as usize && cx >= self.left && cx < self.left + r.width as usize && self.asking.is_none() && self.bar.is_none()+ && let Some(c) = buf.cell_mut((ox + r.x + (cx - self.left) as u16, oy + r.y + (self.cur.line - self.top) as u16)) { c.set_style(Style::default().add_modifier(Modifier::REVERSED)); }+ // The status row: a bar's question, a message, else where the cursor is and the keys.+ let sy = oy + area.height.saturating_sub(1);+ let status = match &self.bar {+ Some(Bar::Find(t)) => format!("Find: {t}▏ Enter next · Shift+F3 previous · Esc close"),+ Some(Bar::Line(t)) => format!("Go to line: {t}▏ Enter go · Esc cancel"),+ None => self.message.clone().unwrap_or_else(|| format!(+ "Ln {}, Col {} · {} lines · UTF-8{} · {} Ctrl+S save · Ctrl+F find · Ctrl+G line · Ctrl+Z undo · Esc close",+ self.cur.line + 1, cx + 1, self.lines.len(), if self.bom { " BOM" } else { "" }, if self.crlf { "CRLF" } else { "LF" })),+ };+ let st = if self.message.is_some() && self.bar.is_none() { look.accent } else { look.muted };+ put(buf, ox + 1, sy, w.saturating_sub(2), &super::fit(&status, w.saturating_sub(2) as usize), st);+ if let Some(focus) = self.asking {+ let (r, buttons, by) = self.ask_layout();+ let r = Rect::new(ox + r.x, oy + r.y, r.width, r.height).intersection(area);+ frame(buf, r, look.warn);+ put(buf, r.x + 2, r.y + 1, r.width.saturating_sub(4), &format!("Save changes to '{}'?", name_of(&self.path)), look.text);+ for (b, (a, _, label)) in buttons.iter().enumerate() { put(buf, ox + a, oy + by, label.width() as u16, label, if b == focus { look.mode } else { look.text }); }+ }+ }++ /// The "Save changes?" box in the middle, its buttons' columns and words, and their row.+ fn ask_layout(&self) -> (Rect, [(u16, u16, &'static str); 3], u16) {+ const LABELS: [&str; 3] = ["[ Save ]", "[ Don't save ]", "[ Cancel ]"];+ let q = format!("Save changes to '{}'?", name_of(&self.path)).width() as u16 + 4;+ let w = q.max(LABELS.iter().map(|l| l.width() as u16 + 2).sum::<u16>() + 2).min(self.size.0);+ let r = Rect::new(self.size.0.saturating_sub(w) / 2, self.size.1.saturating_sub(5) / 2, w, 5);+ let by = r.y + 3;+ let mut x = r.x + 2;+ let buttons = LABELS.map(|l| { let b = (x, x + l.width() as u16, l); x += l.width() as u16 + 2; b });+ (r, buttons, by)+ }+}++/// Whether this process may write [path] (access(2), as the file's permissions and owner say).+fn writable(path: &Path) -> bool {+ use std::os::unix::ffi::OsStrExt;+ let Ok(c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else { return false };+ // SAFETY: a valid C string, only read.+ unsafe { libc::access(c.as_ptr(), libc::W_OK) == 0 }+}++/// A grapheme's columns at column [col]: a tab to the next stop.+fn width(g: &str, col: usize) -> usize { if g == "\t" { TAB - col % TAB } else { g.width() } }++/// The column byte [byte] of [line] is drawn at.+pub(super) fn col_of(line: &str, byte: usize) -> usize {+ let mut col = 0;+ for (b, g) in line.grapheme_indices(true) { if b >= byte { break } col += width(g, col) }+ col+}++/// The byte of [line] at column [col] (the start of what covers it; past the end, the end).+fn byte_at(line: &str, col: usize) -> usize {+ let mut c = 0;+ for (b, g) in line.grapheme_indices(true) {+ let w = width(g, c);+ if c + w > col { return b }+ c += w;+ }+ line.len()+}++fn prev(line: &str, byte: usize) -> usize { line[..byte].grapheme_indices(true).next_back().map(|(b, _)| b).unwrap_or(0) }+fn next(line: &str, byte: usize) -> usize { line[byte..].graphemes(true).next().map(|g| byte + g.len()).unwrap_or(byte) }++#[cfg(test)]+mod tests {+ use super::*;++ fn scratch(name: &str, bytes: &[u8]) -> (PathBuf, PathBuf) {+ let d = std::env::temp_dir().join(format!("hn-editor-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&d).unwrap();+ std::fs::write(d.join(name), bytes).unwrap();+ (d.join(name), d)+ }+ fn k(code: KeyCode) -> Chord { Chord::normal(code, KeyModifiers::NONE) }+ fn ctrl(c: char) -> Chord { Chord::normal(KeyCode::Char(c), KeyModifiers::CONTROL) }+ fn typing(e: &mut Editor, s: &str) { for c in s.chars() { e.key(if c == '\n' { k(KeyCode::Enter) } else { k(KeyCode::Char(c)) }); } }++ #[test]+ fn text_is_told_from_what_is_not() {+ assert!(is_text("a.txt", b"hello\n") && is_text("a.py", b"print(1)\n") && is_text("a.md", "# Tiêu đề\n".as_bytes()));+ assert!(is_text("bom.txt", b"\xef\xbb\xbfhi"));+ assert!(!is_text("a.png", b"looks like text"));+ assert!(!is_text("a.bin", b"ab\0cd") && !is_text("a.txt", b"\xff\xfe\x00"));+ assert!(!is_text("latin1.txt", b"caf\xe9"));+ let (p, d) = scratch("big.txt", &vec![b'a'; MAX_SIZE as usize + 1]);+ assert_eq!(Editor::open(&p, "big.txt".into()).err(), Some(Refusal::TooLarge));+ let _ = std::fs::remove_dir_all(d);+ }++ #[test]+ fn typing_deleting_new_lines_and_undo_redo() {+ let (p, d) = scratch("a.txt", b" one\ntwo\n");+ let mut e = Editor::open(&p, "a.txt".into()).unwrap();+ e.key(k(KeyCode::End));+ typing(&mut e, "!\nx");+ assert_eq!(e.lines, [" one!", " x", "two"], "a new line keeps the indent");+ e.key(k(KeyCode::Backspace));+ e.key(k(KeyCode::Backspace));+ assert_eq!(e.lines[1], " ");+ assert!(e.modified());+ e.key(ctrl('z'));+ assert_eq!(e.lines[1], " x", "the deletions undone as one");+ e.key(ctrl('z'));+ e.key(ctrl('z'));+ e.key(ctrl('z'));+ assert_eq!(e.lines, [" one", "two"]);+ assert!(!e.modified(), "back where it was saved");+ e.key(ctrl('y'));+ assert_eq!(e.lines, [" one!", "two"]);+ // Delete at a line's end joins the next.+ e.key(k(KeyCode::Delete));+ assert_eq!(e.lines, [" one!two"]);+ let _ = std::fs::remove_dir_all(d);+ }++ #[test]+ fn selection_copy_paste_and_wide_characters_keep_their_columns() {+ let (p, d) = scratch("v.txt", "Tiếng Việt\n日本語\tx\n".as_bytes());+ let mut e = Editor::open(&p, "v.txt".into()).unwrap();+ for _ in 0..5 { e.key(Chord::normal(KeyCode::Right, KeyModifiers::SHIFT)); }+ assert_eq!(e.key(ctrl('c')), EdOut::Clipboard("Tiếng".into()));+ e.key(k(KeyCode::Down));+ assert_eq!(col_of(&e.lines[1], e.cur.col), 4, "column 5 is inside 語: before it");+ e.key(k(KeyCode::Right));+ assert_eq!(col_of(&e.lines[1], e.cur.col), 6, "after 日本語, three of two columns");+ assert_eq!(col_of(&e.lines[1], e.lines[1].len()), 9, "the tab to column 8, then x");+ e.key(ctrl('v'));+ assert_eq!(e.lines[1], "日本語Tiếng\tx");+ // Ctrl+Left goes back a word.+ e.key(Chord::normal(KeyCode::Left, KeyModifiers::CONTROL));+ assert_eq!(e.cur.col, 0);+ let _ = std::fs::remove_dir_all(d);+ }++ #[test]+ fn saving_keeps_crlf_the_bom_no_final_newline_and_permissions() {+ use std::os::unix::fs::PermissionsExt;+ let (p, d) = scratch("w.txt", b"\xef\xbb\xbfa\r\nb");+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o640)).unwrap();+ let mut e = Editor::open(&p, "w.txt".into()).unwrap();+ e.key(Chord::normal(KeyCode::End, KeyModifiers::CONTROL));+ typing(&mut e, "c");+ e.key(ctrl('s'));+ assert_eq!(std::fs::read(&p).unwrap(), b"\xef\xbb\xbfa\r\nbc");+ assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o640);+ assert!(!e.modified() && e.message.as_deref() == Some("Saved w.txt"));+ assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "no temporary file left");+ let _ = std::fs::remove_dir_all(d);+ }++ #[test]+ fn find_lights_and_goes_to_each_place_round() {+ let (p, d) = scratch("f.txt", b"cat\ndog cat\ncat\n");+ let mut e = Editor::open(&p, "f.txt".into()).unwrap();+ e.key(ctrl('f'));+ typing(&mut e, "cat");+ e.key(k(KeyCode::Enter));+ assert_eq!(e.selection(), Some((Pos { line: 0, col: 0 }, Pos { line: 0, col: 3 })));+ e.key(k(KeyCode::Enter));+ assert_eq!(e.cur, Pos { line: 1, col: 7 });+ e.key(Chord::normal(KeyCode::F(3), KeyModifiers::SHIFT));+ assert_eq!(e.cur, Pos { line: 0, col: 3 });+ e.key(k(KeyCode::Esc));+ assert!(e.bar.is_none());+ let _ = std::fs::remove_dir_all(d);+ }++ #[test]+ fn closing_with_changes_asks_first() {+ let (p, d) = scratch("c.txt", b"x\n");+ let mut e = Editor::open(&p, "c.txt".into()).unwrap();+ assert_eq!(e.key(k(KeyCode::Esc)), EdOut::Close, "nothing changed: closed at once");+ typing(&mut e, "y");+ assert_eq!(e.key(k(KeyCode::Esc)), EdOut::None);+ assert_eq!(e.asking, Some(0));+ e.key(k(KeyCode::Right));+ e.key(k(KeyCode::Right));+ assert_eq!(e.key(k(KeyCode::Enter)), EdOut::None, "Cancel: still editing");+ assert!(e.asking.is_none() && e.modified());+ e.key(ctrl('q'));+ assert_eq!(e.key(k(KeyCode::Enter)), EdOut::Close, "Save, then closed");+ assert_eq!(std::fs::read_to_string(&p).unwrap(), "yx\n");+ let _ = std::fs::remove_dir_all(d);+ }++ #[test]+ fn a_read_only_file_is_shown_not_changed() {+ use std::os::unix::fs::PermissionsExt;+ let (p, d) = scratch("r.txt", b"keep\n");+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o444)).unwrap();+ let mut e = Editor::open(&p, "r.txt".into()).unwrap();+ assert!(e.readonly);+ typing(&mut e, "z");+ assert_eq!(e.lines, ["keep"]);+ assert!(e.message.as_deref().is_some_and(|m| m.starts_with("read-only")));+ let area = Rect::new(0, 0, 60, 10);+ let mut buf = Buffer::empty(area);+ e.draw(&mut buf, area, &Look::default());+ let top: String = (0..60).map(|x| buf[(x, 0)].symbol().to_string()).collect();+ assert!(top.contains("r.txt") && top.contains("read-only"), "{top}");+ let _ = std::fs::remove_dir_all(d);+ }+}