BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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