diff --git a/src/main.rs b/src/main.rs index 36dbb37..e26379c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -39,6 +39,10 @@ const TAB_SCROLL_STEP: f32 = 120.0; const TAB_SCROLL_ID: Id = Id::new("tab-strip"); /// 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"); fn main() -> iced::Result { iced::application(Moorly::default, update, view) @@ -51,8 +55,8 @@ fn main() -> iced::Result { fn subscription(state: &Moorly) -> Subscription { let keyboard = keyboard::listen() .with(( - state.shortcuts.settings.clone(), - state.shortcuts.quit.clone(), + state.saved_shortcuts.settings.clone(), + state.saved_shortcuts.quit.clone(), state.shortcut_capture.is_some(), )) .filter_map(|((settings_shortcut, quit_shortcut, capturing), event)| { @@ -244,7 +248,7 @@ impl ShortcutAction { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] struct Shortcuts { settings: Option, quit: Option, @@ -312,7 +316,6 @@ struct ShortcutCapture { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[allow(dead_code)] // Stored for when profiles can actually start sessions. enum ProfileKind { #[default] Ssh, @@ -320,8 +323,19 @@ enum ProfileKind { 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", + } + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[allow(dead_code)] // Stored for when profiles can actually start sessions. enum SessionEnd { #[default] Auto, @@ -330,8 +344,26 @@ enum SessionEnd { 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)] -#[allow(dead_code)] // Stored for when profiles can actually start sessions. enum AuthMethod { #[default] Password, @@ -340,6 +372,28 @@ enum AuthMethod { 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 { @@ -355,6 +409,188 @@ struct Profile { private_key: String, } +/// Editable state of the "add 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, +} + +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(), + } + } + + 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) + } +} + +/// 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. #[derive(Debug, Clone)] struct ProfileFolder { @@ -383,11 +619,14 @@ struct Moorly { menu_open: bool, tabs_submenu_open: bool, 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, tabs: Vec, active_tab: Option, @@ -401,6 +640,7 @@ struct Moorly { hide_tab_close_draft: bool, advanced_open: bool, colors: [Color; 5], + saved_colors: [Color; 5], open_color_picker: Option, fade_animation: Animation, hovered_tab: Option, @@ -409,6 +649,10 @@ struct Moorly { profile_folders: Vec, selected: Option, hovered_folder: Option, + add_menu_open: bool, + folder_dialog: Option, + profile_dialog: Option, + dir_picker: Option, next_blank_tab: u32, tab_offset: f32, tab_viewport_width: f32, @@ -589,6 +833,117 @@ fn builtin_colors(_preference: theme::Preference) -> [Color; 5] { DEFAULT_COLORS } +/// Everything persisted in `config.toml`, 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, +} + +impl Default for ConfigFile { + fn default() -> Self { + Self { + general: GeneralConfig::default(), + startup: StartupConfig::default(), + appearance: AppearanceConfig::default(), + shortcuts: ShortcutConfig::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 = "default_true")] + hide_tab_close: bool, +} + +impl Default for AppearanceConfig { + fn default() -> Self { + Self { + theme: default_theme(), + custom_theme: None, + hide_tab_close: true, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ShortcutConfig { + #[serde(default = "default_settings_shortcut")] + settings: String, + #[serde(default = "default_quit_shortcut")] + quit: String, +} + +impl Default for ShortcutConfig { + fn default() -> Self { + Self { + settings: default_settings_shortcut(), + quit: default_quit_shortcut(), + } + } +} + +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 color_to_hex(color: Color) -> String { let r = (color.r * 255.0).round() as u8; let g = (color.g * 255.0).round() as u8; @@ -726,7 +1081,6 @@ fn apply_theme_choice(state: &mut Moorly, choice: ThemeChoice) { ThemeChoice::BuiltIn(preference) => { state.theme = *preference; state.colors = builtin_colors(*preference); - theme::save(*preference); } ThemeChoice::Custom { id, .. } => { if let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id) { @@ -736,7 +1090,6 @@ fn apply_theme_choice(state: &mut Moorly, choice: ThemeChoice) { id: theme.id.clone(), name: theme.name.clone(), }; - theme::save(theme.based_on); return; } } @@ -775,23 +1128,76 @@ impl SettingsSection { } } -/// Path of the general settings file, alongside the theme file. +/// Path of the settings file. Everything lives in the same `config.toml`. fn config_path() -> Option { - theme::config_path().map(|path| path.with_file_name("config")) + theme::config_path() } -/// Reads a boolean setting from the config file. Defaults to enabled. -fn load_setting(key: &str) -> bool { - config_path() - .and_then(|path| std::fs::read_to_string(path).ok()) - .and_then(|text| { +/// Reads `config.toml`, 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")) - }) - .unwrap_or(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 +} + +/// Resolves the saved theme selection to its live theme and colors. +fn resolve_theme( + appearance: &AppearanceConfig, + custom_themes: &[CustomTheme], +) -> (ThemeChoice, theme::Preference, [Color; 5]) { + if let Some(id) = &appearance.custom_theme + && 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, + ); + } + + let preference = theme::Preference::parse(&appearance.theme).unwrap_or_default(); + + (ThemeChoice::BuiltIn(preference), preference, builtin_colors(preference)) } /// 0.5s total: 250ms fading out plus 250ms fading in. @@ -810,6 +1216,19 @@ fn apply_settings(state: &mut Moorly) { state.fade_settings = state.fade_settings_draft; state.hide_tab_close = state.hide_tab_close_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.fade_settings { if let Some(pending) = state.pending_settings_section.take() { state.settings_section = pending; @@ -818,7 +1237,19 @@ fn apply_settings(state: &mut Moorly) { } } -fn save_settings(show_start_tab: bool, fade_settings: bool, hide_tab_close: bool) { +/// 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.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; +} + +fn save_config(state: &Moorly) { let Some(path) = config_path() else { return; }; @@ -827,30 +1258,70 @@ fn save_settings(show_start_tab: bool, fade_settings: bool, hide_tab_close: bool let _ = std::fs::create_dir_all(parent); } - let _ = std::fs::write( - path, - format!( - "show_start_tab={show_start_tab}\nfade_settings={fade_settings}\nhide_tab_close={hide_tab_close}\n" - ), - ); + 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, + }, + hide_tab_close: state.hide_tab_close, + }, + 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(), + }, + } } impl Default for Moorly { fn default() -> Self { - let show_start_tab = load_setting("show_start_tab"); - let fade_settings = load_setting("fade_settings"); - let hide_tab_close = load_setting("hide_tab_close"); - let theme = theme::load(); + let config = load_config(); + let custom_themes = load_custom_themes(); + let (theme_choice, theme, colors) = resolve_theme(&config.appearance, &custom_themes); + 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 shortcuts = Shortcuts { + settings: Shortcut::parse(&config.shortcuts.settings), + quit: Shortcut::parse(&config.shortcuts.quit), + }; Self { menu_open: false, tabs_submenu_open: false, theme, - theme_choice: ThemeChoice::BuiltIn(theme), - custom_themes: load_custom_themes(), + 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::default(), + shortcuts: shortcuts.clone(), + saved_shortcuts: shortcuts, shortcut_capture: None, tabs: if show_start_tab { vec![Tab::Start] @@ -867,7 +1338,8 @@ impl Default for Moorly { hide_tab_close, hide_tab_close_draft: hide_tab_close, advanced_open: false, - colors: DEFAULT_COLORS, + colors, + saved_colors: colors, open_color_picker: None, fade_animation: new_fade_animation(), hovered_tab: None, @@ -876,6 +1348,10 @@ impl Default for Moorly { profile_folders: vec![ProfileFolder::default_folder()], selected: None, hovered_folder: None, + add_menu_open: false, + folder_dialog: None, + profile_dialog: None, + dir_picker: None, next_blank_tab: 1, tab_offset: 0.0, tab_viewport_width: 0.0, @@ -915,10 +1391,38 @@ enum Message { Frame(Instant), ProfileFilterChanged(String), ClearProfileFilter, + ToggleAddMenu, + CloseAddMenu, ToggleFolder(usize), HoverFolder(Option), HoverTab { tab: Tab, hovered: bool }, SelectProfile { folder: usize, profile: usize }, + OpenProfileDialog, + ProfileNameChanged(String), + ProfileKindSelected(ProfileKind), + ProfileFolderSelected(FolderChoice), + SessionEndSelected(SessionEnd), + ProfileHostChanged(String), + ProfilePortChanged(String), + ProfileUsernameChanged(String), + AuthMethodSelected(AuthMethod), + ProfilePasswordChanged(String), + TogglePasswordVisibility, + ProfileStartPathChanged(String), + ProfilePrivateKeyChanged(String), + OpenDirectoryPicker, + OpenPrivateKeyPicker, + DirPickerEnter(PathBuf), + DirPickerSelect(PathBuf), + DirPickerUp, + ConfirmDirectoryPicker, + CancelDirectoryPicker, + ConfirmProfile, + CancelProfile, + OpenFolderDialog, + FolderNameChanged(String), + ConfirmFolder, + CancelFolder, Ignore, OpenShortcutCapture(ShortcutAction), CancelShortcut, @@ -1026,7 +1530,13 @@ fn update(state: &mut Moorly, message: Message) -> Task { name, }; state.theme = based_on; - theme::save(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 => { @@ -1044,6 +1554,13 @@ fn update(state: &mut Moorly, message: Message) -> Task { theme.colors = state.colors; } + if matches!( + &state.saved_theme_choice, + ThemeChoice::Custom { id: saved, .. } if saved == id + ) { + state.saved_colors = state.colors; + } + state.theme_signature = themes_signature(); } } @@ -1054,7 +1571,14 @@ fn update(state: &mut Moorly, message: Message) -> Task { { state.theme = theme.based_on; state.colors = theme.colors; - theme::save(theme.based_on); + + 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 => { @@ -1090,9 +1614,25 @@ fn update(state: &mut Moorly, message: Message) -> Task { state.theme = theme.based_on; state.colors = theme.colors; } + + 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 { state.theme_choice = ThemeChoice::BuiltIn(state.theme); state.colors = builtin_colors(state.theme); + + if matches!( + &state.saved_theme_choice, + ThemeChoice::Custom { id: saved, .. } if saved == &id + ) { + state.saved_theme_choice = state.theme_choice.clone(); + state.saved_colors = state.colors; + } } } } @@ -1144,17 +1684,9 @@ fn update(state: &mut Moorly, message: Message) -> Task { Message::CancelColorPicker => state.open_color_picker = None, Message::SaveSettings => { apply_settings(state); - save_settings( - state.show_start_tab, - state.fade_settings, - state.hide_tab_close, - ); - } - Message::UndoChanges => { - 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; + save_config(state); } + Message::UndoChanges => undo_settings(state), Message::Frame(now) => { if !state.fade_animation.is_animating(now) && !state.fade_animation.value() @@ -1166,6 +1698,8 @@ fn update(state: &mut Moorly, message: Message) -> Task { } 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; @@ -1201,6 +1735,210 @@ fn update(state: &mut Moorly, message: Message) -> Task { Message::SelectProfile { folder, profile } => { state.selected = Some(Selection::Profile { folder, profile }); } + Message::OpenProfileDialog => { + let folder = match state.selected { + Some(Selection::Folder(index)) => index, + Some(Selection::Profile { folder, .. }) => folder, + None => 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::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.as_ref() 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) = state.profile_folders.get_mut(folder_index) else { + return Task::none(); + }; + + folder.profiles.push(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(), + }); + folder.expanded = true; + state.selected = Some(Selection::Profile { + folder: folder_index, + profile: folder.profiles.len() - 1, + }); + state.profile_dialog = None; + } + Message::CancelProfile => state.profile_dialog = None, + Message::OpenFolderDialog => { + state.add_menu_open = false; + state.folder_dialog = Some(String::new()); + return operation::focus(FOLDER_NAME_INPUT); + } + Message::FolderNameChanged(value) => { + if let Some(draft) = state.folder_dialog.as_mut() { + *draft = value; + } + } + Message::ConfirmFolder => { + let Some(name) = state + .folder_dialog + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(str::to_owned) + else { + return Task::none(); + }; + + let index = state.profile_folders.len(); + state.profile_folders.push(ProfileFolder { + name, + profiles: Vec::new(), + expanded: true, + }); + state.selected = Some(Selection::Folder(index)); + state.folder_dialog = None; + } + Message::CancelFolder => state.folder_dialog = None, Message::Ignore => {} Message::OpenShortcutCapture(action) => { state.shortcut_capture = Some(ShortcutCapture { @@ -1788,8 +2526,7 @@ fn shortcut_capture_panel(capture: &ShortcutCapture) -> Element<'_, Message> { .into() } -/// Profile list with a search filter row. -fn profiles_panel(state: &Moorly) -> Element<'_, Message> { +fn profiles_panel(state: &Moorly, show_add: bool) -> Element<'_, Message> { let field = text_input("Filter", &state.profile_filter) .on_input(Message::ProfileFilterChanged) .padding(Padding { @@ -1826,6 +2563,24 @@ fn profiles_panel(state: &Moorly) -> Element<'_, Message> { 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 mut list = column![].width(Length::Fill); for (index, folder) in state.profile_folders.iter().enumerate() { if index > 0 { @@ -1844,13 +2599,559 @@ fn profiles_panel(state: &Moorly) -> Element<'_, Message> { .height(Length::Fill) .style(theme::settings_frame); - column![filter, list] + let base = column![filter_row, list] .spacing(12) .width(Length::Fill) - .height(Length::Fill) + .height(Length::Fill); + + if !show_add { + return stack![base].into(); + } + + let dialog_open = state.folder_dialog.is_some() + || state.profile_dialog.is_some() + || state.dir_picker.is_some(); + + 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.folder_dialog.is_some() { + Message::CancelFolder + } else if state.profile_dialog.is_some() { + Message::CancelProfile + } else { + Message::CloseAddMenu + }); + + let mut layers = stack![base, backdrop]; + + if 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 dialog = container( + column![ + text("New folder").size(14), + text_input("Folder name", draft) + .id(FOLDER_NAME_INPUT) + .on_input(Message::FolderNameChanged) + .on_submit(Message::ConfirmFolder) + .padding(6) + .style(theme::filter_field) + .width(Length::Fill), + row![ + space::horizontal(), + button("Cancel") + .on_press(Message::CancelFolder) + .style(theme::danger_option), + button("Add") + .on_press_maybe( + (!draft.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.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. +fn profile_dialog_view<'a>( + draft: &'a ProfileDraft, + folders: &'a [ProfileFolder], +) -> Element<'a, Message> { + let title = 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.name.clone(), + }) + .collect(); + let selected_folder = choices.get(draft.folder).cloned(); + + 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![ + 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("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( @@ -1945,7 +3246,7 @@ fn start_page(state: &Moorly) -> Element<'_, Message> { container( container( column![ - container(profiles_panel(state)) + container(profiles_panel(state, false)) .width(Length::Fill) .height(list_height), settings, @@ -2050,7 +3351,7 @@ fn settings_page(state: &Moorly) -> Element<'_, Message> { content = content.push(shortcuts_panel(state)); } if state.settings_section == SettingsSection::Profiles { - content = content.push(profiles_panel(state)); + content = content.push(profiles_panel(state, true)); } let content = container(content) @@ -2091,7 +3392,9 @@ fn settings_page(state: &Moorly) -> Element<'_, Message> { 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.hide_tab_close_draft != state.hide_tab_close + || state.theme_choice != state.saved_theme_choice + || state.shortcuts != state.saved_shortcuts; let page: Element<'_, Message> = if dirty { let bar = container( @@ -2481,11 +3784,14 @@ mod tests { menu_open: false, tabs_submenu_open: false, 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, tabs: Vec::new(), active_tab: None, @@ -2499,6 +3805,7 @@ mod tests { hide_tab_close_draft: true, advanced_open: false, colors: super::DEFAULT_COLORS, + saved_colors: super::DEFAULT_COLORS, open_color_picker: None, fade_animation: super::new_fade_animation(), hovered_tab: None, @@ -2507,6 +3814,10 @@ mod tests { profile_folders: vec![super::ProfileFolder::default_folder()], selected: None, hovered_folder: None, + add_menu_open: false, + folder_dialog: None, + profile_dialog: None, + dir_picker: None, next_blank_tab: 1, tab_offset: 0.0, tab_viewport_width: 0.0, @@ -2598,6 +3909,86 @@ mod tests { assert_eq!(state.hide_tab_close_draft, state.hide_tab_close); } + #[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.saved_theme = theme::Preference::Dark; + state.saved_theme_choice = super::ThemeChoice::BuiltIn(theme::Preference::Dark); + + 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("[shortcuts]")); + assert_eq!(parsed["general"]["fade_settings"].as_bool(), Some(false)); + assert_eq!(parsed["appearance"]["theme"].as_str(), Some("dark")); + assert_eq!(parsed["shortcuts"]["settings"].as_str(), Some("Ctrl+,")); + + 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\"")); + } + + #[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 long_titles_are_ellipsized_to_max_width() { assert_eq!(super::fit_title("Settings"), "Settings"); @@ -2951,4 +4342,236 @@ mod tests { 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_deref(), Some("")); + 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 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))); + } } diff --git a/src/theme.rs b/src/theme.rs index 9fc2f7d..84682c2 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -5,7 +5,6 @@ //! changes while the app is running). use std::env; -use std::fs; use std::path::PathBuf; use iced::border::Radius; @@ -72,28 +71,6 @@ impl std::fmt::Display for Preference { } } -/// Loads the persisted preference, falling back to `System`. -pub fn load() -> Preference { - config_path() - .and_then(|path| fs::read_to_string(path).ok()) - .and_then(|value| Preference::parse(value.trim())) - .unwrap_or_default() -} - -/// Persists the preference. Failures are ignored so theme selection never -/// blocks the UI; the in-memory choice still applies for this session. -pub fn save(preference: Preference) { - let Some(path) = config_path() else { - return; - }; - - if let Some(parent) = path.parent() { - let _ = fs::create_dir_all(parent); - } - - let _ = fs::write(path, preference.as_str()); -} - pub(crate) fn config_path() -> Option { let base = if cfg!(windows) { env::var_os("APPDATA").map(PathBuf::from) @@ -103,7 +80,7 @@ pub(crate) fn config_path() -> Option { .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config"))) }?; - Some(base.join("moorly").join("theme")) + Some(base.join("moorly").join("config.toml")) } /// Style for the top menubar. @@ -194,6 +171,22 @@ pub fn settings_active(_theme: &Theme, _status: button::Status, accent: Color) - } } +/// Style for the currently selected option in a group of choice buttons. +pub fn selected_option(theme: &Theme, _status: button::Status) -> button::Style { + let palette = theme.extended_palette(); + + button::Style { + background: Some(palette.primary.base.color.into()), + text_color: palette.primary.base.text, + border: Border { + color: palette.primary.base.color, + width: 1.0, + radius: 4.0.into(), + }, + ..button::Style::default() + } +} + /// Style for an unselected choice button: outlined so it reads as a button /// rather than a plain text label. pub fn outlined_option(theme: &Theme, status: button::Status) -> button::Style { @@ -218,6 +211,15 @@ pub fn positive_option(theme: &Theme, status: button::Status) -> button::Style { }) } +/// Style for a destructive/cancelling action button (red). +pub fn danger_option(theme: &Theme, status: button::Status) -> button::Style { + let danger = theme.extended_palette().danger; + filled_option(match status { + button::Status::Hovered | button::Status::Pressed => danger.strong, + _ => danger.base, + }) +} + fn filled_option(pair: iced::theme::palette::Pair) -> button::Style { button::Style { background: Some(pair.color.into()), @@ -231,6 +233,22 @@ fn filled_option(pair: iced::theme::palette::Pair) -> button::Style { } } +/// Style for the password eye button while the password is revealed. +pub fn revealed_eye(theme: &Theme, status: button::Status) -> button::Style { + let palette = theme.extended_palette(); + + button::Style { + background: None, + text_color: palette.background.base.text, + border: Border { + color: palette.primary.base.color, + width: 1.0, + radius: 4.0.into(), + }, + ..button::text(theme, status) + } +} + /// Style for a selectable list row; the selected one gets a tinted background. pub fn selectable_row(theme: &Theme, status: button::Status, selected: bool) -> button::Style { if selected {