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;
  15use futures::channel::oneshot::{self, Receiver};
  16use itertools::Itertools;
  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::BladeRenderer;
  30use crate::*;
  31
  32pub(crate) struct WindowsWindow(pub Rc<WindowsWindowStatePtr>);
  33
  34pub struct WindowsWindowState {
  35    pub origin: Point<DevicePixels>,
  36    pub physical_size: Size<DevicePixels>,
  37    pub fullscreen_restore_bounds: Bounds<DevicePixels>,
  38    pub scale_factor: f32,
  39
  40    pub callbacks: Callbacks,
  41    pub input_handler: Option<PlatformInputHandler>,
  42
  43    pub renderer: BladeRenderer,
  44
  45    pub click_state: ClickState,
  46    pub mouse_wheel_settings: MouseWheelSettings,
  47    pub current_cursor: HCURSOR,
  48
  49    pub display: WindowsDisplay,
  50    fullscreen: Option<StyleAndBounds>,
  51    hwnd: HWND,
  52}
  53
  54pub(crate) struct WindowsWindowStatePtr {
  55    hwnd: HWND,
  56    pub(crate) state: RefCell<WindowsWindowState>,
  57    pub(crate) handle: AnyWindowHandle,
  58    pub(crate) hide_title_bar: bool,
  59    pub(crate) executor: ForegroundExecutor,
  60}
  61
  62impl WindowsWindowState {
  63    fn new(
  64        hwnd: HWND,
  65        transparent: bool,
  66        cs: &CREATESTRUCTW,
  67        mouse_wheel_settings: MouseWheelSettings,
  68        current_cursor: HCURSOR,
  69        display: WindowsDisplay,
  70    ) -> Self {
  71        let origin = point(cs.x.into(), cs.y.into());
  72        let physical_size = size(cs.cx.into(), cs.cy.into());
  73        let fullscreen_restore_bounds = Bounds {
  74            origin,
  75            size: physical_size,
  76        };
  77        let scale_factor = {
  78            let monitor_dpi = unsafe { GetDpiForWindow(hwnd) } as f32;
  79            monitor_dpi / USER_DEFAULT_SCREEN_DPI as f32
  80        };
  81        let renderer = windows_renderer::windows_renderer(hwnd, transparent);
  82        let callbacks = Callbacks::default();
  83        let input_handler = None;
  84        let click_state = ClickState::new();
  85        let fullscreen = None;
  86
  87        Self {
  88            origin,
  89            physical_size,
  90            fullscreen_restore_bounds,
  91            scale_factor,
  92            callbacks,
  93            input_handler,
  94            renderer,
  95            click_state,
  96            mouse_wheel_settings,
  97            current_cursor,
  98            display,
  99            fullscreen,
 100            hwnd,
 101        }
 102    }
 103
 104    #[inline]
 105    pub(crate) fn is_fullscreen(&self) -> bool {
 106        self.fullscreen.is_some()
 107    }
 108
 109    pub(crate) fn is_maximized(&self) -> bool {
 110        !self.is_fullscreen() && unsafe { IsZoomed(self.hwnd) }.as_bool()
 111    }
 112
 113    fn bounds(&self) -> Bounds<DevicePixels> {
 114        Bounds {
 115            origin: self.origin,
 116            size: self.physical_size,
 117        }
 118    }
 119
 120    fn window_bounds(&self) -> WindowBounds {
 121        let placement = unsafe {
 122            let mut placement = WINDOWPLACEMENT {
 123                length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
 124                ..Default::default()
 125            };
 126            GetWindowPlacement(self.hwnd, &mut placement).log_err();
 127            placement
 128        };
 129        let bounds = Bounds {
 130            origin: point(
 131                DevicePixels(placement.rcNormalPosition.left),
 132                DevicePixels(placement.rcNormalPosition.top),
 133            ),
 134            size: size(
 135                DevicePixels(placement.rcNormalPosition.right - placement.rcNormalPosition.left),
 136                DevicePixels(placement.rcNormalPosition.bottom - placement.rcNormalPosition.top),
 137            ),
 138        };
 139
 140        if self.is_fullscreen() {
 141            WindowBounds::Fullscreen(self.fullscreen_restore_bounds)
 142        } else if placement.showCmd == SW_SHOWMAXIMIZED.0 as u32 {
 143            WindowBounds::Maximized(bounds)
 144        } else {
 145            WindowBounds::Windowed(bounds)
 146        }
 147    }
 148
 149    /// get the logical size of the app's drawable area.
 150    ///
 151    /// Currently, GPUI uses logical size of the app to handle mouse interactions (such as
 152    /// whether the mouse collides with other elements of GPUI).
 153    fn content_size(&self) -> Size<Pixels> {
 154        logical_size(self.physical_size, self.scale_factor)
 155    }
 156
 157    fn title_bar_padding(&self) -> Pixels {
 158        // using USER_DEFAULT_SCREEN_DPI because GPUI handles the scale with the scale factor
 159        let padding = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, USER_DEFAULT_SCREEN_DPI) };
 160        px(padding as f32)
 161    }
 162
 163    fn title_bar_top_offset(&self) -> Pixels {
 164        if self.is_maximized() {
 165            self.title_bar_padding() * 2
 166        } else {
 167            px(0.)
 168        }
 169    }
 170
 171    fn title_bar_height(&self) -> Pixels {
 172        // todo(windows) this is hard set to match the ui title bar
 173        //               in the future the ui title bar component will report the size
 174        px(32.) + self.title_bar_top_offset()
 175    }
 176
 177    pub(crate) fn caption_button_width(&self) -> Pixels {
 178        // todo(windows) this is hard set to match the ui title bar
 179        //               in the future the ui title bar component will report the size
 180        px(36.)
 181    }
 182
 183    pub(crate) fn get_titlebar_rect(&self) -> anyhow::Result<RECT> {
 184        let height = self.title_bar_height();
 185        let mut rect = RECT::default();
 186        unsafe { GetClientRect(self.hwnd, &mut rect) }?;
 187        rect.bottom = rect.top + ((height.0 * self.scale_factor).round() as i32);
 188        Ok(rect)
 189    }
 190}
 191
 192impl WindowsWindowStatePtr {
 193    fn new(context: &WindowCreateContext, hwnd: HWND, cs: &CREATESTRUCTW) -> Rc<Self> {
 194        let state = RefCell::new(WindowsWindowState::new(
 195            hwnd,
 196            context.transparent,
 197            cs,
 198            context.mouse_wheel_settings,
 199            context.current_cursor,
 200            context.display,
 201        ));
 202
 203        Rc::new(Self {
 204            state,
 205            hwnd,
 206            handle: context.handle,
 207            hide_title_bar: context.hide_title_bar,
 208            executor: context.executor.clone(),
 209        })
 210    }
 211}
 212
 213#[derive(Default)]
 214pub(crate) struct Callbacks {
 215    pub(crate) request_frame: Option<Box<dyn FnMut()>>,
 216    pub(crate) input: Option<Box<dyn FnMut(crate::PlatformInput) -> DispatchEventResult>>,
 217    pub(crate) active_status_change: Option<Box<dyn FnMut(bool)>>,
 218    pub(crate) resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 219    pub(crate) moved: Option<Box<dyn FnMut()>>,
 220    pub(crate) should_close: Option<Box<dyn FnMut() -> bool>>,
 221    pub(crate) close: Option<Box<dyn FnOnce()>>,
 222    pub(crate) appearance_changed: Option<Box<dyn FnMut()>>,
 223}
 224
 225struct WindowCreateContext {
 226    inner: Option<Rc<WindowsWindowStatePtr>>,
 227    handle: AnyWindowHandle,
 228    hide_title_bar: bool,
 229    display: WindowsDisplay,
 230    transparent: bool,
 231    executor: ForegroundExecutor,
 232    mouse_wheel_settings: MouseWheelSettings,
 233    current_cursor: HCURSOR,
 234}
 235
 236impl WindowsWindow {
 237    pub(crate) fn new(
 238        handle: AnyWindowHandle,
 239        params: WindowParams,
 240        icon: HICON,
 241        executor: ForegroundExecutor,
 242        mouse_wheel_settings: MouseWheelSettings,
 243        current_cursor: HCURSOR,
 244    ) -> Self {
 245        let classname = register_wnd_class(icon);
 246        let hide_title_bar = params
 247            .titlebar
 248            .as_ref()
 249            .map(|titlebar| titlebar.appears_transparent)
 250            .unwrap_or(false);
 251        let windowname = HSTRING::from(
 252            params
 253                .titlebar
 254                .as_ref()
 255                .and_then(|titlebar| titlebar.title.as_ref())
 256                .map(|title| title.as_ref())
 257                .unwrap_or(""),
 258        );
 259        let dwstyle = WS_THICKFRAME | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX;
 260        let hinstance = get_module_handle();
 261        let mut context = WindowCreateContext {
 262            inner: None,
 263            handle,
 264            hide_title_bar,
 265            // todo(windows) move window to target monitor
 266            // options.display_id
 267            display: WindowsDisplay::primary_monitor().unwrap(),
 268            transparent: params.window_background != WindowBackgroundAppearance::Opaque,
 269            executor,
 270            mouse_wheel_settings,
 271            current_cursor,
 272        };
 273        let lpparam = Some(&context as *const _ as *const _);
 274        let raw_hwnd = unsafe {
 275            CreateWindowExW(
 276                WS_EX_APPWINDOW,
 277                classname,
 278                &windowname,
 279                dwstyle,
 280                CW_USEDEFAULT,
 281                CW_USEDEFAULT,
 282                CW_USEDEFAULT,
 283                CW_USEDEFAULT,
 284                None,
 285                None,
 286                hinstance,
 287                lpparam,
 288            )
 289        };
 290        let state_ptr = Rc::clone(context.inner.as_ref().unwrap());
 291        register_drag_drop(state_ptr.clone());
 292        let wnd = Self(state_ptr);
 293
 294        unsafe {
 295            let mut placement = WINDOWPLACEMENT {
 296                length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
 297                ..Default::default()
 298            };
 299            GetWindowPlacement(raw_hwnd, &mut placement).log_err();
 300            placement.rcNormalPosition.left = params.bounds.left().0;
 301            placement.rcNormalPosition.right = params.bounds.right().0;
 302            placement.rcNormalPosition.top = params.bounds.top().0;
 303            placement.rcNormalPosition.bottom = params.bounds.bottom().0;
 304            SetWindowPlacement(raw_hwnd, &placement).log_err();
 305        }
 306        unsafe { ShowWindow(raw_hwnd, SW_SHOW) };
 307
 308        wnd
 309    }
 310}
 311
 312impl rwh::HasWindowHandle for WindowsWindow {
 313    fn window_handle(&self) -> std::result::Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 314        let raw =
 315            rwh::Win32WindowHandle::new(unsafe { NonZeroIsize::new_unchecked(self.0.hwnd.0) })
 316                .into();
 317        Ok(unsafe { rwh::WindowHandle::borrow_raw(raw) })
 318    }
 319}
 320
 321// todo(windows)
 322impl rwh::HasDisplayHandle for WindowsWindow {
 323    fn display_handle(&self) -> std::result::Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 324        unimplemented!()
 325    }
 326}
 327
 328impl Drop for WindowsWindow {
 329    fn drop(&mut self) {
 330        self.0.state.borrow_mut().renderer.destroy();
 331        // clone this `Rc` to prevent early release of the pointer
 332        let this = self.0.clone();
 333        self.0
 334            .executor
 335            .spawn(async move {
 336                let handle = this.hwnd;
 337                unsafe {
 338                    RevokeDragDrop(handle).log_err();
 339                    DestroyWindow(handle).log_err();
 340                }
 341            })
 342            .detach();
 343    }
 344}
 345
 346impl PlatformWindow for WindowsWindow {
 347    fn bounds(&self) -> Bounds<DevicePixels> {
 348        self.0.state.borrow().bounds()
 349    }
 350
 351    fn is_maximized(&self) -> bool {
 352        self.0.state.borrow().is_maximized()
 353    }
 354
 355    fn window_bounds(&self) -> WindowBounds {
 356        self.0.state.borrow().window_bounds()
 357    }
 358
 359    /// get the logical size of the app's drawable area.
 360    ///
 361    /// Currently, GPUI uses logical size of the app to handle mouse interactions (such as
 362    /// whether the mouse collides with other elements of GPUI).
 363    fn content_size(&self) -> Size<Pixels> {
 364        self.0.state.borrow().content_size()
 365    }
 366
 367    fn scale_factor(&self) -> f32 {
 368        self.0.state.borrow().scale_factor
 369    }
 370
 371    // todo(windows)
 372    fn appearance(&self) -> WindowAppearance {
 373        WindowAppearance::Dark
 374    }
 375
 376    fn display(&self) -> Rc<dyn PlatformDisplay> {
 377        Rc::new(self.0.state.borrow().display)
 378    }
 379
 380    fn mouse_position(&self) -> Point<Pixels> {
 381        let scale_factor = self.scale_factor();
 382        let point = unsafe {
 383            let mut point: POINT = std::mem::zeroed();
 384            GetCursorPos(&mut point)
 385                .context("unable to get cursor position")
 386                .log_err();
 387            ScreenToClient(self.0.hwnd, &mut point);
 388            point
 389        };
 390        logical_point(point.x as f32, point.y as f32, scale_factor)
 391    }
 392
 393    // todo(windows)
 394    fn modifiers(&self) -> Modifiers {
 395        Modifiers::none()
 396    }
 397
 398    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 399        self.0.state.borrow_mut().input_handler = Some(input_handler);
 400    }
 401
 402    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 403        self.0.state.borrow_mut().input_handler.take()
 404    }
 405
 406    fn prompt(
 407        &self,
 408        level: PromptLevel,
 409        msg: &str,
 410        detail: Option<&str>,
 411        answers: &[&str],
 412    ) -> Option<Receiver<usize>> {
 413        let (done_tx, done_rx) = oneshot::channel();
 414        let msg = msg.to_string();
 415        let detail_string = match detail {
 416            Some(info) => Some(info.to_string()),
 417            None => None,
 418        };
 419        let answers = answers.iter().map(|s| s.to_string()).collect::<Vec<_>>();
 420        let handle = self.0.hwnd;
 421        self.0
 422            .executor
 423            .spawn(async move {
 424                unsafe {
 425                    let mut config;
 426                    config = std::mem::zeroed::<TASKDIALOGCONFIG>();
 427                    config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;
 428                    config.hwndParent = handle;
 429                    let title;
 430                    let main_icon;
 431                    match level {
 432                        crate::PromptLevel::Info => {
 433                            title = windows::core::w!("Info");
 434                            main_icon = TD_INFORMATION_ICON;
 435                        }
 436                        crate::PromptLevel::Warning => {
 437                            title = windows::core::w!("Warning");
 438                            main_icon = TD_WARNING_ICON;
 439                        }
 440                        crate::PromptLevel::Critical => {
 441                            title = windows::core::w!("Critical");
 442                            main_icon = TD_ERROR_ICON;
 443                        }
 444                    };
 445                    config.pszWindowTitle = title;
 446                    config.Anonymous1.pszMainIcon = main_icon;
 447                    let instruction = msg.encode_utf16().chain(Some(0)).collect_vec();
 448                    config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());
 449                    let hints_encoded;
 450                    if let Some(ref hints) = detail_string {
 451                        hints_encoded = hints.encode_utf16().chain(Some(0)).collect_vec();
 452                        config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());
 453                    };
 454                    let mut buttons = Vec::new();
 455                    let mut btn_encoded = Vec::new();
 456                    for (index, btn_string) in answers.iter().enumerate() {
 457                        let encoded = btn_string.encode_utf16().chain(Some(0)).collect_vec();
 458                        buttons.push(TASKDIALOG_BUTTON {
 459                            nButtonID: index as _,
 460                            pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),
 461                        });
 462                        btn_encoded.push(encoded);
 463                    }
 464                    config.cButtons = buttons.len() as _;
 465                    config.pButtons = buttons.as_ptr();
 466
 467                    config.pfCallback = None;
 468                    let mut res = std::mem::zeroed();
 469                    let _ = TaskDialogIndirect(&config, Some(&mut res), None, None)
 470                        .inspect_err(|e| log::error!("unable to create task dialog: {}", e));
 471
 472                    let _ = done_tx.send(res as usize);
 473                }
 474            })
 475            .detach();
 476
 477        Some(done_rx)
 478    }
 479
 480    fn activate(&self) {
 481        let hwnd = self.0.hwnd;
 482        unsafe { SetActiveWindow(hwnd) };
 483        unsafe { SetFocus(hwnd) };
 484        unsafe { SetForegroundWindow(hwnd) };
 485    }
 486
 487    fn is_active(&self) -> bool {
 488        self.0.hwnd == unsafe { GetActiveWindow() }
 489    }
 490
 491    fn set_title(&mut self, title: &str) {
 492        unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
 493            .inspect_err(|e| log::error!("Set title failed: {e}"))
 494            .ok();
 495    }
 496
 497    fn set_app_id(&mut self, _app_id: &str) {}
 498
 499    fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
 500        self.0
 501            .state
 502            .borrow_mut()
 503            .renderer
 504            .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
 505    }
 506
 507    // todo(windows)
 508    fn set_edited(&mut self, _edited: bool) {}
 509
 510    // todo(windows)
 511    fn show_character_palette(&self) {}
 512
 513    fn minimize(&self) {
 514        unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE) };
 515    }
 516
 517    fn zoom(&self) {
 518        unsafe { ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE) };
 519    }
 520
 521    fn toggle_fullscreen(&self) {
 522        let state_ptr = self.0.clone();
 523        self.0
 524            .executor
 525            .spawn(async move {
 526                let mut lock = state_ptr.state.borrow_mut();
 527                lock.fullscreen_restore_bounds = Bounds {
 528                    origin: lock.origin,
 529                    size: lock.physical_size,
 530                };
 531                let StyleAndBounds {
 532                    style,
 533                    x,
 534                    y,
 535                    cx,
 536                    cy,
 537                } = if let Some(state) = lock.fullscreen.take() {
 538                    state
 539                } else {
 540                    let style =
 541                        WINDOW_STYLE(unsafe { get_window_long(state_ptr.hwnd, GWL_STYLE) } as _);
 542                    let mut rc = RECT::default();
 543                    unsafe { GetWindowRect(state_ptr.hwnd, &mut rc) }.log_err();
 544                    let _ = lock.fullscreen.insert(StyleAndBounds {
 545                        style,
 546                        x: rc.left,
 547                        y: rc.top,
 548                        cx: rc.right - rc.left,
 549                        cy: rc.bottom - rc.top,
 550                    });
 551                    let style = style
 552                        & !(WS_THICKFRAME
 553                            | WS_SYSMENU
 554                            | WS_MAXIMIZEBOX
 555                            | WS_MINIMIZEBOX
 556                            | WS_CAPTION);
 557                    let bounds = lock.display.bounds();
 558                    StyleAndBounds {
 559                        style,
 560                        x: bounds.left().0,
 561                        y: bounds.top().0,
 562                        cx: bounds.size.width.0,
 563                        cy: bounds.size.height.0,
 564                    }
 565                };
 566                drop(lock);
 567                unsafe { set_window_long(state_ptr.hwnd, GWL_STYLE, style.0 as isize) };
 568                unsafe {
 569                    SetWindowPos(
 570                        state_ptr.hwnd,
 571                        HWND::default(),
 572                        x,
 573                        y,
 574                        cx,
 575                        cy,
 576                        SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER,
 577                    )
 578                }
 579                .log_err();
 580            })
 581            .detach();
 582    }
 583
 584    fn is_fullscreen(&self) -> bool {
 585        self.0.state.borrow().is_fullscreen()
 586    }
 587
 588    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
 589        self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
 590    }
 591
 592    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
 593        self.0.state.borrow_mut().callbacks.input = Some(callback);
 594    }
 595
 596    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 597        self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
 598    }
 599
 600    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 601        self.0.state.borrow_mut().callbacks.resize = Some(callback);
 602    }
 603
 604    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 605        self.0.state.borrow_mut().callbacks.moved = Some(callback);
 606    }
 607
 608    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 609        self.0.state.borrow_mut().callbacks.should_close = Some(callback);
 610    }
 611
 612    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 613        self.0.state.borrow_mut().callbacks.close = Some(callback);
 614    }
 615
 616    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 617        self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
 618    }
 619
 620    fn draw(&self, scene: &Scene) {
 621        self.0.state.borrow_mut().renderer.draw(scene)
 622    }
 623
 624    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 625        self.0.state.borrow().renderer.sprite_atlas().clone()
 626    }
 627
 628    fn get_raw_handle(&self) -> HWND {
 629        self.0.hwnd
 630    }
 631
 632    fn show_window_menu(&self, _position: Point<Pixels>) {}
 633
 634    fn start_system_move(&self) {}
 635
 636    fn should_render_window_controls(&self) -> bool {
 637        false
 638    }
 639}
 640
 641#[implement(IDropTarget)]
 642struct WindowsDragDropHandler(pub Rc<WindowsWindowStatePtr>);
 643
 644impl WindowsDragDropHandler {
 645    fn handle_drag_drop(&self, input: PlatformInput) {
 646        let mut lock = self.0.state.borrow_mut();
 647        if let Some(mut func) = lock.callbacks.input.take() {
 648            drop(lock);
 649            func(input);
 650            self.0.state.borrow_mut().callbacks.input = Some(func);
 651        }
 652    }
 653}
 654
 655#[allow(non_snake_case)]
 656impl IDropTarget_Impl for WindowsDragDropHandler {
 657    fn DragEnter(
 658        &self,
 659        pdataobj: Option<&IDataObject>,
 660        _grfkeystate: MODIFIERKEYS_FLAGS,
 661        pt: &POINTL,
 662        pdweffect: *mut DROPEFFECT,
 663    ) -> windows::core::Result<()> {
 664        unsafe {
 665            let Some(idata_obj) = pdataobj else {
 666                log::info!("no dragging file or directory detected");
 667                return Ok(());
 668            };
 669            let config = FORMATETC {
 670                cfFormat: CF_HDROP.0,
 671                ptd: std::ptr::null_mut() as _,
 672                dwAspect: DVASPECT_CONTENT.0,
 673                lindex: -1,
 674                tymed: TYMED_HGLOBAL.0 as _,
 675            };
 676            if idata_obj.QueryGetData(&config as _) == S_OK {
 677                *pdweffect = DROPEFFECT_LINK;
 678                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 679                    return Ok(());
 680                };
 681                if idata.u.hGlobal.is_invalid() {
 682                    return Ok(());
 683                }
 684                let hdrop = idata.u.hGlobal.0 as *mut HDROP;
 685                let mut paths = SmallVec::<[PathBuf; 2]>::new();
 686                let file_count = DragQueryFileW(*hdrop, DRAGDROP_GET_FILES_COUNT, None);
 687                for file_index in 0..file_count {
 688                    let filename_length = DragQueryFileW(*hdrop, file_index, None) as usize;
 689                    let mut buffer = vec![0u16; filename_length + 1];
 690                    let ret = DragQueryFileW(*hdrop, file_index, Some(buffer.as_mut_slice()));
 691                    if ret == 0 {
 692                        log::error!("unable to read file name");
 693                        continue;
 694                    }
 695                    if let Some(file_name) =
 696                        String::from_utf16(&buffer[0..filename_length]).log_err()
 697                    {
 698                        if let Some(path) = PathBuf::from_str(&file_name).log_err() {
 699                            paths.push(path);
 700                        }
 701                    }
 702                }
 703                ReleaseStgMedium(&mut idata);
 704                let mut cursor_position = POINT { x: pt.x, y: pt.y };
 705                ScreenToClient(self.0.hwnd, &mut cursor_position);
 706                let scale_factor = self.0.state.borrow().scale_factor;
 707                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 708                    position: logical_point(
 709                        cursor_position.x as f32,
 710                        cursor_position.y as f32,
 711                        scale_factor,
 712                    ),
 713                    paths: ExternalPaths(paths),
 714                });
 715                self.handle_drag_drop(input);
 716            } else {
 717                *pdweffect = DROPEFFECT_NONE;
 718            }
 719        }
 720        Ok(())
 721    }
 722
 723    fn DragOver(
 724        &self,
 725        _grfkeystate: MODIFIERKEYS_FLAGS,
 726        pt: &POINTL,
 727        _pdweffect: *mut DROPEFFECT,
 728    ) -> windows::core::Result<()> {
 729        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 730        unsafe {
 731            ScreenToClient(self.0.hwnd, &mut cursor_position);
 732        }
 733        let scale_factor = self.0.state.borrow().scale_factor;
 734        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
 735            position: logical_point(
 736                cursor_position.x as f32,
 737                cursor_position.y as f32,
 738                scale_factor,
 739            ),
 740        });
 741        self.handle_drag_drop(input);
 742
 743        Ok(())
 744    }
 745
 746    fn DragLeave(&self) -> windows::core::Result<()> {
 747        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
 748        self.handle_drag_drop(input);
 749
 750        Ok(())
 751    }
 752
 753    fn Drop(
 754        &self,
 755        _pdataobj: Option<&IDataObject>,
 756        _grfkeystate: MODIFIERKEYS_FLAGS,
 757        pt: &POINTL,
 758        _pdweffect: *mut DROPEFFECT,
 759    ) -> windows::core::Result<()> {
 760        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 761        unsafe {
 762            ScreenToClient(self.0.hwnd, &mut cursor_position);
 763        }
 764        let scale_factor = self.0.state.borrow().scale_factor;
 765        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
 766            position: logical_point(
 767                cursor_position.x as f32,
 768                cursor_position.y as f32,
 769                scale_factor,
 770            ),
 771        });
 772        self.handle_drag_drop(input);
 773
 774        Ok(())
 775    }
 776}
 777
 778#[derive(Debug)]
 779pub(crate) struct ClickState {
 780    button: MouseButton,
 781    last_click: Instant,
 782    last_position: Point<DevicePixels>,
 783    pub(crate) current_count: usize,
 784}
 785
 786impl ClickState {
 787    pub fn new() -> Self {
 788        ClickState {
 789            button: MouseButton::Left,
 790            last_click: Instant::now(),
 791            last_position: Point::default(),
 792            current_count: 0,
 793        }
 794    }
 795
 796    /// update self and return the needed click count
 797    pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
 798        if self.button == button && self.is_double_click(new_position) {
 799            self.current_count += 1;
 800        } else {
 801            self.current_count = 1;
 802        }
 803        self.last_click = Instant::now();
 804        self.last_position = new_position;
 805        self.button = button;
 806
 807        self.current_count
 808    }
 809
 810    #[inline]
 811    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
 812        let diff = self.last_position - new_position;
 813
 814        self.last_click.elapsed() < DOUBLE_CLICK_INTERVAL
 815            && diff.x.0.abs() <= DOUBLE_CLICK_SPATIAL_TOLERANCE
 816            && diff.y.0.abs() <= DOUBLE_CLICK_SPATIAL_TOLERANCE
 817    }
 818}
 819
 820struct StyleAndBounds {
 821    style: WINDOW_STYLE,
 822    x: i32,
 823    y: i32,
 824    cx: i32,
 825    cy: i32,
 826}
 827
 828fn register_wnd_class(icon_handle: HICON) -> PCWSTR {
 829    const CLASS_NAME: PCWSTR = w!("Zed::Window");
 830
 831    static ONCE: Once = Once::new();
 832    ONCE.call_once(|| {
 833        let wc = WNDCLASSW {
 834            lpfnWndProc: Some(wnd_proc),
 835            hIcon: icon_handle,
 836            lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
 837            style: CS_HREDRAW | CS_VREDRAW,
 838            hInstance: get_module_handle().into(),
 839            ..Default::default()
 840        };
 841        unsafe { RegisterClassW(&wc) };
 842    });
 843
 844    CLASS_NAME
 845}
 846
 847unsafe extern "system" fn wnd_proc(
 848    hwnd: HWND,
 849    msg: u32,
 850    wparam: WPARAM,
 851    lparam: LPARAM,
 852) -> LRESULT {
 853    if msg == WM_NCCREATE {
 854        let cs = lparam.0 as *const CREATESTRUCTW;
 855        let cs = unsafe { &*cs };
 856        let ctx = cs.lpCreateParams as *mut WindowCreateContext;
 857        let ctx = unsafe { &mut *ctx };
 858        let state_ptr = WindowsWindowStatePtr::new(ctx, hwnd, cs);
 859        let weak = Box::new(Rc::downgrade(&state_ptr));
 860        unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
 861        ctx.inner = Some(state_ptr);
 862        return LRESULT(1);
 863    }
 864    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 865    if ptr.is_null() {
 866        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
 867    }
 868    let inner = unsafe { &*ptr };
 869    let r = if let Some(state) = inner.upgrade() {
 870        handle_msg(hwnd, msg, wparam, lparam, state)
 871    } else {
 872        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
 873    };
 874    if msg == WM_NCDESTROY {
 875        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
 876        unsafe { drop(Box::from_raw(ptr)) };
 877    }
 878    r
 879}
 880
 881pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
 882    if hwnd == HWND(0) {
 883        return None;
 884    }
 885
 886    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 887    if !ptr.is_null() {
 888        let inner = unsafe { &*ptr };
 889        inner.upgrade()
 890    } else {
 891        None
 892    }
 893}
 894
 895fn get_module_handle() -> HMODULE {
 896    unsafe {
 897        let mut h_module = std::mem::zeroed();
 898        GetModuleHandleExW(
 899            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
 900            windows::core::w!("ZedModule"),
 901            &mut h_module,
 902        )
 903        .expect("Unable to get module handle"); // this should never fail
 904
 905        h_module
 906    }
 907}
 908
 909fn register_drag_drop(state_ptr: Rc<WindowsWindowStatePtr>) {
 910    let window_handle = state_ptr.hwnd;
 911    let handler = WindowsDragDropHandler(state_ptr);
 912    // The lifetime of `IDropTarget` is handled by Windows, it wont release untill
 913    // we call `RevokeDragDrop`.
 914    // So, it's safe to drop it here.
 915    let drag_drop_handler: IDropTarget = handler.into();
 916    unsafe {
 917        RegisterDragDrop(window_handle, &drag_drop_handler)
 918            .expect("unable to register drag-drop event")
 919    };
 920}
 921
 922// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-dragqueryfilew
 923const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
 924// https://learn.microsoft.com/en-us/windows/win32/controls/ttm-setdelaytime?redirectedfrom=MSDN
 925const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(500);
 926// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics
 927const DOUBLE_CLICK_SPATIAL_TOLERANCE: i32 = 4;
 928
 929mod windows_renderer {
 930    use std::{num::NonZeroIsize, sync::Arc};
 931
 932    use blade_graphics as gpu;
 933    use raw_window_handle as rwh;
 934    use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::GWLP_HINSTANCE};
 935
 936    use crate::{
 937        get_window_long,
 938        platform::blade::{BladeRenderer, BladeSurfaceConfig},
 939    };
 940
 941    pub(super) fn windows_renderer(hwnd: HWND, transparent: bool) -> BladeRenderer {
 942        let raw = RawWindow { hwnd: hwnd.0 };
 943        let gpu: Arc<gpu::Context> = Arc::new(
 944            unsafe {
 945                gpu::Context::init_windowed(
 946                    &raw,
 947                    gpu::ContextDesc {
 948                        validation: false,
 949                        capture: false,
 950                        overlay: false,
 951                    },
 952                )
 953            }
 954            .unwrap(),
 955        );
 956        let config = BladeSurfaceConfig {
 957            size: gpu::Extent::default(),
 958            transparent,
 959        };
 960
 961        BladeRenderer::new(gpu, config)
 962    }
 963
 964    struct RawWindow {
 965        hwnd: isize,
 966    }
 967
 968    impl rwh::HasWindowHandle for RawWindow {
 969        fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 970            Ok(unsafe {
 971                let hwnd = NonZeroIsize::new_unchecked(self.hwnd);
 972                let mut handle = rwh::Win32WindowHandle::new(hwnd);
 973                let hinstance = get_window_long(HWND(self.hwnd), GWLP_HINSTANCE);
 974                handle.hinstance = NonZeroIsize::new(hinstance);
 975                rwh::WindowHandle::borrow_raw(handle.into())
 976            })
 977        }
 978    }
 979
 980    impl rwh::HasDisplayHandle for RawWindow {
 981        fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 982            let handle = rwh::WindowsDisplayHandle::new();
 983            Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
 984        }
 985    }
 986}
 987
 988#[cfg(test)]
 989mod tests {
 990    use super::ClickState;
 991    use crate::{point, DevicePixels, MouseButton};
 992    use std::time::Duration;
 993
 994    #[test]
 995    fn test_double_click_interval() {
 996        let mut state = ClickState::new();
 997        assert_eq!(
 998            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
 999            1
1000        );
1001        assert_eq!(
1002            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1003            1
1004        );
1005        assert_eq!(
1006            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1007            1
1008        );
1009        assert_eq!(
1010            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1011            2
1012        );
1013        state.last_click -= Duration::from_millis(700);
1014        assert_eq!(
1015            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1016            1
1017        );
1018    }
1019
1020    #[test]
1021    fn test_double_click_spatial_tolerance() {
1022        let mut state = ClickState::new();
1023        assert_eq!(
1024            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1025            1
1026        );
1027        assert_eq!(
1028            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1029            2
1030        );
1031        assert_eq!(
1032            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1033            1
1034        );
1035        assert_eq!(
1036            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1037            1
1038        );
1039    }
1040}