diff --git a/src/autostart.rs b/src/autostart.rs new file mode 100644 index 0000000..1c15e6d --- /dev/null +++ b/src/autostart.rs @@ -0,0 +1,120 @@ +//! Login autostart integration. +//! +//! Linux uses an XDG autostart entry, Windows a script in `shell:startup`. +//! Both use a stable file name and only ever touch that one file. + +/// Stable name of our XDG autostart entry. +#[cfg(target_os = "linux")] +pub const LINUX_FILE: &str = "dev.moorly.Moorly.desktop"; +/// Stable name of our Windows startup script. +#[cfg(windows)] +pub const WINDOWS_FILE: &str = "Moorly.cmd"; + +#[cfg(target_os = "linux")] +fn entry_path() -> Option { + let config = std::env::var_os("XDG_CONFIG_HOME") + .map(std::path::PathBuf::from) + .or_else(|| { + std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".config")) + })?; + + Some(config.join("autostart").join(LINUX_FILE)) +} + +#[cfg(windows)] +fn entry_path() -> Option { + let appdata = std::env::var_os("APPDATA").map(std::path::PathBuf::from)?; + + Some( + appdata + .join("Microsoft") + .join("Windows") + .join("Start Menu") + .join("Programs") + .join("Startup") + .join(WINDOWS_FILE), + ) +} + +#[cfg(not(any(target_os = "linux", windows)))] +fn entry_path() -> Option { + None +} + +/// Whether our autostart entry exists. +pub fn enabled() -> bool { + entry_path().is_some_and(|path| path.is_file()) +} + +/// Creates or refreshes our autostart entry. +pub fn enable() -> Result<(), String> { + let path = entry_path() + .ok_or_else(|| "Autostart at login is only supported on Linux and Windows.".to_owned())?; + let executable = std::env::current_exe() + .map_err(|error| format!("Could not find the Moorly executable: {error}"))?; + + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir) + .map_err(|error| format!("Could not create the autostart folder: {error}"))?; + } + + std::fs::write(&path, entry_contents(&executable)) + .map_err(|error| format!("Could not write the autostart entry: {error}")) +} + +/// Removes our autostart entry, leaving every other entry untouched. +pub fn disable() -> Result<(), String> { + let Some(path) = entry_path() else { + return Ok(()); + }; + + match std::fs::remove_file(&path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(format!("Could not remove the autostart entry: {error}")), + } +} + +#[cfg(target_os = "linux")] +fn entry_contents(executable: &std::path::Path) -> String { + let executable = executable.display().to_string(); + let executable = executable.replace('\\', "\\\\").replace('"', "\\\""); + + format!( + "[Desktop Entry]\n\ + Type=Application\n\ + Name=Moorly\n\ + Comment=SSH and terminal client\n\ + Exec=\"{executable}\"\n\ + Icon=utilities-terminal\n\ + Terminal=false\n\ + Categories=Network;Utility;TerminalEmulator;\n\ + StartupNotify=true\n\ + StartupWMClass=Moorly\n\ + X-Moorly-Generated=true\n" + ) +} + +#[cfg(windows)] +fn entry_contents(executable: &std::path::Path) -> String { + format!( + "@echo off\r\nstart \"\" \"{}\"\r\n", + executable.display() + ) +} + +#[cfg(not(any(target_os = "linux", windows)))] +fn entry_contents(_executable: &std::path::Path) -> String { + String::new() +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + #[test] + fn entry_is_marked_as_ours() { + let entry = super::entry_contents(std::path::Path::new("/usr/bin/moorly")); + + assert!(entry.contains("Exec=\"/usr/bin/moorly\"")); + assert!(entry.contains("X-Moorly-Generated=true")); + } +} diff --git a/src/main.rs b/src/main.rs index a412f0c..d222c23 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ use iced::{ }; #[cfg_attr(test, allow(dead_code))] +mod autostart; mod hotkeys; mod notifications; #[allow(dead_code)] @@ -1779,6 +1780,9 @@ struct Moorly { close_to_tray_draft: bool, minimize_to_tray: bool, minimize_to_tray_draft: bool, + /// Mirrors the OS autostart entry so the settings button knows which + /// action to offer. + autostart_at_login: bool, drag: Option, theme: theme::Preference, saved_theme: theme::Preference, @@ -4841,6 +4845,7 @@ impl Default for Moorly { close_to_tray_draft: close_to_tray, minimize_to_tray, minimize_to_tray_draft: minimize_to_tray, + autostart_at_login: autostart::enabled(), drag: None, theme, saved_theme: theme, @@ -4986,6 +4991,8 @@ enum Message { SetFadeSettings(bool), SetCloseToTray(bool), SetMinimizeToTray(bool), + EnableAutostartAtLogin, + DisableAutostartAtLogin, SetHideTabClose(bool), SetShowNewSessionButton(bool), SetShowCommandPaletteDescription(bool), @@ -5731,6 +5738,10 @@ fn update(state: &mut Moorly, message: Message) -> Task { window_state.quick_menu_open = false; state.folder_menu = None; + if tab == Tab::Settings && state.settings_section == SettingsSection::General { + state.autostart_at_login = autostart::enabled(); + } + // New tabs land at the end, so bring that end into view. if is_new { return scroll_tabs_to_end(state, window); @@ -5751,6 +5762,10 @@ fn update(state: &mut Moorly, message: Message) -> Task { Message::SelectSettingsSection(section) => { state.folder_menu = None; + if section == SettingsSection::General { + state.autostart_at_login = autostart::enabled(); + } + if section == state.settings_section && state.pending_settings_section.is_none() { // Already showing this section. } else if !state.fade_settings { @@ -5814,6 +5829,30 @@ fn update(state: &mut Moorly, message: Message) -> Task { 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, + Message::EnableAutostartAtLogin => match autostart::enable() { + Ok(()) => state.autostart_at_login = true, + Err(error) => { + state.notifications.add( + notifications::Notification::new( + notifications::NotificationKind::Error, + error, + ) + .title("Autostart at login"), + ); + } + }, + Message::DisableAutostartAtLogin => match autostart::disable() { + Ok(()) => state.autostart_at_login = false, + Err(error) => { + state.notifications.add( + notifications::Notification::new( + notifications::NotificationKind::Error, + error, + ) + .title("Autostart at login"), + ); + } + }, Message::SetHideTabClose(value) => state.hide_tab_close_draft = value, Message::SetShowNewSessionButton(value) => state.show_new_session_button_draft = value, Message::SetShowCommandPaletteDescription(value) => { @@ -9965,6 +10004,32 @@ fn general_panel(state: &Moorly) -> Element<'_, Message> { ); } + let login_action: Element<'_, Message> = if state.autostart_at_login { + button("Remove autostart") + .on_press(Message::DisableAutostartAtLogin) + .padding([6, 12]) + .style(theme::danger_option) + .into() + } else { + button("Enable autostart") + .on_press(Message::EnableAutostartAtLogin) + .padding([6, 12]) + .style(theme::positive_option) + .into() + }; + + panel = panel.push( + column![ + styled_text(&state.typography.h2, "Autostart at login"), + styled_text( + &state.typography.caption, + "Start Moorly automatically when you sign in.", + ), + row![login_action, space::horizontal()], + ] + .spacing(8), + ); + panel.into() } @@ -12028,6 +12093,7 @@ mod tests { close_to_tray_draft: false, minimize_to_tray: false, minimize_to_tray_draft: false, + autostart_at_login: false, drag: None, theme: theme::Preference::default(), saved_theme: theme::Preference::default(),