diff --git a/src/main.rs b/src/main.rs index 2777629..77c91e9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ -use std::collections::HashMap; -use std::path::PathBuf; +use std::cmp::Ordering; +use std::collections::{BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; @@ -10,8 +11,8 @@ use iced::widget::{ stack, text, text_input, toggler, tooltip, }; use iced::{ - Alignment, Animation, Border, Color, Element, Length, Padding, Point, Rectangle, Shadow, Size, - Subscription, Task, Vector, keyboard, mouse, window, + Alignment, Animation, Border, Color, Element, Font, Length, Padding, Point, Rectangle, Shadow, + Size, Subscription, Task, Vector, font, keyboard, mouse, window, }; mod notifications; @@ -61,6 +62,8 @@ const THEME_NAME_INPUT: Id = Id::new("theme-name"); 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"; fn main() -> iced::Result { iced::daemon(boot, update, view) @@ -416,7 +419,8 @@ struct ShortcutCapture { error: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] enum ProfileKind { #[default] Ssh, @@ -436,7 +440,8 @@ impl ProfileKind { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] enum SessionEnd { #[default] Auto, @@ -464,7 +469,8 @@ impl std::fmt::Display for SessionEnd { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] enum AuthMethod { #[default] Password, @@ -688,22 +694,120 @@ fn resolve_start_path(input: &str) -> PathBuf { PathBuf::from(input) } -/// A named group of profiles. +/// 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 { + /// 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, } 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 { - name: "Ungrouped".to_owned(), + 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) + } + } +} + +/// Contents of `profiles/folders.toml`. +#[derive(Debug, Serialize, Deserialize)] +struct FoldersFile { + #[serde(default)] + folders: Vec, +} + +/// One `profiles/.toml` file. +#[derive(Debug, Serialize, Deserialize)] +struct ProfileFile { + #[serde(default)] + name: String, + #[serde(default)] + folder: 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, +} + +impl ProfileFile { + fn from_profile(profile: &Profile, folder: &str) -> Self { + Self { + name: profile.name.clone(), + folder: 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(), + } + } + + 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, + } + } +} + +fn default_profile_port() -> String { + "22".to_owned() } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1381,6 +1485,266 @@ fn write_custom_theme( 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| usize::from(path != DEFAULT_PROFILE_FOLDER); + rank(a).cmp(&rank(b)).then_with(|| a.cmp(b)) +} + +fn add_folder_and_parents(paths: &mut BTreeSet, path: &str) { + if path.is_empty() { + return; + } + + let mut prefix = String::new(); + for part in path.split('/') { + if !prefix.is_empty() { + prefix.push('/'); + } + prefix.push_str(part); + paths.insert(prefix.clone()); + } +} + +fn load_profiles() -> Vec { + profiles_dir() + .map(|dir| load_profiles_from(&dir)) + .unwrap_or_else(|| vec![ProfileFolder::default_folder()]) +} + +/// 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 tracked = BTreeSet::new(); + tracked.insert(DEFAULT_PROFILE_FOLDER.to_owned()); + let mut untracked = BTreeSet::new(); + + if let Ok(text) = std::fs::read_to_string(dir.join("folders.toml")) + && let Ok(file) = toml::from_str::(&text) + { + for folder in file.folders { + add_folder_and_parents(&mut tracked, &normalize_folder_path(&folder)); + } + } + + 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 = normalize_folder_path(&file.folder); + add_missing_folder_and_parents(&tracked, &mut untracked, &folder); + profiles.push((folder, file.into_profile())); + } + } + + let mut folder_paths: Vec = tracked.into_iter().collect(); + folder_paths.extend(untracked.iter().cloned()); + folder_paths.sort_by(|a, b| folder_order(a, b)); + folder_paths.dedup(); + + let mut folders: Vec = folder_paths + .into_iter() + .map(|path| { + let mut folder = ProfileFolder::from_path(path); + folder.untracked = untracked.contains(&folder.path); + folder + }) + .collect(); + + for (folder_path, profile) in profiles { + if let Some(folder) = folders.iter_mut().find(|folder| folder.path == folder_path) { + folder.profiles.push(profile); + } + } + + folders +} + +/// Adds a profile's folder and any missing parents as runtime-only folders, +/// unless the path is already part of `folders.toml`. +fn add_missing_folder_and_parents( + tracked: &BTreeSet, + untracked: &mut BTreeSet, + path: &str, +) { + let mut prefix = String::new(); + + for part in path.split('/') { + if !prefix.is_empty() { + prefix.push('/'); + } + prefix.push_str(part); + + if !tracked.contains(&prefix) { + untracked.insert(prefix.clone()); + } + } +} + +/// 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 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_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; + } + + 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(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 Some(()); + } + + let dir = profiles_dir()?; + write_profile_to(&dir, profile, folder).map(|_| ()) +} + +fn write_folders_to(dir: &Path, folders: &[ProfileFolder]) -> Option<()> { + std::fs::create_dir_all(dir).ok()?; + + let mut paths: Vec = folders + .iter() + .filter(|folder| !folder.untracked) + .map(|folder| folder.path.clone()) + .collect(); + paths.sort_by(|a, b| folder_order(a, b)); + paths.dedup(); + + let text = toml::to_string_pretty(&FoldersFile { folders: paths }).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 apply_theme_choice(state: &mut Moorly, choice: ThemeChoice) { match &choice { ThemeChoice::BuiltIn(preference) => { @@ -1745,7 +2109,7 @@ impl Default for Moorly { hovered_tab: None, tab_close_fades: HashMap::new(), profile_filter: String::new(), - profile_folders: vec![ProfileFolder::default_folder()], + profile_folders: load_profiles(), selected: None, hovered_folder: None, add_menu_open: false, @@ -2350,7 +2714,11 @@ fn update(state: &mut Moorly, message: Message) -> Task { let folder = match state.selected { Some(Selection::Folder(index)) => index, Some(Selection::Profile { folder, .. }) => folder, - None => 0, + 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)); @@ -2496,11 +2864,14 @@ fn update(state: &mut Moorly, message: Message) -> Task { let folder_index = draft .folder .min(state.profile_folders.len().saturating_sub(1)); - let Some(folder) = state.profile_folders.get_mut(folder_index) else { + let Some(folder_path) = state + .profile_folders + .get(folder_index) + .map(|folder| folder.path.clone()) + else { return Task::none(); }; - - folder.profiles.push(Profile { + let profile = Profile { name: draft.name.trim().to_owned(), kind: draft.kind, session_end: draft.session_end, @@ -2511,7 +2882,16 @@ fn update(state: &mut Moorly, message: Message) -> Task { password: draft.password.clone(), start_path: draft.start_path.clone(), private_key: draft.private_key.clone(), - }); + }; + + write_profile(&profile, &folder_path); + save_folders(&state.profile_folders); + + 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, @@ -2541,14 +2921,11 @@ fn update(state: &mut Moorly, message: Message) -> Task { return Task::none(); }; - let index = state.profile_folders.len(); - state.profile_folders.push(ProfileFolder { - name, - profiles: Vec::new(), - expanded: true, - }); + let path = normalize_folder_path(&name); + let index = ensure_folder(&mut state.profile_folders, &path); state.selected = Some(Selection::Folder(index)); state.folder_dialog = None; + save_folders(&state.profile_folders); } Message::CancelFolder => state.folder_dialog = None, Message::Ignore => {} @@ -4060,6 +4437,7 @@ fn profiles_panel(state: &Moorly, show_add: bool) -> Element<'_, Message> { .padding(6) .style(theme::filter_field) .width(Length::Fill), + text("Use / to nest folders, e.g. Work/Production").size(11), row![ space::horizontal(), button("Cancel") @@ -4231,7 +4609,7 @@ fn profile_dialog_view<'a>( .enumerate() .map(|(index, folder)| FolderChoice { index, - name: folder.name.clone(), + name: folder.path.clone(), }) .collect(); let selected_folder = choices.get(draft.folder).cloned(); @@ -4532,17 +4910,39 @@ fn profile_folder_row( ) -> Element<'_, 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 expanded { "📂" } else { "📁" }; + let folder_glyph = if folder.untracked { + if expanded { + "🗁\u{fe0e}" + } else { + "🗀\u{fe0e}" + } + } else if expanded { + "📂" + } else { + "📁" + }; - let mut heading_content = row![ - text(folder_glyph).size(14), - text(folder.name.as_str()).size(14), - space::horizontal(), - ] - .spacing(8) - .align_y(Alignment::Center) - .width(Length::Fill); + 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 is_selected || hovered == Some(index) { heading_content = heading_content.push( @@ -4556,7 +4956,12 @@ fn profile_folder_row( let heading = button(heading_content) .on_press(Message::ToggleFolder(index)) .width(Length::Fill) - .padding([8, 10]) + .padding(Padding { + top: 8.0, + right: 10.0, + bottom: 8.0, + left: 10.0 + indent, + }) .style(move |theme, status| { let mut style = theme::selectable_row(theme, status, is_selected); if !expanded { @@ -4590,7 +4995,12 @@ fn profile_folder_row( profile: profile_index, }) .width(Length::Fill) - .padding([4, 26]) + .padding(Padding { + top: 4.0, + right: 26.0, + bottom: 4.0, + left: 26.0 + indent, + }) .style(move |theme, status| theme::selectable_row(theme, status, profile_selected)), ); } @@ -6319,4 +6729,111 @@ mod tests { assert_eq!(state.profile_folders[1].name, "Work"); assert_eq!(state.selected, Some(super::Selection::Folder(1))); } + + #[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("\"Work/Production\"")); + assert!(!folders_text.contains("Missing")); + + 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(), + }; + + 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("folder = \"Work/Production\"")); + assert!(text.contains("kind = \"ssh\"")); + assert!(text.contains("session_end = \"reconnect\"")); + assert!(text.contains("host = \"example.com\"")); + assert!(text.contains("private_key = \"/keys/id\"")); + + 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(); + } } diff --git a/src/theme.rs b/src/theme.rs index 56f843c..b124b66 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -24,6 +24,9 @@ pub const TAB_ACTIVE_BG: Color = Color::from_rgb8(0x19, 0x19, 0x19); pub const TAB_INACTIVE_BG: Color = Color::from_rgb8(0x13, 0x13, 0x13); /// Text and icons drawn on the dark tab bar. pub const TAB_TEXT: Color = Color::from_rgb8(0xe6, 0xe6, 0xe6); +/// Blue used for folders that only exist at runtime because a profile refers +/// to a path missing from `folders.toml`. +pub const UNTRACKED_FOLDER: Color = Color::from_rgb8(0x4a, 0x90, 0xd9); #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Preference { @@ -80,15 +83,16 @@ pub(crate) fn config_path() -> Option { .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config"))) }?; - // Debug builds get their own file so manual testing never touches the - // settings used by a release build. - let file = if cfg!(debug_assertions) { - "config_debug.toml" + // Debug builds get their own folder so manual testing never touches the + // profiles, themes, or settings used by a release build. Filenames stay + // the same so individual files can be copied between the two. + let folder = if cfg!(debug_assertions) { + "moorly_debug" } else { - "config.toml" + "moorly" }; - Some(base.join("moorly").join(file)) + Some(base.join(folder).join("config.toml")) } /// Style for the top menubar. @@ -119,12 +123,7 @@ pub fn menu(theme: &Theme) -> container::Style { /// Style for a tab in the menubar; active tabs sit on the content surface. /// The active outline is drawn separately so it has no bottom edge. -pub fn tab( - _theme: &Theme, - active: bool, - active_bg: Color, - inactive_bg: Color, -) -> container::Style { +pub fn tab(_theme: &Theme, active: bool, active_bg: Color, inactive_bg: Color) -> container::Style { container::Style { background: Some(if active { active_bg.into() @@ -275,8 +274,7 @@ pub fn selectable_row(theme: &Theme, status: button::Status, selected: bool) -> let mut style = button::text(theme, status); if matches!(status, button::Status::Hovered) { - style.background = - Some(theme.extended_palette().background.weak.color.into()); + style.background = Some(theme.extended_palette().background.weak.color.into()); } style @@ -354,18 +352,8 @@ mod tests { #[test] fn active_tabs_are_visually_distinct() { let theme = Theme::Light; - let active = super::tab( - &theme, - true, - super::TAB_ACTIVE_BG, - super::TAB_INACTIVE_BG, - ); - let inactive = super::tab( - &theme, - false, - super::TAB_ACTIVE_BG, - super::TAB_INACTIVE_BG, - ); + let active = super::tab(&theme, true, super::TAB_ACTIVE_BG, super::TAB_INACTIVE_BG); + let inactive = super::tab(&theme, false, super::TAB_ACTIVE_BG, super::TAB_INACTIVE_BG); assert_ne!(active.background, inactive.background); assert_eq!(active.border.width, 0.0);