Added single-instance, where second instance raises the current running instance instead of creating a second conflicting instance
Moorly CI / windows-build (push) Successful in 3m2s
Moorly CI / linux-build (push) Successful in 4m7s

This commit is contained in:
Squid committed 2026-11-12 20:07:56 +01:00
1 parent 6425cfaacf
commit 4dc4401871
4 files changed
+190 -2

No files matched your search

Generated
+12
View File
@@ -2089,6 +2089,17 @@ dependencies = [
"hybrid-array", "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]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.18" version = "1.0.18"
@@ -2510,6 +2521,7 @@ dependencies = [
"global-hotkey", "global-hotkey",
"iced", "iced",
"iced_aw", "iced_aw",
"instance-handoff",
"nix", "nix",
"russh", "russh",
"russh-sftp", "russh-sftp",
+1
View File
@@ -6,6 +6,7 @@ edition = "2024"
[dependencies] [dependencies]
iced = { version = "0.14.0", features = ["tokio", "advanced"] } iced = { version = "0.14.0", features = ["tokio", "advanced"] }
iced_aw = { path = "vendor/iced_aw", default-features = false, features = ["color_picker"] } iced_aw = { path = "vendor/iced_aw", default-features = false, features = ["color_picker"] }
instance-handoff = "=0.1.0-alpha.2"
russh = "0.65.0" russh = "0.65.0"
russh-sftp = "3.0.1" russh-sftp = "3.0.1"
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }
+90 -2
View File
@@ -21,6 +21,7 @@ use iced::{
mod autostart; mod autostart;
mod hotkeys; mod hotkeys;
mod notifications; mod notifications;
mod single_instance;
#[allow(dead_code)] #[allow(dead_code)]
mod terminal; mod terminal;
mod theme; mod theme;
@@ -93,11 +94,21 @@ const DEFAULT_PROFILE_FOLDER: &str = "Ungrouped";
const ROOT_FOLDER_INDEX: usize = usize::MAX; const ROOT_FOLDER_INDEX: usize = usize::MAX;
fn main() -> iced::Result { 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) .title(window_title)
.theme(|state: &Moorly, _window| state.theme.iced()) .theme(|state: &Moorly, _window| state.theme.iced())
.subscription(subscription) .subscription(subscription)
.run() .run();
single_instance::shutdown();
result
} }
/// Opens the first window and gives it the Start tab when configured. /// Opens the first window and gives it the Start tab when configured.
@@ -409,6 +420,7 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
terminal_text, terminal_text,
hotkeys::subscription().map(Message::Hotkey), hotkeys::subscription().map(Message::Hotkey),
tray::subscription().map(Message::Tray), tray::subscription().map(Message::Tray),
single_instance::subscription(),
iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes),
window::events().map(|(window, event)| Message::WindowEvent(window, event)), window::events().map(|(window, event)| Message::WindowEvent(window, event)),
iced::event::listen_with(pointer_event), iced::event::listen_with(pointer_event),
@@ -5242,6 +5254,7 @@ enum Message {
ScrollTabsBy(window::Id, f32), ScrollTabsBy(window::Id, f32),
Hotkey(hotkeys::Event), Hotkey(hotkeys::Event),
Tray(tray::Event), Tray(tray::Event),
SecondInstanceActivated,
FinishToggleWindowVisibility(Option<bool>), FinishToggleWindowVisibility(Option<bool>),
FinishMinimizeToTray(window::Id, Option<bool>), FinishMinimizeToTray(window::Id, Option<bool>),
Quit, Quit,
@@ -6674,6 +6687,7 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
} }
Message::Hotkey(event) => return handle_hotkey_event(state, event), Message::Hotkey(event) => return handle_hotkey_event(state, event),
Message::Tray(event) => return handle_tray_event(state, event), Message::Tray(event) => return handle_tray_event(state, event),
Message::SecondInstanceActivated => return activate_main_window(state),
Message::FinishToggleWindowVisibility(minimized) => { Message::FinishToggleWindowVisibility(minimized) => {
return finish_toggle_window_visibility(state, minimized); return finish_toggle_window_visibility(state, minimized);
} }
@@ -6690,6 +6704,7 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
Message::Quit => { Message::Quit => {
tray::shutdown(); tray::shutdown();
hotkeys::shutdown(); hotkeys::shutdown();
single_instance::shutdown();
// Drop PTY sessions explicitly so their child processes are // Drop PTY sessions explicitly so their child processes are
// terminated before process::exit bypasses the state destructor. // terminated before process::exit bypasses the state destructor.
state.terminal_sessions.clear(); state.terminal_sessions.clear();
@@ -6770,6 +6785,38 @@ fn reopen_main_window(state: &mut Moorly, window_state: WindowState) -> Task<Mes
Task::batch([open.map(|_| Message::Ignore), window::gain_focus(id)]) Task::batch([open.map(|_| Message::Ignore), window::gain_focus(id)])
} }
/// Restores and raises the main window for a second launch. Compositors that
/// refuse focus still get a user-attention request, and the window is never
/// recreated when it already exists.
fn activate_main_window(state: &mut Moorly) -> Task<Message> {
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<Message> { fn toggle_main_window(state: &mut Moorly) -> Task<Message> {
if state.main_window_hidden { if state.main_window_hidden {
return show_main_window(state); return show_main_window(state);
@@ -12612,6 +12659,47 @@ mod tests {
assert!(state.terminal_sessions[&id].selection.is_none()); 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] #[test]
fn quick_power_shells_are_numbered_separately() { fn quick_power_shells_are_numbered_separately() {
let entries = vec![ let entries = vec![
+87
View File
@@ -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<Option<Owner>> = Mutex::new(None);
static EVENTS: Mutex<Option<UnboundedReceiver<()>>> = 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<crate::Message> {
Subscription::run(events)
}
fn events() -> impl Stream<Item = crate::Message> {
stream::channel(
8,
|mut output: iced::futures::channel::mpsc::Sender<crate::Message>| 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();
}
}