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