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