BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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