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