BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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