| 1 | use std::ffi::c_void; |
| 2 | use std::io::Cursor; |
| 3 | use std::sync::Arc; |
| 4 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use calling::ShareKind; |
| 8 | use gpui_kit::Window; |
| 9 | use raw_window_handle::{HasWindowHandle, RawWindowHandle}; |
| 10 | use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem}; |
| 11 | use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent}; |
| 12 | use windows::Win32::Foundation::{COLORREF, HWND, LPARAM, POINT, RECT, WPARAM}; |
| 13 | use windows::Win32::Graphics::Dwm::{ |
| 14 | DWMWA_BORDER_COLOR, DWMWA_CLOAKED, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS, |
| 15 | DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DONOTROUND, DwmGetWindowAttribute, |
| 16 | DwmSetWindowAttribute, |
| 17 | }; |
| 18 | use windows::Win32::Graphics::Gdi::{ |
| 19 | CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject, |
| 20 | ENUM_CURRENT_SETTINGS, EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ, |
| 21 | MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromPoint, MonitorFromRect, MonitorFromWindow, |
| 22 | }; |
| 23 | use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance}; |
| 24 | use windows::Win32::UI::HiDpi::{ |
| 25 | GetDpiForMonitor, GetDpiForWindow, GetSystemMetricsForDpi, MDT_EFFECTIVE_DPI, |
| 26 | }; |
| 27 | use windows::Win32::UI::Shell::{ |
| 28 | ITaskbarList3, QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_QUIET_TIME, |
| 29 | QUNS_RUNNING_D3D_FULL_SCREEN, SHQueryUserNotificationState, TaskbarList, |
| 30 | }; |
| 31 | use windows::Win32::UI::WindowsAndMessaging::{ |
| 32 | CreateIconIndirect, DestroyIcon, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, FLASHWINFO, |
| 33 | FlashWindowEx, GW_HWNDPREV, GWL_EXSTYLE, GWL_STYLE, GetWindow, GetWindowLongPtrW, |
| 34 | GetWindowRect, HICON, HWND_NOTOPMOST, HWND_TOPMOST, ICON_BIG, ICON_SMALL, ICONINFO, IsIconic, |
| 35 | IsWindowVisible, LWA_ALPHA, SM_CXSMICON, SPI_GETCLIENTAREAANIMATION, SW_HIDE, SW_RESTORE, |
| 36 | SW_SHOW, SW_SHOWNOACTIVATE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, |
| 37 | SWP_NOSIZE, SWP_NOZORDER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SendMessageW, |
| 38 | SetForegroundWindow, SetLayeredWindowAttributes, SetWindowDisplayAffinity, SetWindowLongPtrW, |
| 39 | SetWindowPos, ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WM_SETICON, |
| 40 | WS_CAPTION, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP, |
| 41 | WS_THICKFRAME, |
| 42 | }; |
| 43 | use windows::core::{BOOL, PCWSTR, w}; |
| 44 | |
| 45 | use super::stack_plan::{StackPlan, stack_plan}; |
| 46 | use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea}; |
| 47 | use crate::notify::badge::{Badge, render_badge}; |
| 48 | |
| 49 | const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3"); |
| 50 | const TRAY_ICON_SIZE: u32 = 32; |
| 51 | const WINDOW_ICON_SIZE: f32 = 32.; |
| 52 | const WINDOW_SMALL_ICON_SIZE: f32 = 16.; |
| 53 | const TRAY_DOT_RADIUS: f32 = 6.; |
| 54 | const BASE_DPI: f32 = 96.; |
| 55 | const RING_POLL: Duration = Duration::from_millis(20); |
| 56 | |
| 57 | fn hwnd(handle: NativeHandle) -> HWND { |
| 58 | HWND(handle as *mut c_void) |
| 59 | } |
| 60 | |
| 61 | pub fn native_handle(window: &Window) -> Option<NativeHandle> { |
| 62 | match HasWindowHandle::window_handle(window).ok()?.as_raw() { |
| 63 | RawWindowHandle::Win32(handle) => Some(handle.hwnd.get()), |
| 64 | _ => None, |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | pub fn window_transparency_available(_window: &Window) -> bool { |
| 69 | // GPUI then renders into an opaque hwnd swap chain without alpha. |
| 70 | !std::env::var("GPUI_DISABLE_DIRECT_COMPOSITION") |
| 71 | .is_ok_and(|value| value == "true" || value == "1") |
| 72 | } |
| 73 | |
| 74 | pub fn prepare_toast_window(handle: NativeHandle) { |
| 75 | unsafe { |
| 76 | // GPUI creates popups with style 0, and Windows adds a caption frame to that on its own. |
| 77 | let frame = (WS_CAPTION | WS_THICKFRAME).0 as isize; |
| 78 | let style = GetWindowLongPtrW(hwnd(handle), GWL_STYLE); |
| 79 | SetWindowLongPtrW( |
| 80 | hwnd(handle), |
| 81 | GWL_STYLE, |
| 82 | (style & !frame) | WS_POPUP.0 as isize, |
| 83 | ); |
| 84 | let _ = SetWindowPos( |
| 85 | hwnd(handle), |
| 86 | None, |
| 87 | 0, |
| 88 | 0, |
| 89 | 0, |
| 90 | 0, |
| 91 | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, |
| 92 | ); |
| 93 | let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE); |
| 94 | SetWindowLongPtrW( |
| 95 | hwnd(handle), |
| 96 | GWL_EXSTYLE, |
| 97 | style | WS_EX_NOACTIVATE.0 as isize, |
| 98 | ); |
| 99 | let no_border = DWMWA_COLOR_NONE; |
| 100 | let _ = DwmSetWindowAttribute( |
| 101 | hwnd(handle), |
| 102 | DWMWA_BORDER_COLOR, |
| 103 | &no_border as *const _ as *const c_void, |
| 104 | size_of::<u32>() as u32, |
| 105 | ); |
| 106 | let preference = DWMWCP_DONOTROUND; |
| 107 | let _ = DwmSetWindowAttribute( |
| 108 | hwnd(handle), |
| 109 | DWMWA_WINDOW_CORNER_PREFERENCE, |
| 110 | &preference as *const _ as *const c_void, |
| 111 | size_of_val(&preference) as u32, |
| 112 | ); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | pub fn set_activatable(handle: NativeHandle, activatable: bool) { |
| 117 | unsafe { |
| 118 | let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE); |
| 119 | let flag = WS_EX_NOACTIVATE.0 as isize; |
| 120 | let updated = if activatable { |
| 121 | style & !flag |
| 122 | } else { |
| 123 | style | flag |
| 124 | }; |
| 125 | SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, updated); |
| 126 | if activatable { |
| 127 | let _ = SetForegroundWindow(hwnd(handle)); |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | pub fn work_area(handle: NativeHandle) -> Option<WorkArea> { |
| 133 | unsafe { |
| 134 | let monitor = MonitorFromWindow(hwnd(handle), MONITOR_DEFAULTTONEAREST); |
| 135 | let mut info = MONITORINFO { |
| 136 | cbSize: size_of::<MONITORINFO>() as u32, |
| 137 | ..Default::default() |
| 138 | }; |
| 139 | if !GetMonitorInfoW(monitor, &mut info).as_bool() { |
| 140 | return None; |
| 141 | } |
| 142 | let RECT { |
| 143 | left, |
| 144 | top, |
| 145 | right, |
| 146 | bottom, |
| 147 | } = info.rcWork; |
| 148 | let dpi = GetDpiForWindow(hwnd(handle)); |
| 149 | Some(WorkArea { |
| 150 | left, |
| 151 | top, |
| 152 | right, |
| 153 | bottom, |
| 154 | scale: if dpi == 0 { 1. } else { dpi as f32 / BASE_DPI }, |
| 155 | }) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | pub fn work_area_at(x: i32, y: i32) -> Option<WorkArea> { |
| 160 | unsafe { |
| 161 | let monitor = MonitorFromPoint(POINT { x, y }, MONITOR_DEFAULTTONEAREST); |
| 162 | let mut info = MONITORINFO { |
| 163 | cbSize: size_of::<MONITORINFO>() as u32, |
| 164 | ..Default::default() |
| 165 | }; |
| 166 | if !GetMonitorInfoW(monitor, &mut info).as_bool() { |
| 167 | return None; |
| 168 | } |
| 169 | let (mut dpi_x, mut dpi_y) = (0, 0); |
| 170 | let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) { |
| 171 | Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI, |
| 172 | _ => 1., |
| 173 | }; |
| 174 | let RECT { |
| 175 | left, |
| 176 | top, |
| 177 | right, |
| 178 | bottom, |
| 179 | } = info.rcWork; |
| 180 | Some(WorkArea { |
| 181 | left, |
| 182 | top, |
| 183 | right, |
| 184 | bottom, |
| 185 | scale, |
| 186 | }) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | pub fn place(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) { |
| 191 | unsafe { |
| 192 | let _ = SetWindowPos( |
| 193 | hwnd(handle), |
| 194 | Some(HWND_TOPMOST), |
| 195 | x, |
| 196 | y, |
| 197 | width, |
| 198 | height, |
| 199 | SWP_NOACTIVATE | SWP_NOOWNERZORDER, |
| 200 | ); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | fn is_topmost(window: HWND) -> bool { |
| 205 | unsafe { GetWindowLongPtrW(window, GWL_EXSTYLE) & WS_EX_TOPMOST.0 as isize != 0 } |
| 206 | } |
| 207 | |
| 208 | fn band_after(shared_topmost: bool, previous: Option<HWND>) -> HWND { |
| 209 | match previous { |
| 210 | Some(previous) if shared_topmost || !is_topmost(previous) => previous, |
| 211 | _ if shared_topmost => HWND_TOPMOST, |
| 212 | _ => HWND_NOTOPMOST, |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | fn windows_above(shared: HWND, group: &[NativeHandle]) -> Vec<NativeHandle> { |
| 217 | let mut above = Vec::new(); |
| 218 | let mut current = shared; |
| 219 | while let Ok(previous) = unsafe { GetWindow(current, GW_HWNDPREV) } { |
| 220 | above.push(previous.0 as NativeHandle); |
| 221 | if !group.contains(&(previous.0 as NativeHandle)) { |
| 222 | break; |
| 223 | } |
| 224 | current = previous; |
| 225 | } |
| 226 | above |
| 227 | } |
| 228 | |
| 229 | pub fn place_rect(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) { |
| 230 | unsafe { |
| 231 | let _ = SetWindowPos( |
| 232 | hwnd(handle), |
| 233 | None, |
| 234 | x, |
| 235 | y, |
| 236 | width, |
| 237 | height, |
| 238 | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER, |
| 239 | ); |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | pub fn stack_group_above(shared: NativeHandle, group: &[NativeHandle]) { |
| 244 | let shared = hwnd(shared); |
| 245 | let above = windows_above(shared, group); |
| 246 | let StackPlan::Rebuild { after } = stack_plan(&above, group) else { |
| 247 | return; |
| 248 | }; |
| 249 | let mut insert_after = band_after(is_topmost(shared), after.map(hwnd)); |
| 250 | for handle in group { |
| 251 | unsafe { |
| 252 | let _ = SetWindowPos( |
| 253 | hwnd(*handle), |
| 254 | Some(insert_after), |
| 255 | 0, |
| 256 | 0, |
| 257 | 0, |
| 258 | 0, |
| 259 | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_NOSIZE, |
| 260 | ); |
| 261 | } |
| 262 | insert_after = hwnd(*handle); |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | pub fn show_window_inactive(handle: NativeHandle) { |
| 267 | unsafe { |
| 268 | let _ = ShowWindow(hwnd(handle), SW_SHOWNOACTIVATE); |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | pub fn exclude_from_capture(handle: NativeHandle) { |
| 273 | unsafe { |
| 274 | let _ = SetWindowDisplayAffinity(hwnd(handle), WDA_EXCLUDEFROMCAPTURE); |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | pub fn make_window_click_through(window: &Window) { |
| 279 | if let Some(handle) = native_handle(window) { |
| 280 | make_click_through(handle); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | fn make_click_through(handle: NativeHandle) { |
| 285 | unsafe { |
| 286 | let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE); |
| 287 | let added = (WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE).0 as isize; |
| 288 | SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, style | added); |
| 289 | // A layered window stays invisible until its alpha is set. |
| 290 | let _ = SetLayeredWindowAttributes(hwnd(handle), COLORREF(0), u8::MAX, LWA_ALPHA); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | pub fn window_minimized(handle: NativeHandle) -> bool { |
| 295 | unsafe { IsIconic(hwnd(handle)).as_bool() } |
| 296 | } |
| 297 | |
| 298 | fn screen_rect(rect: RECT) -> ScreenRect { |
| 299 | ScreenRect { |
| 300 | left: rect.left, |
| 301 | top: rect.top, |
| 302 | right: rect.right, |
| 303 | bottom: rect.bottom, |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | pub fn window_rect(handle: NativeHandle) -> Option<ScreenRect> { |
| 308 | let mut rect = RECT::default(); |
| 309 | unsafe { GetWindowRect(hwnd(handle), &mut rect).ok()? }; |
| 310 | Some(screen_rect(rect)) |
| 311 | } |
| 312 | |
| 313 | fn visible_frame(window: HWND) -> Option<ScreenRect> { |
| 314 | let mut rect = RECT::default(); |
| 315 | unsafe { |
| 316 | if IsIconic(window).as_bool() || !IsWindowVisible(window).as_bool() { |
| 317 | return None; |
| 318 | } |
| 319 | let mut cloaked = 0u32; |
| 320 | let queried = DwmGetWindowAttribute( |
| 321 | window, |
| 322 | DWMWA_CLOAKED, |
| 323 | &mut cloaked as *mut _ as *mut c_void, |
| 324 | size_of::<u32>() as u32, |
| 325 | ); |
| 326 | if queried.is_ok() && cloaked != 0 { |
| 327 | return None; |
| 328 | } |
| 329 | // Excludes the invisible resize margin that GetWindowRect includes. |
| 330 | let framed = DwmGetWindowAttribute( |
| 331 | window, |
| 332 | DWMWA_EXTENDED_FRAME_BOUNDS, |
| 333 | &mut rect as *mut _ as *mut c_void, |
| 334 | size_of::<RECT>() as u32, |
| 335 | ); |
| 336 | if framed.is_err() { |
| 337 | GetWindowRect(window, &mut rect).ok()?; |
| 338 | } |
| 339 | } |
| 340 | Some(screen_rect(rect)) |
| 341 | } |
| 342 | |
| 343 | fn screen_frame(index: u32) -> Option<ScreenRect> { |
| 344 | unsafe { |
| 345 | let mut device = DISPLAY_DEVICEW { |
| 346 | cb: size_of::<DISPLAY_DEVICEW>() as u32, |
| 347 | ..Default::default() |
| 348 | }; |
| 349 | if !EnumDisplayDevicesW(PCWSTR::null(), index, &mut device, 0).as_bool() |
| 350 | || device.StateFlags & DISPLAY_DEVICE_ACTIVE == Default::default() |
| 351 | { |
| 352 | return None; |
| 353 | } |
| 354 | let mut mode = DEVMODEW { |
| 355 | dmSize: size_of::<DEVMODEW>() as u16, |
| 356 | ..Default::default() |
| 357 | }; |
| 358 | if !EnumDisplaySettingsW( |
| 359 | PCWSTR(device.DeviceName.as_ptr()), |
| 360 | ENUM_CURRENT_SETTINGS, |
| 361 | &mut mode, |
| 362 | ) |
| 363 | .as_bool() |
| 364 | { |
| 365 | return None; |
| 366 | } |
| 367 | let position = mode.Anonymous1.Anonymous2.dmPosition; |
| 368 | Some(ScreenRect { |
| 369 | left: position.x, |
| 370 | top: position.y, |
| 371 | right: position.x + mode.dmPelsWidth as i32, |
| 372 | bottom: position.y + mode.dmPelsHeight as i32, |
| 373 | }) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | fn geometry_around(target: ScreenRect) -> Option<ShareGeometry> { |
| 378 | unsafe { |
| 379 | let rect = RECT { |
| 380 | left: target.left, |
| 381 | top: target.top, |
| 382 | right: target.right, |
| 383 | bottom: target.bottom, |
| 384 | }; |
| 385 | let monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST); |
| 386 | let mut info = MONITORINFO { |
| 387 | cbSize: size_of::<MONITORINFO>() as u32, |
| 388 | ..Default::default() |
| 389 | }; |
| 390 | if !GetMonitorInfoW(monitor, &mut info).as_bool() { |
| 391 | return None; |
| 392 | } |
| 393 | let (mut dpi_x, mut dpi_y) = (0, 0); |
| 394 | let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) { |
| 395 | Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI, |
| 396 | _ => 1., |
| 397 | }; |
| 398 | let RECT { |
| 399 | left, |
| 400 | top, |
| 401 | right, |
| 402 | bottom, |
| 403 | } = info.rcWork; |
| 404 | Some(ShareGeometry { |
| 405 | target, |
| 406 | work: WorkArea { |
| 407 | left, |
| 408 | top, |
| 409 | right, |
| 410 | bottom, |
| 411 | scale, |
| 412 | }, |
| 413 | }) |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | pub fn share_geometry(kind: ShareKind, id: u64) -> Option<ShareGeometry> { |
| 418 | let target = match kind { |
| 419 | ShareKind::Screen => screen_frame(u32::try_from(id).ok()?)?, |
| 420 | ShareKind::Window => visible_frame(hwnd(id as NativeHandle))?, |
| 421 | }; |
| 422 | geometry_around(target) |
| 423 | } |
| 424 | |
| 425 | pub fn system_quiet() -> bool { |
| 426 | let state = unsafe { SHQueryUserNotificationState() }; |
| 427 | matches!( |
| 428 | state, |
| 429 | Ok(QUNS_BUSY | QUNS_RUNNING_D3D_FULL_SCREEN | QUNS_PRESENTATION_MODE | QUNS_QUIET_TIME) |
| 430 | ) |
| 431 | } |
| 432 | |
| 433 | pub fn restore_and_raise(handle: NativeHandle) { |
| 434 | unsafe { |
| 435 | let command = if IsIconic(hwnd(handle)).as_bool() { |
| 436 | SW_RESTORE |
| 437 | } else { |
| 438 | SW_SHOW |
| 439 | }; |
| 440 | let _ = ShowWindow(hwnd(handle), command); |
| 441 | let _ = SetForegroundWindow(hwnd(handle)); |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | pub fn hide_window(handle: NativeHandle) { |
| 446 | unsafe { |
| 447 | let _ = ShowWindow(hwnd(handle), SW_HIDE); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | pub fn flash(handle: NativeHandle) { |
| 452 | let info = FLASHWINFO { |
| 453 | cbSize: size_of::<FLASHWINFO>() as u32, |
| 454 | hwnd: hwnd(handle), |
| 455 | dwFlags: FLASHW_TRAY | FLASHW_TIMERNOFG, |
| 456 | uCount: 0, |
| 457 | dwTimeout: 0, |
| 458 | }; |
| 459 | unsafe { |
| 460 | let _ = FlashWindowEx(&info); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | pub fn stop_flash(handle: NativeHandle) { |
| 465 | let info = FLASHWINFO { |
| 466 | cbSize: size_of::<FLASHWINFO>() as u32, |
| 467 | hwnd: hwnd(handle), |
| 468 | dwFlags: FLASHW_STOP, |
| 469 | uCount: 0, |
| 470 | dwTimeout: 0, |
| 471 | }; |
| 472 | unsafe { |
| 473 | let _ = FlashWindowEx(&info); |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) { |
| 478 | unsafe { |
| 479 | let Ok(taskbar) = |
| 480 | CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER) |
| 481 | else { |
| 482 | return; |
| 483 | }; |
| 484 | if taskbar.HrInit().is_err() { |
| 485 | return; |
| 486 | } |
| 487 | match badge { |
| 488 | None => { |
| 489 | let _ = taskbar.SetOverlayIcon(hwnd(handle), HICON::default(), w!("")); |
| 490 | } |
| 491 | Some(badge) => { |
| 492 | let Some(icon) = icon_from_badge(badge, handle) else { |
| 493 | return; |
| 494 | }; |
| 495 | let _ = taskbar.SetOverlayIcon(hwnd(handle), icon, w!("Unread chats")); |
| 496 | let _ = DestroyIcon(icon); |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | unsafe fn icon_from_badge(badge: &Badge, handle: NativeHandle) -> Option<HICON> { |
| 503 | unsafe { |
| 504 | let dpi = GetDpiForWindow(hwnd(handle)); |
| 505 | let size = GetSystemMetricsForDpi(SM_CXSMICON, dpi).max(16) as u32; |
| 506 | icon_from_bgra(&render_badge(badge, size), size) |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | unsafe fn icon_from_bgra(pixels: &[u8], size: u32) -> Option<HICON> { |
| 511 | unsafe { |
| 512 | let color = CreateBitmap( |
| 513 | size as i32, |
| 514 | size as i32, |
| 515 | 1, |
| 516 | 32, |
| 517 | Some(pixels.as_ptr() as *const c_void), |
| 518 | ); |
| 519 | let mask = CreateBitmap(size as i32, size as i32, 1, 1, None); |
| 520 | let info = ICONINFO { |
| 521 | fIcon: BOOL(1), |
| 522 | xHotspot: 0, |
| 523 | yHotspot: 0, |
| 524 | hbmMask: mask, |
| 525 | hbmColor: color, |
| 526 | }; |
| 527 | let icon = CreateIconIndirect(&info).ok(); |
| 528 | let _ = DeleteObject(HGDIOBJ(color.0)); |
| 529 | let _ = DeleteObject(HGDIOBJ(mask.0)); |
| 530 | icon |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | pub fn set_window_icon(window: &Window, png: &[u8]) { |
| 535 | let Some(handle) = native_handle(window) else { |
| 536 | return; |
| 537 | }; |
| 538 | let Ok(decoded) = image::load_from_memory(png) else { |
| 539 | return; |
| 540 | }; |
| 541 | let dpi = unsafe { GetDpiForWindow(hwnd(handle)) }; |
| 542 | let scale = if dpi == 0 { 1. } else { dpi as f32 / BASE_DPI }; |
| 543 | for (kind, base_size) in [ |
| 544 | (ICON_BIG, WINDOW_ICON_SIZE), |
| 545 | (ICON_SMALL, WINDOW_SMALL_ICON_SIZE), |
| 546 | ] { |
| 547 | let size = (base_size * scale).round() as u32; |
| 548 | let mut pixels = decoded |
| 549 | .resize_exact(size, size, image::imageops::FilterType::Lanczos3) |
| 550 | .to_rgba8() |
| 551 | .into_raw(); |
| 552 | for pixel in pixels.chunks_exact_mut(4) { |
| 553 | pixel.swap(0, 2); |
| 554 | } |
| 555 | unsafe { |
| 556 | let Some(icon) = icon_from_bgra(&pixels, size) else { |
| 557 | continue; |
| 558 | }; |
| 559 | let previous = SendMessageW( |
| 560 | hwnd(handle), |
| 561 | WM_SETICON, |
| 562 | Some(WPARAM(kind as usize)), |
| 563 | Some(LPARAM(icon.0 as isize)), |
| 564 | ); |
| 565 | if previous.0 != 0 { |
| 566 | let _ = DestroyIcon(HICON(previous.0 as *mut c_void)); |
| 567 | } |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | static SOUND_OUTPUT: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None); |
| 573 | |
| 574 | pub fn set_sound_output(device_key: Option<String>) { |
| 575 | *SOUND_OUTPUT |
| 576 | .lock() |
| 577 | .unwrap_or_else(|poisoned| poisoned.into_inner()) = device_key; |
| 578 | } |
| 579 | |
| 580 | fn open_sound_sink() -> Option<rodio::MixerDeviceSink> { |
| 581 | use rodio::cpal::traits::{DeviceTrait, HostTrait}; |
| 582 | let chosen = SOUND_OUTPUT |
| 583 | .lock() |
| 584 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 585 | .clone(); |
| 586 | let device = chosen.and_then(|device_key| { |
| 587 | rodio::cpal::default_host() |
| 588 | .output_devices() |
| 589 | .ok()? |
| 590 | .find(|device| { |
| 591 | device.id().is_ok_and(|id| id.1 == device_key) |
| 592 | || device |
| 593 | .description() |
| 594 | .is_ok_and(|description| description.name() == device_key) |
| 595 | }) |
| 596 | }); |
| 597 | device |
| 598 | .and_then(|device| { |
| 599 | rodio::DeviceSinkBuilder::from_device(device) |
| 600 | .and_then(|builder| builder.open_stream()) |
| 601 | .ok() |
| 602 | }) |
| 603 | .or_else(|| rodio::DeviceSinkBuilder::open_default_sink().ok()) |
| 604 | } |
| 605 | |
| 606 | pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) { |
| 607 | std::thread::spawn(move || { |
| 608 | let Some(mut sink) = open_sound_sink() else { |
| 609 | return; |
| 610 | }; |
| 611 | sink.log_on_drop(false); |
| 612 | loop { |
| 613 | let Ok(player) = rodio::play(sink.mixer(), Cursor::new(bytes.clone())) else { |
| 614 | return; |
| 615 | }; |
| 616 | while !player.empty() { |
| 617 | if stop.load(Ordering::SeqCst) { |
| 618 | player.stop(); |
| 619 | return; |
| 620 | } |
| 621 | std::thread::sleep(RING_POLL); |
| 622 | } |
| 623 | if !looped || stop.load(Ordering::SeqCst) { |
| 624 | return; |
| 625 | } |
| 626 | } |
| 627 | }); |
| 628 | } |
| 629 | |
| 630 | pub fn play_mp3(bytes: Vec<u8>) { |
| 631 | std::thread::spawn(move || { |
| 632 | let Some(mut sink) = open_sound_sink() else { |
| 633 | return; |
| 634 | }; |
| 635 | sink.log_on_drop(false); |
| 636 | if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(bytes)) { |
| 637 | player.sleep_until_end(); |
| 638 | } |
| 639 | }); |
| 640 | } |
| 641 | |
| 642 | pub fn play_sound() { |
| 643 | std::thread::spawn(|| { |
| 644 | let Some(mut sink) = open_sound_sink() else { |
| 645 | return; |
| 646 | }; |
| 647 | sink.log_on_drop(false); |
| 648 | if let Ok(player) = rodio::play(sink.mixer(), Cursor::new(SOUND_BYTES)) { |
| 649 | player.sleep_until_end(); |
| 650 | } |
| 651 | }); |
| 652 | } |
| 653 | |
| 654 | const ID_OPEN: &str = "open"; |
| 655 | const ID_SOUND: &str = "sound"; |
| 656 | const ID_DO_NOT_DISTURB: &str = "do_not_disturb"; |
| 657 | const ID_SETTINGS: &str = "settings"; |
| 658 | const ID_QUIT: &str = "quit"; |
| 659 | |
| 660 | pub struct Tray { |
| 661 | icon: TrayIcon, |
| 662 | sound: CheckMenuItem, |
| 663 | do_not_disturb: CheckMenuItem, |
| 664 | plain: Icon, |
| 665 | with_dot: Icon, |
| 666 | } |
| 667 | |
| 668 | impl Tray { |
| 669 | pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> { |
| 670 | let (plain, with_dot) = tray_icons(icon_png)?; |
| 671 | let open = MenuItem::with_id(ID_OPEN, "Open", true, None); |
| 672 | let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None); |
| 673 | let dnd = CheckMenuItem::with_id( |
| 674 | ID_DO_NOT_DISTURB, |
| 675 | "Do not disturb", |
| 676 | true, |
| 677 | do_not_disturb, |
| 678 | None, |
| 679 | ); |
| 680 | let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None); |
| 681 | let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None); |
| 682 | let menu = Menu::new(); |
| 683 | menu.append_items(&[ |
| 684 | &open, |
| 685 | &PredefinedMenuItem::separator(), |
| 686 | &sound, |
| 687 | &dnd, |
| 688 | &settings, |
| 689 | &PredefinedMenuItem::separator(), |
| 690 | &quit, |
| 691 | ]) |
| 692 | .ok()?; |
| 693 | let icon = TrayIconBuilder::new() |
| 694 | .with_icon(plain.clone()) |
| 695 | .with_tooltip(crate::APP_NAME) |
| 696 | .with_menu(Box::new(menu)) |
| 697 | .with_menu_on_left_click(false) |
| 698 | .build() |
| 699 | .ok()?; |
| 700 | Some(Tray { |
| 701 | icon, |
| 702 | sound, |
| 703 | do_not_disturb: dnd, |
| 704 | plain, |
| 705 | with_dot, |
| 706 | }) |
| 707 | } |
| 708 | |
| 709 | pub fn poll(&self) -> Vec<TrayCommand> { |
| 710 | let mut commands = Vec::new(); |
| 711 | while let Ok(event) = MenuEvent::receiver().try_recv() { |
| 712 | let command = match event.id.0.as_str() { |
| 713 | ID_OPEN => TrayCommand::Open, |
| 714 | ID_SOUND => TrayCommand::ToggleSound, |
| 715 | ID_DO_NOT_DISTURB => TrayCommand::ToggleDoNotDisturb, |
| 716 | ID_SETTINGS => TrayCommand::Settings, |
| 717 | ID_QUIT => TrayCommand::Quit, |
| 718 | _ => continue, |
| 719 | }; |
| 720 | commands.push(command); |
| 721 | } |
| 722 | while let Ok(event) = TrayIconEvent::receiver().try_recv() { |
| 723 | if let TrayIconEvent::Click { |
| 724 | button: MouseButton::Left, |
| 725 | button_state: MouseButtonState::Up, |
| 726 | .. |
| 727 | } = event |
| 728 | { |
| 729 | commands.push(TrayCommand::Toggle); |
| 730 | } |
| 731 | } |
| 732 | commands |
| 733 | } |
| 734 | |
| 735 | pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) { |
| 736 | let Some((plain, with_dot)) = tray_icons(icon_png) else { |
| 737 | return; |
| 738 | }; |
| 739 | self.plain = plain; |
| 740 | self.with_dot = with_dot; |
| 741 | let icon = if mention { &self.with_dot } else { &self.plain }; |
| 742 | let _ = self.icon.set_icon(Some(icon.clone())); |
| 743 | } |
| 744 | |
| 745 | pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) { |
| 746 | self.sound.set_checked(!sound_on); |
| 747 | self.do_not_disturb.set_checked(do_not_disturb); |
| 748 | let icon = if mention { &self.with_dot } else { &self.plain }; |
| 749 | let _ = self.icon.set_icon(Some(icon.clone())); |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | fn tray_icons(icon_png: &[u8]) -> Option<(Icon, Icon)> { |
| 754 | let decoded = image::load_from_memory(icon_png).ok()?; |
| 755 | let resized = decoded |
| 756 | .resize_exact( |
| 757 | TRAY_ICON_SIZE, |
| 758 | TRAY_ICON_SIZE, |
| 759 | image::imageops::FilterType::Lanczos3, |
| 760 | ) |
| 761 | .to_rgba8(); |
| 762 | let plain = resized.clone().into_raw(); |
| 763 | let mut dotted = resized; |
| 764 | let size = TRAY_ICON_SIZE as f32; |
| 765 | let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.); |
| 766 | for (column, row, pixel) in dotted.enumerate_pixels_mut() { |
| 767 | let distance = |
| 768 | ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt(); |
| 769 | if distance <= TRAY_DOT_RADIUS { |
| 770 | *pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]); |
| 771 | } |
| 772 | } |
| 773 | Some(( |
| 774 | Icon::from_rgba(plain, TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?, |
| 775 | Icon::from_rgba(dotted.into_raw(), TRAY_ICON_SIZE, TRAY_ICON_SIZE).ok()?, |
| 776 | )) |
| 777 | } |
| 778 | |
| 779 | pub fn animations_enabled() -> bool { |
| 780 | let mut enabled = BOOL(1); |
| 781 | let read = unsafe { |
| 782 | SystemParametersInfoW( |
| 783 | SPI_GETCLIENTAREAANIMATION, |
| 784 | 0, |
| 785 | Some(&mut enabled as *mut BOOL as *mut c_void), |
| 786 | SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0), |
| 787 | ) |
| 788 | }; |
| 789 | read.is_err() || enabled.as_bool() |
| 790 | } |