use std::cmp::Ordering; use std::collections::{BTreeSet, HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::OnceLock; use serde::{Deserialize, Serialize}; use iced::time::{Duration, Instant}; use iced::widget::text::{IntoFragment, Wrapping}; use iced::widget::{Id, operation}; use iced::widget::{ button, checkbox, column, container, mouse_area, pick_list, responsive, row, rule, scrollable, space, stack, text, text_input, toggler, tooltip, }; use iced::{ Alignment, Animation, Border, Color, Element, Font, Length, Padding, Point, Rectangle, Shadow, Size, Subscription, Task, Vector, font, keyboard, mouse, window, }; mod notifications; #[allow(dead_code)] mod terminal; mod theme; const MENUBAR_HEIGHT: f32 = 40.0; /// Settings heading sizes: tab title, sub-section header, normal text, caption. const SETTINGS_H1_SIZE: f32 = 22.0; const SETTINGS_H2_SIZE: f32 = 18.0; const SETTINGS_H3_SIZE: f32 = 16.0; const SETTINGS_CAPTION_SIZE: f32 = 13.0; /// Default font choice for every typography level. const MONO_FONT_FAMILY: &str = "JetBrains Mono"; const TERMINAL_FONT_SIZE: f32 = 14.0; const SSH_FONT_SIZE: f32 = 14.0; /// Pre-filled font sizes offered by the typography drop-down. const FONT_SIZE_STEPS: [f32; 14] = [ 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 28.0, 32.0, 36.0, ]; /// Tab width bounds and gap, used to fit as many tabs as the strip allows. const TAB_MAX_WIDTH: f32 = 230.0; const TAB_MIN_WIDTH: f32 = 100.0; const TAB_SPACING: f32 = 2.0; /// Space kept clear for the hamburger/close button at the end of the menubar. const HAMBURGER_WIDTH: f32 = 32.0; /// Fixed width of the two tab-strip scroll buttons. const SCROLL_BUTTON_WIDTH: f32 = 32.0; /// Left padding of the menubar, i.e. where the tab strip starts. const TAB_STRIP_LEFT: f32 = 5.0; /// Right padding of the menubar. const MENUBAR_RIGHT_PADDING: f32 = 8.0; /// How close to a tab-strip edge a drag must be before it auto-scrolls. const DRAG_EDGE: f32 = 40.0; /// Fastest auto-scroll speed while dragging, in pixels per frame. const DRAG_SCROLL_SPEED: f32 = 16.0; /// Size of the floating tab ghost shown while dragging. const DRAG_GHOST_WIDTH: f32 = 190.0; const DRAG_GHOST_HEIGHT: f32 = 30.0; /// Layout of the in-window "move to window" drop panel. const DROP_PANEL_WIDTH: f32 = 280.0; const DROP_PANEL_PADDING: f32 = 6.0; const DROP_HEADER_HEIGHT: f32 = 22.0; const DROP_ROW_HEIGHT: f32 = 30.0; const DROP_ROW_GAP: f32 = 2.0; /// Longest tab title shown before it gets ellipsized. const MAX_TAB_TITLE: usize = 20; /// Fixed height for rows in the hamburger menu. const MENU_ITEM_HEIGHT: f32 = 24.0; /// Fixed height of the hamburger row inside the menu panel. const HAMBURGER_ROW_HEIGHT: f32 = 24.0; /// Panel padding of the hamburger menu. const MENU_PADDING: f32 = 4.0; /// Pixels moved per press of a tab-strip scroll button. const TAB_SCROLL_STEP: f32 = 120.0; /// Identifies the theme-name field so it can be focused when opened. const THEME_NAME_INPUT: Id = Id::new("theme-name"); /// Identifies the new-folder name field so it can be focused when opened. const FOLDER_NAME_INPUT: Id = Id::new("folder-name"); /// Identifies the new-profile name field so it can be focused when opened. const PROFILE_NAME_INPUT: Id = Id::new("profile-name"); /// Folder shown for profiles that have not been put into a group. const DEFAULT_PROFILE_FOLDER: &str = "Ungrouped"; /// Sentinel destination used to move folders outside any parent folder. const ROOT_FOLDER_INDEX: usize = usize::MAX; fn main() -> iced::Result { iced::daemon(boot, update, view) .title(window_title) .theme(|state: &Moorly, _window| state.theme.iced()) .subscription(subscription) .run() } /// Opens the first window and gives it the Start tab when configured. fn boot() -> (Moorly, Task) { let mut state = Moorly::default(); let settings = window::Settings { exit_on_close_request: false, ..window::Settings::default() }; let size = settings.size; let (id, task) = window::open(settings); state .windows .insert(id, WindowState::new(state.show_start_tab, size)); state.window_order.push(id); state.main_window = Some(id); state.focused_window = Some(id); let fonts = Task::batch([ iced::font::load(include_bytes!("../assets/fonts/Inter/Inter-Variable.ttf").as_slice()) .map(|_| Message::Ignore), iced::font::load( include_bytes!("../assets/fonts/JetBrainsMono/JetBrainsMono-Variable.ttf").as_slice(), ) .map(|_| Message::Ignore), iced::font::load( include_bytes!("../assets/fonts/JetBrainsMono/JetBrainsMonoNL-Variable.ttf").as_slice(), ) .map(|_| Message::Ignore), ]); (state, Task::batch([task.map(|_| Message::Ignore), fonts])) } fn window_title(state: &Moorly, window: window::Id) -> String { if state.main_window == Some(window) { return "Moorly".to_owned(); } match state .windows .get(&window) .and_then(|state| state.active_tab) { Some(tab) => format!("{} - Moorly", tab.title()), None => "Moorly".to_owned(), } } /// Raw mouse events are needed for tab dragging and cross-window drops. fn pointer_event( event: iced::Event, _status: iced::event::Status, window: window::Id, ) -> Option { match event { iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { Some(Message::PointerPressed(window)) } iced::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => { Some(Message::PointerReleased(window)) } iced::Event::Mouse(mouse::Event::CursorMoved { position }) => { Some(Message::PointerMoved(window, position)) } iced::Event::Mouse(mouse::Event::CursorLeft) => Some(Message::PointerLeft(window)), _ => None, } } /// Key presses are captured by focused text inputs, so palette keys are /// listened for globally instead of through `keyboard::listen`. fn key_press_event( event: iced::Event, _status: iced::event::Status, window: window::Id, ) -> Option<(keyboard::Key, keyboard::Modifiers, window::Id)> { match event { iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, repeat: false, .. }) => Some((key, modifiers, window)), _ => None, } } fn palette_event( event: iced::Event, _status: iced::event::Status, window: window::Id, ) -> Option { let iced::Event::Keyboard(keyboard::Event::KeyPressed { key, repeat: false, .. }) = event else { return None; }; match key { keyboard::Key::Named(keyboard::key::Named::Escape) => { Some(Message::CloseCommandPalette(window)) } keyboard::Key::Named(keyboard::key::Named::ArrowUp) => { Some(Message::CommandPaletteUp(window)) } keyboard::Key::Named(keyboard::key::Named::ArrowDown) => { Some(Message::CommandPaletteDown(window)) } keyboard::Key::Named(keyboard::key::Named::Enter) => { Some(Message::RunSelectedCommand(window)) } _ => None, } } fn subscription(state: &Moorly) -> Subscription { let active_window = state.focused_window.or(state.main_window); let keyboard = keyboard::listen() .with(( state.saved_shortcuts.settings.clone(), state.saved_shortcuts.quit.clone(), state.saved_shortcuts.quick_terminal.clone(), state.saved_shortcuts.quick_ssh.clone(), state.shortcut_capture.is_some(), active_window, )) .filter_map( |( ( settings_shortcut, quit_shortcut, quick_terminal_shortcut, quick_ssh_shortcut, capturing, window, ), event, )| { let keyboard::Event::KeyPressed { key, modifiers, repeat: false, .. } = event else { return None; }; if capturing { return Some(Message::CaptureKey { key, modifiers }); } if quit_shortcut .as_ref() .is_some_and(|shortcut| shortcut.matches(&key, modifiers)) { return Some(Message::Quit); } if let Some(shortcut) = &settings_shortcut && shortcut.matches(&key, modifiers) { return window.map(|window| Message::SelectTab(window, Tab::Settings)); } if let Some(shortcut) = &quick_terminal_shortcut && shortcut.matches(&key, modifiers) { return window.map(Message::QuickTerminal); } if let Some(shortcut) = &quick_ssh_shortcut && shortcut.matches(&key, modifiers) { return window.map(Message::QuickSsh); } match key { keyboard::Key::Character(key) if cfg!(debug_assertions) && key.eq_ignore_ascii_case("n") && modifiers.control() && modifiers.shift() => { Some(Message::ShowNotificationDemo) } keyboard::Key::Character(key) if key.eq_ignore_ascii_case("w") && modifiers.control() && modifiers.shift() => { window.map(Message::CloseActiveTab) } _ => None, } }, ); // Keep frames coming until the fade-out has been swapped for the new // section or the tab close icons have finished fading. let now = Instant::now(); let tab_close_animating = state .tab_close_fades .values() .any(|animation| animation.is_animating(now)); let palette_shortcut = iced::event::listen_with(key_press_event) .with(( state.saved_shortcuts.command_palette.clone(), state.shortcut_capture.is_some(), state.command_palette_enabled, )) .filter_map( |((shortcut, capturing, enabled), (key, modifiers, window))| { (enabled && !capturing && shortcut .as_ref() .is_some_and(|shortcut| shortcut.matches(&key, modifiers))) .then_some(Message::ToggleCommandPalette(window)) }, ); let mut subscriptions = vec![ keyboard, palette_shortcut, iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), window::events().map(|(window, event)| Message::WindowEvent(window, event)), iced::event::listen_with(pointer_event), iced::event::listen_with(palette_event), ]; if state.drag.is_some() { subscriptions.push(iced::time::every(Duration::from_millis(16)).map(|_| Message::DragTick)); } if state.fade_animation.is_animating(now) || state.pending_settings_section.is_some() || tab_close_animating { subscriptions.push(window::frames().map(Message::Frame)); } // Timed notifications only need a coarse expiry timer; fades use frames. if state.notifications.has_timed() { subscriptions .push(iced::time::every(Duration::from_millis(250)).map(Message::NotificationTick)); } if state.notifications.is_animating(now) { subscriptions.push(window::frames().map(Message::NotificationTick)); } Subscription::batch(subscriptions) } #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct Shortcut { control: bool, shift: bool, alt: bool, key: String, } impl Shortcut { /// Parses text like `Ctrl+Shift+K` into a shortcut. Unknown modifiers and /// missing keys are rejected. fn parse(input: &str) -> Option { let parts: Vec<&str> = input .split('+') .map(str::trim) .filter(|part| !part.is_empty()) .collect(); let (key, modifiers) = parts.split_last()?; // Only single-character keys and Space are supported for now. let key = if key.eq_ignore_ascii_case("space") { "space".to_owned() } else if key.chars().count() == 1 { key.to_ascii_lowercase() } else { return None; }; let mut shortcut = Self { control: false, shift: false, alt: false, key, }; for modifier in modifiers { match modifier.to_ascii_lowercase().as_str() { "ctrl" | "control" => shortcut.control = true, "shift" => shortcut.shift = true, "alt" => shortcut.alt = true, _ => return None, } } Some(shortcut) } fn matches(&self, key: &keyboard::Key, modifiers: keyboard::Modifiers) -> bool { self.control == modifiers.control() && self.shift == modifiers.shift() && self.alt == modifiers.alt() && key_name(key).is_some_and(|name| name == self.key) } /// Builds a shortcut from a captured key press. Plain keys are rejected so /// a shortcut cannot hijack ordinary typing. fn from_key(key: &keyboard::Key, modifiers: keyboard::Modifiers) -> Option { if !(modifiers.control() || modifiers.alt()) { return None; } Some(Self { control: modifiers.control(), shift: modifiers.shift(), alt: modifiers.alt(), key: key_name(key)?, }) } fn key_label(&self) -> String { if self.key == "space" { return "Space".to_owned(); } let is_letter = self.key.chars().count() == 1 && self.key.chars().next().is_some_and(char::is_alphabetic); if is_letter { self.key.to_ascii_uppercase() } else { self.key.clone() } } } /// Normalized name of a key that shortcuts can bind to. fn key_name(key: &keyboard::Key) -> Option { match key { keyboard::Key::Character(key) => Some(key.as_str().to_ascii_lowercase()), keyboard::Key::Named(keyboard::key::Named::Space) => Some("space".to_owned()), _ => None, } } impl std::fmt::Display for Shortcut { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut parts = Vec::new(); if self.control { parts.push("Ctrl".to_owned()); } if self.shift { parts.push("Shift".to_owned()); } if self.alt { parts.push("Alt".to_owned()); } parts.push(self.key_label()); f.write_str(&parts.join("+")) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ShortcutAction { Settings, Quit, CommandPalette, QuickTerminal, QuickSsh, } impl ShortcutAction { fn label(self) -> &'static str { match self { Self::Settings => "Settings", Self::Quit => "Quit", Self::CommandPalette => "Command palette", Self::QuickTerminal => "Quick terminal", Self::QuickSsh => "Quick SSH", } } } #[derive(Debug, Clone, PartialEq, Eq)] struct Shortcuts { settings: Option, quit: Option, command_palette: Option, quick_terminal: Option, quick_ssh: Option, } impl Default for Shortcuts { fn default() -> Self { Self { settings: Shortcut::parse("Ctrl+,"), quit: Shortcut::parse("Ctrl+Shift+Q"), command_palette: Shortcut::parse("Ctrl+Shift+Space"), quick_terminal: Shortcut::parse("Ctrl+Shift+T"), quick_ssh: Shortcut::parse("Ctrl+Shift+S"), } } } impl Shortcuts { fn get(&self, action: ShortcutAction) -> Option<&Shortcut> { match action { ShortcutAction::Settings => self.settings.as_ref(), ShortcutAction::Quit => self.quit.as_ref(), ShortcutAction::CommandPalette => self.command_palette.as_ref(), ShortcutAction::QuickTerminal => self.quick_terminal.as_ref(), ShortcutAction::QuickSsh => self.quick_ssh.as_ref(), } } fn set(&mut self, action: ShortcutAction, shortcut: Option) { match action { ShortcutAction::Settings => self.settings = shortcut, ShortcutAction::Quit => self.quit = shortcut, ShortcutAction::CommandPalette => self.command_palette = shortcut, ShortcutAction::QuickTerminal => self.quick_terminal = shortcut, ShortcutAction::QuickSsh => self.quick_ssh = shortcut, } } /// Name of another action already bound to `candidate`, if any. `except` /// is the action being rebound, which must not conflict with itself. fn conflict(&self, candidate: &Shortcut, except: ShortcutAction) -> Option<&'static str> { let configurable = [ (ShortcutAction::Settings, &self.settings), (ShortcutAction::Quit, &self.quit), (ShortcutAction::CommandPalette, &self.command_palette), (ShortcutAction::QuickTerminal, &self.quick_terminal), (ShortcutAction::QuickSsh, &self.quick_ssh), ]; if let Some((action, _)) = configurable .iter() .find(|(action, shortcut)| *action != except && shortcut.as_ref() == Some(candidate)) { return Some(action.label()); } // Shortcuts that are fixed for now but still own their keys. let reserved: &[(&str, &str)] = &[("Close Active Tab", "Ctrl+Shift+W")]; reserved.iter().find_map(|(name, text)| { (Shortcut::parse(text).as_ref() == Some(candidate)).then_some(*name) }) } } /// Keys picked so far while rebinding a shortcut. #[derive(Debug, Clone)] struct ShortcutCapture { action: ShortcutAction, candidate: Option, error: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] enum ProfileKind { #[default] Ssh, Terminal, PowerShell, } impl ProfileKind { const ALL: [Self; 3] = [Self::Ssh, Self::Terminal, Self::PowerShell]; fn label(self) -> &'static str { match self { Self::Ssh => "SSH", Self::Terminal => "Terminal", Self::PowerShell => "PowerShell", } } } /// Icon shown next to a profile, in the profile list and command palette. fn profile_glyph(kind: ProfileKind, color: Color) -> Element<'static, Message> { match kind { ProfileKind::Ssh => container(text(">_").size(9).font(Font::MONOSPACE).color(color)) .width(18) .height(16) .align_x(Alignment::Center) .align_y(Alignment::Center) .style(move |_| container::Style { border: Border { color, width: 1.0, radius: 3.0.into(), }, ..container::Style::default() }) .into(), ProfileKind::Terminal => column![ container(space::horizontal()) .width(16) .height(10) .style(move |_| container::Style { border: Border { color, width: 1.5, radius: 2.0.into(), }, ..container::Style::default() }), container(space::horizontal()) .width(6) .height(2) .style(move |_| container::Style { background: Some(color.into()), ..container::Style::default() }), ] .spacing(1) .align_x(Alignment::Center) .into(), ProfileKind::PowerShell => text("👤").size(13).into(), } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] enum SessionEnd { #[default] Auto, Keep, Reconnect, Close, } impl SessionEnd { const ALL: [Self; 4] = [Self::Auto, Self::Keep, Self::Reconnect, Self::Close]; fn label(self) -> &'static str { match self { Self::Auto => "Auto", Self::Keep => "Keep", Self::Reconnect => "Reconnect", Self::Close => "Close", } } } impl std::fmt::Display for SessionEnd { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.label()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] enum AuthMethod { #[default] Password, Key, Agent, Interactive, } impl AuthMethod { const ALL: [Self; 4] = [Self::Password, Self::Key, Self::Agent, Self::Interactive]; fn label(self) -> &'static str { match self { Self::Password => "Password", Self::Key => "Key", Self::Agent => "Agent", Self::Interactive => "Interactive", } } fn glyph(self) -> &'static str { match self { Self::Password => "🔑", Self::Key => "🗝", Self::Agent => "🤖", Self::Interactive => "⌨", } } } #[derive(Debug, Clone)] #[allow(dead_code)] // Stored for when profiles can actually start sessions. struct Profile { name: String, kind: ProfileKind, session_end: SessionEnd, host: String, port: String, username: String, auth: AuthMethod, password: String, start_path: String, private_key: String, glyph_color: Color, /// UUID of the folder this profile belongs to. folder_id: String, /// File this profile was loaded from or saved to. file: Option, } /// Editable state of the add/edit profile dialog. #[derive(Debug, Clone)] struct ProfileDraft { name: String, folder: usize, kind: ProfileKind, session_end: SessionEnd, host: String, port: String, username: String, auth: AuthMethod, password: String, password_visible: bool, start_path: String, private_key: String, glyph_color: Color, color_picker_open: bool, /// Folder and index of the profile being edited. editing: Option<(usize, usize)>, } impl ProfileDraft { fn new(folder: usize) -> Self { Self { name: String::new(), folder, kind: ProfileKind::default(), session_end: SessionEnd::default(), host: String::new(), port: "22".to_owned(), username: String::new(), auth: AuthMethod::default(), password: String::new(), password_visible: false, start_path: default_start_path(), private_key: String::new(), glyph_color: Color::WHITE, color_picker_open: false, editing: None, } } fn from_profile(folder: usize, profile: &Profile, profile_index: usize) -> Self { Self { name: profile.name.clone(), folder, kind: profile.kind, session_end: profile.session_end, host: profile.host.clone(), port: profile.port.clone(), username: profile.username.clone(), auth: profile.auth, password: profile.password.clone(), password_visible: false, start_path: profile.start_path.clone(), private_key: profile.private_key.clone(), glyph_color: profile.glyph_color, color_picker_open: false, editing: Some((folder, profile_index)), } } fn port_valid(&self) -> bool { match self.kind { ProfileKind::Ssh => self.port.parse::().is_ok_and(|port| port <= 65534), _ => true, } } fn valid(&self) -> bool { !self.name.trim().is_empty() && self.port_valid() } } /// An entry in the folder drop-down. #[derive(Debug, Clone, PartialEq, Eq)] struct FolderChoice { index: usize, name: String, } impl std::fmt::Display for FolderChoice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.name) } } fn root_folder_choice() -> FolderChoice { FolderChoice { index: ROOT_FOLDER_INDEX, name: "Root".to_owned(), } } /// Name and destination of a folder being created. #[derive(Debug, Clone)] struct FolderDraft { name: String, parent: FolderChoice, } impl FolderDraft { fn new(parent: FolderChoice) -> Self { Self { name: String::new(), parent, } } } /// Every folder, plus the root, for choosing where a new folder goes. fn folder_dialog_choices(folders: &[ProfileFolder]) -> Vec { std::iter::once(root_folder_choice()) .chain( folders .iter() .enumerate() .map(|(index, folder)| FolderChoice { index, name: folder.path.clone(), }), ) .collect() } /// Which profile field a path picker is filling. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum PickerTarget { StartPath, PrivateKey, } /// In-app path browser state. In folder mode only directories are listed and /// the current directory can be chosen; in file mode files are listed too. #[derive(Debug, Clone)] struct DirPicker { path: PathBuf, entries: Vec, selected: Option, files: bool, target: PickerTarget, error: Option, } impl DirPicker { fn open(path: PathBuf, files: bool, target: PickerTarget) -> Self { let mut picker = Self { path, entries: Vec::new(), selected: None, files, target, error: None, }; picker.reload(); picker } fn reload(&mut self) { match std::fs::read_dir(&self.path) { Ok(read) => { let mut directories = Vec::new(); let mut files = Vec::new(); for entry in read.filter_map(|entry| entry.ok()) { let path = entry.path(); if path.is_dir() { directories.push(path); } else if self.files { files.push(path); } } directories.sort(); files.sort(); self.entries = directories; self.entries.extend(files); self.selected = None; self.error = None; } Err(error) => { self.entries.clear(); self.selected = None; self.error = Some(error.to_string()); } } } fn navigate(&mut self, path: PathBuf) { self.path = path; self.reload(); } fn can_confirm(&self) -> bool { !self.files || self.selected.is_some() } } fn home_dir() -> PathBuf { if cfg!(windows) { std::env::var_os("USERPROFILE") .map(PathBuf::from) .or_else(|| { let drive = std::env::var_os("HOMEDRIVE")?; let path = std::env::var_os("HOMEPATH")?; let mut home = PathBuf::from(drive); home.push(path); Some(home) }) .unwrap_or_else(|| PathBuf::from("C:\\")) } else { std::env::var_os("HOME") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from("/")) } } fn default_start_path() -> String { if cfg!(windows) { std::env::var("HOMEPATH").unwrap_or_else(|_| home_dir().to_string_lossy().into_owned()) } else { "~/".to_owned() } } /// Resolves a typed path, expanding `~` to the home directory. fn resolve_start_path(input: &str) -> PathBuf { let input = input.trim(); if input.is_empty() || input == "~" { return home_dir(); } if let Some(rest) = input .strip_prefix("~/") .or_else(|| input.strip_prefix("~\\")) { return home_dir().join(rest); } PathBuf::from(input) } /// A named group of profiles. Folders form a tree through slash-separated /// paths such as `Work/Production`, which keeps selection index-based. #[derive(Debug, Clone)] struct ProfileFolder { /// Stable identity that profile files reference. id: String, /// Slash-separated path from the root, e.g. `Work/Production`. path: String, name: String, profiles: Vec, expanded: bool, /// True when a profile references this folder but it is not listed in /// `folders.toml`; such folders only exist for this run. untracked: bool, } fn new_folder_id() -> String { uuid::Uuid::new_v4().to_string() } impl ProfileFolder { fn default_folder() -> Self { Self::from_path(DEFAULT_PROFILE_FOLDER.to_owned()) } fn from_path(path: String) -> Self { let name = path .rsplit('/') .next() .filter(|name| !name.is_empty()) .unwrap_or(DEFAULT_PROFILE_FOLDER) .to_owned(); Self { id: new_folder_id(), path, name, profiles: Vec::new(), expanded: true, untracked: false, } } fn depth(&self) -> usize { if self.path == DEFAULT_PROFILE_FOLDER { 0 } else { self.path.split('/').count().saturating_sub(1) } } } /// One folder record in `profiles/folders.toml`. /// /// Folders are linked by UUID instead of by path, so two folders can share a /// name. Root folders have no `parent_id`. #[derive(Debug, Clone, Serialize, Deserialize)] struct FolderRecord { #[serde(default = "new_folder_id")] id: String, #[serde(default)] name: String, #[serde(default, skip_serializing_if = "Option::is_none")] parent_id: Option, /// Full path from files written before folders were linked by UUID. #[serde(default, skip_serializing_if = "String::is_empty")] path: String, } /// Accepts both the old `folders = ["Work"]` format and the UUID records. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] enum FolderEntry { Path(String), Record(FolderRecord), } /// Contents of `profiles/folders.toml`. #[derive(Debug, Serialize, Deserialize)] struct FoldersFile { #[serde(default)] folders: Vec, } #[derive(Debug, Serialize)] struct FoldersOutFile { folders: Vec, } /// One `profiles/.toml` file. #[derive(Debug, Clone, Serialize, Deserialize)] struct ProfileFile { #[serde(default)] name: String, /// UUID of the folder that contains this profile. #[serde(default)] parent_id: String, /// Legacy name-based folder reference, still read but no longer written. #[serde(default, skip_serializing)] folder: String, /// Legacy folder path fallback, still read but no longer written. #[serde(default, skip_serializing)] folder_name: String, #[serde(default)] kind: ProfileKind, #[serde(default)] session_end: SessionEnd, #[serde(default)] host: String, #[serde(default = "default_profile_port")] port: String, #[serde(default)] username: String, #[serde(default)] auth: AuthMethod, #[serde(default)] password: String, #[serde(default)] start_path: String, #[serde(default)] private_key: String, #[serde(default = "default_profile_glyph_color")] glyph_color: String, #[serde(default, skip_serializing_if = "Option::is_none")] trash: Option, } fn default_profile_glyph_color() -> String { color_to_hex(Color::WHITE) } /// Metadata added to a profile file after it is moved to `.trash`. #[derive(Debug, Clone, Default, Serialize, Deserialize)] struct TrashInfo { #[serde(default)] previous_path: String, #[serde(default)] deleted: String, } /// One deleted folder recorded in `.trash/folders.toml`. #[derive(Debug, Clone, Serialize, Deserialize)] struct TrashFolder { name: String, #[serde(default)] previous_path: String, #[serde(default)] deleted: String, } #[derive(Debug, Default, Serialize, Deserialize)] struct TrashFoldersFile { #[serde(default)] folders: Vec, } #[derive(Debug, Clone)] enum TrashEntry { Folder(TrashFolder), Profile { file: PathBuf, profile: ProfileFile }, } impl TrashEntry { fn name(&self) -> &str { match self { Self::Folder(folder) => &folder.name, Self::Profile { profile, .. } => &profile.name, } } fn previous_path(&self) -> &str { match self { Self::Folder(folder) => &folder.previous_path, Self::Profile { profile, .. } => profile .trash .as_ref() .map(|trash| trash.previous_path.as_str()) .unwrap_or_default(), } } fn deleted(&self) -> &str { match self { Self::Folder(folder) => &folder.deleted, Self::Profile { profile, .. } => profile .trash .as_ref() .map(|trash| trash.deleted.as_str()) .unwrap_or_default(), } } fn is_folder(&self) -> bool { matches!(self, Self::Folder(_)) } } impl ProfileFile { fn from_profile(profile: &Profile, folder: &str) -> Self { Self { name: profile.name.clone(), parent_id: profile.folder_id.clone(), folder: profile.folder_id.clone(), folder_name: folder.to_owned(), kind: profile.kind, session_end: profile.session_end, host: profile.host.clone(), port: profile.port.clone(), username: profile.username.clone(), auth: profile.auth, password: profile.password.clone(), start_path: profile.start_path.clone(), private_key: profile.private_key.clone(), glyph_color: color_to_hex(profile.glyph_color), trash: None, } } fn into_profile(self) -> Profile { Profile { name: self.name.trim().to_owned(), kind: self.kind, session_end: self.session_end, host: self.host.trim().to_owned(), port: self.port, username: self.username.trim().to_owned(), auth: self.auth, password: self.password, start_path: self.start_path, private_key: self.private_key, glyph_color: color_from_hex(&self.glyph_color).unwrap_or(Color::WHITE), folder_id: if self.parent_id.trim().is_empty() { self.folder } else { self.parent_id }, file: None, } } } fn default_profile_port() -> String { "22".to_owned() } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum Selection { Folder(usize), Profile { folder: usize, profile: usize }, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum TransferMode { Copy, Move, } impl TransferMode { fn label(self) -> &'static str { match self { Self::Copy => "Copy to", Self::Move => "Move to", } } fn action(self) -> &'static str { match self { Self::Copy => "Copy", Self::Move => "Move", } } } #[derive(Debug, Clone)] struct TransferDialog { mode: TransferMode, destination: usize, } /// Actions offered by the command palette. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Command { Settings, Close, Move, Left, Right, QuickTerminal, QuickSsh, MoveToWindow(window::Id), FocusWindow(window::Id), FocusTab(window::Id, Tab), SelectProfile { folder: usize, profile: usize }, Exit, } impl Command { const ALL: [Self; 8] = [ Self::Settings, Self::Close, Self::Move, Self::Left, Self::Right, Self::QuickTerminal, Self::QuickSsh, Self::Exit, ]; fn label(&self, state: &Moorly) -> String { match self { Self::Settings => "Settings".to_owned(), Self::Close => "Close".to_owned(), Self::Move => "Move".to_owned(), Self::Left => "Left".to_owned(), Self::Right => "Right".to_owned(), Self::QuickTerminal => "Quick Terminal".to_owned(), Self::QuickSsh => "Quick SSH".to_owned(), Self::MoveToWindow(id) | Self::FocusWindow(id) => window_title(state, *id), Self::FocusTab(_, tab) => tab.title(), Self::SelectProfile { folder, profile } => state .profile_folders .get(*folder) .and_then(|folder| folder.profiles.get(*profile)) .map(|profile| profile.name.clone()) .unwrap_or_default(), Self::Exit => "Exit".to_owned(), } } fn description(&self, state: &Moorly) -> String { match self { Self::Settings => "Opens the settings tab".to_owned(), Self::Close => "Closes the active tab".to_owned(), Self::Move => "Moves the active tab to a new window".to_owned(), Self::Left => "Switches to the tab on the left".to_owned(), Self::Right => "Switches to the tab on the right".to_owned(), Self::QuickTerminal => "Opens a quick terminal".to_owned(), Self::QuickSsh => "Opens a quick SSH session".to_owned(), Self::MoveToWindow(id) => { format!("Moves the active tab to {}", window_title(state, *id)) } Self::FocusWindow(_) => "Focuses this window".to_owned(), Self::FocusTab(id, _) => { format!("Focuses this tab in {}", window_title(state, *id)) } Self::SelectProfile { folder, .. } => { let folder = state .profile_folders .get(*folder) .map(|folder| folder.path.as_str()) .unwrap_or_default(); format!("Profile in {folder}") } Self::Exit => "Quits the program".to_owned(), } } /// The shortcut configured for this command, if it has one. fn shortcut(&self, state: &Moorly) -> Option { let action = match self { Self::Settings => ShortcutAction::Settings, Self::Exit => ShortcutAction::Quit, Self::QuickTerminal => ShortcutAction::QuickTerminal, Self::QuickSsh => ShortcutAction::QuickSsh, Self::Close => return Some("Ctrl+Shift+W".to_owned()), _ => return None, }; state.shortcuts.get(action).map(ToString::to_string) } /// Left/Right only exist while there is a tab to switch to. fn available(&self, state: &Moorly, window: window::Id) -> bool { match self { Self::Left => adjacent_tab(state, window, -1).is_some(), Self::Right => adjacent_tab(state, window, 1).is_some(), _ => true, } } fn profile_glyph(&self, state: &Moorly) -> Option<(ProfileKind, Color)> { match self { Self::SelectProfile { folder, profile } => state .profile_folders .get(*folder) .and_then(|folder| folder.profiles.get(*profile)) .map(|profile| (profile.kind, profile.glyph_color)), _ => None, } } fn matching(state: &Moorly, source: window::Id, query: &str) -> Vec { let mut commands: Vec = Self::ALL .into_iter() .filter(|command| command.available(state, source)) .filter(|command| fuzzy_match(&command.label(state), query)) .collect(); for (folder_index, folder) in state.profile_folders.iter().enumerate() { commands.extend( folder .profiles .iter() .enumerate() .filter(|(_, profile)| fuzzy_match(&profile.name, query)) .map(|(profile_index, _)| Self::SelectProfile { folder: folder_index, profile: profile_index, }), ); } for id in &state.window_order { let Some(window_state) = state.windows.get(id) else { continue; }; if *id != source && fuzzy_match(&window_title(state, *id), query) { commands.push(Self::FocusWindow(*id)); } commands.extend( window_state .tabs .iter() .filter(|tab| fuzzy_match(&tab.title(), query)) .map(|tab| Self::FocusTab(*id, *tab)), ); } // While Move matches, offer every other window as a destination. if commands.contains(&Self::Move) { commands.extend( drop_targets(state, source) .into_iter() .map(|(id, _)| Self::MoveToWindow(id)), ); } commands } } /// The tab next to the active one in `window`, or `None` at either end. fn adjacent_tab(state: &Moorly, window: window::Id, delta: isize) -> Option { let window_state = state.windows.get(&window)?; let active = window_state.active_tab?; let index = window_state.tabs.iter().position(|tab| *tab == active)?; window_state .tabs .get(index.checked_add_signed(delta)?) .copied() } /// Case-insensitive subsequence match, so `stg` finds `Settings`. fn fuzzy_match(haystack: &str, needle: &str) -> bool { let needle = needle.trim(); if needle.is_empty() { return true; } let mut haystack = haystack.chars().flat_map(char::to_lowercase); needle .chars() .flat_map(char::to_lowercase) .all(|needle| haystack.any(|haystack| haystack == needle)) } /// Per-window UI state: tabs, menus and tab-strip scrolling. struct WindowState { tabs: Vec, active_tab: Option, menu_open: bool, tabs_submenu_open: bool, quick_menu_open: bool, command_palette_open: bool, command_palette_query: String, command_palette_selected: usize, command_palette_input: Id, tab_offset: f32, scroll_id: Id, size: Size, position: Option, pointer: Option, } impl WindowState { fn new(show_start_tab: bool, size: Size) -> Self { Self { tabs: if show_start_tab { vec![Tab::Start] } else { Vec::new() }, active_tab: show_start_tab.then_some(Tab::Start), menu_open: false, tabs_submenu_open: false, quick_menu_open: false, command_palette_open: false, command_palette_query: String::new(), command_palette_selected: 0, command_palette_input: Id::unique(), tab_offset: 0.0, scroll_id: Id::unique(), size, position: None, pointer: None, } } fn with_tab(tab: Tab, size: Size, position: Option) -> Self { Self { tabs: vec![tab], active_tab: Some(tab), menu_open: false, tabs_submenu_open: false, quick_menu_open: false, command_palette_open: false, command_palette_query: String::new(), command_palette_selected: 0, command_palette_input: Id::unique(), tab_offset: 0.0, scroll_id: Id::unique(), size, position, pointer: None, } } } /// A tab currently being dragged. `pointer` is in the source window's /// coordinates and may leave the window while the button is held. struct TabDrag { window: window::Id, tab: Tab, origin: Point, pointer: Point, moved: bool, detach: bool, } struct Moorly { windows: HashMap, window_order: Vec, main_window: Option, focused_window: Option, drag: Option, theme: theme::Preference, saved_theme: theme::Preference, theme_choice: ThemeChoice, saved_theme_choice: ThemeChoice, custom_themes: Vec, theme_name_dialog: Option, theme_signature: Vec<(String, u64)>, shortcuts: Shortcuts, saved_shortcuts: Shortcuts, shortcut_capture: Option, settings_section: SettingsSection, pending_settings_section: Option, show_start_tab: bool, show_start_tab_draft: bool, fade_settings: bool, fade_settings_draft: bool, hide_tab_close: bool, hide_tab_close_draft: bool, show_new_session_button: bool, show_new_session_button_draft: bool, show_command_palette_description: bool, show_command_palette_description_draft: bool, typography: Typography, typography_draft: Typography, typography_size_inputs: [String; 6], typography_open: bool, typography_font_menu: Option, command_palette_enabled: bool, command_palette_enabled_draft: bool, advanced_open: bool, colors: [Color; 6], saved_colors: [Color; 6], custom_toasts: bool, toast_colors: [Color; 9], builtin_custom_toasts: bool, builtin_toast_colors: [Color; 9], open_color_picker: Option, open_toast_color_picker: Option, fade_animation: Animation, hovered_tab: Option, tab_close_fades: HashMap>, profile_filter: String, profile_folders: Vec, selected: Option, checked: HashSet, trash_open: bool, trash_entries: Vec, trash_checked: HashSet, transfer: Option, confirm_delete: bool, confirm_purge_trash: bool, hovered_folder: Option, add_menu_open: bool, folder_dialog: Option, folder_rename: Option<(usize, String)>, folder_menu: Option<(usize, Point)>, profile_dialog: Option, dir_picker: Option, next_blank_tab: u32, notifications: notifications::NotificationManager, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum Tab { Start, Settings, Blank(u32), } impl Tab { fn title(self) -> String { match self { Self::Start => "Start".to_owned(), Self::Settings => "Settings".to_owned(), Self::Blank(number) => format!("temp {number}"), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ColorOption { Accent, ActiveTabOutline, MainBackground, SidebarBackground, Text, Border, } impl ColorOption { const ALL: [Self; 6] = [ Self::Accent, Self::ActiveTabOutline, Self::MainBackground, Self::SidebarBackground, Self::Text, Self::Border, ]; fn label(self) -> &'static str { match self { Self::Accent => "Accent color", Self::ActiveTabOutline => "Active tab outline", Self::MainBackground => "Main background", Self::SidebarBackground => "Sidebar background", Self::Text => "Text color", Self::Border => "Border color", } } fn index(self) -> usize { match self { Self::Accent => 0, Self::ActiveTabOutline => 1, Self::MainBackground => 2, Self::SidebarBackground => 3, Self::Text => 4, Self::Border => 5, } } } const DEFAULT_COLORS: [Color; 6] = [ theme::SETTINGS_ACTIVE, theme::ACTIVE_TAB, theme::TAB_ACTIVE_BG, theme::TAB_INACTIVE_BG, theme::TAB_TEXT, Color::WHITE, ]; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ToastColorOption { Background, Text, Title, Border, Info, Success, Warning, Error, Dismiss, } impl ToastColorOption { const ALL: [Self; 9] = [ Self::Background, Self::Text, Self::Title, Self::Border, Self::Info, Self::Success, Self::Warning, Self::Error, Self::Dismiss, ]; fn label(self) -> &'static str { match self { Self::Background => "Notification background", Self::Text => "Notification text", Self::Title => "Notification title", Self::Border => "Notification border", Self::Info => "Info accent", Self::Success => "Success accent", Self::Warning => "Warning accent", Self::Error => "Error accent", Self::Dismiss => "Dismiss icon", } } fn index(self) -> usize { match self { Self::Background => 0, Self::Text => 1, Self::Title => 2, Self::Border => 3, Self::Info => 4, Self::Success => 5, Self::Warning => 6, Self::Error => 7, Self::Dismiss => 8, } } } #[derive(Debug, Clone, PartialEq, Eq)] enum ThemeChoice { BuiltIn(theme::Preference), Custom { id: String, name: String }, } impl ThemeChoice { fn label(&self) -> String { match self { Self::BuiltIn(preference) => preference.label().to_owned(), Self::Custom { name, .. } => name.clone(), } } } #[derive(Debug, Clone, PartialEq, Eq)] enum ThemeOption { Theme { choice: ThemeChoice, selected: bool }, Separator, } impl std::fmt::Display for ThemeOption { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Separator => f.write_str("────────────────"), Self::Theme { choice, selected } => { if *selected { write!(f, "✓ {}", choice.label()) } else { f.write_str(&choice.label()) } } } } } #[derive(Debug, Clone)] struct CustomTheme { id: String, name: String, based_on: theme::Preference, colors: [Color; 6], custom_toasts: bool, toast_colors: [Color; 9], typography: Typography, } #[derive(Debug, Serialize, Deserialize)] struct ThemeFile { name: String, based_on: String, #[serde(skip_serializing_if = "Option::is_none")] accent: Option, #[serde(skip_serializing_if = "Option::is_none")] active_tab_outline: Option, #[serde(skip_serializing_if = "Option::is_none")] main_background: Option, #[serde(skip_serializing_if = "Option::is_none")] sidebar_background: Option, #[serde(skip_serializing_if = "Option::is_none")] text: Option, #[serde(skip_serializing_if = "Option::is_none")] border: Option, #[serde(default)] typography: TypographyConfig, #[serde(default)] toast: ToastFile, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] struct ToastFile { #[serde(default)] enabled: bool, #[serde(skip_serializing_if = "Option::is_none")] background: Option, #[serde(skip_serializing_if = "Option::is_none")] text: Option, #[serde(skip_serializing_if = "Option::is_none")] title: Option, #[serde(skip_serializing_if = "Option::is_none")] border: Option, #[serde(skip_serializing_if = "Option::is_none")] info: Option, #[serde(skip_serializing_if = "Option::is_none")] success: Option, #[serde(skip_serializing_if = "Option::is_none")] warning: Option, #[serde(skip_serializing_if = "Option::is_none")] error: Option, #[serde(skip_serializing_if = "Option::is_none")] dismiss: Option, } impl ThemeFile { fn from_colors( name: String, based_on: theme::Preference, colors: &[Color; 6], base: &[Color; 6], custom_toasts: bool, toast_colors: &[Color; 9], typography: &Typography, ) -> Self { let changed = |option: ColorOption| { let index = option.index(); (colors[index] != base[index]).then(|| color_to_hex(colors[index])) }; Self { name, based_on: based_on.as_str().to_owned(), accent: changed(ColorOption::Accent), active_tab_outline: changed(ColorOption::ActiveTabOutline), main_background: changed(ColorOption::MainBackground), sidebar_background: changed(ColorOption::SidebarBackground), text: changed(ColorOption::Text), border: changed(ColorOption::Border), typography: TypographyConfig::from_typography(typography), toast: ToastFile::from_colors(custom_toasts, toast_colors), } } fn colors(&self, based_on: theme::Preference) -> [Color; 6] { let mut colors = builtin_colors(based_on); let mut apply = |option: ColorOption, value: &Option| { if let Some(color) = value.as_deref().and_then(color_from_hex) { colors[option.index()] = color; } }; apply(ColorOption::Accent, &self.accent); apply(ColorOption::ActiveTabOutline, &self.active_tab_outline); apply(ColorOption::MainBackground, &self.main_background); apply(ColorOption::SidebarBackground, &self.sidebar_background); apply(ColorOption::Text, &self.text); apply(ColorOption::Border, &self.border); colors } } impl ToastFile { fn from_colors(enabled: bool, colors: &[Color; 9]) -> Self { Self { enabled, background: Some(color_to_hex(colors[0])), text: Some(color_to_hex(colors[1])), title: Some(color_to_hex(colors[2])), border: Some(color_to_hex(colors[3])), info: Some(color_to_hex(colors[4])), success: Some(color_to_hex(colors[5])), warning: Some(color_to_hex(colors[6])), error: Some(color_to_hex(colors[7])), dismiss: Some(color_to_hex(colors[8])), } } fn colors(&self, based_on: theme::Preference) -> [Color; 9] { let mut colors = builtin_toast_colors(based_on); for (color, value) in colors.iter_mut().zip([ &self.background, &self.text, &self.title, &self.border, &self.info, &self.success, &self.warning, &self.error, &self.dismiss, ]) { if let Some(parsed) = value.as_deref().and_then(color_from_hex) { *color = parsed; } } colors } } fn builtin_colors(_preference: theme::Preference) -> [Color; 6] { DEFAULT_COLORS } fn builtin_toast_colors(preference: theme::Preference) -> [Color; 9] { let theme = preference.iced().unwrap_or(iced::Theme::Dark); notifications::ToastColors::default_for(&theme).as_array() } /// One customizable text style in the Appearance settings. #[derive(Debug, Clone, PartialEq)] struct TextStyle { font: String, size: f32, bold: bool, italic: bool, underline: bool, strikethrough: bool, } impl TextStyle { fn new(font: &str, size: f32) -> Self { Self { font: font.to_owned(), size, bold: false, italic: false, underline: false, strikethrough: false, } } } /// The text styles used across the settings UI and terminal sessions. #[derive(Debug, Clone, PartialEq)] struct Typography { h1: TextStyle, h2: TextStyle, h3: TextStyle, caption: TextStyle, terminal: TextStyle, ssh: TextStyle, } impl Default for Typography { fn default() -> Self { let ui_font = default_ui_font(); Self { h1: TextStyle::new(ui_font, SETTINGS_H1_SIZE), h2: TextStyle::new(ui_font, SETTINGS_H2_SIZE), h3: TextStyle::new(ui_font, SETTINGS_H3_SIZE), caption: TextStyle::new(ui_font, SETTINGS_CAPTION_SIZE), terminal: TextStyle::new(MONO_FONT_FAMILY, TERMINAL_FONT_SIZE), ssh: TextStyle::new(MONO_FONT_FAMILY, SSH_FONT_SIZE), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum TypographyLevel { H1, H2, H3, Caption, Terminal, Ssh, } impl TypographyLevel { const ALL: [Self; 6] = [ Self::H1, Self::H2, Self::H3, Self::Caption, Self::Terminal, Self::Ssh, ]; fn label(self) -> &'static str { match self { Self::H1 => "H1 - Title", Self::H2 => "H2 - Sub-title", Self::H3 => "H3 - Text", Self::Caption => "Caption", Self::Terminal => "Terminal", Self::Ssh => "SSH", } } fn default_size(self) -> f32 { match self { Self::H1 => SETTINGS_H1_SIZE, Self::H2 => SETTINGS_H2_SIZE, Self::H3 => SETTINGS_H3_SIZE, Self::Caption => SETTINGS_CAPTION_SIZE, Self::Terminal => TERMINAL_FONT_SIZE, Self::Ssh => SSH_FONT_SIZE, } } fn index(self) -> usize { match self { Self::H1 => 0, Self::H2 => 1, Self::H3 => 2, Self::Caption => 3, Self::Terminal => 4, Self::Ssh => 5, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum TextStyleFlag { Bold, Italic, Underline, Strikethrough, } impl TextStyleFlag { const ALL: [Self; 4] = [ Self::Bold, Self::Italic, Self::Underline, Self::Strikethrough, ]; fn label(self) -> &'static str { match self { Self::Bold => "Bold", Self::Italic => "Italic", Self::Underline => "Underline", Self::Strikethrough => "Strikethrough", } } fn enabled(self, style: &TextStyle) -> bool { match self { Self::Bold => style.bold, Self::Italic => style.italic, Self::Underline => style.underline, Self::Strikethrough => style.strikethrough, } } fn toggle(self, style: &mut TextStyle) { match self { Self::Bold => style.bold = !style.bold, Self::Italic => style.italic = !style.italic, Self::Underline => style.underline = !style.underline, Self::Strikethrough => style.strikethrough = !style.strikethrough, } } } impl Typography { fn style(&self, level: TypographyLevel) -> &TextStyle { match level { TypographyLevel::H1 => &self.h1, TypographyLevel::H2 => &self.h2, TypographyLevel::H3 => &self.h3, TypographyLevel::Caption => &self.caption, TypographyLevel::Terminal => &self.terminal, TypographyLevel::Ssh => &self.ssh, } } fn style_mut(&mut self, level: TypographyLevel) -> &mut TextStyle { match level { TypographyLevel::H1 => &mut self.h1, TypographyLevel::H2 => &mut self.h2, TypographyLevel::H3 => &mut self.h3, TypographyLevel::Caption => &mut self.caption, TypographyLevel::Terminal => &mut self.terminal, TypographyLevel::Ssh => &mut self.ssh, } } } static FONT_FAMILIES: OnceLock> = OnceLock::new(); fn default_ui_font() -> &'static str { if cfg!(windows) { "Segoe UI" } else { "Inter" } } /// Font families known to iced's font system, loaded once at first use. fn available_font_families() -> &'static [&'static str] { FONT_FAMILIES.get_or_init(|| { let mut names = BTreeSet::new(); for bundled in ["Inter", "JetBrains Mono", "JetBrains Mono NL"] { names.insert(bundled.to_owned()); } if let Ok(mut font_system) = iced::advanced::graphics::text::font_system().write() { let db = font_system.raw().db(); for face in db.faces() { let Some((family, _)) = face.families.first() else { continue; }; // Skip symbol/emoji-only faces; their rows would render blank. let supports_latin = db .with_face_data(face.id, |data, index| { ttf_parser::Face::parse(data, index).is_ok_and(|face| { ['A', 'a', '0'] .iter() .all(|character| face.glyph_index(*character).is_some()) }) }) .unwrap_or(false); if supports_latin { names.insert(family.clone()); } } } names .into_iter() .map(|name| Box::leak(name.into_boxed_str()) as &'static str) .collect() }) } fn font_for_name(name: &str) -> Font { let requested = if name.trim().is_empty() || name == "Default" { default_ui_font() } else { name }; if let Some(family) = available_font_families() .iter() .find(|family| **family == requested) { return Font::with_name(*family); } // A missing theme font falls back to the platform default, then to the // bundled UI font. if requested != default_ui_font() && let Some(family) = available_font_families() .iter() .find(|family| **family == default_ui_font()) { return Font::with_name(*family); } if let Some(family) = available_font_families() .iter() .find(|family| **family == "Inter") { return Font::with_name(*family); } Font::DEFAULT } fn typography_font(style: &TextStyle) -> Font { let mut font = font_for_name(&style.font); if style.bold { font.weight = font::Weight::Bold; } if style.italic { font.style = font::Style::Italic; } font } fn styled_text<'a>(style: &TextStyle, content: impl IntoFragment<'a>) -> Element<'a, Message> { let span: iced::widget::text::Span<'_, (), Font> = iced::widget::text::Span::new(content) .size(style.size) .font(typography_font(style)) .underline(style.underline) .strikethrough(style.strikethrough); iced::widget::rich_text([span]).into() } /// One entry in a typography size drop-down. #[derive(Debug, Clone, PartialEq)] struct SizeChoice { size: Option, label: String, } impl std::fmt::Display for SizeChoice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.label) } } fn size_choices(level: TypographyLevel, selected: f32) -> (Vec, SizeChoice) { let default = level.default_size(); let mut choices: Vec = FONT_SIZE_STEPS .iter() .map(|size| SizeChoice { size: Some(*size), label: if (*size - default).abs() < 0.01 { format!("{size} px (Default)") } else { format!("{size} px") }, }) .collect(); if let Some(choice) = choices .iter() .find(|choice| { choice .size .is_some_and(|size| (size - selected).abs() < 0.01) }) .cloned() { return (choices, choice); } let custom = SizeChoice { size: None, label: "".to_owned(), }; choices.insert(0, custom.clone()); (choices, custom) } fn typography_size_inputs(typography: &Typography) -> [String; 6] { std::array::from_fn(|index| { let level = TypographyLevel::ALL[index]; format!("{}", typography.style(level).size) }) } /// Everything persisted in the config file, grouped by settings tab. #[derive(Debug, Clone, Serialize, Deserialize)] struct ConfigFile { #[serde(default)] general: GeneralConfig, #[serde(default)] startup: StartupConfig, #[serde(default)] appearance: AppearanceConfig, #[serde(default)] shortcuts: ShortcutConfig, #[serde(default)] command_palette: CommandPaletteConfig, } impl Default for ConfigFile { fn default() -> Self { Self { general: GeneralConfig::default(), startup: StartupConfig::default(), appearance: AppearanceConfig::default(), shortcuts: ShortcutConfig::default(), command_palette: CommandPaletteConfig::default(), } } } #[derive(Debug, Clone, Serialize, Deserialize)] struct GeneralConfig { #[serde(default = "default_true")] fade_settings: bool, } impl Default for GeneralConfig { fn default() -> Self { Self { fade_settings: true, } } } #[derive(Debug, Clone, Serialize, Deserialize)] struct StartupConfig { #[serde(default = "default_true")] show_start_tab: bool, } impl Default for StartupConfig { fn default() -> Self { Self { show_start_tab: true, } } } #[derive(Debug, Clone, Serialize, Deserialize)] struct AppearanceConfig { #[serde(default = "default_theme")] theme: String, #[serde(default, skip_serializing_if = "Option::is_none")] custom_theme: Option, #[serde(default, skip_serializing_if = "Option::is_none")] custom_theme_name: Option, #[serde(default = "default_true")] hide_tab_close: bool, #[serde(default = "default_true")] show_new_session_button: bool, #[serde(default = "default_true")] show_command_palette_description: bool, #[serde(default)] typography: TypographyConfig, #[serde(default)] toast: ToastFile, } impl Default for AppearanceConfig { fn default() -> Self { Self { theme: default_theme(), custom_theme: None, custom_theme_name: None, hide_tab_close: true, show_new_session_button: true, show_command_palette_description: true, typography: TypographyConfig::default(), toast: ToastFile::default(), } } } #[derive(Debug, Clone, Serialize, Deserialize)] struct TypographyConfig { #[serde(default = "default_h1_style")] h1: TextStyleConfig, #[serde(default = "default_h2_style")] h2: TextStyleConfig, #[serde(default = "default_h3_style")] h3: TextStyleConfig, #[serde(default = "default_caption_style")] caption: TextStyleConfig, #[serde(default = "default_terminal_style")] terminal: TextStyleConfig, #[serde(default = "default_ssh_style")] ssh: TextStyleConfig, } #[derive(Debug, Clone, Serialize, Deserialize)] struct TextStyleConfig { #[serde(default = "default_font_family")] font: String, #[serde(default = "default_body_size")] size: f32, #[serde(default)] bold: bool, #[serde(default)] italic: bool, #[serde(default)] underline: bool, #[serde(default)] strikethrough: bool, } impl Default for TextStyleConfig { fn default() -> Self { Self::from_style(&Typography::default().h3) } } impl TextStyleConfig { fn from_style(style: &TextStyle) -> Self { Self { font: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, underline: style.underline, strikethrough: style.strikethrough, } } fn into_style(&self) -> TextStyle { TextStyle { font: self.font.clone(), size: self.size, bold: self.bold, italic: self.italic, underline: self.underline, strikethrough: self.strikethrough, } } } impl Default for TypographyConfig { fn default() -> Self { Self::from_typography(&Typography::default()) } } impl TypographyConfig { fn from_typography(typography: &Typography) -> Self { Self { h1: TextStyleConfig::from_style(&typography.h1), h2: TextStyleConfig::from_style(&typography.h2), h3: TextStyleConfig::from_style(&typography.h3), caption: TextStyleConfig::from_style(&typography.caption), terminal: TextStyleConfig::from_style(&typography.terminal), ssh: TextStyleConfig::from_style(&typography.ssh), } } fn into_typography(&self) -> Typography { Typography { h1: self.h1.into_style(), h2: self.h2.into_style(), h3: self.h3.into_style(), caption: self.caption.into_style(), terminal: self.terminal.into_style(), ssh: self.ssh.into_style(), } } } fn default_font_family() -> String { default_ui_font().to_owned() } fn default_body_size() -> f32 { SETTINGS_H3_SIZE } fn default_h1_style() -> TextStyleConfig { TextStyleConfig::from_style(&Typography::default().h1) } fn default_h2_style() -> TextStyleConfig { TextStyleConfig::from_style(&Typography::default().h2) } fn default_h3_style() -> TextStyleConfig { TextStyleConfig::from_style(&Typography::default().h3) } fn default_caption_style() -> TextStyleConfig { TextStyleConfig::from_style(&Typography::default().caption) } fn default_terminal_style() -> TextStyleConfig { TextStyleConfig::from_style(&Typography::default().terminal) } fn default_ssh_style() -> TextStyleConfig { TextStyleConfig::from_style(&Typography::default().ssh) } #[derive(Debug, Clone, Serialize, Deserialize)] struct ShortcutConfig { #[serde(default = "default_settings_shortcut")] settings: String, #[serde(default = "default_quit_shortcut")] quit: String, #[serde(default = "default_command_palette_shortcut")] command_palette: String, #[serde(default = "default_quick_terminal_shortcut")] quick_terminal: String, #[serde(default = "default_quick_ssh_shortcut")] quick_ssh: String, } impl Default for ShortcutConfig { fn default() -> Self { Self { settings: default_settings_shortcut(), quit: default_quit_shortcut(), command_palette: default_command_palette_shortcut(), quick_terminal: default_quick_terminal_shortcut(), quick_ssh: default_quick_ssh_shortcut(), } } } #[derive(Debug, Clone, Serialize, Deserialize)] struct CommandPaletteConfig { #[serde(default = "default_true")] enabled: bool, } impl Default for CommandPaletteConfig { fn default() -> Self { Self { enabled: true } } } fn default_true() -> bool { true } fn default_theme() -> String { theme::Preference::default().as_str().to_owned() } fn default_settings_shortcut() -> String { Shortcuts::default() .settings .map(|shortcut| shortcut.to_string()) .unwrap_or_default() } fn default_quit_shortcut() -> String { Shortcuts::default() .quit .map(|shortcut| shortcut.to_string()) .unwrap_or_default() } fn default_command_palette_shortcut() -> String { Shortcuts::default() .command_palette .map(|shortcut| shortcut.to_string()) .unwrap_or_default() } fn default_quick_terminal_shortcut() -> String { Shortcuts::default() .quick_terminal .map(|shortcut| shortcut.to_string()) .unwrap_or_default() } fn default_quick_ssh_shortcut() -> String { Shortcuts::default() .quick_ssh .map(|shortcut| shortcut.to_string()) .unwrap_or_default() } fn color_to_hex(color: Color) -> String { let r = (color.r * 255.0).round() as u8; let g = (color.g * 255.0).round() as u8; let b = (color.b * 255.0).round() as u8; if color.a >= 0.999 { format!("#{r:02X}{g:02X}{b:02X}") } else { let a = (color.a * 255.0).round() as u8; format!("#{r:02X}{g:02X}{b:02X}{a:02X}") } } fn color_from_hex(text: &str) -> Option { let hex = text.trim().trim_start_matches('#'); let byte = |range: std::ops::Range| u8::from_str_radix(&hex[range], 16).ok(); match hex.len() { 6 => Some(Color::from_rgb8(byte(0..2)?, byte(2..4)?, byte(4..6)?)), 8 => Some(Color::from_rgba8( byte(0..2)?, byte(2..4)?, byte(4..6)?, f32::from(byte(6..8)?) / 255.0, )), _ => None, } } fn themes_dir() -> Option { config_path().and_then(|path| path.parent().map(|parent| parent.join("Themes"))) } fn load_custom_themes() -> Vec { let Some(dir) = themes_dir() else { return Vec::new(); }; let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new(); }; let mut themes = Vec::new(); for entry in entries.flatten() { let path = entry.path(); if path.extension().and_then(|extension| extension.to_str()) != Some("toml") { continue; } let Some(id) = path .file_stem() .map(|stem| stem.to_string_lossy().into_owned()) else { continue; }; let Ok(text) = std::fs::read_to_string(&path) else { continue; }; let Ok(file) = toml::from_str::(&text) else { continue; }; let Some(based_on) = theme::Preference::parse(&file.based_on) else { continue; }; let colors = file.colors(based_on); let toast_colors = file.toast.colors(based_on); themes.push(CustomTheme { id, name: file.name, based_on, colors, custom_toasts: file.toast.enabled, toast_colors, typography: file.typography.into_typography(), }); } themes } fn themes_signature() -> Vec<(String, u64)> { let Some(dir) = themes_dir() else { return Vec::new(); }; let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new(); }; let mut signature = Vec::new(); for entry in entries.flatten() { let path = entry.path(); if path.extension().and_then(|extension| extension.to_str()) != Some("toml") { continue; } let name = path .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_default(); let modified = entry .metadata() .ok() .and_then(|metadata| metadata.modified().ok()) .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) .map(|duration| duration.as_nanos() as u64) .unwrap_or_default(); signature.push((name, modified)); } signature.sort(); signature } fn write_custom_theme( id: &str, name: &str, based_on: theme::Preference, colors: &[Color; 6], custom_toasts: bool, toast_colors: &[Color; 9], typography: &Typography, ) -> Option<()> { let dir = themes_dir()?; std::fs::create_dir_all(&dir).ok()?; let base = builtin_colors(based_on); let file = ThemeFile::from_colors( name.to_owned(), based_on, colors, &base, custom_toasts, toast_colors, typography, ); let text = toml::to_string_pretty(&file).ok()?; std::fs::write(dir.join(format!("{id}.toml")), text).ok()?; Some(()) } /// Directory holding `folders.toml` and one TOML file per profile. fn profiles_dir() -> Option { config_path().and_then(|path| path.parent().map(|parent| parent.join("profiles"))) } fn normalize_folder_path(value: &str) -> String { let path = value .split(['/', '\\']) .map(str::trim) .filter(|part| !part.is_empty() && *part != "." && *part != "..") .collect::>() .join("/"); if path.is_empty() { DEFAULT_PROFILE_FOLDER.to_owned() } else { path } } /// Keep the default folder first, then sort the tree by path so parents come /// before their children. fn folder_order(a: &str, b: &str) -> Ordering { let rank = |path: &str| { if path == DEFAULT_PROFILE_FOLDER { 0 } else if path.starts_with("Ungrouped/") { 1 } else { 2 } }; rank(a).cmp(&rank(b)).then_with(|| a.cmp(b)) } /// A folder is hidden when any ancestor folder is collapsed. fn folder_visible(folders: &[ProfileFolder], index: usize) -> bool { let Some(folder) = folders.get(index) else { return false; }; let parts: Vec<&str> = folder .path .split('/') .filter(|part| !part.is_empty()) .collect(); let mut prefix = String::new(); for part in parts.iter().take(parts.len().saturating_sub(1)) { if !prefix.is_empty() { prefix.push('/'); } prefix.push_str(part); if let Some(ancestor) = folders.iter().find(|folder| folder.path == prefix) && !ancestor.expanded { return false; } } true } fn load_profiles() -> Vec { let folders = profiles_dir() .map(|dir| load_profiles_from(&dir)) .unwrap_or_else(|| vec![ProfileFolder::default_folder()]); // Persist UUIDs generated for folders from the old path-only format. save_folders(&folders); folders } /// Adds a path and any missing parents to the folder map. `id` is only used /// for the full path; generated parents get fresh UUIDs. fn insert_folder_path( folders: &mut HashMap, path: &str, id: Option, untracked: bool, ) { let parts: Vec<&str> = path.split('/').filter(|part| !part.is_empty()).collect(); let mut prefix = String::new(); for (index, part) in parts.iter().enumerate() { if !prefix.is_empty() { prefix.push('/'); } prefix.push_str(part); match folders.get_mut(&prefix) { Some((_, existing_untracked)) => { if !untracked { *existing_untracked = false; } } None => { let folder_id = if index + 1 == parts.len() { id.clone().unwrap_or_else(new_folder_id) } else { new_folder_id() }; folders.insert(prefix.clone(), (folder_id, untracked)); } } } } /// Resolves a profile's folder UUID, falling back to the legacy folder name /// when the folder is missing from `folders.toml`. fn resolve_profile_folder( folders: &mut HashMap, file: &ProfileFile, ) -> (String, String) { let reference = if file.parent_id.trim().is_empty() { file.folder.trim() } else { file.parent_id.trim() }; if uuid::Uuid::parse_str(reference).is_ok() && let Some((path, _)) = folders.iter().find(|(_, (id, _))| id == reference) { return (reference.to_owned(), path.clone()); } // Legacy files used the folder path/name instead of its UUID. let fallback = if !file.folder_name.trim().is_empty() { normalize_folder_path(&file.folder_name) } else if !reference.is_empty() && uuid::Uuid::parse_str(reference).is_err() { normalize_folder_path(reference) } else { DEFAULT_PROFILE_FOLDER.to_owned() }; if let Some((id, _)) = folders.get(&fallback) { return (id.clone(), fallback); } let id = if uuid::Uuid::parse_str(reference).is_ok() { reference.to_owned() } else { new_folder_id() }; insert_folder_path(folders, &fallback, Some(id.clone()), true); (id, fallback) } /// Turns the IDs and `parent_id` links in `folders.toml` back into paths. /// Records written before the UUID format carry a full `path` and are kept. fn load_folder_records(folders: &mut HashMap, file: FoldersFile) { let mut linked: HashMap)> = HashMap::new(); for entry in file.folders { match entry { FolderEntry::Path(path) => { insert_folder_path( folders, &normalize_folder_path(&path), Some(new_folder_id()), false, ); } FolderEntry::Record(record) => { let id = if record.id.trim().is_empty() { new_folder_id() } else { record.id }; if record.name.trim().is_empty() && !record.path.trim().is_empty() { insert_folder_path( folders, &normalize_folder_path(&record.path), Some(id), false, ); } else { let parent_id = record.parent_id.filter(|parent| !parent.trim().is_empty()); linked.insert(id, (record.name, parent_id)); } } } } // Insert parents first so `insert_folder_path` never invents a new UUID // for a parent that is already in the file. let mut paths: Vec<(String, String)> = linked .keys() .map(|id| (id.clone(), folder_path_from_records(id, &linked))) .collect(); paths.sort_by_key(|(_, path)| path.matches('/').count()); for (id, path) in paths { insert_folder_path(folders, &normalize_folder_path(&path), Some(id), false); } } fn folder_path_from_records( id: &str, records: &HashMap)>, ) -> String { let mut parts = Vec::new(); let mut current = Some(id); let mut seen = HashSet::new(); while let Some(id) = current { if !seen.insert(id) { break; } let Some((name, parent_id)) = records.get(id) else { break; }; if !name.trim().is_empty() { parts.push(name.trim().to_owned()); } current = parent_id.as_deref(); } parts.reverse(); if parts.is_empty() { DEFAULT_PROFILE_FOLDER.to_owned() } else { parts.join("/") } } /// Rebuilds the folder tree and profile lists from the `profiles` directory. /// Folders referenced by a profile but missing from `folders.toml` are added /// as runtime-only folders. fn load_profiles_from(dir: &Path) -> Vec { let mut folder_map: HashMap = HashMap::new(); if let Ok(text) = std::fs::read_to_string(dir.join("folders.toml")) && let Ok(file) = toml::from_str::(&text) { load_folder_records(&mut folder_map, file); } insert_folder_path( &mut folder_map, DEFAULT_PROFILE_FOLDER, Some(new_folder_id()), false, ); let mut profiles = Vec::new(); if let Ok(entries) = std::fs::read_dir(dir) { let mut files: Vec = entries .flatten() .map(|entry| entry.path()) .filter(|path| { path.extension().and_then(|extension| extension.to_str()) == Some("toml") && path.file_name().and_then(|name| name.to_str()) != Some("folders.toml") }) .collect(); files.sort(); for path in files { let Ok(text) = std::fs::read_to_string(&path) else { continue; }; let Ok(mut file) = toml::from_str::(&text) else { continue; }; if file.name.trim().is_empty() { file.name = path .file_stem() .map(|stem| stem.to_string_lossy().into_owned()) .unwrap_or_default(); } let (folder_id, folder_path) = resolve_profile_folder(&mut folder_map, &file); let needs_migration = file.parent_id.trim() != folder_id || !file.folder.trim().is_empty() || !file.folder_name.trim().is_empty(); let mut profile = file.into_profile(); profile.folder_id = folder_id.clone(); profile.file = Some(path); // Rewrite files that still place the profile by folder name. if needs_migration { save_profile(&mut profile, &folder_path); } profiles.push((folder_id, profile)); } } let mut folders: Vec = folder_map .into_iter() .map(|(path, (id, untracked))| { let mut folder = ProfileFolder::from_path(path); folder.id = id; folder.untracked = untracked; folder }) .collect(); folders.sort_by(|a, b| folder_order(&a.path, &b.path)); for (folder_id, profile) in profiles { if let Some(folder) = folders.iter_mut().find(|folder| folder.id == folder_id) { folder.profiles.push(profile); } } folders } /// Adds a folder and any missing parents, then returns the folder's index. fn ensure_folder(folders: &mut Vec, path: &str) -> usize { add_folder_to_list(folders, path); folders.sort_by(|a, b| folder_order(&a.path, &b.path)); folders .iter() .position(|folder| folder.path == path) .unwrap_or(0) } fn add_folder_to_list(folders: &mut Vec, path: &str) { let mut prefix = String::new(); for part in path.split('/') { if !prefix.is_empty() { prefix.push('/'); } prefix.push_str(part); if let Some(folder) = folders.iter_mut().find(|folder| folder.path == prefix) { folder.untracked = false; } else { folders.push(ProfileFolder::from_path(prefix.clone())); } } } fn rename_folder(state: &mut Moorly) -> Task { let Some((index, draft)) = state.folder_rename.clone() else { return Task::none(); }; let new_name = draft.trim().to_owned(); let Some(folder) = state.profile_folders.get(index) else { state.folder_rename = None; return Task::none(); }; let old_path = folder.path.clone(); if new_name.is_empty() || new_name.contains('/') || old_path == DEFAULT_PROFILE_FOLDER { return Task::none(); } let parent = old_path .rsplit_once('/') .map(|(parent, _)| parent) .unwrap_or(""); let new_path = if parent.is_empty() { new_name.clone() } else { format!("{parent}/{new_name}") }; if new_path == old_path { state.folder_rename = None; return Task::none(); } let affected: Vec<(usize, String)> = state .profile_folders .iter() .enumerate() .filter(|(_, folder)| is_folder_under(&folder.path, &old_path)) .map(|(index, folder)| { let suffix = folder.path.strip_prefix(&old_path).unwrap_or(""); (index, format!("{new_path}{suffix}")) }) .collect(); // Do not let a rename collide with a folder outside the renamed subtree. for (affected_index, path) in &affected { let collides = state .profile_folders .iter() .enumerate() .any(|(index, folder)| { index != *affected_index && !affected.iter().any(|(affected, _)| *affected == index) && folder.path == *path }); if collides { return Task::none(); } } for (folder_index, path) in &affected { state.profile_folders[*folder_index].path = path.clone(); if *folder_index == index { state.profile_folders[*folder_index].name = new_name.clone(); } } state .profile_folders .sort_by(|a, b| folder_order(&a.path, &b.path)); save_folders(&state.profile_folders); state.folder_rename = None; Task::none() } fn profile_file_stem(name: &str) -> String { let stem: String = name .trim() .chars() .map(|character| { if character.is_control() || matches!( character, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' ) { '_' } else { character } }) .collect(); let stem = stem.trim().trim_matches('.').trim(); if stem.is_empty() { "profile".to_owned() } else if stem.eq_ignore_ascii_case("folders") { "folders-profile".to_owned() } else { stem.chars().take(100).collect() } } fn write_profile_file(path: &Path, profile: &Profile, folder: &str) -> Option<()> { let text = toml::to_string_pretty(&ProfileFile::from_profile(profile, folder)).ok()?; std::fs::write(path, text).ok()?; // Profile files can contain passwords and keys; keep them private. #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).ok()?; } Some(()) } fn write_profile_to(dir: &Path, profile: &Profile, folder: &str) -> Option { std::fs::create_dir_all(dir).ok()?; let stem = profile_file_stem(&profile.name); let mut path = dir.join(format!("{stem}.toml")); let mut suffix = 2; while path.exists() { path = dir.join(format!("{stem}-{suffix}.toml")); suffix += 1; } write_profile_file(&path, profile, folder)?; Some(path) } fn write_profile(profile: &Profile, folder: &str) -> Option { // Never let the unit tests write into the developer's real profile files. if cfg!(test) { return None; } write_profile_to(&profiles_dir()?, profile, folder) } /// Persists a profile at its existing file, or creates one if it has none. fn save_profile(profile: &mut Profile, folder: &str) { if cfg!(test) { return; } if let Some(file) = &profile.file { let _ = write_profile_file(file, profile, folder); } else if let Some(path) = write_profile(profile, folder) { profile.file = Some(path); } } fn write_folders_to(dir: &Path, folders: &[ProfileFolder]) -> Option<()> { std::fs::create_dir_all(dir).ok()?; let mut sorted: Vec<&ProfileFolder> = folders.iter().filter(|folder| !folder.untracked).collect(); sorted.sort_by(|a, b| folder_order(&a.path, &b.path)); sorted.dedup_by(|a, b| a.path == b.path); let ids: HashMap<&str, &str> = sorted .iter() .map(|folder| (folder.path.as_str(), folder.id.as_str())) .collect(); let records: Vec = sorted .iter() .map(|folder| FolderRecord { id: folder.id.clone(), name: if folder.name.trim().is_empty() { folder .path .rsplit('/') .next() .unwrap_or(DEFAULT_PROFILE_FOLDER) .to_owned() } else { folder.name.clone() }, parent_id: folder .path .rsplit_once('/') .and_then(|(parent, _)| ids.get(parent).map(|id| (*id).to_owned())), path: String::new(), }) .collect(); let text = toml::to_string_pretty(&FoldersOutFile { folders: records }).ok()?; std::fs::write(dir.join("folders.toml"), text).ok()?; Some(()) } fn save_folders(folders: &[ProfileFolder]) { if cfg!(test) { return; } let Some(dir) = profiles_dir() else { return; }; let _ = write_folders_to(&dir, folders); } fn trash_dir() -> Option { config_path().and_then(|path| path.parent().map(|parent| parent.join(".trash"))) } fn timestamp_now() -> String { let seconds = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|duration| duration.as_secs()) .unwrap_or_default(); format_timestamp(seconds) } fn format_timestamp(seconds: u64) -> String { let days = (seconds / 86_400) as i64; let time = seconds % 86_400; let z = days + 719_468; let era = if z >= 0 { z } else { z - 146_096 } / 146_097; let doe = z - era * 146_097; let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; let year = yoe + era * 400; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let day = doy - (153 * mp + 2) / 5 + 1; let month = mp + if mp < 10 { 3 } else { -9 }; let year = year + if month <= 2 { 1 } else { 0 }; format!( "{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02}", time / 3_600, (time % 3_600) / 60, time % 60 ) } fn load_trash_entries() -> Vec { trash_dir() .map(|dir| load_trash_entries_from(&dir)) .unwrap_or_default() } fn load_trash_entries_from(dir: &Path) -> Vec { let mut entries = Vec::new(); if let Ok(text) = std::fs::read_to_string(dir.join("folders.toml")) && let Ok(file) = toml::from_str::(&text) { entries.extend(file.folders.into_iter().map(TrashEntry::Folder)); } if let Ok(read) = std::fs::read_dir(dir) { let mut files: Vec = read .flatten() .map(|entry| entry.path()) .filter(|path| { path.extension().and_then(|extension| extension.to_str()) == Some("toml") && path.file_name().and_then(|name| name.to_str()) != Some("folders.toml") }) .collect(); files.sort(); for file in files { let Ok(text) = std::fs::read_to_string(&file) else { continue; }; let Ok(profile) = toml::from_str::(&text) else { continue; }; if profile.trash.is_some() { entries.push(TrashEntry::Profile { file, profile }); } } } entries } fn append_trash_folders(folders: &[TrashFolder]) { if cfg!(test) || folders.is_empty() { return; } let Some(dir) = trash_dir() else { return; }; let _ = std::fs::create_dir_all(&dir); let path = dir.join("folders.toml"); let mut file = std::fs::read_to_string(&path) .ok() .and_then(|text| toml::from_str::(&text).ok()) .unwrap_or_default(); file.folders.extend_from_slice(folders); if let Ok(text) = toml::to_string_pretty(&file) { let _ = std::fs::write(path, text); } } fn save_trash_folders(folders: &[TrashFolder]) { if cfg!(test) { return; } let Some(dir) = trash_dir() else { return; }; let _ = std::fs::create_dir_all(&dir); let file = TrashFoldersFile { folders: folders.to_vec(), }; if let Ok(text) = toml::to_string_pretty(&file) { let _ = std::fs::write(dir.join("folders.toml"), text); } } fn move_profile_to_trash(profile: &Profile, folder: &str) -> Option { if cfg!(test) { return None; } let dir = trash_dir()?; std::fs::create_dir_all(&dir).ok()?; let stem = profile_file_stem(&profile.name); let mut path = dir.join(format!("{stem}.toml")); let mut suffix = 2; while path.exists() { path = dir.join(format!("{stem}-{suffix}.toml")); suffix += 1; } let mut file = ProfileFile::from_profile(profile, folder); file.trash = Some(TrashInfo { previous_path: folder.to_owned(), deleted: timestamp_now(), }); let text = toml::to_string_pretty(&file).ok()?; std::fs::write(&path, text).ok()?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).ok()?; } if let Some(original) = &profile.file { let _ = std::fs::remove_file(original); } Some(path) } fn is_folder_under(path: &str, root: &str) -> bool { path == root || path .strip_prefix(root) .is_some_and(|rest| rest.starts_with('/')) } fn checked_folder_roots(state: &Moorly) -> Vec { let mut roots: Vec = state .checked .iter() .filter_map(|item| match item { Selection::Folder(index) => state .profile_folders .get(*index) .map(|folder| folder.path.clone()), Selection::Profile { .. } => None, }) .collect(); // A checked child folder is already covered by its checked parent. roots.sort_by_key(|path| path.split('/').count()); let mut filtered: Vec = Vec::new(); for root in roots { if !filtered.iter().any(|parent| is_folder_under(&root, parent)) { filtered.push(root); } } filtered } fn default_transfer_destination(state: &Moorly) -> usize { let roots = checked_folder_roots(state); let individual = checked_profile_indices(state, &roots); let root_available = !roots.is_empty() && individual.is_empty() && roots.iter().any(|root| root.contains('/')); let is_valid = |index: usize| { state .profile_folders .get(index) .is_some_and(|folder| !roots.iter().any(|root| is_folder_under(&folder.path, root))) }; let preferred = state.selected.and_then(|selection| match selection { Selection::Folder(index) => Some(index), Selection::Profile { folder, .. } => Some(folder), }); if preferred.is_some_and(is_valid) { return preferred.unwrap(); } if root_available { return ROOT_FOLDER_INDEX; } state .profile_folders .iter() .enumerate() .find(|(index, _)| is_valid(*index)) .map(|(index, _)| index) .unwrap_or(0) } /// Checked profiles that are not already covered by a checked folder. fn checked_profile_indices(state: &Moorly, roots: &[String]) -> Vec<(usize, usize)> { let mut items = Vec::new(); for (folder_index, folder) in state.profile_folders.iter().enumerate() { if roots.iter().any(|root| is_folder_under(&folder.path, root)) { continue; } for profile_index in 0..folder.profiles.len() { if state.checked.contains(&Selection::Profile { folder: folder_index, profile: profile_index, }) { items.push((folder_index, profile_index)); } } } items } fn remove_folders(state: &mut Moorly, roots: &[String]) { if roots.is_empty() { return; } let remove_paths: HashSet = state .profile_folders .iter() .filter(|folder| roots.iter().any(|root| is_folder_under(&folder.path, root))) .map(|folder| folder.path.clone()) .collect(); state .profile_folders .retain(|folder| !remove_paths.contains(&folder.path)); } fn apply_transfer(state: &mut Moorly, mode: TransferMode, destination: usize) { let (destination_path, destination_id) = if destination == ROOT_FOLDER_INDEX { (String::new(), None) } else { let Some((path, id)) = state .profile_folders .get(destination) .map(|folder| (folder.path.clone(), folder.id.clone())) else { state.transfer = None; return; }; (path, Some(id)) }; let roots = checked_folder_roots(state); let individual = checked_profile_indices(state, &roots); let snapshot = state.profile_folders.clone(); let mut placements = Vec::new(); let mut moved_roots = Vec::new(); for root in &roots { if destination_path == *root || is_folder_under(&destination_path, root) { continue; } let leaf = root.rsplit('/').next().unwrap_or(root); let new_root = if destination_path.is_empty() { leaf.to_owned() } else { format!("{destination_path}/{leaf}") }; if new_root == *root { continue; } for folder in snapshot .iter() .filter(|folder| is_folder_under(&folder.path, root)) { let suffix = folder.path.strip_prefix(root).unwrap_or(""); let new_path = format!("{new_root}{suffix}"); add_folder_to_list(&mut state.profile_folders, &new_path); let new_folder_id = state .profile_folders .iter() .find(|folder| folder.path == new_path) .map(|folder| folder.id.clone()) .unwrap_or_default(); for source in &folder.profiles { let mut profile = source.clone(); profile.folder_id = new_folder_id.clone(); match mode { TransferMode::Copy => { profile.file = write_profile(&profile, &new_path); } TransferMode::Move => save_profile(&mut profile, &new_path), } placements.push((new_path.clone(), profile)); } } moved_roots.push(root.clone()); } let individual_path = if destination_path.is_empty() { DEFAULT_PROFILE_FOLDER.to_owned() } else { destination_path.clone() }; let individual_id = destination_id.clone().unwrap_or_else(|| { state .profile_folders .iter() .find(|folder| folder.path == DEFAULT_PROFILE_FOLDER) .map(|folder| folder.id.clone()) .unwrap_or_default() }); for (folder_index, profile_index) in &individual { let Some(source) = snapshot .get(*folder_index) .and_then(|folder| folder.profiles.get(*profile_index)) else { continue; }; let mut profile = source.clone(); profile.folder_id = individual_id.clone(); match mode { TransferMode::Copy => { profile.file = write_profile(&profile, &individual_path); } TransferMode::Move => save_profile(&mut profile, &individual_path), } placements.push((individual_path.clone(), profile)); } if mode == TransferMode::Move { // Removing by descending index keeps the remaining indices valid. let mut sorted = individual; sorted.sort_unstable_by(|a, b| b.cmp(a)); for (folder_index, profile_index) in sorted { if let Some(folder) = state.profile_folders.get_mut(folder_index) && profile_index < folder.profiles.len() { folder.profiles.remove(profile_index); } } remove_folders(state, &moved_roots); } for (folder_path, profile) in placements { if let Some(folder) = state .profile_folders .iter_mut() .find(|folder| folder.path == folder_path) { folder.expanded = true; folder.profiles.push(profile); } } add_folder_to_list(&mut state.profile_folders, DEFAULT_PROFILE_FOLDER); state .profile_folders .sort_by(|a, b| folder_order(&a.path, &b.path)); state.checked.clear(); state.selected = None; state.transfer = None; save_folders(&state.profile_folders); } fn promoted_path(path: &str, selected_folders: &HashSet) -> String { let mut kept = Vec::new(); let mut prefix = String::new(); for part in path.split('/') { if !prefix.is_empty() { prefix.push('/'); } prefix.push_str(part); if !selected_folders.contains(&prefix) { kept.push(part); } } if kept.is_empty() { DEFAULT_PROFILE_FOLDER.to_owned() } else { kept.join("/") } } fn apply_delete(state: &mut Moorly) { let selected_folders: HashSet = state .checked .iter() .filter_map(|item| match item { Selection::Folder(index) => state .profile_folders .get(*index) .map(|folder| folder.path.clone()), Selection::Profile { .. } => None, }) .collect(); let selected_profiles: HashSet<(usize, usize)> = state .checked .iter() .filter_map(|item| match item { Selection::Profile { folder, profile } => Some((*folder, *profile)), Selection::Folder(_) => None, }) .collect(); let timestamp = timestamp_now(); let snapshot = state.profile_folders.clone(); let mut trash_folders = Vec::new(); for folder in &snapshot { if !selected_folders.contains(&folder.path) { continue; } let previous_path = folder .path .rsplit_once('/') .map(|(parent, _)| parent) .unwrap_or(""); trash_folders.push(TrashFolder { name: folder.name.clone(), previous_path: previous_path.to_owned(), deleted: timestamp.clone(), }); } let mut kept_folders: Vec = Vec::new(); for folder in &snapshot { if selected_folders.contains(&folder.path) { continue; } let path = promoted_path(&folder.path, &selected_folders); if !kept_folders.iter().any(|folder| folder.path == path) { let mut entry = folder.clone(); entry.path = path; entry.profiles.clear(); kept_folders.push(entry); } } for (folder_index, folder) in snapshot.iter().enumerate() { for (profile_index, profile) in folder.profiles.iter().enumerate() { if selected_profiles.contains(&(folder_index, profile_index)) { move_profile_to_trash(profile, &folder.path); continue; } let path = promoted_path(&folder.path, &selected_folders); if !kept_folders.iter().any(|folder| folder.path == path) { kept_folders.push(ProfileFolder::from_path(path.clone())); } let mut profile = profile.clone(); profile.folder_id = kept_folders .iter() .find(|folder| folder.path == path) .map(|folder| folder.id.clone()) .unwrap_or_default(); if path != folder.path { save_profile(&mut profile, &path); } if let Some(target) = kept_folders.iter_mut().find(|folder| folder.path == path) { target.profiles.push(profile); } } } if !kept_folders .iter() .any(|folder| folder.path == DEFAULT_PROFILE_FOLDER) { kept_folders.push(ProfileFolder::default_folder()); } kept_folders.sort_by(|a, b| folder_order(&a.path, &b.path)); append_trash_folders(&trash_folders); state.profile_folders = kept_folders; state.checked.clear(); state.selected = None; state.confirm_delete = false; save_folders(&state.profile_folders); } fn restore_trash_items(state: &mut Moorly) { if state.trash_checked.is_empty() { return; } let entries = state.trash_entries.clone(); let mut remaining_folders = Vec::new(); let mut removed_indices = HashSet::new(); let mut restored = 0usize; // Restore folders first so their profiles have somewhere to go. for (index, entry) in entries.iter().enumerate() { let TrashEntry::Folder(folder) = entry else { continue; }; if state.trash_checked.contains(&index) { let path = if folder.previous_path.is_empty() { folder.name.clone() } else { format!("{}/{}", folder.previous_path, folder.name) }; add_folder_to_list(&mut state.profile_folders, &path); removed_indices.insert(index); restored += 1; } else { remaining_folders.push(folder.clone()); } } for (index, entry) in entries.iter().enumerate() { let TrashEntry::Profile { file, profile } = entry else { continue; }; if !state.trash_checked.contains(&index) { continue; } let folder_path = profile .trash .as_ref() .map(|trash| normalize_folder_path(&trash.previous_path)) .unwrap_or_else(|| DEFAULT_PROFILE_FOLDER.to_owned()); if !state .profile_folders .iter() .any(|folder| folder.path == folder_path) { add_folder_to_list(&mut state.profile_folders, &folder_path); } let mut restored_profile = profile.clone().into_profile(); restored_profile.folder_id = state .profile_folders .iter() .find(|folder| folder.path == folder_path) .map(|folder| folder.id.clone()) .unwrap_or_default(); let new_file = write_profile(&restored_profile, &folder_path); // Keep the trash entry if the profile could not be written back. if !cfg!(test) && new_file.is_none() { continue; } restored_profile.file = new_file; if let Some(folder) = state .profile_folders .iter_mut() .find(|folder| folder.path == folder_path) { folder.expanded = true; folder.profiles.push(restored_profile); removed_indices.insert(index); restored += 1; } if !cfg!(test) { let _ = std::fs::remove_file(file); } } save_trash_folders(&remaining_folders); state.trash_entries = entries .into_iter() .enumerate() .filter(|(index, _)| !removed_indices.contains(index)) .map(|(_, entry)| entry) .collect(); state.trash_checked.clear(); add_folder_to_list(&mut state.profile_folders, DEFAULT_PROFILE_FOLDER); state .profile_folders .sort_by(|a, b| folder_order(&a.path, &b.path)); save_folders(&state.profile_folders); state.selected = None; state.checked.clear(); let message = if restored == 1 { "Restored 1 item from trash.".to_owned() } else { format!("Restored {restored} items from trash.") }; state.notifications.add( notifications::Notification::new(notifications::NotificationKind::Success, message) .title("Restored"), ); } fn purge_trash_items(state: &mut Moorly) { if state.trash_checked.is_empty() { return; } let entries = state.trash_entries.clone(); let checked = state.trash_checked.clone(); let mut remaining_folders = Vec::new(); let mut removed = 0usize; for (index, entry) in entries.iter().enumerate() { if checked.contains(&index) { if let TrashEntry::Profile { file, .. } = entry && !cfg!(test) { let _ = std::fs::remove_file(file); } removed += 1; } else if let TrashEntry::Folder(folder) = entry { remaining_folders.push(folder.clone()); } } save_trash_folders(&remaining_folders); state.trash_entries = entries .into_iter() .enumerate() .filter(|(index, _)| !checked.contains(index)) .map(|(_, entry)| entry) .collect(); state.trash_checked.clear(); state.confirm_purge_trash = false; let message = if removed == 1 { "Deleted 1 item permanently.".to_owned() } else { format!("Deleted {removed} items permanently.") }; state.notifications.add( notifications::Notification::new(notifications::NotificationKind::Success, message) .title("Deleted"), ); } fn apply_theme_choice(state: &mut Moorly, choice: ThemeChoice) { match &choice { ThemeChoice::BuiltIn(preference) => { state.theme = *preference; state.colors = builtin_colors(*preference); state.custom_toasts = state.builtin_custom_toasts; state.toast_colors = state.builtin_toast_colors; } ThemeChoice::Custom { id, .. } => { if let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id) { state.theme = theme.based_on; state.colors = theme.colors; state.custom_toasts = theme.custom_toasts; state.toast_colors = theme.toast_colors; state.typography = theme.typography.clone(); state.typography_draft = state.typography.clone(); state.typography_size_inputs = typography_size_inputs(&state.typography); state.theme_choice = ThemeChoice::Custom { id: theme.id.clone(), name: theme.name.clone(), }; return; } } } state.theme_choice = choice; } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] enum SettingsSection { #[default] General, Startup, Appearance, Shortcuts, CommandPalette, Profiles, } impl SettingsSection { const ALL: [Self; 6] = [ Self::General, Self::Startup, Self::Appearance, Self::Shortcuts, Self::CommandPalette, Self::Profiles, ]; fn label(self) -> &'static str { match self { Self::General => "General", Self::Startup => "Startup", Self::Appearance => "Appearance", Self::Shortcuts => "Shortcuts", Self::CommandPalette => "Command Palette", Self::Profiles => "Profiles", } } } /// Path of the settings file. Everything lives in the same file. fn config_path() -> Option { theme::config_path() } /// Reads the config file, falling back to the old split config files so an /// upgrade keeps the user's existing settings. fn load_config() -> ConfigFile { if let Some(path) = config_path() && let Ok(text) = std::fs::read_to_string(&path) && let Ok(config) = toml::from_str(&text) { return config; } let mut config = ConfigFile::default(); if let Some(path) = config_path().map(|path| path.with_file_name("config")) && let Ok(text) = std::fs::read_to_string(path) { let load = |key: &str| { let prefix = format!("{key}="); text.lines() .find_map(|line| line.strip_prefix(&prefix)) .map(|value| value.trim().eq_ignore_ascii_case("true")) }; if let Some(value) = load("show_start_tab") { config.startup.show_start_tab = value; } if let Some(value) = load("fade_settings") { config.general.fade_settings = value; } if let Some(value) = load("hide_tab_close") { config.appearance.hide_tab_close = value; } } if let Some(path) = config_path().map(|path| path.with_file_name("theme")) && let Ok(text) = std::fs::read_to_string(path) && let Some(preference) = theme::Preference::parse(text.trim()) { config.appearance.theme = preference.as_str().to_owned(); } config } /// Toast customization saved for built-in themes in the config file. fn builtin_toast_config(appearance: &AppearanceConfig) -> (bool, [Color; 9]) { let preference = theme::Preference::parse(&appearance.theme).unwrap_or_default(); ( appearance.toast.enabled, appearance.toast.colors(preference), ) } /// Resolves the saved theme selection to its live theme and colors. The final /// flag reports that a selected custom theme could not be found, in which case /// the app falls back to the built-in dark theme. fn resolve_theme( appearance: &AppearanceConfig, custom_themes: &[CustomTheme], ) -> ( ThemeChoice, theme::Preference, [Color; 6], bool, [Color; 9], Typography, bool, ) { if let Some(id) = &appearance.custom_theme { if let Some(theme) = custom_themes.iter().find(|theme| theme.id == *id) { return ( ThemeChoice::Custom { id: theme.id.clone(), name: theme.name.clone(), }, theme.based_on, theme.colors, theme.custom_toasts, theme.toast_colors, theme.typography.clone(), false, ); } let preference = theme::Preference::Dark; let (custom_toasts, toast_colors) = builtin_toast_config(appearance); return ( ThemeChoice::BuiltIn(preference), preference, builtin_colors(preference), custom_toasts, toast_colors, appearance.typography.into_typography(), true, ); } let preference = theme::Preference::parse(&appearance.theme).unwrap_or_default(); let (custom_toasts, toast_colors) = builtin_toast_config(appearance); ( ThemeChoice::BuiltIn(preference), preference, builtin_colors(preference), custom_toasts, toast_colors, appearance.typography.into_typography(), false, ) } /// Warning shown when the saved custom theme is no longer on disk. fn missing_theme_notification(name: Option<&str>) -> notifications::Notification { let message = match name { Some(name) => { format!("The theme \"{name}\" is missing. Switched to the Dark theme.") } None => "The selected custom theme is missing. Switched to the Dark theme.".to_owned(), }; notifications::Notification::new(notifications::NotificationKind::Warning, message) .title("Theme unavailable") .persistent() } /// 0.5s total: 250ms fading out plus 250ms fading in. fn new_fade_animation() -> Animation { Animation::new(true).duration(Duration::from_millis(250)) } /// Fade used by the tab close icon when the tab is hovered or left. fn new_tab_close_animation() -> Animation { Animation::new(false).duration(Duration::from_millis(750)) } /// Commits the draft settings to the running state. fn apply_settings(state: &mut Moorly) { state.show_start_tab = state.show_start_tab_draft; state.fade_settings = state.fade_settings_draft; state.hide_tab_close = state.hide_tab_close_draft; state.show_new_session_button = state.show_new_session_button_draft; state.show_command_palette_description = state.show_command_palette_description_draft; state.typography = state.typography_draft.clone(); state.typography_size_inputs = typography_size_inputs(&state.typography); state.command_palette_enabled = state.command_palette_enabled_draft; state.saved_theme = state.theme; state.saved_theme_choice = state.theme_choice.clone(); state.saved_colors = match &state.saved_theme_choice { ThemeChoice::BuiltIn(preference) => builtin_colors(*preference), ThemeChoice::Custom { id, .. } => state .custom_themes .iter() .find(|theme| theme.id == *id) .map(|theme| theme.colors) .unwrap_or_else(|| builtin_colors(state.theme)), }; state.saved_shortcuts = state.shortcuts.clone(); if !state.show_new_session_button { for window_state in state.windows.values_mut() { window_state.quick_menu_open = false; } } if !state.fade_settings { if let Some(pending) = state.pending_settings_section.take() { state.settings_section = pending; } state.fade_animation = new_fade_animation(); } } /// Discards the drafts, including the previewed theme selection. fn undo_settings(state: &mut Moorly) { state.show_start_tab_draft = state.show_start_tab; state.fade_settings_draft = state.fade_settings; state.hide_tab_close_draft = state.hide_tab_close; state.show_new_session_button_draft = state.show_new_session_button; state.show_command_palette_description_draft = state.show_command_palette_description; state.typography_draft = state.typography.clone(); state.typography_size_inputs = typography_size_inputs(&state.typography_draft); state.command_palette_enabled_draft = state.command_palette_enabled; state.shortcuts = state.saved_shortcuts.clone(); state.shortcut_capture = None; state.theme_choice = state.saved_theme_choice.clone(); state.theme = state.saved_theme; state.colors = state.saved_colors; let (custom_toasts, toast_colors) = match &state.saved_theme_choice { ThemeChoice::BuiltIn(_) => (state.builtin_custom_toasts, state.builtin_toast_colors), ThemeChoice::Custom { id, .. } => state .custom_themes .iter() .find(|theme| theme.id == *id) .map(|theme| (theme.custom_toasts, theme.toast_colors)) .unwrap_or((state.builtin_custom_toasts, state.builtin_toast_colors)), }; state.custom_toasts = custom_toasts; state.toast_colors = toast_colors; } fn save_config(state: &Moorly) { // Never let the unit tests overwrite the developer's real settings. if cfg!(test) { return; } let Some(path) = config_path() else { return; }; if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } if let Ok(text) = toml::to_string_pretty(&config_file(state)) { let _ = std::fs::write(path, text); } } /// The committed settings, laid out one table per settings section. fn config_file(state: &Moorly) -> ConfigFile { ConfigFile { general: GeneralConfig { fade_settings: state.fade_settings, }, startup: StartupConfig { show_start_tab: state.show_start_tab, }, appearance: AppearanceConfig { theme: state.saved_theme.as_str().to_owned(), custom_theme: match &state.saved_theme_choice { ThemeChoice::Custom { id, .. } => Some(id.clone()), ThemeChoice::BuiltIn(_) => None, }, custom_theme_name: match &state.saved_theme_choice { ThemeChoice::Custom { name, .. } => Some(name.clone()), ThemeChoice::BuiltIn(_) => None, }, hide_tab_close: state.hide_tab_close, show_new_session_button: state.show_new_session_button, show_command_palette_description: state.show_command_palette_description, typography: TypographyConfig::from_typography(&state.typography), toast: ToastFile::from_colors(state.builtin_custom_toasts, &state.builtin_toast_colors), }, shortcuts: ShortcutConfig { settings: state .saved_shortcuts .settings .as_ref() .map(ToString::to_string) .unwrap_or_default(), quit: state .saved_shortcuts .quit .as_ref() .map(ToString::to_string) .unwrap_or_default(), command_palette: state .saved_shortcuts .command_palette .as_ref() .map(ToString::to_string) .unwrap_or_default(), quick_terminal: state .saved_shortcuts .quick_terminal .as_ref() .map(ToString::to_string) .unwrap_or_default(), quick_ssh: state .saved_shortcuts .quick_ssh .as_ref() .map(ToString::to_string) .unwrap_or_default(), }, command_palette: CommandPaletteConfig { enabled: state.command_palette_enabled, }, } } impl Default for Moorly { fn default() -> Self { let config = load_config(); let custom_themes = load_custom_themes(); let (theme_choice, theme, colors, custom_toasts, toast_colors, typography, theme_missing) = resolve_theme(&config.appearance, &custom_themes); let (builtin_custom_toasts, builtin_toast_palette) = builtin_toast_config(&config.appearance); let show_start_tab = config.startup.show_start_tab; let fade_settings = config.general.fade_settings; let hide_tab_close = config.appearance.hide_tab_close; let show_new_session_button = config.appearance.show_new_session_button; let show_command_palette_description = config.appearance.show_command_palette_description; let typography_size_inputs = typography_size_inputs(&typography); let command_palette_enabled = config.command_palette.enabled; let shortcuts = Shortcuts { settings: Shortcut::parse(&config.shortcuts.settings), quit: Shortcut::parse(&config.shortcuts.quit), command_palette: Shortcut::parse(&config.shortcuts.command_palette), quick_terminal: Shortcut::parse(&config.shortcuts.quick_terminal), quick_ssh: Shortcut::parse(&config.shortcuts.quick_ssh), }; let mut notifications = notifications::NotificationManager::default(); if theme_missing { notifications.add(missing_theme_notification( config.appearance.custom_theme_name.as_deref(), )); } Self { windows: HashMap::new(), window_order: Vec::new(), main_window: None, focused_window: None, drag: None, theme, saved_theme: theme, theme_choice: theme_choice.clone(), saved_theme_choice: theme_choice, custom_themes, theme_name_dialog: None, theme_signature: themes_signature(), shortcuts: shortcuts.clone(), saved_shortcuts: shortcuts, shortcut_capture: None, settings_section: SettingsSection::default(), pending_settings_section: None, show_start_tab, show_start_tab_draft: show_start_tab, fade_settings, fade_settings_draft: fade_settings, hide_tab_close, hide_tab_close_draft: hide_tab_close, show_new_session_button, show_new_session_button_draft: show_new_session_button, show_command_palette_description, show_command_palette_description_draft: show_command_palette_description, typography: typography.clone(), typography_draft: typography, typography_size_inputs, typography_open: false, typography_font_menu: None, command_palette_enabled, command_palette_enabled_draft: command_palette_enabled, advanced_open: false, colors, saved_colors: colors, custom_toasts, toast_colors, builtin_custom_toasts, builtin_toast_colors: builtin_toast_palette, open_color_picker: None, open_toast_color_picker: None, fade_animation: new_fade_animation(), hovered_tab: None, tab_close_fades: HashMap::new(), profile_filter: String::new(), profile_folders: load_profiles(), selected: None, checked: HashSet::new(), trash_open: false, trash_entries: Vec::new(), trash_checked: HashSet::new(), transfer: None, confirm_delete: false, confirm_purge_trash: false, hovered_folder: None, add_menu_open: false, folder_dialog: None, folder_rename: None, folder_menu: None, profile_dialog: None, dir_picker: None, next_blank_tab: 1, notifications, } } } #[derive(Debug, Clone)] enum Message { WindowEvent(window::Id, window::Event), PointerPressed(window::Id), PointerMoved(window::Id, Point), PointerReleased(window::Id), PointerLeft(window::Id), DragTick, ToggleMenu(window::Id), CloseMenu(window::Id), ToggleQuickAddMenu(window::Id), CloseQuickAddMenu(window::Id), QuickTerminal(window::Id), QuickSsh(window::Id), ToggleTabsSubmenu(window::Id), AddTab(window::Id), CloseActiveTab(window::Id), CloseOtherTabs(window::Id), ToggleCommandPalette(window::Id), CloseCommandPalette(window::Id), CommandPaletteChanged(window::Id, String), CommandPaletteUp(window::Id), CommandPaletteDown(window::Id), RunSelectedCommand(window::Id), RunCommand(window::Id, Command), SelectTheme(ThemeOption), OpenThemeNameDialog, ThemeNameChanged(String), ConfirmThemeName, CancelThemeName, SaveTheme, UndoTheme, ReloadThemes, SelectTab(window::Id, Tab), CloseTab(window::Id, Tab), SelectSettingsSection(SettingsSection), SetShowStartTab(bool), SetFadeSettings(bool), SetHideTabClose(bool), SetShowNewSessionButton(bool), SetShowCommandPaletteDescription(bool), ToggleTypography, ToggleTypographyFontMenu(TypographyLevel), TypographyFontSelected(TypographyLevel, String), TypographySizeSelected(TypographyLevel, SizeChoice), TypographySizeInputChanged(TypographyLevel, String), TypographySizeStep(TypographyLevel, i32), TypographyStyleToggled(TypographyLevel, TextStyleFlag), SetCommandPaletteEnabled(bool), ToggleAdvanced, SetCustomToasts(bool), OpenColorPicker(ColorOption), SubmitColor(ColorOption, Color), OpenToastColorPicker(ToastColorOption), SubmitToastColor(ToastColorOption, Color), CancelColorPicker, SaveSettings, UndoChanges, Notification(notifications::Message), NotificationTick(Instant), ShowNotificationDemo, Frame(Instant), ProfileFilterChanged(String), ClearProfileFilter, ToggleAddMenu, CloseAddMenu, ToggleFolder(usize), HoverFolder(Option), HoverTab { tab: Tab, hovered: bool, }, SelectProfile { folder: usize, profile: usize, }, EditProfile { folder: usize, profile: usize, }, ToggleChecked(Selection), DeselectAll, RestoreFromTrash, ToggleTrashChecked(usize), RestoreSelected, PurgeTrashSelected, ConfirmPurgeTrash, CancelPurgeTrash, CloseTrash, CopyChecked, MoveChecked, DeleteChecked, TransferFolderSelected(FolderChoice), ConfirmTransfer, CancelTransfer, ConfirmDelete, CancelDelete, OpenProfileDialog, ProfileNameChanged(String), ProfileKindSelected(ProfileKind), ProfileFolderSelected(FolderChoice), SessionEndSelected(SessionEnd), ProfileHostChanged(String), ProfilePortChanged(String), ProfileUsernameChanged(String), AuthMethodSelected(AuthMethod), ProfilePasswordChanged(String), TogglePasswordVisibility, ProfileStartPathChanged(String), ProfilePrivateKeyChanged(String), OpenProfileColorPicker, SubmitProfileColor(Color), CancelProfileColorPicker, OpenDirectoryPicker, OpenPrivateKeyPicker, DirPickerEnter(PathBuf), DirPickerSelect(PathBuf), DirPickerUp, ConfirmDirectoryPicker, CancelDirectoryPicker, ConfirmProfile, CancelProfile, OpenFolderDialog, FolderNameChanged(String), FolderParentSelected(FolderChoice), ConfirmFolder, CancelFolder, OpenFolderMenu(window::Id, usize), CloseFolderMenu, FolderMenuCopy(usize), FolderMenuMove(usize), FolderMenuDelete(usize), FolderMenuRename(usize), FolderRenameChanged(String), ConfirmFolderRename, CancelFolderRename, Ignore, OpenShortcutCapture(ShortcutAction), CancelShortcut, ClearShortcut(ShortcutAction), DefaultShortcut(ShortcutAction), ApplyShortcut, CaptureKey { key: keyboard::Key, modifiers: keyboard::Modifiers, }, TabsScrolled(window::Id, scrollable::Viewport), ScrollTabs(window::Id, mouse::ScrollDelta), ScrollTabsBy(window::Id, f32), Quit, } fn update(state: &mut Moorly, message: Message) -> Task { match message { Message::WindowEvent(window, event) => { return window_event(state, window, event); } Message::PointerPressed(window) => { state.focused_window = Some(window); let pending = if state.drag.is_some() { finish_drag(state, window) } else { Task::none() }; start_tab_drag(state, window); return pending; } Message::PointerMoved(window, position) => { if let Some(state) = state.windows.get_mut(&window) { state.pointer = Some(position); } if state .drag .as_ref() .is_some_and(|drag| drag.window == window) { let detach = position.y > MENUBAR_HEIGHT + 12.0; if let Some(drag) = state.drag.as_mut() { drag.pointer = position; drag.detach = detach; drag.moved = drag.moved || (position.x - drag.origin.x).abs() > 4.0 || (position.y - drag.origin.y).abs() > 4.0; } if state.drag.as_ref().is_some_and(|drag| drag.moved) && let Some(delta) = drag_scroll_delta(state) { return scroll_tabs_by(state, window, delta); } } } Message::PointerReleased(window) => return finish_drag(state, window), Message::PointerLeft(window) => { if let Some(drag) = state.drag.as_mut() && drag.window == window { drag.detach = true; } } Message::DragTick => { if let Some(delta) = drag_scroll_delta(state) { let window = state.drag.as_ref().unwrap().window; return scroll_tabs_by(state, window, delta); } } Message::ToggleMenu(window) => { if let Some(state) = state.windows.get_mut(&window) { state.menu_open = !state.menu_open; state.tabs_submenu_open = false; state.quick_menu_open = false; } } Message::CloseMenu(window) => { if let Some(state) = state.windows.get_mut(&window) { state.menu_open = false; state.tabs_submenu_open = false; } } Message::ToggleQuickAddMenu(window) => { if let Some(state) = state.windows.get_mut(&window) { state.quick_menu_open = !state.quick_menu_open; state.menu_open = false; state.tabs_submenu_open = false; } } Message::CloseQuickAddMenu(window) => { if let Some(state) = state.windows.get_mut(&window) { state.quick_menu_open = false; } } Message::QuickTerminal(window) | Message::QuickSsh(window) => { if let Some(state) = state.windows.get_mut(&window) { state.quick_menu_open = false; } } Message::ToggleTabsSubmenu(window) => { if let Some(state) = state.windows.get_mut(&window) { state.tabs_submenu_open = !state.tabs_submenu_open; } } Message::AddTab(window) => { let tab = Tab::Blank(state.next_blank_tab); state.next_blank_tab += 1; if let Some(state) = state.windows.get_mut(&window) { state.tabs.push(tab); state.active_tab = Some(tab); state.menu_open = false; state.tabs_submenu_open = false; } return scroll_tabs_to_end(state, window); } Message::CloseActiveTab(window) => { let active = state .windows .get(&window) .and_then(|state| state.active_tab); if let Some(tab) = active { close_tab(state, window, tab); } if let Some(state) = state.windows.get_mut(&window) { state.menu_open = false; state.tabs_submenu_open = false; } return Task::batch([ reveal_active_tab(state, window), close_window_if_empty(state, window), ]); } Message::CloseOtherTabs(window) => { let active = state .windows .get(&window) .and_then(|state| state.active_tab); if let Some(state) = state.windows.get_mut(&window) { match active { Some(active) => state.tabs.retain(|tab| *tab == active), None => state.tabs.clear(), } state.menu_open = false; state.tabs_submenu_open = false; } if active != Some(Tab::Settings) { state.settings_section = SettingsSection::default(); } return close_window_if_empty(state, window); } Message::ToggleCommandPalette(window) => { let Some(window_state) = state.windows.get_mut(&window) else { return Task::none(); }; if window_state.command_palette_open { close_command_palette(state, window); } else { window_state.command_palette_open = true; window_state.quick_menu_open = false; window_state.command_palette_query.clear(); window_state.command_palette_selected = 0; return operation::focus(window_state.command_palette_input.clone()); } } Message::CloseCommandPalette(window) => close_command_palette(state, window), Message::CommandPaletteChanged(window, query) => { if let Some(window_state) = state.windows.get_mut(&window) && window_state.command_palette_open { window_state.command_palette_query = query; window_state.command_palette_selected = 0; } } Message::CommandPaletteUp(window) => { if let Some(window_state) = state.windows.get_mut(&window) && window_state.command_palette_open { window_state.command_palette_selected = window_state.command_palette_selected.saturating_sub(1); } } Message::CommandPaletteDown(window) => { let query = state .windows .get(&window) .filter(|window_state| window_state.command_palette_open) .map(|window_state| window_state.command_palette_query.clone()); if let Some(query) = query { let last = Command::matching(state, window, &query) .len() .saturating_sub(1); if let Some(window_state) = state.windows.get_mut(&window) { window_state.command_palette_selected = (window_state.command_palette_selected + 1).min(last); } } } Message::RunSelectedCommand(window) => { let command = state .windows .get(&window) .filter(|window_state| window_state.command_palette_open) .and_then(|window_state| { Command::matching(state, window, &window_state.command_palette_query) .get(window_state.command_palette_selected) .copied() }); if let Some(command) = command { return update(state, Message::RunCommand(window, command)); } } Message::RunCommand(window, command) => { let tab = state .windows .get(&window) .and_then(|window_state| window_state.active_tab); close_command_palette(state, window); match command { Command::Settings => { return update(state, Message::SelectTab(window, Tab::Settings)); } Command::Close => { return update(state, Message::CloseActiveTab(window)); } Command::Left => { if let Some(target) = adjacent_tab(state, window, -1) { return update(state, Message::SelectTab(window, target)); } } Command::Right => { if let Some(target) = adjacent_tab(state, window, 1) { return update(state, Message::SelectTab(window, target)); } } Command::QuickTerminal => { return update(state, Message::QuickTerminal(window)); } Command::QuickSsh => { return update(state, Message::QuickSsh(window)); } Command::Move => { if let Some(tab) = tab { return detach_tab(state, window, tab, None); } } Command::MoveToWindow(destination) => { if let Some(tab) = tab { move_tab_to_window(state, window, destination, tab); return close_window_if_empty(state, window); } } Command::FocusWindow(id) => { state.focused_window = Some(id); return window::gain_focus(id); } Command::FocusTab(id, tab) => { state.focused_window = Some(id); return Task::batch([ update(state, Message::SelectTab(id, tab)), window::gain_focus(id), ]); } Command::SelectProfile { folder, profile } => { if let Some(folder_state) = state.profile_folders.get_mut(folder) && folder_state.profiles.get(profile).is_some() { folder_state.expanded = true; state.selected = Some(Selection::Profile { folder, profile }); return update(state, Message::SelectTab(window, Tab::Start)); } } Command::Exit => { return update(state, Message::Quit); } } } Message::SelectTheme(option) => { if let ThemeOption::Theme { choice, .. } = option { apply_theme_choice(state, choice); } } Message::OpenThemeNameDialog => { state.theme_name_dialog = Some(String::new()); return operation::focus(THEME_NAME_INPUT); } Message::ThemeNameChanged(value) => { if let Some(draft) = state.theme_name_dialog.as_mut() { *draft = value.chars().take(100).collect(); } } Message::ConfirmThemeName => { let Some(name) = state .theme_name_dialog .as_deref() .map(str::trim) .filter(|name| !name.is_empty()) .map(str::to_owned) else { return Task::none(); }; let based_on = match &state.theme_choice { ThemeChoice::BuiltIn(preference) => *preference, ThemeChoice::Custom { id, .. } => state .custom_themes .iter() .find(|theme| theme.id == *id) .map(|theme| theme.based_on) .unwrap_or(state.theme), }; let id = uuid::Uuid::new_v4().to_string(); if write_custom_theme( &id, &name, based_on, &state.colors, state.custom_toasts, &state.toast_colors, &state.typography, ) .is_none() { return Task::none(); } state.custom_themes = load_custom_themes(); state.theme_signature = themes_signature(); state.theme_name_dialog = None; state.theme_choice = ThemeChoice::Custom { id, name }; state.theme = based_on; // Creating a theme is a separate action, so it is persisted // immediately instead of waiting for the settings bar. state.saved_theme = based_on; state.saved_theme_choice = state.theme_choice.clone(); state.saved_colors = state.colors; save_config(state); } Message::CancelThemeName => state.theme_name_dialog = None, Message::SaveTheme => { if let ThemeChoice::Custom { id, name } = &state.theme_choice && let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id) { let based_on = theme.based_on; if write_custom_theme( id, name, based_on, &state.colors, state.custom_toasts, &state.toast_colors, &state.typography, ) .is_some() { if let Some(theme) = state.custom_themes.iter_mut().find(|theme| theme.id == *id) { theme.colors = state.colors; theme.custom_toasts = state.custom_toasts; theme.toast_colors = state.toast_colors; theme.typography = state.typography.clone(); } if matches!( &state.saved_theme_choice, ThemeChoice::Custom { id: saved, .. } if saved == id ) { state.saved_colors = state.colors; } state.theme_signature = themes_signature(); } } } Message::UndoTheme => { if let ThemeChoice::Custom { id, .. } = &state.theme_choice && let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id) { state.theme = theme.based_on; state.colors = theme.colors; state.custom_toasts = theme.custom_toasts; state.toast_colors = theme.toast_colors; state.typography = theme.typography.clone(); state.typography_draft = state.typography.clone(); state.typography_size_inputs = typography_size_inputs(&state.typography); if matches!( &state.saved_theme_choice, ThemeChoice::Custom { id: saved, .. } if saved == id ) { state.saved_theme = theme.based_on; state.saved_colors = theme.colors; } } } Message::ReloadThemes => { let signature = themes_signature(); if signature != state.theme_signature { let selected_id = match &state.theme_choice { ThemeChoice::Custom { id, .. } => Some(id.clone()), ThemeChoice::BuiltIn(_) => None, }; let old_theme = selected_id.as_ref().and_then(|id| { state .custom_themes .iter() .find(|theme| theme.id == *id) .cloned() }); let had_no_edits = old_theme .as_ref() .map(|theme| { theme.colors == state.colors && theme.custom_toasts == state.custom_toasts && theme.toast_colors == state.toast_colors && theme.typography == state.typography }) .unwrap_or(true); state.custom_themes = load_custom_themes(); state.theme_signature = signature; if let Some(id) = selected_id { if let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == id) { state.theme_choice = ThemeChoice::Custom { id: id.clone(), name: theme.name.clone(), }; if had_no_edits { state.theme = theme.based_on; state.colors = theme.colors; state.custom_toasts = theme.custom_toasts; state.toast_colors = theme.toast_colors; state.typography = theme.typography.clone(); state.typography_draft = state.typography.clone(); state.typography_size_inputs = typography_size_inputs(&state.typography); } if matches!( &state.saved_theme_choice, ThemeChoice::Custom { id: saved, .. } if saved == &id ) { state.saved_theme = theme.based_on; state.saved_colors = theme.colors; } } else { let missing_name = match &state.theme_choice { ThemeChoice::Custom { name, .. } => Some(name.clone()), ThemeChoice::BuiltIn(_) => None, }; state.theme = theme::Preference::Dark; state.theme_choice = ThemeChoice::BuiltIn(state.theme); state.colors = builtin_colors(state.theme); state.custom_toasts = state.builtin_custom_toasts; state.toast_colors = state.builtin_toast_colors; if matches!( &state.saved_theme_choice, ThemeChoice::Custom { id: saved, .. } if saved == &id ) { state.saved_theme = state.theme; state.saved_theme_choice = state.theme_choice.clone(); state.saved_colors = state.colors; } state .notifications .add(missing_theme_notification(missing_name.as_deref())); } } } } Message::SelectTab(window, tab) => { let Some(window_state) = state.windows.get_mut(&window) else { return Task::none(); }; let is_new = !window_state.tabs.contains(&tab); if is_new { window_state.tabs.push(tab); } window_state.active_tab = Some(tab); window_state.menu_open = false; window_state.tabs_submenu_open = false; window_state.quick_menu_open = false; state.folder_menu = None; // New tabs land at the end, so bring that end into view. if is_new { return scroll_tabs_to_end(state, window); } } Message::CloseTab(window, tab) => { let was_active = close_tab(state, window, tab); return Task::batch([ if was_active { reveal_active_tab(state, window) } else { Task::none() }, close_window_if_empty(state, window), ]); } Message::SelectSettingsSection(section) => { state.folder_menu = None; if section == state.settings_section && state.pending_settings_section.is_none() { // Already showing this section. } else if !state.fade_settings { state.settings_section = section; state.pending_settings_section = None; state.fade_animation = new_fade_animation(); } else if section == state.settings_section { // Clicking the current section cancels a fade to another one. state.pending_settings_section = None; state.fade_animation.go_mut(true, Instant::now()); } else { state.pending_settings_section = Some(section); state.fade_animation.go_mut(false, Instant::now()); } } Message::SetShowStartTab(value) => state.show_start_tab_draft = value, Message::SetFadeSettings(value) => state.fade_settings_draft = value, Message::SetHideTabClose(value) => state.hide_tab_close_draft = value, Message::SetShowNewSessionButton(value) => state.show_new_session_button_draft = value, Message::SetShowCommandPaletteDescription(value) => { state.show_command_palette_description_draft = value; } Message::ToggleTypography => state.typography_open = !state.typography_open, Message::ToggleTypographyFontMenu(level) => { state.typography_font_menu = (state.typography_font_menu != Some(level)).then_some(level); } Message::TypographyFontSelected(level, font) => { state.typography_draft.style_mut(level).font = font; state.typography_font_menu = None; } Message::TypographySizeSelected(level, choice) => { if let Some(size) = choice.size { state.typography_draft.style_mut(level).size = size; state.typography_size_inputs[level.index()] = format!("{size}"); } } Message::TypographySizeInputChanged(level, value) => { state.typography_size_inputs[level.index()] = value.clone(); if let Ok(size) = value.trim().parse::() && size > 0.0 { state.typography_draft.style_mut(level).size = size; } } Message::TypographySizeStep(level, delta) => { let size = (state.typography_draft.style(level).size + delta as f32).max(1.0); state.typography_draft.style_mut(level).size = size; state.typography_size_inputs[level.index()] = format!("{}", size); } Message::TypographyStyleToggled(level, flag) => { flag.toggle(state.typography_draft.style_mut(level)); } Message::SetCommandPaletteEnabled(value) => { state.command_palette_enabled_draft = value; } Message::ToggleAdvanced => state.advanced_open = !state.advanced_open, Message::SetCustomToasts(value) => { state.custom_toasts = value; if !value { state.open_toast_color_picker = None; } if matches!(state.theme_choice, ThemeChoice::BuiltIn(_)) { state.builtin_custom_toasts = value; save_config(state); } } Message::OpenColorPicker(option) => { state.open_color_picker = Some(option); state.open_toast_color_picker = None; } Message::SubmitColor(option, color) => { state.colors[option.index()] = color; state.open_color_picker = None; } Message::OpenToastColorPicker(option) => { state.open_toast_color_picker = Some(option); state.open_color_picker = None; } Message::SubmitToastColor(option, color) => { state.toast_colors[option.index()] = color; state.open_toast_color_picker = None; if matches!(state.theme_choice, ThemeChoice::BuiltIn(_)) { state.builtin_toast_colors = state.toast_colors; save_config(state); } } Message::CancelColorPicker => { state.open_color_picker = None; state.open_toast_color_picker = None; } Message::SaveSettings => { apply_settings(state); save_config(state); } Message::UndoChanges => undo_settings(state), Message::Notification(action) => match action { notifications::Message::Dismiss(id) => state.notifications.dismiss(id), }, Message::NotificationTick(now) => state.notifications.remove_expired(now), Message::ShowNotificationDemo => { use notifications::{Notification, NotificationKind}; state.notifications.add( Notification::new(NotificationKind::Info, "This is a timed info notification.") .title("Info"), ); state.notifications.add( Notification::new( NotificationKind::Success, "The operation completed successfully.", ) .title("Success") .timed(Duration::from_secs(8)), ); state.notifications.add( Notification::new( NotificationKind::Warning, "This warning stays until you dismiss it.", ) .title("Persistent warning") .persistent(), ); state.notifications.add( Notification::new( NotificationKind::Error, "This error is persistent as well.\nUse the close button to dismiss it.", ) .title("Persistent error") .persistent(), ); } Message::Frame(now) => { if !state.fade_animation.is_animating(now) && !state.fade_animation.value() && let Some(pending) = state.pending_settings_section.take() { state.settings_section = pending; state.fade_animation.go_mut(true, now); } } Message::ProfileFilterChanged(value) => state.profile_filter = value, Message::ClearProfileFilter => state.profile_filter.clear(), Message::ToggleAddMenu => state.add_menu_open = !state.add_menu_open, Message::CloseAddMenu => state.add_menu_open = false, Message::ToggleFolder(index) => { if let Some(folder) = state.profile_folders.get_mut(index) { folder.expanded = !folder.expanded; } state.selected = Some(Selection::Folder(index)); } Message::HoverFolder(folder) => state.hovered_folder = folder, Message::HoverTab { tab, hovered } => { let now = Instant::now(); if hovered { state.hovered_tab = Some(tab); for (key, animation) in &mut state.tab_close_fades { if *key != tab { animation.go_mut(false, now); } } state .tab_close_fades .entry(tab) .or_insert_with(new_tab_close_animation) .go_mut(true, now); } else if state.hovered_tab == Some(tab) { state.hovered_tab = None; for animation in state.tab_close_fades.values_mut() { animation.go_mut(false, now); } } } Message::SelectProfile { folder, profile } => { state.selected = Some(Selection::Profile { folder, profile }); } Message::EditProfile { folder, profile } => { let Some(existing) = state .profile_folders .get(folder) .and_then(|folder| folder.profiles.get(profile)) else { return Task::none(); }; state.selected = Some(Selection::Profile { folder, profile }); state.profile_dialog = Some(ProfileDraft::from_profile(folder, existing, profile)); return operation::focus(PROFILE_NAME_INPUT); } Message::ToggleChecked(item) => { if !state.checked.remove(&item) { state.checked.insert(item); } } Message::DeselectAll => state.checked.clear(), Message::RestoreFromTrash => { state.trash_entries = load_trash_entries(); state.trash_checked.clear(); state.trash_open = true; } Message::ToggleTrashChecked(index) => { if !state.trash_checked.remove(&index) { state.trash_checked.insert(index); } } Message::RestoreSelected => restore_trash_items(state), Message::PurgeTrashSelected => { if !state.trash_checked.is_empty() { state.confirm_purge_trash = true; } } Message::ConfirmPurgeTrash => purge_trash_items(state), Message::CancelPurgeTrash => state.confirm_purge_trash = false, Message::CloseTrash => { state.trash_open = false; state.trash_checked.clear(); state.confirm_purge_trash = false; } Message::CopyChecked => { if !state.checked.is_empty() { state.transfer = Some(TransferDialog { mode: TransferMode::Copy, destination: default_transfer_destination(state), }); } } Message::MoveChecked => { if !state.checked.is_empty() { state.transfer = Some(TransferDialog { mode: TransferMode::Move, destination: default_transfer_destination(state), }); } } Message::DeleteChecked => { if !state.checked.is_empty() { state.confirm_delete = true; } } Message::TransferFolderSelected(choice) => { if let Some(transfer) = state.transfer.as_mut() { transfer.destination = choice.index; } } Message::ConfirmTransfer => { if let Some(transfer) = state.transfer.clone() { apply_transfer(state, transfer.mode, transfer.destination); } } Message::CancelTransfer => state.transfer = None, Message::ConfirmDelete => apply_delete(state), Message::CancelDelete => state.confirm_delete = false, Message::OpenProfileDialog => { let folder = match state.selected { Some(Selection::Folder(index)) => index, Some(Selection::Profile { folder, .. }) => folder, None => state .profile_folders .iter() .position(|folder| folder.path == DEFAULT_PROFILE_FOLDER) .unwrap_or(0), }; state.add_menu_open = false; state.profile_dialog = Some(ProfileDraft::new(folder)); return operation::focus(PROFILE_NAME_INPUT); } Message::ProfileNameChanged(value) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.name = value.chars().take(150).collect(); } } Message::ProfileKindSelected(kind) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.kind = kind; } } Message::ProfileFolderSelected(choice) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.folder = choice.index; } } Message::SessionEndSelected(session_end) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.session_end = session_end; } } Message::ProfileHostChanged(value) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.host = value; } } Message::ProfilePortChanged(value) => { let valid = value.chars().all(|c| c.is_ascii_digit()) && (value.is_empty() || value.parse::().is_ok_and(|port| port <= 65534)); if valid { if let Some(draft) = state.profile_dialog.as_mut() { draft.port = value; } } } Message::ProfileUsernameChanged(value) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.username = value; } } Message::AuthMethodSelected(auth) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.auth = auth; } } Message::ProfilePasswordChanged(value) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.password = value; } } Message::TogglePasswordVisibility => { if let Some(draft) = state.profile_dialog.as_mut() { draft.password_visible = !draft.password_visible; } } Message::ProfileStartPathChanged(value) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.start_path = value; } } Message::ProfilePrivateKeyChanged(value) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.private_key = value; } } Message::OpenProfileColorPicker => { if let Some(draft) = state.profile_dialog.as_mut() { draft.color_picker_open = true; } } Message::SubmitProfileColor(color) => { if let Some(draft) = state.profile_dialog.as_mut() { draft.glyph_color = color; draft.color_picker_open = false; } } Message::CancelProfileColorPicker => { if let Some(draft) = state.profile_dialog.as_mut() { draft.color_picker_open = false; } } Message::OpenDirectoryPicker => { let path = state .profile_dialog .as_ref() .map(|draft| resolve_start_path(&draft.start_path)) .filter(|path| path.is_dir()) .unwrap_or_else(home_dir); state.dir_picker = Some(DirPicker::open(path, false, PickerTarget::StartPath)); } Message::OpenPrivateKeyPicker => { let typed = state .profile_dialog .as_ref() .map(|draft| resolve_start_path(&draft.private_key)) .unwrap_or_default(); let directory = if typed.is_dir() { typed } else { typed .parent() .filter(|path| path.is_dir()) .map(PathBuf::from) .unwrap_or_else(home_dir) }; state.dir_picker = Some(DirPicker::open(directory, true, PickerTarget::PrivateKey)); } Message::DirPickerEnter(path) => { if let Some(picker) = state.dir_picker.as_mut() { picker.navigate(path); } } Message::DirPickerSelect(path) => { if let Some(picker) = state.dir_picker.as_mut() { picker.selected = Some(path); } } Message::DirPickerUp => { if let Some(picker) = state.dir_picker.as_mut() { if let Some(parent) = picker.path.parent().map(PathBuf::from) { picker.navigate(parent); } } } Message::ConfirmDirectoryPicker => { if let Some(picker) = state.dir_picker.take() { let value = match picker.target { PickerTarget::StartPath => Some(picker.path.clone()), PickerTarget::PrivateKey => picker.selected.clone(), }; if let (Some(value), Some(draft)) = (value, state.profile_dialog.as_mut()) { let value = value.to_string_lossy().into_owned(); match picker.target { PickerTarget::StartPath => draft.start_path = value, PickerTarget::PrivateKey => draft.private_key = value, } } } } Message::CancelDirectoryPicker => state.dir_picker = None, Message::ConfirmProfile => { let Some(draft) = state.profile_dialog.clone() else { return Task::none(); }; if !draft.valid() { return Task::none(); } let folder_index = draft .folder .min(state.profile_folders.len().saturating_sub(1)); let Some((folder_path, folder_id)) = state .profile_folders .get(folder_index) .map(|folder| (folder.path.clone(), folder.id.clone())) else { return Task::none(); }; let existing_file = draft.editing.and_then(|(folder, profile)| { state .profile_folders .get(folder)? .profiles .get(profile) .and_then(|profile| profile.file.clone()) }); let mut profile = Profile { name: draft.name.trim().to_owned(), kind: draft.kind, session_end: draft.session_end, host: draft.host.trim().to_owned(), port: draft.port.clone(), username: draft.username.trim().to_owned(), auth: draft.auth, password: draft.password.clone(), start_path: draft.start_path.clone(), private_key: draft.private_key.clone(), glyph_color: draft.glyph_color, folder_id, file: existing_file, }; if let Some((old_folder, old_profile)) = draft.editing && let Some(folder) = state.profile_folders.get_mut(old_folder) && old_profile < folder.profiles.len() { folder.profiles.remove(old_profile); } if profile.file.is_some() { save_profile(&mut profile, &folder_path); } else { profile.file = write_profile(&profile, &folder_path); } let Some(folder) = state.profile_folders.get_mut(folder_index) else { return Task::none(); }; folder.profiles.push(profile); folder.expanded = true; state.selected = Some(Selection::Profile { folder: folder_index, profile: folder.profiles.len() - 1, }); save_folders(&state.profile_folders); state.profile_dialog = None; } Message::CancelProfile => state.profile_dialog = None, Message::OpenFolderDialog => { state.add_menu_open = false; let parent_index = match state.selected { Some(Selection::Folder(index)) => Some(index), Some(Selection::Profile { folder, .. }) => Some(folder), None => None, }; let parent = parent_index .and_then(|index| { state.profile_folders.get(index).map(|folder| FolderChoice { index, name: folder.path.clone(), }) }) .unwrap_or_else(root_folder_choice); state.folder_dialog = Some(FolderDraft::new(parent)); return operation::focus(FOLDER_NAME_INPUT); } Message::FolderNameChanged(value) => { if let Some(draft) = state.folder_dialog.as_mut() { draft.name = value; } } Message::FolderParentSelected(parent) => { if let Some(draft) = state.folder_dialog.as_mut() { draft.parent = parent; } } Message::ConfirmFolder => { let Some(draft) = state.folder_dialog.clone() else { return Task::none(); }; let name = draft.name.trim(); if name.is_empty() { return Task::none(); } let parent_path = if draft.parent.index == ROOT_FOLDER_INDEX { "" } else { state .profile_folders .get(draft.parent.index) .map(|folder| folder.path.as_str()) .unwrap_or("") }; let path = normalize_folder_path(&if parent_path.is_empty() { name.to_owned() } else { format!("{parent_path}/{name}") }); let index = ensure_folder(&mut state.profile_folders, &path); state.checked.clear(); state.selected = Some(Selection::Folder(index)); state.folder_dialog = None; save_folders(&state.profile_folders); } Message::CancelFolder => state.folder_dialog = None, Message::OpenFolderMenu(window, index) => { if state .profile_folders .get(index) .is_some_and(|folder| folder.path != DEFAULT_PROFILE_FOLDER) { let pointer = state .windows .get(&window) .and_then(|window_state| window_state.pointer) .unwrap_or(Point::new(0.0, 0.0)); state.folder_menu = Some((index, pointer)); state.selected = Some(Selection::Folder(index)); } } Message::CloseFolderMenu => state.folder_menu = None, Message::FolderMenuCopy(index) => { state.folder_menu = None; state.checked.clear(); state.checked.insert(Selection::Folder(index)); return update(state, Message::CopyChecked); } Message::FolderMenuMove(index) => { state.folder_menu = None; state.checked.clear(); state.checked.insert(Selection::Folder(index)); return update(state, Message::MoveChecked); } Message::FolderMenuDelete(index) => { state.folder_menu = None; state.checked.clear(); state.checked.insert(Selection::Folder(index)); return update(state, Message::DeleteChecked); } Message::FolderMenuRename(index) => { state.folder_menu = None; let Some(folder) = state.profile_folders.get(index) else { return Task::none(); }; state.folder_rename = Some((index, folder.name.clone())); return operation::focus(FOLDER_NAME_INPUT); } Message::FolderRenameChanged(value) => { if let Some((_, draft)) = state.folder_rename.as_mut() { *draft = value.chars().take(150).collect(); } } Message::ConfirmFolderRename => return rename_folder(state), Message::CancelFolderRename => state.folder_rename = None, Message::Ignore => {} Message::OpenShortcutCapture(action) => { state.shortcut_capture = Some(ShortcutCapture { action, candidate: None, error: None, }); } Message::CancelShortcut => state.shortcut_capture = None, Message::ClearShortcut(action) => { state.shortcuts.set(action, None); state.shortcut_capture = None; } Message::DefaultShortcut(action) => { state .shortcuts .set(action, Shortcuts::default().get(action).cloned()); state.shortcut_capture = None; } Message::ApplyShortcut => apply_shortcut(state), Message::CaptureKey { key, modifiers } => match key { keyboard::Key::Named(keyboard::key::Named::Escape) => { state.shortcut_capture = None; } keyboard::Key::Named(keyboard::key::Named::Enter) => apply_shortcut(state), keyboard::Key::Named( keyboard::key::Named::Control | keyboard::key::Named::Shift | keyboard::key::Named::Alt, ) => {} _ => { if let Some(capture) = state.shortcut_capture.as_mut() { match Shortcut::from_key(&key, modifiers) { Some(shortcut) => { capture.candidate = Some(shortcut); capture.error = None; } None => { capture.candidate = None; capture.error = Some("Use Ctrl or Alt plus a key.".to_owned()); } } } } }, Message::TabsScrolled(window, viewport) => { if let Some(window_state) = state.windows.get_mut(&window) { window_state.tab_offset = viewport.absolute_offset().x; } } Message::ScrollTabs(window, delta) => { let amount = match delta { mouse::ScrollDelta::Lines { y, .. } => y * 60.0, mouse::ScrollDelta::Pixels { x, y } => x + y, }; return scroll_tabs_by(state, window, amount); } Message::ScrollTabsBy(window, amount) => { return scroll_tabs_by(state, window, amount); } Message::Quit => std::process::exit(0), } Task::none() } fn close_command_palette(state: &mut Moorly, window: window::Id) { if let Some(window_state) = state.windows.get_mut(&window) { window_state.command_palette_open = false; window_state.command_palette_query.clear(); window_state.command_palette_selected = 0; } } /// Commits the captured shortcut if it is valid and unused. fn apply_shortcut(state: &mut Moorly) { let Some(capture) = state.shortcut_capture.as_ref() else { return; }; let action = capture.action; let Some(candidate) = capture.candidate.clone() else { if let Some(capture) = state.shortcut_capture.as_mut() { capture.error = Some("Press a key combination first.".to_owned()); } return; }; if let Some(name) = state.shortcuts.conflict(&candidate, action) { if let Some(capture) = state.shortcut_capture.as_mut() { capture.error = Some(format!("Already used by {name}.")); } return; } state.shortcuts.set(action, Some(candidate)); state.shortcut_capture = None; } fn window_event(state: &mut Moorly, window: window::Id, event: window::Event) -> Task { match event { window::Event::Opened { position, size } => { if let Some(window_state) = state.windows.get_mut(&window) { window_state.size = size; if position.is_some() { window_state.position = position; } } } window::Event::Moved(position) => { if let Some(window_state) = state.windows.get_mut(&window) { window_state.position = Some(position); } } window::Event::Resized(size) => { if let Some(window_state) = state.windows.get_mut(&window) { window_state.size = size; } } window::Event::Focused => state.focused_window = Some(window), window::Event::CloseRequested => { remove_window(state, window); if state.windows.is_empty() { return iced::exit(); } return window::close(window); } window::Event::Closed => { remove_window(state, window); if state.windows.is_empty() { return iced::exit(); } } _ => {} } Task::none() } fn remove_window(state: &mut Moorly, window: window::Id) { state.windows.remove(&window); state.window_order.retain(|id| *id != window); if state.main_window == Some(window) { state.main_window = None; } if state.focused_window == Some(window) { state.focused_window = state.window_order.first().copied(); } if state .drag .as_ref() .is_some_and(|drag| drag.window == window) { state.drag = None; } } /// Width the tab strip gets after the quick-add button, scroll buttons and /// hamburger. fn tab_strip_width(window_width: f32, show_new_session_button: bool) -> f32 { let quick_button = if show_new_session_button { HAMBURGER_WIDTH + TAB_SPACING } else { 0.0 }; (window_width - TAB_STRIP_LEFT - MENUBAR_RIGHT_PADDING - 2.0 * SCROLL_BUTTON_WIDTH - HAMBURGER_WIDTH - 3.0 * TAB_SPACING - quick_button) .max(0.0) } struct TabStripMetrics { viewport: f32, width: f32, step: f32, content: f32, offset: f32, } fn tab_strip_metrics(window_state: &WindowState, show_new_session_button: bool) -> TabStripMetrics { let viewport = tab_strip_width(window_state.size.width, show_new_session_button); let count = window_state.tabs.len(); let width = tab_width(viewport, count); let step = width + TAB_SPACING; let content = if count == 0 { 0.0 } else { step * count as f32 - TAB_SPACING }; let offset = window_state.tab_offset.min((content - viewport).max(0.0)); TabStripMetrics { viewport, width, step, content, offset, } } /// Index of the tab under `point`, if the point is inside the tab strip. fn tab_index_at(state: &Moorly, window: window::Id, point: Point) -> Option { let window_state = state.windows.get(&window)?; if window_state.tabs.is_empty() || point.y < 0.0 || point.y > MENUBAR_HEIGHT || point.x < TAB_STRIP_LEFT { return None; } let metrics = tab_strip_metrics(window_state, state.show_new_session_button); if metrics.viewport <= 0.0 || point.x > TAB_STRIP_LEFT + metrics.viewport { return None; } let relative = point.x - TAB_STRIP_LEFT + metrics.offset; if relative < 0.0 || relative > metrics.content { return None; } Some(((relative / metrics.step).floor() as usize).min(window_state.tabs.len() - 1)) } /// Gap the dragged tab would be inserted into: `0` is before the first tab, /// `tabs.len()` is after the last one. fn tab_gap_index(state: &Moorly, window: window::Id, x: f32) -> Option { let window_state = state.windows.get(&window)?; if window_state.tabs.is_empty() { return Some(0); } let metrics = tab_strip_metrics(window_state, state.show_new_session_button); let relative = x - TAB_STRIP_LEFT + metrics.offset; let mut gap = window_state.tabs.len(); for index in 0..window_state.tabs.len() { let midpoint = index as f32 * metrics.step + metrics.width / 2.0; if relative < midpoint { gap = index; break; } } Some(gap) } fn start_tab_drag(state: &mut Moorly, window: window::Id) { state.drag = None; let Some((pointer, menu_open)) = state .windows .get(&window) .map(|window_state| (window_state.pointer, window_state.menu_open)) else { return; }; if menu_open { return; } let Some(pointer) = pointer else { return; }; let Some(index) = tab_index_at(state, window, pointer) else { return; }; let Some(window_state) = state.windows.get(&window) else { return; }; state.drag = Some(TabDrag { window, tab: window_state.tabs[index], origin: pointer, pointer, moved: false, detach: false, }); } fn apply_tab_move(state: &mut Moorly, window: window::Id, tab: Tab, gap: usize) { let Some(window_state) = state.windows.get_mut(&window) else { return; }; let Some(current) = window_state.tabs.iter().position(|open| *open == tab) else { return; }; // Removing the tab collapses its own slot, so gaps after it shift left. let target = if current < gap { gap - 1 } else { gap }; if target == current { return; } window_state.tabs.remove(current); window_state.tabs.insert(target, tab); } /// Scroll delta for auto-scrolling while a tab is dragged near an edge. fn drag_scroll_delta(state: &Moorly) -> Option { let drag = state.drag.as_ref()?; if drag.detach || !drag.moved { return None; } let window_state = state.windows.get(&drag.window)?; let metrics = tab_strip_metrics(window_state, state.show_new_session_button); if window_state.tabs.is_empty() || metrics.viewport <= 0.0 || metrics.content <= metrics.viewport { return None; } let x = drag.pointer.x; let left = TAB_STRIP_LEFT; let right = left + metrics.viewport; if x < left + DRAG_EDGE { let amount = ((left + DRAG_EDGE - x) / DRAG_EDGE).clamp(0.0, 1.0); return Some(-DRAG_SCROLL_SPEED * amount); } if x > right - DRAG_EDGE { let amount = ((x - (right - DRAG_EDGE)) / DRAG_EDGE).clamp(0.0, 1.0); return Some(DRAG_SCROLL_SPEED * amount); } None } // ponytail: window geometry is enough for X11/Windows drops. Wayland does not // expose window positions, so there a drop only moves tabs when the release is // routed directly to the destination window. fn window_at(state: &Moorly, except: window::Id, point: Point) -> Option { state.windows.iter().find_map(|(id, window_state)| { if *id == except { return None; } let position = window_state.position?; Rectangle::new(position, window_state.size) .contains(point) .then_some(*id) }) } fn drop_targets(state: &Moorly, source: window::Id) -> Vec<(window::Id, String)> { state .window_order .iter() .filter(|id| **id != source && state.windows.contains_key(id)) .map(|id| (*id, window_title(state, *id))) .collect() } fn drop_panel_rect(window_state: &WindowState, count: usize) -> Rectangle { let width = DROP_PANEL_WIDTH.min((window_state.size.width - 24.0).max(120.0)); let height = DROP_PANEL_PADDING * 2.0 + DROP_HEADER_HEIGHT + count as f32 * (DROP_ROW_HEIGHT + DROP_ROW_GAP); let x = ((window_state.size.width - width) / 2.0).max(0.0); let y = MENUBAR_HEIGHT + 8.0; Rectangle::new(Point::new(x, y), Size::new(width, height)) } fn drop_target_index(state: &Moorly, source: window::Id, point: Point) -> Option { let window_state = state.windows.get(&source)?; let targets = drop_targets(state, source); if targets.is_empty() { return None; } let rect = drop_panel_rect(window_state, targets.len()); if !rect.contains(point) { return None; } let row_top = rect.y + DROP_PANEL_PADDING + DROP_HEADER_HEIGHT + DROP_ROW_GAP; if point.y < row_top { return None; } let index = ((point.y - row_top) / (DROP_ROW_HEIGHT + DROP_ROW_GAP)).floor() as usize; (index < targets.len()).then_some(index) } fn drop_target_at(state: &Moorly, source: window::Id, point: Point) -> Option { let index = drop_target_index(state, source, point)?; drop_targets(state, source).get(index).map(|(id, _)| *id) } fn move_tab_to_window(state: &mut Moorly, source: window::Id, destination: window::Id, tab: Tab) { let Some(source_state) = state.windows.get_mut(&source) else { return; }; let Some(index) = source_state.tabs.iter().position(|open| *open == tab) else { return; }; source_state.tabs.remove(index); if source_state.active_tab == Some(tab) { source_state.active_tab = source_state .tabs .get(index) .or_else(|| source_state.tabs.last()) .copied(); } if let Some(destination_state) = state.windows.get_mut(&destination) { if !destination_state.tabs.contains(&tab) { destination_state.tabs.push(tab); } destination_state.active_tab = Some(tab); } state.focused_window = Some(destination); } /// Moves a tab into a brand-new window positioned where it was dropped. fn detach_tab( state: &mut Moorly, source: window::Id, tab: Tab, global: Option, ) -> Task { let Some(source_state) = state.windows.get_mut(&source) else { return Task::none(); }; let Some(index) = source_state.tabs.iter().position(|open| *open == tab) else { return Task::none(); }; source_state.tabs.remove(index); if source_state.active_tab == Some(tab) { source_state.active_tab = source_state .tabs .get(index) .or_else(|| source_state.tabs.last()) .copied(); } let size = Size::new(900.0, 600.0); let position = global.map(|point| Point::new((point.x - 100.0).max(0.0), (point.y - 20.0).max(0.0))); let settings = window::Settings { size, position: position.map_or(window::Position::Default, window::Position::Specific), exit_on_close_request: false, ..window::Settings::default() }; let (id, open) = window::open(settings); state .windows .insert(id, WindowState::with_tab(tab, size, position)); state.window_order.push(id); state.focused_window = Some(id); Task::batch([ open.map(|_| Message::Ignore), close_window_if_empty(state, source), ]) } fn finish_drag(state: &mut Moorly, released_in: window::Id) -> Task { let Some(drag) = state.drag.take() else { return Task::none(); }; let source = drag.window; let tab = drag.tab; if !drag.moved || !state .windows .get(&source) .is_some_and(|window_state| window_state.tabs.contains(&tab)) { return Task::none(); } // Dropping directly into another window is the cross-window move path. if released_in != source && state.windows.contains_key(&released_in) { move_tab_to_window(state, source, released_in, tab); return close_window_if_empty(state, source); } let Some(window_state) = state.windows.get(&source) else { return Task::none(); }; let outside = drag.pointer.x < 0.0 || drag.pointer.y < 0.0 || drag.pointer.x > window_state.size.width || drag.pointer.y > window_state.size.height; // On Wayland the window under the pointer is unknowable, so the user can // drop onto the in-window target list instead. if (drag.detach || outside) && let Some(destination) = drop_target_at(state, source, drag.pointer) { move_tab_to_window(state, source, destination, tab); return close_window_if_empty(state, source); } let global = window_state .position .map(|position| Point::new(position.x + drag.pointer.x, position.y + drag.pointer.y)); if drag.detach || outside { if let Some(global) = global && let Some(destination) = window_at(state, source, global) { move_tab_to_window(state, source, destination, tab); return close_window_if_empty(state, source); } return detach_tab(state, source, tab, global); } if let Some(gap) = tab_gap_index(state, source, drag.pointer.x) { apply_tab_move(state, source, tab, gap); } Task::none() } fn close_window_if_empty(state: &mut Moorly, window: window::Id) -> Task { if !state .windows .get(&window) .is_some_and(|window_state| window_state.tabs.is_empty()) { return Task::none(); } remove_window(state, window); if state.windows.is_empty() { return iced::exit(); } window::close(window) } fn scroll_tabs_by(state: &Moorly, window: window::Id, x: f32) -> Task { let Some(window_state) = state.windows.get(&window) else { return Task::none(); }; operation::scroll_by( window_state.scroll_id.clone(), operation::AbsoluteOffset { x, y: 0.0 }, ) } fn scroll_tabs_to_end(state: &Moorly, window: window::Id) -> Task { let Some(window_state) = state.windows.get(&window) else { return Task::none(); }; operation::snap_to( window_state.scroll_id.clone(), operation::RelativeOffset::END, ) } /// Removes a tab and keeps the selection sensible: the next tab on the right /// takes over, falling back to the new last tab. Returns whether the active /// tab was the one closed. fn close_tab(state: &mut Moorly, window: window::Id, tab: Tab) -> bool { let was_active = { let Some(window_state) = state.windows.get_mut(&window) else { return false; }; let Some(index) = window_state.tabs.iter().position(|open| *open == tab) else { return false; }; let was_active = window_state.active_tab == Some(tab); window_state.tabs.remove(index); if was_active { window_state.active_tab = window_state .tabs .get(index) .or_else(|| window_state.tabs.last()) .copied(); } was_active }; // Drop the tab's page state along with the tab itself. if tab == Tab::Settings { state.settings_section = SettingsSection::default(); } was_active } /// Estimated scroll delta that brings the active tab into view, or `None` /// when it already is (or the strip does not overflow). fn tab_reveal_delta(state: &Moorly, window: window::Id) -> Option { let window_state = state.windows.get(&window)?; let index = window_state .active_tab .and_then(|active| window_state.tabs.iter().position(|tab| *tab == active))?; if window_state.tabs.is_empty() { return None; } let metrics = tab_strip_metrics(window_state, state.show_new_session_button); if metrics.viewport <= 0.0 || metrics.content <= metrics.viewport { return None; } let start = index as f32 * metrics.step; let visible_start = metrics.offset; let visible_end = metrics.offset + metrics.viewport; if start >= visible_start && start + metrics.width <= visible_end { return None; } let target = (start - (metrics.viewport - metrics.width) / 2.0).max(0.0); Some(target - metrics.offset) } fn reveal_active_tab(state: &Moorly, window: window::Id) -> Task { match tab_reveal_delta(state, window) { Some(delta) => scroll_tabs_by(state, window, delta), None => Task::none(), } } fn quick_add_button( open: bool, text_color: Color, window: window::Id, ) -> iced::widget::Button<'static, Message> { let glyph = if open { "+▴" } else { "+▾" }; button(text(glyph).size(14)) .on_press(Message::ToggleQuickAddMenu(window)) .width(HAMBURGER_WIDTH) .padding([2, 8]) .style(move |theme, status| theme::menubar_button(theme, status, text_color)) } /// Dropdown under the quick-add button. fn quick_add_menu(window: window::Id) -> Element<'static, Message> { let menu = container( column![ menu_item("Quick Terminal", None, Message::QuickTerminal(window)), menu_item("Quick SSH", None, Message::QuickSsh(window)), ] .spacing(4), ) .width(180) .padding(MENU_PADDING) .style(theme::menu); container(menu) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Start) .align_y(Alignment::Start) .padding(Padding { top: MENUBAR_HEIGHT, left: TAB_STRIP_LEFT, ..Padding::ZERO }) .into() } fn hamburger( open: bool, text_color: Color, window: window::Id, ) -> iced::widget::Button<'static, Message> { let icon: Element<'static, Message> = if open { stack![ text("☰").size(14), container(text("X").size(11).color(theme::DANGER)) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Start), ] .into() } else { text("☰").size(14).into() }; button(icon) .on_press(Message::ToggleMenu(window)) .width(HAMBURGER_WIDTH) .padding([2, 8]) .style(move |theme, status| theme::menubar_button(theme, status, text_color)) } /// Shortens a title to `MAX_TAB_TITLE` characters, ellipsizing the rest. fn fit_title(title: &str) -> String { if title.chars().count() <= MAX_TAB_TITLE { return title.to_owned(); } let mut fitted: String = title.chars().take(MAX_TAB_TITLE - 3).collect(); fitted.push_str("..."); fitted } /// Width that lets the strip show as many tabs as possible, between the /// minimum and maximum tab widths. fn tab_width(available: f32, count: usize) -> f32 { let count = count as f32; if count == 0.0 || available <= 0.0 { return TAB_MAX_WIDTH; } let available = available - TAB_SPACING * (count - 1.0); (available / count).clamp(TAB_MIN_WIDTH, TAB_MAX_WIDTH) } fn tab_shell( content: Element<'static, Message>, active: bool, width: f32, active_bg: Color, inactive_bg: Color, outline: Color, ) -> Element<'static, Message> { let tab = container(content) .width(width) .height(Length::Fill) .align_y(Alignment::Center) .style(move |theme| theme::tab(theme, active, active_bg, inactive_bg)); // Draw the active outline as three separate edges so there is no bottom // border to blend away. if active { let top = container(space::horizontal()) .width(Length::Fill) .height(1.0) .style(move |theme| theme::tab_outline(theme, outline)); let left = container(space::vertical()) .width(1.0) .height(Length::Fill) .style(move |theme| theme::tab_outline(theme, outline)); let right = container( container(space::vertical()) .width(1.0) .height(Length::Fill) .style(move |theme| theme::tab_outline(theme, outline)), ) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End); stack![tab, top, left, right].into() } else { tab.into() } } fn tab_view( window: window::Id, tab: Tab, active: bool, hide_close: bool, close_opacity: f32, width: f32, colors: [Color; 6], ) -> Element<'static, Message> { let title = tab.title(); let padding = Padding::new(10.0); let text_color = colors[ColorOption::Text.index()]; let active_bg = colors[ColorOption::MainBackground.index()]; let inactive_bg = colors[ColorOption::SidebarBackground.index()]; let outline = colors[ColorOption::ActiveTabOutline.index()]; let title_button = button( container(text(fit_title(&title)).size(15)) .width(Length::Fill) .align_x(Alignment::Center), ) .on_press(Message::SelectTab(window, tab)) .padding(padding) .width(Length::Fill) .clip(true) .style(move |theme, status| { let mut style = button::text(theme, status); style.text_color = if active { text_color } else { text_color.scale_alpha(0.6) }; style }); let close_icon = |padding: Padding| { button(text("×").size(15)) .on_press(Message::CloseTab(window, tab)) .padding(padding) .style(move |theme, status| { let mut style = button::text(theme, status); style.text_color = text_color; style.text_color.a = close_opacity; style }) }; let tab_element = if hide_close { let tab = tab_shell( title_button.into(), active, width, active_bg, inactive_bg, outline, ); if close_opacity <= 0.01 { tab } else { let close = container(close_icon(Padding::new(4.0))).style(move |_theme: &iced::Theme| { let mut background = if active { active_bg } else { inactive_bg }; background.a = close_opacity; container::Style { background: Some(background.into()), border: Border { color: Color::TRANSPARENT, width: 0.0, radius: 4.0.into(), }, ..container::Style::default() } }); let overlay = container(close) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Center) .padding(Padding::ZERO.right(12.0)); stack![tab, overlay] .width(width) .height(Length::Fill) .into() } } else { tab_shell( row![title_button, close_icon(Padding::new(10.0))] .spacing(0) .align_y(Alignment::Center) .into(), active, width, active_bg, inactive_bg, outline, ) }; let content = mouse_area(tab_element) .on_enter(Message::HoverTab { tab, hovered: true }) .on_exit(Message::HoverTab { tab, hovered: false, }); tooltip( content, container(text(title).size(11)).padding(4), tooltip::Position::Bottom, ) .into() } /// Floating copy of the dragged tab that follows the pointer. fn drag_ghost( state: &Moorly, window: window::Id, colors: [Color; 6], ) -> Option> { let drag = state .drag .as_ref() .filter(|drag| drag.window == window && drag.moved)?; let window_state = state.windows.get(&window)?; let x = (drag.pointer.x + 12.0).clamp(0.0, (window_state.size.width - DRAG_GHOST_WIDTH).max(0.0)); let y = (drag.pointer.y + 12.0).clamp(0.0, (window_state.size.height - DRAG_GHOST_HEIGHT).max(0.0)); let text_color = colors[ColorOption::Text.index()]; let mut background = colors[ColorOption::MainBackground.index()]; background.a = 0.9; let outline = colors[ColorOption::ActiveTabOutline.index()]; let ghost = container( text(fit_title(&drag.tab.title())) .size(14) .color(text_color), ) .width(DRAG_GHOST_WIDTH) .height(DRAG_GHOST_HEIGHT) .padding([5, 10]) .align_y(Alignment::Center) .style(move |_| container::Style { background: Some(background.into()), border: Border { color: outline, width: 1.0, radius: 6.0.into(), }, shadow: Shadow { color: Color::BLACK.scale_alpha(0.35), offset: Vector::new(0.0, 4.0), blur_radius: 10.0, }, text_color: Some(text_color), ..container::Style::default() }); Some( container(ghost) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Start) .align_y(Alignment::Start) .padding(Padding { top: y, left: x, right: 0.0, bottom: 0.0, }) .into(), ) } /// Vertical marker showing where the dragged tab will be inserted on release. fn tab_drop_bar( state: &Moorly, window: window::Id, colors: [Color; 6], ) -> Option> { let drag = state .drag .as_ref() .filter(|drag| drag.window == window && drag.moved && !drag.detach)?; let window_state = state.windows.get(&window)?; let outside = drag.pointer.x < 0.0 || drag.pointer.y < 0.0 || drag.pointer.x > window_state.size.width || drag.pointer.y > window_state.size.height; if outside || window_state.tabs.is_empty() { return None; } let metrics = tab_strip_metrics(window_state, state.show_new_session_button); if metrics.viewport <= 0.0 { return None; } let gap = tab_gap_index(state, window, drag.pointer.x)?; let content_x = if gap == 0 { 0.0 } else if gap >= window_state.tabs.len() { metrics.content } else { gap as f32 * metrics.step - TAB_SPACING / 2.0 }; let x = TAB_STRIP_LEFT + content_x - metrics.offset; if x < TAB_STRIP_LEFT || x > TAB_STRIP_LEFT + metrics.viewport { return None; } let accent = colors[ColorOption::Accent.index()]; let bar = container(space::horizontal()) .width(2.0) .height(MENUBAR_HEIGHT - 12.0) .style(move |_| container::Style { background: Some(accent.into()), border: Border { color: Color::TRANSPARENT, width: 0.0, radius: 1.0.into(), }, ..container::Style::default() }); Some( container(bar) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Start) .align_y(Alignment::Start) .padding(Padding { top: 6.0, left: x - 1.0, right: 0.0, bottom: 0.0, }) .into(), ) } /// In-window list of other windows to drop a dragged tab onto. This is the /// cross-window path that works on Wayland, where window positions are hidden. fn drop_panel( state: &Moorly, window: window::Id, colors: [Color; 6], ) -> Option> { let drag = state.drag.as_ref().filter(|drag| drag.window == window)?; let window_state = state.windows.get(&window)?; let outside = drag.pointer.x < 0.0 || drag.pointer.y < 0.0 || drag.pointer.x > window_state.size.width || drag.pointer.y > window_state.size.height; if !drag.detach && !outside { return None; } let targets = drop_targets(state, window); if targets.is_empty() { return None; } let rect = drop_panel_rect(window_state, targets.len()); let hovered = drop_target_index(state, window, drag.pointer); let text_color = colors[ColorOption::Text.index()]; let background = colors[ColorOption::SidebarBackground.index()]; let outline = colors[ColorOption::ActiveTabOutline.index()]; let accent = colors[ColorOption::Accent.index()]; let mut rows = column![].spacing(DROP_ROW_GAP).width(Length::Fill); for (index, (_, title)) in targets.iter().enumerate() { let selected = hovered == Some(index); rows = rows.push( container(text(fit_title(title)).size(13).color(text_color)) .width(Length::Fill) .height(DROP_ROW_HEIGHT) .padding([0, 8]) .align_y(Alignment::Center) .style(move |_| container::Style { background: Some( if selected { accent.scale_alpha(0.35) } else { background } .into(), ), border: Border { color: outline.scale_alpha(0.4), width: if selected { 1.0 } else { 0.0 }, radius: 4.0.into(), }, ..container::Style::default() }), ); } let header = container( text("Move to window") .size(12) .color(text_color.scale_alpha(0.7)), ) .width(Length::Fill) .height(DROP_HEADER_HEIGHT) .align_y(Alignment::Center) .padding([0, 8]); let panel = container(column![header, rows].spacing(DROP_ROW_GAP)) .width(rect.width) .padding(DROP_PANEL_PADDING) .style(move |_| container::Style { background: Some(background.into()), border: Border { color: outline, width: 1.0, radius: 8.0.into(), }, shadow: Shadow { color: Color::BLACK.scale_alpha(0.35), offset: Vector::new(0.0, 6.0), blur_radius: 16.0, }, text_color: Some(text_color), ..container::Style::default() }); Some( container(panel) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Start) .align_y(Alignment::Start) .padding(Padding { top: rect.y, left: rect.x, right: 0.0, bottom: 0.0, }) .into(), ) } /// Theme selection as a right-aligned drop list. fn theme_picker(state: &Moorly) -> Element<'_, Message> { let mut options = Vec::new(); let mut custom: Vec<&CustomTheme> = state.custom_themes.iter().collect(); custom.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase())); for theme in custom { let choice = ThemeChoice::Custom { id: theme.id.clone(), name: theme.name.clone(), }; options.push(ThemeOption::Theme { selected: choice == state.theme_choice, choice, }); } if !state.custom_themes.is_empty() { options.push(ThemeOption::Separator); } for preference in theme::Preference::ALL { let choice = ThemeChoice::BuiltIn(preference); options.push(ThemeOption::Theme { selected: choice == state.theme_choice, choice, }); } let selected = options .iter() .find(|option| matches!(option, ThemeOption::Theme { selected: true, .. })) .cloned(); row![ styled_text(&state.typography.h3, "Themes"), space::horizontal(), pick_list(options, selected, Message::SelectTheme).width(200), ] .spacing(8) .align_y(Alignment::Center) .into() } /// Collapsible custom typography controls for the four text styles. fn typography_panel(state: &Moorly) -> Element<'_, Message> { let glyph = if state.typography_open { "▴" } else { "▾" }; let header = button( row![ styled_text(&state.typography.h2, "Custom typography"), space::horizontal(), styled_text(&state.typography.h2, glyph), ] .width(Length::Fill) .align_y(Alignment::Center), ) .on_press(Message::ToggleTypography) .width(Length::Fill) .padding([6, 0]) .style(button::text); let mut panel = column![header].spacing(8).width(Length::Fill); if state.typography_open { let mut rows = column![].spacing(14).width(Length::Fill); for level in TypographyLevel::ALL { let style = state.typography_draft.style(level); let (size_choices, size_selected) = size_choices(level, style.size); let is_section = matches!(level, TypographyLevel::Terminal | TypographyLevel::Ssh); let heading: Element<'_, Message> = if is_section { styled_text(&state.typography.h2, level.label()) } else { styled_text( &state.typography.h3, format!("Typography - {}", level.label()), ) }; let mut style_row = row![].spacing(6); for flag in TextStyleFlag::ALL { style_row = style_row.push(typography_style_button( &state.typography.h3, level, flag, flag.enabled(style), )); } let group = column![ heading, styled_text(&state.typography.h3, "Font family"), font_family_picker(state, level), styled_text(&state.typography.h3, "Font Size"), row![ pick_list(size_choices, Some(size_selected), move |choice| { Message::TypographySizeSelected(level, choice) }) .width(Length::Fill), typography_size_box(state, level), ] .spacing(8) .align_y(Alignment::Center), style_row, ] .spacing(4); rows = rows.push(group); if level != TypographyLevel::Ssh { rows = rows.push(rule::horizontal(1)); } } panel = panel.push(rows); } container(panel) .width(Length::Fill) .padding(8) .style(theme::advanced_frame) .into() } fn font_family_choices(current: &str) -> Vec { let mut choices: Vec = available_font_families() .iter() .map(|family| (*family).to_owned()) .collect(); if !choices.iter().any(|choice| choice == current) { choices.push(current.to_owned()); } choices } fn font_family_picker(state: &Moorly, level: TypographyLevel) -> Element<'_, Message> { let current = state.typography_draft.style(level).font.clone(); let open = state.typography_font_menu == Some(level); let field = button( text(current.clone()) .font(font_for_name(¤t)) .size(state.typography.h3.size), ) .on_press(Message::ToggleTypographyFontMenu(level)) .width(Length::Fill) .padding([6, 10]) .style(|theme: &iced::Theme, status| { let mut button = button::text(theme, status); button.border = Border { color: theme::border_color(), width: 1.0, radius: 4.0.into(), }; button }); let mut column = column![field].spacing(4).width(Length::Fill); if open { let mut choices = column![].spacing(2).width(Length::Fill); for family in font_family_choices(¤t) { let selected = family == current; let label = text(family.clone()) .font(font_for_name(&family)) .size(state.typography.h3.size); choices = choices.push( button(label) .on_press(Message::TypographyFontSelected(level, family)) .width(Length::Fill) .padding([4, 8]) .style(move |theme, status| theme::selectable_row(theme, status, selected)), ); } let list = container( scrollable(choices) .height(Length::Fixed(180.0)) .width(Length::Fill), ) .width(Length::Fill) .padding(2) .style(|_theme: &iced::Theme| container::Style { border: Border { color: theme::border_color(), width: 1.0, radius: 4.0.into(), }, ..container::Style::default() }); column = column.push(list); } column.into() } fn typography_style_button( style: &TextStyle, level: TypographyLevel, flag: TextStyleFlag, active: bool, ) -> Element<'static, Message> { button(styled_text(style, flag.label())) .on_press(Message::TypographyStyleToggled(level, flag)) .padding([4, 8]) .style(move |theme, status| { let mut button = button::text(theme, status); button.border = Border { color: if active { theme::ACTIVE_TAB } else { Color::WHITE }, width: 1.0, radius: 5.0.into(), }; button }) .into() } /// Current size with `-` and `+` buttons embedded at the sides. fn typography_size_box(state: &Moorly, level: TypographyLevel) -> Element<'_, Message> { let field = text_input("", &state.typography_size_inputs[level.index()]) .on_input(move |value| Message::TypographySizeInputChanged(level, value)) .padding(Padding { top: 6.0, right: 26.0, bottom: 6.0, left: 26.0, }) .style(theme::filter_field) .width(Length::Fixed(116.0)); let step_style = |theme: &iced::Theme, status: button::Status| { let mut button = button::text(theme, status); if status == button::Status::Hovered { button.background = Some(theme.extended_palette().background.weak.color.into()); } button }; let minus = container( button(text("-").size(12)) .on_press(Message::TypographySizeStep(level, -1)) .width(Length::Fill) .height(Length::Fill) .padding(0) .style(step_style), ) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Start) .align_y(Alignment::Center) .padding(Padding::ZERO.left(0.0)) .max_width(26.0); let plus = container( button(text("+").size(12)) .on_press(Message::TypographySizeStep(level, 1)) .width(Length::Fill) .height(Length::Fill) .padding(0) .style(step_style), ) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Center) .padding(Padding::ZERO.right(0.0)) .max_width(26.0); let left_divider = container(container(rule::vertical(1)).height(Length::Fixed(18.0))) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Start) .align_y(Alignment::Center) .padding(Padding::ZERO.left(26.0)); let right_divider = container(container(rule::vertical(1)).height(Length::Fixed(18.0))) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Center) .padding(Padding::ZERO.right(26.0)); stack![field, minus, plus, left_divider, right_divider].into() } /// Collapsible area for future advanced appearance settings. fn advanced_panel(state: &Moorly) -> Element<'_, Message> { let glyph = if state.advanced_open { "▴" } else { "▾" }; let header = button( row![ styled_text(&state.typography.h2, "Advanced customization"), space::horizontal(), styled_text(&state.typography.h2, glyph), ] .width(Length::Fill) .align_y(Alignment::Center), ) .on_press(Message::ToggleAdvanced) .width(Length::Fill) .padding([6, 0]) .style(button::text); let mut panel = column![header].spacing(8).width(Length::Fill); if state.advanced_open { let mut rows = column![].spacing(8).width(Length::Fill); for option in ColorOption::ALL { rows = rows.push(color_row(state, option)); } rows = rows.push(rule::horizontal(1)); rows = rows.push( row![ styled_text(&state.typography.h3, "Custom toaster colors"), space::horizontal(), toggler(state.custom_toasts).on_toggle(Message::SetCustomToasts), ] .align_y(Alignment::Center), ); if state.custom_toasts { for option in ToastColorOption::ALL { rows = rows.push(toast_color_row(state, option)); } } let actions = match &state.theme_choice { ThemeChoice::BuiltIn(_) => row![ space::horizontal(), button("Save as new theme") .on_press(Message::OpenThemeNameDialog) .padding([6, 12]) .style(theme::positive_option), ], ThemeChoice::Custom { .. } => row![ space::horizontal(), button("Save") .on_press(Message::SaveTheme) .padding([6, 12]) .style(theme::positive_option), button("Save as new") .on_press(Message::OpenThemeNameDialog) .padding([6, 12]) .style(theme::outlined_option), button("Undo") .on_press(Message::UndoTheme) .padding([6, 12]) .style(theme::outlined_option), ], } .spacing(8) .align_y(Alignment::Center); rows = rows.push(actions); panel = panel.push(rows); } container(panel) .width(Length::Fill) .padding(8) .style(theme::advanced_frame) .into() } /// One theme color option: label on the left, clickable swatch on the right. fn color_row(state: &Moorly, option: ColorOption) -> Element<'_, Message> { color_swatch_row( &state.typography.h3, option.label(), state.colors[option.index()], state.open_color_picker == Some(option), Message::OpenColorPicker(option), move |color| Message::SubmitColor(option, color), ) } /// One custom-toast color option, using the same swatch control as the theme. fn toast_color_row(state: &Moorly, option: ToastColorOption) -> Element<'_, Message> { color_swatch_row( &state.typography.h3, option.label(), state.toast_colors[option.index()], state.open_toast_color_picker == Some(option), Message::OpenToastColorPicker(option), move |color| Message::SubmitToastColor(option, color), ) } fn color_swatch_row<'a>( style: &'a TextStyle, label: &'static str, color: Color, open: bool, on_open: Message, on_submit: impl Fn(Color) -> Message + 'static, ) -> Element<'a, Message> { let swatch = container(space::horizontal()) .width(24) .height(24) .style(move |_| container::Style { background: Some(color.into()), border: Border { color: theme::border_color(), width: 1.0, radius: 3.0.into(), }, ..container::Style::default() }); let button = button(swatch) .on_press(on_open) .padding(3) .style(button::text); let picker = iced_aw::color_picker(open, color, button, Message::CancelColorPicker, on_submit); row![styled_text(style, label), space::horizontal(), picker] .align_y(Alignment::Center) .into() } /// Shortcut bindings list. fn shortcuts_panel(state: &Moorly) -> Element<'_, Message> { let mut panel = column![ shortcut_row( &state.typography.h3, ShortcutAction::Settings, state.shortcuts.get(ShortcutAction::Settings), ), shortcut_row( &state.typography.h3, ShortcutAction::Quit, state.shortcuts.get(ShortcutAction::Quit) ), shortcut_row( &state.typography.h3, ShortcutAction::CommandPalette, state.shortcuts.get(ShortcutAction::CommandPalette), ), shortcut_row( &state.typography.h3, ShortcutAction::QuickTerminal, state.shortcuts.get(ShortcutAction::QuickTerminal), ), shortcut_row( &state.typography.h3, ShortcutAction::QuickSsh, state.shortcuts.get(ShortcutAction::QuickSsh), ), ] .spacing(8); match &state.shortcut_capture { Some(capture) => panel = panel.push(shortcut_capture_panel(capture)), None => { panel = panel.push(text("Press ... to change a shortcut.").size(12)); } } panel.into() } /// One read-only binding row with buttons to clear or rebind it. fn shortcut_row( style: &TextStyle, action: ShortcutAction, shortcut: Option<&Shortcut>, ) -> Element<'static, Message> { let value = shortcut.map(ToString::to_string).unwrap_or_default(); // No `on_input`: the field only displays the binding. let field = text_input("None", &value).width(180).padding(6); row![ container(styled_text(style, action.label())).width(120), field, button("Default") .on_press(Message::DefaultShortcut(action)) .style(theme::outlined_option), button("None") .on_press(Message::ClearShortcut(action)) .style(theme::outlined_option), button("...") .on_press(Message::OpenShortcutCapture(action)) .style(theme::outlined_option), ] .spacing(8) .align_y(Alignment::Center) .into() } /// Popover shown while a new shortcut is being recorded. fn shortcut_capture_panel(capture: &ShortcutCapture) -> Element<'_, Message> { let preview = capture .candidate .as_ref() .map(ToString::to_string) .unwrap_or_else(|| "Press a key combination".to_owned()); let mut panel = column![ text(format!( "Enter a new shortcut for {}", capture.action.label() )) .size(12), container(text(preview).size(16)) .width(Length::Fill) .padding([6, 10]) .style(theme::settings_frame), ] .spacing(6); if let Some(error) = &capture.error { panel = panel.push(text(error).size(12).color(theme::DANGER)); } panel = panel.push( row![ button("Apply") .on_press(Message::ApplyShortcut) .style(theme::outlined_option), button("Cancel") .on_press(Message::CancelShortcut) .style(theme::outlined_option), ] .spacing(6), ); container(panel) .width(280) .padding(10) .style(theme::menu) .into() } fn profile_action_button<'a>( glyph: &'a str, tip: &'a str, message: Message, enabled: bool, danger: bool, ) -> Element<'a, Message> { let glyph = text(glyph).size(16); let glyph = if danger { glyph.color(theme::DANGER.scale_alpha(if enabled { 1.0 } else { 0.4 })) } else { glyph }; let button = button(glyph) .on_press_maybe(enabled.then_some(message)) .padding([6, 10]) .style(theme::outlined_option); tooltip( button, container(text(tip).size(11)).padding(4), tooltip::Position::Top, ) .into() } fn profiles_panel(state: &Moorly, window: window::Id, show_add: bool) -> Element<'_, Message> { let field = text_input("Filter", &state.profile_filter) .on_input(Message::ProfileFilterChanged) .padding(Padding { top: 6.0, right: 32.0, bottom: 6.0, left: 28.0, }) .style(theme::filter_field) .width(Length::Fill); let search = container(text("⌕").size(24)) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Start) .align_y(Alignment::Center) .padding(Padding::ZERO.left(9.0)); let mut filter = stack![field, search].width(Length::Fill); if !state.profile_filter.is_empty() { let clear = container( button(text("✕").size(15)) .on_press(Message::ClearProfileFilter) .padding([2, 4]) .style(button::text), ) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Center) .padding(Padding::ZERO.right(6.0)); filter = filter.push(clear); } let add_button = button( row![text("+").size(16), text("Add"), text("▾").size(12)] .spacing(6) .align_y(Alignment::Center), ) .on_press(Message::ToggleAddMenu) .padding([6, 10]) .style(theme::outlined_option); let filter_row = if show_add { row![filter, add_button] .spacing(12) .align_y(Alignment::Center) .width(Length::Fill) } else { row![filter].width(Length::Fill) }; let has_checked = !state.checked.is_empty(); let actions = row![ profile_action_button( "✕", "Deselect all", Message::DeselectAll, has_checked, false ), profile_action_button("⧉", "Copy to", Message::CopyChecked, has_checked, false), profile_action_button("➜", "Move to", Message::MoveChecked, has_checked, false), profile_action_button("🗑", "Delete", Message::DeleteChecked, has_checked, true), space::horizontal(), profile_action_button( "🗑↗", "Restore from trash", Message::RestoreFromTrash, true, false ), ] .spacing(6) .width(Length::Fill); let mut list = column![].width(Length::Fill); let mut first_visible = true; for (index, folder) in state.profile_folders.iter().enumerate() { if !folder_visible(&state.profile_folders, index) { continue; } if !first_visible { list = list.push(rule::horizontal(1)); } first_visible = false; list = list.push(profile_folder_row( index, folder, state.selected, &state.checked, state.hovered_folder, window, show_add, )); } let list = container(scrollable(list).width(Length::Fill).height(Length::Fill)) .width(Length::Fill) .height(Length::Fill) .style(theme::settings_frame); let base = column![filter_row] .spacing(12) .width(Length::Fill) .height(Length::Fill); let base = if show_add { base.push(actions) } else { base }; let base = base.push(list); let dialog_open = state.folder_dialog.is_some() || state.folder_rename.is_some() || state.profile_dialog.is_some() || state.transfer.is_some() || state.trash_open || state.confirm_delete || state.confirm_purge_trash || state.dir_picker.is_some(); if !show_add && !dialog_open { return stack![base].into(); } if !state.add_menu_open && !dialog_open { return stack![base].into(); } // Clicking anywhere outside the open layer dismisses it. let backdrop = mouse_area( container(space::horizontal()) .width(Length::Fill) .height(Length::Fill), ) .on_press(if state.dir_picker.is_some() { Message::CancelDirectoryPicker } else if state.confirm_purge_trash { Message::CancelPurgeTrash } else if state.trash_open { Message::CloseTrash } else if state.folder_dialog.is_some() { Message::CancelFolder } else if state.folder_rename.is_some() { Message::CancelFolderRename } else if state.transfer.is_some() { Message::CancelTransfer } else if state.confirm_delete { Message::CancelDelete } else if state.profile_dialog.is_some() { Message::CancelProfile } else { Message::CloseAddMenu }); let mut layers = stack![base, backdrop]; if show_add && state.add_menu_open { let menu = container( column![ button( row![text("👤").size(14), text("Profile")] .spacing(8) .align_y(Alignment::Center), ) .on_press(Message::OpenProfileDialog) .width(Length::Fill) .padding([6, 10]) .style(button::text), button( row![text("📁").size(14), text("Folder")] .spacing(8) .align_y(Alignment::Center), ) .on_press(Message::OpenFolderDialog) .width(Length::Fill) .padding([6, 10]) .style(button::text), ] .width(Length::Fill), ) .width(120) .padding(4) .style(theme::menu); // ponytail: fixed offset under the filter row; keep in sync with its height. let menu_layer = container(menu) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Start) .padding(Padding::ZERO.top(44.0)); layers = layers.push(menu_layer); } if let Some(draft) = &state.folder_dialog { let choices = folder_dialog_choices(&state.profile_folders); let selected = choices .iter() .find(|choice| choice.index == draft.parent.index) .cloned() .unwrap_or_else(|| draft.parent.clone()); let dialog = container( column![ text("New folder").size(14), text_input("Folder name", &draft.name) .id(FOLDER_NAME_INPUT) .on_input(Message::FolderNameChanged) .on_submit(Message::ConfirmFolder) .padding(6) .style(theme::filter_field) .width(Length::Fill), column![ text("Parent folder").size(12), pick_list(choices, Some(selected), Message::FolderParentSelected) .width(Length::Fill), ] .spacing(4), text("Use / to nest folders, e.g. Work/Production").size(11), row![ space::horizontal(), button("Cancel") .on_press(Message::CancelFolder) .style(theme::danger_option), button("Add") .on_press_maybe( (!draft.name.trim().is_empty()).then_some(Message::ConfirmFolder) ) .style(theme::positive_option), ] .spacing(8), ] .spacing(10) .width(Length::Fill), ) .width(260) .padding(12) .style(theme::menu); // Swallow clicks on the dialog surface so only the backdrop outside it // dismisses the dialog. let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); layers = layers.push(dialog_layer); } if let Some((_, draft)) = &state.folder_rename { let dialog = container( column![ text("Rename folder").size(14), text_input("Folder name", draft) .id(FOLDER_NAME_INPUT) .on_input(Message::FolderRenameChanged) .on_submit(Message::ConfirmFolderRename) .padding(6) .style(theme::filter_field) .width(Length::Fill), row![ space::horizontal(), button("Cancel") .on_press(Message::CancelFolderRename) .style(theme::danger_option), button("Rename") .on_press_maybe( (!draft.trim().is_empty()).then_some(Message::ConfirmFolderRename) ) .style(theme::positive_option), ] .spacing(8), ] .spacing(10) .width(Length::Fill), ) .width(280) .padding(12) .style(theme::menu); let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); layers = layers.push(dialog_layer); } if state.trash_open { let dialog = trash_dialog_view(state); let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); layers = layers.push(dialog_layer); } if state.confirm_purge_trash { let dialog = container( column![ text("Delete selected items permanently?").size(14), text(format!( "{} selected item(s) will be permanently deleted. This cannot be undone.", state.trash_checked.len() )) .size(12), row![ space::horizontal(), button("Cancel") .on_press(Message::CancelPurgeTrash) .style(theme::outlined_option), button("Delete permanently") .on_press(Message::ConfirmPurgeTrash) .style(theme::danger_option), ] .spacing(8), ] .spacing(10) .width(Length::Fill), ) .width(400) .padding(12) .style(theme::menu); let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); layers = layers.push(dialog_layer); } if let Some(transfer) = &state.transfer { let dialog = transfer_dialog_view(transfer, state); let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); layers = layers.push(dialog_layer); } if state.confirm_delete { let dialog = container( column![ text("Delete selected items?").size(14), text(format!( "{} selected item(s) will be moved to the trash and can be restored later.", state.checked.len() )) .size(12), row![ space::horizontal(), button("Cancel") .on_press(Message::CancelDelete) .style(theme::outlined_option), button("Delete") .on_press(Message::ConfirmDelete) .style(theme::danger_option), ] .spacing(8), ] .spacing(10) .width(Length::Fill), ) .width(320) .padding(12) .style(theme::menu); let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); layers = layers.push(dialog_layer); } if let Some(draft) = &state.profile_dialog { let dialog = profile_dialog_view(draft, &state.profile_folders); let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); layers = layers.push(dialog_layer); } if let Some(picker) = &state.dir_picker { let dialog = directory_picker_view(picker); let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); layers = layers.push(dialog_layer); } layers.into() } /// Folder/file browser used by the Terminal start path and SSH private key. fn directory_picker_view(picker: &DirPicker) -> Element<'_, Message> { let mut entries = column![].width(Length::Fill); if picker.path.parent().is_some() { entries = entries.push( button(row![text("📁").size(14), text("..")].spacing(8)) .on_press(Message::DirPickerUp) .width(Length::Fill) .padding([6, 8]) .style(button::text), ); } for path in &picker.entries { let is_dir = path.is_dir(); let name = path .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| path.display().to_string()); let glyph = if is_dir { "📁" } else { "📄" }; let message = if is_dir { Message::DirPickerEnter(path.clone()) } else { Message::DirPickerSelect(path.clone()) }; let selected = picker.selected.as_ref() == Some(path); entries = entries.push( button( row![text(glyph).size(14), text(name)] .spacing(8) .align_y(Alignment::Center), ) .on_press(message) .width(Length::Fill) .padding([6, 8]) .style(move |theme, status| theme::selectable_row(theme, status, selected)), ); } let listing = container(scrollable(entries).width(Length::Fill).height(Length::Fill)) .width(Length::Fill) .height(240) .style(theme::settings_frame); let title = if picker.files { "Select private key" } else { "Select folder" }; let mut content = column![ text(title).size(16), text(picker.path.display().to_string()).size(12), listing, ] .spacing(10) .width(Length::Fill); if let Some(selected) = &picker.selected { content = content.push(text(selected.display().to_string()).size(12)); } if let Some(error) = &picker.error { content = content.push(text(error).size(12).color(theme::DANGER)); } content = content.push( row![ space::horizontal(), button("Cancel") .on_press(Message::CancelDirectoryPicker) .style(theme::danger_option), button("Select") .on_press_maybe( picker .can_confirm() .then_some(Message::ConfirmDirectoryPicker) ) .style(theme::positive_option), ] .spacing(8), ); container(content) .width(520) .padding(16) .style(theme::menu) .into() } /// The add-profile dialog: details on the left, type-specific view on the right. /// Dialog listing everything currently in the `.trash` folder. fn trash_dialog_view(state: &Moorly) -> Element<'_, Message> { let selected = !state.trash_checked.is_empty(); let header = row![ button("Restore selected") .on_press_maybe(selected.then_some(Message::RestoreSelected)) .style(theme::positive_option), button("Delete selected permanently") .on_press_maybe(selected.then_some(Message::PurgeTrashSelected)) .style(theme::danger_option), space::horizontal(), button("Close") .on_press(Message::CloseTrash) .style(theme::outlined_option), ] .spacing(8) .width(Length::Fill); let columns = row![ text("Name").size(11).width(Length::Fixed(200.0)), text("Previous path").size(11).width(Length::Fixed(220.0)), text("Deleted").size(11).width(Length::Fixed(160.0)), ] .spacing(8) .padding([4, 0]); let mut rows = column![columns].spacing(2).width(Length::Fill); for (index, entry) in state.trash_entries.iter().enumerate() { let checked = state.trash_checked.contains(&index); let glyph = if entry.is_folder() { "🗀\u{fe0e}" } else { "👤" }; let previous_path = if entry.previous_path().is_empty() { "—" } else { entry.previous_path() }; rows = rows.push( row![ checkbox(checked) .size(16) .on_toggle(move |_| Message::ToggleTrashChecked(index)), container( row![text(glyph).size(13), text(entry.name()).size(13)] .spacing(6) .align_y(Alignment::Center) ) .width(Length::Fixed(200.0)), text(previous_path).size(12).width(Length::Fixed(220.0)), text(entry.deleted()).size(12).width(Length::Fixed(160.0)), ] .spacing(8) .align_y(Alignment::Center) .padding([4, 0]), ); } if state.trash_entries.is_empty() { rows = rows.push(container(text("Trash is empty.").size(13)).padding([8, 0])); } let listing = container(scrollable(rows).width(Length::Fill).height(Length::Fill)) .width(Length::Fill) .height(360) .style(theme::settings_frame); container( column![styled_text(&state.typography.h2, "Trash"), header, listing] .spacing(10) .width(Length::Fill), ) .width(720) .padding(16) .style(theme::menu) .into() } /// Folder picker used by the "Copy to" and "Move to" actions. fn transfer_choices(state: &Moorly) -> Vec { let roots = checked_folder_roots(state); let individual = checked_profile_indices(state, &roots); let mut choices: Vec = state .profile_folders .iter() .enumerate() .filter(|(_, folder)| !roots.iter().any(|root| is_folder_under(&folder.path, root))) .map(|(index, folder)| FolderChoice { index, name: folder.path.clone(), }) .collect(); if !roots.is_empty() && individual.is_empty() && roots.iter().any(|root| root.contains('/')) { choices.insert( 0, FolderChoice { index: ROOT_FOLDER_INDEX, name: "Root".to_owned(), }, ); } choices } fn transfer_dialog_view<'a>(transfer: &TransferDialog, state: &'a Moorly) -> Element<'a, Message> { let choices = transfer_choices(state); let selected = choices .iter() .find(|choice| choice.index == transfer.destination) .cloned(); container( column![ text(transfer.mode.label()).size(14), pick_list(choices, selected, Message::TransferFolderSelected).width(Length::Fill), row![ space::horizontal(), button("Cancel") .on_press(Message::CancelTransfer) .style(theme::outlined_option), button(transfer.mode.action()) .on_press(Message::ConfirmTransfer) .style(theme::positive_option), ] .spacing(8), ] .spacing(10) .width(Length::Fill), ) .width(320) .padding(12) .style(theme::menu) .into() } fn profile_dialog_view<'a>( draft: &'a ProfileDraft, folders: &'a [ProfileFolder], ) -> Element<'a, Message> { let title = if draft.editing.is_some() { "Edit profile" } else if draft.name.trim().is_empty() { "New profile" } else { draft.name.as_str() }; let choices: Vec = folders .iter() .enumerate() .map(|(index, folder)| FolderChoice { index, name: folder.path.clone(), }) .collect(); let selected_folder = choices.get(draft.folder).cloned(); let swatch = container(space::horizontal()) .width(24) .height(24) .style(move |_| container::Style { background: Some(draft.glyph_color.into()), border: Border { color: theme::border_color(), width: 1.0, radius: 3.0.into(), }, ..container::Style::default() }); let swatch_button = button(swatch) .on_press(Message::OpenProfileColorPicker) .padding(3) .style(button::text); let color_picker = iced_aw::color_picker( draft.color_picker_open, draft.glyph_color, swatch_button, Message::CancelProfileColorPicker, Message::SubmitProfileColor, ); let left = column![ text(title).size(18), column![ text("Name").size(12), text_input("Profile name", &draft.name) .id(PROFILE_NAME_INPUT) .on_input(Message::ProfileNameChanged) .padding(6) .style(theme::filter_field) .width(Length::Fill), ] .spacing(4), column![ text("Folder").size(12), pick_list(choices, selected_folder, Message::ProfileFolderSelected).width(Length::Fill), ] .spacing(4), row![text("Glyph color"), space::horizontal(), color_picker].align_y(Alignment::Center), row![ column![ text("When a session ends").size(13), text("Only close the tab when session is explicitly terminated").size(10), ] .spacing(2) .width(Length::Fill), pick_list( SessionEnd::ALL, Some(draft.session_end), Message::SessionEndSelected, ) .width(110), ] .spacing(10) .align_y(Alignment::Center), ] .spacing(14) .width(260); let mut kind_picker = row![].spacing(6); for kind in ProfileKind::ALL { let item = button(text(kind.label())) .on_press(Message::ProfileKindSelected(kind)) .padding([6, 10]); kind_picker = kind_picker.push(if kind == draft.kind { item.style(theme::selected_option) } else { item.style(theme::outlined_option) }); } let right = column![kind_picker, profile_kind_view(draft)] .spacing(14) .width(Length::Fill); let body = row![left, right] .spacing(24) .align_y(Alignment::Start) .width(Length::Fill); let buttons = row![ space::horizontal(), button("Cancel") .on_press(Message::CancelProfile) .style(theme::danger_option), button(if draft.editing.is_some() { "Save" } else { "Add" }) .on_press_maybe(draft.valid().then_some(Message::ConfirmProfile)) .style(theme::positive_option), ] .spacing(8); container(column![body, buttons].spacing(16).width(Length::Fill)) .width(720) .padding(16) .style(theme::menu) .into() } /// Right-hand side of the profile dialog for the selected profile type. fn profile_kind_view(draft: &ProfileDraft) -> Element<'_, Message> { match draft.kind { ProfileKind::Terminal => { let field = text_input("Start path", &draft.start_path) .on_input(Message::ProfileStartPathChanged) .padding(Padding { top: 6.0, right: 40.0, bottom: 6.0, left: 8.0, }) .style(theme::filter_field) .width(Length::Fill); let browse = container( button("...") .on_press(Message::OpenDirectoryPicker) .padding([2, 6]) .style(|theme, status| theme::selectable_row(theme, status, false)), ) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Center) .padding(Padding::ZERO.right(6.0)); column![ text("Terminal").size(18), column![ text("Start path").size(12), stack![field, browse].width(Length::Fill), ] .spacing(4), ] .spacing(12) .into() } ProfileKind::PowerShell => text("PowerShell").size(18).into(), ProfileKind::Ssh => { let host_port = row![ column![ text("Host").size(12), text_input("Hostname or IP", &draft.host) .on_input(Message::ProfileHostChanged) .padding(6) .style(theme::filter_field) .width(Length::Fill), ] .spacing(4) .width(292), space::horizontal(), column![ text("Port").size(12), text_input("22", &draft.port) .on_input(Message::ProfilePortChanged) .padding(6) .style(theme::filter_field) .width(Length::Fill), ] .spacing(4) .width(64), ] .spacing(12); let username = column![ text("Username").size(12), text_input("Username", &draft.username) .on_input(Message::ProfileUsernameChanged) .padding(6) .style(theme::filter_field) .width(Length::Fill), ] .spacing(4) .width(292); let mut auth_buttons = row![].spacing(6).width(Length::Fill); for auth in AuthMethod::ALL { let item = button( column![text(auth.glyph()).size(18), text(auth.label()).size(11),] .spacing(2) .align_x(Alignment::Center) .width(Length::Fill), ) .on_press(Message::AuthMethodSelected(auth)) .width(Length::Fill) .padding([13, 4]); auth_buttons = auth_buttons.push(if auth == draft.auth { item.style(theme::selected_option) } else { item.style(theme::outlined_option) }); } let mut content = column![ text("SSH Connection").size(18), host_port, username, auth_buttons, ] .spacing(12); if draft.auth == AuthMethod::Password { content = content.push(password_field(draft)); } if draft.auth == AuthMethod::Key { content = content.push(private_key_field(draft)); } content.into() } } } /// Password label and masked field with an eye toggle. fn password_field(draft: &ProfileDraft) -> Element<'_, Message> { let field = text_input("Password", &draft.password) .secure(!draft.password_visible) .on_input(Message::ProfilePasswordChanged) .padding(Padding { top: 6.0, right: 32.0, bottom: 6.0, left: 8.0, }) .style(theme::filter_field) .width(Length::Fill); let eye_icon: Element<'_, Message> = if draft.password_visible { text("👁").size(16).into() } else { // Eye with a line across it, rather than an ambiguous curve. stack![ text("👁").size(16), container( rule::horizontal(1).style(|theme: &iced::Theme| iced::widget::rule::Style { color: theme.extended_palette().background.base.text, radius: 0.0.into(), fill_mode: iced::widget::rule::FillMode::Full, snap: true, }), ) .width(Length::Fill) .height(Length::Fill) .align_y(Alignment::Center), ] .into() }; let eye_button = button(eye_icon) .on_press(Message::TogglePasswordVisibility) .padding([2, 4]); let eye_button = if draft.password_visible { eye_button.style(theme::revealed_eye) } else { eye_button.style(button::text) }; let eye = container(eye_button) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Center) .padding(Padding::ZERO.right(6.0)); column![ text("Password").size(12), stack![field, eye].width(Length::Fill), ] .spacing(4) .into() } /// Private key label and file field with a browse button. fn private_key_field(draft: &ProfileDraft) -> Element<'_, Message> { let field = text_input("Private key", &draft.private_key) .on_input(Message::ProfilePrivateKeyChanged) .padding(Padding { top: 6.0, right: 40.0, bottom: 6.0, left: 8.0, }) .style(theme::filter_field) .width(Length::Fill); let browse = container( button("...") .on_press(Message::OpenPrivateKeyPicker) .padding([2, 6]) .style(|theme, status| theme::selectable_row(theme, status, false)), ) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Center) .padding(Padding::ZERO.right(6.0)); column![ text("Private Key").size(12), stack![field, browse].width(Length::Fill), ] .spacing(4) .into() } /// One folder heading followed by its profiles. Clicking the heading toggles /// the profile list; clicking a row selects it. fn profile_folder_row<'a>( index: usize, folder: &'a ProfileFolder, selected: Option, checked: &'a HashSet, hovered: Option, window: window::Id, show_checks: bool, ) -> Element<'a, Message> { let is_selected = selected == Some(Selection::Folder(index)); let expanded = folder.expanded; let indent = folder.depth() as f32 * 18.0; let folder_glyph = if folder.untracked { if expanded { "🗁\u{fe0e}" } else { "🗀\u{fe0e}" } } else if expanded { "📂" } else { "📁" }; let glyph = text(folder_glyph).size(14); let glyph = if folder.untracked { glyph.color(theme::UNTRACKED_FOLDER) } else { glyph }; let mut name = text(folder.name.as_str()).size(14); if folder.untracked { name = name.font(Font { style: font::Style::Italic, ..Font::DEFAULT }); } let mut heading_content = row![glyph, name, space::horizontal()] .spacing(8) .align_y(Alignment::Center) .width(Length::Fill); if show_checks && (is_selected || hovered == Some(index)) { heading_content = heading_content.push( button(text("⋮").size(14)) .on_press(Message::Ignore) .padding(0) .width(20) .height(14) .style(button::text), ); } let heading = button(heading_content) .on_press(Message::ToggleFolder(index)) .width(Length::Fill) .padding(Padding { top: 8.0, right: 10.0, bottom: 8.0, left: if show_checks { 0.0 } else { 10.0 + indent }, }) .style(move |theme, status| { let mut style = theme::selectable_row(theme, status, is_selected); if !expanded { style.text_color = style.text_color.scale_alpha(0.6); } style }); let mut heading = mouse_area(heading) .on_enter(Message::HoverFolder(Some(index))) .on_exit(Message::HoverFolder(None)); if show_checks { heading = heading.on_right_press(Message::OpenFolderMenu(window, index)); } let folder_checked = checked.contains(&Selection::Folder(index)); let heading: Element<'_, Message> = if show_checks { let folder_checkbox: Element<'_, Message> = if folder.path == DEFAULT_PROFILE_FOLDER { container(space::horizontal()) .width(16) .padding(Padding { top: 8.0, right: 6.0, bottom: 8.0, left: 10.0 + indent, }) .into() } else { container( checkbox(folder_checked) .size(16) .on_toggle(move |_| Message::ToggleChecked(Selection::Folder(index))), ) .padding(Padding { top: 8.0, right: 6.0, bottom: 8.0, left: 10.0 + indent, }) .into() }; row![folder_checkbox, heading] .align_y(Alignment::Center) .width(Length::Fill) .into() } else { heading.into() }; let mut rows = column![heading].width(Length::Fill); if expanded { for (profile_index, profile) in folder.profiles.iter().enumerate() { let profile_selected = selected == Some(Selection::Profile { folder: index, profile: profile_index, }); let profile_checked = checked.contains(&Selection::Profile { folder: index, profile: profile_index, }); let profile_row = button( row![ profile_glyph(profile.kind, profile.glyph_color), text(profile.name.as_str()).size(13) ] .spacing(8) .align_y(Alignment::Center), ) .width(Length::Fill) .padding(Padding { top: 4.0, right: 26.0, bottom: 4.0, left: if show_checks { 0.0 } else { 26.0 + indent }, }) .style(move |theme, status| theme::selectable_row(theme, status, profile_selected)); let profile_row = mouse_area(profile_row) .on_press(Message::SelectProfile { folder: index, profile: profile_index, }) .on_double_click(Message::EditProfile { folder: index, profile: profile_index, }); if show_checks { let profile_checkbox = container(checkbox(profile_checked).size(16).on_toggle(move |_| { Message::ToggleChecked(Selection::Profile { folder: index, profile: profile_index, }) })) .padding(Padding { top: 4.0, right: 6.0, bottom: 4.0, left: 26.0 + indent, }); rows = rows.push( row![profile_checkbox, profile_row] .align_y(Alignment::Center) .width(Length::Fill), ); } else { rows = rows.push(profile_row); } } } rows.into() } /// Landing tab: the profile listing with a shortcut to the Settings page. fn start_page(state: &Moorly, window: window::Id) -> Element<'_, Message> { responsive(move |size| { // Half the window and 60% of its height, with sensible minimums. let width = (size.width * 0.5).max(400.0); let list_height = (size.height * 0.6).max(300.0); let settings = button( row![text("⚙\u{fe0e}").size(16), text("Settings")] .spacing(6) .align_y(Alignment::Center), ) .on_press(Message::SelectTab(window, Tab::Settings)) .padding([6, 12]) .style(theme::outlined_option); container( container( column![ container(profiles_panel(state, window, false)) .width(Length::Fill) .height(list_height), settings, ] .spacing(12) .width(Length::Fill) .align_x(Alignment::Center), ) .width(width) .padding(12) .style(theme::settings_frame), ) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .padding(16) .into() }) .into() } /// General settings that are edited as a draft until saved. /// Reference table of every command the command palette can offer. fn command_palette_panel(state: &Moorly) -> Element<'_, Message> { let mut rows = column![ row![ styled_text(&state.typography.h3, "Enable command palette"), space::horizontal(), toggler(state.command_palette_enabled_draft) .on_toggle(Message::SetCommandPaletteEnabled), ] .align_y(Alignment::Center), rule::horizontal(1), row![ container(text("Command").size(13)).width(180), styled_text(&state.typography.caption, "Description"), ] .spacing(12), rule::horizontal(1), ] .spacing(8); for command in Command::ALL { rows = rows.push(command_palette_row( &state.typography.caption, command.label(state), command.description(state), )); } // Commands generated from the current profiles, tabs and windows. for (label, description) in [ ( "Profile name", "Switches to the matching profile and opens the Start tab", ), ("Tab title", "Focuses the matching tab in its window"), ( "Window title", "Focuses the matching window, or moves the active tab into it", ), ] { rows = rows.push(command_palette_row( &state.typography.caption, label.to_owned(), description.to_owned(), )); } rows.into() } fn command_palette_row( style: &TextStyle, command: String, description: String, ) -> Element<'static, Message> { row![ container(text(command).size(13)).width(180), styled_text(style, description), ] .spacing(12) .into() } fn general_panel(state: &Moorly) -> Element<'_, Message> { row![ styled_text(&state.typography.h3, "Fade In/Fade out animation"), space::horizontal(), toggler(state.fade_settings_draft).on_toggle(Message::SetFadeSettings), ] .align_y(Alignment::Center) .into() } /// Startup settings that are edited as a draft until saved. fn startup_panel(state: &Moorly) -> Element<'_, Message> { row![ styled_text(&state.typography.h3, "Show Start tab at startup"), space::horizontal(), toggler(state.show_start_tab_draft).on_toggle(Message::SetShowStartTab), ] .align_y(Alignment::Center) .into() } /// Appearance settings that are edited as a draft until saved. fn appearance_panel(state: &Moorly) -> Element<'_, Message> { column![ theme_picker(state), typography_panel(state), advanced_panel(state), styled_text(&state.typography.h2, "Tab bar"), row![ styled_text(&state.typography.h3, "Show new Session Button"), space::horizontal(), toggler(state.show_new_session_button_draft) .on_toggle(Message::SetShowNewSessionButton), ] .align_y(Alignment::Center), row![ styled_text(&state.typography.h3, "Hide tab close icon"), space::horizontal(), toggler(state.hide_tab_close_draft).on_toggle(Message::SetHideTabClose), ] .align_y(Alignment::Center), styled_text(&state.typography.h2, "Command Palette"), row![ styled_text(&state.typography.h3, "Show command palette description"), space::horizontal(), toggler(state.show_command_palette_description_draft) .on_toggle(Message::SetShowCommandPaletteDescription), ] .align_y(Alignment::Center), ] .spacing(12) .into() } fn folder_context_menu(state: &Moorly, window: window::Id) -> Option> { if state.settings_section != SettingsSection::Profiles { return None; } let (index, pointer) = state.folder_menu?; let window_state = state.windows.get(&window)?; let width = 160.0; let height = MENU_PADDING * 2.0 + 4.0 * MENU_ITEM_HEIGHT + 3.0 * 4.0; let max_x = (window_state.size.width - width - 8.0).max(8.0); let max_y = (window_state.size.height - height - 8.0).max(8.0); let menu = container( column![ menu_item("Copy to", None, Message::FolderMenuCopy(index)), menu_item("Move to", None, Message::FolderMenuMove(index)), menu_item("Delete", None, Message::FolderMenuDelete(index)), menu_item("Rename", None, Message::FolderMenuRename(index)), ] .spacing(4), ) .width(width) .padding(MENU_PADDING) .style(theme::menu); Some( container(menu) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Start) .align_y(Alignment::Start) .padding(Padding { top: (pointer.y - MENUBAR_HEIGHT).clamp(8.0, max_y), left: pointer.x.clamp(8.0, max_x), ..Padding::ZERO }) .into(), ) } fn settings_page(state: &Moorly, window: window::Id) -> Element<'_, Message> { let accent = state.colors[ColorOption::Accent.index()]; let text_color = state.colors[ColorOption::Text.index()]; let main_background = state.colors[ColorOption::MainBackground.index()]; // Fit the longest section name, but stop growing at 20 characters and // wrap instead. The 10 px estimate covers the default font's average glyph. let label_chars = SettingsSection::ALL .iter() .map(|section| section.label().chars().count()) .max() .unwrap_or(1) .min(20); let label_width = label_chars as f32 * 10.0; // Menu padding (8 both sides) plus button padding (10 both sides). let menu_width = label_width + 36.0; let menu_item = |section: SettingsSection| { let label = container( text(section.label()) .width(Length::Fixed(label_width)) .wrapping(Wrapping::WordOrGlyph), ) .width(Length::Fill) .align_x(Alignment::Start); let item = button(label) .on_press(Message::SelectSettingsSection(section)) .width(Length::Fill) .padding([6, 10]); if section == state.settings_section { item.style(move |theme, status| theme::settings_active(theme, status, accent)) } else { item.style(move |theme, status| theme::menubar_button(theme, status, text_color)) } }; let menu = container(column(SettingsSection::ALL.map(|section| menu_item(section).into())).spacing(2)) .width(menu_width) .height(Length::Fill) .padding(8); let scrolls = state.settings_section != SettingsSection::Profiles; // Leave room for the overlay scrollbar so right-aligned controls do not // move or get covered when it appears. let mut content = column![] .spacing(12) .width(Length::Fill) .padding(Padding::ZERO.right(if scrolls { 12.0 } else { 0.0 })); content = content.push(styled_text( &state.typography.h1, state.settings_section.label(), )); if state.settings_section == SettingsSection::General { content = content.push(general_panel(state)); } if state.settings_section == SettingsSection::Startup { content = content.push(startup_panel(state)); } if state.settings_section == SettingsSection::Appearance { content = content.push(appearance_panel(state)); } if state.settings_section == SettingsSection::Shortcuts { content = content.push(shortcuts_panel(state)); } if state.settings_section == SettingsSection::CommandPalette { content = content.push(command_palette_panel(state)); } if state.settings_section == SettingsSection::Profiles { content = content.push(profiles_panel(state, window, true)); } let body: Element<'_, Message> = if scrolls { scrollable(content) .width(Length::Fill) .height(Length::Fill) .into() } else { content.into() }; let content = container(body) .width(Length::Fill) .height(Length::Fill) .padding(16); // Fade the content pane to the frame background, swap sections at // full opacity, then fade back in. let now = Instant::now(); let fading = state.fade_animation.is_animating(now) || !state.fade_animation.value(); let fade = state.fade_animation.interpolate(0.0, 1.0, now); let content: Element<'_, Message> = if fading { let overlay = container(space::horizontal()) .width(Length::Fill) .height(Length::Fill) .style(move |_| { let mut color = main_background; color.a = 1.0 - fade; container::Style { background: Some(color.into()), ..container::Style::default() } }); stack![content, overlay] .width(Length::Fill) .height(Length::Fill) .into() } else { content.into() }; let frame = row![menu, content].width(Length::Fill).height(Length::Fill); // Size the content pane like the start tab's centered panel, then add // the settings menu to the side. let panel_width = state .windows .get(&window) .map(|window_state| (window_state.size.width * 0.5).max(400.0) + menu_width) .unwrap_or(400.0 + menu_width); let frame = container(frame).width(panel_width).height(Length::Fill); let frame = container(frame) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center); let dirty = state.show_start_tab_draft != state.show_start_tab || state.fade_settings_draft != state.fade_settings || state.hide_tab_close_draft != state.hide_tab_close || state.show_new_session_button_draft != state.show_new_session_button || state.show_command_palette_description_draft != state.show_command_palette_description || state.typography_draft != state.typography || state.command_palette_enabled_draft != state.command_palette_enabled || state.theme_choice != state.saved_theme_choice || state.shortcuts != state.saved_shortcuts; let page: Element<'_, Message> = if dirty { let bar = container( row![ text("There is unsaved changes"), space::horizontal(), button( row![text("✓"), text("Save changes")] .spacing(6) .align_y(Alignment::Center), ) .on_press(Message::SaveSettings) .padding([6, 12]) .style(theme::positive_option), button( row![text("↶"), text("Undo changes")] .spacing(6) .align_y(Alignment::Center), ) .on_press(Message::UndoChanges) .padding([6, 12]) .style(theme::outlined_option), ] .spacing(8) .align_y(Alignment::Center), ) .width(Length::Fill) .padding([8, 12]) .style(theme::settings_bar); let bar_layer = container(bar) .width(Length::Fill) .height(Length::Fill) .align_y(Alignment::End); stack![frame, bar_layer] .width(Length::Fill) .height(Length::Fill) .into() } else { frame.into() }; let page: Element<'_, Message> = if let Some(menu) = folder_context_menu(state, window) { let backdrop = mouse_area( container(space::horizontal()) .width(Length::Fill) .height(Length::Fill), ) .on_press(Message::CloseFolderMenu); stack![page, backdrop, menu] .width(Length::Fill) .height(Length::Fill) .into() } else { page }; if let Some(draft) = &state.theme_name_dialog { let dialog = container( column![ text("Save as new theme").size(14), text_input("Theme name", draft) .id(THEME_NAME_INPUT) .on_input(Message::ThemeNameChanged) .on_submit(Message::ConfirmThemeName) .padding(6) .style(theme::filter_field) .width(Length::Fill), row![ space::horizontal(), button("Cancel") .on_press(Message::CancelThemeName) .style(theme::outlined_option), button("Save") .on_press_maybe( (!draft.trim().is_empty()).then_some(Message::ConfirmThemeName) ) .style(theme::positive_option), ] .spacing(8), ] .spacing(10) .width(Length::Fill), ) .width(320) .padding(12) .style(theme::menu); let dialog = mouse_area(dialog).on_press(Message::Ignore); let dialog_layer = container(dialog) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Center); let backdrop = mouse_area( container(space::horizontal()) .width(Length::Fill) .height(Length::Fill), ) .on_press(Message::CancelThemeName); stack![page, backdrop, dialog_layer].into() } else { page } } /// A left-aligned menu row with an optional right-aligned shortcut. The /// vertical bar and shortcut live inside the same clickable button. fn menu_item( label: &'static str, shortcut: Option, message: Message, ) -> iced::widget::Button<'static, Message> { menu_item_with_glyph(None, label, shortcut, message) } fn menu_item_with_glyph( glyph: Option<&'static str>, label: &'static str, shortcut: Option, message: Message, ) -> iced::widget::Button<'static, Message> { let mut content = row![] .width(Length::Fill) .align_y(Alignment::Center) .spacing(6); if let Some(glyph) = glyph { content = content.push(text(glyph).size(16)); } content = content.push(text(label)); if let Some(shortcut) = shortcut { content = content .push(space::horizontal()) .push(container(rule::vertical(1)).height(12).padding([0, 6])) .push(text(shortcut).size(11)); } button(content) .on_press(message) .width(Length::Fill) .height(MENU_ITEM_HEIGHT) .padding([4, 8]) .style(button::text) } /// Vertical offset of the Tabs row inside the menu column, so the chevron /// column can place its `◀ |` alongside it. Keep in sync with the layout. fn tabs_row_top() -> f32 { let mut top = MENU_ITEM_HEIGHT + 4.0; if cfg!(debug_assertions) { top += MENU_ITEM_HEIGHT + 4.0; } top } /// Vertical offset of the Tabs row from the top of the menu panel, so the /// submenu can start at the same height. fn tabs_submenu_top() -> f32 { MENU_PADDING + HAMBURGER_ROW_HEIGHT + 2.0 + tabs_row_top() } fn scroll_button( symbol: &'static str, delta: f32, enabled: bool, text_color: Color, window: window::Id, ) -> iced::widget::Button<'static, Message> { button(text(symbol).size(17)) .on_press_maybe(enabled.then_some(Message::ScrollTabsBy(window, delta))) .width(SCROLL_BUTTON_WIDTH) .padding([0, 6]) .style(move |theme, status| theme::menubar_button(theme, status, text_color)) } /// Whether the tab strip can still scroll left/right. fn tab_scroll_limits(state: &Moorly, window: window::Id) -> (bool, bool) { let Some(window_state) = state.windows.get(&window) else { return (false, false); }; if window_state.tabs.is_empty() { return (false, false); } let metrics = tab_strip_metrics(window_state, state.show_new_session_button); let max_offset = (metrics.content - metrics.viewport).max(0.0); let offset = window_state.tab_offset.min(max_offset); (offset > 0.5, offset < max_offset - 0.5) } fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> { let Some(window_state) = state.windows.get(&window) else { return container(space::horizontal()) .width(Length::Fill) .height(Length::Fill) .into(); }; // Tab strip: size tabs to the strip's current width so as many as // possible fit before scrolling starts. let tabs = window_state.tabs.clone(); let active_tab = window_state.active_tab; let menu_open = window_state.menu_open; let quick_menu_open = window_state.quick_menu_open; let show_new_session_button = state.show_new_session_button; let tabs_submenu_open = window_state.tabs_submenu_open; let scroll_id = window_state.scroll_id.clone(); let hide_close = state.hide_tab_close; let colors = state.colors; let text_color = colors[ColorOption::Text.index()]; let main_background = colors[ColorOption::MainBackground.index()]; let sidebar_background = colors[ColorOption::SidebarBackground.index()]; let now = Instant::now(); let close_opacities: HashMap = tabs .iter() .map(|tab| { let opacity = if hide_close { state .tab_close_fades .get(tab) .map(|animation| animation.interpolate(0.0, 1.0, now)) .unwrap_or(0.0) } else { 1.0 }; (*tab, opacity) }) .collect(); let tab_strip = responsive(move |size| { let width = tab_width(size.width, tabs.len()); let mut tab_row = row![].spacing(TAB_SPACING).height(Length::Fill); for &tab in &tabs { tab_row = tab_row.push(tab_view( window, tab, active_tab == Some(tab), hide_close, close_opacities.get(&tab).copied().unwrap_or(0.0), width, colors, )); } let tab_strip = scrollable(tab_row) .direction(scrollable::Direction::Horizontal( scrollable::Scrollbar::hidden(), )) .id(scroll_id.clone()) .width(Length::Fill) .height(Length::Fill) .on_scroll(move |viewport| Message::TabsScrolled(window, viewport)); // Convert vertical wheel input into horizontal tab-strip scrolling. mouse_area(tab_strip) .on_scroll(move |delta| Message::ScrollTabs(window, delta)) .into() }); let (can_scroll_left, can_scroll_right) = tab_scroll_limits(state, window); let mut bar = row![].spacing(2).align_y(Alignment::Center); if show_new_session_button { bar = bar.push(quick_add_button(quick_menu_open, text_color, window)); } bar = bar .push(tab_strip) .push(scroll_button( "◀", -TAB_SCROLL_STEP, can_scroll_left, text_color, window, )) .push(scroll_button( "▶", TAB_SCROLL_STEP, can_scroll_right, text_color, window, )); if menu_open { // The dropdown draws the close button over this spot. bar = bar.push(space::horizontal().width(HAMBURGER_WIDTH)); } else { bar = bar.push(hamburger(false, text_color, window)); } let menubar = container(bar) .width(Length::Fill) .height(MENUBAR_HEIGHT) .align_y(Alignment::Center) .padding(Padding { top: 0.0, right: MENUBAR_RIGHT_PADDING, bottom: 0.0, left: TAB_STRIP_LEFT, }) .style(move |theme| theme::menubar(theme, sidebar_background)); let main_area: Element<'_, Message> = match active_tab { Some(Tab::Start) => start_page(state, window), Some(Tab::Settings) => settings_page(state, window), _ => container(column![]) .width(Length::Fill) .height(Length::Fill) .into(), }; let main_area = container(main_area) .width(Length::Fill) .height(Length::Fill) .style(move |_| container::Style { background: Some(main_background.into()), text_color: Some(text_color), ..container::Style::default() }); let base = column![menubar, main_area]; let ghost = drag_ghost(state, window, colors); let drop_bar = tab_drop_bar(state, window, colors); let drop_panel = drop_panel(state, window, colors); if !menu_open { // Keep the root a `stack` so the tab strip's scroll state survives // opening/closing the menu. let mut root = stack![base]; if let Some(ghost) = ghost { root = root.push(ghost); } if let Some(drop_bar) = drop_bar { root = root.push(drop_bar); } if let Some(drop_panel) = drop_panel { root = root.push(drop_panel); } if quick_menu_open { let backdrop = mouse_area( container(space::horizontal()) .width(Length::Fill) .height(Length::Fill), ) .on_press(Message::CloseQuickAddMenu(window)); root = root.push(backdrop); root = root.push(quick_add_menu(window)); } return root.into(); } let menu_items = column![].spacing(4); let settings_shortcut = state .shortcuts .get(ShortcutAction::Settings) .map(ToString::to_string); let quit_shortcut = state .shortcuts .get(ShortcutAction::Quit) .map(ToString::to_string); let mut menu_items = menu_items.push(menu_item_with_glyph( Some("⚙\u{fe0e}"), "Settings", settings_shortcut, Message::SelectTab(window, Tab::Settings), )); if cfg!(debug_assertions) { menu_items = menu_items.push(menu_item("temp Add Tab", None, Message::AddTab(window))); } let menu_items = menu_items .push(menu_item("Tabs", None, Message::ToggleTabsSubmenu(window))) .push(rule::horizontal(1)) .push(menu_item("Quit", quit_shortcut, Message::Quit)) .width(Length::Fill); // The `◀ |` marker owns its own column; menu rows start to its right. let tabs_marker = container(column![ space::vertical().height(tabs_row_top()), container( row![ text("◀").size(16), container(rule::vertical(1)).height(12).padding([0, 6]), ] .align_y(Alignment::Center), ) .height(MENU_ITEM_HEIGHT) .padding(Padding::ZERO.top(4.0)) .align_y(Alignment::Start), ]) .width(24); let menu = container( column![ container(hamburger(true, text_color, window)) .width(Length::Fill) .height(HAMBURGER_ROW_HEIGHT) .align_x(Alignment::End) .align_y(Alignment::Center), row![tabs_marker, menu_items].align_y(Alignment::Start), ] .spacing(2), ) .width(220) .padding(MENU_PADDING) .style(theme::menu); let tabs_submenu = container( column![ menu_item( "Close Active Tab", Some("Ctrl+Shift+W".to_owned()), Message::CloseActiveTab(window), ), menu_item( "Close all other tabs", None, Message::CloseOtherTabs(window), ), ] .spacing(4), ) .width(220) .padding(MENU_PADDING) .style(theme::menu); // Push the submenu down so its first row starts level with the Tabs row. let tabs_submenu = container(tabs_submenu).padding(Padding::ZERO.top(tabs_submenu_top() - MENU_PADDING)); let mut dropdown_row = row![].spacing(0).align_y(Alignment::Start); if tabs_submenu_open { dropdown_row = dropdown_row.push(tabs_submenu); } dropdown_row = dropdown_row.push(menu); let dropdown = container(dropdown_row) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::End) .align_y(Alignment::Start) .padding(Padding::ZERO.right(8.0)); // Clicking anywhere outside the dropdown dismisses it. let backdrop = mouse_area( container(space::horizontal()) .width(Length::Fill) .height(Length::Fill), ) .on_press(Message::CloseMenu(window)); let mut root = stack![base, backdrop, dropdown] .width(Length::Fill) .height(Length::Fill); if let Some(ghost) = ghost { root = root.push(ghost); } if let Some(drop_bar) = drop_bar { root = root.push(drop_bar); } if let Some(drop_panel) = drop_panel { root = root.push(drop_panel); } root.into() } /// One command row: name over description and shortcut, with the Enter hint /// on the selected row. Descriptions and shortcuts follow the appearance /// setting. fn command_palette_item( state: &Moorly, window: window::Id, command: Command, selected: bool, ) -> Element<'static, Message> { let show_description = state.show_command_palette_description; let mut title = row![] .spacing(8) .align_y(Alignment::Center) .width(Length::Fill); if let Some((kind, color)) = command.profile_glyph(state) { title = title.push(profile_glyph(kind, color)); } title = title.push(text(command.label(state)).size(16)); if selected { title = title.push(space::horizontal()).push( container(text("Enter").size(11)) .align_y(Alignment::Center) .padding([0, 8]) .style(|_theme: &iced::Theme| container::Style { border: Border { color: theme::border_color(), width: 1.0, radius: 4.0.into(), }, ..container::Style::default() }), ); } let mut details = column![title].spacing(2); if show_description { let mut info = row![] .spacing(8) .align_y(Alignment::Center) .width(Length::Fill); info = info.push(text(command.description(state)).size(12)); if let Some(shortcut) = command.shortcut(state) { info = info.push(space::horizontal()).push(text(shortcut).size(11)); } details = details.push(info); } let content = row![details.width(Length::Fill)] .align_y(Alignment::Center) .height(Length::Fill); button(content) .on_press(Message::RunCommand(window, command)) .width(Length::Fill) .height(if show_description { 52 } else { 34 }) .padding([4, 10]) .style(move |theme, status| theme::selectable_row(theme, status, selected)) .into() } /// Top-of-window command palette field and matching command list. fn command_palette_layer(state: &Moorly, window: window::Id) -> Option> { let window_state = state.windows.get(&window)?; if !window_state.command_palette_open { return None; } let field = text_input("Type a command...", &window_state.command_palette_query) .id(window_state.command_palette_input.clone()) .on_input(move |query| Message::CommandPaletteChanged(window, query)) .padding([10, 12]) .style(theme::filter_field) .width(Length::Fill); let matches = Command::matching(state, window, &window_state.command_palette_query); let selected = window_state .command_palette_selected .min(matches.len().saturating_sub(1)); let mut list = column![].spacing(2); if matches.is_empty() { list = list.push(container(text("No matching commands").size(12)).padding(8)); } else { for (index, command) in matches.into_iter().enumerate() { list = list.push(command_palette_item( state, window, command, index == selected, )); } } let panel = container(column![field, list].spacing(6)) .width(560) .padding(6) .style(theme::menu); Some( container(panel) .width(Length::Fill) .height(Length::Fill) .align_x(Alignment::Center) .align_y(Alignment::Start) .padding(Padding::ZERO.top(8.0)) .into(), ) } /// The application content with the notification stack rendered above it. fn view(state: &Moorly, window: window::Id) -> Element<'_, Message> { theme::set_border_color(state.colors[ColorOption::Border.index()]); let content = main_view(state, window); let palette = command_palette_layer(state, window); if state.notifications.is_empty() && palette.is_none() { return content; } let mut root = stack![content]; if !state.notifications.is_empty() { let toasts = state .notifications .view( Instant::now(), state .custom_toasts .then(|| notifications::ToastColors::from_array(state.toast_colors)), ) .map(Message::Notification); root = root.push(toasts); } if let Some(palette) = palette { root = root.push(palette); } root.width(Length::Fill).height(Length::Fill).into() } #[cfg(test)] mod tests { use super::{Message, Moorly, Tab, theme, update}; use iced::keyboard; fn test_window() -> iced::window::Id { static WINDOW: std::sync::OnceLock = std::sync::OnceLock::new(); *WINDOW.get_or_init(iced::window::Id::unique) } fn window_state(state: &Moorly) -> &super::WindowState { &state.windows[&test_window()] } fn window_state_mut(state: &mut Moorly) -> &mut super::WindowState { state.windows.get_mut(&test_window()).unwrap() } fn state() -> Moorly { let window = test_window(); let window_state = super::WindowState::new(false, iced::Size::new(1024.0, 768.0)); Moorly { windows: [(window, window_state)].into_iter().collect(), window_order: vec![window], main_window: Some(window), focused_window: Some(window), drag: None, theme: theme::Preference::default(), saved_theme: theme::Preference::default(), theme_choice: super::ThemeChoice::BuiltIn(theme::Preference::default()), saved_theme_choice: super::ThemeChoice::BuiltIn(theme::Preference::default()), custom_themes: Vec::new(), theme_name_dialog: None, theme_signature: Vec::new(), shortcuts: super::Shortcuts::default(), saved_shortcuts: super::Shortcuts::default(), shortcut_capture: None, settings_section: super::SettingsSection::default(), pending_settings_section: None, show_start_tab: true, show_start_tab_draft: true, fade_settings: true, fade_settings_draft: true, hide_tab_close: true, hide_tab_close_draft: true, show_new_session_button: true, show_new_session_button_draft: true, show_command_palette_description: true, show_command_palette_description_draft: true, typography: super::Typography::default(), typography_draft: super::Typography::default(), typography_size_inputs: super::typography_size_inputs(&super::Typography::default()), typography_open: false, typography_font_menu: None, command_palette_enabled: true, command_palette_enabled_draft: true, advanced_open: false, colors: super::DEFAULT_COLORS, saved_colors: super::DEFAULT_COLORS, custom_toasts: false, toast_colors: super::builtin_toast_colors(theme::Preference::default()), builtin_custom_toasts: false, builtin_toast_colors: super::builtin_toast_colors(theme::Preference::default()), open_color_picker: None, open_toast_color_picker: None, fade_animation: super::new_fade_animation(), hovered_tab: None, tab_close_fades: Default::default(), profile_filter: String::new(), profile_folders: vec![super::ProfileFolder::default_folder()], selected: None, checked: super::HashSet::new(), trash_open: false, trash_entries: Vec::new(), trash_checked: super::HashSet::new(), transfer: None, confirm_delete: false, confirm_purge_trash: false, hovered_folder: None, add_menu_open: false, folder_dialog: None, folder_rename: None, folder_menu: None, profile_dialog: None, dir_picker: None, next_blank_tab: 1, notifications: super::notifications::NotificationManager::default(), } } fn profile(name: &str) -> super::Profile { super::Profile { name: name.to_owned(), kind: super::ProfileKind::Ssh, session_end: super::SessionEnd::Auto, host: String::new(), port: "22".to_owned(), username: String::new(), auth: super::AuthMethod::Password, password: String::new(), start_path: String::new(), private_key: String::new(), glyph_color: iced::Color::WHITE, folder_id: String::new(), file: None, } } #[test] fn start_tab_follows_the_saved_setting() { let (state, _) = super::boot(); let window = state.windows.keys().next().copied().unwrap(); let expected = state.show_start_tab.then_some(Tab::Start); assert_eq!( state.windows[&window].tabs, expected.into_iter().collect::>() ); assert_eq!(state.windows[&window].active_tab, expected); assert_eq!(Tab::Start.title(), "Start"); } #[test] fn fade_starts_visible_and_ends_hidden() { let start = iced::time::Instant::now(); let mut fade = super::new_fade_animation(); assert_eq!(fade.interpolate(0.0, 1.0, start), 1.0); fade.go_mut(false, start); assert!(fade.interpolate(0.0, 1.0, start) > 0.99); assert!(fade.interpolate(0.0, 1.0, start + iced::time::Duration::from_millis(250)) < 0.01); } #[test] fn section_switch_waits_for_the_fade_out() { let mut state = state(); state.settings_section = super::SettingsSection::General; let _ = update( &mut state, Message::SelectSettingsSection(super::SettingsSection::Startup), ); assert_eq!(state.settings_section, super::SettingsSection::General); assert_eq!( state.pending_settings_section, Some(super::SettingsSection::Startup) ); assert!( state .fade_animation .is_animating(iced::time::Instant::now()) ); let later = iced::time::Instant::now() + iced::time::Duration::from_secs(1); let _ = update(&mut state, Message::Frame(later)); assert_eq!(state.settings_section, super::SettingsSection::Startup); assert_eq!(state.pending_settings_section, None); } #[test] fn startup_changes_wait_for_save_or_undo() { let mut state = state(); let _ = update(&mut state, Message::SetShowStartTab(false)); assert!(state.show_start_tab); assert!(!state.show_start_tab_draft); let _ = update(&mut state, Message::UndoChanges); assert_eq!(state.show_start_tab_draft, state.show_start_tab); let _ = update(&mut state, Message::SetShowStartTab(false)); super::apply_settings(&mut state); assert!(!state.show_start_tab); assert_eq!(state.show_start_tab_draft, state.show_start_tab); } #[test] fn hiding_tab_close_waits_for_save_or_undo() { let mut state = state(); let _ = update(&mut state, Message::SetHideTabClose(false)); assert!(state.hide_tab_close); assert!(!state.hide_tab_close_draft); let _ = update(&mut state, Message::UndoChanges); assert_eq!(state.hide_tab_close_draft, state.hide_tab_close); let _ = update(&mut state, Message::SetHideTabClose(false)); super::apply_settings(&mut state); assert!(!state.hide_tab_close); assert_eq!(state.hide_tab_close_draft, state.hide_tab_close); } #[test] fn hiding_the_new_session_button_waits_for_save_or_undo() { let mut state = state(); let _ = update(&mut state, Message::SetShowNewSessionButton(false)); assert!(state.show_new_session_button); assert!(!state.show_new_session_button_draft); let _ = update(&mut state, Message::UndoChanges); assert_eq!( state.show_new_session_button_draft, state.show_new_session_button ); let _ = update(&mut state, Message::SetShowNewSessionButton(false)); super::apply_settings(&mut state); assert!(!state.show_new_session_button); assert_eq!( state.show_new_session_button_draft, state.show_new_session_button ); assert!(super::tab_strip_width(1024.0, false) > super::tab_strip_width(1024.0, true)); } #[test] fn custom_typography_waits_for_save_or_undo() { let mut state = state(); let level = super::TypographyLevel::H1; let _ = update( &mut state, Message::TypographyFontSelected(level, "Test Font".to_owned()), ); let _ = update( &mut state, Message::TypographySizeInputChanged(level, "30".to_owned()), ); assert_eq!(state.typography.h1.font, super::default_ui_font()); assert_eq!(state.typography.h1.size, super::SETTINGS_H1_SIZE); assert_eq!(state.typography_draft.h1.font, "Test Font"); assert_eq!(state.typography_draft.h1.size, 30.0); let _ = update(&mut state, Message::UndoChanges); assert_eq!(state.typography_draft.h1.font, super::default_ui_font()); assert_eq!(state.typography_draft.h1.size, super::SETTINGS_H1_SIZE); assert_eq!(state.typography_size_inputs[0], "22"); let _ = update( &mut state, Message::TypographyFontSelected(level, "Test Font".to_owned()), ); let _ = update( &mut state, Message::TypographySizeInputChanged(level, "30".to_owned()), ); let _ = update(&mut state, Message::SaveSettings); assert_eq!(state.typography.h1.font, "Test Font"); assert_eq!(state.typography.h1.size, 30.0); } #[test] fn default_typography_uses_platform_and_bundled_fonts() { let typography = super::Typography::default(); assert_eq!(typography.h1.font, super::default_ui_font()); assert_eq!(typography.h2.font, super::default_ui_font()); assert_eq!(typography.terminal.font, "JetBrains Mono"); assert_eq!(typography.ssh.font, "JetBrains Mono"); } #[test] fn typography_style_flags_toggle_draft_only() { let mut state = state(); let level = super::TypographyLevel::H2; let _ = update( &mut state, Message::TypographyStyleToggled(level, super::TextStyleFlag::Bold), ); assert!(state.typography_draft.h2.bold); assert!(!state.typography.h2.bold); let _ = update(&mut state, Message::SaveSettings); assert!(state.typography.h2.bold); } #[test] fn typography_size_choices_mark_defaults_and_custom_sizes() { let (choices, selected) = super::size_choices(super::TypographyLevel::H1, 22.0); assert_eq!(choices.len(), super::FONT_SIZE_STEPS.len()); assert_eq!(selected.label, "22 px (Default)"); let (choices, selected) = super::size_choices(super::TypographyLevel::H1, 23.0); assert_eq!(selected.label, ""); assert!(choices.iter().any(|choice| choice.label == "")); } #[test] fn hiding_command_palette_descriptions_waits_for_save_or_undo() { let mut state = state(); let _ = update(&mut state, Message::SetShowCommandPaletteDescription(false)); assert!(state.show_command_palette_description); assert!(!state.show_command_palette_description_draft); let _ = update(&mut state, Message::UndoChanges); assert_eq!( state.show_command_palette_description_draft, state.show_command_palette_description ); let _ = update(&mut state, Message::SetShowCommandPaletteDescription(false)); super::apply_settings(&mut state); assert!(!state.show_command_palette_description); assert_eq!( state.show_command_palette_description_draft, state.show_command_palette_description ); } #[test] fn disabling_the_command_palette_waits_for_save_or_undo() { let mut state = state(); let _ = update(&mut state, Message::SetCommandPaletteEnabled(false)); assert!(state.command_palette_enabled); assert!(!state.command_palette_enabled_draft); let _ = update(&mut state, Message::UndoChanges); assert_eq!( state.command_palette_enabled_draft, state.command_palette_enabled ); let _ = update(&mut state, Message::SetCommandPaletteEnabled(false)); super::apply_settings(&mut state); assert!(!state.command_palette_enabled); assert_eq!( state.command_palette_enabled_draft, state.command_palette_enabled ); } #[test] fn theme_selection_waits_for_save_or_undo() { let mut state = state(); let dark = super::ThemeOption::Theme { choice: super::ThemeChoice::BuiltIn(theme::Preference::Dark), selected: false, }; let _ = update(&mut state, Message::SelectTheme(dark.clone())); assert_eq!(state.theme, theme::Preference::Dark); assert_eq!(state.saved_theme, theme::Preference::System); assert_ne!(state.theme_choice, state.saved_theme_choice); let _ = update(&mut state, Message::UndoChanges); assert_eq!(state.theme, theme::Preference::System); assert_eq!(state.theme_choice, state.saved_theme_choice); let _ = update(&mut state, Message::SelectTheme(dark)); super::apply_settings(&mut state); assert_eq!(state.saved_theme, theme::Preference::Dark); assert_eq!(state.saved_theme_choice, state.theme_choice); } #[test] fn config_is_written_as_sectioned_toml() { let mut state = state(); state.fade_settings = false; state.show_start_tab = false; state.hide_tab_close = false; state.show_new_session_button = false; state.show_command_palette_description = false; state.typography.h1.font = "Test Font".to_owned(); state.typography.h1.size = 30.0; state.command_palette_enabled = false; state.saved_theme = theme::Preference::Dark; state.saved_theme_choice = super::ThemeChoice::BuiltIn(theme::Preference::Dark); state.builtin_custom_toasts = true; state.builtin_toast_colors[super::ToastColorOption::Info.index()] = iced::Color::from_rgb8(1, 2, 3); let text = toml::to_string_pretty(&super::config_file(&state)).unwrap(); let parsed: toml::Value = toml::from_str(&text).unwrap(); assert!(text.contains("[general]\nfade_settings = false")); assert!(text.contains("[startup]\nshow_start_tab = false")); assert!(text.contains("[appearance]\ntheme = \"dark\"")); assert!(text.contains("show_new_session_button = false")); assert!(text.contains("show_command_palette_description = false")); assert!(text.contains("[appearance.typography.h1]")); assert!(text.contains("font = \"Test Font\"")); assert!(text.contains("size = 30.0")); assert!(text.contains("[appearance.toast]")); assert!(text.contains("[shortcuts]")); assert!(text.contains("[command_palette]\nenabled = false")); assert_eq!(parsed["general"]["fade_settings"].as_bool(), Some(false)); assert_eq!(parsed["appearance"]["theme"].as_str(), Some("dark")); assert_eq!( parsed["appearance"]["toast"]["enabled"].as_bool(), Some(true) ); assert_eq!( parsed["appearance"]["toast"]["info"].as_str(), Some("#010203") ); assert_eq!(parsed["shortcuts"]["settings"].as_str(), Some("Ctrl+,")); assert_eq!( parsed["shortcuts"]["quick_terminal"].as_str(), Some("Ctrl+Shift+T") ); assert_eq!( parsed["shortcuts"]["quick_ssh"].as_str(), Some("Ctrl+Shift+S") ); state.saved_theme_choice = super::ThemeChoice::Custom { id: "abc".to_owned(), name: "Mine".to_owned(), }; let text = toml::to_string_pretty(&super::config_file(&state)).unwrap(); assert!(text.contains("custom_theme = \"abc\"")); assert!(text.contains("custom_theme_name = \"Mine\"")); } #[test] fn missing_custom_theme_falls_back_to_dark() { let appearance = super::AppearanceConfig { theme: "light".to_owned(), custom_theme: Some("gone".to_owned()), ..super::AppearanceConfig::default() }; let (choice, preference, _, _, _, _, missing) = super::resolve_theme(&appearance, &[]); assert!(missing); assert_eq!(preference, theme::Preference::Dark); assert_eq!(choice, super::ThemeChoice::BuiltIn(theme::Preference::Dark)); } #[test] fn shortcut_changes_wait_for_save_or_undo() { let mut state = state(); let _ = update( &mut state, Message::OpenShortcutCapture(super::ShortcutAction::Settings), ); let _ = update( &mut state, press( keyboard::Key::Character("k".into()), keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT, ), ); let _ = update(&mut state, Message::ApplyShortcut); assert_eq!( state.shortcuts.settings.as_ref().map(ToString::to_string), Some("Ctrl+Shift+K".to_owned()) ); assert_eq!( state .saved_shortcuts .settings .as_ref() .map(ToString::to_string), Some("Ctrl+,".to_owned()) ); super::apply_settings(&mut state); assert_eq!(state.saved_shortcuts, state.shortcuts); } #[test] fn notification_demo_adds_all_types() { let mut state = state(); let _ = update(&mut state, Message::ShowNotificationDemo); assert_eq!(state.notifications.len(), 4); } #[test] fn long_titles_are_ellipsized_to_max_width() { assert_eq!(super::fit_title("Settings"), "Settings"); assert_eq!(super::fit_title(&"a".repeat(20)), "a".repeat(20)); let fitted = super::fit_title(&"a".repeat(30)); assert_eq!(fitted, format!("{}...", "a".repeat(17))); assert_eq!(fitted.chars().count(), 20); } #[test] fn tab_width_fits_the_strip_within_bounds() { assert_eq!(super::tab_width(0.0, 2), super::TAB_MAX_WIDTH); assert_eq!(super::tab_width(1000.0, 2), super::TAB_MAX_WIDTH); assert_eq!(super::tab_width(500.0, 10), super::TAB_MIN_WIDTH); let width = super::tab_width(500.0, 3); assert!((width - (500.0 - 2.0 * super::TAB_SPACING) / 3.0).abs() < 0.01); } #[test] fn theme_colors_round_trip_through_hex() { let color = iced::Color::from_rgb8(0x12, 0x34, 0x56); assert_eq!(super::color_to_hex(color), "#123456"); assert_eq!(super::color_from_hex("#123456"), Some(color)); assert_eq!( super::color_from_hex("#12345680"), Some(iced::Color::from_rgba8(0x12, 0x34, 0x56, 128.0 / 255.0)) ); } #[test] fn theme_file_only_stores_changed_colors() { let mut colors = super::DEFAULT_COLORS; colors[super::ColorOption::Accent.index()] = iced::Color::from_rgb8(1, 2, 3); colors[super::ColorOption::Border.index()] = iced::Color::from_rgb8(4, 5, 6); let file = super::ThemeFile::from_colors( "Test theme".to_owned(), theme::Preference::Dark, &colors, &super::DEFAULT_COLORS, true, &super::builtin_toast_colors(theme::Preference::Dark), &super::Typography::default(), ); let text = toml::to_string(&file).unwrap(); assert!(text.contains("name = \"Test theme\"")); assert!(text.contains("based_on = \"dark\"")); assert!(text.contains("accent = \"#010203\"")); assert!(text.contains("border = \"#040506\"")); assert!(!text.contains("active_tab_outline")); assert!(text.contains("[typography.h1]")); assert!(text.contains(&format!("font = \"{}\"", super::default_ui_font()))); assert!(text.contains("[toast]")); assert!(text.contains("enabled = true")); assert!(text.contains("background = \"#")); assert!(file.toast.enabled); let loaded = file.colors(theme::Preference::Dark); assert_eq!( loaded[super::ColorOption::Accent.index()], iced::Color::from_rgb8(1, 2, 3) ); assert_eq!( loaded[super::ColorOption::Text.index()], super::DEFAULT_COLORS[super::ColorOption::Text.index()] ); } #[test] fn color_picker_updates_the_swatch_and_closes() { let mut state = state(); let option = super::ColorOption::Accent; let color = iced::Color::from_rgb(0.1, 0.2, 0.3); let _ = update(&mut state, Message::OpenColorPicker(option)); assert_eq!(state.open_color_picker, Some(option)); let _ = update(&mut state, Message::SubmitColor(option, color)); assert_eq!(state.colors[option.index()], color); assert_eq!(state.open_color_picker, None); } #[test] fn toaster_color_picker_updates_only_toast_colors() { let mut state = state(); // A custom theme keeps edits out of the config file and in the theme file. state.theme_choice = super::ThemeChoice::Custom { id: "test".to_owned(), name: "Test".to_owned(), }; let option = super::ToastColorOption::Info; let color = iced::Color::from_rgb(0.4, 0.5, 0.6); let _ = update(&mut state, Message::SetCustomToasts(true)); let _ = update(&mut state, Message::OpenToastColorPicker(option)); assert_eq!(state.open_toast_color_picker, Some(option)); let _ = update(&mut state, Message::SubmitToastColor(option, color)); assert_eq!(state.toast_colors[option.index()], color); assert_eq!(state.open_toast_color_picker, None); assert_eq!(state.colors, super::DEFAULT_COLORS); let _ = update(&mut state, Message::SetCustomToasts(false)); assert!(!state.custom_toasts); } #[test] fn builtin_toast_config_is_loaded_from_toml() { let config: super::ConfigFile = toml::from_str( r##" [appearance] theme = "dark" [appearance.toast] enabled = true info = "#010203" "##, ) .unwrap(); let (enabled, colors) = super::builtin_toast_config(&config.appearance); assert!(enabled); assert_eq!( colors[super::ToastColorOption::Info.index()], iced::Color::from_rgb8(1, 2, 3) ); } #[test] fn theme_file_round_trips_toast_settings() { let mut toast = super::builtin_toast_colors(theme::Preference::Dark); toast[super::ToastColorOption::Background.index()] = iced::Color::from_rgb8(1, 2, 3); let file = super::ThemeFile::from_colors( "Test theme".to_owned(), theme::Preference::Dark, &super::DEFAULT_COLORS, &super::DEFAULT_COLORS, true, &toast, &super::Typography::default(), ); let text = toml::to_string_pretty(&file).unwrap(); let loaded: super::ThemeFile = toml::from_str(&text).unwrap(); assert!(loaded.toast.enabled); assert_eq!( loaded.toast.colors(theme::Preference::Dark) [super::ToastColorOption::Background.index()], iced::Color::from_rgb8(1, 2, 3) ); } #[test] fn tab_close_fades_in_and_out() { let mut state = state(); let tab = Tab::Start; let _ = update(&mut state, Message::HoverTab { tab, hovered: true }); let later = iced::time::Instant::now() + iced::time::Duration::from_secs(1); let fade = state.tab_close_fades.get(&tab).unwrap(); assert!(fade.interpolate(0.0, 1.0, later) > 0.99); let _ = update( &mut state, Message::HoverTab { tab, hovered: false, }, ); let end = iced::time::Instant::now() + iced::time::Duration::from_secs(2); let fade = state.tab_close_fades.get(&tab).unwrap(); assert!(fade.interpolate(0.0, 1.0, end) < 0.01); } #[test] fn tab_scroll_buttons_follow_the_viewport() { let mut state = state(); let window = test_window(); { let window_state = window_state_mut(&mut state); // 349px window => 200px strip; five tabs overflow at the min width. window_state.size = iced::Size::new(349.0, 768.0); window_state.tabs = (1..=5).map(Tab::Blank).collect(); } window_state_mut(&mut state).tab_offset = 0.0; assert_eq!(super::tab_scroll_limits(&state, window), (false, true)); window_state_mut(&mut state).tab_offset = 150.0; assert_eq!(super::tab_scroll_limits(&state, window), (true, true)); window_state_mut(&mut state).tab_offset = 310.0; assert_eq!(super::tab_scroll_limits(&state, window), (true, false)); } #[test] fn add_tab_appends_a_new_blank_tab() { let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::SelectTab(window, Tab::Settings)); let _ = update(&mut state, Message::AddTab(window)); let _ = update(&mut state, Message::AddTab(window)); let window_state = window_state(&state); assert_eq!( window_state.tabs, vec![Tab::Settings, Tab::Blank(1), Tab::Blank(2)] ); assert_eq!(window_state.active_tab, Some(Tab::Blank(2))); assert_eq!(window_state.tabs[1].title(), "temp 1"); assert_eq!(window_state.tabs[2].title(), "temp 2"); } #[test] fn revealing_active_tab_only_scrolls_when_needed() { let mut state = state(); let window = test_window(); { let window_state = window_state_mut(&mut state); // 549px window => 400px strip; ten tabs overflow at the min width. window_state.size = iced::Size::new(549.0, 768.0); window_state.tabs = (1..=10).map(Tab::Blank).collect(); window_state.active_tab = Some(Tab::Blank(10)); } window_state_mut(&mut state).tab_offset = 620.0; assert_eq!(super::tab_reveal_delta(&state, window), None); window_state_mut(&mut state).tab_offset = 0.0; assert!(super::tab_reveal_delta(&state, window).unwrap() > 0.0); } #[test] fn close_other_tabs_keeps_only_the_active_one() { let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::SelectTab(window, Tab::Settings)); let _ = update(&mut state, Message::AddTab(window)); let _ = update(&mut state, Message::AddTab(window)); let _ = update(&mut state, Message::CloseOtherTabs(window)); let window_state = window_state(&state); assert_eq!(window_state.tabs, vec![Tab::Blank(2)]); assert_eq!(window_state.active_tab, Some(Tab::Blank(2))); } #[test] fn close_active_tab_shortcut_closes_selected_tab() { let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::SelectTab(window, Tab::Settings)); let _ = update(&mut state, Message::AddTab(window)); let _ = update(&mut state, Message::CloseActiveTab(window)); let window_state = window_state(&state); assert_eq!(window_state.tabs, vec![Tab::Settings]); assert_eq!(window_state.active_tab, Some(Tab::Settings)); } #[test] fn closing_selects_the_next_tab_then_the_last() { let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::SelectTab(window, Tab::Settings)); let _ = update(&mut state, Message::AddTab(window)); let _ = update(&mut state, Message::AddTab(window)); let _ = update(&mut state, Message::SelectTab(window, Tab::Blank(1))); let _ = update(&mut state, Message::CloseTab(window, Tab::Blank(1))); assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(2))); let _ = update(&mut state, Message::CloseTab(window, Tab::Blank(2))); assert_eq!(window_state(&state).active_tab, Some(Tab::Settings)); } #[test] fn closing_the_last_tab_unloads_the_window() { let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::SelectTab(window, Tab::Settings)); assert_eq!(window_state(&state).tabs, vec![Tab::Settings]); assert_eq!(window_state(&state).active_tab, Some(Tab::Settings)); let _ = update( &mut state, Message::SelectSettingsSection(super::SettingsSection::Startup), ); let _ = update(&mut state, Message::CloseTab(window, Tab::Settings)); assert!(!state.windows.contains_key(&window)); assert!(state.window_order.is_empty()); assert_eq!(state.settings_section, super::SettingsSection::General); } #[test] fn dragging_reorders_tabs_and_moving_the_last_tab_closes_the_window() { let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::SelectTab(window, Tab::Settings)); let _ = update(&mut state, Message::AddTab(window)); let _ = update(&mut state, Message::AddTab(window)); // 1024px window => 909px strip => 230px tabs with 2px gaps. state.drag = Some(super::TabDrag { window, tab: Tab::Settings, origin: iced::Point::new(10.0, 20.0), pointer: iced::Point::new(585.0, 20.0), moved: true, detach: false, }); // The move is pending until release. assert_eq!( window_state(&state).tabs, vec![Tab::Settings, Tab::Blank(1), Tab::Blank(2)] ); assert_eq!(super::tab_gap_index(&state, window, 585.0), Some(3)); let _ = super::finish_drag(&mut state, window); assert_eq!( window_state(&state).tabs, vec![Tab::Blank(1), Tab::Blank(2), Tab::Settings] ); let destination = iced::window::Id::unique(); state.windows.insert( destination, super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None), ); state.window_order.push(destination); let source = window_state_mut(&mut state); source.tabs = vec![Tab::Settings]; source.active_tab = Some(Tab::Settings); super::move_tab_to_window(&mut state, window, destination, Tab::Settings); let _ = super::close_window_if_empty(&mut state, window); assert!(!state.windows.contains_key(&window)); assert_eq!(state.windows[&destination].active_tab, Some(Tab::Settings)); assert_eq!( super::window_title(&state, destination), "Settings - Moorly" ); } #[test] fn drop_panel_selects_the_window_under_the_pointer() { let mut state = state(); let source = test_window(); let destination = iced::window::Id::unique(); state.windows.insert( destination, super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None), ); state.window_order.push(destination); let rect = super::drop_panel_rect(window_state(&state), 1); let row_y = rect.y + super::DROP_PANEL_PADDING + super::DROP_HEADER_HEIGHT + super::DROP_ROW_GAP + super::DROP_ROW_HEIGHT / 2.0; let point = iced::Point::new(rect.x + 10.0, row_y); assert_eq!( super::drop_target_at(&state, source, point), Some(destination) ); assert_eq!( super::drop_target_at(&state, source, iced::Point::new(0.0, 0.0)), None ); } #[test] fn dragging_near_an_edge_requests_autoscroll() { let mut state = state(); let window = test_window(); window_state_mut(&mut state).tabs = (1..=20).map(Tab::Blank).collect(); let viewport = super::tab_strip_width(1024.0, true); state.drag = Some(super::TabDrag { window, tab: Tab::Blank(1), origin: iced::Point::new(10.0, 20.0), pointer: iced::Point::new(super::TAB_STRIP_LEFT + viewport - 2.0, 20.0), moved: true, detach: false, }); assert!(super::drag_scroll_delta(&state).unwrap() > 0.0); state.drag.as_mut().unwrap().pointer = iced::Point::new(6.0, 20.0); assert!(super::drag_scroll_delta(&state).unwrap() < 0.0); } #[test] fn shortcuts_round_trip_through_text() { let shortcut = super::Shortcut::parse("ctrl+shift+k").unwrap(); assert_eq!(shortcut.to_string(), "Ctrl+Shift+K"); assert_eq!( super::Shortcut::parse("Ctrl+,").unwrap().to_string(), "Ctrl+," ); assert_eq!( super::Shortcut::parse("Ctrl+Shift+Space") .unwrap() .to_string(), "Ctrl+Shift+Space" ); assert_eq!(super::Shortcut::parse("Ctrl+"), None); assert_eq!(super::Shortcut::parse("Hyper+K"), None); } #[test] fn space_shortcuts_match_the_space_key() { let shortcut = super::Shortcut::parse("Ctrl+Shift+Space").unwrap(); assert!(shortcut.matches( &keyboard::Key::Named(keyboard::key::Named::Space), keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT, )); } #[test] fn command_palette_toggles_and_closes() { let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::ToggleCommandPalette(window)); assert!(window_state(&state).command_palette_open); let _ = update(&mut state, Message::ToggleCommandPalette(window)); assert!(!window_state(&state).command_palette_open); let _ = update(&mut state, Message::ToggleCommandPalette(window)); let _ = update(&mut state, Message::CloseCommandPalette(window)); assert!(!window_state(&state).command_palette_open); } #[test] fn command_palette_fuzzy_matches_and_runs_settings() { assert!(super::fuzzy_match("Settings", "stg")); assert!(super::fuzzy_match("Settings", "")); assert!(!super::fuzzy_match("Settings", "xyz")); let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::ToggleCommandPalette(window)); let _ = update( &mut state, Message::CommandPaletteChanged(window, "sett".to_owned()), ); assert_eq!( super::Command::matching(&state, window, "sett"), vec![super::Command::Settings] ); assert_eq!( super::Command::matching(&state, window, "exit"), vec![super::Command::Exit] ); let _ = update(&mut state, Message::RunSelectedCommand(window)); assert_eq!(window_state(&state).active_tab, Some(Tab::Settings)); assert!(!window_state(&state).command_palette_open); } #[test] fn quick_add_menu_toggles_and_closes() { let mut state = state(); let window = test_window(); let _ = update(&mut state, Message::ToggleQuickAddMenu(window)); assert!(window_state(&state).quick_menu_open); assert!(!window_state(&state).menu_open); let _ = update(&mut state, Message::QuickTerminal(window)); assert!(!window_state(&state).quick_menu_open); let _ = update(&mut state, Message::ToggleQuickAddMenu(window)); let _ = update(&mut state, Message::CloseQuickAddMenu(window)); assert!(!window_state(&state).quick_menu_open); } #[test] fn commands_report_their_configured_shortcuts() { let state = state(); assert_eq!( super::Command::Settings.shortcut(&state), Some("Ctrl+,".to_owned()) ); assert_eq!( super::Command::Exit.shortcut(&state), Some("Ctrl+Shift+Q".to_owned()) ); assert_eq!( super::Command::QuickTerminal.shortcut(&state), Some("Ctrl+Shift+T".to_owned()) ); assert_eq!( super::Command::QuickSsh.shortcut(&state), Some("Ctrl+Shift+S".to_owned()) ); assert_eq!( super::Command::Close.shortcut(&state), Some("Ctrl+Shift+W".to_owned()) ); assert_eq!(super::Command::Left.shortcut(&state), None); } #[test] fn quick_commands_are_in_the_palette_and_do_nothing_yet() { let mut state = state(); let window = test_window(); let tabs = window_state(&state).tabs.clone(); assert_eq!( super::Command::matching(&state, window, "quick terminal"), vec![super::Command::QuickTerminal] ); assert_eq!( super::Command::matching(&state, window, "quick ssh"), vec![super::Command::QuickSsh] ); let _ = update( &mut state, Message::RunCommand(window, super::Command::QuickTerminal), ); let _ = update( &mut state, Message::RunCommand(window, super::Command::QuickSsh), ); assert_eq!(window_state(&state).tabs, tabs); } #[test] fn left_and_right_commands_switch_adjacent_tabs() { let mut state = state(); let window = test_window(); window_state_mut(&mut state).tabs = vec![Tab::Start, Tab::Settings, Tab::Blank(1)]; window_state_mut(&mut state).active_tab = Some(Tab::Start); assert!(super::Command::matching(&state, window, "left").is_empty()); assert_eq!( super::Command::matching(&state, window, "right"), vec![super::Command::Right] ); let _ = update( &mut state, Message::RunCommand(window, super::Command::Right), ); assert_eq!(window_state(&state).active_tab, Some(Tab::Settings)); assert_eq!( super::Command::matching(&state, window, "left"), vec![super::Command::Left] ); let _ = update( &mut state, Message::RunCommand(window, super::Command::Left), ); assert_eq!(window_state(&state).active_tab, Some(Tab::Start)); window_state_mut(&mut state).active_tab = Some(Tab::Blank(1)); assert!(super::Command::matching(&state, window, "right").is_empty()); let _ = update( &mut state, Message::RunCommand(window, super::Command::Right), ); assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(1))); } #[test] fn command_palette_close_closes_the_active_tab() { let mut state = state(); let window = test_window(); window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)]; window_state_mut(&mut state).active_tab = Some(Tab::Settings); let _ = update(&mut state, Message::ToggleCommandPalette(window)); let _ = update( &mut state, Message::CommandPaletteChanged(window, "close".to_owned()), ); let _ = update(&mut state, Message::RunSelectedCommand(window)); assert_eq!(window_state(&state).tabs, vec![Tab::Blank(1)]); assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(1))); assert!(!window_state(&state).command_palette_open); } #[test] fn move_command_detaches_the_active_tab_to_a_new_window() { let mut state = state(); let window = test_window(); window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)]; window_state_mut(&mut state).active_tab = Some(Tab::Settings); let _ = update(&mut state, Message::ToggleCommandPalette(window)); let _ = update( &mut state, Message::CommandPaletteChanged(window, "move".to_owned()), ); let _ = update(&mut state, Message::RunSelectedCommand(window)); assert_eq!(state.windows.len(), 2); let detached = *state.window_order.last().unwrap(); assert_eq!(state.windows[&detached].active_tab, Some(Tab::Settings)); assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(1))); } #[test] fn move_command_lists_windows_and_moves_to_the_selected_one() { let mut state = state(); let window = test_window(); let destination = iced::window::Id::unique(); state.windows.insert( destination, super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None), ); state.window_order.push(destination); window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)]; window_state_mut(&mut state).active_tab = Some(Tab::Settings); assert_eq!( super::Command::matching(&state, window, "move"), vec![ super::Command::Move, super::Command::MoveToWindow(destination) ] ); let _ = update(&mut state, Message::ToggleCommandPalette(window)); let _ = update( &mut state, Message::CommandPaletteChanged(window, "move".to_owned()), ); let _ = update(&mut state, Message::CommandPaletteDown(window)); let _ = update(&mut state, Message::RunSelectedCommand(window)); assert_eq!(window_state(&state).tabs, vec![Tab::Blank(1)]); assert_eq!(state.windows[&destination].active_tab, Some(Tab::Settings)); } #[test] fn command_palette_focuses_a_matching_window() { let mut state = state(); let window = test_window(); let destination = iced::window::Id::unique(); state.windows.insert( destination, super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None), ); state.window_order.push(destination); assert_eq!( super::Command::matching(&state, window, "temp 9"), vec![ super::Command::FocusWindow(destination), super::Command::FocusTab(destination, Tab::Blank(9)) ] ); let _ = update(&mut state, Message::ToggleCommandPalette(window)); let _ = update( &mut state, Message::CommandPaletteChanged(window, "temp 9".to_owned()), ); let _ = update(&mut state, Message::RunSelectedCommand(window)); assert_eq!(state.focused_window, Some(destination)); } #[test] fn command_palette_focuses_a_matching_tab_in_its_window() { let mut state = state(); let window = test_window(); let destination = iced::window::Id::unique(); let mut destination_state = super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None); destination_state.tabs.push(Tab::Settings); state.windows.insert(destination, destination_state); state.window_order.push(destination); assert_eq!( super::Command::matching(&state, window, "settings"), vec![ super::Command::Settings, super::Command::FocusTab(destination, Tab::Settings) ] ); let _ = update(&mut state, Message::ToggleCommandPalette(window)); let _ = update( &mut state, Message::CommandPaletteChanged(window, "settings".to_owned()), ); let _ = update(&mut state, Message::CommandPaletteDown(window)); let _ = update(&mut state, Message::RunSelectedCommand(window)); assert_eq!(state.focused_window, Some(destination)); assert_eq!(state.windows[&destination].active_tab, Some(Tab::Settings)); } #[test] fn command_palette_selects_a_matching_profile() { let mut state = state(); let window = test_window(); state.profile_folders[0].profiles.push(profile("Alpha")); state.profile_folders[0].expanded = false; assert_eq!( super::Command::matching(&state, window, "alph"), vec![super::Command::SelectProfile { folder: 0, profile: 0 }] ); let _ = update(&mut state, Message::ToggleCommandPalette(window)); let _ = update( &mut state, Message::CommandPaletteChanged(window, "alph".to_owned()), ); let _ = update(&mut state, Message::RunSelectedCommand(window)); assert_eq!( state.selected, Some(super::Selection::Profile { folder: 0, profile: 0 }) ); assert!(state.profile_folders[0].expanded); assert_eq!(window_state(&state).active_tab, Some(Tab::Start)); } fn press(key: keyboard::Key, modifiers: keyboard::Modifiers) -> Message { Message::CaptureKey { key, modifiers } } #[test] fn changing_the_settings_shortcut_rebinds_it() { let mut state = state(); let _ = update( &mut state, Message::OpenShortcutCapture(super::ShortcutAction::Settings), ); let _ = update( &mut state, press( keyboard::Key::Character("k".into()), keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT, ), ); assert_eq!( state .shortcut_capture .as_ref() .unwrap() .candidate .as_ref() .unwrap() .to_string(), "Ctrl+Shift+K" ); let _ = update(&mut state, Message::ApplyShortcut); assert_eq!( state.shortcuts.settings.as_ref().map(ToString::to_string), Some("Ctrl+Shift+K".to_owned()) ); assert!(state.shortcut_capture.is_none()); } #[test] fn conflicting_shortcuts_are_rejected() { let mut state = state(); let _ = update( &mut state, Message::OpenShortcutCapture(super::ShortcutAction::Settings), ); let _ = update( &mut state, press( keyboard::Key::Character("w".into()), keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT, ), ); let _ = update(&mut state, Message::ApplyShortcut); assert_eq!( state.shortcuts.settings.as_ref().map(ToString::to_string), Some("Ctrl+,".to_owned()) ); assert!(state.shortcut_capture.as_ref().unwrap().error.is_some()); } #[test] fn shortcuts_cannot_steal_each_others_keys() { let mut state = state(); let _ = update( &mut state, Message::OpenShortcutCapture(super::ShortcutAction::Settings), ); let _ = update( &mut state, press( keyboard::Key::Character("q".into()), keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT, ), ); let _ = update(&mut state, Message::ApplyShortcut); assert_eq!( state.shortcuts.settings.as_ref().map(ToString::to_string), Some("Ctrl+,".to_owned()) ); assert_eq!( state.shortcuts.quit.as_ref().map(ToString::to_string), Some("Ctrl+Shift+Q".to_owned()) ); } #[test] fn plain_keys_are_not_accepted_as_shortcuts() { let mut state = state(); let _ = update( &mut state, Message::OpenShortcutCapture(super::ShortcutAction::Settings), ); let _ = update( &mut state, press( keyboard::Key::Character("k".into()), keyboard::Modifiers::NONE, ), ); assert!(state.shortcut_capture.as_ref().unwrap().candidate.is_none()); assert!(state.shortcut_capture.as_ref().unwrap().error.is_some()); } #[test] fn clearing_a_shortcut_removes_only_that_binding() { let mut state = state(); let _ = update( &mut state, Message::ClearShortcut(super::ShortcutAction::Settings), ); assert!(state.shortcuts.settings.is_none()); assert!(state.shortcuts.quit.is_some()); } #[test] fn restoring_a_shortcut_default_rebinds_it() { let mut state = state(); let _ = update( &mut state, Message::ClearShortcut(super::ShortcutAction::Settings), ); assert!(state.shortcuts.settings.is_none()); let _ = update( &mut state, Message::DefaultShortcut(super::ShortcutAction::Settings), ); assert_eq!( state.shortcuts.settings.as_ref().map(ToString::to_string), Some("Ctrl+,".to_owned()) ); } #[test] fn quit_has_a_default_shortcut() { let state = state(); assert_eq!( state.shortcuts.quit.as_ref().map(ToString::to_string), Some("Ctrl+Shift+Q".to_owned()) ); } #[test] fn quick_actions_have_default_shortcuts() { let state = state(); assert_eq!( state .shortcuts .quick_terminal .as_ref() .map(ToString::to_string), Some("Ctrl+Shift+T".to_owned()) ); assert_eq!( state.shortcuts.quick_ssh.as_ref().map(ToString::to_string), Some("Ctrl+Shift+S".to_owned()) ); } #[test] fn profiles_start_with_an_ungrouped_map() { let state = state(); assert_eq!(state.profile_folders.len(), 1); assert_eq!(state.profile_folders[0].name, "Ungrouped"); assert!(state.profile_folders[0].profiles.is_empty()); } #[test] fn clicking_a_folder_toggles_its_profiles() { let mut state = state(); assert!(state.profile_folders[0].expanded); let _ = update(&mut state, Message::ToggleFolder(0)); assert!(!state.profile_folders[0].expanded); assert_eq!(state.selected, Some(super::Selection::Folder(0))); let _ = update(&mut state, Message::ToggleFolder(0)); assert!(state.profile_folders[0].expanded); } #[test] fn add_menu_opens_the_folder_dialog() { let mut state = state(); let _ = update(&mut state, Message::ToggleAddMenu); assert!(state.add_menu_open); let _ = update(&mut state, Message::OpenFolderDialog); assert_eq!( state .folder_dialog .as_ref() .map(|draft| draft.name.as_str()), Some("") ); assert_eq!( state.folder_dialog.as_ref().map(|draft| draft.parent.index), Some(super::ROOT_FOLDER_INDEX) ); assert!(!state.add_menu_open); let _ = update(&mut state, Message::FolderNameChanged("Work".to_owned())); let _ = update(&mut state, Message::ConfirmFolder); assert_eq!(state.profile_folders.len(), 2); assert_eq!(state.profile_folders[1].name, "Work"); assert!(state.folder_dialog.is_none()); } #[test] fn cancelling_a_folder_does_not_add_it() { let mut state = state(); let _ = update(&mut state, Message::OpenFolderDialog); let _ = update(&mut state, Message::FolderNameChanged("Work".to_owned())); let _ = update(&mut state, Message::CancelFolder); assert_eq!(state.profile_folders.len(), 1); assert!(state.folder_dialog.is_none()); } #[test] fn empty_folder_names_are_rejected() { let mut state = state(); let _ = update(&mut state, Message::OpenFolderDialog); let _ = update(&mut state, Message::FolderNameChanged(" ".to_owned())); let _ = update(&mut state, Message::ConfirmFolder); assert_eq!(state.profile_folders.len(), 1); assert!(state.folder_dialog.is_some()); } #[test] fn adding_a_profile_opens_its_folder_and_selects_it() { let mut state = state(); let _ = update(&mut state, Message::ToggleFolder(0)); assert!(!state.profile_folders[0].expanded); let _ = update(&mut state, Message::OpenProfileDialog); let _ = update(&mut state, Message::ProfileNameChanged("Server".to_owned())); let _ = update(&mut state, Message::ConfirmProfile); assert!(state.profile_folders[0].expanded); assert_eq!( state.selected, Some(super::Selection::Profile { folder: 0, profile: 0, }) ); } #[test] fn editing_a_profile_updates_it_in_place() { let mut state = state(); state.profile_folders[0].profiles.push(profile("Old")); let color = iced::Color::from_rgb8(0x12, 0x34, 0x56); let _ = update( &mut state, Message::EditProfile { folder: 0, profile: 0, }, ); assert_eq!(state.profile_dialog.as_ref().unwrap().name, "Old"); let _ = update(&mut state, Message::ProfileNameChanged("New".to_owned())); let _ = update( &mut state, Message::ProfileHostChanged("new.example".to_owned()), ); let _ = update( &mut state, Message::ProfileKindSelected(super::ProfileKind::Terminal), ); let _ = update(&mut state, Message::SubmitProfileColor(color)); let _ = update(&mut state, Message::ConfirmProfile); assert!(state.profile_dialog.is_none()); assert_eq!(state.profile_folders[0].profiles.len(), 1); let profile = &state.profile_folders[0].profiles[0]; assert_eq!(profile.name, "New"); assert_eq!(profile.host, "new.example"); assert_eq!(profile.kind, super::ProfileKind::Terminal); assert_eq!(profile.glyph_color, color); } #[test] fn profile_dialog_stores_the_entered_details() { let mut state = state(); let _ = update(&mut state, Message::OpenProfileDialog); let _ = update(&mut state, Message::ProfileNameChanged("Server".to_owned())); let _ = update( &mut state, Message::ProfileHostChanged("example.com".to_owned()), ); let _ = update(&mut state, Message::ProfilePortChanged("2222".to_owned())); let _ = update( &mut state, Message::ProfileUsernameChanged("root".to_owned()), ); let _ = update( &mut state, Message::ProfilePasswordChanged("hunter2".to_owned()), ); let _ = update( &mut state, Message::ProfileKindSelected(super::ProfileKind::Ssh), ); let _ = update( &mut state, Message::SessionEndSelected(super::SessionEnd::Reconnect), ); let _ = update(&mut state, Message::ConfirmProfile); let profile = &state.profile_folders[0].profiles[0]; assert_eq!(profile.name, "Server"); assert_eq!(profile.host, "example.com"); assert_eq!(profile.port, "2222"); assert_eq!(profile.username, "root"); assert_eq!(profile.password, "hunter2"); assert_eq!(profile.session_end, super::SessionEnd::Reconnect); } #[test] fn auth_method_is_exclusive_and_password_visibility_toggles() { let mut state = state(); let _ = update(&mut state, Message::OpenProfileDialog); let _ = update( &mut state, Message::AuthMethodSelected(super::AuthMethod::Key), ); assert_eq!( state.profile_dialog.as_ref().unwrap().auth, super::AuthMethod::Key ); let _ = update(&mut state, Message::TogglePasswordVisibility); assert!(state.profile_dialog.as_ref().unwrap().password_visible); let _ = update(&mut state, Message::TogglePasswordVisibility); assert!(!state.profile_dialog.as_ref().unwrap().password_visible); } #[test] fn profile_port_only_accepts_0_to_65534() { let mut state = state(); let _ = update(&mut state, Message::OpenProfileDialog); let _ = update(&mut state, Message::ProfilePortChanged("65534".to_owned())); assert_eq!(state.profile_dialog.as_ref().unwrap().port, "65534"); let _ = update(&mut state, Message::ProfilePortChanged("65535".to_owned())); assert_eq!(state.profile_dialog.as_ref().unwrap().port, "65534"); let _ = update(&mut state, Message::ProfilePortChanged("abc".to_owned())); assert_eq!(state.profile_dialog.as_ref().unwrap().port, "65534"); let _ = update(&mut state, Message::ProfilePortChanged(String::new())); assert_eq!(state.profile_dialog.as_ref().unwrap().port, ""); } #[test] fn profile_names_are_limited_to_150_chars() { let mut state = state(); let _ = update(&mut state, Message::OpenProfileDialog); let _ = update(&mut state, Message::ProfileNameChanged("a".repeat(200))); assert_eq!( state.profile_dialog.as_ref().unwrap().name.chars().count(), 150 ); } #[test] fn terminal_profiles_store_the_start_path() { let mut state = state(); let _ = update(&mut state, Message::OpenProfileDialog); let draft = state.profile_dialog.as_ref().unwrap(); if cfg!(windows) { assert!(!draft.start_path.is_empty()); } else { assert_eq!(draft.start_path, "~/"); } let _ = update( &mut state, Message::ProfileKindSelected(super::ProfileKind::Terminal), ); let _ = update(&mut state, Message::ProfileNameChanged("Term".to_owned())); let _ = update( &mut state, Message::ProfileStartPathChanged("/tmp".to_owned()), ); let _ = update(&mut state, Message::ConfirmProfile); assert_eq!(state.profile_folders[0].profiles[0].start_path, "/tmp"); } #[test] fn directory_picker_lists_subdirectories() { let stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); let root = std::env::temp_dir().join(format!("moorly-test-{stamp}")); let child = root.join("child"); std::fs::create_dir_all(&child).unwrap(); let picker = super::DirPicker::open(root.clone(), false, super::PickerTarget::StartPath); assert_eq!(picker.entries, vec![child]); assert!(picker.error.is_none()); std::fs::remove_dir_all(&root).unwrap(); } #[test] fn private_key_picker_selects_a_file() { let stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); let root = std::env::temp_dir().join(format!("moorly-key-test-{stamp}")); std::fs::create_dir_all(&root).unwrap(); let key = root.join("id_test"); std::fs::write(&key, b"key").unwrap(); let mut picker = super::DirPicker::open(root.clone(), true, super::PickerTarget::PrivateKey); assert_eq!(picker.entries, vec![key.clone()]); assert!(!picker.can_confirm()); picker.selected = Some(key.clone()); assert!(picker.can_confirm()); let mut state = state(); state.profile_dialog = Some(super::ProfileDraft::new(0)); state.dir_picker = Some(picker); let _ = update(&mut state, Message::ConfirmDirectoryPicker); assert_eq!( state.profile_dialog.as_ref().unwrap().private_key, key.to_string_lossy() ); assert!(state.dir_picker.is_none()); std::fs::remove_dir_all(&root).unwrap(); } #[test] fn adding_a_folder_selects_it() { let mut state = state(); let _ = update(&mut state, Message::OpenFolderDialog); let _ = update(&mut state, Message::FolderNameChanged("Work".to_owned())); let _ = update(&mut state, Message::ConfirmFolder); assert_eq!(state.profile_folders[1].name, "Work"); assert_eq!(state.selected, Some(super::Selection::Folder(1))); } #[test] fn new_folder_defaults_to_the_selected_folder() { let mut state = state(); let _ = update(&mut state, Message::OpenFolderDialog); let _ = update(&mut state, Message::FolderNameChanged("Work".to_owned())); let _ = update(&mut state, Message::ConfirmFolder); let _ = update(&mut state, Message::OpenFolderDialog); let parent = state.folder_dialog.as_ref().unwrap().parent.clone(); assert_eq!(parent.name, "Work"); let _ = update( &mut state, Message::FolderNameChanged("Production".to_owned()), ); let _ = update(&mut state, Message::ConfirmFolder); assert!( state .profile_folders .iter() .any(|folder| folder.path == "Work/Production") ); } #[test] fn new_folder_defaults_to_the_selected_profiles_folder() { let mut state = state(); let index = super::ensure_folder(&mut state.profile_folders, "Work"); state.profile_folders[index] .profiles .push(profile("Server")); state.selected = Some(super::Selection::Profile { folder: index, profile: 0, }); let _ = update(&mut state, Message::OpenFolderDialog); let parent = state.folder_dialog.as_ref().unwrap().parent.clone(); assert_eq!(parent.name, "Work"); // The drop-down can still override the default destination. let _ = update( &mut state, Message::FolderParentSelected(super::root_folder_choice()), ); let _ = update(&mut state, Message::FolderNameChanged("Top".to_owned())); let _ = update(&mut state, Message::ConfirmFolder); assert!( state .profile_folders .iter() .any(|folder| folder.path == "Top") ); } #[test] fn checkboxes_toggle_and_clear() { let mut state = state(); let _ = update( &mut state, Message::ToggleChecked(super::Selection::Folder(0)), ); assert!(state.checked.contains(&super::Selection::Folder(0))); let _ = update( &mut state, Message::ToggleChecked(super::Selection::Profile { folder: 0, profile: 0, }), ); assert_eq!(state.checked.len(), 2); let _ = update(&mut state, Message::DeselectAll); assert!(state.checked.is_empty()); } #[test] fn delete_removes_checked_profiles_and_folders() { let mut state = state(); state.profile_folders = vec![ super::ProfileFolder::default_folder(), super::ProfileFolder::from_path("Work".to_owned()), super::ProfileFolder::from_path("Work/Sub".to_owned()), ]; state.profile_folders[0].profiles.push(profile("Loose")); state.profile_folders[1].profiles.push(profile("Inside")); state.profile_folders[2].profiles.push(profile("Nested")); state.checked.insert(super::Selection::Profile { folder: 0, profile: 0, }); state.checked.insert(super::Selection::Folder(1)); let _ = update(&mut state, Message::DeleteChecked); assert!(state.confirm_delete); let _ = update(&mut state, Message::ConfirmDelete); assert!(state.checked.is_empty()); assert!(!state.confirm_delete); assert!( state .profile_folders .iter() .all(|folder| folder.path != "Work") ); // Unchecked children move up instead of going with the deleted folder. let sub = state .profile_folders .iter() .find(|folder| folder.path == "Sub") .unwrap(); assert_eq!(sub.profiles.len(), 1); assert_eq!(sub.profiles[0].name, "Nested"); let default = state .profile_folders .iter() .find(|folder| folder.path == "Ungrouped") .unwrap(); assert_eq!(default.profiles.len(), 1); assert_eq!(default.profiles[0].name, "Inside"); } #[test] fn copy_and_move_transfer_checked_profiles() { let mut state = state(); state.profile_folders = vec![ super::ProfileFolder::default_folder(), super::ProfileFolder::from_path("Work".to_owned()), ]; state.profile_folders[0].profiles.push(profile("Source")); state.checked.insert(super::Selection::Profile { folder: 0, profile: 0, }); let _ = update(&mut state, Message::CopyChecked); let _ = update( &mut state, Message::TransferFolderSelected(super::FolderChoice { index: 1, name: "Work".to_owned(), }), ); let _ = update(&mut state, Message::ConfirmTransfer); assert_eq!(state.profile_folders[0].profiles.len(), 1); assert_eq!(state.profile_folders[1].profiles.len(), 1); assert_eq!(state.profile_folders[1].profiles[0].name, "Source"); state.checked.insert(super::Selection::Profile { folder: 0, profile: 0, }); let _ = update(&mut state, Message::MoveChecked); let _ = update( &mut state, Message::TransferFolderSelected(super::FolderChoice { index: 1, name: "Work".to_owned(), }), ); let _ = update(&mut state, Message::ConfirmTransfer); assert!(state.profile_folders[0].profiles.is_empty()); assert_eq!(state.profile_folders[1].profiles.len(), 2); } #[test] fn trash_restore_recreates_folders_and_profiles() { let mut state = state(); state.profile_folders = vec![super::ProfileFolder::default_folder()]; let mut profile_file = super::ProfileFile::from_profile(&profile("Loose"), "Ungrouped"); profile_file.trash = Some(super::TrashInfo { previous_path: "Ungrouped".to_owned(), deleted: "2026-11-07 12:00:00".to_owned(), }); state.trash_entries = vec![ super::TrashEntry::Folder(super::TrashFolder { name: "Work".to_owned(), previous_path: String::new(), deleted: "2026-11-07 12:00:00".to_owned(), }), super::TrashEntry::Profile { file: std::path::PathBuf::from("/nonexistent/trash.toml"), profile: profile_file, }, ]; state.trash_checked.insert(0); state.trash_checked.insert(1); let _ = update(&mut state, Message::RestoreSelected); assert!(state.trash_entries.is_empty()); assert_eq!(state.profile_folders[0].profiles.len(), 1); assert_eq!(state.profile_folders[0].profiles[0].name, "Loose"); let work = state .profile_folders .iter() .find(|folder| folder.path == "Work") .unwrap(); assert!(work.profiles.is_empty()); } #[test] fn trash_purge_deletes_only_checked_entries() { let mut state = state(); state.trash_entries = vec![ super::TrashEntry::Folder(super::TrashFolder { name: "Keep".to_owned(), previous_path: String::new(), deleted: "2026-11-07 12:00:00".to_owned(), }), super::TrashEntry::Folder(super::TrashFolder { name: "Remove".to_owned(), previous_path: String::new(), deleted: "2026-11-07 12:00:00".to_owned(), }), ]; state.trash_checked.insert(1); let _ = update(&mut state, Message::PurgeTrashSelected); assert!(state.confirm_purge_trash); let _ = update(&mut state, Message::ConfirmPurgeTrash); assert_eq!(state.trash_entries.len(), 1); assert_eq!(state.trash_entries[0].name(), "Keep"); assert!(state.trash_checked.is_empty()); assert!(!state.confirm_purge_trash); } #[test] fn moving_a_folder_moves_its_subtree() { let mut state = state(); state.profile_folders = vec![ super::ProfileFolder::default_folder(), super::ProfileFolder::from_path("Work".to_owned()), super::ProfileFolder::from_path("Home".to_owned()), ]; state.profile_folders[1].profiles.push(profile("Server")); state.checked.insert(super::Selection::Folder(1)); let _ = update(&mut state, Message::MoveChecked); let _ = update( &mut state, Message::TransferFolderSelected(super::FolderChoice { index: 2, name: "Home".to_owned(), }), ); let _ = update(&mut state, Message::ConfirmTransfer); assert!( state .profile_folders .iter() .all(|folder| folder.path != "Work") ); let moved = state .profile_folders .iter() .find(|folder| folder.path == "Home/Work") .unwrap(); assert_eq!(moved.profiles.len(), 1); assert_eq!(moved.profiles[0].name, "Server"); } #[test] fn collapsing_a_folder_hides_its_descendants() { let mut folders = vec![ super::ProfileFolder::default_folder(), super::ProfileFolder::from_path("Ungrouped/Work".to_owned()), super::ProfileFolder::from_path("Ungrouped/Work/Sub".to_owned()), super::ProfileFolder::from_path("Home".to_owned()), ]; folders[0].expanded = false; assert!(!super::folder_visible(&folders, 1)); assert!(!super::folder_visible(&folders, 2)); assert!(super::folder_visible(&folders, 3)); } #[test] fn moving_a_folder_under_ungrouped_nests_it() { let mut state = state(); state.profile_folders = vec![ super::ProfileFolder::default_folder(), super::ProfileFolder::from_path("Work".to_owned()), super::ProfileFolder::from_path("Home".to_owned()), ]; state.profile_folders[1].profiles.push(profile("Server")); state.checked.insert(super::Selection::Folder(1)); let _ = update(&mut state, Message::MoveChecked); let _ = update( &mut state, Message::TransferFolderSelected(super::FolderChoice { index: 0, name: "Ungrouped".to_owned(), }), ); let _ = update(&mut state, Message::ConfirmTransfer); let moved = state .profile_folders .iter() .find(|folder| folder.path == "Ungrouped/Work") .unwrap(); assert_eq!(moved.depth(), 1); assert_eq!(moved.profiles[0].name, "Server"); assert!( state .profile_folders .iter() .all(|folder| folder.path != "Work") ); let ungrouped = state .profile_folders .iter() .position(|folder| folder.path == "Ungrouped") .unwrap(); assert_eq!( state .profile_folders .iter() .position(|folder| folder.path == "Ungrouped/Work"), Some(ungrouped + 1) ); } #[test] fn folder_transfer_excludes_the_source_and_offers_root() { let mut state = state(); state.profile_folders = vec![ super::ProfileFolder::default_folder(), super::ProfileFolder::from_path("Home".to_owned()), super::ProfileFolder::from_path("Home/Work".to_owned()), super::ProfileFolder::from_path("Home/Work/Sub".to_owned()), super::ProfileFolder::from_path("Other".to_owned()), ]; state.checked.insert(super::Selection::Folder(2)); let choices = super::transfer_choices(&state); assert!( !choices .iter() .any(|choice| choice.name == "Home/Work" || choice.name == "Home/Work/Sub") ); assert!(choices.iter().any(|choice| choice.name == "Other")); assert!( choices .iter() .any(|choice| choice.index == super::ROOT_FOLDER_INDEX && choice.name == "Root") ); } #[test] fn moving_a_folder_to_root_makes_it_top_level() { let mut state = state(); state.profile_folders = vec![ super::ProfileFolder::default_folder(), super::ProfileFolder::from_path("Home".to_owned()), super::ProfileFolder::from_path("Home/Work".to_owned()), super::ProfileFolder::from_path("Home/Work/Sub".to_owned()), ]; state.profile_folders[2].profiles.push(profile("Server")); state.checked.insert(super::Selection::Folder(2)); let _ = update(&mut state, Message::MoveChecked); let _ = update(&mut state, Message::ConfirmTransfer); assert!( state .profile_folders .iter() .all(|folder| folder.path != "Home/Work") ); let moved = state .profile_folders .iter() .find(|folder| folder.path == "Work") .unwrap(); assert_eq!(moved.profiles[0].name, "Server"); assert!( state .profile_folders .iter() .any(|folder| folder.path == "Work/Sub") ); } #[test] fn renaming_a_folder_updates_its_subtree_but_keeps_ids() { let mut state = state(); state.profile_folders = vec![ super::ProfileFolder::default_folder(), super::ProfileFolder::from_path("Work".to_owned()), super::ProfileFolder::from_path("Work/Sub".to_owned()), ]; let work_id = state.profile_folders[1].id.clone(); let sub_id = state.profile_folders[2].id.clone(); let mut server = profile("Server"); server.folder_id = work_id.clone(); state.profile_folders[1].profiles.push(server); let mut nested = profile("Nested"); nested.folder_id = sub_id.clone(); state.profile_folders[2].profiles.push(nested); let _ = update(&mut state, Message::OpenFolderMenu(test_window(), 1)); assert_eq!(state.folder_menu.map(|(index, _)| index), Some(1)); let _ = update(&mut state, Message::FolderMenuRename(1)); let _ = update( &mut state, Message::FolderRenameChanged("Office".to_owned()), ); let _ = update(&mut state, Message::ConfirmFolderRename); assert_eq!(state.profile_folders[1].path, "Office"); assert_eq!(state.profile_folders[2].path, "Office/Sub"); assert_eq!(state.profile_folders[1].id, work_id); assert_eq!(state.profile_folders[2].id, sub_id); assert_eq!(state.profile_folders[1].profiles[0].folder_id, work_id); assert_eq!(state.profile_folders[2].profiles[0].folder_id, sub_id); } #[test] fn ungrouped_has_no_context_menu() { let mut state = state(); let _ = update(&mut state, Message::OpenFolderMenu(test_window(), 0)); assert_eq!(state.folder_menu, None); } #[test] fn trash_timestamps_are_readable() { assert_eq!(super::format_timestamp(0), "1970-01-01 00:00:00"); assert_eq!( super::format_timestamp(1_700_000_000), "2023-11-14 22:13:20" ); } #[test] fn trash_entries_load_from_folders_and_profiles() { let stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); let root = std::env::temp_dir().join(format!("moorly-trash-test-{stamp}")); std::fs::create_dir_all(&root).unwrap(); std::fs::write( root.join("folders.toml"), "[[folders]]\nname = \"Work\"\nprevious_path = \"\"\ndeleted = \"2026-11-07 12:00:00\"\n", ) .unwrap(); let mut profile_file = super::ProfileFile::from_profile(&profile("Server"), "Work"); profile_file.trash = Some(super::TrashInfo { previous_path: "Work".to_owned(), deleted: "2026-11-07 12:01:00".to_owned(), }); let text = toml::to_string_pretty(&profile_file).unwrap(); assert!(text.contains("[trash]")); std::fs::write(root.join("Server.toml"), text).unwrap(); let entries = super::load_trash_entries_from(&root); assert_eq!(entries.len(), 2); let folder = entries.iter().find(|entry| entry.is_folder()).unwrap(); assert_eq!(folder.name(), "Work"); assert_eq!(folder.previous_path(), ""); assert_eq!(folder.deleted(), "2026-11-07 12:00:00"); let profile = entries.iter().find(|entry| !entry.is_folder()).unwrap(); assert_eq!(profile.name(), "Server"); assert_eq!(profile.previous_path(), "Work"); assert_eq!(profile.deleted(), "2026-11-07 12:01:00"); std::fs::remove_dir_all(&root).unwrap(); } #[test] fn profiles_load_nested_folders_and_create_missing_parents() { let stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); let root = std::env::temp_dir().join(format!("moorly-profiles-test-{stamp}")); std::fs::create_dir_all(&root).unwrap(); std::fs::write( root.join("folders.toml"), "folders = [\"Work/Production\"]\n", ) .unwrap(); std::fs::write( root.join("Server.toml"), "name = \"Server\"\nfolder = \"Work/Production\"\nhost = \"example.com\"\n", ) .unwrap(); std::fs::write( root.join("Orphan.toml"), "name = \"Orphan\"\nfolder = \"Missing/Deep\"\nkind = \"terminal\"\n", ) .unwrap(); let folders = super::load_profiles_from(&root); let paths: Vec<&str> = folders.iter().map(|folder| folder.path.as_str()).collect(); assert!(paths.contains(&"Ungrouped")); assert!(paths.contains(&"Work")); assert!(paths.contains(&"Work/Production")); assert!(paths.contains(&"Missing")); assert!(paths.contains(&"Missing/Deep")); assert!( paths.iter().position(|path| *path == "Work") < paths.iter().position(|path| *path == "Work/Production") ); let production = folders .iter() .find(|folder| folder.path == "Work/Production") .unwrap(); assert_eq!(production.profiles.len(), 1); assert_eq!(production.profiles[0].name, "Server"); assert_eq!(production.profiles[0].host, "example.com"); assert!(!production.untracked); let work = folders.iter().find(|folder| folder.path == "Work").unwrap(); assert!(!work.untracked); let orphan = folders .iter() .find(|folder| folder.path == "Missing/Deep") .unwrap(); assert_eq!(orphan.profiles[0].name, "Orphan"); assert!(orphan.untracked); assert!( folders .iter() .find(|folder| folder.path == "Missing") .unwrap() .untracked ); super::write_folders_to(&root, &folders).unwrap(); let folders_text = std::fs::read_to_string(root.join("folders.toml")).unwrap(); assert!(folders_text.contains("name = \"Work\"")); assert!(folders_text.contains("name = \"Production\"")); assert!(folders_text.contains(&format!("parent_id = \"{}\"", work.id))); assert!(!folders_text.contains("path =")); assert!(!folders_text.contains("Missing")); std::fs::remove_dir_all(&root).unwrap(); } #[test] fn profiles_load_by_folder_uuid() { let stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); let root = std::env::temp_dir().join(format!("moorly-profile-uuid-test-{stamp}")); std::fs::create_dir_all(&root).unwrap(); let id = super::new_folder_id(); let child = super::new_folder_id(); std::fs::write( root.join("folders.toml"), format!( "[[folders]]\nid = \"{id}\"\nname = \"Work\"\n\n\ [[folders]]\nid = \"{child}\"\nname = \"Production\"\nparent_id = \"{id}\"\n" ), ) .unwrap(); std::fs::write( root.join("Server.toml"), format!("name = \"Server\"\nparent_id = \"{child}\"\n"), ) .unwrap(); let folders = super::load_profiles_from(&root); let production = folders .iter() .find(|folder| folder.path == "Work/Production") .unwrap(); assert_eq!(production.id, child); assert_eq!(production.profiles[0].folder_id, child); assert_eq!( folders .iter() .find(|folder| folder.path == "Work") .unwrap() .id, id ); std::fs::remove_dir_all(&root).unwrap(); } #[test] fn profile_files_store_the_folder_and_settings() { let stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); let root = std::env::temp_dir().join(format!("moorly-profile-file-test-{stamp}")); let profile = super::Profile { name: "Server/Test".to_owned(), kind: super::ProfileKind::Ssh, session_end: super::SessionEnd::Reconnect, host: "example.com".to_owned(), port: "2222".to_owned(), username: "root".to_owned(), auth: super::AuthMethod::Key, password: "secret".to_owned(), start_path: "/tmp".to_owned(), private_key: "/keys/id".to_owned(), glyph_color: iced::Color::WHITE, folder_id: "folder-id".to_owned(), file: None, }; let path = super::write_profile_to(&root, &profile, "Work/Production").unwrap(); assert_eq!(path.file_name().unwrap(), "Server_Test.toml"); let text = std::fs::read_to_string(&path).unwrap(); assert!(text.contains("parent_id = \"folder-id\"")); assert!(!text.contains("folder =")); assert!(!text.contains("folder_name =")); assert!(text.contains("kind = \"ssh\"")); assert!(text.contains("session_end = \"reconnect\"")); assert!(text.contains("host = \"example.com\"")); assert!(text.contains("private_key = \"/keys/id\"")); assert!(text.contains("glyph_color = \"#FFFFFF\"")); let duplicate = super::write_profile_to(&root, &profile, "Work/Production").unwrap(); assert_eq!(duplicate.file_name().unwrap(), "Server_Test-2.toml"); std::fs::remove_dir_all(&root).unwrap(); } }