From f7af0f56b4e79207159429ff43afcbd3e1b70e3d Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 18 Nov 2026 18:46:11 -0600 Subject: [PATCH] S013: settings dialog, editable context menus (menus.toml), menu editor Shared files actions.rs, app.slint, main.rs, shell/mod.rs carry S012 hunks and are committed with S012. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 1 + .../S013-settings-context-menus.md | 10 +- Plans/INDEX.md | 2 +- crates/tunal/src/config.rs | 56 ++- crates/tunal/src/folder/mod.rs | 54 ++- crates/tunal/src/folder/sort.rs | 30 +- crates/tunal/src/menus.rs | 175 ++++++++ crates/tunal/src/settings.rs | 226 ++++++++++ crates/tunal/src/theme_bridge.rs | 27 +- crates/tunal/ui/components/icon.slint | 2 + crates/tunal/ui/dialogs/menu-editor.slint | 401 ++++++++++++++++++ crates/tunal/ui/dialogs/settings.slint | 329 ++++++++++++++ crates/tunal/ui/motion.slint | 5 + docs/PROGRESS.md | 7 + 14 files changed, 1297 insertions(+), 28 deletions(-) create mode 100644 crates/tunal/src/menus.rs create mode 100644 crates/tunal/src/settings.rs create mode 100644 crates/tunal/ui/dialogs/menu-editor.slint create mode 100644 crates/tunal/ui/dialogs/settings.slint diff --git a/CLAUDE.md b/CLAUDE.md index c2936f1..3d472a2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -89,6 +89,7 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~ | `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 | +| `TUNAL_SETTINGS=<0-4> cargo run -p tunal -- --screenshot --size 1000x700` (`XDG_CONFIG_HOME=`) | settings dialog page over a folder | S013 | Don't assume a tool exists: check first. When your plan creates a tool, add its row here. diff --git a/Plans/03 File browsing/S013-settings-context-menus.md b/Plans/03 File browsing/S013-settings-context-menus.md index f2b783e..7b39111 100644 --- a/Plans/03 File browsing/S013-settings-context-menus.md +++ b/Plans/03 File browsing/S013-settings-context-menus.md @@ -10,11 +10,11 @@ A settings dialog and context menus the user edits in the app (add, remove, reor crates/tunal/src/{actions.rs,config.rs}; crates/tunal/ui/components/{dialog,menu,switch,list-row}.slint. ## Steps -- [ ] Settings dialog pages: General (hidden files, folders first, restore tabs), View (default view, sort, grouping), Previews (placeholder for S018), Motion (follow system / always reduce / never reduce), Context menus. -- [ ] Menu model per context (file, folder, multiple items, empty area, trash): action ids + separators; defaults; stored in `menus.toml`. -- [ ] Menu editor: add from available actions, remove, reorder by drag and by buttons (animated), reset to defaults. -- [ ] Context menus are built from the model everywhere (views, sidebar entries). -- [ ] PROGRESS entry, INDEX line, commit `S013: …` +- [x] Settings dialog pages: General (hidden files, folders first, restore tabs), View (default view, sort, grouping), Previews (placeholder for S018), Motion (follow system / always reduce / never reduce), Context menus. +- [x] Menu model per context (file, folder, multiple items, empty area, trash): action ids + separators; defaults; stored in `menus.toml`. +- [x] Menu editor: add from available actions, remove, reorder by drag and by buttons (animated), reset to defaults. +- [x] Context menus are built from the model everywhere (views, sidebar entries). +- [x] PROGRESS entry, INDEX line, commit `S013: …` ## 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 2cd7625..f27064e 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -25,7 +25,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v - [x] [S010 — Tabs, split view, breadcrumbs, history and places](03%20File%20browsing/S010-navigation-shell.md) · Opus medium - [x] [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 +- [x] [S013 — Settings dialog and editable context menus](03%20File%20browsing/S013-settings-context-menus.md) · Sonnet high - [ ] [S014 — In-app drag and drop](03%20File%20browsing/S014-in-app-dnd.md) · Opus medium ## 04 Directory metadata diff --git a/crates/tunal/src/config.rs b/crates/tunal/src/config.rs index 00d8c01..8e347ad 100644 --- a/crates/tunal/src/config.rs +++ b/crates/tunal/src/config.rs @@ -60,13 +60,60 @@ pub fn store(name: &str, value: &T) { } } +/// Details list or icon grid. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum View { + #[default] + Details, + Grid, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Sort { + #[default] + Name, + Size, + Type, + Modified, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Group { + #[default] + None, + Type, + Modified, + Size, +} + +/// Whether motion follows the desktop's animation setting. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Motion { + #[default] + System, + Reduce, + Full, +} + /// `settings.toml`. Later plans add their fields here. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct Settings { /// Reopen the tabs of the last session. pub restore_session: bool, pub show_sidebar: bool, + pub show_hidden: bool, + pub folders_first: bool, + /// What a new pane starts with. + pub view: View, + pub sort: Sort, + pub sort_descending: bool, + pub group: Group, + pub motion: Motion, } impl Default for Settings { @@ -74,6 +121,13 @@ impl Default for Settings { Self { restore_session: true, show_sidebar: true, + show_hidden: false, + folders_first: true, + view: View::Details, + sort: Sort::Name, + sort_descending: false, + group: Group::None, + motion: Motion::System, } } } diff --git a/crates/tunal/src/folder/mod.rs b/crates/tunal/src/folder/mod.rs index 55695b7..ad4861b 100644 --- a/crates/tunal/src/folder/mod.rs +++ b/crates/tunal/src/folder/mod.rs @@ -16,6 +16,7 @@ use slint::{Model, ModelNotify, ModelRc, ModelTracker, SharedString, VecModel}; use tunal_core::playlist::Playlist; use tunal_core::{Entry, Error, Locations, Uri, Watch}; +use crate::config; use crate::icons::{self, Category}; use crate::{ DetailRow, FolderState, FolderStatus, GridRow, Grouping, MenuEntry, MenuItem, NavKey, @@ -132,7 +133,7 @@ impl FolderModel { by_name: HashMap::new(), rows: Vec::new(), row_of: HashMap::new(), - settings: Settings::default(), + settings: Settings::from_config(&config::load("settings")), playlists: Vec::new(), playlist_path: None, selected: HashSet::new(), @@ -569,6 +570,35 @@ impl FolderModel { self.set_filter(&filter); } + /// The settings dialog changed what applies to panes already open. + pub fn apply_config(&self, cfg: &config::Settings) { + let (hidden, folders_first) = (cfg.show_hidden, cfg.folders_first); + let current = { + let s = self.state.borrow(); + (s.settings.show_hidden, s.settings.folders_first) + }; + if current != (hidden, folders_first) { + self.update(|s| { + s.show_hidden = hidden; + s.folders_first = folders_first; + }); + } + } + + /// True when everything selected (or under the cursor) is a folder. + pub fn selection_is_dir(&self) -> bool { + let s = self.state.borrow(); + let names: Vec<&Vec> = if s.selected.is_empty() { + s.cursor.iter().collect() + } else { + s.selected.iter().collect() + }; + !names.is_empty() + && names + .iter() + .all(|n| s.by_name.get(*n).is_some_and(|&i| s.items[i].is_dir)) + } + pub fn toggle_hidden(&self) { self.update(|s| s.show_hidden = !s.show_hidden); } @@ -889,21 +919,25 @@ impl FolderModel { line as i32 } - /// Enter or double-click: opens the folder at `row` (the cursor row when `None`). - pub fn activate(&self, row: Option) { - let target = { + /// Enter or double-click: opens the folder at `row` (the cursor row when `None`); a file + /// is returned for the caller to open. + pub fn activate(&self, row: Option) -> Option { + let (uri, is_dir) = { let s = self.state.borrow(); let row = row.or_else(|| s.cursor.as_ref().and_then(|c| s.row_of.get(c)).copied()); match row.and_then(|r| s.rows.get(r)) { - Some(Row::Item(i)) if s.items[*i].is_dir => { - s.dir.as_ref().map(|d| d.join(&s.items[*i].entry.name)) - } - _ => None, + Some(Row::Item(i)) => ( + s.dir.as_ref().map(|d| d.join(&s.items[*i].entry.name)), + s.items[*i].is_dir, + ), + _ => (None, false), } }; - if let Some(dir) = target { - self.open_travel(dir, Travel::Into); + if is_dir { + self.open_travel(uri?, Travel::Into); + return None; } + uri } } diff --git a/crates/tunal/src/folder/sort.rs b/crates/tunal/src/folder/sort.rs index 98c8589..0d6ab3b 100644 --- a/crates/tunal/src/folder/sort.rs +++ b/crates/tunal/src/folder/sort.rs @@ -7,6 +7,7 @@ use tunal_core::playlist::Ranks; use super::Item; use crate::ViewMode; +use crate::config; use crate::icons::Category; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -39,18 +40,29 @@ pub struct Settings { pub mode: ViewMode, } -impl Default for Settings { - fn default() -> Self { +impl Settings { + /// A new pane's settings: the defaults chosen in the settings dialog. + pub fn from_config(cfg: &config::Settings) -> Self { Self { - key: SortKey::Name, - descending: false, - folders_first: true, - group: GroupBy::None, - show_hidden: false, + key: match cfg.sort { + config::Sort::Name => SortKey::Name, + config::Sort::Size => SortKey::Size, + config::Sort::Type => SortKey::Type, + config::Sort::Modified => SortKey::Modified, + }, + descending: cfg.sort_descending, + folders_first: cfg.folders_first, + group: match cfg.group { + config::Group::None => GroupBy::None, + config::Group::Type => GroupBy::Type, + config::Group::Modified => GroupBy::Modified, + config::Group::Size => GroupBy::Size, + }, + show_hidden: cfg.show_hidden, filter: String::new(), // `TUNAL_VIEW=grid` starts in the grid view (screenshots). - mode: match std::env::var("TUNAL_VIEW").as_deref() { - Ok("grid") => ViewMode::Grid, + mode: match (std::env::var("TUNAL_VIEW").as_deref(), cfg.view) { + (Ok("grid"), _) | (_, config::View::Grid) => ViewMode::Grid, _ => ViewMode::Details, }, } diff --git a/crates/tunal/src/menus.rs b/crates/tunal/src/menus.rs new file mode 100644 index 0000000..8c55458 --- /dev/null +++ b/crates/tunal/src/menus.rs @@ -0,0 +1,175 @@ +//! The context menus, one list of action ids per context, kept in `menus.toml`. A context +//! the file doesn't name uses its default; ids this build doesn't know are skipped when a menu +//! is built, so a file written by a newer build still works. + +use serde::{Deserialize, Serialize}; + +use crate::actions::Action; +use crate::config; + +/// Stands for a separator in a list. +pub const SEPARATOR: &str = "-"; + +/// What the menu was opened on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Context { + File, + Folder, + Multiple, + Empty, + Trash, +} + +impl Context { + pub const ALL: [Context; 5] = [ + Self::File, + Self::Folder, + Self::Multiple, + Self::Empty, + Self::Trash, + ]; + + pub fn label(self) -> &'static str { + match self { + Self::File => "File", + Self::Folder => "Folder", + Self::Multiple => "Several items", + Self::Empty => "Empty area", + Self::Trash => "Trash", + } + } + + /// The menu before the user edits it. + pub fn defaults(self) -> Vec { + let ids: &[&str] = match self { + Self::File => &[ + "open", + "open-with", + "-", + "cut", + "copy", + "paste", + "-", + "copy-path", + "rename", + "-", + "trash", + "delete", + "-", + "properties", + ], + Self::Folder => &[ + "open", + "-", + "cut", + "copy", + "paste", + "-", + "copy-path", + "rename", + "new-folder", + "-", + "trash", + "delete", + "-", + "properties", + ], + Self::Multiple => &[ + "cut", + "copy", + "-", + "copy-path", + "-", + "trash", + "delete", + "-", + "properties", + ], + Self::Empty => &[ + "paste", + "new-folder", + "-", + "copy-path", + "-", + "properties", + "settings", + ], + Self::Trash => &["restore", "copy", "copy-path", "-", "delete", "empty-trash"], + }; + ids.iter().map(|s| s.to_string()).collect() + } +} + +/// `menus.toml`: a context that is missing keeps its default. +#[derive(Debug, Default, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct Menus { + file: Option>, + folder: Option>, + multiple: Option>, + empty: Option>, + trash: Option>, +} + +impl Menus { + pub fn load() -> Self { + config::load("menus") + } + + pub fn save(&self) { + config::store("menus", self); + } + + fn slot(&mut self, ctx: Context) -> &mut Option> { + match ctx { + Context::File => &mut self.file, + Context::Folder => &mut self.folder, + Context::Multiple => &mut self.multiple, + Context::Empty => &mut self.empty, + Context::Trash => &mut self.trash, + } + } + + /// The ids of `ctx`, edited or default. + pub fn ids(&self, ctx: Context) -> Vec { + let edited = match ctx { + Context::File => &self.file, + Context::Folder => &self.folder, + Context::Multiple => &self.multiple, + Context::Empty => &self.empty, + Context::Trash => &self.trash, + }; + edited.clone().unwrap_or_else(|| ctx.defaults()) + } + + /// The menu as shown: known actions only, `None` for a separator, with no separator at + /// either end or twice in a row. + pub fn layout(&self, ctx: Context) -> Vec> { + let mut out: Vec> = Vec::new(); + for id in self.ids(ctx) { + if id == SEPARATOR { + if !out.is_empty() && out.last() != Some(&None) { + out.push(None); + } + } else if let Some(action) = Action::from_id(&id) { + out.push(Some(action)); + } + } + if out.last() == Some(&None) { + out.pop(); + } + out + } + + pub fn set(&mut self, ctx: Context, ids: Vec) { + *self.slot(ctx) = Some(ids); + } + + pub fn reset(&mut self, ctx: Context) { + *self.slot(ctx) = None; + } + + pub fn is_default(&self, ctx: Context) -> bool { + self.ids(ctx) == ctx.defaults() + } +} diff --git a/crates/tunal/src/settings.rs b/crates/tunal/src/settings.rs new file mode 100644 index 0000000..d066608 --- /dev/null +++ b/crates/tunal/src/settings.rs @@ -0,0 +1,226 @@ +//! The settings dialog: the options in `settings.toml` and the context menu editor +//! (`menus.toml`). Every change is applied and stored at once. + +use std::cell::{Cell, RefCell}; +use std::rc::{Rc, Weak}; + +use slint::{ComponentHandle, ModelRc, VecModel}; + +use crate::actions::{Action, Actions}; +use crate::config::{self, Group, Motion, Sort, View}; +use crate::menus::{Context, SEPARATOR}; +use crate::shell::Shell; +use crate::{EditRow, MainWindow, SettingsData, theme_bridge}; + +pub struct SettingsUi { + me: Weak, + ui: slint::Weak, + shell: Weak, + actions: Rc, + /// The context the menu editor shows. + context: Cell, + /// The ids of that menu: what the editor edits. + ids: RefCell>, +} + +impl SettingsUi { + pub fn attach(ui: &MainWindow, shell: &Rc, actions: &Rc) -> Rc { + let settings = Rc::new_cyclic(|me| Self { + me: me.clone(), + ui: ui.as_weak(), + shell: Rc::downgrade(shell), + actions: actions.clone(), + context: Cell::new(0), + ids: RefCell::new(Vec::new()), + }); + theme_bridge::set_motion(ui, config::load::("settings").motion); + settings.bind(ui); + settings + } + + fn data(cfg: &config::Settings) -> SettingsData { + SettingsData { + restore_session: cfg.restore_session, + show_hidden: cfg.show_hidden, + folders_first: cfg.folders_first, + view: cfg.view as i32, + sort: cfg.sort as i32, + sort_descending: cfg.sort_descending, + group: cfg.group as i32, + motion: cfg.motion as i32, + } + } + + fn opening(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + ui.set_settings(Self::data(&config::load("settings"))); + ui.set_menu_contexts(ModelRc::new(VecModel::from( + Context::ALL + .iter() + .map(|c| c.label().into()) + .collect::>(), + ))); + self.show_menu(self.context.get().min(Context::ALL.len() - 1)); + } + + fn changed(&self, data: SettingsData) { + let mut cfg: config::Settings = config::load("settings"); + cfg.restore_session = data.restore_session; + cfg.show_hidden = data.show_hidden; + cfg.folders_first = data.folders_first; + cfg.view = [View::Details, View::Grid][data.view.clamp(0, 1) as usize]; + cfg.sort = + [Sort::Name, Sort::Size, Sort::Type, Sort::Modified][data.sort.clamp(0, 3) as usize]; + cfg.sort_descending = data.sort_descending; + cfg.group = [Group::None, Group::Type, Group::Modified, Group::Size] + [data.group.clamp(0, 3) as usize]; + cfg.motion = + [Motion::System, Motion::Reduce, Motion::Full][data.motion.clamp(0, 2) as usize]; + // The window's own sidebar state is saved with the session, not by this dialog. + if let Some(ui) = self.ui.upgrade() { + cfg.show_sidebar = ui.get_show_sidebar(); + theme_bridge::set_motion(&ui, cfg.motion); + } + config::store("settings", &cfg); + if let Some(shell) = self.shell.upgrade() { + for pane in shell.panes() { + pane.model.apply_config(&cfg); + } + } + } + + // ---- menu editor -------------------------------------------------------------------- + + fn context(&self) -> Context { + Context::ALL[self.context.get().min(Context::ALL.len() - 1)] + } + + fn row(id: &str) -> Option { + if id == SEPARATOR { + return Some(EditRow { + text: Default::default(), + icon: Default::default(), + shortcut: Default::default(), + separator: true, + }); + } + let action = Action::from_id(id)?; + Some(EditRow { + text: action.label().into(), + icon: action.glyph().into(), + shortcut: action.shortcut_text().into(), + separator: false, + }) + } + + /// Shows the menu of context `index`. + fn show_menu(&self, index: usize) { + self.context.set(index); + let ctx = self.context(); + // Ids this build doesn't know are not shown, so an edit drops them. + let ids: Vec = self + .actions + .menu_ids(ctx) + .into_iter() + .filter(|id| id == SEPARATOR || Action::from_id(id).is_some()) + .collect(); + *self.ids.borrow_mut() = ids; + self.refresh(); + } + + fn refresh(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let ids = self.ids.borrow(); + let rows: Vec = ids.iter().filter_map(|id| Self::row(id)).collect(); + let available: Vec = Action::ALL + .iter() + .filter(|a| !ids.iter().any(|id| id == a.id())) + .filter_map(|a| Self::row(a.id())) + .collect(); + ui.set_menu_context(self.context.get() as i32); + ui.set_menu_rows(ModelRc::new(VecModel::from(rows))); + ui.set_menu_available(ModelRc::new(VecModel::from(available))); + ui.set_menu_can_reset(!self.actions.menu_is_default(self.context())); + } + + /// Stores the edited ids and shows them. + fn commit(&self) { + self.actions + .set_menu(self.context(), Some(self.ids.borrow().clone())); + self.refresh(); + } + + fn moved(&self, from: usize, to: usize) { + { + let mut ids = self.ids.borrow_mut(); + if from >= ids.len() || to >= ids.len() { + return; + } + let id = ids.remove(from); + ids.insert(to, id); + } + self.commit(); + } + + fn removed(&self, index: usize) { + { + let mut ids = self.ids.borrow_mut(); + if index >= ids.len() { + return; + } + ids.remove(index); + } + self.commit(); + } + + /// Adds the `index`th of the actions not in the menu. + fn added(&self, index: usize) { + let id = { + let ids = self.ids.borrow(); + Action::ALL + .iter() + .filter(|a| !ids.iter().any(|id| id == a.id())) + .nth(index) + .map(|a| a.id().to_string()) + }; + if let Some(id) = id { + self.ids.borrow_mut().push(id); + self.commit(); + } + } + + fn reset(&self) { + self.actions.set_menu(self.context(), None); + self.show_menu(self.context.get()); + } + + fn bind(&self, ui: &MainWindow) { + 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 + } + }); + }}; + } + on!(on_settings_opening, |s| s.opening()); + on!(on_settings_changed, |s, data| s.changed(data)); + on!(on_menu_context_selected, |s, i| s + .show_menu(i.max(0) as usize)); + on!(on_menu_moved, |s, from, to| s + .moved(from.max(0) as usize, to.max(0) as usize)); + on!(on_menu_removed, |s, i| s.removed(i.max(0) as usize)); + on!(on_menu_added, |s, i| s.added(i.max(0) as usize)); + on!(on_menu_separator_added, |s| { + s.ids.borrow_mut().push(SEPARATOR.to_string()); + s.commit(); + }); + on!(on_menu_reset, |s| s.reset()); + } +} diff --git a/crates/tunal/src/theme_bridge.rs b/crates/tunal/src/theme_bridge.rs index d10fc1d..77ee85b 100644 --- a/crates/tunal/src/theme_bridge.rs +++ b/crates/tunal/src/theme_bridge.rs @@ -1,8 +1,11 @@ //! Feeds the desktop appearance (and agent overrides) into the Slint `Theme` and `MotionPrefs`. +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; + use slint::{Color, ComponentHandle}; use tunal_theme::{Appearance, ColorScheme, Palette, Palettes}; +use crate::config; use crate::{Gallery, MainWindow, MotionPrefs, Theme}; /// Overrides for agents and screenshots: `TUNAL_SEED=#rrggbb`, `TUNAL_SCHEME=light|dark`, @@ -42,6 +45,25 @@ impl Overrides { } } +/// The Motion choice of the settings (0 follow the system, 1 reduce, 2 never reduce) and what +/// the desktop last said, so a change of either gives the right flag at once. +static MOTION: AtomicU8 = AtomicU8::new(0); +static SYSTEM_REDUCED: AtomicBool = AtomicBool::new(false); + +/// Applies the Motion setting now. +pub fn set_motion(ui: &impl Themed, motion: config::Motion) { + MOTION.store(motion as u8, Ordering::Relaxed); + ui.motion_prefs().set_reduced(reduced(false)); +} + +fn reduced(forced: bool) -> bool { + match MOTION.load(Ordering::Relaxed) { + 1 => true, + 2 => forced, + _ => forced || SYSTEM_REDUCED.load(Ordering::Relaxed), + } +} + /// A window with the `Theme` and `MotionPrefs` globals. pub trait Themed: ComponentHandle + 'static { fn theme(&self) -> Theme<'_>; @@ -84,8 +106,9 @@ pub fn apply(ui: &impl Themed, appearance: &Appearance, overrides: Overrides) { let theme = ui.theme(); theme.set_dark(scheme == ColorScheme::Dark); set_colors(&theme, &palette); - let reduced = overrides.reduced_motion || appearance.animations == Some(false); - ui.motion_prefs().set_reduced(reduced); + SYSTEM_REDUCED.store(appearance.animations == Some(false), Ordering::Relaxed); + ui.motion_prefs() + .set_reduced(reduced(overrides.reduced_motion)); } macro_rules! colors { diff --git a/crates/tunal/ui/components/icon.slint b/crates/tunal/ui/components/icon.slint index 3ba56a9..26663ff 100644 --- a/crates/tunal/ui/components/icon.slint +++ b/crates/tunal/ui/components/icon.slint @@ -52,5 +52,7 @@ export global Icons { out property expand-more: "\u{e5cf}"; out property side-navigation: "\u{e9e2}"; out property more-vert: "\u{e5d4}"; + out property drag-handle: "\u{e945}"; + out property restore: "\u{e8b3}"; out property create-new-folder: "\u{e2cc}"; } diff --git a/crates/tunal/ui/dialogs/menu-editor.slint b/crates/tunal/ui/dialogs/menu-editor.slint new file mode 100644 index 0000000..6d2e330 --- /dev/null +++ b/crates/tunal/ui/dialogs/menu-editor.slint @@ -0,0 +1,401 @@ +import { ScrollView } from "std-widgets.slint"; +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 { Chip, ChipKind } from "../components/chip.slint"; +import { StateLayer } from "../components/state-layer.slint"; + +// One action (or separator) of a menu being edited. +export struct EditRow { + text: string, + // Glyph from `Icons`; empty for none. + icon: string, + shortcut: string, + separator: bool, +} + +// Heading over a column of rows. +component ColumnTitle inherits Text { + color: Theme.on-surface-variant; + font-size: Theme.label-medium.size; + font-weight: Theme.label-medium.weight; + height: 24px; + vertical-alignment: center; +} + +// Edits the menu of one context: the rows of the menu (drag by the handle or use the arrow +// buttons to reorder, the cross removes) and the actions still available (click to add). +// The owner applies each change and hands back the new rows. +export component MenuEditor inherits VerticalLayout { + in property <[string]> contexts; + in property context; + in property <[EditRow]> rows; + in property <[EditRow]> available; + in property can-reset; + callback context-selected(int); + callback moved(from: int, to: int); + callback removed(int); + callback added(int); + callback separator-added(); + callback reset(); + + property row-h: 36px; + property handle-w: 32px; + // The row being moved and the slot it is heading for. `dragging`: the pointer holds it; + // otherwise it settles into `target` and the change is applied when it has arrived. + property drag: -1; + property target; + property dragging; + property settling; + // Applying a change swaps what the rows show; their positions must not animate then. + property snap; + property grab; + property pointer-y; + + spacing: Theme.space-3; + + // Where the row at `i` sits while another one is moving. + pure function slot(i: int, drag: int, target: int) -> int { + if drag < 0 || i == drag { + return i; + } + if drag < target && i > drag && i <= target { + return i - 1; + } + if drag > target && i < drag && i >= target { + return i + 1; + } + i + } + + function settle() { + if root.drag < 0 { + return; + } + if root.target == root.drag { + root.drag = -1; + } else if Motion.time(Motion.short4) == Motion.none { + root.finish(); + } else { + root.settling = true; + } + } + + function finish() { + root.snap = true; + root.moved(root.drag, root.target); + root.drag = -1; + root.settling = false; + } + + function nudge(i: int, by: int) { + if root.drag >= 0 { + return; + } + root.drag = i; + root.target = i + by; + root.dragging = false; + root.settle(); + } + + HorizontalLayout { + spacing: Theme.space-2; + alignment: start; + + for name[i] in root.contexts: Chip { + property sel: i == root.context; + + text: name; + checked: self.sel; + changed sel => { + self.checked = self.sel; + } + clicked => { + root.context-selected(i); + self.checked = true; + } + } + } + + HorizontalLayout { + spacing: Theme.space-4; + + VerticalLayout { + horizontal-stretch: 3; + spacing: Theme.space-1; + + ColumnTitle { + text: "In the menu"; + } + + ScrollView { + height: 280px; + content-height: max(self.height, root.rows.length * root.row-h); + + for row[i] in root.rows: Rectangle { + property held: i == root.drag; + + x: 0; + y: self.held && root.dragging + ? clamp(root.pointer-y - root.grab, 0, (root.rows.length - 1) * root.row-h) + : root.slot(i, root.drag, root.target) * root.row-h; + width: parent.width; + height: root.row-h; + border-radius: Theme.corner-sm; + background: self.held ? Theme.surface-container-highest : transparent; + drop-shadow-blur: self.held ? Theme.float-shadow-blur / 3 : 0; + drop-shadow-color: Theme.shadow.with-alpha(Theme.float-shadow-opacity); + animate y { + duration: root.snap || (self.held && root.dragging) ? Motion.none : Motion.time(Motion.short4); + easing: Motion.emphasized; + } + animate background, drop-shadow-blur { + duration: Motion.time(Motion.short3); + easing: Motion.standard; + } + + HorizontalLayout { + padding-left: root.handle-w; + padding-right: Theme.space-1; + spacing: Theme.space-2; + + if row.separator: VerticalLayout { + alignment: center; + horizontal-stretch: 1; + padding-left: Theme.space-2; + spacing: 0; + + Rectangle { + height: Theme.hairline; + background: Theme.outline; + } + } + + if !row.separator: VerticalLayout { + alignment: center; + + Icon { + glyph: row.icon; + size: 20px; + } + } + + if !row.separator: Text { + horizontal-stretch: 1; + text: row.text; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + overflow: elide; + } + + VerticalLayout { + alignment: center; + + IconButton { + size: 32px; + icon-size: 20px; + icon: Icons.arrow-upward; + tooltip: "Move up"; + enabled: i > 0; + clicked => { + root.nudge(i, -1); + } + } + } + + VerticalLayout { + alignment: center; + + IconButton { + size: 32px; + icon-size: 20px; + icon: Icons.arrow-downward; + tooltip: "Move down"; + enabled: i < root.rows.length - 1; + clicked => { + root.nudge(i, 1); + } + } + } + + VerticalLayout { + alignment: center; + + IconButton { + size: 32px; + icon-size: 20px; + icon: Icons.close; + tooltip: "Remove from the menu"; + clicked => { + if root.drag < 0 { + root.snap = true; + root.removed(i); + } + } + } + } + } + + Icon { + x: (root.handle-w - self.width) / 2 + Theme.space-1; + y: (root.row-h - self.height) / 2; + glyph: Icons.drag-handle; + size: 20px; + opacity: parent.held ? 1 : 0.6; + } + } + + // The grip column, outside the moving rows so the pointer stays in one frame. + handle := TouchArea { + x: 0; + y: 0; + width: root.handle-w; + height: root.rows.length * root.row-h; + mouse-cursor: root.dragging ? MouseCursor.grabbing : MouseCursor.grab; + + pointer-event(event) => { + if event.button == PointerEventButton.left && event.kind == PointerEventKind.down && root.drag < 0 { + root.drag = clamp(floor(self.mouse-y / root.row-h), 0, root.rows.length - 1); + root.target = root.drag; + root.grab = self.mouse-y - root.drag * root.row-h; + root.pointer-y = self.mouse-y; + root.dragging = true; + } else if event.kind == PointerEventKind.up || event.kind == PointerEventKind.cancel { + if root.dragging { + root.dragging = false; + root.settle(); + } + } + } + + moved => { + if root.dragging { + root.pointer-y = self.mouse-y; + root.target = clamp(round((self.mouse-y - root.grab) / root.row-h), 0, root.rows.length - 1); + } + } + } + + // Plays the settle, then applies the change; a pause after it keeps the rows + // from animating into their new content. + Timer { + running: root.settling; + interval: Motion.time(Motion.short4); + triggered => { + root.finish(); + } + } + + Timer { + running: root.snap; + interval: Motion.snap-pause; + triggered => { + root.snap = false; + } + } + } + } + + VerticalLayout { + horizontal-stretch: 2; + spacing: Theme.space-1; + + ColumnTitle { + text: "Add to the menu"; + } + + ScrollView { + height: 280px; + content-height: max(self.height, root.available.length * root.row-h); + + for row[i] in root.available: StateLayer { + y: i * root.row-h; + width: parent.width; + height: root.row-h; + border-radius: Theme.corner-sm; + squeeze: Motion.squeeze-large; + ring-offset: -Theme.focus-ring-width; + tooltip: "Add to the menu"; + clicked => { + root.snap = true; + root.added(i); + } + + HorizontalLayout { + padding-left: Theme.space-2; + padding-right: Theme.space-2; + spacing: Theme.space-2; + + VerticalLayout { + alignment: center; + + Icon { + glyph: row.icon; + size: 20px; + } + } + + Text { + horizontal-stretch: 1; + text: row.text; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + overflow: elide; + } + + VerticalLayout { + alignment: center; + + Icon { + glyph: Icons.add; + size: 20px; + } + } + } + } + + if root.available.length == 0: Text { + text: "Every action is in the menu."; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + y: Theme.space-2; + width: parent.width; + wrap: word-wrap; + } + } + } + } + + HorizontalLayout { + spacing: Theme.space-2; + alignment: start; + + Chip { + kind: ChipKind.assist; + icon: Icons.add; + text: "Separator"; + tooltip: "Add a separator at the end"; + clicked => { + root.snap = true; + root.separator-added(); + } + } + + Chip { + kind: ChipKind.assist; + icon: Icons.restore; + text: "Reset to defaults"; + enabled: root.can-reset; + clicked => { + root.snap = true; + root.reset(); + } + } + } +} diff --git a/crates/tunal/ui/dialogs/settings.slint b/crates/tunal/ui/dialogs/settings.slint new file mode 100644 index 0000000..e351a30 --- /dev/null +++ b/crates/tunal/ui/dialogs/settings.slint @@ -0,0 +1,329 @@ +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Dialog } from "../components/dialog.slint"; +import { ButtonKind } from "../components/button.slint"; +import { ListRow } from "../components/list-row.slint"; +import { Switch } from "../components/switch.slint"; +import { Chip } from "../components/chip.slint"; +import { Icons } from "../components/icon.slint"; +import { MenuEditor, EditRow } from "menu-editor.slint"; + +export { EditRow } + +// What the settings pages show and change; Rust applies and stores every change. +export struct SettingsData { + restore-session: bool, + show-hidden: bool, + folders-first: bool, + // Index into the page's choices. + view: int, + sort: int, + sort-descending: bool, + group: int, + motion: int, +} + +// One choice out of a few, as a row of chips. +component Choices inherits HorizontalLayout { + in property <[string]> names; + in property current; + callback picked(int); + + spacing: Theme.space-2; + alignment: start; + + for name[i] in root.names: Chip { + property sel: i == root.current; + + text: name; + checked: self.sel; + changed sel => { + self.checked = self.sel; + } + clicked => { + root.picked(i); + self.checked = true; + } + } +} + +// A setting: its name and a line about it, the control on the right. +component Setting inherits HorizontalLayout { + in property title; + in property hint; + + spacing: Theme.space-4; + height: 52px; + + VerticalLayout { + alignment: center; + horizontal-stretch: 1; + + Text { + text: root.title; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + overflow: elide; + } + + if root.hint != "": Text { + text: root.hint; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + overflow: elide; + } + } + + VerticalLayout { + alignment: center; + + @children + } +} + +// A choice with its name above the chips. +component ChoiceSetting inherits VerticalLayout { + in property title; + in property <[string]> names; + in property current; + callback picked(int); + + spacing: Theme.space-2; + padding-top: Theme.space-2; + padding-bottom: Theme.space-2; + + Text { + text: root.title; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + } + + Choices { + names: root.names; + current: root.current; + picked(i) => { + root.picked(i); + } + } +} + +// The settings, one page at a time; the pages are listed on the left. +export component SettingsDialog inherits Dialog { + in-out property data; + in-out property page; + // The context menu editor (page 4). + in property <[string]> menu-contexts; + in property menu-context; + in property <[EditRow]> menu-rows; + in property <[EditRow]> menu-available; + in property menu-can-reset; + callback changed(SettingsData); + callback menu-context-selected(int); + callback menu-moved(from: int, to: int); + callback menu-removed(int); + callback menu-added(int); + callback menu-separator-added(); + callback menu-reset(); + callback closed(); + + property <[string]> pages: ["General", "View", "Previews", "Motion", "Context menus"]; + property <[string]> glyphs: ["\u{e8b8}", "\u{e8f4}", "\u{e3f4}", "\u{e037}", "\u{e5d4}"]; + + title: "Settings"; + dialog-width: 780px; + actions: [{ text: "Done", kind: ButtonKind.filled }]; + default-action: 0; + cancel-action: 0; + action(i) => { + self.close(); + root.closed(); + } + + HorizontalLayout { + spacing: Theme.space-4; + height: 400px; + + VerticalLayout { + width: 168px; + spacing: Theme.space-1; + alignment: start; + + for name[i] in root.pages: ListRow { + title: name; + icon: root.glyphs[i]; + selected: i == root.page; + clicked => { + root.page = i; + } + } + } + + Rectangle { + horizontal-stretch: 1; + + if root.page == 0: VerticalLayout { + alignment: start; + + Setting { + title: "Show hidden files"; + hint: "Files whose names start with a dot. Ctrl+H in a folder."; + Switch { + checked: root.data.show-hidden; + changed checked => { + root.data.show-hidden = self.checked; + root.changed(root.data); + } + } + } + + Setting { + title: "Folders first"; + hint: "List folders before files when sorting."; + Switch { + checked: root.data.folders-first; + changed checked => { + root.data.folders-first = self.checked; + root.changed(root.data); + } + } + } + + Setting { + title: "Restore tabs"; + hint: "Open the tabs of the last session at start."; + Switch { + checked: root.data.restore-session; + changed checked => { + root.data.restore-session = self.checked; + root.changed(root.data); + } + } + } + } + + if root.page == 1: VerticalLayout { + alignment: start; + + ChoiceSetting { + title: "Default view"; + names: ["Details", "Icons"]; + current: root.data.view; + picked(i) => { + root.data.view = i; + root.changed(root.data); + } + } + + ChoiceSetting { + title: "Sort by"; + names: ["Name", "Size", "Type", "Modified"]; + current: root.data.sort; + picked(i) => { + root.data.sort = i; + root.changed(root.data); + } + } + + Setting { + title: "Largest or newest first"; + hint: "Reverse the default sort order."; + Switch { + checked: root.data.sort-descending; + changed checked => { + root.data.sort-descending = self.checked; + root.changed(root.data); + } + } + } + + ChoiceSetting { + title: "Group by"; + names: ["None", "Type", "Modified", "Size"]; + current: root.data.group; + picked(i) => { + root.data.group = i; + root.changed(root.data); + } + } + + Text { + text: "These are what a new tab starts with. Each pane can change its own."; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + wrap: word-wrap; + } + } + + if root.page == 2: VerticalLayout { + alignment: start; + + Text { + text: "Previews"; + color: Theme.on-surface; + font-size: Theme.title-medium.size; + font-weight: Theme.title-medium.weight; + } + + Text { + text: "Thumbnails and the preview panel will be set up here."; + color: Theme.on-surface-variant; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + wrap: word-wrap; + } + } + + if root.page == 3: VerticalLayout { + alignment: start; + + ChoiceSetting { + title: "Animations"; + names: ["Follow the system", "Always reduce", "Never reduce"]; + current: root.data.motion; + picked(i) => { + root.data.motion = i; + root.changed(root.data); + } + } + + Text { + text: "Reduced motion makes menus, dialogs and lists change at once."; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + wrap: word-wrap; + } + } + + if root.page == 4: MenuEditor { + contexts: root.menu-contexts; + context: root.menu-context; + rows: root.menu-rows; + available: root.menu-available; + can-reset: root.menu-can-reset; + context-selected(i) => { + root.menu-context-selected(i); + } + moved(from, to) => { + root.menu-moved(from, to); + } + removed(i) => { + root.menu-removed(i); + } + added(i) => { + root.menu-added(i); + } + separator-added => { + root.menu-separator-added(); + } + reset => { + root.menu-reset(); + } + } + } + } +} diff --git a/crates/tunal/ui/motion.slint b/crates/tunal/ui/motion.slint index 0280fd4..c1d3e43 100644 --- a/crates/tunal/ui/motion.slint +++ b/crates/tunal/ui/motion.slint @@ -13,6 +13,11 @@ export global MotionPrefs { export global Motion { out property reduced: MotionPrefs.reduced; + // No time at all: a change that must not animate (rows swapping content). + out property none: 0ms; + // How long such a change is held before animation comes back. + out property snap-pause: 60ms; + out property short1: 50ms; out property short2: 100ms; out property short3: 150ms; diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 6f7eedc..492bdaa 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -115,5 +115,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: no live window (pointer right click, Esc in the field, real typing, toast cancel, drag); Rename choice in the conflict dialog (only Skip/Keep both/Replace); the error dialog and failure list were not shown (no failing job triggered); system clipboard copy of files for other apps and drag and drop are later plans; a watch event while a name is edited rebuilds the field (typed text is lost). - Later: accept on blur needs a way to tell focus loss from a row rebuild (rows rebuild on every pane change); Undo toast; a numbered-rename field in the conflict dialog; reveal row after paste. +## S013 — Settings dialog and editable context menus +- Done: `settings.rs` `SettingsUi` (dialog `dialogs/settings.slint`, pages General, View, Previews placeholder, Motion, Context menus; every change stored in `settings.toml` and applied at once: hidden/folders first to open panes, view/sort/group are defaults for new panes, Motion through `theme_bridge::set_motion`). `menus.rs` `Menus` (`menus.toml`, one id list per `Context::{File, Folder, Multiple, Empty, Trash}`, `-` = separator, missing context = default, unknown ids skipped). `dialogs/menu-editor.slint`: add (click), remove, reorder by grip drag or arrow buttons (animated slots, applied after settle), separator, reset. Context menus and the toolbar ⋮ menu are built from the model (`Actions::menu_items`; right click on empty area = Empty, ⋮ = by selection). Action `settings` (Ctrl+,) is in the registry, default in the Empty menu. +- Add an action: new `Action` variant in `actions.rs` (+ `ALL`, id/label/glyph/shortcut/enabled/run). It shows in the editor's "Add" list at once. To put it in a default menu add its id to `Context::defaults` in `menus.rs` (users with an edited menu add it themselves; a menu never edited gets it). +- Verified: build, fmt --check, literal grep empty; screenshots of View and Context menus pages; with a temporary hook (removed) moved `delete` to the top of File, `menus.toml` written, restart showed the new order in the context menu. Clippy: only S012's unused `smoke` methods fail. +- Not done: sidebar place menu still its own fixed list (Open in new tab, bookmark edit). No live drag run (pointer drag, motion); clippy not clean until S012 lands. `TUNAL_SETTINGS=` opens the dialog in a screenshot. Shared files `actions.rs`, `app.slint`, `main.rs`, `shell/mod.rs` hold S012 hunks too: left uncommitted here. +- Later: autoscroll while dragging in a long menu; Previews page (S018); sidebar menu from the model. + ## Later -