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