BlueGit

ict rusty-teams

Files

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

windows_impl.rs

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