BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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