BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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