- Reopen the window even when the relaunch's ack event is gone. - Exit quietly instead of panicking on timeout or Win32 error; bound the startup gate wait. - Fail softly in accept_relaunches; name the locks (Primary, HeldMutex). - Share window_hwnd, derive REOPEN from TRAY_MESSAGE, name the marker. - Test a crashed primary and a relaunch that finds no window. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
300 lines
10 KiB
Rust
300 lines
10 KiB
Rust
//! 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 windows::Win32::{
|
|
Foundation::{
|
|
HANDLE, HWND, LPARAM, LRESULT, WAIT_ABANDONED, WAIT_EVENT, WAIT_OBJECT_0, WAIT_TIMEOUT,
|
|
WPARAM,
|
|
},
|
|
System::Threading::{
|
|
CreateEventW, CreateMutexW, EVENT_MODIFY_STATE, 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");
|
|
// 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 HeldMutex(OwnedHandle, PhantomData<*mut ()>);
|
|
|
|
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<Option<Self>> {
|
|
match status {
|
|
WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(Some(Self(handle, PhantomData))),
|
|
WAIT_TIMEOUT => Ok(None),
|
|
_ => Err(Error::from_thread()),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Drop for HeldMutex {
|
|
fn drop(&mut self) {
|
|
let _ = unsafe { ReleaseMutex(HANDLE(self.0.as_raw_handle())) };
|
|
}
|
|
}
|
|
|
|
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 owned(handle: HANDLE) -> OwnedHandle {
|
|
unsafe { OwnedHandle::from_raw_handle(handle.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<Primary> {
|
|
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<Option<OwnedHandle>>,
|
|
) -> Result<Option<Primary>> {
|
|
// 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(
|
|
&[handle, HANDLE(event.as_raw_handle())],
|
|
false,
|
|
LAUNCH_TIMEOUT_MS,
|
|
)
|
|
},
|
|
None => unsafe { WaitForSingleObject(handle, LAUNCH_TIMEOUT_MS) },
|
|
},
|
|
status => status,
|
|
};
|
|
if status == REOPENED {
|
|
return Ok(None);
|
|
}
|
|
Ok(HeldMutex::from_wait(mutex, status)?.map(|instance| Primary { instance, starting }))
|
|
}
|
|
|
|
fn reply_name(pid: u32) -> HSTRING {
|
|
HSTRING::from(format!("Local\\nessar.arena-tracker.reopened.{pid}"))
|
|
}
|
|
|
|
fn relay() -> Result<Option<OwnedHandle>> {
|
|
unsafe extern "system" fn find(hwnd: HWND, output: LPARAM) -> BOOL {
|
|
if !marked(hwnd) {
|
|
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 = 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.
|
|
PostMessageW(Some(hwnd), REOPEN, WPARAM(sender as usize), LPARAM(0))
|
|
};
|
|
Ok(posted.is_ok().then_some(event))
|
|
}
|
|
|
|
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;
|
|
};
|
|
unsafe {
|
|
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}");
|
|
}
|
|
}
|
|
}
|
|
|
|
unsafe extern "system" fn window_proc(
|
|
hwnd: HWND,
|
|
message: u32,
|
|
wparam: WPARAM,
|
|
lparam: LPARAM,
|
|
id: usize,
|
|
_: usize,
|
|
) -> LRESULT {
|
|
match message {
|
|
REOPEN => {
|
|
if marked(hwnd) {
|
|
crate::tray::reopen(hwnd);
|
|
// 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) };
|
|
}
|
|
}
|
|
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::{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<Option<OwnedHandle>>,
|
|
) -> Result<Option<Primary>> {
|
|
claim(PCWSTR(starting.as_ptr()), PCWSTR(instance.as_ptr()), relay)
|
|
}
|
|
|
|
fn event(signaled: bool) -> Result<Option<OwnedHandle>> {
|
|
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 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(|| {
|
|
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 result = claim_with(names, || {
|
|
relaying.send(()).unwrap();
|
|
event(false)
|
|
});
|
|
assert!(result.unwrap().is_some());
|
|
});
|
|
let result = attempted.recv_timeout(Duration::from_secs(5));
|
|
drop(primary);
|
|
result.unwrap();
|
|
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();
|
|
});
|
|
}
|
|
}
|