BlueGit

ict rusty-teams

Files

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

windows_impl.rs

windows_impl.rs 22.9 KiB Download Raw
1use std::ffi::c_void;
2use std::io::Cursor;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::time::Duration;
6
7use calling::ShareKind;
8use gpui_kit::Window;
9use raw_window_handle::{HasWindowHandle, RawWindowHandle};
10use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem};
11use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
12use windows::Win32::Foundation::{COLORREF, HWND, LPARAM, POINT, RECT, WPARAM};
13use windows::Win32::Graphics::Dwm::{
14 DWMWA_BORDER_COLOR, DWMWA_CLOAKED, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS,
15 DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DONOTROUND, DwmGetWindowAttribute,
16 DwmSetWindowAttribute,
17};
18use windows::Win32::Graphics::Gdi::{
19 CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject,
20 ENUM_CURRENT_SETTINGS, EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ,
21 MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromPoint, MonitorFromRect, MonitorFromWindow,
22};
23use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
24use windows::Win32::UI::HiDpi::{GetDpiForMonitor, GetDpiForWindow, MDT_EFFECTIVE_DPI};
25use windows::Win32::UI::Shell::{
26 ITaskbarList3, QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_QUIET_TIME,
27 QUNS_RUNNING_D3D_FULL_SCREEN, SHQueryUserNotificationState, TaskbarList,
28};
29use windows::Win32::UI::WindowsAndMessaging::{
30 CreateIconIndirect, DestroyIcon, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, FLASHWINFO,
31 FlashWindowEx, GW_HWNDPREV, GWL_EXSTYLE, GWL_STYLE, GetWindow, GetWindowLongPtrW,
32 GetWindowRect, HICON, HWND_NOTOPMOST, HWND_TOPMOST, ICON_BIG, ICON_SMALL, ICONINFO, IsIconic,
33 IsWindowVisible, LWA_ALPHA, SPI_GETCLIENTAREAANIMATION, SW_HIDE, SW_RESTORE, SW_SHOW,
34 SW_SHOWNOACTIVATE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
35 SWP_NOZORDER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SendMessageW, SetForegroundWindow,
36 SetLayeredWindowAttributes, SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WM_SETICON, WS_CAPTION,
38 WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP, WS_THICKFRAME,
39};
40use windows::core::{BOOL, PCWSTR, w};
41
42use super::stack_plan::{StackPlan, stack_plan};
43use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};
44use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};
45
46const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");
47const TRAY_ICON_SIZE: u32 = 32;
48const WINDOW_ICON_SIZE: f32 = 32.;
49const WINDOW_SMALL_ICON_SIZE: f32 = 16.;
50const TRAY_DOT_RADIUS: f32 = 6.;
51const BASE_DPI: f32 = 96.;
52const RING_POLL: Duration = Duration::from_millis(20);
53
54fn hwnd(handle: NativeHandle) -> HWND {
55 HWND(handle as *mut c_void)
56}
57
58pub fn native_handle(window: &Window) -> Option<NativeHandle> {
59 match HasWindowHandle::window_handle(window).ok()?.as_raw() {
60 RawWindowHandle::Win32(handle) => Some(handle.hwnd.get()),
61 _ => None,
62 }
63}
64
65pub fn prepare_toast_window(handle: NativeHandle) {
66 unsafe {
67 // GPUI creates popups with style 0, and Windows adds a caption frame to that on its own.
68 let frame = (WS_CAPTION | WS_THICKFRAME).0 as isize;
69 let style = GetWindowLongPtrW(hwnd(handle), GWL_STYLE);
70 SetWindowLongPtrW(
71 hwnd(handle),
72 GWL_STYLE,
73 (style & !frame) | WS_POPUP.0 as isize,
74 );
75 let _ = SetWindowPos(
76 hwnd(handle),
77 None,
78 0,
79 0,
80 0,
81 0,
82 SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE,
83 );
84 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
85 SetWindowLongPtrW(
86 hwnd(handle),
87 GWL_EXSTYLE,
88 style | WS_EX_NOACTIVATE.0 as isize,
89 );
90 let no_border = DWMWA_COLOR_NONE;
91 let _ = DwmSetWindowAttribute(
92 hwnd(handle),
93 DWMWA_BORDER_COLOR,
94 &no_border as *const _ as *const c_void,
95 size_of::<u32>() as u32,
96 );
97 let preference = DWMWCP_DONOTROUND;
98 let _ = DwmSetWindowAttribute(
99 hwnd(handle),
100 DWMWA_WINDOW_CORNER_PREFERENCE,
101 &preference as *const _ as *const c_void,
102 size_of_val(&preference) as u32,
103 );
104 }
105}
106
107pub fn set_activatable(handle: NativeHandle, activatable: bool) {
108 unsafe {
109 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
110 let flag = WS_EX_NOACTIVATE.0 as isize;
111 let updated = if activatable {
112 style & !flag
113 } else {
114 style | flag
115 };
116 SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, updated);
117 if activatable {
118 let _ = SetForegroundWindow(hwnd(handle));
119 }
120 }
121}
122
123pub fn work_area(handle: NativeHandle) -> Option<WorkArea> {
124 unsafe {
125 let monitor = MonitorFromWindow(hwnd(handle), MONITOR_DEFAULTTONEAREST);
126 let mut info = MONITORINFO {
127 cbSize: size_of::<MONITORINFO>() as u32,
128 ..Default::default()
129 };
130 if !GetMonitorInfoW(monitor, &mut info).as_bool() {
131 return None;
132 }
133 let RECT {
134 left,
135 top,
136 right,
137 bottom,
138 } = info.rcWork;
139 let dpi = GetDpiForWindow(hwnd(handle));
140 Some(WorkArea {
141 left,
142 top,
143 right,
144 bottom,
145 scale: if dpi == 0 { 1. } else { dpi as f32 / BASE_DPI },
146 })
147 }
148}
149
150pub fn work_area_at(x: i32, y: i32) -> Option<WorkArea> {
151 unsafe {
152 let monitor = MonitorFromPoint(POINT { x, y }, MONITOR_DEFAULTTONEAREST);
153 let mut info = MONITORINFO {
154 cbSize: size_of::<MONITORINFO>() as u32,
155 ..Default::default()
156 };
157 if !GetMonitorInfoW(monitor, &mut info).as_bool() {
158 return None;
159 }
160 let (mut dpi_x, mut dpi_y) = (0, 0);
161 let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) {
162 Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,
163 _ => 1.,
164 };
165 let RECT {
166 left,
167 top,
168 right,
169 bottom,
170 } = info.rcWork;
171 Some(WorkArea {
172 left,
173 top,
174 right,
175 bottom,
176 scale,
177 })
178 }
179}
180
181pub fn place(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) {
182 unsafe {
183 let _ = SetWindowPos(
184 hwnd(handle),
185 Some(HWND_TOPMOST),
186 x,
187 y,
188 width,
189 height,
190 SWP_NOACTIVATE | SWP_NOOWNERZORDER,
191 );
192 }
193}
194
195fn is_topmost(window: HWND) -> bool {
196 unsafe { GetWindowLongPtrW(window, GWL_EXSTYLE) & WS_EX_TOPMOST.0 as isize != 0 }
197}
198
199fn band_after(shared_topmost: bool, previous: Option<HWND>) -> HWND {
200 match previous {
201 Some(previous) if shared_topmost || !is_topmost(previous) => previous,
202 _ if shared_topmost => HWND_TOPMOST,
203 _ => HWND_NOTOPMOST,
204 }
205}
206
207fn windows_above(shared: HWND, group: &[NativeHandle]) -> Vec<NativeHandle> {
208 let mut above = Vec::new();
209 let mut current = shared;
210 while let Ok(previous) = unsafe { GetWindow(current, GW_HWNDPREV) } {
211 above.push(previous.0 as NativeHandle);
212 if !group.contains(&(previous.0 as NativeHandle)) {
213 break;
214 }
215 current = previous;
216 }
217 above
218}
219
220pub fn place_rect(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) {
221 unsafe {
222 let _ = SetWindowPos(
223 hwnd(handle),
224 None,
225 x,
226 y,
227 width,
228 height,
229 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER,
230 );
231 }
232}
233
234pub fn stack_group_above(shared: NativeHandle, group: &[NativeHandle]) {
235 let shared = hwnd(shared);
236 let above = windows_above(shared, group);
237 let StackPlan::Rebuild { after } = stack_plan(&above, group) else {
238 return;
239 };
240 let mut insert_after = band_after(is_topmost(shared), after.map(hwnd));
241 for handle in group {
242 unsafe {
243 let _ = SetWindowPos(
244 hwnd(*handle),
245 Some(insert_after),
246 0,
247 0,
248 0,
249 0,
250 SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_NOSIZE,
251 );
252 }
253 insert_after = hwnd(*handle);
254 }
255}
256
257pub fn show_window_inactive(handle: NativeHandle) {
258 unsafe {
259 let _ = ShowWindow(hwnd(handle), SW_SHOWNOACTIVATE);
260 }
261}
262
263pub fn exclude_from_capture(handle: NativeHandle) {
264 unsafe {
265 let _ = SetWindowDisplayAffinity(hwnd(handle), WDA_EXCLUDEFROMCAPTURE);
266 }
267}
268
269pub fn make_window_click_through(window: &Window) {
270 if let Some(handle) = native_handle(window) {
271 make_click_through(handle);
272 }
273}
274
275fn make_click_through(handle: NativeHandle) {
276 unsafe {
277 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
278 let added = (WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE).0 as isize;
279 SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, style | added);
280 // A layered window stays invisible until its alpha is set.
281 let _ = SetLayeredWindowAttributes(hwnd(handle), COLORREF(0), u8::MAX, LWA_ALPHA);
282 }
283}
284
285pub fn window_minimized(handle: NativeHandle) -> bool {
286 unsafe { IsIconic(hwnd(handle)).as_bool() }
287}
288
289fn screen_rect(rect: RECT) -> ScreenRect {
290 ScreenRect {
291 left: rect.left,
292 top: rect.top,
293 right: rect.right,
294 bottom: rect.bottom,
295 }
296}
297
298pub fn window_rect(handle: NativeHandle) -> Option<ScreenRect> {
299 let mut rect = RECT::default();
300 unsafe { GetWindowRect(hwnd(handle), &mut rect).ok()? };
301 Some(screen_rect(rect))
302}
303
304fn visible_frame(window: HWND) -> Option<ScreenRect> {
305 let mut rect = RECT::default();
306 unsafe {
307 if IsIconic(window).as_bool() || !IsWindowVisible(window).as_bool() {
308 return None;
309 }
310 let mut cloaked = 0u32;
311 let queried = DwmGetWindowAttribute(
312 window,
313 DWMWA_CLOAKED,
314 &mut cloaked as *mut _ as *mut c_void,
315 size_of::<u32>() as u32,
316 );
317 if queried.is_ok() && cloaked != 0 {
318 return None;
319 }
320 // Excludes the invisible resize margin that GetWindowRect includes.
321 let framed = DwmGetWindowAttribute(
322 window,
323 DWMWA_EXTENDED_FRAME_BOUNDS,
324 &mut rect as *mut _ as *mut c_void,
325 size_of::<RECT>() as u32,
326 );
327 if framed.is_err() {
328 GetWindowRect(window, &mut rect).ok()?;
329 }
330 }
331 Some(screen_rect(rect))
332}
333
334fn screen_frame(index: u32) -> Option<ScreenRect> {
335 unsafe {
336 let mut device = DISPLAY_DEVICEW {
337 cb: size_of::<DISPLAY_DEVICEW>() as u32,
338 ..Default::default()
339 };
340 if !EnumDisplayDevicesW(PCWSTR::null(), index, &mut device, 0).as_bool()
341 || device.StateFlags & DISPLAY_DEVICE_ACTIVE == Default::default()
342 {
343 return None;
344 }
345 let mut mode = DEVMODEW {
346 dmSize: size_of::<DEVMODEW>() as u16,
347 ..Default::default()
348 };
349 if !EnumDisplaySettingsW(
350 PCWSTR(device.DeviceName.as_ptr()),
351 ENUM_CURRENT_SETTINGS,
352 &mut mode,
353 )
354 .as_bool()
355 {
356 return None;
357 }
358 let position = mode.Anonymous1.Anonymous2.dmPosition;
359 Some(ScreenRect {
360 left: position.x,
361 top: position.y,
362 right: position.x + mode.dmPelsWidth as i32,
363 bottom: position.y + mode.dmPelsHeight as i32,
364 })
365 }
366}
367
368fn geometry_around(target: ScreenRect) -> Option<ShareGeometry> {
369 unsafe {
370 let rect = RECT {
371 left: target.left,
372 top: target.top,
373 right: target.right,
374 bottom: target.bottom,
375 };
376 let monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);
377 let mut info = MONITORINFO {
378 cbSize: size_of::<MONITORINFO>() as u32,
379 ..Default::default()
380 };
381 if !GetMonitorInfoW(monitor, &mut info).as_bool() {
382 return None;
383 }
384 let (mut dpi_x, mut dpi_y) = (0, 0);
385 let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) {
386 Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,
387 _ => 1.,
388 };
389 let RECT {
390 left,
391 top,
392 right,
393 bottom,
394 } = info.rcWork;
395 Some(ShareGeometry {
396 target,
397 work: WorkArea {
398 left,
399 top,
400 right,
401 bottom,
402 scale,
403 },
404 })
405 }
406}
407
408pub fn share_geometry(kind: ShareKind, id: u64) -> Option<ShareGeometry> {
409 let target = match kind {
410 ShareKind::Screen => screen_frame(u32::try_from(id).ok()?)?,
411 ShareKind::Window => visible_frame(hwnd(id as NativeHandle))?,
412 };
413 geometry_around(target)
414}
415
416pub fn system_quiet() -> bool {
417 let state = unsafe { SHQueryUserNotificationState() };
418 matches!(
419 state,
420 Ok(QUNS_BUSY | QUNS_RUNNING_D3D_FULL_SCREEN | QUNS_PRESENTATION_MODE | QUNS_QUIET_TIME)
421 )
422}
423
424pub fn restore_and_raise(handle: NativeHandle) {
425 unsafe {
426 let command = if IsIconic(hwnd(handle)).as_bool() {
427 SW_RESTORE
428 } else {
429 SW_SHOW
430 };
431 let _ = ShowWindow(hwnd(handle), command);
432 let _ = SetForegroundWindow(hwnd(handle));
433 }
434}
435
436pub fn hide_window(handle: NativeHandle) {
437 unsafe {
438 let _ = ShowWindow(hwnd(handle), SW_HIDE);
439 }
440}
441
442pub fn flash(handle: NativeHandle) {
443 let info = FLASHWINFO {
444 cbSize: size_of::<FLASHWINFO>() as u32,
445 hwnd: hwnd(handle),
446 dwFlags: FLASHW_TRAY | FLASHW_TIMERNOFG,
447 uCount: 0,
448 dwTimeout: 0,
449 };
450 unsafe {
451 let _ = FlashWindowEx(&info);
452 }
453}
454
455pub fn stop_flash(handle: NativeHandle) {
456 let info = FLASHWINFO {
457 cbSize: size_of::<FLASHWINFO>() as u32,
458 hwnd: hwnd(handle),
459 dwFlags: FLASHW_STOP,
460 uCount: 0,
461 dwTimeout: 0,
462 };
463 unsafe {
464 let _ = FlashWindowEx(&info);
465 }
466}
467
468pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) {
469 unsafe {
470 let Ok(taskbar) =
471 CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)
472 else {
473 return;
474 };
475 if taskbar.HrInit().is_err() {
476 return;
477 }
478 match badge {
479 None => {
480 let _ = taskbar.SetOverlayIcon(hwnd(handle), HICON::default(), w!(""));
481 }
482 Some(badge) => {
483 let Some(icon) = icon_from_badge(badge) else {
484 return;
485 };
486 let _ = taskbar.SetOverlayIcon(hwnd(handle), icon, w!("Unread chats"));
487 let _ = DestroyIcon(icon);
488 }
489 }
490 }
491}
492
493unsafe fn icon_from_badge(badge: &Badge) -> Option<HICON> {
494 unsafe { icon_from_bgra(&render_badge(badge), BADGE_SIZE as u32) }
495}
496
497unsafe fn icon_from_bgra(pixels: &[u8], size: u32) -> Option<HICON> {
498 unsafe {
499 let color = CreateBitmap(
500 size as i32,
501 size as i32,
502 1,
503 32,
504 Some(pixels.as_ptr() as *const c_void),
505 );
506 let mask = CreateBitmap(size as i32, size as i32, 1, 1, None);
507 let info = ICONINFO {
508 fIcon: BOOL(1),
509 xHotspot: 0,
510 yHotspot: 0,
511 hbmMask: mask,
512 hbmColor: color,
513 };
514 let icon = CreateIconIndirect(&info).ok();
515 let _ = DeleteObject(HGDIOBJ(color.0));
516 let _ = DeleteObject(HGDIOBJ(mask.0));
517 icon
518 }
519}
520
521pub fn set_window_icon(window: &Window, png: &[u8]) {
522 let Some(handle) = native_handle(window) else {
523 return;
524 };
525 let Ok(decoded) = image::load_from_memory(png) else {
526 return;
527 };
528 let dpi = unsafe { GetDpiForWindow(hwnd(handle)) };
529 let scale = if dpi == 0 { 1. } else { dpi as f32 / BASE_DPI };
530 for (kind, base_size) in [
531 (ICON_BIG, WINDOW_ICON_SIZE),
532 (ICON_SMALL, WINDOW_SMALL_ICON_SIZE),
533 ] {
534 let size = (base_size * scale).round() as u32;
535 let mut pixels = decoded
536 .resize_exact(size, size, image::imageops::FilterType::Lanczos3)
537 .to_rgba8()
538 .into_raw();
539 for pixel in pixels.chunks_exact_mut(4) {
540 pixel.swap(0, 2);
541 }
542 unsafe {
543 let Some(icon) = icon_from_bgra(&pixels, size) else {
544 continue;
545 };
546 let previous = SendMessageW(
547 hwnd(handle),
548 WM_SETICON,
549 Some(WPARAM(kind as usize)),
550 Some(LPARAM(icon.0 as isize)),
551 );
552 if previous.0 != 0 {
553 let _ = DestroyIcon(HICON(previous.0 as *mut c_void));
554 }
555 }
556 }
557}
558
559pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {
560 std::thread::spawn(move || {
561 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
562 return;
563 };
564 sink.log_on_drop(false);
565 loop {
566 let Ok(player) = rodio::play(sink.mixer(), Cursor::new(bytes.clone())) else {
567 return;
568 };
569 while !player.empty() {
570 if stop.load(Ordering::SeqCst) {
571 player.stop();
572 return;
573 }
574 std::thread::sleep(RING_POLL);
575 }
576 if !looped || stop.load(Ordering::SeqCst) {
577 return;
578 }
579 }
580 });
581}
582
583pub fn play_mp3(bytes: Vec<u8>) {
584 std::thread::spawn(move || {
585 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
586 return;
587 };
588 sink.log_on_drop(false);
589 if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(bytes)) {
590 player.sleep_until_end();
591 }
592 });
593}
594
595pub fn play_sound() {
596 std::thread::spawn(|| {
597 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
598 return;
599 };
600 sink.log_on_drop(false);
601 if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(SOUND_BYTES)) {
602 player.sleep_until_end();
603 }
604 });
605}
606
607const ID_OPEN: &str = "open";
608const ID_SOUND: &str = "sound";
609const ID_DO_NOT_DISTURB: &str = "do_not_disturb";
610const ID_SETTINGS: &str = "settings";
611const ID_QUIT: &str = "quit";
612
613pub struct Tray {
614 icon: TrayIcon,
615 sound: CheckMenuItem,
616 do_not_disturb: CheckMenuItem,
617 plain: Icon,
618 with_dot: Icon,
619}
620
621impl Tray {
622 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
623 let (plain, with_dot) = tray_icons(icon_png)?;
624 let open = MenuItem::with_id(ID_OPEN, "Open", true, None);
625 let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None);
626 let dnd = CheckMenuItem::with_id(
627 ID_DO_NOT_DISTURB,
628 "Do not disturb",
629 true,
630 do_not_disturb,
631 None,
632 );
633 let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None);
634 let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None);
635 let menu = Menu::new();
636 menu.append_items(&[
637 &open,
638 &PredefinedMenuItem::separator(),
639 &sound,
640 &dnd,
641 &settings,
642 &PredefinedMenuItem::separator(),
643 &quit,
644 ])
645 .ok()?;
646 let icon = TrayIconBuilder::new()
647 .with_icon(plain.clone())
648 .with_tooltip(crate::APP_NAME)
649 .with_menu(Box::new(menu))
650 .with_menu_on_left_click(false)
651 .build()
652 .ok()?;
653 Some(Tray {
654 icon,
655 sound,
656 do_not_disturb: dnd,
657 plain,
658 with_dot,
659 })
660 }
661
662 pub fn poll(&self) -> Vec<TrayCommand> {
663 let mut commands = Vec::new();
664 while let Ok(event) = MenuEvent::receiver().try_recv() {
665 let command = match event.id.0.as_str() {
666 ID_OPEN => TrayCommand::Open,
667 ID_SOUND => TrayCommand::ToggleSound,
668 ID_DO_NOT_DISTURB => TrayCommand::ToggleDoNotDisturb,
669 ID_SETTINGS => TrayCommand::Settings,
670 ID_QUIT => TrayCommand::Quit,
671 _ => continue,
672 };
673 commands.push(command);
674 }
675 while let Ok(event) = TrayIconEvent::receiver().try_recv() {
676 if let TrayIconEvent::Click {
677 button: MouseButton::Left,
678 button_state: MouseButtonState::Up,
679 ..
680 } = event
681 {
682 commands.push(TrayCommand::Toggle);
683 }
684 }
685 commands
686 }
687
688 pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) {
689 let Some((plain, with_dot)) = tray_icons(icon_png) else {
690 return;
691 };
692 self.plain = plain;
693 self.with_dot = with_dot;
694 let icon = if mention { &self.with_dot } else { &self.plain };
695 let _ = self.icon.set_icon(Some(icon.clone()));
696 }
697
698 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
699 self.sound.set_checked(!sound_on);
700 self.do_not_disturb.set_checked(do_not_disturb);
701 let icon = if mention { &self.with_dot } else { &self.plain };
702 let _ = self.icon.set_icon(Some(icon.clone()));
703 }
704}
705
706fn tray_icons(icon_png: &[u8]) -> Option<(Icon, Icon)> {
707 let decoded = image::load_from_memory(icon_png).ok()?;
708 let resized = decoded
709 .resize_exact(
710 TRAY_ICON_SIZE,
711 TRAY_ICON_SIZE,
712 image::imageops::FilterType::Lanczos3,
713 )
714 .to_rgba8();
715 let plain = resized.clone().into_raw();
716 let mut dotted = resized;
717 let size = TRAY_ICON_SIZE as f32;
718 let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);
719 for (column, row, pixel) in dotted.enumerate_pixels_mut() {
720 let distance =
721 ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();
722 if distance <= TRAY_DOT_RADIUS {
723 *pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);
724 }
725 }
726 Some((
727 Icon::from_rgba(plain, TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
728 Icon::from_rgba(dotted.into_raw(), TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
729 ))
730}
731
732pub fn animations_enabled() -> bool {
733 let mut enabled = BOOL(1);
734 let read = unsafe {
735 SystemParametersInfoW(
736 SPI_GETCLIENTAREAANIMATION,
737 0,
738 Some(&mut enabled as *mut BOOL as *mut c_void),
739 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
740 )
741 };
742 read.is_err() || enabled.as_bool()
743}