diff --git a/src/main.rs b/src/main.rs index bdb2371..711f3eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -157,7 +157,12 @@ fn boot() -> (Moorly, Task) { } } - (state, Task::batch([task.map(|_| Message::Ignore), fonts])) + let autostart = start_autostart_profiles(&mut state, id); + + ( + state, + Task::batch([task.map(|_| Message::Ignore), fonts, autostart]), + ) } fn window_title(state: &Moorly, window: window::Id) -> String { @@ -1739,6 +1744,10 @@ struct Moorly { pending_settings_section: Option, show_start_tab: bool, show_start_tab_draft: bool, + autostart_profiles: Vec, + autostart_profiles_draft: Vec, + autostart_choice: Option, + autostart_selected: Option, fade_settings: bool, fade_settings_draft: bool, hide_tab_close: bool, @@ -2560,16 +2569,87 @@ impl Default for GeneralConfig { struct StartupConfig { #[serde(default = "default_true")] show_start_tab: bool, + /// Profiles started in order when Moorly launches. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + autostart_profiles: Vec, } impl Default for StartupConfig { fn default() -> Self { Self { show_start_tab: true, + autostart_profiles: Vec::new(), } } } +/// A profile chosen to start with the application. The file is the stable +/// identity across renames and folder moves; folder and name are a fallback +/// for profiles that have not been written to disk yet. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +struct AutostartProfile { + #[serde(default)] + kind: AutostartKind, + #[serde(default, skip_serializing_if = "Option::is_none")] + file: Option, + #[serde(default)] + folder_id: String, + #[serde(default)] + name: String, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +enum AutostartKind { + /// A profile from the profile list. + #[default] + Profile, + /// A plain local terminal, added any number of times. + QuickTerminal, + /// A PowerShell terminal, offered on Windows. + QuickPowerShell, +} + +impl AutostartProfile { + fn quick_terminal() -> Self { + Self::quick(AutostartKind::QuickTerminal) + } + + fn quick_power_shell() -> Self { + Self::quick(AutostartKind::QuickPowerShell) + } + + fn quick(kind: AutostartKind) -> Self { + Self { + kind, + file: None, + folder_id: String::new(), + name: String::new(), + } + } + + fn from_profile(folder: &ProfileFolder, profile: &Profile) -> Self { + Self { + kind: AutostartKind::Profile, + file: profile.file.clone(), + folder_id: folder.id.clone(), + name: profile.name.clone(), + } + } +} + +/// An entry in the profile drop-down, labelled with its folder path. +#[derive(Debug, Clone, PartialEq, Eq)] +struct AutostartChoice { + profile: AutostartProfile, + label: String, +} + +impl std::fmt::Display for AutostartChoice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.label) + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] struct AppearanceConfig { #[serde(default = "default_theme")] @@ -4501,6 +4581,7 @@ fn new_tab_close_animation() -> Animation { /// Commits the draft settings to the running state. fn apply_settings(state: &mut Moorly) { state.show_start_tab = state.show_start_tab_draft; + state.autostart_profiles = state.autostart_profiles_draft.clone(); state.fade_settings = state.fade_settings_draft; state.close_to_tray = state.close_to_tray_draft; state.minimize_to_tray = state.minimize_to_tray_draft; @@ -4541,6 +4622,8 @@ fn apply_settings(state: &mut Moorly) { /// Discards the drafts, including the previewed theme selection. fn undo_settings(state: &mut Moorly) { state.show_start_tab_draft = state.show_start_tab; + state.autostart_profiles_draft = state.autostart_profiles.clone(); + state.autostart_selected = None; state.fade_settings_draft = state.fade_settings; state.close_to_tray_draft = state.close_to_tray; state.minimize_to_tray_draft = state.minimize_to_tray; @@ -4599,6 +4682,7 @@ fn config_file(state: &Moorly) -> ConfigFile { }, startup: StartupConfig { show_start_tab: state.show_start_tab, + autostart_profiles: state.autostart_profiles.clone(), }, appearance: AppearanceConfig { theme: state.saved_theme.as_str().to_owned(), @@ -4669,6 +4753,7 @@ impl Default for Moorly { let (builtin_custom_toasts, builtin_toast_palette) = builtin_toast_config(&config.appearance); let show_start_tab = config.startup.show_start_tab; + let autostart_profiles = config.startup.autostart_profiles.clone(); let fade_settings = config.general.fade_settings; let close_to_tray = config.general.close_to_tray; let minimize_to_tray = config.general.minimize_to_tray; @@ -4721,6 +4806,10 @@ impl Default for Moorly { pending_settings_section: None, show_start_tab, show_start_tab_draft: show_start_tab, + autostart_profiles: autostart_profiles.clone(), + autostart_profiles_draft: autostart_profiles, + autostart_choice: None, + autostart_selected: None, fade_settings, fade_settings_draft: fade_settings, hide_tab_close, @@ -4834,6 +4923,14 @@ enum Message { CloseTab(window::Id, Tab), SelectSettingsSection(SettingsSection), SetShowStartTab(bool), + AutostartChoiceSelected(AutostartChoice), + SelectAutostart(usize), + AddAutostartProfile, + MoveAutostartTop(usize), + MoveAutostartUp(usize), + MoveAutostartDown(usize), + MoveAutostartBottom(usize), + RemoveAutostartProfile(usize), SetFadeSettings(bool), SetCloseToTray(bool), SetMinimizeToTray(bool), @@ -5582,6 +5679,50 @@ fn update(state: &mut Moorly, message: Message) -> Task { } } Message::SetShowStartTab(value) => state.show_start_tab_draft = value, + Message::AutostartChoiceSelected(choice) => state.autostart_choice = Some(choice), + Message::SelectAutostart(index) => state.autostart_selected = Some(index), + Message::AddAutostartProfile => { + if let Some(choice) = state.autostart_choice.take() { + // Quick terminals can appear several times; profiles cannot. + let duplicate = choice.profile.kind == AutostartKind::Profile + && state.autostart_profiles_draft.contains(&choice.profile); + + if !duplicate { + state.autostart_profiles_draft.insert(0, choice.profile); + state.autostart_selected = Some(0); + } + } + } + Message::MoveAutostartTop(index) => { + move_autostart(state, index, 0); + state.autostart_selected = Some(0); + } + Message::MoveAutostartUp(index) => { + if index > 0 { + state.autostart_profiles_draft.swap(index, index - 1); + state.autostart_selected = Some(index - 1); + } + } + Message::MoveAutostartDown(index) => { + if index + 1 < state.autostart_profiles_draft.len() { + state.autostart_profiles_draft.swap(index, index + 1); + state.autostart_selected = Some(index + 1); + } + } + Message::MoveAutostartBottom(index) => { + if index < state.autostart_profiles_draft.len() { + let last = state.autostart_profiles_draft.len() - 1; + let entry = state.autostart_profiles_draft.remove(index); + state.autostart_profiles_draft.push(entry); + state.autostart_selected = Some(last); + } + } + Message::RemoveAutostartProfile(index) => { + if index < state.autostart_profiles_draft.len() { + state.autostart_profiles_draft.remove(index); + state.autostart_selected = None; + } + } Message::SetFadeSettings(value) => state.fade_settings_draft = value, Message::SetCloseToTray(value) => state.close_to_tray_draft = value, Message::SetMinimizeToTray(value) => state.minimize_to_tray_draft = value, @@ -9739,14 +9880,343 @@ fn general_panel(state: &Moorly) -> Element<'_, Message> { panel.into() } +/// Moves an autostart entry to `target`, shifting the ones in between. +fn move_autostart(state: &mut Moorly, index: usize, target: usize) { + if index <= target || index >= state.autostart_profiles_draft.len() { + return; + } + + let entry = state.autostart_profiles_draft.remove(index); + state.autostart_profiles_draft.insert(target, entry); +} + +/// Finds the current folder and profile an autostart entry refers to. +fn autostart_target(state: &Moorly, entry: &AutostartProfile) -> Option<(usize, usize)> { + if entry.kind != AutostartKind::Profile { + return None; + } + + state + .profile_folders + .iter() + .enumerate() + .find_map(|(folder_index, folder)| { + let profile_index = folder.profiles.iter().position(|profile| { + entry + .file + .as_ref() + .is_some_and(|file| profile.file.as_ref() == Some(file)) + || (profile.name == entry.name && folder.id == entry.folder_id) + })?; + + Some((folder_index, profile_index)) + }) +} + +fn autostart_label(state: &Moorly, entry: &AutostartProfile) -> String { + if let Some((folder_index, profile_index)) = autostart_target(state, entry) + && let Some(folder) = state.profile_folders.get(folder_index) + && let Some(profile) = folder.profiles.get(profile_index) + { + return format!("{} / {}", folder.path, profile.name); + } + + if entry.name.trim().is_empty() { + "Missing profile".to_owned() + } else { + format!("{} (missing)", entry.name) + } +} + +fn autostart_choices(state: &Moorly) -> Vec { + let mut choices = vec![AutostartChoice { + profile: AutostartProfile::quick_terminal(), + label: "Quick terminal".to_owned(), + }]; + + if cfg!(windows) { + choices.push(AutostartChoice { + profile: AutostartProfile::quick_power_shell(), + label: "Quick PowerShell".to_owned(), + }); + } + + for (folder_index, folder) in state.profile_folders.iter().enumerate() { + for (profile_index, profile) in folder.profiles.iter().enumerate() { + // Hide everything already in the draft list, including profiles + // added since the last save. + if state.autostart_profiles_draft.iter().any(|entry| { + autostart_target(state, entry) == Some((folder_index, profile_index)) + }) { + continue; + } + + choices.push(AutostartChoice { + profile: AutostartProfile::from_profile(folder, profile), + label: format!("{} / {}", folder.path, profile.name), + }); + } + } + + choices +} + +/// Display name for a quick terminal, numbered by position among the other +/// entries of the same kind in the draft list. +fn quick_terminal_label(entries: &[AutostartProfile], index: usize, kind: AutostartKind) -> String { + let base = match kind { + AutostartKind::QuickTerminal => "Quick terminal", + AutostartKind::QuickPowerShell => "Quick PowerShell", + AutostartKind::Profile => return String::new(), + }; + + let count = entries[..=index] + .iter() + .filter(|entry| entry.kind == kind) + .count(); + + if count <= 1 { + base.to_owned() + } else { + format!("{base} {count}") + } +} + +/// A plain local terminal profile used by autostart quick terminals. +fn quick_terminal_profile() -> Profile { + quick_shell_profile("Quick terminal", ProfileKind::Terminal) +} + +fn quick_power_shell_profile() -> Profile { + quick_shell_profile("Quick PowerShell", ProfileKind::PowerShell) +} + +fn quick_shell_profile(name: &str, kind: ProfileKind) -> Profile { + Profile { + name: name.to_owned(), + kind, + session_end: SessionEnd::Auto, + host: String::new(), + port: "22".to_owned(), + username: String::new(), + auth: AuthMethod::default(), + password: String::new(), + start_path: default_start_path(), + private_key: String::new(), + glyph_color: Color::WHITE, + hidden: false, + folder_id: String::new(), + file: None, + } +} + +/// Starts the saved autostart profiles in list order. +fn start_autostart_profiles(state: &mut Moorly, window: window::Id) -> Task { + // Never spawn shells from the developer's real config during unit tests. + if cfg!(test) { + return Task::none(); + } + + let entries = state.autostart_profiles.clone(); + let mut tasks = Vec::new(); + + for entry in entries { + match entry.kind { + AutostartKind::QuickTerminal => tasks.push(start_terminal_profile( + state, + window, + quick_terminal_profile(), + false, + )), + AutostartKind::QuickPowerShell => tasks.push(start_terminal_profile( + state, + window, + quick_power_shell_profile(), + false, + )), + AutostartKind::Profile => { + if let Some((folder, profile)) = autostart_target(state, &entry) { + tasks.push(run_profile(state, window, folder, profile, false)); + } + } + } + } + + Task::batch(tasks) +} + +/// Fixed-size icon button used by the autostart list, so every glyph lines up. +fn autostart_button<'a>( + glyph: &'a str, + tip: &'a str, + message: Message, + enabled: bool, + danger: bool, +) -> Element<'a, Message> { + let mut glyph = text(glyph).size(22); + if danger { + glyph = glyph.color(theme::DANGER.scale_alpha(if enabled { 1.0 } else { 0.4 })); + } + + let glyph = container(glyph) + .width(Length::Fill) + .height(Length::Fill) + .align_x(Alignment::Center) + .align_y(Alignment::Center); + + let button = button(glyph) + .on_press_maybe(enabled.then_some(message)) + .width(40) + .height(34) + .padding(0) + .style(theme::outlined_option); + + tooltip( + button, + container(text(tip).size(12)) + .padding([4, 7]) + .style(theme::menu), + tooltip::Position::Top, + ) + .into() +} + +/// Rows the autostart list always reserves space for. +const AUTOSTART_LIST_ROWS: usize = 10; +/// Height of one compact row in the autostart list. +const AUTOSTART_ROW_HEIGHT: f32 = 30.0; + /// 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), + let entries = &state.autostart_profiles_draft; + let selected = state + .autostart_selected + .filter(|index| *index < entries.len()); + let list_height = AUTOSTART_LIST_ROWS as f32 * AUTOSTART_ROW_HEIGHT; + + let mut rows = column![].spacing(2).width(Length::Fill); + + for (index, entry) in entries.iter().enumerate() { + let label = if entry.kind == AutostartKind::Profile { + autostart_label(state, entry) + } else { + quick_terminal_label(entries, index, entry.kind) + }; + + let content = row![ + container(text(format!("{}.", index + 1)).size(14)).width(28), + text(label).size(14).width(Length::Fill), + ] + .spacing(8) + .align_y(Alignment::Center); + + rows = rows.push( + button(content) + .on_press(Message::SelectAutostart(index)) + .width(Length::Fill) + .padding([5, 8]) + .style(move |theme, status| { + theme::selectable_row(theme, status, selected == Some(index)) + }), + ); + } + + // The list keeps its height even when empty, and scrolls past ten rows. + let list = scrollable(rows) + .height(Length::Fixed(list_height)) + .width(Length::Fill); + let list = container(list) + .padding(4) + .width(Length::Fill) + .style(theme::advanced_frame); + + let index = selected.unwrap_or(0); + let can_move_up = selected.is_some_and(|index| index > 0); + let can_move_down = selected.is_some_and(|index| index + 1 < entries.len()); + + // One column on the right: up controls on top, remove centered, down + // controls at the bottom. + let toolbar = column![ + autostart_button( + "↥", + "Move to top", + Message::MoveAutostartTop(index), + can_move_up, + false, + ), + autostart_button( + "↑", + "Move up", + Message::MoveAutostartUp(index), + can_move_up, + false, + ), + space::vertical(), + autostart_button( + "✕", + "Remove", + Message::RemoveAutostartProfile(index), + selected.is_some(), + true, + ), + space::vertical(), + autostart_button( + "↓", + "Move down", + Message::MoveAutostartDown(index), + can_move_down, + false, + ), + autostart_button( + "↧", + "Move to bottom", + Message::MoveAutostartBottom(index), + can_move_down, + false, + ), ] - .align_y(Alignment::Center) + .spacing(4) + .height(Length::Fixed(list_height + 8.0)) + .align_x(Alignment::Center); + + let list = row![list, toolbar] + .spacing(8) + .align_y(Alignment::Start) + .width(Length::Fill); + + let choices = autostart_choices(state); + let add = button("Add") + .on_press_maybe(state.autostart_choice.is_some().then_some(Message::AddAutostartProfile)) + .padding([6, 16]) + .style(theme::positive_option); + + column![ + 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), + styled_text(&state.typography.h1, "Autostarting profiles"), + styled_text( + &state.typography.caption, + "Profiles in this list start automatically when Moorly launches. \ + They are started in order from top to bottom.", + ), + list, + row![ + pick_list( + choices, + state.autostart_choice.clone(), + Message::AutostartChoiceSelected + ) + .width(Length::Fill), + add, + ] + .spacing(8) + .align_y(Alignment::Center), + ] + .spacing(12) .into() } @@ -9921,6 +10391,7 @@ fn profile_context_menu( fn settings_dirty(state: &Moorly) -> bool { state.show_start_tab_draft != state.show_start_tab + || state.autostart_profiles_draft != state.autostart_profiles || 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 @@ -10315,6 +10786,16 @@ fn run_profile( return Task::none(); }; + start_terminal_profile(state, window, profile, new_window) +} + +/// Starts a local terminal session from an already resolved profile. +fn start_terminal_profile( + state: &mut Moorly, + window: window::Id, + profile: Profile, + new_window: bool, +) -> Task { let Some(shell) = local_shell(profile.kind) else { state.notifications.add( notifications::Notification::new( @@ -11381,6 +11862,10 @@ mod tests { pending_settings_section: None, show_start_tab: true, show_start_tab_draft: true, + autostart_profiles: Vec::new(), + autostart_profiles_draft: Vec::new(), + autostart_choice: None, + autostart_selected: None, fade_settings: true, fade_settings_draft: true, hide_tab_close: true, @@ -11525,6 +12010,162 @@ mod tests { assert_eq!(state.show_start_tab_draft, state.show_start_tab); } + #[test] + fn autostart_profiles_are_added_reordered_and_saved() { + let mut state = state(); + state.profile_folders[0].id = "folder".to_owned(); + state.profile_folders[0].profiles = vec![profile("Alpha"), profile("Beta")]; + + let choices = super::autostart_choices(&state); + // The quick rows plus both profiles. + let quick_rows = 1 + usize::from(cfg!(windows)); + assert_eq!(choices.len(), quick_rows + 2); + assert_eq!( + choices[0].profile.kind, + super::AutostartKind::QuickTerminal + ); + + let beta = choices + .iter() + .find(|choice| choice.profile.name == "Beta") + .unwrap() + .clone(); + let alpha = choices + .iter() + .find(|choice| choice.profile.name == "Alpha") + .unwrap() + .clone(); + + let _ = update(&mut state, Message::AutostartChoiceSelected(beta)); + let _ = update(&mut state, Message::AddAutostartProfile); + assert_eq!(state.autostart_profiles_draft[0].name, "Beta"); + assert!(super::settings_dirty(&state)); + + // Added profiles leave the drop-down until the draft is undone. + let remaining = super::autostart_choices(&state); + assert_eq!(remaining.len(), quick_rows + 1); + assert!( + !remaining + .iter() + .any(|choice| choice.profile.name == "Beta") + ); + + let _ = update(&mut state, Message::AutostartChoiceSelected(alpha.clone())); + let _ = update(&mut state, Message::AddAutostartProfile); + assert_eq!(state.autostart_profiles_draft[0].name, "Alpha"); + + // Adding the same profile twice keeps one entry. + let _ = update(&mut state, Message::AutostartChoiceSelected(alpha)); + let _ = update(&mut state, Message::AddAutostartProfile); + assert_eq!(state.autostart_profiles_draft.len(), 2); + + // A profile added to the profile list shows up in the drop-down. + state.profile_folders[0].profiles.push(profile("Gamma")); + let remaining = super::autostart_choices(&state); + assert_eq!(remaining.len(), quick_rows + 1); + assert!( + remaining + .iter() + .any(|choice| choice.profile.name == "Gamma") + ); + + let _ = update(&mut state, Message::MoveAutostartBottom(0)); + assert_eq!(state.autostart_profiles_draft[1].name, "Alpha"); + let _ = update(&mut state, Message::MoveAutostartUp(1)); + assert_eq!(state.autostart_profiles_draft[0].name, "Alpha"); + let _ = update(&mut state, Message::MoveAutostartDown(0)); + assert_eq!(state.autostart_profiles_draft[1].name, "Alpha"); + let _ = update(&mut state, Message::MoveAutostartTop(1)); + assert_eq!(state.autostart_profiles_draft[0].name, "Alpha"); + + // The committed list only changes on save. + assert!(state.autostart_profiles.is_empty()); + super::apply_settings(&mut state); + assert_eq!(state.autostart_profiles.len(), 2); + assert!(!super::settings_dirty(&state)); + + let _ = update(&mut state, Message::RemoveAutostartProfile(0)); + assert_eq!(state.autostart_profiles_draft.len(), 1); + let _ = update(&mut state, Message::UndoChanges); + assert_eq!(state.autostart_profiles_draft.len(), 2); + } + + #[test] + fn quick_terminals_can_be_added_several_times_and_are_renumbered() { + let mut state = state(); + let quick = super::autostart_choices(&state)[0].clone(); + + for _ in 0..3 { + let _ = update( + &mut state, + Message::AutostartChoiceSelected(quick.clone()), + ); + let _ = update(&mut state, Message::AddAutostartProfile); + } + + let entries = &state.autostart_profiles_draft; + assert_eq!(entries.len(), 3); + assert_eq!( + super::quick_terminal_label(entries, 0, super::AutostartKind::QuickTerminal), + "Quick terminal" + ); + assert_eq!( + super::quick_terminal_label(entries, 1, super::AutostartKind::QuickTerminal), + "Quick terminal 2" + ); + assert_eq!( + super::quick_terminal_label(entries, 2, super::AutostartKind::QuickTerminal), + "Quick terminal 3" + ); + + // The quick terminal row stays available after adding. + assert_eq!( + super::autostart_choices(&state)[0].profile.kind, + super::AutostartKind::QuickTerminal + ); + assert_eq!( + super::autostart_choices(&state) + .iter() + .any(|choice| choice.profile.kind == super::AutostartKind::QuickPowerShell), + cfg!(windows) + ); + + let _ = update(&mut state, Message::RemoveAutostartProfile(1)); + + let entries = &state.autostart_profiles_draft; + assert_eq!(entries.len(), 2); + assert_eq!( + super::quick_terminal_label(entries, 0, super::AutostartKind::QuickTerminal), + "Quick terminal" + ); + assert_eq!( + super::quick_terminal_label(entries, 1, super::AutostartKind::QuickTerminal), + "Quick terminal 2" + ); + } + + #[test] + fn quick_power_shells_are_numbered_separately() { + let entries = vec![ + super::AutostartProfile::quick_terminal(), + super::AutostartProfile::quick_power_shell(), + super::AutostartProfile::quick_power_shell(), + ]; + + assert_eq!( + super::quick_terminal_label(&entries, 0, super::AutostartKind::QuickTerminal), + "Quick terminal" + ); + assert_eq!( + super::quick_terminal_label(&entries, 1, super::AutostartKind::QuickPowerShell), + "Quick PowerShell" + ); + assert_eq!( + super::quick_terminal_label(&entries, 2, super::AutostartKind::QuickPowerShell), + "Quick PowerShell 2" + ); + } + #[test] fn close_to_tray_changes_wait_for_save_or_undo() { let mut state = state(); @@ -11774,6 +12415,12 @@ mod tests { let mut state = state(); state.fade_settings = false; state.show_start_tab = false; + state.autostart_profiles = vec![super::AutostartProfile { + kind: super::AutostartKind::Profile, + file: Some(std::path::PathBuf::from("/profiles/alpha.toml")), + folder_id: "folder-id".to_owned(), + name: "Alpha".to_owned(), + }]; state.hide_tab_close = false; state.show_new_session_button = false; state.show_command_palette_description = false; @@ -11791,6 +12438,9 @@ mod tests { assert!(text.contains("[general]\nfade_settings = false")); assert!(text.contains("[startup]\nshow_start_tab = false")); + assert!(text.contains("[[startup.autostart_profiles]]")); + assert!(text.contains("name = \"Alpha\"")); + assert!(text.contains("file = \"/profiles/alpha.toml\"")); assert!(text.contains("[appearance]\ntheme = \"dark\"")); assert!(text.contains("show_new_session_button = false")); assert!(text.contains("show_command_palette_description = false"));