BlueGit

ict rusty-teams

Files

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

windows_impl.rs

windows_impl.rs 14.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 gpui_kit::Window;
9use raw_window_handle::{HasWindowHandle, RawWindowHandle};
10use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem};
11use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
12use windows::Win32::Foundation::{HWND, RECT};
13use windows::Win32::Graphics::Dwm::{
14 DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DONOTROUND,
15 DwmSetWindowAttribute,
16};
17use windows::Win32::Graphics::Gdi::{
18 CreateBitmap, DeleteObject, GetMonitorInfoW, HGDIOBJ, MONITOR_DEFAULTTONEAREST, MONITORINFO,
19 MonitorFromWindow,
20};
21use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
22use windows::Win32::UI::HiDpi::GetDpiForWindow;
23use windows::Win32::UI::Shell::{
24 ITaskbarList3, QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_QUIET_TIME, QUNS_RUNNING_D3D_FULL_SCREEN,
25 SHQueryUserNotificationState, TaskbarList,
26};
27use windows::Win32::UI::WindowsAndMessaging::{
28 CreateIconIndirect, DestroyIcon, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, FLASHWINFO, FlashWindowEx, GWL_EXSTYLE, GWL_STYLE,
29 GetWindowLongPtrW, HICON, HWND_TOPMOST, ICONINFO, IsIconic, SW_HIDE, SW_RESTORE, SW_SHOW, SWP_NOACTIVATE,
30 SPI_GETCLIENTAREAANIMATION, SWP_FRAMECHANGED, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
31 SWP_NOZORDER, WS_CAPTION, WS_POPUP, WS_THICKFRAME, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetForegroundWindow,
32 SetWindowLongPtrW, SetWindowPos, ShowWindow, SystemParametersInfoW,
33 WS_EX_NOACTIVATE,
34};
35use windows::core::{BOOL, w};
36
37use super::{NativeHandle, TrayCommand, WorkArea};
38use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};
39use crate::notify::ring_tone::{Ringtone, SAMPLE_RATE, ringback_cycle};
40
41const SOUND_BYTES: &[u8] = include_bytes!("../../../assets/sounds/notification.mp3");
42const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../assets/icon/teams-fast-256.png");
43const TRAY_ICON_SIZE: u32 = 32;
44const TRAY_DOT_RADIUS: f32 = 6.;
45const BASE_DPI: f32 = 96.;
46const RING_POLL: Duration = Duration::from_millis(20);
47
48fn hwnd(handle: NativeHandle) -> HWND {
49 HWND(handle as *mut c_void)
50}
51
52pub fn native_handle(window: &Window) -> Option<NativeHandle> {
53 match HasWindowHandle::window_handle(window).ok()?.as_raw() {
54 RawWindowHandle::Win32(handle) => Some(handle.hwnd.get()),
55 _ => None,
56 }
57}
58
59pub fn prepare_toast_window(handle: NativeHandle) {
60 unsafe {
61 // GPUI creates popups with style 0, and Windows adds a caption frame to that on its own.
62 let frame = (WS_CAPTION | WS_THICKFRAME).0 as isize;
63 let style = GetWindowLongPtrW(hwnd(handle), GWL_STYLE);
64 SetWindowLongPtrW(
65 hwnd(handle),
66 GWL_STYLE,
67 (style & !frame) | WS_POPUP.0 as isize,
68 );
69 let _ = SetWindowPos(
70 hwnd(handle),
71 None,
72 0,
73 0,
74 0,
75 0,
76 SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE,
77 );
78 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
79 SetWindowLongPtrW(
80 hwnd(handle),
81 GWL_EXSTYLE,
82 style | WS_EX_NOACTIVATE.0 as isize,
83 );
84 let no_border = DWMWA_COLOR_NONE;
85 let _ = DwmSetWindowAttribute(
86 hwnd(handle),
87 DWMWA_BORDER_COLOR,
88 &no_border as *const _ as *const c_void,
89 size_of::<u32>() as u32,
90 );
91 let preference = DWMWCP_DONOTROUND;
92 let _ = DwmSetWindowAttribute(
93 hwnd(handle),
94 DWMWA_WINDOW_CORNER_PREFERENCE,
95 &preference as *const _ as *const c_void,
96 size_of_val(&preference) as u32,
97 );
98 }
99}
100
101pub fn set_activatable(handle: NativeHandle, activatable: bool) {
102 unsafe {
103 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
104 let flag = WS_EX_NOACTIVATE.0 as isize;
105 let updated = if activatable { style & !flag } else { style | flag };
106 SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, updated);
107 if activatable {
108 let _ = SetForegroundWindow(hwnd(handle));
109 }
110 }
111}
112
113pub fn work_area(handle: NativeHandle) -> Option<WorkArea> {
114 unsafe {
115 let monitor = MonitorFromWindow(hwnd(handle), MONITOR_DEFAULTTONEAREST);
116 let mut info = MONITORINFO {
117 cbSize: size_of::<MONITORINFO>() as u32,
118 ..Default::default()
119 };
120 if !GetMonitorInfoW(monitor, &mut info).as_bool() {
121 return None;
122 }
123 let RECT {
124 left,
125 top,
126 right,
127 bottom,
128 } = info.rcWork;
129 let dpi = GetDpiForWindow(hwnd(handle));
130 Some(WorkArea {
131 left,
132 top,
133 right,
134 bottom,
135 scale: if dpi == 0 { 1. } else { dpi as f32 / BASE_DPI },
136 })
137 }
138}
139
140pub fn place(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) {
141 unsafe {
142 let _ = SetWindowPos(
143 hwnd(handle),
144 Some(HWND_TOPMOST),
145 x,
146 y,
147 width,
148 height,
149 SWP_NOACTIVATE | SWP_NOOWNERZORDER,
150 );
151 }
152}
153
154pub fn system_quiet() -> bool {
155 let state = unsafe { SHQueryUserNotificationState() };
156 matches!(
157 state,
158 Ok(QUNS_BUSY | QUNS_RUNNING_D3D_FULL_SCREEN | QUNS_PRESENTATION_MODE | QUNS_QUIET_TIME)
159 )
160}
161
162pub fn restore_and_raise(handle: NativeHandle) {
163 unsafe {
164 let command = if IsIconic(hwnd(handle)).as_bool() {
165 SW_RESTORE
166 } else {
167 SW_SHOW
168 };
169 let _ = ShowWindow(hwnd(handle), command);
170 let _ = SetForegroundWindow(hwnd(handle));
171 }
172}
173
174pub fn hide_window(handle: NativeHandle) {
175 unsafe {
176 let _ = ShowWindow(hwnd(handle), SW_HIDE);
177 }
178}
179
180pub fn flash(handle: NativeHandle) {
181 let info = FLASHWINFO {
182 cbSize: size_of::<FLASHWINFO>() as u32,
183 hwnd: hwnd(handle),
184 dwFlags: FLASHW_TRAY | FLASHW_TIMERNOFG,
185 uCount: 0,
186 dwTimeout: 0,
187 };
188 unsafe {
189 let _ = FlashWindowEx(&info);
190 }
191}
192
193pub fn stop_flash(handle: NativeHandle) {
194 let info = FLASHWINFO {
195 cbSize: size_of::<FLASHWINFO>() as u32,
196 hwnd: hwnd(handle),
197 dwFlags: FLASHW_STOP,
198 uCount: 0,
199 dwTimeout: 0,
200 };
201 unsafe {
202 let _ = FlashWindowEx(&info);
203 }
204}
205
206pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) {
207 unsafe {
208 let Ok(taskbar) = CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)
209 else {
210 return;
211 };
212 if taskbar.HrInit().is_err() {
213 return;
214 }
215 match badge {
216 None => {
217 let _ = taskbar.SetOverlayIcon(hwnd(handle), HICON::default(), w!(""));
218 }
219 Some(badge) => {
220 let Some(icon) = icon_from_badge(badge) else {
221 return;
222 };
223 let _ = taskbar.SetOverlayIcon(hwnd(handle), icon, w!("Unread chats"));
224 let _ = DestroyIcon(icon);
225 }
226 }
227 }
228}
229
230unsafe fn icon_from_badge(badge: &Badge) -> Option<HICON> {
231 let pixels = render_badge(badge);
232 unsafe {
233 let color = CreateBitmap(
234 BADGE_SIZE as i32,
235 BADGE_SIZE as i32,
236 1,
237 32,
238 Some(pixels.as_ptr() as *const c_void),
239 );
240 let mask = CreateBitmap(BADGE_SIZE as i32, BADGE_SIZE as i32, 1, 1, None);
241 let info = ICONINFO {
242 fIcon: BOOL(1),
243 xHotspot: 0,
244 yHotspot: 0,
245 hbmMask: mask,
246 hbmColor: color,
247 };
248 let icon = CreateIconIndirect(&info).ok();
249 let _ = DeleteObject(HGDIOBJ(color.0));
250 let _ = DeleteObject(HGDIOBJ(mask.0));
251 icon
252 }
253}
254
255pub struct RingTone {
256 stop: Arc<AtomicBool>,
257}
258
259impl Drop for RingTone {
260 fn drop(&mut self) {
261 self.stop.store(true, Ordering::SeqCst);
262 }
263}
264
265pub fn start_ring(ringtone: Ringtone) -> Option<RingTone> {
266 start_cycle(ringtone.cycle(SAMPLE_RATE))
267}
268
269pub fn start_ringback() -> Option<RingTone> {
270 start_cycle(ringback_cycle(SAMPLE_RATE))
271}
272
273pub fn play_preview(ringtone: Ringtone) {
274 let cycle = ringtone.cycle(SAMPLE_RATE);
275 std::thread::spawn(move || {
276 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
277 return;
278 };
279 sink.log_on_drop(false);
280 let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
281 return;
282 };
283 let player = rodio::Player::connect_new(sink.mixer());
284 player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle));
285 player.sleep_until_end();
286 });
287}
288
289fn start_cycle(cycle: Vec<f32>) -> Option<RingTone> {
290 let stop = Arc::new(AtomicBool::new(false));
291 let flag = stop.clone();
292 std::thread::spawn(move || {
293 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
294 return;
295 };
296 sink.log_on_drop(false);
297 let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
298 return;
299 };
300 while !flag.load(Ordering::SeqCst) {
301 let player = rodio::Player::connect_new(sink.mixer());
302 player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));
303 while !player.empty() {
304 if flag.load(Ordering::SeqCst) {
305 player.stop();
306 return;
307 }
308 std::thread::sleep(RING_POLL);
309 }
310 }
311 });
312 Some(RingTone { stop })
313}
314
315pub fn play_sound() {
316 std::thread::spawn(|| {
317 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
318 return;
319 };
320 sink.log_on_drop(false);
321 if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(SOUND_BYTES)) {
322 player.sleep_until_end();
323 }
324 });
325}
326
327const ID_OPEN: &str = "open";
328const ID_SOUND: &str = "sound";
329const ID_DO_NOT_DISTURB: &str = "do_not_disturb";
330const ID_SETTINGS: &str = "settings";
331const ID_QUIT: &str = "quit";
332
333pub struct Tray {
334 icon: TrayIcon,
335 sound: CheckMenuItem,
336 do_not_disturb: CheckMenuItem,
337 plain: Icon,
338 with_dot: Icon,
339}
340
341impl Tray {
342 pub fn new(sound_on: bool, do_not_disturb: bool) -> Option<Self> {
343 let (plain, with_dot) = tray_icons()?;
344 let open = MenuItem::with_id(ID_OPEN, "Open", true, None);
345 let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None);
346 let dnd = CheckMenuItem::with_id(
347 ID_DO_NOT_DISTURB,
348 "Do not disturb",
349 true,
350 do_not_disturb,
351 None,
352 );
353 let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None);
354 let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None);
355 let menu = Menu::new();
356 menu.append_items(&[
357 &open,
358 &PredefinedMenuItem::separator(),
359 &sound,
360 &dnd,
361 &settings,
362 &PredefinedMenuItem::separator(),
363 &quit,
364 ])
365 .ok()?;
366 let icon = TrayIconBuilder::new()
367 .with_icon(plain.clone())
368 .with_tooltip(crate::APP_NAME)
369 .with_menu(Box::new(menu))
370 .with_menu_on_left_click(false)
371 .build()
372 .ok()?;
373 Some(Tray {
374 icon,
375 sound,
376 do_not_disturb: dnd,
377 plain,
378 with_dot,
379 })
380 }
381
382 pub fn poll(&self) -> Vec<TrayCommand> {
383 let mut commands = Vec::new();
384 while let Ok(event) = MenuEvent::receiver().try_recv() {
385 let command = match event.id.0.as_str() {
386 ID_OPEN => TrayCommand::Open,
387 ID_SOUND => TrayCommand::ToggleSound,
388 ID_DO_NOT_DISTURB => TrayCommand::ToggleDoNotDisturb,
389 ID_SETTINGS => TrayCommand::Settings,
390 ID_QUIT => TrayCommand::Quit,
391 _ => continue,
392 };
393 commands.push(command);
394 }
395 while let Ok(event) = TrayIconEvent::receiver().try_recv() {
396 if let TrayIconEvent::Click {
397 button: MouseButton::Left,
398 button_state: MouseButtonState::Up,
399 ..
400 } = event
401 {
402 commands.push(TrayCommand::Toggle);
403 }
404 }
405 commands
406 }
407
408 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
409 self.sound.set_checked(!sound_on);
410 self.do_not_disturb.set_checked(do_not_disturb);
411 let icon = if mention { &self.with_dot } else { &self.plain };
412 let _ = self.icon.set_icon(Some(icon.clone()));
413 }
414}
415
416fn tray_icons() -> Option<(Icon, Icon)> {
417 let decoded = image::load_from_memory(TRAY_ICON_PNG).ok()?;
418 let resized = decoded
419 .resize_exact(
420 TRAY_ICON_SIZE,
421 TRAY_ICON_SIZE,
422 image::imageops::FilterType::Lanczos3,
423 )
424 .to_rgba8();
425 let plain = resized.clone().into_raw();
426 let mut dotted = resized;
427 let size = TRAY_ICON_SIZE as f32;
428 let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);
429 for (column, row, pixel) in dotted.enumerate_pixels_mut() {
430 let distance = ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();
431 if distance <= TRAY_DOT_RADIUS {
432 *pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);
433 }
434 }
435 Some((
436 Icon::from_rgba(plain, TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
437 Icon::from_rgba(dotted.into_raw(), TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
438 ))
439}
440
441pub fn animations_enabled() -> bool {
442 let mut enabled = BOOL(1);
443 let read = unsafe {
444 SystemParametersInfoW(
445 SPI_GETCLIENTAREAANIMATION,
446 0,
447 Some(&mut enabled as *mut BOOL as *mut c_void),
448 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
449 )
450 };
451 read.is_err() || enabled.as_bool()
452}