window.rs

   1#![deny(unsafe_op_in_unsafe_fn)]
   2
   3use std::{
   4    cell::RefCell,
   5    num::NonZeroIsize,
   6    path::PathBuf,
   7    rc::{Rc, Weak},
   8    str::FromStr,
   9    sync::{Arc, Once},
  10    time::{Duration, Instant},
  11};
  12
  13use ::util::ResultExt;
  14use anyhow::{Context as _, Result};
  15use async_task::Runnable;
  16use futures::channel::oneshot::{self, Receiver};
  17use raw_window_handle as rwh;
  18use smallvec::SmallVec;
  19use windows::{
  20    Win32::{
  21        Foundation::*,
  22        Graphics::Gdi::*,
  23        System::{Com::*, LibraryLoader::*, Ole::*, SystemServices::*},
  24        UI::{Controls::*, HiDpi::*, Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
  25    },
  26    core::*,
  27};
  28
  29use crate::*;
  30
  31pub(crate) struct WindowsWindow(pub Rc<WindowsWindowInner>);
  32
  33pub struct WindowsWindowState {
  34    pub origin: Point<Pixels>,
  35    pub logical_size: Size<Pixels>,
  36    pub min_size: Option<Size<Pixels>>,
  37    pub fullscreen_restore_bounds: Bounds<Pixels>,
  38    pub border_offset: WindowBorderOffset,
  39    pub appearance: WindowAppearance,
  40    pub scale_factor: f32,
  41    pub restore_from_minimized: Option<Box<dyn FnMut(RequestFrameOptions)>>,
  42
  43    pub callbacks: Callbacks,
  44    pub input_handler: Option<PlatformInputHandler>,
  45    pub pending_surrogate: Option<u16>,
  46    pub last_reported_modifiers: Option<Modifiers>,
  47    pub last_reported_capslock: Option<Capslock>,
  48    pub hovered: bool,
  49
  50    pub renderer: DirectXRenderer,
  51
  52    pub click_state: ClickState,
  53    pub current_cursor: Option<HCURSOR>,
  54    pub nc_button_pressed: Option<u32>,
  55
  56    pub display: WindowsDisplay,
  57    fullscreen: Option<StyleAndBounds>,
  58    initial_placement: Option<WindowOpenStatus>,
  59    hwnd: HWND,
  60}
  61
  62pub(crate) struct WindowsWindowInner {
  63    hwnd: HWND,
  64    pub(super) this: Weak<Self>,
  65    drop_target_helper: IDropTargetHelper,
  66    pub(crate) state: RefCell<WindowsWindowState>,
  67    pub(crate) system_settings: RefCell<WindowsSystemSettings>,
  68    pub(crate) handle: AnyWindowHandle,
  69    pub(crate) hide_title_bar: bool,
  70    pub(crate) is_movable: bool,
  71    pub(crate) executor: ForegroundExecutor,
  72    pub(crate) windows_version: WindowsVersion,
  73    pub(crate) validation_number: usize,
  74    pub(crate) main_receiver: flume::Receiver<Runnable>,
  75    pub(crate) platform_window_handle: HWND,
  76}
  77
  78impl WindowsWindowState {
  79    fn new(
  80        hwnd: HWND,
  81        directx_devices: &DirectXDevices,
  82        window_params: &CREATESTRUCTW,
  83        current_cursor: Option<HCURSOR>,
  84        display: WindowsDisplay,
  85        min_size: Option<Size<Pixels>>,
  86        appearance: WindowAppearance,
  87        disable_direct_composition: bool,
  88    ) -> Result<Self> {
  89        let scale_factor = {
  90            let monitor_dpi = unsafe { GetDpiForWindow(hwnd) } as f32;
  91            monitor_dpi / USER_DEFAULT_SCREEN_DPI as f32
  92        };
  93        let origin = logical_point(window_params.x as f32, window_params.y as f32, scale_factor);
  94        let logical_size = {
  95            let physical_size = size(
  96                DevicePixels(window_params.cx),
  97                DevicePixels(window_params.cy),
  98            );
  99            physical_size.to_pixels(scale_factor)
 100        };
 101        let fullscreen_restore_bounds = Bounds {
 102            origin,
 103            size: logical_size,
 104        };
 105        let border_offset = WindowBorderOffset::default();
 106        let restore_from_minimized = None;
 107        let renderer = DirectXRenderer::new(hwnd, directx_devices, disable_direct_composition)
 108            .context("Creating DirectX renderer")?;
 109        let callbacks = Callbacks::default();
 110        let input_handler = None;
 111        let pending_surrogate = None;
 112        let last_reported_modifiers = None;
 113        let last_reported_capslock = None;
 114        let hovered = false;
 115        let click_state = ClickState::new();
 116        let nc_button_pressed = None;
 117        let fullscreen = None;
 118        let initial_placement = None;
 119
 120        Ok(Self {
 121            origin,
 122            logical_size,
 123            fullscreen_restore_bounds,
 124            border_offset,
 125            appearance,
 126            scale_factor,
 127            restore_from_minimized,
 128            min_size,
 129            callbacks,
 130            input_handler,
 131            pending_surrogate,
 132            last_reported_modifiers,
 133            last_reported_capslock,
 134            hovered,
 135            renderer,
 136            click_state,
 137            current_cursor,
 138            nc_button_pressed,
 139            display,
 140            fullscreen,
 141            initial_placement,
 142            hwnd,
 143        })
 144    }
 145
 146    #[inline]
 147    pub(crate) fn is_fullscreen(&self) -> bool {
 148        self.fullscreen.is_some()
 149    }
 150
 151    pub(crate) fn is_maximized(&self) -> bool {
 152        !self.is_fullscreen() && unsafe { IsZoomed(self.hwnd) }.as_bool()
 153    }
 154
 155    fn bounds(&self) -> Bounds<Pixels> {
 156        Bounds {
 157            origin: self.origin,
 158            size: self.logical_size,
 159        }
 160    }
 161
 162    // Calculate the bounds used for saving and whether the window is maximized.
 163    fn calculate_window_bounds(&self) -> (Bounds<Pixels>, bool) {
 164        let placement = unsafe {
 165            let mut placement = WINDOWPLACEMENT {
 166                length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
 167                ..Default::default()
 168            };
 169            GetWindowPlacement(self.hwnd, &mut placement)
 170                .context("failed to get window placement")
 171                .log_err();
 172            placement
 173        };
 174        (
 175            calculate_client_rect(
 176                placement.rcNormalPosition,
 177                self.border_offset,
 178                self.scale_factor,
 179            ),
 180            placement.showCmd == SW_SHOWMAXIMIZED.0 as u32,
 181        )
 182    }
 183
 184    fn window_bounds(&self) -> WindowBounds {
 185        let (bounds, maximized) = self.calculate_window_bounds();
 186
 187        if self.is_fullscreen() {
 188            WindowBounds::Fullscreen(self.fullscreen_restore_bounds)
 189        } else if maximized {
 190            WindowBounds::Maximized(bounds)
 191        } else {
 192            WindowBounds::Windowed(bounds)
 193        }
 194    }
 195
 196    /// get the logical size of the app's drawable area.
 197    ///
 198    /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
 199    /// whether the mouse collides with other elements of GPUI).
 200    fn content_size(&self) -> Size<Pixels> {
 201        self.logical_size
 202    }
 203}
 204
 205impl WindowsWindowInner {
 206    fn new(context: &mut WindowCreateContext, hwnd: HWND, cs: &CREATESTRUCTW) -> Result<Rc<Self>> {
 207        let state = RefCell::new(WindowsWindowState::new(
 208            hwnd,
 209            &context.directx_devices,
 210            cs,
 211            context.current_cursor,
 212            context.display,
 213            context.min_size,
 214            context.appearance,
 215            context.disable_direct_composition,
 216        )?);
 217
 218        Ok(Rc::new_cyclic(|this| Self {
 219            hwnd,
 220            this: this.clone(),
 221            drop_target_helper: context.drop_target_helper.clone(),
 222            state,
 223            handle: context.handle,
 224            hide_title_bar: context.hide_title_bar,
 225            is_movable: context.is_movable,
 226            executor: context.executor.clone(),
 227            windows_version: context.windows_version,
 228            validation_number: context.validation_number,
 229            main_receiver: context.main_receiver.clone(),
 230            platform_window_handle: context.platform_window_handle,
 231            system_settings: RefCell::new(WindowsSystemSettings::new(context.display)),
 232        }))
 233    }
 234
 235    fn toggle_fullscreen(&self) {
 236        let Some(this) = self.this.upgrade() else {
 237            log::error!("Unable to toggle fullscreen: window has been dropped");
 238            return;
 239        };
 240        self.executor
 241            .spawn(async move {
 242                let mut lock = this.state.borrow_mut();
 243                let StyleAndBounds {
 244                    style,
 245                    x,
 246                    y,
 247                    cx,
 248                    cy,
 249                } = if let Some(state) = lock.fullscreen.take() {
 250                    state
 251                } else {
 252                    let (window_bounds, _) = lock.calculate_window_bounds();
 253                    lock.fullscreen_restore_bounds = window_bounds;
 254                    let style = WINDOW_STYLE(unsafe { get_window_long(this.hwnd, GWL_STYLE) } as _);
 255                    let mut rc = RECT::default();
 256                    unsafe { GetWindowRect(this.hwnd, &mut rc) }
 257                        .context("failed to get window rect")
 258                        .log_err();
 259                    let _ = lock.fullscreen.insert(StyleAndBounds {
 260                        style,
 261                        x: rc.left,
 262                        y: rc.top,
 263                        cx: rc.right - rc.left,
 264                        cy: rc.bottom - rc.top,
 265                    });
 266                    let style = style
 267                        & !(WS_THICKFRAME
 268                            | WS_SYSMENU
 269                            | WS_MAXIMIZEBOX
 270                            | WS_MINIMIZEBOX
 271                            | WS_CAPTION);
 272                    let physical_bounds = lock.display.physical_bounds();
 273                    StyleAndBounds {
 274                        style,
 275                        x: physical_bounds.left().0,
 276                        y: physical_bounds.top().0,
 277                        cx: physical_bounds.size.width.0,
 278                        cy: physical_bounds.size.height.0,
 279                    }
 280                };
 281                drop(lock);
 282                unsafe { set_window_long(this.hwnd, GWL_STYLE, style.0 as isize) };
 283                unsafe {
 284                    SetWindowPos(
 285                        this.hwnd,
 286                        None,
 287                        x,
 288                        y,
 289                        cx,
 290                        cy,
 291                        SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER,
 292                    )
 293                }
 294                .log_err();
 295            })
 296            .detach();
 297    }
 298
 299    fn set_window_placement(&self) -> Result<()> {
 300        let Some(open_status) = self.state.borrow_mut().initial_placement.take() else {
 301            return Ok(());
 302        };
 303        match open_status.state {
 304            WindowOpenState::Maximized => unsafe {
 305                SetWindowPlacement(self.hwnd, &open_status.placement)
 306                    .context("failed to set window placement")?;
 307                ShowWindowAsync(self.hwnd, SW_MAXIMIZE).ok()?;
 308            },
 309            WindowOpenState::Fullscreen => {
 310                unsafe {
 311                    SetWindowPlacement(self.hwnd, &open_status.placement)
 312                        .context("failed to set window placement")?
 313                };
 314                self.toggle_fullscreen();
 315            }
 316            WindowOpenState::Windowed => unsafe {
 317                SetWindowPlacement(self.hwnd, &open_status.placement)
 318                    .context("failed to set window placement")?;
 319            },
 320        }
 321        Ok(())
 322    }
 323}
 324
 325#[derive(Default)]
 326pub(crate) struct Callbacks {
 327    pub(crate) request_frame: Option<Box<dyn FnMut(RequestFrameOptions)>>,
 328    pub(crate) input: Option<Box<dyn FnMut(crate::PlatformInput) -> DispatchEventResult>>,
 329    pub(crate) active_status_change: Option<Box<dyn FnMut(bool)>>,
 330    pub(crate) hovered_status_change: Option<Box<dyn FnMut(bool)>>,
 331    pub(crate) resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 332    pub(crate) moved: Option<Box<dyn FnMut()>>,
 333    pub(crate) should_close: Option<Box<dyn FnMut() -> bool>>,
 334    pub(crate) close: Option<Box<dyn FnOnce()>>,
 335    pub(crate) hit_test_window_control: Option<Box<dyn FnMut() -> Option<WindowControlArea>>>,
 336    pub(crate) appearance_changed: Option<Box<dyn FnMut()>>,
 337}
 338
 339struct WindowCreateContext {
 340    inner: Option<Result<Rc<WindowsWindowInner>>>,
 341    handle: AnyWindowHandle,
 342    hide_title_bar: bool,
 343    display: WindowsDisplay,
 344    is_movable: bool,
 345    min_size: Option<Size<Pixels>>,
 346    executor: ForegroundExecutor,
 347    current_cursor: Option<HCURSOR>,
 348    windows_version: WindowsVersion,
 349    drop_target_helper: IDropTargetHelper,
 350    validation_number: usize,
 351    main_receiver: flume::Receiver<Runnable>,
 352    platform_window_handle: HWND,
 353    appearance: WindowAppearance,
 354    disable_direct_composition: bool,
 355    directx_devices: DirectXDevices,
 356}
 357
 358impl WindowsWindow {
 359    pub(crate) fn new(
 360        handle: AnyWindowHandle,
 361        params: WindowParams,
 362        creation_info: WindowCreationInfo,
 363    ) -> Result<Self> {
 364        let WindowCreationInfo {
 365            icon,
 366            executor,
 367            current_cursor,
 368            windows_version,
 369            drop_target_helper,
 370            validation_number,
 371            main_receiver,
 372            platform_window_handle,
 373            disable_direct_composition,
 374            directx_devices,
 375        } = creation_info;
 376        register_window_class(icon);
 377        let hide_title_bar = params
 378            .titlebar
 379            .as_ref()
 380            .map(|titlebar| titlebar.appears_transparent)
 381            .unwrap_or(true);
 382        let window_name = HSTRING::from(
 383            params
 384                .titlebar
 385                .as_ref()
 386                .and_then(|titlebar| titlebar.title.as_ref())
 387                .map(|title| title.as_ref())
 388                .unwrap_or(""),
 389        );
 390
 391        let (mut dwexstyle, dwstyle) = if params.kind == WindowKind::PopUp {
 392            (WS_EX_TOOLWINDOW, WINDOW_STYLE(0x0))
 393        } else {
 394            let mut dwstyle = WS_SYSMENU;
 395
 396            if params.is_resizable {
 397                dwstyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
 398            }
 399
 400            if params.is_minimizable {
 401                dwstyle |= WS_MINIMIZEBOX;
 402            }
 403
 404            (WS_EX_APPWINDOW, dwstyle)
 405        };
 406        if !disable_direct_composition {
 407            dwexstyle |= WS_EX_NOREDIRECTIONBITMAP;
 408        }
 409
 410        let hinstance = get_module_handle();
 411        let display = if let Some(display_id) = params.display_id {
 412            // if we obtain a display_id, then this ID must be valid.
 413            WindowsDisplay::new(display_id).unwrap()
 414        } else {
 415            WindowsDisplay::primary_monitor().unwrap()
 416        };
 417        let appearance = system_appearance().unwrap_or_default();
 418        let mut context = WindowCreateContext {
 419            inner: None,
 420            handle,
 421            hide_title_bar,
 422            display,
 423            is_movable: params.is_movable,
 424            min_size: params.window_min_size,
 425            executor,
 426            current_cursor,
 427            windows_version,
 428            drop_target_helper,
 429            validation_number,
 430            main_receiver,
 431            platform_window_handle,
 432            appearance,
 433            disable_direct_composition,
 434            directx_devices,
 435        };
 436        let creation_result = unsafe {
 437            CreateWindowExW(
 438                dwexstyle,
 439                WINDOW_CLASS_NAME,
 440                &window_name,
 441                dwstyle,
 442                CW_USEDEFAULT,
 443                CW_USEDEFAULT,
 444                CW_USEDEFAULT,
 445                CW_USEDEFAULT,
 446                None,
 447                None,
 448                Some(hinstance.into()),
 449                Some(&context as *const _ as *const _),
 450            )
 451        };
 452
 453        // Failure to create a `WindowsWindowState` can cause window creation to fail,
 454        // so check the inner result first.
 455        let this = context.inner.take().transpose()?;
 456        let hwnd = creation_result?;
 457        let this = this.unwrap();
 458
 459        register_drag_drop(&this)?;
 460        configure_dwm_dark_mode(hwnd, appearance);
 461        this.state.borrow_mut().border_offset.update(hwnd)?;
 462        let placement = retrieve_window_placement(
 463            hwnd,
 464            display,
 465            params.bounds,
 466            this.state.borrow().scale_factor,
 467            this.state.borrow().border_offset,
 468        )?;
 469        if params.show {
 470            unsafe { SetWindowPlacement(hwnd, &placement)? };
 471        } else {
 472            this.state.borrow_mut().initial_placement = Some(WindowOpenStatus {
 473                placement,
 474                state: WindowOpenState::Windowed,
 475            });
 476        }
 477
 478        Ok(Self(this))
 479    }
 480}
 481
 482impl rwh::HasWindowHandle for WindowsWindow {
 483    fn window_handle(&self) -> std::result::Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 484        let raw = rwh::Win32WindowHandle::new(unsafe {
 485            NonZeroIsize::new_unchecked(self.0.hwnd.0 as isize)
 486        })
 487        .into();
 488        Ok(unsafe { rwh::WindowHandle::borrow_raw(raw) })
 489    }
 490}
 491
 492// todo(windows)
 493impl rwh::HasDisplayHandle for WindowsWindow {
 494    fn display_handle(&self) -> std::result::Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 495        unimplemented!()
 496    }
 497}
 498
 499impl Drop for WindowsWindow {
 500    fn drop(&mut self) {
 501        // clone this `Rc` to prevent early release of the pointer
 502        let this = self.0.clone();
 503        self.0
 504            .executor
 505            .spawn(async move {
 506                let handle = this.hwnd;
 507                unsafe {
 508                    RevokeDragDrop(handle).log_err();
 509                    DestroyWindow(handle).log_err();
 510                }
 511            })
 512            .detach();
 513    }
 514}
 515
 516impl PlatformWindow for WindowsWindow {
 517    fn bounds(&self) -> Bounds<Pixels> {
 518        self.0.state.borrow().bounds()
 519    }
 520
 521    fn is_maximized(&self) -> bool {
 522        self.0.state.borrow().is_maximized()
 523    }
 524
 525    fn window_bounds(&self) -> WindowBounds {
 526        self.0.state.borrow().window_bounds()
 527    }
 528
 529    /// get the logical size of the app's drawable area.
 530    ///
 531    /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
 532    /// whether the mouse collides with other elements of GPUI).
 533    fn content_size(&self) -> Size<Pixels> {
 534        self.0.state.borrow().content_size()
 535    }
 536
 537    fn resize(&mut self, size: Size<Pixels>) {
 538        let hwnd = self.0.hwnd;
 539        let bounds =
 540            crate::bounds(self.bounds().origin, size).to_device_pixels(self.scale_factor());
 541        let rect = calculate_window_rect(bounds, self.0.state.borrow().border_offset);
 542
 543        self.0
 544            .executor
 545            .spawn(async move {
 546                unsafe {
 547                    SetWindowPos(
 548                        hwnd,
 549                        None,
 550                        bounds.origin.x.0,
 551                        bounds.origin.y.0,
 552                        rect.right - rect.left,
 553                        rect.bottom - rect.top,
 554                        SWP_NOMOVE,
 555                    )
 556                    .context("unable to set window content size")
 557                    .log_err();
 558                }
 559            })
 560            .detach();
 561    }
 562
 563    fn scale_factor(&self) -> f32 {
 564        self.0.state.borrow().scale_factor
 565    }
 566
 567    fn appearance(&self) -> WindowAppearance {
 568        self.0.state.borrow().appearance
 569    }
 570
 571    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 572        Some(Rc::new(self.0.state.borrow().display))
 573    }
 574
 575    fn mouse_position(&self) -> Point<Pixels> {
 576        let scale_factor = self.scale_factor();
 577        let point = unsafe {
 578            let mut point: POINT = std::mem::zeroed();
 579            GetCursorPos(&mut point)
 580                .context("unable to get cursor position")
 581                .log_err();
 582            ScreenToClient(self.0.hwnd, &mut point).ok().log_err();
 583            point
 584        };
 585        logical_point(point.x as f32, point.y as f32, scale_factor)
 586    }
 587
 588    fn modifiers(&self) -> Modifiers {
 589        current_modifiers()
 590    }
 591
 592    fn capslock(&self) -> Capslock {
 593        current_capslock()
 594    }
 595
 596    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 597        self.0.state.borrow_mut().input_handler = Some(input_handler);
 598    }
 599
 600    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 601        self.0.state.borrow_mut().input_handler.take()
 602    }
 603
 604    fn prompt(
 605        &self,
 606        level: PromptLevel,
 607        msg: &str,
 608        detail: Option<&str>,
 609        answers: &[PromptButton],
 610    ) -> Option<Receiver<usize>> {
 611        let (done_tx, done_rx) = oneshot::channel();
 612        let msg = msg.to_string();
 613        let detail_string = detail.map(|detail| detail.to_string());
 614        let handle = self.0.hwnd;
 615        let answers = answers.to_vec();
 616        self.0
 617            .executor
 618            .spawn(async move {
 619                unsafe {
 620                    let mut config = TASKDIALOGCONFIG::default();
 621                    config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;
 622                    config.hwndParent = handle;
 623                    let title;
 624                    let main_icon;
 625                    match level {
 626                        crate::PromptLevel::Info => {
 627                            title = windows::core::w!("Info");
 628                            main_icon = TD_INFORMATION_ICON;
 629                        }
 630                        crate::PromptLevel::Warning => {
 631                            title = windows::core::w!("Warning");
 632                            main_icon = TD_WARNING_ICON;
 633                        }
 634                        crate::PromptLevel::Critical => {
 635                            title = windows::core::w!("Critical");
 636                            main_icon = TD_ERROR_ICON;
 637                        }
 638                    };
 639                    config.pszWindowTitle = title;
 640                    config.Anonymous1.pszMainIcon = main_icon;
 641                    let instruction = HSTRING::from(msg);
 642                    config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());
 643                    let hints_encoded;
 644                    if let Some(ref hints) = detail_string {
 645                        hints_encoded = HSTRING::from(hints);
 646                        config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());
 647                    };
 648                    let mut button_id_map = Vec::with_capacity(answers.len());
 649                    let mut buttons = Vec::new();
 650                    let mut btn_encoded = Vec::new();
 651                    for (index, btn) in answers.iter().enumerate() {
 652                        let encoded = HSTRING::from(btn.label().as_ref());
 653                        let button_id = match btn {
 654                            PromptButton::Ok(_) => IDOK.0,
 655                            PromptButton::Cancel(_) => IDCANCEL.0,
 656                            // the first few low integer values are reserved for known buttons
 657                            // so for simplicity we just go backwards from -1
 658                            PromptButton::Other(_) => -(index as i32) - 1,
 659                        };
 660                        button_id_map.push(button_id);
 661                        buttons.push(TASKDIALOG_BUTTON {
 662                            nButtonID: button_id,
 663                            pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),
 664                        });
 665                        btn_encoded.push(encoded);
 666                    }
 667                    config.cButtons = buttons.len() as _;
 668                    config.pButtons = buttons.as_ptr();
 669
 670                    config.pfCallback = None;
 671                    let mut res = std::mem::zeroed();
 672                    let _ = TaskDialogIndirect(&config, Some(&mut res), None, None)
 673                        .context("unable to create task dialog")
 674                        .log_err();
 675
 676                    if let Some(clicked) =
 677                        button_id_map.iter().position(|&button_id| button_id == res)
 678                    {
 679                        let _ = done_tx.send(clicked);
 680                    }
 681                }
 682            })
 683            .detach();
 684
 685        Some(done_rx)
 686    }
 687
 688    fn activate(&self) {
 689        let hwnd = self.0.hwnd;
 690        let this = self.0.clone();
 691        self.0
 692            .executor
 693            .spawn(async move {
 694                this.set_window_placement().log_err();
 695
 696                unsafe {
 697                    // If the window is minimized, restore it.
 698                    if IsIconic(hwnd).as_bool() {
 699                        ShowWindowAsync(hwnd, SW_RESTORE).ok().log_err();
 700                    }
 701
 702                    SetActiveWindow(hwnd).log_err();
 703                    SetFocus(Some(hwnd)).log_err();
 704                }
 705
 706                // premium ragebait by windows, this is needed because the window
 707                // must have received an input event to be able to set itself to foreground
 708                // so let's just simulate user input as that seems to be the most reliable way
 709                // some more info: https://gist.github.com/Aetopia/1581b40f00cc0cadc93a0e8ccb65dc8c
 710                // bonus: this bug also doesn't manifest if you have vs attached to the process
 711                let inputs = [
 712                    INPUT {
 713                        r#type: INPUT_KEYBOARD,
 714                        Anonymous: INPUT_0 {
 715                            ki: KEYBDINPUT {
 716                                wVk: VK_MENU,
 717                                dwFlags: KEYBD_EVENT_FLAGS(0),
 718                                ..Default::default()
 719                            },
 720                        },
 721                    },
 722                    INPUT {
 723                        r#type: INPUT_KEYBOARD,
 724                        Anonymous: INPUT_0 {
 725                            ki: KEYBDINPUT {
 726                                wVk: VK_MENU,
 727                                dwFlags: KEYEVENTF_KEYUP,
 728                                ..Default::default()
 729                            },
 730                        },
 731                    },
 732                ];
 733                unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };
 734
 735                // todo(windows)
 736                // crate `windows 0.56` reports true as Err
 737                unsafe { SetForegroundWindow(hwnd).as_bool() };
 738            })
 739            .detach();
 740    }
 741
 742    fn is_active(&self) -> bool {
 743        self.0.hwnd == unsafe { GetActiveWindow() }
 744    }
 745
 746    fn is_hovered(&self) -> bool {
 747        self.0.state.borrow().hovered
 748    }
 749
 750    fn set_title(&mut self, title: &str) {
 751        unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
 752            .inspect_err(|e| log::error!("Set title failed: {e}"))
 753            .ok();
 754    }
 755
 756    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
 757        let hwnd = self.0.hwnd;
 758
 759        match background_appearance {
 760            WindowBackgroundAppearance::Opaque => {
 761                // ACCENT_DISABLED
 762                set_window_composition_attribute(hwnd, None, 0);
 763            }
 764            WindowBackgroundAppearance::Transparent => {
 765                // Use ACCENT_ENABLE_TRANSPARENTGRADIENT for transparent background
 766                set_window_composition_attribute(hwnd, None, 2);
 767            }
 768            WindowBackgroundAppearance::Blurred => {
 769                // Enable acrylic blur
 770                // ACCENT_ENABLE_ACRYLICBLURBEHIND
 771                set_window_composition_attribute(hwnd, Some((0, 0, 0, 0)), 4);
 772            }
 773        }
 774    }
 775
 776    fn minimize(&self) {
 777        unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
 778    }
 779
 780    fn zoom(&self) {
 781        unsafe {
 782            if IsWindowVisible(self.0.hwnd).as_bool() {
 783                ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
 784            } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
 785                status.state = WindowOpenState::Maximized;
 786            }
 787        }
 788    }
 789
 790    fn toggle_fullscreen(&self) {
 791        if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
 792            self.0.toggle_fullscreen();
 793        } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
 794            status.state = WindowOpenState::Fullscreen;
 795        }
 796    }
 797
 798    fn is_fullscreen(&self) -> bool {
 799        self.0.state.borrow().is_fullscreen()
 800    }
 801
 802    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
 803        self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
 804    }
 805
 806    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
 807        self.0.state.borrow_mut().callbacks.input = Some(callback);
 808    }
 809
 810    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 811        self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
 812    }
 813
 814    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 815        self.0.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
 816    }
 817
 818    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 819        self.0.state.borrow_mut().callbacks.resize = Some(callback);
 820    }
 821
 822    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 823        self.0.state.borrow_mut().callbacks.moved = Some(callback);
 824    }
 825
 826    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 827        self.0.state.borrow_mut().callbacks.should_close = Some(callback);
 828    }
 829
 830    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 831        self.0.state.borrow_mut().callbacks.close = Some(callback);
 832    }
 833
 834    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
 835        self.0.state.borrow_mut().callbacks.hit_test_window_control = Some(callback);
 836    }
 837
 838    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 839        self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
 840    }
 841
 842    fn draw(&self, scene: &Scene) {
 843        self.0.state.borrow_mut().renderer.draw(scene).log_err();
 844    }
 845
 846    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 847        self.0.state.borrow().renderer.sprite_atlas()
 848    }
 849
 850    fn get_raw_handle(&self) -> HWND {
 851        self.0.hwnd
 852    }
 853
 854    fn gpu_specs(&self) -> Option<GpuSpecs> {
 855        self.0.state.borrow().renderer.gpu_specs().log_err()
 856    }
 857
 858    fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
 859        // There is no such thing on Windows.
 860    }
 861}
 862
 863#[implement(IDropTarget)]
 864struct WindowsDragDropHandler(pub Rc<WindowsWindowInner>);
 865
 866impl WindowsDragDropHandler {
 867    fn handle_drag_drop(&self, input: PlatformInput) {
 868        let mut lock = self.0.state.borrow_mut();
 869        if let Some(mut func) = lock.callbacks.input.take() {
 870            drop(lock);
 871            func(input);
 872            self.0.state.borrow_mut().callbacks.input = Some(func);
 873        }
 874    }
 875}
 876
 877#[allow(non_snake_case)]
 878impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
 879    fn DragEnter(
 880        &self,
 881        pdataobj: windows::core::Ref<IDataObject>,
 882        _grfkeystate: MODIFIERKEYS_FLAGS,
 883        pt: &POINTL,
 884        pdweffect: *mut DROPEFFECT,
 885    ) -> windows::core::Result<()> {
 886        unsafe {
 887            let idata_obj = pdataobj.ok()?;
 888            let config = FORMATETC {
 889                cfFormat: CF_HDROP.0,
 890                ptd: std::ptr::null_mut() as _,
 891                dwAspect: DVASPECT_CONTENT.0,
 892                lindex: -1,
 893                tymed: TYMED_HGLOBAL.0 as _,
 894            };
 895            let cursor_position = POINT { x: pt.x, y: pt.y };
 896            if idata_obj.QueryGetData(&config as _) == S_OK {
 897                *pdweffect = DROPEFFECT_COPY;
 898                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 899                    return Ok(());
 900                };
 901                if idata.u.hGlobal.is_invalid() {
 902                    return Ok(());
 903                }
 904                let hdrop = HDROP(idata.u.hGlobal.0);
 905                let mut paths = SmallVec::<[PathBuf; 2]>::new();
 906                with_file_names(hdrop, |file_name| {
 907                    if let Some(path) = PathBuf::from_str(&file_name).log_err() {
 908                        paths.push(path);
 909                    }
 910                });
 911                ReleaseStgMedium(&mut idata);
 912                let mut cursor_position = cursor_position;
 913                ScreenToClient(self.0.hwnd, &mut cursor_position)
 914                    .ok()
 915                    .log_err();
 916                let scale_factor = self.0.state.borrow().scale_factor;
 917                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 918                    position: logical_point(
 919                        cursor_position.x as f32,
 920                        cursor_position.y as f32,
 921                        scale_factor,
 922                    ),
 923                    paths: ExternalPaths(paths),
 924                });
 925                self.handle_drag_drop(input);
 926            } else {
 927                *pdweffect = DROPEFFECT_NONE;
 928            }
 929            self.0
 930                .drop_target_helper
 931                .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)
 932                .log_err();
 933        }
 934        Ok(())
 935    }
 936
 937    fn DragOver(
 938        &self,
 939        _grfkeystate: MODIFIERKEYS_FLAGS,
 940        pt: &POINTL,
 941        pdweffect: *mut DROPEFFECT,
 942    ) -> windows::core::Result<()> {
 943        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 944        unsafe {
 945            *pdweffect = DROPEFFECT_COPY;
 946            self.0
 947                .drop_target_helper
 948                .DragOver(&cursor_position, *pdweffect)
 949                .log_err();
 950            ScreenToClient(self.0.hwnd, &mut cursor_position)
 951                .ok()
 952                .log_err();
 953        }
 954        let scale_factor = self.0.state.borrow().scale_factor;
 955        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
 956            position: logical_point(
 957                cursor_position.x as f32,
 958                cursor_position.y as f32,
 959                scale_factor,
 960            ),
 961        });
 962        self.handle_drag_drop(input);
 963
 964        Ok(())
 965    }
 966
 967    fn DragLeave(&self) -> windows::core::Result<()> {
 968        unsafe {
 969            self.0.drop_target_helper.DragLeave().log_err();
 970        }
 971        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
 972        self.handle_drag_drop(input);
 973
 974        Ok(())
 975    }
 976
 977    fn Drop(
 978        &self,
 979        pdataobj: windows::core::Ref<IDataObject>,
 980        _grfkeystate: MODIFIERKEYS_FLAGS,
 981        pt: &POINTL,
 982        pdweffect: *mut DROPEFFECT,
 983    ) -> windows::core::Result<()> {
 984        let idata_obj = pdataobj.ok()?;
 985        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 986        unsafe {
 987            *pdweffect = DROPEFFECT_COPY;
 988            self.0
 989                .drop_target_helper
 990                .Drop(idata_obj, &cursor_position, *pdweffect)
 991                .log_err();
 992            ScreenToClient(self.0.hwnd, &mut cursor_position)
 993                .ok()
 994                .log_err();
 995        }
 996        let scale_factor = self.0.state.borrow().scale_factor;
 997        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
 998            position: logical_point(
 999                cursor_position.x as f32,
1000                cursor_position.y as f32,
1001                scale_factor,
1002            ),
1003        });
1004        self.handle_drag_drop(input);
1005
1006        Ok(())
1007    }
1008}
1009
1010#[derive(Debug, Clone, Copy)]
1011pub(crate) struct ClickState {
1012    button: MouseButton,
1013    last_click: Instant,
1014    last_position: Point<DevicePixels>,
1015    double_click_spatial_tolerance_width: i32,
1016    double_click_spatial_tolerance_height: i32,
1017    double_click_interval: Duration,
1018    pub(crate) current_count: usize,
1019}
1020
1021impl ClickState {
1022    pub fn new() -> Self {
1023        let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
1024        let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
1025        let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
1026
1027        ClickState {
1028            button: MouseButton::Left,
1029            last_click: Instant::now(),
1030            last_position: Point::default(),
1031            double_click_spatial_tolerance_width,
1032            double_click_spatial_tolerance_height,
1033            double_click_interval,
1034            current_count: 0,
1035        }
1036    }
1037
1038    /// update self and return the needed click count
1039    pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
1040        if self.button == button && self.is_double_click(new_position) {
1041            self.current_count += 1;
1042        } else {
1043            self.current_count = 1;
1044        }
1045        self.last_click = Instant::now();
1046        self.last_position = new_position;
1047        self.button = button;
1048
1049        self.current_count
1050    }
1051
1052    pub fn system_update(&mut self, wparam: usize) {
1053        match wparam {
1054            // SPI_SETDOUBLECLKWIDTH
1055            29 => {
1056                self.double_click_spatial_tolerance_width =
1057                    unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }
1058            }
1059            // SPI_SETDOUBLECLKHEIGHT
1060            30 => {
1061                self.double_click_spatial_tolerance_height =
1062                    unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }
1063            }
1064            // SPI_SETDOUBLECLICKTIME
1065            32 => {
1066                self.double_click_interval =
1067                    Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)
1068            }
1069            _ => {}
1070        }
1071    }
1072
1073    #[inline]
1074    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
1075        let diff = self.last_position - new_position;
1076
1077        self.last_click.elapsed() < self.double_click_interval
1078            && diff.x.0.abs() <= self.double_click_spatial_tolerance_width
1079            && diff.y.0.abs() <= self.double_click_spatial_tolerance_height
1080    }
1081}
1082
1083struct StyleAndBounds {
1084    style: WINDOW_STYLE,
1085    x: i32,
1086    y: i32,
1087    cx: i32,
1088    cy: i32,
1089}
1090
1091#[repr(C)]
1092struct WINDOWCOMPOSITIONATTRIBDATA {
1093    attrib: u32,
1094    pv_data: *mut std::ffi::c_void,
1095    cb_data: usize,
1096}
1097
1098#[repr(C)]
1099struct AccentPolicy {
1100    accent_state: u32,
1101    accent_flags: u32,
1102    gradient_color: u32,
1103    animation_id: u32,
1104}
1105
1106type Color = (u8, u8, u8, u8);
1107
1108#[derive(Debug, Default, Clone, Copy)]
1109pub(crate) struct WindowBorderOffset {
1110    pub(crate) width_offset: i32,
1111    pub(crate) height_offset: i32,
1112}
1113
1114impl WindowBorderOffset {
1115    pub(crate) fn update(&mut self, hwnd: HWND) -> anyhow::Result<()> {
1116        let window_rect = unsafe {
1117            let mut rect = std::mem::zeroed();
1118            GetWindowRect(hwnd, &mut rect)?;
1119            rect
1120        };
1121        let client_rect = unsafe {
1122            let mut rect = std::mem::zeroed();
1123            GetClientRect(hwnd, &mut rect)?;
1124            rect
1125        };
1126        self.width_offset =
1127            (window_rect.right - window_rect.left) - (client_rect.right - client_rect.left);
1128        self.height_offset =
1129            (window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top);
1130        Ok(())
1131    }
1132}
1133
1134struct WindowOpenStatus {
1135    placement: WINDOWPLACEMENT,
1136    state: WindowOpenState,
1137}
1138
1139enum WindowOpenState {
1140    Maximized,
1141    Fullscreen,
1142    Windowed,
1143}
1144
1145const WINDOW_CLASS_NAME: PCWSTR = w!("Zed::Window");
1146
1147fn register_window_class(icon_handle: HICON) {
1148    static ONCE: Once = Once::new();
1149    ONCE.call_once(|| {
1150        let wc = WNDCLASSW {
1151            lpfnWndProc: Some(window_procedure),
1152            hIcon: icon_handle,
1153            lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
1154            style: CS_HREDRAW | CS_VREDRAW,
1155            hInstance: get_module_handle().into(),
1156            hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1157            ..Default::default()
1158        };
1159        unsafe { RegisterClassW(&wc) };
1160    });
1161}
1162
1163unsafe extern "system" fn window_procedure(
1164    hwnd: HWND,
1165    msg: u32,
1166    wparam: WPARAM,
1167    lparam: LPARAM,
1168) -> LRESULT {
1169    if msg == WM_NCCREATE {
1170        let window_params = lparam.0 as *const CREATESTRUCTW;
1171        let window_params = unsafe { &*window_params };
1172        let window_creation_context = window_params.lpCreateParams as *mut WindowCreateContext;
1173        let window_creation_context = unsafe { &mut *window_creation_context };
1174        return match WindowsWindowInner::new(window_creation_context, hwnd, window_params) {
1175            Ok(window_state) => {
1176                let weak = Box::new(Rc::downgrade(&window_state));
1177                unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1178                window_creation_context.inner = Some(Ok(window_state));
1179                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1180            }
1181            Err(error) => {
1182                window_creation_context.inner = Some(Err(error));
1183                LRESULT(0)
1184            }
1185        };
1186    }
1187
1188    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1189    if ptr.is_null() {
1190        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1191    }
1192    let inner = unsafe { &*ptr };
1193    let result = if let Some(inner) = inner.upgrade() {
1194        inner.handle_msg(hwnd, msg, wparam, lparam)
1195    } else {
1196        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1197    };
1198
1199    if msg == WM_NCDESTROY {
1200        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1201        unsafe { drop(Box::from_raw(ptr)) };
1202    }
1203
1204    result
1205}
1206
1207pub(crate) fn window_from_hwnd(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
1208    if hwnd.is_invalid() {
1209        return None;
1210    }
1211
1212    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1213    if !ptr.is_null() {
1214        let inner = unsafe { &*ptr };
1215        inner.upgrade()
1216    } else {
1217        None
1218    }
1219}
1220
1221fn get_module_handle() -> HMODULE {
1222    unsafe {
1223        let mut h_module = std::mem::zeroed();
1224        GetModuleHandleExW(
1225            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1226            windows::core::w!("ZedModule"),
1227            &mut h_module,
1228        )
1229        .expect("Unable to get module handle"); // this should never fail
1230
1231        h_module
1232    }
1233}
1234
1235fn register_drag_drop(window: &Rc<WindowsWindowInner>) -> Result<()> {
1236    let window_handle = window.hwnd;
1237    let handler = WindowsDragDropHandler(window.clone());
1238    // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1239    // we call `RevokeDragDrop`.
1240    // So, it's safe to drop it here.
1241    let drag_drop_handler: IDropTarget = handler.into();
1242    unsafe {
1243        RegisterDragDrop(window_handle, &drag_drop_handler)
1244            .context("unable to register drag-drop event")?;
1245    }
1246    Ok(())
1247}
1248
1249fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: WindowBorderOffset) -> RECT {
1250    // NOTE:
1251    // The reason we're not using `AdjustWindowRectEx()` here is
1252    // that the size reported by this function is incorrect.
1253    // You can test it, and there are similar discussions online.
1254    // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1255    //
1256    // So we manually calculate these values here.
1257    let mut rect = RECT {
1258        left: bounds.left().0,
1259        top: bounds.top().0,
1260        right: bounds.right().0,
1261        bottom: bounds.bottom().0,
1262    };
1263    let left_offset = border_offset.width_offset / 2;
1264    let top_offset = border_offset.height_offset / 2;
1265    let right_offset = border_offset.width_offset - left_offset;
1266    let bottom_offset = border_offset.height_offset - top_offset;
1267    rect.left -= left_offset;
1268    rect.top -= top_offset;
1269    rect.right += right_offset;
1270    rect.bottom += bottom_offset;
1271    rect
1272}
1273
1274fn calculate_client_rect(
1275    rect: RECT,
1276    border_offset: WindowBorderOffset,
1277    scale_factor: f32,
1278) -> Bounds<Pixels> {
1279    let left_offset = border_offset.width_offset / 2;
1280    let top_offset = border_offset.height_offset / 2;
1281    let right_offset = border_offset.width_offset - left_offset;
1282    let bottom_offset = border_offset.height_offset - top_offset;
1283    let left = rect.left + left_offset;
1284    let top = rect.top + top_offset;
1285    let right = rect.right - right_offset;
1286    let bottom = rect.bottom - bottom_offset;
1287    let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1288    Bounds {
1289        origin: logical_point(left as f32, top as f32, scale_factor),
1290        size: physical_size.to_pixels(scale_factor),
1291    }
1292}
1293
1294fn retrieve_window_placement(
1295    hwnd: HWND,
1296    display: WindowsDisplay,
1297    initial_bounds: Bounds<Pixels>,
1298    scale_factor: f32,
1299    border_offset: WindowBorderOffset,
1300) -> Result<WINDOWPLACEMENT> {
1301    let mut placement = WINDOWPLACEMENT {
1302        length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1303        ..Default::default()
1304    };
1305    unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1306    // the bounds may be not inside the display
1307    let bounds = if display.check_given_bounds(initial_bounds) {
1308        initial_bounds
1309    } else {
1310        display.default_bounds()
1311    };
1312    let bounds = bounds.to_device_pixels(scale_factor);
1313    placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1314    Ok(placement)
1315}
1316
1317fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1318    let mut version = unsafe { std::mem::zeroed() };
1319    let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1320    if !status.is_ok() || version.dwBuildNumber < 17763 {
1321        return;
1322    }
1323
1324    unsafe {
1325        type SetWindowCompositionAttributeType =
1326            unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1327        let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1328        if let Some(user32) = GetModuleHandleA(module_name)
1329            .context("Unable to get user32.dll handle")
1330            .log_err()
1331        {
1332            let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1333            let set_window_composition_attribute: SetWindowCompositionAttributeType =
1334                std::mem::transmute(GetProcAddress(user32, func_name));
1335            let mut color = color.unwrap_or_default();
1336            let is_acrylic = state == 4;
1337            if is_acrylic && color.3 == 0 {
1338                color.3 = 1;
1339            }
1340            let accent = AccentPolicy {
1341                accent_state: state,
1342                accent_flags: if is_acrylic { 0 } else { 2 },
1343                gradient_color: (color.0 as u32)
1344                    | ((color.1 as u32) << 8)
1345                    | ((color.2 as u32) << 16)
1346                    | ((color.3 as u32) << 24),
1347                animation_id: 0,
1348            };
1349            let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1350                attrib: 0x13,
1351                pv_data: &accent as *const _ as *mut _,
1352                cb_data: std::mem::size_of::<AccentPolicy>(),
1353            };
1354            let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1355        }
1356    }
1357}
1358
1359#[cfg(test)]
1360mod tests {
1361    use super::ClickState;
1362    use crate::{DevicePixels, MouseButton, point};
1363    use std::time::Duration;
1364
1365    #[test]
1366    fn test_double_click_interval() {
1367        let mut state = ClickState::new();
1368        assert_eq!(
1369            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1370            1
1371        );
1372        assert_eq!(
1373            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1374            1
1375        );
1376        assert_eq!(
1377            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1378            1
1379        );
1380        assert_eq!(
1381            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1382            2
1383        );
1384        state.last_click -= Duration::from_millis(700);
1385        assert_eq!(
1386            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1387            1
1388        );
1389    }
1390
1391    #[test]
1392    fn test_double_click_spatial_tolerance() {
1393        let mut state = ClickState::new();
1394        assert_eq!(
1395            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1396            1
1397        );
1398        assert_eq!(
1399            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1400            2
1401        );
1402        assert_eq!(
1403            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1404            1
1405        );
1406        assert_eq!(
1407            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1408            1
1409        );
1410    }
1411}