BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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