BlueGit

ict rusty-teams

Files

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

windows_impl.rs

windows_impl.rs 19.5 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_click_through(handle: NativeHandle) {
201 unsafe {
202 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
203 let added = (WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE).0 as isize;
204 SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, style | added);
205 // A layered window stays invisible until its alpha is set.
206 let _ = SetLayeredWindowAttributes(hwnd(handle), COLORREF(0), u8::MAX, LWA_ALPHA);
207 }
208}
209
210pub fn window_minimized(handle: NativeHandle) -> bool {
211 unsafe { IsIconic(hwnd(handle)).as_bool() }
212}
213
214fn screen_rect(rect: RECT) -> ScreenRect {
215 ScreenRect {
216 left: rect.left,
217 top: rect.top,
218 right: rect.right,
219 bottom: rect.bottom,
220 }
221}
222
223pub fn window_rect(handle: NativeHandle) -> Option<ScreenRect> {
224 let mut rect = RECT::default();
225 unsafe { GetWindowRect(hwnd(handle), &mut rect).ok()? };
226 Some(screen_rect(rect))
227}
228
229fn visible_frame(window: HWND) -> Option<ScreenRect> {
230 let mut rect = RECT::default();
231 unsafe {
232 if IsIconic(window).as_bool() {
233 return None;
234 }
235 // Excludes the invisible resize margin that GetWindowRect includes.
236 let framed = DwmGetWindowAttribute(
237 window,
238 DWMWA_EXTENDED_FRAME_BOUNDS,
239 &mut rect as *mut _ as *mut c_void,
240 size_of::<RECT>() as u32,
241 );
242 if framed.is_err() {
243 GetWindowRect(window, &mut rect).ok()?;
244 }
245 }
246 Some(screen_rect(rect))
247}
248
249fn screen_frame(index: u32) -> Option<ScreenRect> {
250 unsafe {
251 let mut device = DISPLAY_DEVICEW {
252 cb: size_of::<DISPLAY_DEVICEW>() as u32,
253 ..Default::default()
254 };
255 if !EnumDisplayDevicesW(PCWSTR::null(), index, &mut device, 0).as_bool()
256 || device.StateFlags & DISPLAY_DEVICE_ACTIVE == Default::default()
257 {
258 return None;
259 }
260 let mut mode = DEVMODEW {
261 dmSize: size_of::<DEVMODEW>() as u16,
262 ..Default::default()
263 };
264 if !EnumDisplaySettingsW(
265 PCWSTR(device.DeviceName.as_ptr()),
266 ENUM_CURRENT_SETTINGS,
267 &mut mode,
268 )
269 .as_bool()
270 {
271 return None;
272 }
273 let position = mode.Anonymous1.Anonymous2.dmPosition;
274 Some(ScreenRect {
275 left: position.x,
276 top: position.y,
277 right: position.x + mode.dmPelsWidth as i32,
278 bottom: position.y + mode.dmPelsHeight as i32,
279 })
280 }
281}
282
283fn geometry_around(target: ScreenRect) -> Option<ShareGeometry> {
284 unsafe {
285 let rect = RECT {
286 left: target.left,
287 top: target.top,
288 right: target.right,
289 bottom: target.bottom,
290 };
291 let monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);
292 let mut info = MONITORINFO {
293 cbSize: size_of::<MONITORINFO>() as u32,
294 ..Default::default()
295 };
296 if !GetMonitorInfoW(monitor, &mut info).as_bool() {
297 return None;
298 }
299 let (mut dpi_x, mut dpi_y) = (0, 0);
300 let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) {
301 Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,
302 _ => 1.,
303 };
304 let RECT {
305 left,
306 top,
307 right,
308 bottom,
309 } = info.rcWork;
310 Some(ShareGeometry {
311 target,
312 work: WorkArea {
313 left,
314 top,
315 right,
316 bottom,
317 scale,
318 },
319 })
320 }
321}
322
323pub fn share_geometry(kind: ShareKind, id: u64) -> Option<ShareGeometry> {
324 let target = match kind {
325 ShareKind::Screen => screen_frame(u32::try_from(id).ok()?)?,
326 ShareKind::Window => visible_frame(hwnd(id as NativeHandle))?,
327 };
328 geometry_around(target)
329}
330
331pub fn system_quiet() -> bool {
332 let state = unsafe { SHQueryUserNotificationState() };
333 matches!(
334 state,
335 Ok(QUNS_BUSY | QUNS_RUNNING_D3D_FULL_SCREEN | QUNS_PRESENTATION_MODE | QUNS_QUIET_TIME)
336 )
337}
338
339pub fn restore_and_raise(handle: NativeHandle) {
340 unsafe {
341 let command = if IsIconic(hwnd(handle)).as_bool() {
342 SW_RESTORE
343 } else {
344 SW_SHOW
345 };
346 let _ = ShowWindow(hwnd(handle), command);
347 let _ = SetForegroundWindow(hwnd(handle));
348 }
349}
350
351pub fn hide_window(handle: NativeHandle) {
352 unsafe {
353 let _ = ShowWindow(hwnd(handle), SW_HIDE);
354 }
355}
356
357pub fn flash(handle: NativeHandle) {
358 let info = FLASHWINFO {
359 cbSize: size_of::<FLASHWINFO>() as u32,
360 hwnd: hwnd(handle),
361 dwFlags: FLASHW_TRAY | FLASHW_TIMERNOFG,
362 uCount: 0,
363 dwTimeout: 0,
364 };
365 unsafe {
366 let _ = FlashWindowEx(&info);
367 }
368}
369
370pub fn stop_flash(handle: NativeHandle) {
371 let info = FLASHWINFO {
372 cbSize: size_of::<FLASHWINFO>() as u32,
373 hwnd: hwnd(handle),
374 dwFlags: FLASHW_STOP,
375 uCount: 0,
376 dwTimeout: 0,
377 };
378 unsafe {
379 let _ = FlashWindowEx(&info);
380 }
381}
382
383pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) {
384 unsafe {
385 let Ok(taskbar) =
386 CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)
387 else {
388 return;
389 };
390 if taskbar.HrInit().is_err() {
391 return;
392 }
393 match badge {
394 None => {
395 let _ = taskbar.SetOverlayIcon(hwnd(handle), HICON::default(), w!(""));
396 }
397 Some(badge) => {
398 let Some(icon) = icon_from_badge(badge) else {
399 return;
400 };
401 let _ = taskbar.SetOverlayIcon(hwnd(handle), icon, w!("Unread chats"));
402 let _ = DestroyIcon(icon);
403 }
404 }
405 }
406}
407
408unsafe fn icon_from_badge(badge: &Badge) -> Option<HICON> {
409 let pixels = render_badge(badge);
410 unsafe {
411 let color = CreateBitmap(
412 BADGE_SIZE as i32,
413 BADGE_SIZE as i32,
414 1,
415 32,
416 Some(pixels.as_ptr() as *const c_void),
417 );
418 let mask = CreateBitmap(BADGE_SIZE as i32, BADGE_SIZE as i32, 1, 1, None);
419 let info = ICONINFO {
420 fIcon: BOOL(1),
421 xHotspot: 0,
422 yHotspot: 0,
423 hbmMask: mask,
424 hbmColor: color,
425 };
426 let icon = CreateIconIndirect(&info).ok();
427 let _ = DeleteObject(HGDIOBJ(color.0));
428 let _ = DeleteObject(HGDIOBJ(mask.0));
429 icon
430 }
431}
432
433pub struct RingTone {
434 stop: Arc<AtomicBool>,
435}
436
437impl Drop for RingTone {
438 fn drop(&mut self) {
439 self.stop.store(true, Ordering::SeqCst);
440 }
441}
442
443pub fn start_ring(ringtone: Ringtone) -> Option<RingTone> {
444 start_cycle(ringtone.cycle(SAMPLE_RATE))
445}
446
447pub fn start_ringback() -> Option<RingTone> {
448 start_cycle(ringback_cycle(SAMPLE_RATE))
449}
450
451pub fn play_preview(ringtone: Ringtone) {
452 let cycle = ringtone.cycle(SAMPLE_RATE);
453 std::thread::spawn(move || {
454 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
455 return;
456 };
457 sink.log_on_drop(false);
458 let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
459 return;
460 };
461 let player = rodio::Player::connect_new(sink.mixer());
462 player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle));
463 player.sleep_until_end();
464 });
465}
466
467fn start_cycle(cycle: Vec<f32>) -> Option<RingTone> {
468 let stop = Arc::new(AtomicBool::new(false));
469 let flag = stop.clone();
470 std::thread::spawn(move || {
471 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
472 return;
473 };
474 sink.log_on_drop(false);
475 let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
476 return;
477 };
478 while !flag.load(Ordering::SeqCst) {
479 let player = rodio::Player::connect_new(sink.mixer());
480 player.append(rodio::buffer::SamplesBuffer::new(
481 channels,
482 rate,
483 cycle.clone(),
484 ));
485 while !player.empty() {
486 if flag.load(Ordering::SeqCst) {
487 player.stop();
488 return;
489 }
490 std::thread::sleep(RING_POLL);
491 }
492 }
493 });
494 Some(RingTone { stop })
495}
496
497pub fn play_sound() {
498 std::thread::spawn(|| {
499 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
500 return;
501 };
502 sink.log_on_drop(false);
503 if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(SOUND_BYTES)) {
504 player.sleep_until_end();
505 }
506 });
507}
508
509const ID_OPEN: &str = "open";
510const ID_SOUND: &str = "sound";
511const ID_DO_NOT_DISTURB: &str = "do_not_disturb";
512const ID_SETTINGS: &str = "settings";
513const ID_QUIT: &str = "quit";
514
515pub struct Tray {
516 icon: TrayIcon,
517 sound: CheckMenuItem,
518 do_not_disturb: CheckMenuItem,
519 plain: Icon,
520 with_dot: Icon,
521}
522
523impl Tray {
524 pub fn new(sound_on: bool, do_not_disturb: bool) -> Option<Self> {
525 let (plain, with_dot) = tray_icons()?;
526 let open = MenuItem::with_id(ID_OPEN, "Open", true, None);
527 let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None);
528 let dnd = CheckMenuItem::with_id(
529 ID_DO_NOT_DISTURB,
530 "Do not disturb",
531 true,
532 do_not_disturb,
533 None,
534 );
535 let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None);
536 let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None);
537 let menu = Menu::new();
538 menu.append_items(&[
539 &open,
540 &PredefinedMenuItem::separator(),
541 &sound,
542 &dnd,
543 &settings,
544 &PredefinedMenuItem::separator(),
545 &quit,
546 ])
547 .ok()?;
548 let icon = TrayIconBuilder::new()
549 .with_icon(plain.clone())
550 .with_tooltip(crate::APP_NAME)
551 .with_menu(Box::new(menu))
552 .with_menu_on_left_click(false)
553 .build()
554 .ok()?;
555 Some(Tray {
556 icon,
557 sound,
558 do_not_disturb: dnd,
559 plain,
560 with_dot,
561 })
562 }
563
564 pub fn poll(&self) -> Vec<TrayCommand> {
565 let mut commands = Vec::new();
566 while let Ok(event) = MenuEvent::receiver().try_recv() {
567 let command = match event.id.0.as_str() {
568 ID_OPEN => TrayCommand::Open,
569 ID_SOUND => TrayCommand::ToggleSound,
570 ID_DO_NOT_DISTURB => TrayCommand::ToggleDoNotDisturb,
571 ID_SETTINGS => TrayCommand::Settings,
572 ID_QUIT => TrayCommand::Quit,
573 _ => continue,
574 };
575 commands.push(command);
576 }
577 while let Ok(event) = TrayIconEvent::receiver().try_recv() {
578 if let TrayIconEvent::Click {
579 button: MouseButton::Left,
580 button_state: MouseButtonState::Up,
581 ..
582 } = event
583 {
584 commands.push(TrayCommand::Toggle);
585 }
586 }
587 commands
588 }
589
590 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
591 self.sound.set_checked(!sound_on);
592 self.do_not_disturb.set_checked(do_not_disturb);
593 let icon = if mention { &self.with_dot } else { &self.plain };
594 let _ = self.icon.set_icon(Some(icon.clone()));
595 }
596}
597
598fn tray_icons() -> Option<(Icon, Icon)> {
599 let decoded = image::load_from_memory(TRAY_ICON_PNG).ok()?;
600 let resized = decoded
601 .resize_exact(
602 TRAY_ICON_SIZE,
603 TRAY_ICON_SIZE,
604 image::imageops::FilterType::Lanczos3,
605 )
606 .to_rgba8();
607 let plain = resized.clone().into_raw();
608 let mut dotted = resized;
609 let size = TRAY_ICON_SIZE as f32;
610 let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);
611 for (column, row, pixel) in dotted.enumerate_pixels_mut() {
612 let distance =
613 ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();
614 if distance <= TRAY_DOT_RADIUS {
615 *pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);
616 }
617 }
618 Some((
619 Icon::from_rgba(plain, TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
620 Icon::from_rgba(dotted.into_raw(), TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
621 ))
622}
623
624pub fn animations_enabled() -> bool {
625 let mut enabled = BOOL(1);
626 let read = unsafe {
627 SystemParametersInfoW(
628 SPI_GETCLIENTAREAANIMATION,
629 0,
630 Some(&mut enabled as *mut BOOL as *mut c_void),
631 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
632 )
633 };
634 read.is_err() || enabled.as_bool()
635}