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 | crate::PromptLevel::Destructive => {
 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
 633#[implement(IDropTarget)]
 634struct WindowsDragDropHandler(pub Rc<WindowsWindowStatePtr>);
 635
 636impl WindowsDragDropHandler {
 637    fn handle_drag_drop(&self, input: PlatformInput) {
 638        let mut lock = self.0.state.borrow_mut();
 639        if let Some(mut func) = lock.callbacks.input.take() {
 640            drop(lock);
 641            func(input);
 642            self.0.state.borrow_mut().callbacks.input = Some(func);
 643        }
 644    }
 645}
 646
 647#[allow(non_snake_case)]
 648impl IDropTarget_Impl for WindowsDragDropHandler {
 649    fn DragEnter(
 650        &self,
 651        pdataobj: Option<&IDataObject>,
 652        _grfkeystate: MODIFIERKEYS_FLAGS,
 653        pt: &POINTL,
 654        pdweffect: *mut DROPEFFECT,
 655    ) -> windows::core::Result<()> {
 656        unsafe {
 657            let Some(idata_obj) = pdataobj else {
 658                log::info!("no dragging file or directory detected");
 659                return Ok(());
 660            };
 661            let config = FORMATETC {
 662                cfFormat: CF_HDROP.0,
 663                ptd: std::ptr::null_mut() as _,
 664                dwAspect: DVASPECT_CONTENT.0,
 665                lindex: -1,
 666                tymed: TYMED_HGLOBAL.0 as _,
 667            };
 668            if idata_obj.QueryGetData(&config as _) == S_OK {
 669                *pdweffect = DROPEFFECT_LINK;
 670                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 671                    return Ok(());
 672                };
 673                if idata.u.hGlobal.is_invalid() {
 674                    return Ok(());
 675                }
 676                let hdrop = idata.u.hGlobal.0 as *mut HDROP;
 677                let mut paths = SmallVec::<[PathBuf; 2]>::new();
 678                let file_count = DragQueryFileW(*hdrop, DRAGDROP_GET_FILES_COUNT, None);
 679                for file_index in 0..file_count {
 680                    let filename_length = DragQueryFileW(*hdrop, file_index, None) as usize;
 681                    let mut buffer = vec![0u16; filename_length + 1];
 682                    let ret = DragQueryFileW(*hdrop, file_index, Some(buffer.as_mut_slice()));
 683                    if ret == 0 {
 684                        log::error!("unable to read file name");
 685                        continue;
 686                    }
 687                    if let Some(file_name) =
 688                        String::from_utf16(&buffer[0..filename_length]).log_err()
 689                    {
 690                        if let Some(path) = PathBuf::from_str(&file_name).log_err() {
 691                            paths.push(path);
 692                        }
 693                    }
 694                }
 695                ReleaseStgMedium(&mut idata);
 696                let mut cursor_position = POINT { x: pt.x, y: pt.y };
 697                ScreenToClient(self.0.hwnd, &mut cursor_position);
 698                let scale_factor = self.0.state.borrow().scale_factor;
 699                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 700                    position: logical_point(
 701                        cursor_position.x as f32,
 702                        cursor_position.y as f32,
 703                        scale_factor,
 704                    ),
 705                    paths: ExternalPaths(paths),
 706                });
 707                self.handle_drag_drop(input);
 708            } else {
 709                *pdweffect = DROPEFFECT_NONE;
 710            }
 711        }
 712        Ok(())
 713    }
 714
 715    fn DragOver(
 716        &self,
 717        _grfkeystate: MODIFIERKEYS_FLAGS,
 718        pt: &POINTL,
 719        _pdweffect: *mut DROPEFFECT,
 720    ) -> windows::core::Result<()> {
 721        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 722        unsafe {
 723            ScreenToClient(self.0.hwnd, &mut cursor_position);
 724        }
 725        let scale_factor = self.0.state.borrow().scale_factor;
 726        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
 727            position: logical_point(
 728                cursor_position.x as f32,
 729                cursor_position.y as f32,
 730                scale_factor,
 731            ),
 732        });
 733        self.handle_drag_drop(input);
 734
 735        Ok(())
 736    }
 737
 738    fn DragLeave(&self) -> windows::core::Result<()> {
 739        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
 740        self.handle_drag_drop(input);
 741
 742        Ok(())
 743    }
 744
 745    fn Drop(
 746        &self,
 747        _pdataobj: Option<&IDataObject>,
 748        _grfkeystate: MODIFIERKEYS_FLAGS,
 749        pt: &POINTL,
 750        _pdweffect: *mut DROPEFFECT,
 751    ) -> windows::core::Result<()> {
 752        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 753        unsafe {
 754            ScreenToClient(self.0.hwnd, &mut cursor_position);
 755        }
 756        let scale_factor = self.0.state.borrow().scale_factor;
 757        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
 758            position: logical_point(
 759                cursor_position.x as f32,
 760                cursor_position.y as f32,
 761                scale_factor,
 762            ),
 763        });
 764        self.handle_drag_drop(input);
 765
 766        Ok(())
 767    }
 768}
 769
 770#[derive(Debug)]
 771pub(crate) struct ClickState {
 772    button: MouseButton,
 773    last_click: Instant,
 774    last_position: Point<DevicePixels>,
 775    pub(crate) current_count: usize,
 776}
 777
 778impl ClickState {
 779    pub fn new() -> Self {
 780        ClickState {
 781            button: MouseButton::Left,
 782            last_click: Instant::now(),
 783            last_position: Point::default(),
 784            current_count: 0,
 785        }
 786    }
 787
 788    /// update self and return the needed click count
 789    pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
 790        if self.button == button && self.is_double_click(new_position) {
 791            self.current_count += 1;
 792        } else {
 793            self.current_count = 1;
 794        }
 795        self.last_click = Instant::now();
 796        self.last_position = new_position;
 797        self.button = button;
 798
 799        self.current_count
 800    }
 801
 802    #[inline]
 803    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
 804        let diff = self.last_position - new_position;
 805
 806        self.last_click.elapsed() < DOUBLE_CLICK_INTERVAL
 807            && diff.x.0.abs() <= DOUBLE_CLICK_SPATIAL_TOLERANCE
 808            && diff.y.0.abs() <= DOUBLE_CLICK_SPATIAL_TOLERANCE
 809    }
 810}
 811
 812struct StyleAndBounds {
 813    style: WINDOW_STYLE,
 814    x: i32,
 815    y: i32,
 816    cx: i32,
 817    cy: i32,
 818}
 819
 820fn register_wnd_class(icon_handle: HICON) -> PCWSTR {
 821    const CLASS_NAME: PCWSTR = w!("Zed::Window");
 822
 823    static ONCE: Once = Once::new();
 824    ONCE.call_once(|| {
 825        let wc = WNDCLASSW {
 826            lpfnWndProc: Some(wnd_proc),
 827            hIcon: icon_handle,
 828            lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
 829            style: CS_HREDRAW | CS_VREDRAW,
 830            hInstance: get_module_handle().into(),
 831            ..Default::default()
 832        };
 833        unsafe { RegisterClassW(&wc) };
 834    });
 835
 836    CLASS_NAME
 837}
 838
 839unsafe extern "system" fn wnd_proc(
 840    hwnd: HWND,
 841    msg: u32,
 842    wparam: WPARAM,
 843    lparam: LPARAM,
 844) -> LRESULT {
 845    if msg == WM_NCCREATE {
 846        let cs = lparam.0 as *const CREATESTRUCTW;
 847        let cs = unsafe { &*cs };
 848        let ctx = cs.lpCreateParams as *mut WindowCreateContext;
 849        let ctx = unsafe { &mut *ctx };
 850        let state_ptr = WindowsWindowStatePtr::new(ctx, hwnd, cs);
 851        let weak = Box::new(Rc::downgrade(&state_ptr));
 852        unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
 853        ctx.inner = Some(state_ptr);
 854        return LRESULT(1);
 855    }
 856    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 857    if ptr.is_null() {
 858        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
 859    }
 860    let inner = unsafe { &*ptr };
 861    let r = if let Some(state) = inner.upgrade() {
 862        handle_msg(hwnd, msg, wparam, lparam, state)
 863    } else {
 864        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
 865    };
 866    if msg == WM_NCDESTROY {
 867        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
 868        unsafe { drop(Box::from_raw(ptr)) };
 869    }
 870    r
 871}
 872
 873pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
 874    if hwnd == HWND(0) {
 875        return None;
 876    }
 877
 878    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 879    if !ptr.is_null() {
 880        let inner = unsafe { &*ptr };
 881        inner.upgrade()
 882    } else {
 883        None
 884    }
 885}
 886
 887fn get_module_handle() -> HMODULE {
 888    unsafe {
 889        let mut h_module = std::mem::zeroed();
 890        GetModuleHandleExW(
 891            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
 892            windows::core::w!("ZedModule"),
 893            &mut h_module,
 894        )
 895        .expect("Unable to get module handle"); // this should never fail
 896
 897        h_module
 898    }
 899}
 900
 901fn register_drag_drop(state_ptr: Rc<WindowsWindowStatePtr>) {
 902    let window_handle = state_ptr.hwnd;
 903    let handler = WindowsDragDropHandler(state_ptr);
 904    // The lifetime of `IDropTarget` is handled by Windows, it wont release untill
 905    // we call `RevokeDragDrop`.
 906    // So, it's safe to drop it here.
 907    let drag_drop_handler: IDropTarget = handler.into();
 908    unsafe {
 909        RegisterDragDrop(window_handle, &drag_drop_handler)
 910            .expect("unable to register drag-drop event")
 911    };
 912}
 913
 914// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-dragqueryfilew
 915const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
 916// https://learn.microsoft.com/en-us/windows/win32/controls/ttm-setdelaytime?redirectedfrom=MSDN
 917const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(500);
 918// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics
 919const DOUBLE_CLICK_SPATIAL_TOLERANCE: i32 = 4;
 920
 921mod windows_renderer {
 922    use std::{num::NonZeroIsize, sync::Arc};
 923
 924    use blade_graphics as gpu;
 925    use raw_window_handle as rwh;
 926    use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::GWLP_HINSTANCE};
 927
 928    use crate::{
 929        get_window_long,
 930        platform::blade::{BladeRenderer, BladeSurfaceConfig},
 931    };
 932
 933    pub(super) fn windows_renderer(hwnd: HWND, transparent: bool) -> BladeRenderer {
 934        let raw = RawWindow { hwnd: hwnd.0 };
 935        let gpu: Arc<gpu::Context> = Arc::new(
 936            unsafe {
 937                gpu::Context::init_windowed(
 938                    &raw,
 939                    gpu::ContextDesc {
 940                        validation: false,
 941                        capture: false,
 942                        overlay: false,
 943                    },
 944                )
 945            }
 946            .unwrap(),
 947        );
 948        let config = BladeSurfaceConfig {
 949            size: gpu::Extent::default(),
 950            transparent,
 951        };
 952
 953        BladeRenderer::new(gpu, config)
 954    }
 955
 956    struct RawWindow {
 957        hwnd: isize,
 958    }
 959
 960    impl rwh::HasWindowHandle for RawWindow {
 961        fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 962            Ok(unsafe {
 963                let hwnd = NonZeroIsize::new_unchecked(self.hwnd);
 964                let mut handle = rwh::Win32WindowHandle::new(hwnd);
 965                let hinstance = get_window_long(HWND(self.hwnd), GWLP_HINSTANCE);
 966                handle.hinstance = NonZeroIsize::new(hinstance);
 967                rwh::WindowHandle::borrow_raw(handle.into())
 968            })
 969        }
 970    }
 971
 972    impl rwh::HasDisplayHandle for RawWindow {
 973        fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 974            let handle = rwh::WindowsDisplayHandle::new();
 975            Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
 976        }
 977    }
 978}
 979
 980#[cfg(test)]
 981mod tests {
 982    use super::ClickState;
 983    use crate::{point, DevicePixels, MouseButton};
 984    use std::time::Duration;
 985
 986    #[test]
 987    fn test_double_click_interval() {
 988        let mut state = ClickState::new();
 989        assert_eq!(
 990            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
 991            1
 992        );
 993        assert_eq!(
 994            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
 995            1
 996        );
 997        assert_eq!(
 998            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
 999            1
1000        );
1001        assert_eq!(
1002            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1003            2
1004        );
1005        state.last_click -= Duration::from_millis(700);
1006        assert_eq!(
1007            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1008            1
1009        );
1010    }
1011
1012    #[test]
1013    fn test_double_click_spatial_tolerance() {
1014        let mut state = ClickState::new();
1015        assert_eq!(
1016            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1017            1
1018        );
1019        assert_eq!(
1020            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1021            2
1022        );
1023        assert_eq!(
1024            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1025            1
1026        );
1027        assert_eq!(
1028            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1029            1
1030        );
1031    }
1032}