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