diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 7c9b11c..e70bcc5 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -262,8 +262,10 @@ fn init_theme(cx: &mut App) { } fn main() { - let Some((_instance, starting)) = - single_instance::launch().expect("Failed to check for a running instance") + let Some(single_instance::Primary { + instance: _instance, + starting, + }) = single_instance::launch() else { return; }; @@ -288,12 +290,12 @@ fn main() { }; match startup() { Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| { - single_instance::attach(window); + single_instance::accept_relaunches(window); cx.new(|cx| RootView::new(setup, window, cx)) }) .map(drop), Err((lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| { - single_instance::attach(window); + single_instance::accept_relaunches(window); apply_theme(preferences.theme, window, cx); window .observe_window_appearance(move |window, cx| { diff --git a/crates/app/src/single_instance.rs b/crates/app/src/single_instance.rs index 77102f7..ea5c790 100644 --- a/crates/app/src/single_instance.rs +++ b/crates/app/src/single_instance.rs @@ -4,15 +4,14 @@ use std::marker::PhantomData; use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; use gpui_kit::Window; -use raw_window_handle::{HasWindowHandle, RawWindowHandle}; use windows::Win32::{ Foundation::{ - ERROR_TIMEOUT, HANDLE, HWND, LPARAM, LRESULT, WAIT_ABANDONED, WAIT_EVENT, WAIT_OBJECT_0, - WAIT_TIMEOUT, WPARAM, + HANDLE, HWND, LPARAM, LRESULT, WAIT_ABANDONED, WAIT_EVENT, WAIT_OBJECT_0, WAIT_TIMEOUT, + WPARAM, }, System::Threading::{ - CreateEventW, CreateMutexW, EVENT_MODIFY_STATE, INFINITE, OpenEventW, ReleaseMutex, - SetEvent, WaitForMultipleObjects, WaitForSingleObject, + CreateEventW, CreateMutexW, EVENT_MODIFY_STATE, OpenEventW, ReleaseMutex, SetEvent, + WaitForMultipleObjects, WaitForSingleObject, }, UI::{ Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}, @@ -24,65 +23,91 @@ use windows::core::{BOOL, Error, HSTRING, PCWSTR, Result, w}; const STARTING: PCWSTR = w!("Local\\nessar.arena-tracker.starting"); const INSTANCE: PCWSTR = w!("Local\\nessar.arena-tracker.instance"); const WINDOW_MARKER: PCWSTR = w!("nessar.arena-tracker.main-window"); -const RELAY_TIMEOUT_MS: u32 = 5_000; -const REOPEN: u32 = WM_APP + 2; +// The marker is only a presence flag, its value is never read. +const MARKED: HANDLE = HANDLE(1 as _); +const REOPEN_SUBCLASS: usize = 0; +// Past this wait another instance is alive, so the launch gives up quietly. +const LAUNCH_TIMEOUT_MS: u32 = 5_000; +// Shares the window's WM_APP message space with the tray's message. +const REOPEN: u32 = crate::tray::TRAY_MESSAGE + 1; // The acknowledgement event is the second object in the wait list. const REOPENED: WAIT_EVENT = WAIT_EVENT(WAIT_OBJECT_0.0 + 1); // Windows requires a mutex to be released on the thread that acquired it. -pub struct SessionLock(OwnedHandle, PhantomData<*mut ()>); +pub struct HeldMutex(OwnedHandle, PhantomData<*mut ()>); -impl SessionLock { - fn from_wait(handle: OwnedHandle, status: WAIT_EVENT) -> Result { +impl HeldMutex { + /// `None` when the wait timed out. An abandoned mutex (crashed owner) counts as acquired. + fn from_wait(handle: OwnedHandle, status: WAIT_EVENT) -> Result> { match status { - WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(Self(handle, PhantomData)), - WAIT_TIMEOUT => Err(Error::from_hresult(ERROR_TIMEOUT.to_hresult())), + WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(Some(Self(handle, PhantomData))), + WAIT_TIMEOUT => Ok(None), _ => Err(Error::from_thread()), } } } -impl Drop for SessionLock { +impl Drop for HeldMutex { fn drop(&mut self) { let _ = unsafe { ReleaseMutex(HANDLE(self.0.as_raw_handle())) }; } } -pub fn launch() -> Result> { - decide(STARTING, INSTANCE, relay) +pub struct Primary { + /// Held for the whole life of the app. + pub instance: HeldMutex, + /// Held until the first window is open, so that relaunches find it. + pub starting: HeldMutex, } -fn decide( - starting: PCWSTR, - instance: PCWSTR, - relay: impl FnOnce() -> Result>, -) -> Result> { - // Serialize launches until the winner has a window. Keep its other lock through app teardown. - let gate = unsafe { CreateMutexW(None, false, starting)? }; - let starting = unsafe { OwnedHandle::from_raw_handle(gate.0) }; - let status = unsafe { WaitForSingleObject(gate, INFINITE) }; - let starting = SessionLock::from_wait(starting, status)?; +fn owned(handle: HANDLE) -> OwnedHandle { + unsafe { OwnedHandle::from_raw_handle(handle.0) } +} - let mutex = unsafe { CreateMutexW(None, false, instance)? }; - let instance = unsafe { OwnedHandle::from_raw_handle(mutex.0) }; - let status = match unsafe { WaitForSingleObject(mutex, 0) } { +fn marked(hwnd: HWND) -> bool { + !unsafe { GetPropW(hwnd, WINDOW_MARKER) }.is_invalid() +} + +/// `None` means exit without starting: the launch was relayed, or another instance is alive. +pub fn launch() -> Option { + claim(STARTING, INSTANCE, relay).unwrap_or_else(|error| { + eprintln!("Failed to check for a running instance: {error}"); + None + }) +} + +fn claim( + starting_name: PCWSTR, + instance_name: PCWSTR, + relay: impl FnOnce() -> Result>, +) -> Result> { + // Serialize launches until the winner has a window. Keep its other lock through app teardown. + let gate = owned(unsafe { CreateMutexW(None, false, starting_name)? }); + let status = unsafe { WaitForSingleObject(HANDLE(gate.as_raw_handle()), LAUNCH_TIMEOUT_MS) }; + let Some(starting) = HeldMutex::from_wait(gate, status)? else { + return Ok(None); + }; + + let mutex = owned(unsafe { CreateMutexW(None, false, instance_name)? }); + let handle = HANDLE(mutex.as_raw_handle()); + let status = match unsafe { WaitForSingleObject(handle, 0) } { WAIT_TIMEOUT => match relay()? { // If the window closes before acknowledging, take over when the owner exits. Some(event) => unsafe { WaitForMultipleObjects( - &[mutex, HANDLE(event.as_raw_handle())], + &[handle, HANDLE(event.as_raw_handle())], false, - RELAY_TIMEOUT_MS, + LAUNCH_TIMEOUT_MS, ) }, - None => unsafe { WaitForSingleObject(mutex, RELAY_TIMEOUT_MS) }, + None => unsafe { WaitForSingleObject(handle, LAUNCH_TIMEOUT_MS) }, }, status => status, }; if status == REOPENED { return Ok(None); } - Ok(Some((SessionLock::from_wait(instance, status)?, starting))) + Ok(HeldMutex::from_wait(mutex, status)?.map(|instance| Primary { instance, starting })) } fn reply_name(pid: u32) -> HSTRING { @@ -91,7 +116,7 @@ fn reply_name(pid: u32) -> HSTRING { fn relay() -> Result> { unsafe extern "system" fn find(hwnd: HWND, output: LPARAM) -> BOOL { - if unsafe { GetPropW(hwnd, WINDOW_MARKER) }.is_invalid() { + if !marked(hwnd) { return true.into(); } unsafe { *(output.0 as *mut HWND) = hwnd }; @@ -108,8 +133,7 @@ fn relay() -> Result> { return Ok(None); } let sender = std::process::id(); - let event = unsafe { CreateEventW(None, false, false, &reply_name(sender))? }; - let event = unsafe { OwnedHandle::from_raw_handle(event.0) }; + let event = owned(unsafe { CreateEventW(None, false, false, &reply_name(sender))? }); let posted = unsafe { let _ = AllowSetForegroundWindow(pid); // A posted reopen runs after any close already in the window's message queue. @@ -118,18 +142,19 @@ fn relay() -> Result> { Ok(posted.is_ok().then_some(event)) } -pub fn attach(window: &Window) { - let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).unwrap().as_raw() - else { - unreachable!("Expected a Win32 window"); +pub fn accept_relaunches(window: &Window) { + let Some(hwnd) = crate::tray::window_hwnd(window) else { + eprintln!("Failed to get the window handle for relaunches"); + return; }; - let hwnd = HWND(handle.hwnd.get() as _); unsafe { - assert!( - SetWindowSubclass(hwnd, Some(window_proc), 0, 0).as_bool(), - "Failed to install the window reopen handler" - ); - SetPropW(hwnd, WINDOW_MARKER, Some(HANDLE(1 as _))).expect("Failed to publish the window"); + if !SetWindowSubclass(hwnd, Some(window_proc), REOPEN_SUBCLASS, 0).as_bool() { + eprintln!("Failed to install the window reopen handler"); + return; + } + if let Err(error) = SetPropW(hwnd, WINDOW_MARKER, Some(MARKED)) { + eprintln!("Failed to publish the window: {error}"); + } } } @@ -143,13 +168,15 @@ unsafe extern "system" fn window_proc( ) -> LRESULT { match message { REOPEN => { - if !unsafe { GetPropW(hwnd, WINDOW_MARKER) }.is_invalid() - && let Ok(event) = - unsafe { OpenEventW(EVENT_MODIFY_STATE, false, &reply_name(wparam.0 as u32)) } - { - let _event = unsafe { OwnedHandle::from_raw_handle(event.0) }; + if marked(hwnd) { crate::tray::reopen(hwnd); - if !unsafe { GetPropW(hwnd, WINDOW_MARKER) }.is_invalid() { + // The relaunching process may have timed out and exited, taking its event along. + if marked(hwnd) + && let Ok(event) = unsafe { + OpenEventW(EVENT_MODIFY_STATE, false, &reply_name(wparam.0 as u32)) + } + { + let _event = owned(event); let _ = unsafe { SetEvent(event) }; } } @@ -168,43 +195,54 @@ unsafe extern "system" fn window_proc( #[cfg(test)] mod tests { - use std::{sync::mpsc, thread, time::Duration}; + use std::{mem, sync::mpsc, thread, time::Duration}; use super::*; + /// Per-pid mutex names, so that tests never meet a real instance or each other. + fn names(test: &str) -> (HSTRING, HSTRING) { + let pid = std::process::id(); + ( + HSTRING::from(format!("Local\\arena-tracker.test.{test}.starting.{pid}")), + HSTRING::from(format!("Local\\arena-tracker.test.{test}.instance.{pid}")), + ) + } + + fn claim_with( + (starting, instance): &(HSTRING, HSTRING), + relay: impl FnOnce() -> Result>, + ) -> Result> { + claim(PCWSTR(starting.as_ptr()), PCWSTR(instance.as_ptr()), relay) + } + + fn event(signaled: bool) -> Result> { + let event = unsafe { CreateEventW(None, false, signaled, PCWSTR::null())? }; + Ok(Some(owned(event))) + } + #[test] fn launch_relays_to_a_running_instance_and_takes_over_after_shutdown() { - let pid = std::process::id(); - let starting = HSTRING::from(format!("Local\\arena-tracker.test.starting.{pid}")); - let instance = HSTRING::from(format!("Local\\arena-tracker.test.instance.{pid}")); - let (starting, instance) = (&starting, &instance); - let names = || (PCWSTR(starting.as_ptr()), PCWSTR(instance.as_ptr())); - let (starting, instance) = names(); - let (primary, initializing) = decide(starting, instance, || { - panic!("First launch has no window to relay to") - }) - .unwrap() - .unwrap(); + let names = names("relay"); + let Primary { + instance: primary, + starting: initializing, + } = claim_with(&names, || panic!("First launch has no window to relay to")) + .unwrap() + .unwrap(); + let names = &names; thread::scope(|scope| { let secondary = scope.spawn(|| { - let (starting, instance) = names(); - let result = decide(starting, instance, || { - let event = unsafe { CreateEventW(None, false, true, PCWSTR::null())? }; - Ok(Some(unsafe { OwnedHandle::from_raw_handle(event.0) })) - }); - assert!(result.unwrap().is_none()); + assert!(claim_with(names, || event(true)).unwrap().is_none()); }); drop(initializing); secondary.join().unwrap(); let (relaying, attempted) = mpsc::channel(); let successor = scope.spawn(move || { - let (starting, instance) = names(); - let result = decide(starting, instance, || { - let event = unsafe { CreateEventW(None, false, false, PCWSTR::null())? }; + let result = claim_with(names, || { relaying.send(()).unwrap(); - Ok(Some(unsafe { OwnedHandle::from_raw_handle(event.0) })) + event(false) }); assert!(result.unwrap().is_some()); }); @@ -214,4 +252,48 @@ mod tests { successor.join().unwrap(); }); } + + #[test] + fn launch_takes_over_from_a_crashed_primary() { + let names = names("crashed"); + thread::scope(|scope| { + scope + .spawn(|| { + let primary = claim_with(&names, || panic!("No window yet")) + .unwrap() + .unwrap(); + // Exiting while owning both mutexes abandons them, as a crash would. + mem::forget(primary); + }) + .join() + .unwrap(); + }); + let result = claim_with(&names, || panic!("The crashed primary left no window")); + assert!(result.unwrap().is_some()); + } + + #[test] + fn launch_without_a_window_takes_over_once_the_owner_exits() { + let names = names("no-window"); + let Primary { instance, starting } = claim_with(&names, || panic!("No window yet")) + .unwrap() + .unwrap(); + drop(starting); + let names = &names; + + thread::scope(|scope| { + let (relaying, attempted) = mpsc::channel(); + let successor = scope.spawn(move || { + let result = claim_with(names, || { + relaying.send(()).unwrap(); + Ok(None) + }); + assert!(result.unwrap().is_some()); + }); + let result = attempted.recv_timeout(Duration::from_secs(5)); + drop(instance); + result.unwrap(); + successor.join().unwrap(); + }); + } } diff --git a/crates/app/src/title_bar.rs b/crates/app/src/title_bar.rs index 20c3896..5f00a6d 100644 --- a/crates/app/src/title_bar.rs +++ b/crates/app/src/title_bar.rs @@ -2,9 +2,8 @@ use gpui_kit::base::Button as BaseButton; use gpui_kit::component::tooltip::Tooltip; use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _}; use gpui_kit::*; -use raw_window_handle::{HasWindowHandle, RawWindowHandle}; use windows::Win32::{ - Foundation::{HWND, LPARAM, WPARAM}, + Foundation::{LPARAM, WPARAM}, UI::WindowsAndMessaging::{PostMessageW, SC_CLOSE, SC_MAXIMIZE, SC_RESTORE, WM_SYSCOMMAND}, }; @@ -139,10 +138,7 @@ fn toggle_maximize(window: &Window) { } fn window_command(window: &Window, command: u32) { - if let Ok(handle) = HasWindowHandle::window_handle(window) - && let RawWindowHandle::Win32(handle) = handle.as_raw() - { - let hwnd = HWND(handle.hwnd.get() as _); + if let Some(hwnd) = crate::tray::window_hwnd(window) { // Post so the native command runs after GPUI finishes dispatching this click. let _ = unsafe { PostMessageW( diff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rs index dfd8933..715f004 100644 --- a/crates/app/src/tray.rs +++ b/crates/app/src/tray.rs @@ -24,7 +24,7 @@ use windows::Win32::{ use windows::core::{PCWSTR, w}; const TRAY_SUBCLASS: usize = 0; -const TRAY_MESSAGE: u32 = WM_APP + 1; +pub(crate) const TRAY_MESSAGE: u32 = WM_APP + 1; const ICON_ID: u32 = 1; const OPEN: u32 = 1; const QUIT: u32 = 2; @@ -35,6 +35,14 @@ const NOTICE_TITLE: &str = "Arena Tracker reste ouvert"; const NOTICE_TEXT: &str = "L’application continue dans la zone de notification. Cliquez sur \ son icône pour la rouvrir, ou faites un clic droit pour la quitter."; +pub(crate) fn window_hwnd(window: &Window) -> Option { + let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).ok()?.as_raw() + else { + return None; + }; + Some(HWND(handle.hwnd.get() as _)) +} + pub struct Tray { hwnd: HWND, taskbar_created: u32, @@ -65,11 +73,7 @@ impl Tray { } pub fn install(window: &Window, notice: Option>, cx: &App) -> Option> { - let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).ok()?.as_raw() - else { - return None; - }; - let hwnd = HWND(handle.hwnd.get() as _); + let hwnd = window_hwnd(window)?; let taskbar_created = unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) }; if taskbar_created == 0 { return None; @@ -255,17 +259,20 @@ pub fn reopen(hwnd: HWND) { .as_bool() { let data = data as *const Tray; - // A native call in open can destroy the window and release the subclass's reference. - let tray = unsafe { - Rc::increment_strong_count(data); - Rc::from_raw(data) - }; - tray.open(); + unsafe { retain(data) }.open(); } else { foreground(hwnd); } } +/// A native call can destroy the window and release the subclass's reference, so take our own. +unsafe fn retain(data: *const Tray) -> Rc { + unsafe { + Rc::increment_strong_count(data); + Rc::from_raw(data) + } +} + fn foreground(hwnd: HWND) { unsafe { let command = if IsIconic(hwnd).as_bool() { @@ -297,10 +304,7 @@ unsafe extern "system" fn window_proc( { return unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }; } - let tray = unsafe { - Rc::increment_strong_count(data); - Rc::from_raw(data) - }; + let tray = unsafe { retain(data) }; match message { WM_CLOSE if tray.enabled.get() => {