BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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