BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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