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.
346 lines
11 KiB
Rust
346 lines
11 KiB
Rust
//! Keeps the existing GPUI window alive while it is hidden in the Windows notification area.
|
||
|
||
use std::{
|
||
cell::Cell,
|
||
rc::{Rc, Weak},
|
||
};
|
||
|
||
use gpui_kit::base::async_util::Sender;
|
||
use gpui_kit::{App, PromptLevel, Subscription, Window};
|
||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||
use windows::Win32::{
|
||
Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, WPARAM},
|
||
System::LibraryLoader::GetModuleHandleW,
|
||
UI::{
|
||
Shell::{
|
||
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;
|
||
const QUIT: u32 = 2;
|
||
const NIN_KEYSELECT: u32 = NIN_SELECT | 1;
|
||
pub const UNAVAILABLE: &str =
|
||
"La zone de notification est indisponible. La fenêtre reste accessible.";
|
||
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 struct Tray {
|
||
hwnd: HWND,
|
||
taskbar_created: u32,
|
||
enabled: Cell<bool>,
|
||
hidden: Cell<bool>,
|
||
/// Until the one-time notice is shown: told when it is, so that it can be recorded.
|
||
notice: Cell<Option<Sender<()>>>,
|
||
_quit: Subscription,
|
||
}
|
||
|
||
impl Tray {
|
||
pub fn install_saved(
|
||
window: &mut Window,
|
||
enabled: bool,
|
||
notice: Option<Sender<()>>,
|
||
cx: &mut App,
|
||
) -> Option<Rc<Self>> {
|
||
if !enabled {
|
||
return None;
|
||
}
|
||
let tray = Self::install(window, notice, cx);
|
||
if tray.is_none() {
|
||
window.defer(cx, |window, cx| {
|
||
drop(window.prompt(PromptLevel::Warning, UNAVAILABLE, None, &["OK"], cx));
|
||
});
|
||
}
|
||
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 taskbar_created = unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) };
|
||
if taskbar_created == 0 {
|
||
return None;
|
||
}
|
||
let tray = Rc::new_cyclic(|weak: &Weak<Self>| {
|
||
let weak = weak.clone();
|
||
let quit = cx.on_app_quit(move |_| {
|
||
if let Some(tray) = weak.upgrade() {
|
||
tray.remove_icon();
|
||
}
|
||
async {}
|
||
});
|
||
Self {
|
||
hwnd,
|
||
taskbar_created,
|
||
enabled: Cell::new(true),
|
||
hidden: Cell::new(false),
|
||
notice: Cell::new(notice),
|
||
_quit: quit,
|
||
}
|
||
});
|
||
// 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), TRAY_SUBCLASS, data as usize) }
|
||
.as_bool()
|
||
{
|
||
drop(unsafe { Rc::from_raw(data) });
|
||
return None;
|
||
}
|
||
Some(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), TRAY_SUBCLASS) }.as_bool() {
|
||
drop(unsafe { Rc::from_raw(data) });
|
||
}
|
||
}
|
||
|
||
fn icon_data(&self) -> NOTIFYICONDATAW {
|
||
NOTIFYICONDATAW {
|
||
cbSize: size_of::<NOTIFYICONDATAW>() as u32,
|
||
hWnd: self.hwnd,
|
||
uID: ICON_ID,
|
||
..Default::default()
|
||
}
|
||
}
|
||
|
||
fn add_icon(&self) -> bool {
|
||
unsafe {
|
||
let icon = GetModuleHandleW(None)
|
||
.and_then(|module| LoadIconW(Some(HINSTANCE(module.0)), PCWSTR(1 as _)))
|
||
.or_else(|_| LoadIconW(None, IDI_APPLICATION));
|
||
let Ok(icon) = icon else { return false };
|
||
let mut data = NOTIFYICONDATAW {
|
||
uFlags: NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP,
|
||
uCallbackMessage: TRAY_MESSAGE,
|
||
hIcon: icon,
|
||
..self.icon_data()
|
||
};
|
||
fill(&mut data.szTip, "Arena Tracker");
|
||
if !Shell_NotifyIconW(NIM_ADD, &data).as_bool() {
|
||
return false;
|
||
}
|
||
data.Anonymous.uVersion = NOTIFYICON_VERSION_4;
|
||
if !Shell_NotifyIconW(NIM_SETVERSION, &data).as_bool() {
|
||
let _ = Shell_NotifyIconW(NIM_DELETE, &data);
|
||
return false;
|
||
}
|
||
true
|
||
}
|
||
}
|
||
|
||
/// Says once, as a Windows notification, that closing kept the app running here.
|
||
fn show_notice(&self) {
|
||
let Some(shown) = self.notice.take() else {
|
||
return;
|
||
};
|
||
let mut data = NOTIFYICONDATAW {
|
||
uFlags: NIF_INFO,
|
||
dwInfoFlags: NIIF_INFO,
|
||
..self.icon_data()
|
||
};
|
||
fill(&mut data.szInfoTitle, NOTICE_TITLE);
|
||
fill(&mut data.szInfo, NOTICE_TEXT);
|
||
if unsafe { Shell_NotifyIconW(NIM_MODIFY, &data) }.as_bool() {
|
||
// Recorded by the settings form, outside this window procedure.
|
||
let _ = shown.try_send(());
|
||
} else {
|
||
self.notice.set(Some(shown));
|
||
}
|
||
}
|
||
|
||
fn remove_icon(&self) {
|
||
if self.hidden.replace(false) {
|
||
let _ = unsafe { Shell_NotifyIconW(NIM_DELETE, &self.icon_data()) };
|
||
}
|
||
}
|
||
|
||
fn open(&self) {
|
||
self.remove_icon();
|
||
foreground(self.hwnd);
|
||
}
|
||
|
||
fn report_unavailable(&self) {
|
||
let message: Vec<_> = UNAVAILABLE.encode_utf16().chain([0]).collect();
|
||
unsafe {
|
||
MessageBoxW(
|
||
Some(self.hwnd),
|
||
PCWSTR(message.as_ptr()),
|
||
w!("Arena Tracker"),
|
||
MB_OK | MB_ICONWARNING,
|
||
);
|
||
}
|
||
}
|
||
|
||
fn show_menu(&self) {
|
||
unsafe {
|
||
let Ok(menu) = CreatePopupMenu() else { return };
|
||
let result = (|| {
|
||
AppendMenuW(menu, MF_STRING, OPEN as usize, w!("Ouvrir"))?;
|
||
AppendMenuW(menu, MF_STRING, QUIT as usize, w!("Quitter"))?;
|
||
let icon = NOTIFYICONIDENTIFIER {
|
||
cbSize: size_of::<NOTIFYICONIDENTIFIER>() as u32,
|
||
hWnd: self.hwnd,
|
||
uID: ICON_ID,
|
||
..Default::default()
|
||
};
|
||
let point = match Shell_NotifyIconGetRect(&icon) {
|
||
Ok(rect) => POINT {
|
||
x: rect.left,
|
||
y: rect.top,
|
||
},
|
||
Err(_) => {
|
||
let mut point = POINT::default();
|
||
GetCursorPos(&mut point)?;
|
||
point
|
||
}
|
||
};
|
||
let _ = SetForegroundWindow(self.hwnd);
|
||
Ok::<_, windows::core::Error>(
|
||
TrackPopupMenu(
|
||
menu,
|
||
TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON,
|
||
point.x,
|
||
point.y,
|
||
None,
|
||
self.hwnd,
|
||
None,
|
||
)
|
||
.0 as u32,
|
||
)
|
||
})();
|
||
let _ = DestroyMenu(menu);
|
||
let _ = PostMessageW(Some(self.hwnd), WM_NULL, WPARAM(0), LPARAM(0));
|
||
match result {
|
||
Ok(OPEN) => self.open(),
|
||
Ok(QUIT) => {
|
||
// Destroying the window takes GPUI's normal exit path without another close request.
|
||
let _ = DestroyWindow(self.hwnd);
|
||
}
|
||
_ if self.hidden.get() => {
|
||
let _ = Shell_NotifyIconW(NIM_SETFOCUS, &self.icon_data());
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Copies `text` into a fixed Win32 string field, truncated, always ending with a NUL.
|
||
fn fill(field: &mut [u16], text: &str) {
|
||
let room = field.len() - 1;
|
||
for (unit, letter) in field[..room].iter_mut().zip(text.encode_utf16()) {
|
||
*unit = letter;
|
||
}
|
||
}
|
||
|
||
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,
|
||
wparam: WPARAM,
|
||
lparam: LPARAM,
|
||
id: usize,
|
||
data: usize,
|
||
) -> LRESULT {
|
||
let data = data as *const Tray;
|
||
// Native calls can dispatch nested messages, including destruction. Keep our own reference
|
||
// for the messages we handle and leave the high-frequency messages on the default path.
|
||
let taskbar_created = unsafe { (*data).taskbar_created };
|
||
if !matches!(
|
||
message,
|
||
WM_CLOSE | WM_ENDSESSION | WM_NCDESTROY | TRAY_MESSAGE
|
||
) && message != taskbar_created
|
||
{
|
||
return unsafe { DefSubclassProc(hwnd, message, wparam, lparam) };
|
||
}
|
||
let tray = unsafe {
|
||
Rc::increment_strong_count(data);
|
||
Rc::from_raw(data)
|
||
};
|
||
|
||
match message {
|
||
WM_CLOSE if tray.enabled.get() => {
|
||
if !tray.hidden.get() {
|
||
if tray.add_icon() {
|
||
tray.hidden.set(true);
|
||
let _ = unsafe { ShowWindow(hwnd, SW_HIDE) };
|
||
tray.show_notice();
|
||
} else {
|
||
tray.report_unavailable();
|
||
}
|
||
}
|
||
return LRESULT(0);
|
||
}
|
||
TRAY_MESSAGE => {
|
||
if tray.hidden.get() && (lparam.0 as u32 >> 16) == ICON_ID {
|
||
match lparam.0 as u32 & 0xffff {
|
||
WM_CONTEXTMENU => tray.show_menu(),
|
||
NIN_SELECT | NIN_KEYSELECT => tray.open(),
|
||
_ => {}
|
||
}
|
||
}
|
||
return LRESULT(0);
|
||
}
|
||
WM_ENDSESSION if wparam.0 != 0 => tray.remove_icon(),
|
||
WM_NCDESTROY => unsafe {
|
||
tray.remove_icon();
|
||
let _ = RemoveWindowSubclass(hwnd, Some(window_proc), id);
|
||
drop(Rc::from_raw(data));
|
||
},
|
||
message if message == taskbar_created && tray.hidden.get() => {
|
||
// Explorer discards notification icons when it recreates the taskbar.
|
||
if !tray.add_icon() {
|
||
tray.open();
|
||
tray.report_unavailable();
|
||
}
|
||
return LRESULT(0);
|
||
}
|
||
_ => {}
|
||
}
|
||
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
|
||
}
|