BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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