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