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