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