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