window.rs

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