BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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