From a11bc277f2eac753d3e3fabb4d9db7c9c29d7f45 Mon Sep 17 00:00:00 2001 From: Nessar Date: Thu, 19 Nov 2026 22:40:58 +0100 Subject: [PATCH] Restore the existing window on relaunch (#50) Elect one process per Windows session before starting GPUI or opening the database. Let the existing window handle reopen requests and preserve its current state. --- crates/app/Cargo.toml | 2 + crates/app/src/main.rs | 9 ++ crates/app/src/single_instance.rs | 217 ++++++++++++++++++++++++++++++ crates/app/src/tray.rs | 52 ++++--- 4 files changed, 265 insertions(+), 15 deletions(-) create mode 100644 crates/app/src/single_instance.rs diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index b170172..73f0247 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -14,7 +14,9 @@ gpui-kit = "=0.9.1" [target.'cfg(windows)'.dependencies] raw-window-handle = "0.6" windows = { version = "0.62", features = [ + "Win32_Security", "Win32_System_LibraryLoader", + "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", ] } diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 0f3959d..7c9b11c 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -4,6 +4,7 @@ mod champion_table; #[cfg(feature = "profile")] mod profile; mod settings; +mod single_instance; mod stats_page; mod text; mod title_bar; @@ -261,6 +262,11 @@ fn init_theme(cx: &mut App) { } fn main() { + let Some((_instance, starting)) = + single_instance::launch().expect("Failed to check for a running instance") + else { + return; + }; let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets); app.run(move |cx| { gpui_kit::init(cx); @@ -282,10 +288,12 @@ fn main() { }; match startup() { Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| { + single_instance::attach(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); apply_theme(preferences.theme, window, cx); window .observe_window_appearance(move |window, cx| { @@ -302,6 +310,7 @@ fn main() { .map(drop), } .expect("Failed to open window"); + drop(starting); }); } diff --git a/crates/app/src/single_instance.rs b/crates/app/src/single_instance.rs new file mode 100644 index 0000000..77102f7 --- /dev/null +++ b/crates/app/src/single_instance.rs @@ -0,0 +1,217 @@ +//! Elects one primary process per Windows session and relays launches to its window. + +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, + }, + System::Threading::{ + CreateEventW, CreateMutexW, EVENT_MODIFY_STATE, INFINITE, OpenEventW, ReleaseMutex, + SetEvent, WaitForMultipleObjects, WaitForSingleObject, + }, + UI::{ + Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}, + WindowsAndMessaging::*, + }, +}; +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 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 ()>); + +impl SessionLock { + 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())), + _ => Err(Error::from_thread()), + } + } +} + +impl Drop for SessionLock { + fn drop(&mut self) { + let _ = unsafe { ReleaseMutex(HANDLE(self.0.as_raw_handle())) }; + } +} + +pub fn launch() -> Result> { + decide(STARTING, INSTANCE, relay) +} + +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)?; + + let mutex = unsafe { CreateMutexW(None, false, instance)? }; + let instance = unsafe { OwnedHandle::from_raw_handle(mutex.0) }; + let status = match unsafe { WaitForSingleObject(mutex, 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())], + false, + RELAY_TIMEOUT_MS, + ) + }, + None => unsafe { WaitForSingleObject(mutex, RELAY_TIMEOUT_MS) }, + }, + status => status, + }; + if status == REOPENED { + return Ok(None); + } + Ok(Some((SessionLock::from_wait(instance, status)?, starting))) +} + +fn reply_name(pid: u32) -> HSTRING { + HSTRING::from(format!("Local\\nessar.arena-tracker.reopened.{pid}")) +} + +fn relay() -> Result> { + unsafe extern "system" fn find(hwnd: HWND, output: LPARAM) -> BOOL { + if unsafe { GetPropW(hwnd, WINDOW_MARKER) }.is_invalid() { + return true.into(); + } + unsafe { *(output.0 as *mut HWND) = hwnd }; + false.into() + } + + let mut hwnd = HWND::default(); + let _ = unsafe { EnumWindows(Some(find), LPARAM((&mut hwnd as *mut HWND) as isize)) }; + if hwnd.is_invalid() { + return Ok(None); + } + let mut pid = 0; + if unsafe { GetWindowThreadProcessId(hwnd, Some(&mut pid)) } == 0 { + 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 posted = unsafe { + let _ = AllowSetForegroundWindow(pid); + // A posted reopen runs after any close already in the window's message queue. + PostMessageW(Some(hwnd), REOPEN, WPARAM(sender as usize), LPARAM(0)) + }; + 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"); + }; + 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"); + } +} + +unsafe extern "system" fn window_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + id: usize, + _: usize, +) -> 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) }; + crate::tray::reopen(hwnd); + if !unsafe { GetPropW(hwnd, WINDOW_MARKER) }.is_invalid() { + let _ = unsafe { SetEvent(event) }; + } + } + return LRESULT(0); + } + WM_DESTROY => { + let _ = unsafe { RemovePropW(hwnd, WINDOW_MARKER) }; + } + WM_NCDESTROY => { + let _ = unsafe { RemoveWindowSubclass(hwnd, Some(window_proc), id) }; + } + _ => {} + } + unsafe { DefSubclassProc(hwnd, message, wparam, lparam) } +} + +#[cfg(test)] +mod tests { + use std::{sync::mpsc, thread, time::Duration}; + + use super::*; + + #[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(); + + 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()); + }); + 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())? }; + relaying.send(()).unwrap(); + Ok(Some(unsafe { OwnedHandle::from_raw_handle(event.0) })) + }); + assert!(result.unwrap().is_some()); + }); + let result = attempted.recv_timeout(Duration::from_secs(5)); + drop(primary); + result.unwrap(); + successor.join().unwrap(); + }); + } +} diff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rs index 401746b..dfd8933 100644 --- a/crates/app/src/tray.rs +++ b/crates/app/src/tray.rs @@ -13,16 +13,17 @@ use windows::Win32::{ System::LibraryLoader::GetModuleHandleW, UI::{ Shell::{ - DefSubclassProc, NIF_ICON, NIF_INFO, NIF_MESSAGE, NIF_SHOWTIP, NIF_TIP, NIIF_INFO, - NIM_ADD, NIM_DELETE, NIM_MODIFY, NIM_SETFOCUS, NIM_SETVERSION, NIN_SELECT, - NOTIFYICON_VERSION_4, NOTIFYICONDATAW, NOTIFYICONIDENTIFIER, RemoveWindowSubclass, - SetWindowSubclass, Shell_NotifyIconGetRect, Shell_NotifyIconW, + DefSubclassProc, GetWindowSubclass, NIF_ICON, NIF_INFO, NIF_MESSAGE, NIF_SHOWTIP, + NIF_TIP, NIIF_INFO, NIM_ADD, NIM_DELETE, NIM_MODIFY, NIM_SETFOCUS, NIM_SETVERSION, + NIN_SELECT, NOTIFYICON_VERSION_4, NOTIFYICONDATAW, NOTIFYICONIDENTIFIER, + RemoveWindowSubclass, SetWindowSubclass, Shell_NotifyIconGetRect, Shell_NotifyIconW, }, WindowsAndMessaging::*, }, }; use windows::core::{PCWSTR, w}; +const TRAY_SUBCLASS: usize = 0; const TRAY_MESSAGE: u32 = WM_APP + 1; const ICON_ID: u32 = 1; const OPEN: u32 = 1; @@ -92,7 +93,7 @@ impl Tray { }); // The subclass owns one reference until WM_NCDESTROY. This window belongs to the UI thread. let data = Rc::into_raw(tray.clone()); - if !unsafe { SetWindowSubclass(hwnd, Some(window_proc), data as usize, data as usize) } + if !unsafe { SetWindowSubclass(hwnd, Some(window_proc), TRAY_SUBCLASS, data as usize) } .as_bool() { drop(unsafe { Rc::from_raw(data) }); @@ -104,7 +105,7 @@ impl Tray { pub fn uninstall(self: Rc) { self.enabled.set(false); let data = Rc::as_ptr(&self); - if unsafe { RemoveWindowSubclass(self.hwnd, Some(window_proc), data as usize) }.as_bool() { + if unsafe { RemoveWindowSubclass(self.hwnd, Some(window_proc), TRAY_SUBCLASS) }.as_bool() { drop(unsafe { Rc::from_raw(data) }); } } @@ -171,15 +172,7 @@ impl Tray { fn open(&self) { self.remove_icon(); - unsafe { - let command = if IsIconic(self.hwnd).as_bool() { - SW_RESTORE - } else { - SW_SHOW - }; - let _ = ShowWindow(self.hwnd, command); - let _ = SetForegroundWindow(self.hwnd); - } + foreground(self.hwnd); } fn report_unavailable(&self) { @@ -256,6 +249,35 @@ fn fill(field: &mut [u16], text: &str) { } } +pub fn reopen(hwnd: HWND) { + let mut data = 0; + if unsafe { GetWindowSubclass(hwnd, Some(window_proc), TRAY_SUBCLASS, Some(&mut data)) } + .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(); + } else { + foreground(hwnd); + } +} + +fn foreground(hwnd: HWND) { + unsafe { + let command = if IsIconic(hwnd).as_bool() { + SW_RESTORE + } else { + SW_SHOW + }; + let _ = ShowWindow(hwnd, command); + let _ = SetForegroundWindow(hwnd); + } +} + unsafe extern "system" fn window_proc( hwnd: HWND, message: u32,