From 4dc4401871363dc99245b66fc43f22110c9c81a5 Mon Sep 17 00:00:00 2001 From: squid Date: Thu, 12 Nov 2026 20:07:56 +0100 Subject: [PATCH] Added single-instance, where second instance raises the current running instance instead of creating a second conflicting instance --- Cargo.lock | 12 ++++++ Cargo.toml | 1 + src/main.rs | 92 +++++++++++++++++++++++++++++++++++++++++- src/single_instance.rs | 87 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 190 insertions(+), 2 deletions(-) create mode 100644 src/single_instance.rs diff --git a/Cargo.lock b/Cargo.lock index c6a6973..59896e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2089,6 +2089,17 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "instance-handoff" +version = "0.1.0-alpha.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7b798f9d4db6f765e87960d57931720f9609c03190f47632456cf8bb3d488e0" +dependencies = [ + "libc", + "log", + "windows-sys 0.61.2", +] + [[package]] name = "itoa" version = "1.0.18" @@ -2510,6 +2521,7 @@ dependencies = [ "global-hotkey", "iced", "iced_aw", + "instance-handoff", "nix", "russh", "russh-sftp", diff --git a/Cargo.toml b/Cargo.toml index 33d08fd..cc2ea9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2024" [dependencies] iced = { version = "0.14.0", features = ["tokio", "advanced"] } iced_aw = { path = "vendor/iced_aw", default-features = false, features = ["color_picker"] } +instance-handoff = "=0.1.0-alpha.2" russh = "0.65.0" russh-sftp = "3.0.1" serde = { version = "1.0.229", features = ["derive"] } diff --git a/src/main.rs b/src/main.rs index 2a60d80..78df955 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,6 +21,7 @@ use iced::{ mod autostart; mod hotkeys; mod notifications; +mod single_instance; #[allow(dead_code)] mod terminal; mod theme; @@ -93,11 +94,21 @@ const DEFAULT_PROFILE_FOLDER: &str = "Ungrouped"; const ROOT_FOLDER_INDEX: usize = usize::MAX; fn main() -> iced::Result { - iced::daemon(boot, update, view) + // Elect the primary before creating any window, tray, hotkeys or + // terminals. A second launch hands its activation request to the owner + // and exits here. + if !single_instance::acquire() { + return Ok(()); + } + + let result = iced::daemon(boot, update, view) .title(window_title) .theme(|state: &Moorly, _window| state.theme.iced()) .subscription(subscription) - .run() + .run(); + + single_instance::shutdown(); + result } /// Opens the first window and gives it the Start tab when configured. @@ -409,6 +420,7 @@ fn subscription(state: &Moorly) -> Subscription { terminal_text, hotkeys::subscription().map(Message::Hotkey), tray::subscription().map(Message::Tray), + single_instance::subscription(), iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), window::events().map(|(window, event)| Message::WindowEvent(window, event)), iced::event::listen_with(pointer_event), @@ -5242,6 +5254,7 @@ enum Message { ScrollTabsBy(window::Id, f32), Hotkey(hotkeys::Event), Tray(tray::Event), + SecondInstanceActivated, FinishToggleWindowVisibility(Option), FinishMinimizeToTray(window::Id, Option), Quit, @@ -6674,6 +6687,7 @@ fn update(state: &mut Moorly, message: Message) -> Task { } Message::Hotkey(event) => return handle_hotkey_event(state, event), Message::Tray(event) => return handle_tray_event(state, event), + Message::SecondInstanceActivated => return activate_main_window(state), Message::FinishToggleWindowVisibility(minimized) => { return finish_toggle_window_visibility(state, minimized); } @@ -6690,6 +6704,7 @@ fn update(state: &mut Moorly, message: Message) -> Task { Message::Quit => { tray::shutdown(); hotkeys::shutdown(); + single_instance::shutdown(); // Drop PTY sessions explicitly so their child processes are // terminated before process::exit bypasses the state destructor. state.terminal_sessions.clear(); @@ -6770,6 +6785,38 @@ fn reopen_main_window(state: &mut Moorly, window_state: WindowState) -> Task Task { + if state.main_window_hidden || state.hidden_main_window.is_some() { + let show = show_main_window(state); + let Some(window) = main_window_id(state) else { + return show; + }; + + return Task::batch([ + show, + window::request_user_attention(window, Some(window::UserAttention::Critical)), + ]); + } + + let Some(window) = main_window_id(state) else { + return Task::none(); + }; + + state.focused_window = Some(window); + + // A plain (not tray) minimized window has no hidden flag; restoring and + // focusing it does not change its mode, so a maximized window stays + // maximized. + Task::batch([ + window::minimize(window, false), + window::gain_focus(window), + window::request_user_attention(window, Some(window::UserAttention::Critical)), + ]) +} + fn toggle_main_window(state: &mut Moorly) -> Task { if state.main_window_hidden { return show_main_window(state); @@ -12612,6 +12659,47 @@ mod tests { assert!(state.terminal_sessions[&id].selection.is_none()); } + #[test] + fn second_instance_activation_restores_a_hidden_window() { + let mut state = state(); + let window = test_window(); + let saved = state.windows.remove(&window).unwrap(); + let tabs = saved.tabs.clone(); + let active_tab = saved.active_tab; + + state.window_order.clear(); + state.main_window = None; + state.focused_window = None; + state.main_window_hidden = true; + state.hidden_main_window = Some(saved); + + let _ = update(&mut state, Message::SecondInstanceActivated); + + assert!(!state.main_window_hidden); + assert!(state.hidden_main_window.is_none()); + + let restored = state.main_window.expect("window was restored"); + assert_eq!(state.windows[&restored].tabs, tabs); + assert_eq!(state.windows[&restored].active_tab, active_tab); + assert_eq!(state.focused_window, Some(restored)); + } + + #[test] + fn second_instance_activation_keeps_a_visible_window() { + let mut state = state(); + let window = test_window(); + let tabs = window_state(&state).tabs.clone(); + let active_tab = window_state(&state).active_tab; + + let _ = update(&mut state, Message::SecondInstanceActivated); + + assert_eq!(state.windows.len(), 1); + assert_eq!(state.main_window, Some(window)); + assert_eq!(state.focused_window, Some(window)); + assert_eq!(window_state(&state).tabs, tabs); + assert_eq!(window_state(&state).active_tab, active_tab); + } + #[test] fn quick_power_shells_are_numbered_separately() { let entries = vec![ diff --git a/src/single_instance.rs b/src/single_instance.rs new file mode 100644 index 0000000..29172a6 --- /dev/null +++ b/src/single_instance.rs @@ -0,0 +1,87 @@ +//! Single-instance election and activation hand-off. +//! +//! `instance-handoff` takes a per-user lock before any window, tray or hotkey +//! exists. Later launches hand over their request and exit; the owner keeps a +//! local IPC listener alive for its lifetime. The OS releases the lock when +//! the owner exits or crashes, so a stale lock cannot block a future launch. + +use std::sync::Mutex; + +use iced::futures::{SinkExt, Stream}; +use iced::{Subscription, stream}; +use instance_handoff::{AppId, Builder, Owner, Request, Started, State}; +use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel}; + +const APP_ID: AppId = AppId::windowed("dev.moorly.Moorly"); + +static OWNER: Mutex> = Mutex::new(None); +static EVENTS: Mutex>> = Mutex::new(None); + +/// Elects the primary instance. Returns `false` when this launch handed its +/// activation request to the already-running instance and should exit. +pub fn acquire() -> bool { + let state = crate::config_path() + .and_then(|path| path.parent().map(|dir| State::dir(dir.to_path_buf()))) + .unwrap_or(State::none()); + + match Builder::new(APP_ID, state).start(&()) { + Started::Owner(claim) => { + let (sender, receiver) = unbounded_channel(); + + if let Ok(mut events) = EVENTS.lock() { + *events = Some(receiver); + } + + let owner = claim.serve(move |_request: Request<()>| sender.send(()).is_ok()); + + if let Ok(mut slot) = OWNER.lock() { + *slot = Some(owner); + } + + true + } + Started::HandedOff(_) => false, + Started::Alone(reason) => { + eprintln!("Moorly could not become the single instance: {reason}"); + false + } + } +} + +/// Activation requests from later launches, delivered into the iced update +/// loop without blocking the GUI thread. +pub fn subscription() -> Subscription { + Subscription::run(events) +} + +fn events() -> impl Stream { + stream::channel( + 8, + |mut output: iced::futures::channel::mpsc::Sender| async move { + let receiver = EVENTS.lock().ok().and_then(|mut slot| slot.take()); + + let Some(mut receiver) = receiver else { + return; + }; + + while receiver.recv().await.is_some() { + if output + .send(crate::Message::SecondInstanceActivated) + .await + .is_err() + { + break; + } + } + }, + ) +} + +/// Stops the IPC listener and gives up the lock before the process exits. +pub fn shutdown() { + if let Ok(mut slot) = OWNER.lock() + && let Some(owner) = slot.take() + { + owner.release(); + } +}