From a1647a662deb26cd16863da2a05334dd8ff43dd0 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 18 Nov 2026 14:37:15 -0600 Subject: [PATCH] S010: tabs, split view, breadcrumb, history, places sidebar and config Shell with one folder model per pane, back/forward/up history, editable breadcrumb with folder completion, draggable pill tabs, places with bookmarks in places.toml, session restore and a status bar. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + Cargo.lock | 3 + Cargo.toml | 1 + .../03 File browsing/S010-navigation-shell.md | 14 +- Plans/INDEX.md | 2 +- crates/tunal/Cargo.toml | 4 +- crates/tunal/src/config.rs | 95 +++ crates/tunal/src/main.rs | 73 +- crates/tunal/src/shell/mod.rs | 800 ++++++++++++++++++ crates/tunal/src/shell/pane.rs | 155 ++++ crates/tunal/src/shell/path.rs | 166 ++++ crates/tunal/src/shell/places.rs | 288 +++++++ crates/tunal/ui/app.slint | 425 ++++++++-- crates/tunal/ui/components/icon.slint | 6 + crates/tunal/ui/components/state-layer.slint | 9 + crates/tunal/ui/shell/breadcrumb.slint | 261 ++++++ crates/tunal/ui/shell/pane.slint | 147 ++++ crates/tunal/ui/shell/sidebar.slint | 170 ++++ crates/tunal/ui/shell/status-bar.slint | 19 + crates/tunal/ui/shell/tab-bar.slint | 219 +++++ crates/tunal/ui/shell/toolbar.slint | 151 ++++ docs/DECISIONS.md | 1 + docs/PROGRESS.md | 7 + 23 files changed, 2895 insertions(+), 122 deletions(-) create mode 100644 crates/tunal/src/config.rs create mode 100644 crates/tunal/src/shell/mod.rs create mode 100644 crates/tunal/src/shell/pane.rs create mode 100644 crates/tunal/src/shell/path.rs create mode 100644 crates/tunal/src/shell/places.rs create mode 100644 crates/tunal/ui/shell/breadcrumb.slint create mode 100644 crates/tunal/ui/shell/pane.slint create mode 100644 crates/tunal/ui/shell/sidebar.slint create mode 100644 crates/tunal/ui/shell/status-bar.slint create mode 100644 crates/tunal/ui/shell/tab-bar.slint create mode 100644 crates/tunal/ui/shell/toolbar.slint diff --git a/CLAUDE.md b/CLAUDE.md index 26818b1..4249a74 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -84,6 +84,7 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~ | `busctl --user call org.freedesktop.portal.Desktop /org/freedesktop/portal/desktop org.freedesktop.portal.Settings ReadOne ss org.freedesktop.appearance accent-color` | inspect portal values | now | | `fc-list` | check bundled/system fonts | now | | `cargo run -p tunal -- --screenshot [--dark] [--size WxH]` (software renderer, offscreen, default 960x640; env `TUNAL_SEED=#rrggbb`, `TUNAL_REDUCED_MOTION=1`, `TUNAL_VIEW=grid`) | single-PNG visual check; full state matrix in phase 12 | S003 | +| `XDG_CONFIG_HOME= cargo run -p tunal -- […] [--split ] --screenshot [--dark] --size 1200x760` | one tab per folder, `--split` adds a split tab (last tab current); no folders = restore `session.toml`. Copy `~/.config/user-dirs.dirs` into `` for the places | S010 | | `XDG_DATA_HOME=/data cargo run -p tunal-core --example ops -- ` (refuses unless XDG_DATA_HOME is inside ``) | job engine + trash smoke run: conflicts, cancel, trash/restore/empty | S007 | | `cargo run -p tunal -- --gallery --screenshot [--dark] --size 1200x1000` (`--gallery` alone opens it in a window) | every control in rest/hover/pressed/focused/disabled; press squeeze not drawn by the software renderer | S004 | | `cargo run -p tunal -- --gallery --page menu\|dialog --screenshot [--dark] --size 960x640` | open menu + submenu + two toasts, or dialog + indeterminate toast, over a stand-in folder | S005 | diff --git a/Cargo.lock b/Cargo.lock index c6ebf1c..9bb6f48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4648,6 +4648,7 @@ dependencies = [ "const-field-offset", "i-slint-backend-linuxkms", "i-slint-backend-selector", + "i-slint-backend-winit", "i-slint-common", "i-slint-core", "i-slint-core-macros", @@ -5442,8 +5443,10 @@ version = "0.1.0" dependencies = [ "jiff", "png", + "serde", "slint", "slint-build", + "toml", "tunal-core", "tunal-theme", ] diff --git a/Cargo.toml b/Cargo.toml index 4b1b975..03a4a59 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ md-5 = "0.11" ureq = { version = "3", default-features = false, features = ["rustls", "gzip"] } serde = { version = "1", features = ["derive"] } serde_json = "1" +toml = "1.2" symphonia = { version = "0.5", features = ["mp3", "aac", "isomp4"] } cpal = "0.18" rubato = "0.16" diff --git a/Plans/03 File browsing/S010-navigation-shell.md b/Plans/03 File browsing/S010-navigation-shell.md index 3d761c2..944e931 100644 --- a/Plans/03 File browsing/S010-navigation-shell.md +++ b/Plans/03 File browsing/S010-navigation-shell.md @@ -10,13 +10,13 @@ The navigation shell: tabs, split view, editable breadcrumb path bar, back/forwa CLAUDE.md §3; docs/DECISIONS.md D-012; crates/tunal/src/folder/ API; crates/tunal/ui/components/{tab,list-row,text-field}.slint. ## Steps -- [ ] Config module: `$XDG_CONFIG_HOME/tunal/*.toml` with serde, atomic writes; `settings.toml` (later plans add fields) and session restore of open tabs. -- [ ] Pane = location + back/forward stacks + folder model + view mode; tab = one or two panes; split view toggle; active pane indicator. -- [ ] Tab bar: new/close/switch, middle-click close, drag to reorder, animated add/close/reorder; Ctrl+T/Ctrl+W/Ctrl+Tab. -- [ ] Breadcrumb: segment chips navigate; Ctrl+L or click on empty space edits the path with folder completion; Enter goes, Esc reverts; accepts URIs (`trash:///`, later others). -- [ ] Back/forward/up buttons, Alt+Left/Right/Up, mouse back/forward buttons. -- [ ] Places sidebar: XDG user dirs (from `user-dirs.dirs`), Trash, Bookmarks (`places.toml`: add current folder, rename, remove, reorder); empty Devices/Network sections with an API for later plans; collapse animated. Status bar: item count and selection size. -- [ ] PROGRESS entry, INDEX line, commit `S010: …` +- [x] Config module: `$XDG_CONFIG_HOME/tunal/*.toml` with serde, atomic writes; `settings.toml` (later plans add fields) and session restore of open tabs. +- [x] Pane = location + back/forward stacks + folder model + view mode; tab = one or two panes; split view toggle; active pane indicator. +- [x] Tab bar: new/close/switch, middle-click close, drag to reorder, animated add/close/reorder; Ctrl+T/Ctrl+W/Ctrl+Tab. +- [x] Breadcrumb: segment chips navigate; Ctrl+L or click on empty space edits the path with folder completion; Enter goes, Esc reverts; accepts URIs (`trash:///`, later others). +- [x] Back/forward/up buttons, Alt+Left/Right/Up, mouse back/forward buttons. +- [x] Places sidebar: XDG user dirs (from `user-dirs.dirs`), Trash, Bookmarks (`places.toml`: add current folder, rename, remove, reorder); empty Devices/Network sections with an API for later plans; collapse animated. Status bar: item count and selection size. +- [x] PROGRESS entry, INDEX line, commit `S010: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 8a1dda3..e7c9658 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -21,7 +21,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v - [x] [S007 — File operations engine and trash](03%20File%20browsing/S007-file-ops-engine.md) · Opus medium - [x] [S008 — Folder model and details view](03%20File%20browsing/S008-folder-model-details.md) · Opus medium - [x] [S009 — Icon grid view and list motion](03%20File%20browsing/S009-grid-and-list-motion.md) · Opus high -- [ ] [S010 — Tabs, split view, breadcrumbs, history and places](03%20File%20browsing/S010-navigation-shell.md) · Opus medium +- [x] [S010 — Tabs, split view, breadcrumbs, history and places](03%20File%20browsing/S010-navigation-shell.md) · Opus medium - [ ] [S011 — File operation actions](03%20File%20browsing/S011-file-op-actions.md) · Sonnet high - [ ] [S012 — Properties, Open and Open with](03%20File%20browsing/S012-properties-open-with.md) · Sonnet medium - [ ] [S013 — Settings dialog and editable context menus](03%20File%20browsing/S013-settings-context-menus.md) · Sonnet high diff --git a/crates/tunal/Cargo.toml b/crates/tunal/Cargo.toml index 659df74..3e27bd7 100644 --- a/crates/tunal/Cargo.toml +++ b/crates/tunal/Cargo.toml @@ -6,11 +6,13 @@ license.workspace = true publish.workspace = true [dependencies] -slint.workspace = true +slint = { workspace = true, features = ["unstable-winit-030"] } tunal-theme = { path = "../tunal-theme" } png.workspace = true tunal-core = { path = "../tunal-core" } jiff.workspace = true +serde.workspace = true +toml.workspace = true [build-dependencies] slint-build.workspace = true diff --git a/crates/tunal/src/config.rs b/crates/tunal/src/config.rs new file mode 100644 index 0000000..00d8c01 --- /dev/null +++ b/crates/tunal/src/config.rs @@ -0,0 +1,95 @@ +//! The config directory, `$XDG_CONFIG_HOME/tunal/`: one TOML file per concern, read with +//! defaults for missing files and fields, written atomically (temp file, then rename). + +use std::fs; +use std::io::{self, Write}; +use std::path::PathBuf; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +/// `$XDG_CONFIG_HOME/tunal`, or `~/.config/tunal`. +pub fn dir() -> PathBuf { + let base = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))) + .unwrap_or_else(|| PathBuf::from("/tmp")); + base.join("tunal") +} + +/// Reads `.toml`; a missing file gives the defaults, a broken one too (with a warning). +pub fn load(name: &str) -> T { + let path = dir().join(format!("{name}.toml")); + match fs::read_to_string(&path) { + Ok(text) => toml::from_str(&text).unwrap_or_else(|e| { + eprintln!("tunal: ignoring {}: {e}", path.display()); + T::default() + }), + Err(e) if e.kind() == io::ErrorKind::NotFound => T::default(), + Err(e) => { + eprintln!("tunal: couldn't read {}: {e}", path.display()); + T::default() + } + } +} + +/// Writes `.toml`: a reader sees either the old file or the new one, never a part. +pub fn save(name: &str, value: &T) -> io::Result<()> { + let dir = dir(); + fs::create_dir_all(&dir)?; + let text = toml::to_string_pretty(value).map_err(io::Error::other)?; + let path = dir.join(format!("{name}.toml")); + let temp = dir.join(format!(".{name}.toml.{}", std::process::id())); + let result = (|| { + let mut file = fs::File::create(&temp)?; + file.write_all(text.as_bytes())?; + file.sync_all()?; + fs::rename(&temp, &path) + })(); + if result.is_err() { + let _ = fs::remove_file(&temp); + } + result +} + +/// Writes `.toml`, reporting a failure on stderr only. +pub fn store(name: &str, value: &T) { + if let Err(e) = save(name, value) { + eprintln!("tunal: couldn't save {name}.toml: {e}"); + } +} + +/// `settings.toml`. Later plans add their fields here. +#[derive(Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct Settings { + /// Reopen the tabs of the last session. + pub restore_session: bool, + pub show_sidebar: bool, +} + +impl Default for Settings { + fn default() -> Self { + Self { + restore_session: true, + show_sidebar: true, + } + } +} + +/// `session.toml`: the open tabs, saved when the window closes. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct Session { + pub tabs: Vec, + pub current: usize, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct TabSession { + /// Location URIs, one per pane (two in split view). + pub panes: Vec, + pub active: usize, +} diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs index 33657eb..df0eb33 100644 --- a/crates/tunal/src/main.rs +++ b/crates/tunal/src/main.rs @@ -1,6 +1,8 @@ +mod config; mod folder; mod icons; mod screenshot; +mod shell; mod theme_bridge; use std::path::PathBuf; @@ -10,18 +12,31 @@ use tunal_core::{Locations, Uri}; slint::include_modules!(); -const USAGE: &str = "usage: tunal [] [--gallery [--page menu|dialog]] \ - [--screenshot [--dark] [--size WxH]]"; +const USAGE: &str = "usage: tunal […] [--split ] \ + [--gallery [--page menu|dialog]] [--screenshot [--dark] [--size WxH]]"; fn main() -> ExitCode { let result = parse(std::env::args().skip(1)).and_then(|args| match args.screenshot { None if args.gallery => gallery(args.page).and_then(run).map_err(|e| e.to_string()), - None => window(args.dir, false) - .and_then(run) + None => window(args.tabs, false) + .and_then(|(ui, shell)| { + run(ui)?; + shell.save(); + Ok(()) + }) .map_err(|e| e.to_string()), Some(options) if args.gallery => screenshot::run(options, || gallery(args.page)), - // A screenshot is one frame: list the folder before it is drawn. - Some(options) => screenshot::run(options, || window(args.dir, true)), + // A screenshot is one frame: list the folder before it is drawn. The shell lives until + // the frame is drawn, so callbacks fired while drawing (grid columns) still reach it. + Some(options) => { + let mut shell = None; + screenshot::run(options, || { + window(args.tabs, true).map(|(ui, s)| { + shell = Some(s); + ui + }) + }) + } }); match result { Ok(()) => ExitCode::SUCCESS, @@ -32,25 +47,19 @@ fn main() -> ExitCode { } } -/// The main window, showing `dir` if given (temporary until places and navigation land). -fn window(dir: Option, blocking: bool) -> Result { +/// The main window with the shell: one tab per entry of `tabs` (two folders make a split +/// tab), else the last session. `blocking` lists the folders before returning (screenshots). +fn window( + tabs: Vec>, + blocking: bool, +) -> Result<(MainWindow, std::rc::Rc), slint::PlatformError> { let ui = MainWindow::new()?; - let model = folder::attach(&ui, Locations::with_local()); - let m = std::rc::Rc::downgrade(&model); - ui.on_sort_menu_activated(move |index, sub| { - if let Some(m) = m.upgrade() { - m.sort_menu_activated(index.max(0) as usize, sub); - } - }); - if let Some(dir) = dir { - let uri = Uri::from_path(&dir); - if blocking { - model.open_blocking(uri); - } else { - model.open(uri); - } - } - Ok(ui) + let tabs = tabs + .iter() + .map(|dirs| dirs.iter().map(|d| Uri::from_path(d)).collect()) + .collect(); + let shell = shell::Shell::attach(&ui, Locations::with_local(), tabs, blocking); + Ok((ui, shell)) } fn gallery(page: GalleryPage) -> Result { @@ -66,14 +75,15 @@ fn run(ui: impl theme_bridge::Themed) -> Result<(), slint::PlatformError> { } struct Args { - dir: Option, + /// Folders of each tab given on the command line. + tabs: Vec>, gallery: bool, page: GalleryPage, screenshot: Option, } fn parse(mut args: impl Iterator) -> Result { - let mut dir = None; + let mut tabs = Vec::new(); let mut gallery = false; let mut page = GalleryPage::Controls; let mut options = screenshot::Options { @@ -86,6 +96,11 @@ fn parse(mut args: impl Iterator) -> Result { while let Some(arg) = args.next() { match arg.as_str() { "--gallery" => gallery = true, + "--split" => { + let a = args.next().ok_or(USAGE)?; + let b = args.next().ok_or(USAGE)?; + tabs.push(vec![PathBuf::from(a), PathBuf::from(b)]); + } "--page" => { page = match args.next().as_deref() { Some("menu") => GalleryPage::Menu, @@ -108,7 +123,7 @@ fn parse(mut args: impl Iterator) -> Result { options.size = (parse(w)?, parse(h)?); screenshot_flags = true; } - _ if !arg.starts_with('-') && dir.is_none() => dir = Some(PathBuf::from(arg)), + _ if !arg.starts_with('-') => tabs.push(vec![PathBuf::from(arg)]), _ => return Err(USAGE.into()), } } @@ -117,7 +132,7 @@ fn parse(mut args: impl Iterator) -> Result { } if !screenshot_flags { return Ok(Args { - dir, + tabs, gallery, page, screenshot: None, @@ -128,7 +143,7 @@ fn parse(mut args: impl Iterator) -> Result { } options.reduced_motion = gallery; Ok(Args { - dir, + tabs, gallery, page, screenshot: Some(options), diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs new file mode 100644 index 0000000..0aadf7e --- /dev/null +++ b/crates/tunal/src/shell/mod.rs @@ -0,0 +1,800 @@ +//! The navigation shell: tabs of one or two panes, history, the breadcrumb, the places +//! sidebar and the status bar, bound to the `MainWindow`. + +mod pane; +mod path; +pub mod places; + +use std::cell::{Cell, RefCell}; +use std::rc::{Rc, Weak}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use slint::{ComponentHandle, Model, ModelRc, VecModel}; +use tunal_core::{Locations, Uri}; + +use crate::config::{self, Session, TabSession}; +use crate::folder::format; +use crate::{ + Completion, Crumb, MainWindow, MenuEntry, MenuItem, PaneData, PlaceItem, SidebarSection, + TabData, +}; +use pane::Pane; +use places::{Places, Section}; + +struct Tab { + id: i32, + slot: usize, + panes: Vec>, + active: usize, +} + +/// What the place menu was opened on. +#[derive(Clone, Copy)] +struct MenuTarget { + section: Section, + index: usize, +} + +pub struct Shell { + ui: slint::Weak, + me: Weak, + locations: Locations, + blocking: bool, + /// Tabs in opening order, as the tab model rows. + tabs: RefCell>, + current: Cell, + next_id: Cell, + tab_rows: Rc>, + pane_rows: Rc>, + places: RefCell, + menu_target: Cell>, + /// Bumped per completion request; older results are dropped. + completion: Arc, +} + +impl Shell { + /// Binds the shell to `ui` and opens `tabs` (one or two folders each; the last one is + /// current), else the saved session, else home. `blocking` lists folders before + /// returning (screenshots). + pub fn attach( + ui: &MainWindow, + locations: Locations, + tabs: Vec>, + blocking: bool, + ) -> Rc { + let shell = Rc::new_cyclic(|me| Self { + ui: ui.as_weak(), + me: me.clone(), + locations, + blocking, + tabs: RefCell::new(Vec::new()), + current: Cell::new(0), + next_id: Cell::new(1), + tab_rows: Rc::new(VecModel::default()), + pane_rows: Rc::new(VecModel::default()), + places: RefCell::new(Places::load()), + menu_target: Cell::new(None), + completion: Arc::new(AtomicU64::new(0)), + }); + ui.set_tabs(ModelRc::from(shell.tab_rows.clone())); + ui.set_panes(ModelRc::from(shell.pane_rows.clone())); + let settings: config::Settings = config::load("settings"); + ui.set_show_sidebar(settings.show_sidebar); + shell.bind(ui); + + let session: Session = if tabs.is_empty() && settings.restore_session { + config::load("session") + } else { + Session::default() + }; + if !tabs.is_empty() { + for dirs in tabs { + shell.open_tab(dirs); + } + } else { + for tab in &session.tabs { + let uris: Vec = tab + .panes + .iter() + .filter_map(|u| Uri::parse(u)) + .take(2) + .collect(); + if !uris.is_empty() { + shell.open_tab(uris); + let mut tabs = shell.tabs.borrow_mut(); + let t = tabs.last_mut().expect("just opened"); + t.active = tab.active.min(t.panes.len() - 1); + } + } + if shell.tabs.borrow().is_empty() { + shell.open_tab(vec![Uri::from_path(&places::home())]); + } else { + let n = shell.tabs.borrow().len(); + shell.current.set(session.current.min(n - 1)); + } + } + shell.show_current(); + shell + } + + /// The open tabs, for `session.toml`, and the sidebar setting, for `settings.toml`. + pub fn save(&self) { + let tabs = self.tabs.borrow(); + let mut order: Vec<&Tab> = tabs.iter().collect(); + order.sort_by_key(|t| t.slot); + let session = Session { + tabs: order + .iter() + .map(|t| TabSession { + panes: t + .panes + .iter() + .filter_map(|p| p.dir()) + .map(|d| d.to_string()) + .collect(), + active: t.active, + }) + .collect(), + current: tabs.get(self.current.get()).map_or(0, |t| t.slot), + }; + config::store("session", &session); + let mut settings: config::Settings = config::load("settings"); + if let Some(ui) = self.ui.upgrade() { + settings.show_sidebar = ui.get_show_sidebar(); + } + config::store("settings", &settings); + } + + // ---- tabs --------------------------------------------------------------------------- + + fn new_pane(&self, uri: Uri) -> Rc { + let id = self.next_id.get(); + self.next_id.set(id + 1); + let Some(ui) = self.ui.upgrade() else { + unreachable!("panes are made while the window lives"); + }; + let pane = Pane::new(id, &ui, self.locations.clone(), self.blocking); + let me = self.me.clone(); + pane.model.on_changed(move |_| { + if let Some(shell) = me.upgrade() { + shell.pane_changed(id); + } + }); + pane.go(uri); + pane + } + + /// Opens a tab after the last one and makes it current. + fn open_tab(&self, uris: Vec) { + let panes: Vec> = uris.into_iter().map(|u| self.new_pane(u)).collect(); + let id = self.next_id.get() as i32; + self.next_id.set(self.next_id.get() + 1); + let slot = self.tabs.borrow().len(); + let tab = Tab { + id, + slot, + panes, + active: 0, + }; + self.tab_rows.push(self.tab_data(&tab)); + self.tabs.borrow_mut().push(tab); + self.current.set(slot); + } + + /// A new tab at the active pane's folder. + fn new_tab(&self) { + let dir = self.active().and_then(|p| p.dir()); + self.open_tab(vec![dir.unwrap_or_else(|| Uri::from_path(&places::home()))]); + self.show_current(); + } + + fn tab_data(&self, tab: &Tab) -> TabData { + let dir = tab.panes.get(tab.active).and_then(|p| p.dir()); + let (title, glyph) = dir.map(|d| path::title(&d)).unwrap_or_default(); + TabData { + id: tab.id, + title: title.into(), + glyph: glyph.into(), + slot: tab.slot as i32, + } + } + + fn index_of(&self, id: i32) -> Option { + self.tabs.borrow().iter().position(|t| t.id == id) + } + + fn select_tab(&self, index: usize) { + if index < self.tabs.borrow().len() && index != self.current.get() { + self.current.set(index); + self.show_current(); + } + } + + fn close_tab(&self, index: usize) { + let mut tabs = self.tabs.borrow_mut(); + if tabs.len() <= 1 || index >= tabs.len() { + return; + } + let closed = tabs.remove(index); + for t in tabs.iter_mut().filter(|t| t.slot > closed.slot) { + t.slot -= 1; + } + // The neighbour that takes the closed tab's place, or the one before it. + let next_slot = closed.slot.min(tabs.len() - 1); + let next = tabs.iter().position(|t| t.slot == next_slot).unwrap_or(0); + let was_current = index == self.current.get(); + let current = if was_current { + next + } else if self.current.get() > index { + self.current.get() - 1 + } else { + self.current.get() + }; + drop(tabs); + self.tab_rows.remove(index); + self.refresh_tab_rows(); + self.current.set(current); + self.show_current(); + } + + /// Moves tab `id` to `slot`, shifting the tabs between. + fn move_tab(&self, id: i32, slot: usize) { + let mut tabs = self.tabs.borrow_mut(); + let Some(from) = tabs.iter().find(|t| t.id == id).map(|t| t.slot) else { + return; + }; + let to = slot.min(tabs.len() - 1); + for t in tabs.iter_mut() { + if t.id == id { + t.slot = to; + } else if from < t.slot && t.slot <= to { + t.slot -= 1; + } else if to <= t.slot && t.slot < from { + t.slot += 1; + } + } + drop(tabs); + self.refresh_tab_rows(); + self.show_current(); + } + + /// Next or previous tab by place, wrapping. + fn cycle(&self, backward: bool) { + let tabs = self.tabs.borrow(); + let n = tabs.len(); + let slot = tabs[self.current.get()].slot; + let want = if backward { + (slot + n - 1) % n + } else { + (slot + 1) % n + }; + let index = tabs.iter().position(|t| t.slot == want); + drop(tabs); + if let Some(index) = index { + self.select_tab(index); + } + } + + fn refresh_tab_rows(&self) { + for (i, tab) in self.tabs.borrow().iter().enumerate() { + let data = self.tab_data(tab); + if self.tab_rows.row_data(i).as_ref() != Some(&data) { + self.tab_rows.set_row_data(i, data); + } + } + } + + // ---- panes -------------------------------------------------------------------------- + + fn active(&self) -> Option> { + let tabs = self.tabs.borrow(); + let tab = tabs.get(self.current.get())?; + tab.panes.get(tab.active).cloned() + } + + fn pane_at(&self, index: usize) -> Option> { + let tabs = self.tabs.borrow(); + tabs.get(self.current.get())?.panes.get(index).cloned() + } + + fn set_active_pane(&self, index: usize) { + let changed = { + let mut tabs = self.tabs.borrow_mut(); + let Some(tab) = tabs.get_mut(self.current.get()) else { + return; + }; + let ok = index < tab.panes.len() && tab.active != index; + if ok { + tab.active = index; + } + ok + }; + if changed { + self.refresh_tab_rows(); + self.show_chrome(); + } + } + + fn toggle_split(&self) { + let (split, dir) = { + let tabs = self.tabs.borrow(); + let tab = &tabs[self.current.get()]; + (tab.panes.len() > 1, tab.panes[tab.active].dir()) + }; + if split { + let mut tabs = self.tabs.borrow_mut(); + let tab = &mut tabs[self.current.get()]; + let keep = tab.panes.remove(tab.active); + tab.panes = vec![keep]; + tab.active = 0; + } else { + let pane = self.new_pane(dir.unwrap_or_else(|| Uri::from_path(&places::home()))); + let mut tabs = self.tabs.borrow_mut(); + let tab = &mut tabs[self.current.get()]; + tab.panes.push(pane); + tab.active = 1; + } + self.show_current(); + } + + /// A pane's folder model changed: redraw what shows it. + fn pane_changed(&self, id: u64) { + let (index, is_active, tab_index) = { + let tabs = self.tabs.borrow(); + let found = tabs.iter().enumerate().find_map(|(ti, t)| { + t.panes + .iter() + .position(|p| p.id == id) + .map(|pi| (ti, pi, pi == t.active)) + }); + let Some((ti, pi, active)) = found else { + return; + }; + (pi, active, ti) + }; + if tab_index == self.current.get() { + if let Some(pane) = self.pane_at(index) + && index < self.pane_rows.row_count() + { + self.pane_rows.set_row_data(index, pane.data()); + } + if is_active { + self.show_chrome(); + } + } + if is_active { + self.refresh_tab_rows(); + } + } + + /// Shows the current tab: its panes, then everything that follows the active pane. + fn show_current(&self) { + let rows: Vec = { + let tabs = self.tabs.borrow(); + tabs[self.current.get()] + .panes + .iter() + .map(|p| p.data()) + .collect() + }; + if rows.len() == self.pane_rows.row_count() { + for (i, row) in rows.into_iter().enumerate() { + self.pane_rows.set_row_data(i, row); + } + } else { + self.pane_rows.set_vec(rows); + } + self.show_chrome(); + self.focus_active(); + } + + /// Tab bar selection, toolbar, breadcrumb, sort menu, sidebar and status bar. + fn show_chrome(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let (id, slot, active) = { + let tabs = self.tabs.borrow(); + let t = &tabs[self.current.get()]; + (t.id, t.slot, t.active) + }; + ui.set_current_tab(id); + ui.set_current_slot(slot as i32); + ui.set_active_pane(active as i32); + let Some(pane) = self.active() else { + return; + }; + ui.set_can_back(pane.can_back()); + ui.set_can_forward(pane.can_forward()); + ui.set_can_up(pane.can_up()); + let dir = pane.dir(); + let crumbs: Vec = dir + .as_ref() + .map(path::segments) + .unwrap_or_default() + .into_iter() + .map(|s| Crumb { + name: s.name.into(), + glyph: s.glyph.into(), + }) + .collect(); + ui.set_crumbs(ModelRc::new(VecModel::from(crumbs))); + ui.set_path(dir.as_ref().map(path::text).unwrap_or_default().into()); + ui.set_sort_menu(ModelRc::new(VecModel::from(pane.model.sort_menu()))); + ui.set_status(status(&pane).into()); + self.show_sidebar(&ui, dir.as_ref()); + } + + fn show_sidebar(&self, ui: &MainWindow, dir: Option<&Uri>) { + let places = self.places.borrow(); + let sections: Vec = Section::ALL + .into_iter() + .map(|section| { + let items: Vec = places + .items(section) + .iter() + .map(|p| PlaceItem { + name: p.name.as_str().into(), + glyph: p.glyph.into(), + current: Some(&p.uri) == dir, + }) + .collect(); + SidebarSection { + title: section.title().into(), + items: ModelRc::new(VecModel::from(items)), + collapsed: places.collapsed(section), + empty: section.empty().into(), + can_add: section == Section::Bookmarks, + } + }) + .collect(); + let model = ui.get_sections(); + // Same section count every time: update rows so the collapse animation keeps state. + match model.as_any().downcast_ref::>() { + Some(rows) if rows.row_count() == sections.len() => { + for (i, s) in sections.into_iter().enumerate() { + rows.set_row_data(i, s); + } + } + _ => ui.set_sections(ModelRc::new(VecModel::from(sections))), + } + } + + fn focus_active(&self) { + if let Some(ui) = self.ui.upgrade() { + ui.set_focus_request(ui.get_focus_request().wrapping_add(1)); + } + } + + /// Runs `f` on the active pane, then redraws the chrome (history buttons change). + fn with_active(&self, f: impl FnOnce(&Pane)) { + if let Some(pane) = self.active() { + f(&pane); + self.show_chrome(); + } + } + + fn go(&self, uri: Uri) { + self.with_active(|p| p.go(uri)); + self.focus_active(); + } + + // ---- places ------------------------------------------------------------------------- + + fn open_place(&self, section: Section, index: usize, new_tab: bool) { + let Some(uri) = self + .places + .borrow() + .get(section, index) + .map(|p| p.uri.clone()) + else { + return; + }; + if new_tab { + self.open_tab(vec![uri]); + self.show_current(); + } else { + self.go(uri); + } + } + + fn add_bookmark(&self) { + let Some(dir) = self.active().and_then(|p| p.dir()) else { + return; + }; + let (name, _) = path::title(&dir); + self.places.borrow_mut().add_bookmark(name, dir); + self.show_chrome(); + } + + fn show_place_menu(&self, section: Section, index: usize) { + let items = self.place_menu(section, index); + if let Some(ui) = self.ui.upgrade() { + ui.set_place_menu(ModelRc::new(VecModel::from(items))); + } + } + + fn place_menu(&self, section: Section, index: usize) -> Vec { + self.menu_target.set(Some(MenuTarget { section, index })); + let item = |text: &str, icon: &str, disabled: bool| MenuItem { + text: text.into(), + icon: icon.into(), + shortcut: Default::default(), + disabled, + separator: false, + submenu: ModelRc::new(VecModel::::default()), + }; + let mut items = vec![item("Open in new tab", "\u{e89e}", false)]; + if section == Section::Bookmarks { + let last = self.places.borrow().items(section).len().saturating_sub(1); + items.push(item("Rename", "\u{e3c9}", false)); + items.push(item("Move up", "\u{e5d8}", index == 0)); + items.push(item("Move down", "\u{e5db}", index >= last)); + items.push(item("Remove", "\u{e872}", false)); + } + items + } + + fn place_menu_activated(&self, choice: usize) { + let Some(MenuTarget { section, index }) = self.menu_target.get() else { + return; + }; + match choice { + 0 => self.open_place(section, index, true), + 1 => { + let name = self + .places + .borrow() + .get(section, index) + .map(|p| p.name.clone()); + if let (Some(name), Some(ui)) = (name, self.ui.upgrade()) { + ui.invoke_rename_bookmark(name.into()); + } + return; + } + 2 => self.places.borrow_mut().move_bookmark(index, -1), + 3 => self.places.borrow_mut().move_bookmark(index, 1), + 4 => self.places.borrow_mut().remove_bookmark(index), + _ => {} + } + self.menu_target.set(None); + self.show_chrome(); + } + + fn rename_bookmark(&self, name: &str) { + if let Some(MenuTarget { + section: Section::Bookmarks, + index, + }) = self.menu_target.take() + { + self.places.borrow_mut().rename_bookmark(index, name); + self.show_chrome(); + } + } + + // ---- breadcrumb --------------------------------------------------------------------- + + /// Completes `text` off the UI thread; the newest request wins. + fn complete(&self, text: String) { + let generation = self.completion.fetch_add(1, Ordering::SeqCst) + 1; + let set = |ui: &MainWindow, items: Vec<(String, String)>| { + let items: Vec = items + .into_iter() + .map(|(name, text)| Completion { + name: name.into(), + text: text.into(), + }) + .collect(); + ui.set_completions(ModelRc::new(VecModel::from(items))); + }; + if text.is_empty() { + if let Some(ui) = self.ui.upgrade() { + set(&ui, Vec::new()); + } + return; + } + let current = self.active().and_then(|p| p.dir()); + let locations = self.locations.clone(); + let latest = self.completion.clone(); + let ui = self.ui.clone(); + std::thread::spawn(move || { + let items = path::complete(&locations, &text, current.as_ref()); + if latest.load(Ordering::SeqCst) != generation { + return; + } + let _ = ui.upgrade_in_event_loop(move |ui| { + if latest.load(Ordering::SeqCst) == generation { + set(&ui, items); + } + }); + }); + } + + fn path_accepted(&self, text: &str) { + self.complete(String::new()); + let current = self.active().and_then(|p| p.dir()); + if let Some(uri) = path::parse(text, current.as_ref()) { + self.go(uri); + } else { + self.focus_active(); + } + } + + fn go_crumb(&self, index: usize) { + let target = self + .active() + .and_then(|p| p.dir()) + .and_then(|d| path::segments(&d).into_iter().nth(index)) + .map(|s| s.uri); + if let Some(uri) = target { + self.go(uri); + } + } + + // ---- wiring ------------------------------------------------------------------------- + + fn bind(&self, ui: &MainWindow) { + // `on!(setter, |shell, args…| body)`: runs `body` while the shell lives. + macro_rules! on { + ($setter:ident, |$s:ident $(, $arg:ident)*| $body:expr) => {{ + let me = self.me.clone(); + ui.$setter(move |$($arg),*| { + if let Some($s) = me.upgrade() { + $body; + } + }); + }}; + } + // Pane callbacks carry the pane's index in the current tab first. + macro_rules! on_pane { + ($setter:ident, |$s:ident, $p:ident $(, $arg:ident)*| $body:expr) => {{ + let me = self.me.clone(); + ui.$setter(move |pane $(, $arg)*| { + if let Some($s) = me.upgrade() { + if let Some($p) = $s.pane_at(pane.max(0) as usize) { + $body; + } + } + }); + }}; + } + let section = |i: i32| Section::ALL.get(usize::try_from(i).ok()?).copied(); + + on!(on_tab_selected, |s, id| if let Some(i) = s.index_of(id) { + s.select_tab(i) + }); + on!(on_tab_closed, |s, id| if let Some(i) = s.index_of(id) { + s.close_tab(i) + }); + on!(on_tab_moved, |s, id, slot| s + .move_tab(id, slot.max(0) as usize)); + on!(on_new_tab, |s| s.new_tab()); + on!(on_cycle_tab, |s, backward| s.cycle(backward)); + on!(on_close_tab, |s| s.close_tab(s.current.get())); + on!(on_pane_activated, |s, i| s + .set_active_pane(i.max(0) as usize)); + on!(on_toggle_split, |s| s.toggle_split()); + on!(on_toggle_sidebar, |s| if let Some(ui) = s.ui.upgrade() { + ui.set_show_sidebar(!ui.get_show_sidebar()) + }); + on!(on_back, |s| s.with_active(|p| p.back())); + on!(on_forward, |s| s.with_active(|p| p.forward())); + on!(on_up, |s| s.with_active(|p| p.up())); + on!(on_go_crumb, |s, i| s.go_crumb(i.max(0) as usize)); + on!(on_path_edited, |s, text| s.complete(text.into())); + on!(on_path_accepted, |s, text| s.path_accepted(&text)); + on!(on_path_reverted, |s| { + s.complete(String::new()); + s.focus_active() + }); + + on_pane!(on_sort_by, |_s, p, column| p.model.sort_column(column)); + on_pane!(on_filter_typed, |_s, p, text| p.model.type_filter(&text)); + on_pane!(on_filter_edited, |_s, p, text| p.model.set_filter(&text)); + on_pane!(on_toggle_hidden, |_s, p| p.model.toggle_hidden()); + on_pane!(on_row_clicked, |_s, p, row, ctrl, shift| { + p.model.click(row.max(0) as usize, ctrl, shift) + }); + on_pane!(on_row_activated, |s, p, row| { + p.activate(usize::try_from(row).ok()); + s.show_chrome() + }); + on_pane!(on_select_all, |_s, p| p.model.select_all()); + on_pane!(on_grid_columns_changed, |_s, p, n| p + .model + .set_columns(n.max(1) as usize)); + on_pane!(on_motion_settled, |_s, p| p.model.motion_settled()); + on_pane!(on_view_mode_selected, |_s, p, mode| p.model.set_mode(mode)); + on_pane!(on_clear_selection, |_s, p| p.model.clear_selection()); + let me = self.me.clone(); + ui.on_navigate(move |i, key, shift, page| { + me.upgrade() + .and_then(|s| s.pane_at(i.max(0) as usize)) + .map_or(-1, |p| p.model.navigate(key, shift, page.max(1) as usize)) + }); + on!( + on_sort_menu_activated, + |s, index, sub| if let Some(p) = s.active() { + p.model.sort_menu_activated(index.max(0) as usize, sub) + } + ); + + on!( + on_place_opened, + |s, i, index, new_tab| if let Some(sec) = section(i) { + s.open_place(sec, index.max(0) as usize, new_tab) + } + ); + on!(on_section_toggled, |s, i| if let Some(sec) = section(i) { + s.places.borrow_mut().toggle(sec); + s.show_chrome() + }); + on!(on_add_bookmark, |s| s.add_bookmark()); + on!( + on_place_menu_requested, + |s, i, index| if let Some(sec) = section(i) { + s.show_place_menu(sec, index.max(0) as usize) + } + ); + on!(on_place_menu_activated, |s, index, _sub| { + s.place_menu_activated(index.max(0) as usize) + }); + on!(on_bookmark_renamed, |s, name| s.rename_bookmark(&name)); + + self.bind_mouse_buttons(ui); + } + + /// Mouse back and forward buttons go to the pane under the pointer. Slint's own touch + /// areas take every button press, so these are caught before Slint sees them. + fn bind_mouse_buttons(&self, ui: &MainWindow) { + use slint::winit_030::winit::event::{ElementState, MouseButton, WindowEvent}; + use slint::winit_030::{EventResult, WinitWindowAccessor}; + + let me = self.me.clone(); + let weak = ui.as_weak(); + ui.window().on_winit_window_event(move |_, event| { + let WindowEvent::MouseInput { + state: ElementState::Pressed, + button: button @ (MouseButton::Back | MouseButton::Forward), + .. + } = event + else { + return EventResult::Propagate; + }; + let (Some(shell), Some(ui)) = (me.upgrade(), weak.upgrade()) else { + return EventResult::Propagate; + }; + let hovered = ui.get_hovered_pane(); + if hovered >= 0 { + shell.set_active_pane(hovered as usize); + } + if *button == MouseButton::Back { + shell.with_active(|p| p.back()); + } else { + shell.with_active(|p| p.forward()); + } + EventResult::PreventDefault + }); + } +} + +/// `12 items`, `3 of 12 selected (4.2 MiB)`, plus hidden files left out. +fn status(pane: &Pane) -> String { + let state = pane.model.state(); + if state.status == crate::FolderStatus::Loading { + return "Loading".into(); + } + if state.status == crate::FolderStatus::Error { + return String::new(); + } + let items = state.items; + let mut text = match pane.model.selection() { + (0, _) => format!("{items} {}", if items == 1 { "item" } else { "items" }), + (n, bytes) => format!("{n} of {items} selected ({})", format::size(bytes)), + }; + if state.hidden > 0 { + text.push_str(&format!(", {} hidden", state.hidden)); + } + text +} diff --git a/crates/tunal/src/shell/pane.rs b/crates/tunal/src/shell/pane.rs new file mode 100644 index 0000000..0fa9ef3 --- /dev/null +++ b/crates/tunal/src/shell/pane.rs @@ -0,0 +1,155 @@ +//! A pane: one folder model (which keeps the view mode) and its back and forward stacks. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::{Rc, Weak}; +use std::sync::Arc; +use std::time::Duration; + +use slint::{ComponentHandle, ModelRc, VecModel}; +use tunal_core::{Locations, Uri}; + +use super::path; +use crate::folder::{Deliver, FolderModel}; +use crate::{MainWindow, MotionPrefs, PaneData, Travel}; + +thread_local! { + /// Models by pane id, so worker results find their model on the UI thread. + static MODELS: RefCell>> = RefCell::new(HashMap::new()); +} + +pub struct Pane { + pub id: u64, + pub model: Rc, + back: RefCell>, + forward: RefCell>, + /// List on the calling thread, without watching (screenshots). + blocking: bool, +} + +impl Pane { + pub fn new(id: u64, ui: &MainWindow, locations: Locations, blocking: bool) -> Rc { + let deliver: Deliver = Arc::new(move |msg| { + let _ = slint::invoke_from_event_loop(move || { + let model = MODELS.with(|m| m.borrow().get(&id).and_then(Weak::upgrade)); + if let Some(model) = model { + model.apply(msg); + } + }); + }); + let model = FolderModel::new(locations, deliver); + MODELS.with(|m| m.borrow_mut().insert(id, Rc::downgrade(&model))); + let weak = ui.as_weak(); + model.set_list_time(move || { + let ms = weak + .upgrade() + .map_or(0, |ui| ui.global::().get_list_change()); + Duration::from_millis(ms.max(0) as u64) + }); + Rc::new(Self { + id, + model, + back: RefCell::new(Vec::new()), + forward: RefCell::new(Vec::new()), + blocking, + }) + } + + pub fn dir(&self) -> Option { + self.model.dir() + } + + fn open(&self, uri: Uri, travel: Travel) { + match travel { + _ if self.blocking => self.model.open_blocking(uri), + Travel::None => self.model.open(uri), + travel => self.model.open_travel(uri, travel), + } + } + + /// Goes to `uri`, remembering the folder left for Back. A parent or child of the folder + /// shown slides in as up or into; any other place appears in place. + pub fn go(&self, uri: Uri) { + let current = self.dir(); + if current.as_ref() == Some(&uri) { + return; + } + let travel = match ¤t { + Some(c) if c.parent().as_ref() == Some(&uri) => Travel::Up, + Some(c) if uri.parent().as_ref() == Some(c) => Travel::Into, + _ => Travel::None, + }; + if let Some(current) = current { + self.back.borrow_mut().push(current); + } + self.forward.borrow_mut().clear(); + self.open(uri, travel); + } + + pub fn back(&self) { + let Some(to) = self.back.borrow_mut().pop() else { + return; + }; + if let Some(current) = self.dir() { + self.forward.borrow_mut().push(current); + } + self.open(to, Travel::Back); + } + + pub fn forward(&self) { + let Some(to) = self.forward.borrow_mut().pop() else { + return; + }; + if let Some(current) = self.dir() { + self.back.borrow_mut().push(current); + } + self.open(to, Travel::Forward); + } + + pub fn up(&self) { + if let Some(parent) = self.dir().as_ref().and_then(Uri::parent) { + self.go(parent); + } + } + + /// Enter or double-click on a row: a folder opens in this pane, with history. + pub fn activate(&self, row: Option) { + let before = self.dir(); + self.model.activate(row); + if self.dir() != before { + if let Some(before) = before { + self.back.borrow_mut().push(before); + } + self.forward.borrow_mut().clear(); + } + } + + pub fn can_back(&self) -> bool { + !self.back.borrow().is_empty() + } + + pub fn can_forward(&self) -> bool { + !self.forward.borrow().is_empty() + } + + pub fn can_up(&self) -> bool { + self.dir().and_then(|d| d.parent()).is_some() + } + + pub fn data(&self) -> PaneData { + let (title, glyph) = self.dir().map(|d| path::title(&d)).unwrap_or_default(); + PaneData { + rows: ModelRc::from(self.model.clone()), + lines: ModelRc::new(VecModel::from(self.model.grid_lines())), + folder: self.model.state(), + title: title.into(), + glyph: glyph.into(), + } + } +} + +impl Drop for Pane { + fn drop(&mut self) { + MODELS.with(|m| m.borrow_mut().remove(&self.id)); + } +} diff --git a/crates/tunal/src/shell/path.rs b/crates/tunal/src/shell/path.rs new file mode 100644 index 0000000..66b4581 --- /dev/null +++ b/crates/tunal/src/shell/path.rs @@ -0,0 +1,166 @@ +//! The breadcrumb's side of a location: segments to show, the text to edit, what a typed +//! path means, and folder completions for it. + +use std::ops::ControlFlow; +use std::path::{Component, Path, PathBuf}; + +use tunal_core::{FILE, Locations, TRASH, Uri, display_name}; + +use super::places::{self, FOLDER, HOME, REMOTE, ROOT, TRASH_GLYPH}; + +pub struct Segment { + pub name: String, + pub glyph: &'static str, + pub uri: Uri, +} + +/// The segments from the root of `uri` (home stands in for its own path) to `uri` itself. +pub fn segments(uri: &Uri) -> Vec { + let mut chain = vec![uri.clone()]; + while let Some(parent) = chain.last().and_then(Uri::parent) { + chain.push(parent); + } + chain.reverse(); + let home = Uri::from_path(&places::home()); + let start = chain.iter().position(|u| *u == home).unwrap_or(0); + chain[start..] + .iter() + .map(|u| { + let (name, glyph) = if *u == home { + ("Home".to_owned(), HOME) + } else { + match u.file_name() { + Some(name) => (display_name(name), ""), + None => root_name(u), + } + }; + Segment { + name, + glyph, + uri: u.clone(), + } + }) + .collect() +} + +fn root_name(uri: &Uri) -> (String, &'static str) { + match uri.scheme() { + FILE => ("File system".to_owned(), ROOT), + TRASH => ("Trash".to_owned(), TRASH_GLYPH), + _ if !uri.authority().is_empty() => (uri.authority().to_owned(), REMOTE), + scheme => (scheme.to_owned(), REMOTE), + } +} + +/// Folder name and glyph of `uri`, for tabs and pane headers. +pub fn title(uri: &Uri) -> (String, &'static str) { + let last = segments(uri).pop(); + match last { + Some(s) if s.glyph.is_empty() => (s.name, FOLDER), + Some(s) => (s.name, s.glyph), + None => (uri.to_string(), FOLDER), + } +} + +/// What the path field starts from: a plain path for local folders, the URI otherwise. +pub fn text(uri: &Uri) -> String { + match uri.to_path() { + Some(path) => path.to_string_lossy().into_owned(), + None => uri.to_string(), + } +} + +/// Reads typed text: a URI (`trash:///`), an absolute path, `~/…`, or a path relative to +/// `current`. `.` and `..` are resolved here. +pub fn parse(text: &str, current: Option<&Uri>) -> Option { + let text = text.trim(); + if text.is_empty() { + return None; + } + if text.contains("://") { + return Uri::parse(text); + } + let path = if text == "~" { + places::home() + } else if let Some(rest) = text.strip_prefix("~/") { + places::home().join(rest) + } else if text.starts_with('/') { + PathBuf::from(text) + } else { + match current { + Some(dir) if dir.scheme() != FILE => { + return Some(relative(dir.clone(), text)); + } + Some(dir) => dir.to_path()?.join(text), + None => places::home().join(text), + } + }; + Some(Uri::from_path(&normalize(&path))) +} + +/// `text` (`a/../b`) applied to a non-local folder. +fn relative(mut dir: Uri, text: &str) -> Uri { + for part in text.split('/') { + match part { + "" | "." => {} + ".." => dir = dir.parent().unwrap_or(dir), + name => dir = dir.join(name.as_bytes()), + } + } + dir +} + +fn normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::from("/"); + for c in path.components() { + match c { + Component::Normal(name) => out.push(name), + Component::ParentDir => { + out.pop(); + } + Component::RootDir | Component::CurDir | Component::Prefix(_) => {} + } + } + out +} + +/// Folder completions of `text`: the folders in its parent part whose names start with its +/// last part (case-insensitive; hidden ones only when that part starts with a dot). Blocking. +pub fn complete(locations: &Locations, text: &str, current: Option<&Uri>) -> Vec<(String, String)> { + const LIMIT: usize = 50; + let (base, prefix) = match text.rfind('/') { + Some(i) => text.split_at(i + 1), + None => ("", text), + }; + let dir = if base.is_empty() { + current.cloned() + } else { + parse(base, current) + }; + let Some(dir) = dir else { + return Vec::new(); + }; + let Ok(backend) = locations.resolve(&dir) else { + return Vec::new(); + }; + let wanted = prefix.to_lowercase(); + let mut found = Vec::new(); + let _ = backend.list(&dir, &mut |entries| { + for e in entries { + let hidden_ok = !e.hidden || prefix.starts_with('.'); + if e.kind.is_dir() && hidden_ok && e.display_name.to_lowercase().starts_with(&wanted) { + found.push(e.display_name); + } + } + ControlFlow::Continue(()) + }); + found.sort_by_key(|n| n.to_lowercase()); + found.truncate(LIMIT); + found + .into_iter() + .map(|name| { + let text = format!("{base}{name}/"); + (name, text) + }) + .collect() +} diff --git a/crates/tunal/src/shell/places.rs b/crates/tunal/src/shell/places.rs new file mode 100644 index 0000000..61e0618 --- /dev/null +++ b/crates/tunal/src/shell/places.rs @@ -0,0 +1,288 @@ +//! The sidebar's places: home and the XDG user dirs, Trash, bookmarks (`places.toml`), and +//! the Devices and Network sections later plans fill through [`Places::set_section`]. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; +use tunal_core::{TRASH, Uri}; + +use crate::config; + +pub const HOME: &str = "\u{e88a}"; +pub const FOLDER: &str = "\u{e2c7}"; +pub const TRASH_GLYPH: &str = "\u{e872}"; +pub const BOOKMARK: &str = "\u{e866}"; +pub const ROOT: &str = "\u{f80e}"; +pub const REMOTE: &str = "\u{eb2f}"; + +/// Sidebar sections, top to bottom; the index is the section number the UI reports. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Section { + Places, + Bookmarks, + Devices, + Network, +} + +impl Section { + pub const ALL: [Section; 4] = [Self::Places, Self::Bookmarks, Self::Devices, Self::Network]; + + pub fn title(self) -> &'static str { + match self { + Self::Places => "Places", + Self::Bookmarks => "Bookmarks", + Self::Devices => "Devices", + Self::Network => "Network", + } + } + + /// Text of the section while it has no items. + pub fn empty(self) -> &'static str { + match self { + Self::Places => "", + Self::Bookmarks => "Bookmark a folder to keep it here", + Self::Devices => "No phones connected", + Self::Network => "No network locations", + } + } + + fn key(self) -> &'static str { + match self { + Self::Places => "places", + Self::Bookmarks => "bookmarks", + Self::Devices => "devices", + Self::Network => "network", + } + } +} + +#[derive(Debug, Clone)] +pub struct Place { + pub name: String, + pub glyph: &'static str, + pub uri: Uri, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Bookmark { + name: String, + uri: String, +} + +/// `places.toml`. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(default)] +struct PlacesFile { + bookmarks: Vec, + /// Keys of the collapsed sections. + collapsed: Vec, +} + +pub struct Places { + standard: Vec, + bookmarks: Vec, + devices: Vec, + network: Vec, + collapsed: HashSet
, +} + +impl Places { + pub fn load() -> Self { + let file: PlacesFile = config::load("places"); + let bookmarks = file + .bookmarks + .into_iter() + .filter_map(|b| { + Some(Place { + name: b.name, + glyph: BOOKMARK, + uri: Uri::parse(&b.uri)?, + }) + }) + .collect(); + let collapsed = Section::ALL + .into_iter() + .filter(|s| file.collapsed.iter().any(|k| k == s.key())) + .collect(); + Self { + standard: standard(), + bookmarks, + devices: Vec::new(), + network: Vec::new(), + collapsed, + } + } + + fn save(&self) { + let file = PlacesFile { + bookmarks: self + .bookmarks + .iter() + .map(|p| Bookmark { + name: p.name.clone(), + uri: p.uri.to_string(), + }) + .collect(), + collapsed: Section::ALL + .into_iter() + .filter(|s| self.collapsed.contains(s)) + .map(|s| s.key().to_owned()) + .collect(), + }; + config::store("places", &file); + } + + pub fn items(&self, section: Section) -> &[Place] { + match section { + Section::Places => &self.standard, + Section::Bookmarks => &self.bookmarks, + Section::Devices => &self.devices, + Section::Network => &self.network, + } + } + + pub fn get(&self, section: Section, index: usize) -> Option<&Place> { + self.items(section).get(index) + } + + /// Replaces the items of a section the app fills at run time (devices, network). + #[expect(dead_code, reason = "the device and network plans fill these sections")] + pub fn set_section(&mut self, section: Section, items: Vec) { + match section { + Section::Devices => self.devices = items, + Section::Network => self.network = items, + Section::Places | Section::Bookmarks => {} + } + } + + pub fn collapsed(&self, section: Section) -> bool { + self.collapsed.contains(§ion) + } + + pub fn toggle(&mut self, section: Section) { + if !self.collapsed.remove(§ion) { + self.collapsed.insert(section); + } + self.save(); + } + + /// Bookmarks `uri` under `name`, unless it is bookmarked already. + pub fn add_bookmark(&mut self, name: String, uri: Uri) { + if self.bookmarks.iter().any(|p| p.uri == uri) { + return; + } + self.bookmarks.push(Place { + name, + glyph: BOOKMARK, + uri, + }); + self.collapsed.remove(&Section::Bookmarks); + self.save(); + } + + pub fn rename_bookmark(&mut self, index: usize, name: &str) { + let name = name.trim(); + if let Some(p) = self.bookmarks.get_mut(index).filter(|_| !name.is_empty()) { + p.name = name.to_owned(); + self.save(); + } + } + + pub fn remove_bookmark(&mut self, index: usize) { + if index < self.bookmarks.len() { + self.bookmarks.remove(index); + self.save(); + } + } + + /// Moves bookmark `index` by `by` places (up is negative). + pub fn move_bookmark(&mut self, index: usize, by: isize) { + let Some(to) = index + .checked_add_signed(by) + .filter(|&t| t < self.bookmarks.len()) + else { + return; + }; + if index < self.bookmarks.len() { + let p = self.bookmarks.remove(index); + self.bookmarks.insert(to, p); + self.save(); + } + } +} + +pub fn home() -> PathBuf { + std::env::var_os("HOME").map_or_else(|| PathBuf::from("/"), PathBuf::from) +} + +/// Home, the user dirs that exist (in the usual order), and Trash. +fn standard() -> Vec { + let home = home(); + let mut places = vec![Place { + name: "Home".into(), + glyph: HOME, + uri: Uri::from_path(&home), + }]; + let dirs = user_dirs(&home); + const KINDS: [(&str, &str, &str); 6] = [ + ("DESKTOP", "Desktop", "\u{e30c}"), + ("DOCUMENTS", "Documents", "\u{e873}"), + ("DOWNLOAD", "Downloads", "\u{f090}"), + ("MUSIC", "Music", "\u{e030}"), + ("PICTURES", "Pictures", "\u{e413}"), + ("VIDEOS", "Videos", "\u{e04a}"), + ]; + for (key, fallback, glyph) in KINDS { + let Some(path) = dirs.iter().find(|(k, _)| k == key).map(|(_, p)| p) else { + continue; + }; + // A dir set to home itself is the spec's way of turning it off. + if *path == home || !path.is_dir() { + continue; + } + let name = path + .file_name() + .map_or_else(|| fallback.to_owned(), |n| n.to_string_lossy().into_owned()); + places.push(Place { + name, + glyph, + uri: Uri::from_path(path), + }); + } + places.push(Place { + name: "Trash".into(), + glyph: TRASH_GLYPH, + uri: Uri::new(TRASH, "", "/"), + }); + places +} + +/// `$XDG_CONFIG_HOME/user-dirs.dirs` as (`DESKTOP`, path) pairs. +fn user_dirs(home: &Path) -> Vec<(String, PathBuf)> { + let config = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .unwrap_or_else(|| home.join(".config")); + let Ok(text) = std::fs::read_to_string(config.join("user-dirs.dirs")) else { + return Vec::new(); + }; + parse_user_dirs(&text, home) +} + +/// Lines like `XDG_MUSIC_DIR="$HOME/Music"`; only `$HOME/…` and absolute paths are valid. +fn parse_user_dirs(text: &str, home: &Path) -> Vec<(String, PathBuf)> { + text.lines() + .filter_map(|line| { + let (key, value) = line.trim().split_once('=')?; + let key = key.strip_prefix("XDG_")?.strip_suffix("_DIR")?; + let value = value.trim().strip_prefix('"')?.strip_suffix('"')?; + let path = match value.strip_prefix("$HOME") { + Some(rest) => home.join(rest.trim_start_matches('/')), + None if value.starts_with('/') => PathBuf::from(value), + None => return None, + }; + Some((key.to_owned(), path)) + }) + .collect() +} diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint index f9d5cbf..e2ffa5b 100644 --- a/crates/tunal/ui/app.slint +++ b/crates/tunal/ui/app.slint @@ -1,14 +1,25 @@ import "../../../assets/fonts/MaterialSymbolsRounded[FILL,GRAD,opsz,wght].ttf"; import { Theme } from "theme.slint"; import { Motion, MotionPrefs } from "motion.slint"; -import { Icon, Icons } from "components/icon.slint"; import { Menu, MenuItem, MenuEntry } from "components/menu.slint"; -import { DetailsView, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn } from "views/details-view.slint"; +import { Dialog } from "components/dialog.slint"; +import { ButtonKind } from "components/button.slint"; +import { TextField } from "components/text-field.slint"; +import { DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode } from "views/details-view.slint"; +import { GridRow } from "views/grid-view.slint"; +import { TabBar, TabData } from "shell/tab-bar.slint"; +import { Toolbar } from "shell/toolbar.slint"; +import { Crumb, Completion, CompletionList } from "shell/breadcrumb.slint"; +import { Pane, PaneData } from "shell/pane.slint"; +import { Sidebar, SidebarSection, PlaceItem } from "shell/sidebar.slint"; +import { StatusBar } from "shell/status-bar.slint"; -export { Theme, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn } +export { Theme, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode, GridRow } +export { TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem } export { Gallery, GalleryPage } from "gallery.slint"; -// Placeholder shell (sidebar + content) until the views land. +// The window: sidebar, tab bar, toolbar with the breadcrumb, the panes of the current tab +// (two in split view) and the status bar. State comes from Rust (shell/). export component MainWindow inherits Window { title: "Tunal"; icon: @image-url("../../../assets/tunal.png"); @@ -19,100 +30,312 @@ export component MainWindow inherits Window { background: Theme.surface; animate background { duration: Motion.time(Motion.medium2); easing: Motion.standard; } - // The open folder (FolderModel in Rust). - in property <[DetailRow]> rows; - in property folder; + // Tabs, by opening order (see TabData). + in property <[TabData]> tabs; + in property current-tab; + in property current-slot; + callback tab-selected(int); + callback tab-closed(int); + callback tab-moved(int, int); + callback new-tab(); + callback cycle-tab(bool); + callback close-tab(); + + // The panes of the current tab; the toolbar, breadcrumb and keys act on the active one. + in property <[PaneData]> panes; + in property active-pane; + // Bumped by Rust to move keyboard focus into the active pane. + in property focus-request; + // The pane under the pointer (mouse back and forward buttons), -1 for none. + out property hovered-pane: -1; + callback pane-activated(int); + callback sort-by(int, SortColumn); + callback filter-typed(int, string); + callback filter-edited(int, string); + callback toggle-hidden(int); + callback row-clicked(int, int, bool, bool); + callback row-activated(int, int); + callback select-all(int); + callback clear-selection(int); + callback navigate(int, NavKey, bool, int) -> int; + callback grid-columns-changed(int, int); + callback motion-settled(int); + callback view-mode-selected(int, ViewMode); in property <[MenuItem]> sort-menu; - callback sort-by <=> details.sort-by; - callback filter-typed <=> details.filter-typed; - callback filter-edited <=> details.filter-edited; - callback toggle-hidden <=> details.toggle-hidden; - callback row-clicked <=> details.row-clicked; - callback row-activated <=> details.row-activated; - callback select-all <=> details.select-all; - callback clear-selection <=> details.clear-selection; - callback navigate <=> details.navigate; callback sort-menu-activated(int, int); - HorizontalLayout { - sidebar := Rectangle { - width: 240px; - background: Theme.surface-container-low; - animate background { duration: Motion.time(Motion.medium2); easing: Motion.standard; } + // Navigation of the active pane. + in property can-back; + in property can-forward; + in property can-up; + in property <[Crumb]> crumbs; + in property path; + in property <[Completion]> completions; + callback back(); + callback forward(); + callback up(); + callback go-crumb(int); + callback path-edited(string); + callback path-accepted(string); + // Editing the path ended without going anywhere. + callback path-reverted(); + callback toggle-split(); + + // Sidebar. + in property <[SidebarSection]> sections; + in property show-sidebar: true; + in property <[MenuItem]> place-menu; + callback toggle-sidebar(); + callback place-opened(int, int, bool); + callback section-toggled(int); + callback add-bookmark(); + callback place-menu-requested(int, int); + callback place-menu-activated(int, int); + callback bookmark-renamed(string); + + in property status; + + public function open-place-menu(x: length, y: length) { + place-popup.open-at(x, y); + } + + public function rename-bookmark(name: string) { + rename-field.text = name; + rename-dialog.show(); + } + + public function edit-path() { + toolbar.edit-path(); + } + + shortcuts := FocusScope { + capture-key-pressed(event) => { + if event.modifiers.control && !event.modifiers.alt { + if event.text == Key.Tab || event.text == Key.Backtab { + root.cycle-tab(event.modifiers.shift || event.text == Key.Backtab); + return accept; + } + if event.text == "t" || event.text == "T" { + root.new-tab(); + return accept; + } + if event.text == "w" || event.text == "W" { + root.close-tab(); + return accept; + } + if event.text == "l" || event.text == "L" { + toolbar.edit-path(); + return accept; + } + if event.text == "d" || event.text == "D" { + root.add-bookmark(); + return accept; + } + } + if event.modifiers.alt && !event.modifiers.control && !toolbar.editing { + if event.text == Key.LeftArrow { + root.back(); + return accept; + } + if event.text == Key.RightArrow { + root.forward(); + return accept; + } + if event.text == Key.UpArrow { + root.up(); + return accept; + } + } + if event.text == Key.F3 { + root.toggle-split(); + return accept; + } + if event.text == Key.F9 { + root.toggle-sidebar(); + return accept; + } + reject + } + + HorizontalLayout { + Sidebar { + width: root.show-sidebar ? 240px : 0; + visible: self.width > 0; + sections: root.sections; + animate width { duration: Motion.time(Motion.medium2); easing: Motion.emphasized; } + open(section, index, new-tab) => { + root.place-opened(section, index, new-tab); + } + toggle(section) => { + root.section-toggled(section); + } + add-bookmark => { + root.add-bookmark(); + } + item-menu(section, index, x, y) => { + root.place-menu-requested(section, index); + place-popup.open-at(x, y); + } + } VerticalLayout { - padding: Theme.space-3; - spacing: Theme.space-1; - alignment: start; + HorizontalLayout { + padding-left: Theme.space-2; + padding-right: Theme.space-2; + padding-top: Theme.space-1; + + TabBar { + tabs: root.tabs; + current: root.current-tab; + current-slot: root.current-slot; + selected(id) => { + root.tab-selected(id); + } + close(id) => { + root.tab-closed(id); + } + moved(id, slot) => { + root.tab-moved(id, slot); + } + new-tab => { + root.new-tab(); + } + } + } + + toolbar := Toolbar { + can-back: root.can-back; + can-forward: root.can-forward; + can-up: root.can-up; + split: root.panes.length > 1; + sidebar: root.show-sidebar; + crumbs: root.crumbs; + path: root.path; + completions: root.completions; + view-mode: root.active-pane < root.panes.length ? root.panes[root.active-pane].folder.mode : ViewMode.details; + view-mode-selected(mode) => { + root.view-mode-selected(root.active-pane, mode); + } + back => { + root.back(); + } + forward => { + root.forward(); + } + up => { + root.up(); + } + toggle-split => { + root.toggle-split(); + } + toggle-sidebar => { + root.toggle-sidebar(); + } + go(i) => { + root.go-crumb(i); + } + path-edited(text) => { + root.path-edited(text); + } + path-accepted(text) => { + root.path-accepted(text); + } + path-reverted => { + root.path-reverted(); + } + } HorizontalLayout { - padding-left: Theme.space-4; - padding-right: Theme.space-4; - height: 40px; - spacing: Theme.space-3; + padding-left: root.panes.length > 1 ? Theme.space-2 : 0; + padding-right: root.panes.length > 1 ? Theme.space-2 : 0; + spacing: Theme.space-2; - VerticalLayout { - alignment: center; - Icon { glyph: Icons.home; } + for pane[i] in root.panes: Pane { + property request: root.focus-request + root.refocus; + data: pane; + active: i == root.active-pane; + split: root.panes.length > 1; + init => { + if self.active { + self.focus-view(); + } + } + changed request => { + if self.active { + self.focus-view(); + } + } + changed hovered => { + if self.hovered { + root.hovered-pane = i; + } else if root.hovered-pane == i { + root.hovered-pane = -1; + } + } + activated => { + root.pane-activated(i); + } + sort-by(column) => { + root.sort-by(i, column); + } + open-sort-menu(x, y) => { + sort-popup.open-at(x, y); + } + filter-typed(text) => { + root.filter-typed(i, text); + } + filter-edited(text) => { + root.filter-edited(i, text); + } + toggle-hidden => { + root.toggle-hidden(i); + } + row-clicked(row, ctrl, shift) => { + root.row-clicked(i, row, ctrl, shift); + } + row-activated(row) => { + root.row-activated(i, row); + } + select-all => { + root.select-all(i); + } + clear-selection => { + root.clear-selection(i); + } + navigate(key, shift, page) => { + root.navigate(i, key, shift, page) + } + columns-changed(n) => { + root.grid-columns-changed(i, n); + } + motion-settled => { + root.motion-settled(i); + } } + } - Text { - text: "Home"; - color: Theme.on-surface; - font-size: Theme.label-large.size; - font-weight: Theme.label-large.weight; - vertical-alignment: center; - } + StatusBar { + text: root.status; } } } + } - // The details view stays built (its callbacks are bound above); the placeholder covers - // it until a folder is open. - Rectangle { - details := DetailsView { - rows: root.rows; - state: root.folder; - open-sort-menu(x, y) => { - sort-popup.open-at(x, y); - } - init => { - self.focus-view(); - } - } + // Focus back to the active pane (after the breadcrumb or a menu). + property refocus; + function focus-pane() { + root.refocus += 1; + } - if !root.folder.open: Rectangle { - background: Theme.surface; - - VerticalLayout { - alignment: center; - spacing: Theme.space-2; - - HorizontalLayout { - alignment: center; - Icon { - glyph: Icons.folder; - size: 48px; - } - } - - Text { - text: "No folder open"; - color: Theme.on-surface; - font-size: Theme.title-medium.size; - font-weight: Theme.title-medium.weight; - horizontal-alignment: center; - } - - Text { - text: "Folders you open appear here"; - color: Theme.on-surface-variant; - font-size: Theme.body-medium.size; - font-weight: Theme.body-medium.weight; - horizontal-alignment: center; - } - } - } + CompletionList { + x: toolbar.crumb-x; + y: toolbar.crumb-bottom + Theme.space-1; + width: toolbar.crumb-width; + visible: toolbar.editing && root.completions.length > 0; + completions: root.completions; + highlight: toolbar.highlight; + picked(text) => { + toolbar.pick(text); } } @@ -125,7 +348,41 @@ export component MainWindow inherits Window { root.sort-menu-activated(index, sub); } closed => { - details.focus-view(); + root.focus-pane(); + } + } + + place-popup := Menu { + width: 100%; + height: 100%; + items: root.place-menu; + leading-icons: true; + activated(index, sub) => { + root.place-menu-activated(index, sub); + } + } + + rename-dialog := Dialog { + width: 100%; + height: 100%; + title: "Rename bookmark"; + body: "The folder itself keeps its name."; + content-focus: true; + actions: [{ text: "Cancel", kind: ButtonKind.text }, { text: "Rename", kind: ButtonKind.filled }]; + default-action: 1; + cancel-action: 0; + focus-content => { + rename-field.focus(); + } + action(i) => { + self.close(); + if i == 1 { + root.bookmark-renamed(rename-field.text); + } + } + + rename-field := TextField { + label: "Name"; } } } diff --git a/crates/tunal/ui/components/icon.slint b/crates/tunal/ui/components/icon.slint index 8f2e951..0847786 100644 --- a/crates/tunal/ui/components/icon.slint +++ b/crates/tunal/ui/components/icon.slint @@ -45,4 +45,10 @@ export global Icons { out property arrow-upward: "\u{e5d8}"; out property arrow-downward: "\u{e5db}"; out property error: "\u{e000}"; + out property arrow-back: "\u{e5c4}"; + out property arrow-forward: "\u{e5c8}"; + out property vertical-split: "\u{e949}"; + out property bookmark-add: "\u{e598}"; + out property expand-more: "\u{e5cf}"; + out property side-navigation: "\u{e9e2}"; } diff --git a/crates/tunal/ui/components/state-layer.slint b/crates/tunal/ui/components/state-layer.slint index 865e358..6dec2ab 100644 --- a/crates/tunal/ui/components/state-layer.slint +++ b/crates/tunal/ui/components/state-layer.slint @@ -36,6 +36,11 @@ export component StateLayer inherits Rectangle { callback double-clicked; // Keys held at the last pointer press, for Ctrl/Shift clicks. out property modifiers; + // Raw pointer events and moves while pressed, for drags and other buttons. + callback pointer(PointerEvent); + callback moved(); + out property mouse-x: touch.mouse-x; + out property pressed-x: touch.pressed-x; property keyboard-focus; property ring-inset: Theme.focus-ring-width + root.ring-offset; @@ -99,6 +104,10 @@ export component StateLayer inherits Rectangle { if event.kind == PointerEventKind.down { root.modifiers = event.modifiers; } + root.pointer(event); + } + moved => { + root.moved(); } changed has-hover => { if !self.has-hover { diff --git a/crates/tunal/ui/shell/breadcrumb.slint b/crates/tunal/ui/shell/breadcrumb.slint new file mode 100644 index 0000000..04f4c0f --- /dev/null +++ b/crates/tunal/ui/shell/breadcrumb.slint @@ -0,0 +1,261 @@ +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Icon, Icons } from "../components/icon.slint"; +import { StateLayer } from "../components/state-layer.slint"; + +// One segment of the path: the root (glyph and name) or a folder. +export struct Crumb { + name: string, + glyph: string, +} + +// A folder that completes the typed path: its name and the whole path it completes to. +export struct Completion { + name: string, + text: string, +} + +component CrumbChip inherits StateLayer { + in property name; + in property glyph; + in property last; + + property content: root.last ? Theme.on-surface : Theme.on-surface-variant; + + height: 32px; + min-width: 32px; + border-radius: Theme.corner-full(self.height); + squeeze: Motion.squeeze; + tint: root.content; + focusable: false; + accessible-role: button; + accessible-label: root.name; + accessible-action-default => { + self.activate(); + } + + HorizontalLayout { + padding-left: Theme.space-2; + padding-right: Theme.space-2; + spacing: Theme.space-1; + + if root.glyph != "": VerticalLayout { + alignment: center; + Icon { + glyph: root.glyph; + size: 18px; + color: root.content; + } + } + + Text { + text: root.name; + color: root.content; + font-size: Theme.label-large.size; + font-weight: root.last ? Theme.label-large.weight : Theme.body-medium.weight; + vertical-alignment: center; + overflow: elide; + } + } +} + +// The path of the active pane as segment chips. Ctrl+L or a click on the empty part turns +// it into a text field: Enter goes, Esc puts the chips back, Tab and the arrows complete +// folder names (the list is drawn by `CompletionList`, above the panes). +export component Breadcrumb inherits Rectangle { + in property <[Crumb]> crumbs; + // The location as text, what editing starts from. + in property path; + in property <[Completion]> completions; + out property editing; + in-out property highlight: -1; + out property text: input.text; + + callback go(int); + callback edited(string); + callback accepted(string); + // Editing ended without going anywhere. + callback reverted(); + + public function edit() { + root.editing = true; + input.text = root.path; + input.focus(); + input.select-all(); + } + + public function stop() { + root.editing = false; + root.highlight = -1; + } + + // A completion picked with the pointer: go there. + public function pick(to: string) { + root.stop(); + root.accepted(to); + } + + function complete(to: string) { + input.text = to; + input.set-selection-offsets(to.character-count * 4, to.character-count * 4); + root.highlight = -1; + root.edited(to); + } + + height: 40px; + border-radius: Theme.corner-full(self.height); + background: Theme.surface-container-high; + border-width: root.editing ? 2px : 0; + border-color: Theme.primary; + clip: true; + + // Behind the chips: the empty part of the bar starts editing. + TouchArea { + mouse-cursor: MouseCursor.text; + clicked => { + root.edit(); + } + } + + if !root.editing: HorizontalLayout { + padding-left: Theme.space-1; + padding-right: Theme.space-4; + alignment: start; + + for crumb[i] in root.crumbs: HorizontalLayout { + if i > 0: VerticalLayout { + alignment: center; + Icon { + glyph: Icons.chevron-right; + size: 18px; + color: Theme.on-surface-variant; + } + } + + CrumbChip { + name: crumb.name; + glyph: crumb.glyph; + last: i == root.crumbs.length - 1; + clicked => { + root.go(i); + } + } + } + } + + keys := FocusScope { + visible: root.editing; + enabled: root.editing; + x: Theme.space-4; + width: parent.width - 2 * Theme.space-4; + + capture-key-pressed(event) => { + if event.text == Key.Escape { + root.stop(); + root.reverted(); + return accept; + } + if event.text == Key.DownArrow && root.completions.length > 0 { + root.highlight = mod(root.highlight + 1, root.completions.length); + return accept; + } + if event.text == Key.UpArrow && root.completions.length > 0 { + root.highlight = root.highlight <= 0 ? root.completions.length - 1 : root.highlight - 1; + return accept; + } + // Tab completes; with nothing to complete it still stays in the field. + if event.text == Key.Tab { + if root.completions.length > 0 { + root.complete(root.completions[max(0, root.highlight)].text); + } + return accept; + } + if event.text == Key.Return { + let target = root.highlight >= 0 && root.highlight < root.completions.length + ? root.completions[root.highlight].text : input.text; + root.stop(); + root.accepted(target); + return accept; + } + reject + } + + input := TextInput { + single-line: true; + color: Theme.on-surface; + selection-background-color: Theme.primary-container; + selection-foreground-color: Theme.on-primary-container; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + accessible-label: "Location"; + edited => { + root.highlight = -1; + root.edited(self.text); + } + changed has-focus => { + if !self.has-focus && root.editing { + root.stop(); + root.reverted(); + } + } + } + } +} + +// The completions of an editing breadcrumb, placed under it by the window. +export component CompletionList inherits Rectangle { + in property <[Completion]> completions; + in property highlight; + callback picked(string); + + property row-height: 36px; + property shown: min(8, root.completions.length); + + height: root.shown * root.row-height + 2 * Theme.space-1; + visible: root.shown > 0; + border-radius: Theme.corner-md; + background: Theme.surface-container; + drop-shadow-blur: Theme.float-shadow-blur; + drop-shadow-offset-y: Theme.float-shadow-offset; + drop-shadow-color: Theme.shadow.with-alpha(Theme.float-shadow-opacity); + + for c[i] in root.completions: StateLayer { + visible: i < root.shown; + x: Theme.space-1; + y: Theme.space-1 + i * root.row-height; + width: parent.width - 2 * Theme.space-1; + height: root.row-height; + border-radius: Theme.corner-sm; + focusable: false; + background: i == root.highlight ? Theme.secondary-container : transparent; + clicked => { + root.picked(c.text); + } + + HorizontalLayout { + padding-left: Theme.space-3; + padding-right: Theme.space-3; + spacing: Theme.space-3; + + VerticalLayout { + alignment: center; + Icon { + glyph: Icons.folder; + size: 18px; + color: i == root.highlight ? Theme.on-secondary-container : Theme.on-surface-variant; + } + } + + Text { + horizontal-stretch: 1; + text: c.name; + color: i == root.highlight ? Theme.on-secondary-container : Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + overflow: elide; + } + } + } +} diff --git a/crates/tunal/ui/shell/pane.slint b/crates/tunal/ui/shell/pane.slint new file mode 100644 index 0000000..3678680 --- /dev/null +++ b/crates/tunal/ui/shell/pane.slint @@ -0,0 +1,147 @@ +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Icon } from "../components/icon.slint"; +import { DetailRow, FolderState, NavKey, SortColumn } from "../views/details-view.slint"; +import { GridRow } from "../views/grid-view.slint"; +import { FolderView } from "../views/view-switch.slint"; + +// One pane of a tab, set from Rust (shell/pane.rs). +export struct PaneData { + rows: [DetailRow], + // The grid view's lines over the same rows. + lines: [GridRow], + folder: FolderState, + // Folder name and glyph, for the split-view header and the tab. + title: string, + glyph: string, +} + +// A folder view with its header. In split view the header names the folder and marks the +// active pane: the one the toolbar, breadcrumb and shortcuts act on. +export component Pane inherits Rectangle { + in property data; + in property active; + in property split; + out property hovered: touch.has-hover; + + // The pointer or keyboard went here: make this the active pane. + callback activated(); + callback sort-by(SortColumn); + callback open-sort-menu(length, length); + callback filter-typed(string); + callback filter-edited(string); + callback toggle-hidden(); + callback row-clicked(int, bool, bool); + callback row-activated(int); + callback select-all(); + callback clear-selection(); + callback navigate(NavKey, bool, int) -> int; + callback columns-changed(int); + callback motion-settled(); + + public function focus-view() { + details.focus-view(); + } + + property header-height: root.split ? 32px : 0; + + border-radius: root.split ? Theme.corner-md : 0; + clip: true; + background: Theme.surface; + + // Clicks the view leaves alone (empty space, the header) still activate the pane; the + // hover is for the mouse back and forward buttons, which go to the pane under the pointer. + touch := TouchArea { + clicked => { + root.activated(); + root.focus-view(); + } + + VerticalLayout { + if root.split: Rectangle { + height: root.header-height; + background: root.active ? Theme.secondary-container : Theme.surface-container; + animate background { duration: Motion.time(Motion.short4); easing: Motion.standard; } + + HorizontalLayout { + padding-left: Theme.space-3; + padding-right: Theme.space-3; + spacing: Theme.space-2; + + VerticalLayout { + alignment: center; + Icon { + glyph: root.data.glyph; + size: 18px; + color: root.active ? Theme.on-secondary-container : Theme.on-surface-variant; + animate color { duration: Motion.time(Motion.short4); easing: Motion.standard; } + } + } + + Text { + horizontal-stretch: 1; + text: root.data.title; + color: root.active ? Theme.on-secondary-container : Theme.on-surface-variant; + font-size: Theme.label-large.size; + font-weight: Theme.label-large.weight; + vertical-alignment: center; + overflow: elide; + animate color { duration: Motion.time(Motion.short4); easing: Motion.standard; } + } + } + } + + details := FolderView { + rows: root.data.rows; + lines: root.data.lines; + state: root.data.folder; + columns-changed(n) => { + root.columns-changed(n); + } + motion-settled => { + root.motion-settled(); + } + sort-by(column) => { + root.activated(); + root.sort-by(column); + } + open-sort-menu(x, y) => { + root.activated(); + root.open-sort-menu(x, y); + } + filter-typed(text) => { + root.activated(); + root.filter-typed(text); + } + filter-edited(text) => { + root.activated(); + root.filter-edited(text); + } + toggle-hidden => { + root.activated(); + root.toggle-hidden(); + } + row-clicked(row, ctrl, shift) => { + root.activated(); + root.row-clicked(row, ctrl, shift); + } + row-activated(row) => { + root.activated(); + root.row-activated(row); + } + select-all => { + root.activated(); + root.select-all(); + } + clear-selection => { + root.activated(); + root.clear-selection(); + } + navigate(key, shift, page) => { + root.activated(); + root.navigate(key, shift, page) + } + } + } + } +} diff --git a/crates/tunal/ui/shell/sidebar.slint b/crates/tunal/ui/shell/sidebar.slint new file mode 100644 index 0000000..b18d173 --- /dev/null +++ b/crates/tunal/ui/shell/sidebar.slint @@ -0,0 +1,170 @@ +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Icon, Icons } from "../components/icon.slint"; +import { IconButton } from "../components/icon-button.slint"; +import { ListRow } from "../components/list-row.slint"; +import { StateLayer } from "../components/state-layer.slint"; + +export struct PlaceItem { + name: string, + glyph: string, + // Shows the selection fill: the active pane is at this place. + current: bool, +} + +// One section of the sidebar (places, bookmarks, devices, network), set from Rust. +export struct SidebarSection { + title: string, + items: [PlaceItem], + collapsed: bool, + // Shown when there are no items. + empty: string, + // Offers "Add the current folder" in its header (bookmarks). + can-add: bool, +} + +component SectionHeader inherits StateLayer { + in property title; + in property collapsed; + in property can-add; + callback add(); + + height: 36px; + border-radius: Theme.corner-full(self.height); + squeeze: Motion.squeeze-large; + tint: Theme.on-surface-variant; + accessible-role: button; + accessible-label: root.title; + accessible-expandable: true; + accessible-expanded: !root.collapsed; + accessible-action-default => { + self.activate(); + } + + HorizontalLayout { + padding-left: Theme.space-4; + padding-right: Theme.space-1; + spacing: Theme.space-2; + + Text { + horizontal-stretch: 1; + text: root.title; + color: Theme.on-surface-variant; + font-size: Theme.label-medium.size; + font-weight: Theme.label-medium.weight; + vertical-alignment: center; + overflow: elide; + } + + if root.can-add: VerticalLayout { + alignment: center; + IconButton { + icon: Icons.bookmark-add; + size: 28px; + icon-size: 18px; + tooltip: "Bookmark the current folder (Ctrl+D)"; + clicked => { + root.add(); + } + } + } + + VerticalLayout { + alignment: center; + Rectangle { + width: 28px; + height: 28px; + Icon { + glyph: Icons.expand-more; + size: 18px; + color: Theme.on-surface-variant; + transform-rotation: root.collapsed ? -90deg : 0deg; + animate transform-rotation { duration: Motion.time(Motion.short4); easing: Motion.emphasized; } + } + } + } + } +} + +// Places, bookmarks, devices and network locations in collapsible sections. +export component Sidebar inherits Rectangle { + in property <[SidebarSection]> sections; + // Left click (or middle click, `new-tab`) on item `index` of section `section`. + callback open(section: int, index: int, new-tab: bool); + callback toggle(section: int); + callback add-bookmark(); + // Right click on an item, at window coordinates. + callback item-menu(section: int, index: int, x: length, y: length); + + property row-height: 40px; + + background: Theme.surface-container-low; + animate background { duration: Motion.time(Motion.medium2); easing: Motion.standard; } + + Flickable { + content-height: max(self.height, column.preferred-height); + + column := VerticalLayout { + padding: Theme.space-3; + spacing: Theme.space-1; + alignment: start; + + for section[s] in root.sections: VerticalLayout { + SectionHeader { + title: section.title; + collapsed: section.collapsed; + can-add: section.can-add; + clicked => { + root.toggle(s); + } + add => { + root.add-bookmark(); + } + } + + // Folds to nothing: clipped while its height animates. + Rectangle { + property full: section.items.length == 0 ? root.row-height : section.items.length * root.row-height; + height: section.collapsed ? 0 : self.full; + clip: true; + animate height { duration: Motion.time(Motion.medium2); easing: Motion.emphasized; } + + if section.items.length == 0: Text { + x: Theme.space-4; + y: 0; + width: parent.width - 2 * Theme.space-4; + height: root.row-height; + text: section.empty; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + vertical-alignment: center; + overflow: elide; + } + + for item[i] in section.items: ListRow { + x: 0; + y: i * root.row-height; + width: parent.width; + height: root.row-height; + icon: item.glyph; + title: item.name; + selected: item.current; + focusable: false; + clicked => { + root.open(s, i, false); + } + pointer(event) => { + if event.kind == PointerEventKind.up && event.button == PointerEventButton.middle { + root.open(s, i, true); + } + if event.kind == PointerEventKind.down && event.button == PointerEventButton.right { + root.item-menu(s, i, self.absolute-position.x + self.mouse-x, self.absolute-position.y + root.row-height); + } + } + } + } + } + } + } +} diff --git a/crates/tunal/ui/shell/status-bar.slint b/crates/tunal/ui/shell/status-bar.slint new file mode 100644 index 0000000..997eda6 --- /dev/null +++ b/crates/tunal/ui/shell/status-bar.slint @@ -0,0 +1,19 @@ +import { Theme } from "../theme.slint"; + +// One line under the panes: what the active pane shows and what is selected in it. +export component StatusBar inherits Rectangle { + in property text; + + height: 28px; + + Text { + x: Theme.space-4; + width: parent.width - 2 * Theme.space-4; + text: root.text; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + vertical-alignment: center; + overflow: elide; + } +} diff --git a/crates/tunal/ui/shell/tab-bar.slint b/crates/tunal/ui/shell/tab-bar.slint new file mode 100644 index 0000000..0d0a9fa --- /dev/null +++ b/crates/tunal/ui/shell/tab-bar.slint @@ -0,0 +1,219 @@ +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Icon, Icons } from "../components/icon.slint"; +import { IconButton } from "../components/icon-button.slint"; +import { StateLayer } from "../components/state-layer.slint"; + +// One tab as Rust keeps it. Rows stay in the order the tabs were opened, so closing or moving +// one never rebuilds the others; `slot` is the place it is shown at. +export struct TabData { + id: int, + title: string, + glyph: string, + slot: int, +} + +component ShellTab inherits StateLayer { + in property title; + in property glyph; + in property active; + // Off for the only tab: there is always one. + in property closable; + callback close(); + // Left press moved past the drag threshold, then each move while dragged. + callback drag-moved(length); + callback drag-ended(); + + property content: root.active ? Theme.on-secondary-container : Theme.on-surface-variant; + property dragging; + // Fades in once when the tab opens; tabs are never rebuilt, so this runs once per tab. + property born; + init => { + root.born = true; + } + + border-radius: Theme.corner-full(self.height); + squeeze: Motion.squeeze-large; + ring-offset: -Theme.focus-ring-width; + tint: root.content; + opacity: root.born ? 1 : 0; + animate opacity { duration: Motion.time(Motion.short4); easing: Motion.standard-decelerate; } + + accessible-role: tab; + accessible-label: root.title; + accessible-item-selectable: true; + accessible-item-selected: root.active; + accessible-action-default => { + self.activate(); + } + + pointer(event) => { + if event.button == PointerEventButton.middle && event.kind == PointerEventKind.up && root.closable { + root.close(); + } + if event.button == PointerEventButton.left && event.kind == PointerEventKind.up && root.dragging { + root.dragging = false; + root.drag-ended(); + } + } + moved => { + if !root.dragging && abs(root.mouse-x - root.pressed-x) > Theme.space-1 { + root.dragging = true; + } + if root.dragging { + root.drag-moved(root.mouse-x - root.pressed-x); + } + } + + HorizontalLayout { + padding-left: Theme.space-3; + padding-right: root.closable ? Theme.space-1 : Theme.space-3; + spacing: Theme.space-2; + + VerticalLayout { + alignment: center; + Icon { + glyph: root.glyph; + size: 18px; + color: root.content; + animate color { duration: Motion.time(Motion.short4); easing: Motion.standard; } + } + } + + Text { + horizontal-stretch: 1; + text: root.title; + color: root.content; + font-size: Theme.label-large.size; + font-weight: Theme.label-large.weight; + vertical-alignment: center; + overflow: elide; + animate color { duration: Motion.time(Motion.short4); easing: Motion.standard; } + } + + if root.closable: VerticalLayout { + alignment: center; + IconButton { + icon: Icons.close; + size: 28px; + icon-size: 18px; + tooltip: "Close tab (Ctrl+W)"; + clicked => { + root.close(); + } + } + } + } +} + +// Pill tabs sharing the width between a minimum and a maximum, one selection pill that slides +// to the current tab, and a new-tab button after the last tab. A dragged tab stays under the +// pointer while the others slide aside to show where it drops. +export component TabBar { + in property <[TabData]> tabs; + in property current; + // Slot of the current tab, for the selection pill. + in property current-slot; + callback selected(id: int); + callback close(id: int); + // Tab `id` dropped at `slot`. + callback moved(id: int, slot: int); + callback new-tab(); + + property gap: Theme.space-1; + property tab-height: 36px; + property button: 40px; + property min-tab: 76px; + property max-tab: 240px; + property room: root.width - root.button - root.gap; + property tab-width: root.tabs.length == 0 ? root.max-tab + : max(root.min-tab, min(root.max-tab, (root.room - (root.tabs.length - 1) * root.gap) / root.tabs.length)); + property step: root.tab-width + root.gap; + + // The dragged tab (-1 for none), its slot, its x and where it would drop. + property drag-id: -1; + property drag-from; + property drag-x; + property drag-to: min(root.tabs.length - 1, max(0, round(root.drag-x / root.step))); + + // Slot a tab is shown at while another one is dragged. + pure function shown(slot: int) -> int { + if root.drag-id < 0 { + return slot; + } + if root.drag-from < slot && slot <= root.drag-to { + return slot - 1; + } + if root.drag-to <= slot && slot < root.drag-from { + return slot + 1; + } + slot + } + + height: 40px + 2 * Theme.space-1; + accessible-role: tab-list; + + Rectangle { + clip: true; + width: root.room; + x: 0; + + // The selection pill, under the tabs. + if root.tabs.length > 0: Rectangle { + // Dragging selects the tab, so a dragged tab is always the current one. + x: root.drag-id >= 0 ? root.drag-x : root.current-slot * root.step; + y: (parent.height - root.tab-height) / 2; + width: root.tab-width; + height: root.tab-height; + border-radius: Theme.corner-full(self.height); + background: Theme.secondary-container; + animate x { duration: Motion.time(root.drag-id >= 0 ? 0 : Motion.medium2); easing: Motion.emphasized; } + } + + for tab in root.tabs: ShellTab { + property dragged: tab.id == root.drag-id; + property rest-x: root.shown(tab.slot) * root.step; + x: self.dragged ? root.drag-x : self.rest-x; + y: (parent.height - root.tab-height) / 2; + width: root.tab-width; + height: root.tab-height; + title: tab.title; + glyph: tab.glyph; + active: tab.id == root.current; + closable: root.tabs.length > 1; + animate x { duration: Motion.time(self.dragged ? 0 : Motion.medium2); easing: Motion.emphasized; } + + clicked => { + root.selected(tab.id); + } + close => { + root.close(tab.id); + } + drag-moved(dx) => { + if root.drag-id != tab.id { + root.drag-id = tab.id; + root.drag-from = tab.slot; + root.drag-x = self.x; + root.selected(tab.id); + } + root.drag-x = max(0, min((root.tabs.length - 1) * root.step, root.drag-x + dx)); + } + drag-ended => { + root.moved(tab.id, root.drag-to); + root.drag-id = -1; + } + } + } + + IconButton { + x: min(root.room + root.gap, root.tabs.length * root.step); + y: (parent.height - self.height) / 2; + icon: Icons.add; + size: root.button; + tooltip: "New tab (Ctrl+T)"; + animate x { duration: Motion.time(Motion.medium2); easing: Motion.emphasized; } + clicked => { + root.new-tab(); + } + } +} diff --git a/crates/tunal/ui/shell/toolbar.slint b/crates/tunal/ui/shell/toolbar.slint new file mode 100644 index 0000000..b2dd370 --- /dev/null +++ b/crates/tunal/ui/shell/toolbar.slint @@ -0,0 +1,151 @@ +import { Theme } from "../theme.slint"; +import { Icons } from "../components/icon.slint"; +import { IconButton } from "../components/icon-button.slint"; +import { ViewMode } from "../views/details-view.slint"; +import { ViewSwitch } from "../views/view-switch.slint"; +import { Breadcrumb, Crumb, Completion } from "breadcrumb.slint"; + +// Navigation for the active pane: sidebar toggle, back, forward, up, the breadcrumb, the +// view mode and the split view toggle. +export component Toolbar inherits Rectangle { + in property can-back; + in property can-forward; + in property can-up; + in property split; + in property sidebar; + in property <[Crumb]> crumbs; + in property path; + in property <[Completion]> completions; + in property view-mode; + in-out property highlight <=> crumb.highlight; + out property editing: crumb.editing; + // Where the completion list goes, in window coordinates. + out property crumb-x: crumb.absolute-position.x; + out property crumb-bottom: crumb.absolute-position.y + crumb.height; + out property crumb-width: crumb.width; + + callback back(); + callback forward(); + callback up(); + callback toggle-split(); + callback view-mode-selected(ViewMode); + callback toggle-sidebar(); + callback go(int); + callback path-edited(string); + callback path-accepted(string); + callback path-reverted(); + + public function edit-path() { + crumb.edit(); + } + + public function pick(to: string) { + crumb.pick(to); + } + + height: 56px; + + HorizontalLayout { + padding-left: Theme.space-2; + padding-right: Theme.space-2; + spacing: Theme.space-1; + alignment: stretch; + + VerticalLayout { + alignment: center; + IconButton { + icon: Icons.side-navigation; + toggle: true; + checked: root.sidebar; + tooltip: "Sidebar (F9)"; + clicked => { + root.toggle-sidebar(); + } + } + } + + VerticalLayout { + alignment: center; + IconButton { + icon: Icons.arrow-back; + enabled: root.can-back; + tooltip: "Back (Alt+Left)"; + clicked => { + root.back(); + } + } + } + + VerticalLayout { + alignment: center; + IconButton { + icon: Icons.arrow-forward; + enabled: root.can-forward; + tooltip: "Forward (Alt+Right)"; + clicked => { + root.forward(); + } + } + } + + VerticalLayout { + alignment: center; + IconButton { + icon: Icons.arrow-upward; + enabled: root.can-up; + tooltip: "Parent folder (Alt+Up)"; + clicked => { + root.up(); + } + } + } + + VerticalLayout { + alignment: center; + horizontal-stretch: 1; + padding-left: Theme.space-2; + padding-right: Theme.space-2; + + crumb := Breadcrumb { + crumbs: root.crumbs; + path: root.path; + completions: root.completions; + go(i) => { + root.go(i); + } + edited(text) => { + root.path-edited(text); + } + accepted(text) => { + root.path-accepted(text); + } + reverted => { + root.path-reverted(); + } + } + } + + VerticalLayout { + alignment: center; + ViewSwitch { + mode: root.view-mode; + selected(mode) => { + root.view-mode-selected(mode); + } + } + } + + VerticalLayout { + alignment: center; + IconButton { + icon: Icons.vertical-split; + toggle: true; + checked: root.split; + tooltip: "Split view (F3)"; + clicked => { + root.toggle-split(); + } + } + } + } +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 61eb541..482d51f 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -35,3 +35,4 @@ D-030 — 2026-11-18 — Playlist sort refined (supersedes D-021's details, keep D-031 — 2026-11-18 — Floating surfaces don't use `PopupWindow` (it closes without exit motion): `Menu` and `Dialog` inherit `Overlay` and `ToastStack` is a plain layer, each placed last in the window at `width: 100%; height: 100%` in the order ToastStack, Dialog, Menu; they open with window coordinates and play exit motion by animating a `progress` that reverses mid-flight. Dialogs never close themselves (owner calls `close()` from `action`); toast models are owned outside (`closing` ends one, `removed(index)` drops it). Tooltips stay on `PopupWindow` (fade in, leave at once) — S005 — every UI plan with menus, dialogs or toasts (S010–S013, S018–S031). D-032 — 2026-11-18 — Folder views use `folder::FolderModel` (one per view, `Rc`, a Slint `Model` of `DetailRow`s formatted on demand; worker results reach it through `upgrade_in_event_loop` + `as_any` downcast and carry a generation); selection is a set of raw names (`click`, `navigate`, `select_all`); sort menus are built in Rust as `[MenuItem]` and opened at window level (D-031); list rows set `StateLayer.focusable: false` and the view's `FocusScope` owns the keys; watch events are hints (unchanged stat is ignored: the local backend also reports reads) — S008 — S009–S015. D-033 — 2026-11-18 — View mode and list motion: `ViewMode { details, grid }` (views/details-view.slint) lives in `folder::Settings::mode`, so one per `FolderModel` = per pane, carried over between folders like the sort, and reaches the views as `FolderState.mode` (`set_mode`); `.directory` view settings read and write that field. `FolderView` (views/view-switch.slint) stacks both views and cross-fades them; `ViewSwitch` is the segmented control. List changes (sort, filter, hidden, watch, playlist re-sort; not listing chunks) animate from Rust-computed per-row `from`/`to` offsets and leaving copies, drawn from one `MotionClock` (motion.slint, `animation-tick()` while running only), length `MotionPrefs.list-change` (0 under reduced motion = no transition); instant above 2000 rows. Opening with `open_travel(uri, Travel)` slides content from the right (into, forward) or left (up, back) — S009 — S010, S015, S018 (grid thumbnails in `GridCell`). +D-034 — 2026-11-18 — Window shell API: MainWindow holds `panes: [PaneData { rows, lines, folder, title, glyph }]` for the current tab and every folder-view callback takes the pane index first (`sort-by(int, SortColumn)`, `row-activated(int, int)`, `view-mode-selected(int, ViewMode)`, …); toolbar, breadcrumb, sort menu and status follow `active-pane`. Rust side: `shell::Shell` owns tabs/panes and binds those callbacks; one `FolderModel` per `shell::pane::Pane`, worker results routed by pane id; `folder::attach` is gone. Config goes through `config::{load, store}` (TOML in `$XDG_CONFIG_HOME/tunal/`), later settings are new fields on `config::Settings`; sidebar sections Devices/Network are filled with `Places::set_section` — S010 — S011–S015, S024–S029. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 271d826..f5875a3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -92,5 +92,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: navigation slide and live motion not watched (no event loop offscreen; S035); `tunal --screenshot` in the grid view shows one column until S010 keeps the Shell alive in its screenshot path. Screenshot env `TUNAL_VIEW=grid` added. - Later: a live switch to reduced motion during a change leaves its leaving rows until the next change; entering rows interrupted mid-growth jump to full height; grid thumbnails (S018) go in `GridCell`. +## S010 — Tabs, split view, breadcrumbs, history and places +- Done: `config.rs` (`$XDG_CONFIG_HOME/tunal/.toml`, `load` with defaults, atomic `save`/`store`; `Settings { restore_session, show_sidebar }`, `Session { tabs: [{ panes: [uri], active }], current }` saved on window close). `shell/`: `Shell::attach(ui, locations, tabs, blocking)` owns tabs (rows in opening order + `slot`), one `Pane` per view (`pane.rs`: own `FolderModel`, back/forward stacks, `open_travel` into/up/back/forward, deliver by pane id), split toggle (F3, new pane active), active pane header; `path.rs` crumbs (Home stands in for its path, `File system`, `Trash`), typed paths (`~`, `..`, relative, any `scheme://`), folder completion off-thread; `places.rs` (home + `user-dirs.dirs` + Trash, bookmarks in `places.toml` with rename/move/remove menu and dialog, collapsed sections; `Places::set_section(Section::Devices|Network, Vec)` for later plans, `#[expect(dead_code)]` until used). UI `ui/shell/{tab-bar,toolbar,breadcrumb,pane,sidebar,status-bar}.slint`; MainWindow is per pane now (D-034). Mouse back/forward via the winit event hook (`unstable-winit-030`). `StateLayer` gained `pointer`, `moved`, `mouse-x`, `pressed-x`. `tunal […] [--split a b]`. +- Open a URI in a new tab: `Shell::open_tab(vec![uri]); show_current()` (private; add a `pub fn` when a plan needs it from outside the shell). +- Verified: workspace build, clippy -D warnings, fmt --check, literal grep empty; looked at light + dark 1200x760 with two tabs, split view and sidebar, restored session (3 tabs, bookmarks, collapsed section), breadcrumb editing with completion list. Temporary uncommitted hook in a scratch copy: history (into/up/back/forward/crumb), typed paths, completion of 5 inputs, select-all status, tab new/move/cycle/close, split, bookmarks add (deduped)/move/rename/remove, session + places files written and read back; real key and pointer events through the window: Ctrl+T/W/Tab, Ctrl+L + typing + Enter/Esc, Alt+arrows, F3, F9, middle-click close, drag tab to front, click empty breadcrumb, place and crumb clicks. +- Not done: mouse back/forward buttons not exercised (winit only; no live window). Tab and section motion not watched (software renderer ignores `transform-*`; screenshots are single frames). Completion list delivery needs the event loop (logic and list checked separately). A closed tab vanishes at once; the others slide over. +- Later: tab bar scrolling past the minimum width; drag-reorder bookmarks in the sidebar; per-place glyph on tabs (Music shows a plain folder); Backspace to go up. + ## Later -