Restaurer la fenêtre existante au relancement #53

Merged
nessar merged 2 commits from feat/50-single-instance into main 2026-11-19 23:10:46 +01:00
5 changed files with 365 additions and 31 deletions

No files matched your search

+2
View File
@@ -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",
] }
+11
View File
@@ -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,13 @@ fn init_theme(cx: &mut App) {
}
fn main() {
let Some(single_instance::Primary {
instance: _instance,
starting,
}) = single_instance::launch()
else {
return;
};
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
@@ -282,10 +290,12 @@ fn main() {
};
match startup() {
Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| {
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::accept_relaunches(window);
apply_theme(preferences.theme, window, cx);
window
.observe_window_appearance(move |window, cx| {
@@ -302,6 +312,7 @@ fn main() {
.map(drop),
}
.expect("Failed to open window");
drop(starting);
});
}
+299
View File
@@ -0,0 +1,299 @@
//! 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();
});
}
}
+2 -6
View File
@@ -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(
+51 -25
View File
@@ -13,17 +13,18 @@ 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_MESSAGE: u32 = WM_APP + 1;
const TRAY_SUBCLASS: usize = 0;
pub(crate) const TRAY_MESSAGE: u32 = WM_APP + 1;
const ICON_ID: u32 = 1;
const OPEN: u32 = 1;
const QUIT: u32 = 2;
@@ -34,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<HWND> {
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,
@@ -64,11 +73,7 @@ impl Tray {
}
pub fn install(window: &Window, notice: Option<Sender<()>>, cx: &App) -> Option<Rc<Self>> {
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;
@@ -92,7 +97,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 +109,7 @@ impl Tray {
pub fn uninstall(self: Rc<Self>) {
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 +176,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 +253,38 @@ 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;
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<Tray> {
unsafe {
Rc::increment_strong_count(data);
Rc::from_raw(data)
}
}
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,
@@ -275,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() => {