BlueGit

ict rusty-teams

Files

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

windows_impl.rs

46a97707 History
windows_impl.rs 24.5 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, WDA_NONE, 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 include_in_capture(handle: NativeHandle) {
278 unsafe {
279 let _ = SetWindowDisplayAffinity(hwnd(handle), WDA_NONE);
280 }
281}
282
283pub fn make_window_click_through(window: &Window) {
284 if let Some(handle) = native_handle(window) {
285 make_click_through(handle);
286 }
287}
288
289fn make_click_through(handle: NativeHandle) {
290 unsafe {
291 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
292 let added = (WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE).0 as isize;
293 SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, style | added);
294 // A layered window stays invisible until its alpha is set.
295 let _ = SetLayeredWindowAttributes(hwnd(handle), COLORREF(0), u8::MAX, LWA_ALPHA);
296 }
297}
298
299pub fn window_minimized(handle: NativeHandle) -> bool {
300 unsafe { IsIconic(hwnd(handle)).as_bool() }
301}
302
303fn screen_rect(rect: RECT) -> ScreenRect {
304 ScreenRect {
305 left: rect.left,
306 top: rect.top,
307 right: rect.right,
308 bottom: rect.bottom,
309 }
310}
311
312pub fn window_rect(handle: NativeHandle) -> Option<ScreenRect> {
313 let mut rect = RECT::default();
314 unsafe { GetWindowRect(hwnd(handle), &mut rect).ok()? };
315 Some(screen_rect(rect))
316}
317
318fn visible_frame(window: HWND) -> Option<ScreenRect> {
319 let mut rect = RECT::default();
320 unsafe {
321 if IsIconic(window).as_bool() || !IsWindowVisible(window).as_bool() {
322 return None;
323 }
324 let mut cloaked = 0u32;
325 let queried = DwmGetWindowAttribute(
326 window,
327 DWMWA_CLOAKED,
328 &mut cloaked as *mut _ as *mut c_void,
329 size_of::<u32>() as u32,
330 );
331 if queried.is_ok() && cloaked != 0 {
332 return None;
333 }
334 // Excludes the invisible resize margin that GetWindowRect includes.
335 let framed = DwmGetWindowAttribute(
336 window,
337 DWMWA_EXTENDED_FRAME_BOUNDS,
338 &mut rect as *mut _ as *mut c_void,
339 size_of::<RECT>() as u32,
340 );
341 if framed.is_err() {
342 GetWindowRect(window, &mut rect).ok()?;
343 }
344 }
345 Some(screen_rect(rect))
346}
347
348fn screen_frame(index: u32) -> Option<ScreenRect> {
349 unsafe {
350 let mut device = DISPLAY_DEVICEW {
351 cb: size_of::<DISPLAY_DEVICEW>() as u32,
352 ..Default::default()
353 };
354 if !EnumDisplayDevicesW(PCWSTR::null(), index, &mut device, 0).as_bool()
355 || device.StateFlags & DISPLAY_DEVICE_ACTIVE == Default::default()
356 {
357 return None;
358 }
359 let mut mode = DEVMODEW {
360 dmSize: size_of::<DEVMODEW>() as u16,
361 ..Default::default()
362 };
363 if !EnumDisplaySettingsW(
364 PCWSTR(device.DeviceName.as_ptr()),
365 ENUM_CURRENT_SETTINGS,
366 &mut mode,
367 )
368 .as_bool()
369 {
370 return None;
371 }
372 let position = mode.Anonymous1.Anonymous2.dmPosition;
373 Some(ScreenRect {
374 left: position.x,
375 top: position.y,
376 right: position.x + mode.dmPelsWidth as i32,
377 bottom: position.y + mode.dmPelsHeight as i32,
378 })
379 }
380}
381
382fn geometry_around(target: ScreenRect) -> Option<ShareGeometry> {
383 unsafe {
384 let rect = RECT {
385 left: target.left,
386 top: target.top,
387 right: target.right,
388 bottom: target.bottom,
389 };
390 let monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);
391 let mut info = MONITORINFO {
392 cbSize: size_of::<MONITORINFO>() as u32,
393 ..Default::default()
394 };
395 if !GetMonitorInfoW(monitor, &mut info).as_bool() {
396 return None;
397 }
398 let (mut dpi_x, mut dpi_y) = (0, 0);
399 let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) {
400 Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,
401 _ => 1.,
402 };
403 let RECT {
404 left,
405 top,
406 right,
407 bottom,
408 } = info.rcWork;
409 Some(ShareGeometry {
410 target,
411 work: WorkArea {
412 left,
413 top,
414 right,
415 bottom,
416 scale,
417 },
418 })
419 }
420}
421
422pub fn share_geometry(kind: ShareKind, id: u64) -> Option<ShareGeometry> {
423 let target = match kind {
424 ShareKind::Screen => screen_frame(u32::try_from(id).ok()?)?,
425 ShareKind::Window => visible_frame(hwnd(id as NativeHandle))?,
426 };
427 geometry_around(target)
428}
429
430pub fn system_quiet() -> bool {
431 let state = unsafe { SHQueryUserNotificationState() };
432 matches!(
433 state,
434 Ok(QUNS_BUSY | QUNS_RUNNING_D3D_FULL_SCREEN | QUNS_PRESENTATION_MODE | QUNS_QUIET_TIME)
435 )
436}
437
438pub fn restore_and_raise(handle: NativeHandle) {
439 unsafe {
440 let command = if IsIconic(hwnd(handle)).as_bool() {
441 SW_RESTORE
442 } else {
443 SW_SHOW
444 };
445 let _ = ShowWindow(hwnd(handle), command);
446 let _ = SetForegroundWindow(hwnd(handle));
447 }
448}
449
450pub fn hide_window(handle: NativeHandle) {
451 unsafe {
452 let _ = ShowWindow(hwnd(handle), SW_HIDE);
453 }
454}
455
456pub fn flash(handle: NativeHandle) {
457 let info = FLASHWINFO {
458 cbSize: size_of::<FLASHWINFO>() as u32,
459 hwnd: hwnd(handle),
460 dwFlags: FLASHW_TRAY | FLASHW_TIMERNOFG,
461 uCount: 0,
462 dwTimeout: 0,
463 };
464 unsafe {
465 let _ = FlashWindowEx(&info);
466 }
467}
468
469pub fn stop_flash(handle: NativeHandle) {
470 let info = FLASHWINFO {
471 cbSize: size_of::<FLASHWINFO>() as u32,
472 hwnd: hwnd(handle),
473 dwFlags: FLASHW_STOP,
474 uCount: 0,
475 dwTimeout: 0,
476 };
477 unsafe {
478 let _ = FlashWindowEx(&info);
479 }
480}
481
482pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) {
483 unsafe {
484 let Ok(taskbar) =
485 CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)
486 else {
487 return;
488 };
489 if taskbar.HrInit().is_err() {
490 return;
491 }
492 match badge {
493 None => {
494 let _ = taskbar.SetOverlayIcon(hwnd(handle), HICON::default(), w!(""));
495 }
496 Some(badge) => {
497 let Some(icon) = icon_from_badge(badge, handle) else {
498 return;
499 };
500 let _ = taskbar.SetOverlayIcon(hwnd(handle), icon, w!("Unread chats"));
501 let _ = DestroyIcon(icon);
502 }
503 }
504 }
505}
506
507unsafe fn icon_from_badge(badge: &Badge, handle: NativeHandle) -> Option<HICON> {
508 unsafe {
509 let dpi = GetDpiForWindow(hwnd(handle));
510 let size = GetSystemMetricsForDpi(SM_CXSMICON, dpi).max(16) as u32;
511 icon_from_bgra(&render_badge(badge, size), size)
512 }
513}
514
515unsafe fn icon_from_bgra(pixels: &[u8], size: u32) -> Option<HICON> {
516 unsafe {
517 let color = CreateBitmap(
518 size as i32,
519 size as i32,
520 1,
521 32,
522 Some(pixels.as_ptr() as *const c_void),
523 );
524 let mask = CreateBitmap(size as i32, size as i32, 1, 1, None);
525 let info = ICONINFO {
526 fIcon: BOOL(1),
527 xHotspot: 0,
528 yHotspot: 0,
529 hbmMask: mask,
530 hbmColor: color,
531 };
532 let icon = CreateIconIndirect(&info).ok();
533 let _ = DeleteObject(HGDIOBJ(color.0));
534 let _ = DeleteObject(HGDIOBJ(mask.0));
535 icon
536 }
537}
538
539pub fn set_window_icon(window: &Window, png: &[u8]) {
540 let Some(handle) = native_handle(window) else {
541 return;
542 };
543 let Ok(decoded) = image::load_from_memory(png) else {
544 return;
545 };
546 let dpi = unsafe { GetDpiForWindow(hwnd(handle)) };
547 let scale = if dpi == 0 { 1. } else { dpi as f32 / BASE_DPI };
548 for (kind, base_size) in [
549 (ICON_BIG, WINDOW_ICON_SIZE),
550 (ICON_SMALL, WINDOW_SMALL_ICON_SIZE),
551 ] {
552 let size = (base_size * scale).round() as u32;
553 let mut pixels = decoded
554 .resize_exact(size, size, image::imageops::FilterType::Lanczos3)
555 .to_rgba8()
556 .into_raw();
557 for pixel in pixels.chunks_exact_mut(4) {
558 pixel.swap(0, 2);
559 }
560 unsafe {
561 let Some(icon) = icon_from_bgra(&pixels, size) else {
562 continue;
563 };
564 let previous = SendMessageW(
565 hwnd(handle),
566 WM_SETICON,
567 Some(WPARAM(kind as usize)),
568 Some(LPARAM(icon.0 as isize)),
569 );
570 if previous.0 != 0 {
571 let _ = DestroyIcon(HICON(previous.0 as *mut c_void));
572 }
573 }
574 }
575}
576
577static SOUND_OUTPUT: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
578
579pub fn set_sound_output(device_key: Option<String>) {
580 *SOUND_OUTPUT.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = device_key;
581}
582
583fn open_sound_sink() -> Option<rodio::MixerDeviceSink> {
584 use rodio::cpal::traits::{DeviceTrait, HostTrait};
585 let chosen = SOUND_OUTPUT
586 .lock()
587 .unwrap_or_else(|poisoned| poisoned.into_inner())
588 .clone();
589 let device = chosen.and_then(|device_key| {
590 rodio::cpal::default_host()
591 .output_devices()
592 .ok()?
593 .find(|device| {
594 device.id().is_ok_and(|id| id.1 == device_key)
595 || device
596 .description()
597 .is_ok_and(|description| description.name() == device_key)
598 })
599 });
600 device
601 .and_then(|device| {
602 rodio::DeviceSinkBuilder::from_device(device)
603 .and_then(|builder| builder.open_stream())
604 .ok()
605 })
606 .or_else(|| rodio::DeviceSinkBuilder::open_default_sink().ok())
607}
608
609pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {
610 std::thread::spawn(move || {
611 let Some(mut sink) = open_sound_sink() else {
612 return;
613 };
614 sink.log_on_drop(false);
615 loop {
616 let Ok(player) = rodio::play(sink.mixer(), Cursor::new(bytes.clone())) else {
617 return;
618 };
619 while !player.empty() {
620 if stop.load(Ordering::SeqCst) {
621 player.stop();
622 return;
623 }
624 std::thread::sleep(RING_POLL);
625 }
626 if !looped || stop.load(Ordering::SeqCst) {
627 return;
628 }
629 }
630 });
631}
632
633pub fn play_mp3(bytes: Vec<u8>) {
634 std::thread::spawn(move || {
635 let Some(mut sink) = open_sound_sink() else {
636 return;
637 };
638 sink.log_on_drop(false);
639 if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(bytes)) {
640 player.sleep_until_end();
641 }
642 });
643}
644
645pub fn play_sound() {
646 std::thread::spawn(|| {
647 let Some(mut sink) = open_sound_sink() else {
648 return;
649 };
650 sink.log_on_drop(false);
651 if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(SOUND_BYTES)) {
652 player.sleep_until_end();
653 }
654 });
655}
656
657const ID_OPEN: &str = "open";
658const ID_SOUND: &str = "sound";
659const ID_DO_NOT_DISTURB: &str = "do_not_disturb";
660const ID_SETTINGS: &str = "settings";
661const ID_QUIT: &str = "quit";
662
663pub struct Tray {
664 icon: TrayIcon,
665 sound: CheckMenuItem,
666 do_not_disturb: CheckMenuItem,
667 plain: Icon,
668 with_dot: Icon,
669}
670
671impl Tray {
672 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
673 let (plain, with_dot) = tray_icons(icon_png)?;
674 let open = MenuItem::with_id(ID_OPEN, "Open", true, None);
675 let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None);
676 let dnd = CheckMenuItem::with_id(
677 ID_DO_NOT_DISTURB,
678 "Do not disturb",
679 true,
680 do_not_disturb,
681 None,
682 );
683 let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None);
684 let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None);
685 let menu = Menu::new();
686 menu.append_items(&[
687 &open,
688 &PredefinedMenuItem::separator(),
689 &sound,
690 &dnd,
691 &settings,
692 &PredefinedMenuItem::separator(),
693 &quit,
694 ])
695 .ok()?;
696 let icon = TrayIconBuilder::new()
697 .with_icon(plain.clone())
698 .with_tooltip(crate::APP_NAME)
699 .with_menu(Box::new(menu))
700 .with_menu_on_left_click(false)
701 .build()
702 .ok()?;
703 Some(Tray {
704 icon,
705 sound,
706 do_not_disturb: dnd,
707 plain,
708 with_dot,
709 })
710 }
711
712 pub fn poll(&self) -> Vec<TrayCommand> {
713 let mut commands = Vec::new();
714 while let Ok(event) = MenuEvent::receiver().try_recv() {
715 let command = match event.id.0.as_str() {
716 ID_OPEN => TrayCommand::Open,
717 ID_SOUND => TrayCommand::ToggleSound,
718 ID_DO_NOT_DISTURB => TrayCommand::ToggleDoNotDisturb,
719 ID_SETTINGS => TrayCommand::Settings,
720 ID_QUIT => TrayCommand::Quit,
721 _ => continue,
722 };
723 commands.push(command);
724 }
725 while let Ok(event) = TrayIconEvent::receiver().try_recv() {
726 if let TrayIconEvent::Click {
727 button: MouseButton::Left,
728 button_state: MouseButtonState::Up,
729 ..
730 } = event
731 {
732 commands.push(TrayCommand::Toggle);
733 }
734 }
735 commands
736 }
737
738 pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) {
739 let Some((plain, with_dot)) = tray_icons(icon_png) else {
740 return;
741 };
742 self.plain = plain;
743 self.with_dot = with_dot;
744 let icon = if mention { &self.with_dot } else { &self.plain };
745 let _ = self.icon.set_icon(Some(icon.clone()));
746 }
747
748 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
749 self.sound.set_checked(!sound_on);
750 self.do_not_disturb.set_checked(do_not_disturb);
751 let icon = if mention { &self.with_dot } else { &self.plain };
752 let _ = self.icon.set_icon(Some(icon.clone()));
753 }
754}
755
756fn tray_icons(icon_png: &[u8]) -> Option<(Icon, Icon)> {
757 let decoded = image::load_from_memory(icon_png).ok()?;
758 let resized = decoded
759 .resize_exact(
760 TRAY_ICON_SIZE,
761 TRAY_ICON_SIZE,
762 image::imageops::FilterType::Lanczos3,
763 )
764 .to_rgba8();
765 let plain = resized.clone().into_raw();
766 let mut dotted = resized;
767 let size = TRAY_ICON_SIZE as f32;
768 let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);
769 for (column, row, pixel) in dotted.enumerate_pixels_mut() {
770 let distance =
771 ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();
772 if distance <= TRAY_DOT_RADIUS {
773 *pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);
774 }
775 }
776 Some((
777 Icon::from_rgba(plain, TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
778 Icon::from_rgba(dotted.into_raw(), TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
779 ))
780}
781
782pub fn animations_enabled() -> bool {
783 let mut enabled = BOOL(1);
784 let read = unsafe {
785 SystemParametersInfoW(
786 SPI_GETCLIENTAREAANIMATION,
787 0,
788 Some(&mut enabled as *mut BOOL as *mut c_void),
789 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
790 )
791 };
792 read.is_err() || enabled.as_bool()
793}