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