BlueGit

ict rusty-teams

Files

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

windows_impl.rs

windows_impl.rs 13.3 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::{SAMPLE_RATE, ring_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() -> Option<RingTone> {
266 let stop = Arc::new(AtomicBool::new(false));
267 let flag = stop.clone();
268 std::thread::spawn(move || {
269 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
270 return;
271 };
272 sink.log_on_drop(false);
273 let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
274 return;
275 };
276 let cycle = ring_cycle(SAMPLE_RATE);
277 while !flag.load(Ordering::SeqCst) {
278 let player = rodio::Player::connect_new(sink.mixer());
279 player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));
280 while !player.empty() {
281 if flag.load(Ordering::SeqCst) {
282 player.stop();
283 return;
284 }
285 std::thread::sleep(RING_POLL);
286 }
287 }
288 });
289 Some(RingTone { stop })
290}
291
292pub fn play_sound() {
293 std::thread::spawn(|| {
294 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
295 return;
296 };
297 sink.log_on_drop(false);
298 if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(SOUND_BYTES)) {
299 player.sleep_until_end();
300 }
301 });
302}
303
304const ID_OPEN: &str = "open";
305const ID_SOUND: &str = "sound";
306const ID_DO_NOT_DISTURB: &str = "do_not_disturb";
307const ID_SETTINGS: &str = "settings";
308const ID_QUIT: &str = "quit";
309
310pub struct Tray {
311 icon: TrayIcon,
312 sound: CheckMenuItem,
313 do_not_disturb: CheckMenuItem,
314 plain: Icon,
315 with_dot: Icon,
316}
317
318impl Tray {
319 pub fn new(sound_on: bool, do_not_disturb: bool) -> Option<Self> {
320 let (plain, with_dot) = tray_icons()?;
321 let open = MenuItem::with_id(ID_OPEN, "Open", true, None);
322 let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None);
323 let dnd = CheckMenuItem::with_id(
324 ID_DO_NOT_DISTURB,
325 "Do not disturb",
326 true,
327 do_not_disturb,
328 None,
329 );
330 let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None);
331 let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None);
332 let menu = Menu::new();
333 menu.append_items(&[
334 &open,
335 &PredefinedMenuItem::separator(),
336 &sound,
337 &dnd,
338 &settings,
339 &PredefinedMenuItem::separator(),
340 &quit,
341 ])
342 .ok()?;
343 let icon = TrayIconBuilder::new()
344 .with_icon(plain.clone())
345 .with_tooltip(crate::APP_NAME)
346 .with_menu(Box::new(menu))
347 .with_menu_on_left_click(false)
348 .build()
349 .ok()?;
350 Some(Tray {
351 icon,
352 sound,
353 do_not_disturb: dnd,
354 plain,
355 with_dot,
356 })
357 }
358
359 pub fn poll(&self) -> Vec<TrayCommand> {
360 let mut commands = Vec::new();
361 while let Ok(event) = MenuEvent::receiver().try_recv() {
362 let command = match event.id.0.as_str() {
363 ID_OPEN => TrayCommand::Open,
364 ID_SOUND => TrayCommand::ToggleSound,
365 ID_DO_NOT_DISTURB => TrayCommand::ToggleDoNotDisturb,
366 ID_SETTINGS => TrayCommand::Settings,
367 ID_QUIT => TrayCommand::Quit,
368 _ => continue,
369 };
370 commands.push(command);
371 }
372 while let Ok(event) = TrayIconEvent::receiver().try_recv() {
373 if let TrayIconEvent::Click {
374 button: MouseButton::Left,
375 button_state: MouseButtonState::Up,
376 ..
377 } = event
378 {
379 commands.push(TrayCommand::Toggle);
380 }
381 }
382 commands
383 }
384
385 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
386 self.sound.set_checked(!sound_on);
387 self.do_not_disturb.set_checked(do_not_disturb);
388 let icon = if mention { &self.with_dot } else { &self.plain };
389 let _ = self.icon.set_icon(Some(icon.clone()));
390 }
391}
392
393fn tray_icons() -> Option<(Icon, Icon)> {
394 let decoded = image::load_from_memory(TRAY_ICON_PNG).ok()?;
395 let resized = decoded
396 .resize_exact(
397 TRAY_ICON_SIZE,
398 TRAY_ICON_SIZE,
399 image::imageops::FilterType::Lanczos3,
400 )
401 .to_rgba8();
402 let plain = resized.clone().into_raw();
403 let mut dotted = resized;
404 let size = TRAY_ICON_SIZE as f32;
405 let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);
406 for (column, row, pixel) in dotted.enumerate_pixels_mut() {
407 let distance = ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();
408 if distance <= TRAY_DOT_RADIUS {
409 *pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);
410 }
411 }
412 Some((
413 Icon::from_rgba(plain, TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
414 Icon::from_rgba(dotted.into_raw(), TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?,
415 ))
416}
417
418pub fn animations_enabled() -> bool {
419 let mut enabled = BOOL(1);
420 let read = unsafe {
421 SystemParametersInfoW(
422 SPI_GETCLIENTAREAANIMATION,
423 0,
424 Some(&mut enabled as *mut BOOL as *mut c_void),
425 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
426 )
427 };
428 read.is_err() || enabled.as_bool()
429}