BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / notify / platform / windows_impl.rs

windows_impl.rs

windows_impl.rs 11.7 KiB Download Raw
1use std::ffi::c_void;
2use std::io::Cursor;
3
4use gpui_kit::Window;
5use raw_window_handle::{HasWindowHandle, RawWindowHandle};
6use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem};
7use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
8use windows::Win32::Foundation::{HWND, RECT};
9use windows::Win32::Graphics::Dwm::{
10 DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DONOTROUND,
11 DwmSetWindowAttribute,
12};
13use windows::Win32::Graphics::Gdi::{
14 CreateBitmap, DeleteObject, GetMonitorInfoW, HGDIOBJ, MONITOR_DEFAULTTONEAREST, MONITORINFO,
15 MonitorFromWindow,
16};
17use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
18use windows::Win32::UI::HiDpi::GetDpiForWindow;
19use windows::Win32::UI::Shell::{
20 ITaskbarList3, QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_QUIET_TIME, QUNS_RUNNING_D3D_FULL_SCREEN,
21 SHQueryUserNotificationState, TaskbarList,
22};
23use windows::Win32::UI::WindowsAndMessaging::{
24 CreateIconIndirect, DestroyIcon, FLASHW_TIMERNOFG, FLASHW_TRAY, FLASHWINFO, FlashWindowEx, GWL_EXSTYLE, GWL_STYLE,
25 GetWindowLongPtrW, HICON, HWND_TOPMOST, ICONINFO, IsIconic, SW_HIDE, SW_RESTORE, SW_SHOW, SWP_NOACTIVATE,
26 SPI_GETCLIENTAREAANIMATION, SWP_FRAMECHANGED, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
27 SWP_NOZORDER, WS_CAPTION, WS_POPUP, WS_THICKFRAME, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetForegroundWindow,
28 SetWindowLongPtrW, SetWindowPos, ShowWindow, SystemParametersInfoW,
29 WS_EX_NOACTIVATE,
30};
31use windows::core::{BOOL, w};
32
33use super::{NativeHandle, TrayCommand, WorkArea};
34use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};
35
36const SOUND_BYTES: &[u8] = include_bytes!("../../../assets/sounds/notification.mp3");
37const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../assets/icon/teams-fast-256.png");
38const TRAY_ICON_SIZE: u32 = 32;
39const TRAY_DOT_RADIUS: f32 = 6.;
40const BASE_DPI: f32 = 96.;
41
42fn hwnd(handle: NativeHandle) -> HWND {
43 HWND(handle as *mut c_void)
44}
45
46pub fn native_handle(window: &Window) -> Option<NativeHandle> {
47 match HasWindowHandle::window_handle(window).ok()?.as_raw() {
48 RawWindowHandle::Win32(handle) => Some(handle.hwnd.get()),
49 _ => None,
50 }
51}
52
53pub fn prepare_toast_window(handle: NativeHandle) {
54 unsafe {
55 // GPUI creates popups with style 0, and Windows adds a caption frame to that on its own.
56 let frame = (WS_CAPTION | WS_THICKFRAME).0 as isize;
57 let style = GetWindowLongPtrW(hwnd(handle), GWL_STYLE);
58 SetWindowLongPtrW(
59 hwnd(handle),
60 GWL_STYLE,
61 (style & !frame) | WS_POPUP.0 as isize,
62 );
63 let _ = SetWindowPos(
64 hwnd(handle),
65 None,
66 0,
67 0,
68 0,
69 0,
70 SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE,
71 );
72 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
73 SetWindowLongPtrW(
74 hwnd(handle),
75 GWL_EXSTYLE,
76 style | WS_EX_NOACTIVATE.0 as isize,
77 );
78 let no_border = DWMWA_COLOR_NONE;
79 let _ = DwmSetWindowAttribute(
80 hwnd(handle),
81 DWMWA_BORDER_COLOR,
82 &no_border as *const _ as *const c_void,
83 size_of::<u32>() as u32,
84 );
85 let preference = DWMWCP_DONOTROUND;
86 let _ = DwmSetWindowAttribute(
87 hwnd(handle),
88 DWMWA_WINDOW_CORNER_PREFERENCE,
89 &preference as *const _ as *const c_void,
90 size_of_val(&preference) as u32,
91 );
92 }
93}
94
95pub fn set_activatable(handle: NativeHandle, activatable: bool) {
96 unsafe {
97 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
98 let flag = WS_EX_NOACTIVATE.0 as isize;
99 let updated = if activatable { style & !flag } else { style | flag };
100 SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, updated);
101 if activatable {
102 let _ = SetForegroundWindow(hwnd(handle));
103 }
104 }
105}
106
107pub fn work_area(handle: NativeHandle) -> Option<WorkArea> {
108 unsafe {
109 let monitor = MonitorFromWindow(hwnd(handle), MONITOR_DEFAULTTONEAREST);
110 let mut info = MONITORINFO {
111 cbSize: size_of::<MONITORINFO>() as u32,
112 ..Default::default()
113 };
114 if !GetMonitorInfoW(monitor, &mut info).as_bool() {
115 return None;
116 }
117 let RECT {
118 left,
119 top,
120 right,
121 bottom,
122 } = info.rcWork;
123 let dpi = GetDpiForWindow(hwnd(handle));
124 Some(WorkArea {
125 left,
126 top,
127 right,
128 bottom,
129 scale: if dpi == 0 { 1. } else { dpi as f32 / BASE_DPI },
130 })
131 }
132}
133
134pub fn place(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) {
135 unsafe {
136 let _ = SetWindowPos(
137 hwnd(handle),
138 Some(HWND_TOPMOST),
139 x,
140 y,
141 width,
142 height,
143 SWP_NOACTIVATE | SWP_NOOWNERZORDER,
144 );
145 }
146}
147
148pub fn system_quiet() -> bool {
149 let state = unsafe { SHQueryUserNotificationState() };
150 matches!(
151 state,
152 Ok(QUNS_BUSY | QUNS_RUNNING_D3D_FULL_SCREEN | QUNS_PRESENTATION_MODE | QUNS_QUIET_TIME)
153 )
154}
155
156pub fn restore_and_raise(handle: NativeHandle) {
157 unsafe {
158 let command = if IsIconic(hwnd(handle)).as_bool() {
159 SW_RESTORE
160 } else {
161 SW_SHOW
162 };
163 let _ = ShowWindow(hwnd(handle), command);
164 let _ = SetForegroundWindow(hwnd(handle));
165 }
166}
167
168pub fn hide_window(handle: NativeHandle) {
169 unsafe {
170 let _ = ShowWindow(hwnd(handle), SW_HIDE);
171 }
172}
173
174pub fn flash(handle: NativeHandle) {
175 let info = FLASHWINFO {
176 cbSize: size_of::<FLASHWINFO>() as u32,
177 hwnd: hwnd(handle),
178 dwFlags: FLASHW_TRAY | FLASHW_TIMERNOFG,
179 uCount: 0,
180 dwTimeout: 0,
181 };
182 unsafe {
183 let _ = FlashWindowEx(&info);
184 }
185}
186
187pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) {
188 unsafe {
189 let Ok(taskbar) = CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)
190 else {
191 return;
192 };
193 if taskbar.HrInit().is_err() {
194 return;
195 }
196 match badge {
197 None => {
198 let _ = taskbar.SetOverlayIcon(hwnd(handle), HICON::default(), w!(""));
199 }
200 Some(badge) => {
201 let Some(icon) = icon_from_badge(badge) else {
202 return;
203 };
204 let _ = taskbar.SetOverlayIcon(hwnd(handle), icon, w!("Unread chats"));
205 let _ = DestroyIcon(icon);
206 }
207 }
208 }
209}
210
211unsafe fn icon_from_badge(badge: &Badge) -> Option<HICON> {
212 let pixels = render_badge(badge);
213 unsafe {
214 let color = CreateBitmap(
215 BADGE_SIZE as i32,
216 BADGE_SIZE as i32,
217 1,
218 32,
219 Some(pixels.as_ptr() as *const c_void),
220 );
221 let mask = CreateBitmap(BADGE_SIZE as i32, BADGE_SIZE as i32, 1, 1, None);
222 let info = ICONINFO {
223 fIcon: BOOL(1),
224 xHotspot: 0,
225 yHotspot: 0,
226 hbmMask: mask,
227 hbmColor: color,
228 };
229 let icon = CreateIconIndirect(&info).ok();
230 let _ = DeleteObject(HGDIOBJ(color.0));
231 let _ = DeleteObject(HGDIOBJ(mask.0));
232 icon
233 }
234}
235
236pub fn play_sound() {
237 std::thread::spawn(|| {
238 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
239 return;
240 };
241 sink.log_on_drop(false);
242 if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(SOUND_BYTES)) {
243 player.sleep_until_end();
244 }
245 });
246}
247
248const ID_OPEN: &str = "open";
249const ID_SOUND: &str = "sound";
250const ID_DO_NOT_DISTURB: &str = "do_not_disturb";
251const ID_SETTINGS: &str = "settings";
252const ID_QUIT: &str = "quit";
253
254pub struct Tray {
255 icon: TrayIcon,
256 sound: CheckMenuItem,
257 do_not_disturb: CheckMenuItem,
258 plain: Icon,
259 with_dot: Icon,
260}
261
262impl Tray {
263 pub fn new(sound_on: bool, do_not_disturb: bool) -> Option<Self> {
264 let (plain, with_dot) = tray_icons()?;
265 let open = MenuItem::with_id(ID_OPEN, "Open", true, None);
266 let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None);
267 let dnd = CheckMenuItem::with_id(
268 ID_DO_NOT_DISTURB,
269 "Do not disturb",
270 true,
271 do_not_disturb,
272 None,
273 );
274 let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None);
275 let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None);
276 let menu = Menu::new();
277 menu.append_items(&[
278 &open,
279 &PredefinedMenuItem::separator(),
280 &sound,
281 &dnd,
282 &settings,
283 &PredefinedMenuItem::separator(),
284 &quit,
285 ])
286 .ok()?;
287 let icon = TrayIconBuilder::new()
288 .with_icon(plain.clone())
289 .with_tooltip(crate::APP_NAME)
290 .with_menu(Box::new(menu))
291 .with_menu_on_left_click(false)
292 .build()
293 .ok()?;
294 Some(Tray {
295 icon,
296 sound,
297 do_not_disturb: dnd,
298 plain,
299 with_dot,
300 })
301 }
302
303 pub fn poll(&self) -> Vec<TrayCommand> {
304 let mut commands = Vec::new();
305 while let Ok(event) = MenuEvent::receiver().try_recv() {
306 let command = match event.id.0.as_str() {
307 ID_OPEN => TrayCommand::Open,
308 ID_SOUND => TrayCommand::ToggleSound,
309 ID_DO_NOT_DISTURB => TrayCommand::ToggleDoNotDisturb,
310 ID_SETTINGS => TrayCommand::Settings,
311 ID_QUIT => TrayCommand::Quit,
312 _ => continue,
313 };
314 commands.push(command);
315 }
316 while let Ok(event) = TrayIconEvent::receiver().try_recv() {
317 if let TrayIconEvent::Click {
318 button: MouseButton::Left,
319 button_state: MouseButtonState::Up,
320 ..
321 } = event
322 {
323 commands.push(TrayCommand::Toggle);
324 }
325 }
326 commands
327 }
328
329 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
330 self.sound.set_checked(!sound_on);
331 self.do_not_disturb.set_checked(do_not_disturb);
332 let icon = if mention { &self.with_dot } else { &self.plain };
333 let _ = self.icon.set_icon(Some(icon.clone()));
334 }
335}
336
337fn tray_icons() -> Option<(Icon, Icon)> {
338 let decoded = image::load_from_memory(TRAY_ICON_PNG).ok()?;
339 let resized = decoded
340 .resize_exact(
341 TRAY_ICON_SIZE,
342 TRAY_ICON_SIZE,
343 image::imageops::FilterType::Lanczos3,
344 )
345 .to_rgba8();
346 let plain = resized.clone().into_raw();
347 let mut dotted = resized;
348 let size = TRAY_ICON_SIZE as f32;
349 let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);
350 for (column, row, pixel) in dotted.enumerate_pixels_mut() {
351 let distance = ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();
352 if distance <= TRAY_DOT_RADIUS {
353 *pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);
354 }
355 }
356 Some((
357 Icon::from_rgba(plain, TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
358 Icon::from_rgba(dotted.into_raw(), TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
359 ))
360}
361
362pub fn animations_enabled() -> bool {
363 let mut enabled = BOOL(1);
364 let read = unsafe {
365 SystemParametersInfoW(
366 SPI_GETCLIENTAREAANIMATION,
367 0,
368 Some(&mut enabled as *mut BOOL as *mut c_void),
369 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
370 )
371 };
372 read.is_err() || enabled.as_bool()
373}