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: params.window_background != WindowBackgroundAppearance::Opaque,
 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_app_id(&mut self, _app_id: &str) {}
 515
 516    fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
 517        self.0
 518            .state
 519            .borrow_mut()
 520            .renderer
 521            .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
 522    }
 523
 524    // todo(windows)
 525    fn set_edited(&mut self, _edited: bool) {}
 526
 527    // todo(windows)
 528    fn show_character_palette(&self) {}
 529
 530    fn minimize(&self) {
 531        unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
 532    }
 533
 534    fn zoom(&self) {
 535        unsafe { ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err() };
 536    }
 537
 538    fn toggle_fullscreen(&self) {
 539        let state_ptr = self.0.clone();
 540        self.0
 541            .executor
 542            .spawn(async move {
 543                let mut lock = state_ptr.state.borrow_mut();
 544                lock.fullscreen_restore_bounds = Bounds {
 545                    origin: lock.origin,
 546                    size: lock.logical_size,
 547                };
 548                let StyleAndBounds {
 549                    style,
 550                    x,
 551                    y,
 552                    cx,
 553                    cy,
 554                } = if let Some(state) = lock.fullscreen.take() {
 555                    state
 556                } else {
 557                    let style =
 558                        WINDOW_STYLE(unsafe { get_window_long(state_ptr.hwnd, GWL_STYLE) } as _);
 559                    let mut rc = RECT::default();
 560                    unsafe { GetWindowRect(state_ptr.hwnd, &mut rc) }.log_err();
 561                    let _ = lock.fullscreen.insert(StyleAndBounds {
 562                        style,
 563                        x: rc.left,
 564                        y: rc.top,
 565                        cx: rc.right - rc.left,
 566                        cy: rc.bottom - rc.top,
 567                    });
 568                    let style = style
 569                        & !(WS_THICKFRAME
 570                            | WS_SYSMENU
 571                            | WS_MAXIMIZEBOX
 572                            | WS_MINIMIZEBOX
 573                            | WS_CAPTION);
 574                    let physical_bounds = lock.display.physical_bounds();
 575                    StyleAndBounds {
 576                        style,
 577                        x: physical_bounds.left().0,
 578                        y: physical_bounds.top().0,
 579                        cx: physical_bounds.size.width.0,
 580                        cy: physical_bounds.size.height.0,
 581                    }
 582                };
 583                drop(lock);
 584                unsafe { set_window_long(state_ptr.hwnd, GWL_STYLE, style.0 as isize) };
 585                unsafe {
 586                    SetWindowPos(
 587                        state_ptr.hwnd,
 588                        HWND::default(),
 589                        x,
 590                        y,
 591                        cx,
 592                        cy,
 593                        SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER,
 594                    )
 595                }
 596                .log_err();
 597            })
 598            .detach();
 599    }
 600
 601    fn is_fullscreen(&self) -> bool {
 602        self.0.state.borrow().is_fullscreen()
 603    }
 604
 605    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
 606        self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
 607    }
 608
 609    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
 610        self.0.state.borrow_mut().callbacks.input = Some(callback);
 611    }
 612
 613    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 614        self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
 615    }
 616
 617    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 618        self.0.state.borrow_mut().callbacks.resize = Some(callback);
 619    }
 620
 621    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 622        self.0.state.borrow_mut().callbacks.moved = Some(callback);
 623    }
 624
 625    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 626        self.0.state.borrow_mut().callbacks.should_close = Some(callback);
 627    }
 628
 629    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 630        self.0.state.borrow_mut().callbacks.close = Some(callback);
 631    }
 632
 633    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 634        self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
 635    }
 636
 637    fn draw(&self, scene: &Scene) {
 638        self.0.state.borrow_mut().renderer.draw(scene)
 639    }
 640
 641    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 642        self.0.state.borrow().renderer.sprite_atlas().clone()
 643    }
 644
 645    fn get_raw_handle(&self) -> HWND {
 646        self.0.hwnd
 647    }
 648
 649    fn show_window_menu(&self, _position: Point<Pixels>) {}
 650
 651    fn start_system_move(&self) {}
 652
 653    fn should_render_window_controls(&self) -> bool {
 654        false
 655    }
 656}
 657
 658#[implement(IDropTarget)]
 659struct WindowsDragDropHandler(pub Rc<WindowsWindowStatePtr>);
 660
 661impl WindowsDragDropHandler {
 662    fn handle_drag_drop(&self, input: PlatformInput) {
 663        let mut lock = self.0.state.borrow_mut();
 664        if let Some(mut func) = lock.callbacks.input.take() {
 665            drop(lock);
 666            func(input);
 667            self.0.state.borrow_mut().callbacks.input = Some(func);
 668        }
 669    }
 670}
 671
 672#[allow(non_snake_case)]
 673impl IDropTarget_Impl for WindowsDragDropHandler {
 674    fn DragEnter(
 675        &self,
 676        pdataobj: Option<&IDataObject>,
 677        _grfkeystate: MODIFIERKEYS_FLAGS,
 678        pt: &POINTL,
 679        pdweffect: *mut DROPEFFECT,
 680    ) -> windows::core::Result<()> {
 681        unsafe {
 682            let Some(idata_obj) = pdataobj else {
 683                log::info!("no dragging file or directory detected");
 684                return Ok(());
 685            };
 686            let config = FORMATETC {
 687                cfFormat: CF_HDROP.0,
 688                ptd: std::ptr::null_mut() as _,
 689                dwAspect: DVASPECT_CONTENT.0,
 690                lindex: -1,
 691                tymed: TYMED_HGLOBAL.0 as _,
 692            };
 693            if idata_obj.QueryGetData(&config as _) == S_OK {
 694                *pdweffect = DROPEFFECT_LINK;
 695                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 696                    return Ok(());
 697                };
 698                if idata.u.hGlobal.is_invalid() {
 699                    return Ok(());
 700                }
 701                let hdrop = idata.u.hGlobal.0 as *mut HDROP;
 702                let mut paths = SmallVec::<[PathBuf; 2]>::new();
 703                let file_count = DragQueryFileW(*hdrop, DRAGDROP_GET_FILES_COUNT, None);
 704                for file_index in 0..file_count {
 705                    let filename_length = DragQueryFileW(*hdrop, file_index, None) as usize;
 706                    let mut buffer = vec![0u16; filename_length + 1];
 707                    let ret = DragQueryFileW(*hdrop, file_index, Some(buffer.as_mut_slice()));
 708                    if ret == 0 {
 709                        log::error!("unable to read file name");
 710                        continue;
 711                    }
 712                    if let Some(file_name) =
 713                        String::from_utf16(&buffer[0..filename_length]).log_err()
 714                    {
 715                        if let Some(path) = PathBuf::from_str(&file_name).log_err() {
 716                            paths.push(path);
 717                        }
 718                    }
 719                }
 720                ReleaseStgMedium(&mut idata);
 721                let mut cursor_position = POINT { x: pt.x, y: pt.y };
 722                ScreenToClient(self.0.hwnd, &mut cursor_position)
 723                    .ok()
 724                    .log_err();
 725                let scale_factor = self.0.state.borrow().scale_factor;
 726                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 727                    position: logical_point(
 728                        cursor_position.x as f32,
 729                        cursor_position.y as f32,
 730                        scale_factor,
 731                    ),
 732                    paths: ExternalPaths(paths),
 733                });
 734                self.handle_drag_drop(input);
 735            } else {
 736                *pdweffect = DROPEFFECT_NONE;
 737            }
 738        }
 739        Ok(())
 740    }
 741
 742    fn DragOver(
 743        &self,
 744        _grfkeystate: MODIFIERKEYS_FLAGS,
 745        pt: &POINTL,
 746        _pdweffect: *mut DROPEFFECT,
 747    ) -> windows::core::Result<()> {
 748        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 749        unsafe {
 750            ScreenToClient(self.0.hwnd, &mut cursor_position)
 751                .ok()
 752                .log_err();
 753        }
 754        let scale_factor = self.0.state.borrow().scale_factor;
 755        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
 756            position: logical_point(
 757                cursor_position.x as f32,
 758                cursor_position.y as f32,
 759                scale_factor,
 760            ),
 761        });
 762        self.handle_drag_drop(input);
 763
 764        Ok(())
 765    }
 766
 767    fn DragLeave(&self) -> windows::core::Result<()> {
 768        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
 769        self.handle_drag_drop(input);
 770
 771        Ok(())
 772    }
 773
 774    fn Drop(
 775        &self,
 776        _pdataobj: Option<&IDataObject>,
 777        _grfkeystate: MODIFIERKEYS_FLAGS,
 778        pt: &POINTL,
 779        _pdweffect: *mut DROPEFFECT,
 780    ) -> windows::core::Result<()> {
 781        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 782        unsafe {
 783            ScreenToClient(self.0.hwnd, &mut cursor_position)
 784                .ok()
 785                .log_err();
 786        }
 787        let scale_factor = self.0.state.borrow().scale_factor;
 788        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
 789            position: logical_point(
 790                cursor_position.x as f32,
 791                cursor_position.y as f32,
 792                scale_factor,
 793            ),
 794        });
 795        self.handle_drag_drop(input);
 796
 797        Ok(())
 798    }
 799}
 800
 801#[derive(Debug)]
 802pub(crate) struct ClickState {
 803    button: MouseButton,
 804    last_click: Instant,
 805    last_position: Point<DevicePixels>,
 806    pub(crate) current_count: usize,
 807}
 808
 809impl ClickState {
 810    pub fn new() -> Self {
 811        ClickState {
 812            button: MouseButton::Left,
 813            last_click: Instant::now(),
 814            last_position: Point::default(),
 815            current_count: 0,
 816        }
 817    }
 818
 819    /// update self and return the needed click count
 820    pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
 821        if self.button == button && self.is_double_click(new_position) {
 822            self.current_count += 1;
 823        } else {
 824            self.current_count = 1;
 825        }
 826        self.last_click = Instant::now();
 827        self.last_position = new_position;
 828        self.button = button;
 829
 830        self.current_count
 831    }
 832
 833    #[inline]
 834    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
 835        let diff = self.last_position - new_position;
 836
 837        self.last_click.elapsed() < DOUBLE_CLICK_INTERVAL
 838            && diff.x.0.abs() <= DOUBLE_CLICK_SPATIAL_TOLERANCE
 839            && diff.y.0.abs() <= DOUBLE_CLICK_SPATIAL_TOLERANCE
 840    }
 841}
 842
 843struct StyleAndBounds {
 844    style: WINDOW_STYLE,
 845    x: i32,
 846    y: i32,
 847    cx: i32,
 848    cy: i32,
 849}
 850
 851fn register_wnd_class(icon_handle: HICON) -> PCWSTR {
 852    const CLASS_NAME: PCWSTR = w!("Zed::Window");
 853
 854    static ONCE: Once = Once::new();
 855    ONCE.call_once(|| {
 856        let wc = WNDCLASSW {
 857            lpfnWndProc: Some(wnd_proc),
 858            hIcon: icon_handle,
 859            lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
 860            style: CS_HREDRAW | CS_VREDRAW,
 861            hInstance: get_module_handle().into(),
 862            ..Default::default()
 863        };
 864        unsafe { RegisterClassW(&wc) };
 865    });
 866
 867    CLASS_NAME
 868}
 869
 870unsafe extern "system" fn wnd_proc(
 871    hwnd: HWND,
 872    msg: u32,
 873    wparam: WPARAM,
 874    lparam: LPARAM,
 875) -> LRESULT {
 876    if msg == WM_NCCREATE {
 877        let cs = lparam.0 as *const CREATESTRUCTW;
 878        let cs = unsafe { &*cs };
 879        let ctx = cs.lpCreateParams as *mut WindowCreateContext;
 880        let ctx = unsafe { &mut *ctx };
 881        let state_ptr = WindowsWindowStatePtr::new(ctx, hwnd, cs);
 882        let weak = Box::new(Rc::downgrade(&state_ptr));
 883        unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
 884        ctx.inner = Some(state_ptr);
 885        return LRESULT(1);
 886    }
 887    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 888    if ptr.is_null() {
 889        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
 890    }
 891    let inner = unsafe { &*ptr };
 892    let r = if let Some(state) = inner.upgrade() {
 893        handle_msg(hwnd, msg, wparam, lparam, state)
 894    } else {
 895        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
 896    };
 897    if msg == WM_NCDESTROY {
 898        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
 899        unsafe { drop(Box::from_raw(ptr)) };
 900    }
 901    r
 902}
 903
 904pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
 905    if hwnd == HWND(0) {
 906        return None;
 907    }
 908
 909    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 910    if !ptr.is_null() {
 911        let inner = unsafe { &*ptr };
 912        inner.upgrade()
 913    } else {
 914        None
 915    }
 916}
 917
 918fn get_module_handle() -> HMODULE {
 919    unsafe {
 920        let mut h_module = std::mem::zeroed();
 921        GetModuleHandleExW(
 922            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
 923            windows::core::w!("ZedModule"),
 924            &mut h_module,
 925        )
 926        .expect("Unable to get module handle"); // this should never fail
 927
 928        h_module
 929    }
 930}
 931
 932fn register_drag_drop(state_ptr: Rc<WindowsWindowStatePtr>) {
 933    let window_handle = state_ptr.hwnd;
 934    let handler = WindowsDragDropHandler(state_ptr);
 935    // The lifetime of `IDropTarget` is handled by Windows, it wont release untill
 936    // we call `RevokeDragDrop`.
 937    // So, it's safe to drop it here.
 938    let drag_drop_handler: IDropTarget = handler.into();
 939    unsafe {
 940        RegisterDragDrop(window_handle, &drag_drop_handler)
 941            .expect("unable to register drag-drop event")
 942    };
 943}
 944
 945// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-dragqueryfilew
 946const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
 947// https://learn.microsoft.com/en-us/windows/win32/controls/ttm-setdelaytime?redirectedfrom=MSDN
 948const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(500);
 949// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics
 950const DOUBLE_CLICK_SPATIAL_TOLERANCE: i32 = 4;
 951
 952mod windows_renderer {
 953    use std::{num::NonZeroIsize, sync::Arc};
 954
 955    use blade_graphics as gpu;
 956    use raw_window_handle as rwh;
 957    use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::GWLP_HINSTANCE};
 958
 959    use crate::{
 960        get_window_long,
 961        platform::blade::{BladeRenderer, BladeSurfaceConfig},
 962    };
 963
 964    pub(super) fn windows_renderer(hwnd: HWND, transparent: bool) -> BladeRenderer {
 965        let raw = RawWindow { hwnd: hwnd.0 };
 966        let gpu: Arc<gpu::Context> = Arc::new(
 967            unsafe {
 968                gpu::Context::init_windowed(
 969                    &raw,
 970                    gpu::ContextDesc {
 971                        validation: false,
 972                        capture: false,
 973                        overlay: false,
 974                    },
 975                )
 976            }
 977            .unwrap(),
 978        );
 979        let config = BladeSurfaceConfig {
 980            size: gpu::Extent::default(),
 981            transparent,
 982        };
 983
 984        BladeRenderer::new(gpu, config)
 985    }
 986
 987    struct RawWindow {
 988        hwnd: isize,
 989    }
 990
 991    impl rwh::HasWindowHandle for RawWindow {
 992        fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 993            Ok(unsafe {
 994                let hwnd = NonZeroIsize::new_unchecked(self.hwnd);
 995                let mut handle = rwh::Win32WindowHandle::new(hwnd);
 996                let hinstance = get_window_long(HWND(self.hwnd), GWLP_HINSTANCE);
 997                handle.hinstance = NonZeroIsize::new(hinstance);
 998                rwh::WindowHandle::borrow_raw(handle.into())
 999            })
1000        }
1001    }
1002
1003    impl rwh::HasDisplayHandle for RawWindow {
1004        fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1005            let handle = rwh::WindowsDisplayHandle::new();
1006            Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
1007        }
1008    }
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013    use super::ClickState;
1014    use crate::{point, DevicePixels, MouseButton};
1015    use std::time::Duration;
1016
1017    #[test]
1018    fn test_double_click_interval() {
1019        let mut state = ClickState::new();
1020        assert_eq!(
1021            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1022            1
1023        );
1024        assert_eq!(
1025            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1026            1
1027        );
1028        assert_eq!(
1029            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1030            1
1031        );
1032        assert_eq!(
1033            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1034            2
1035        );
1036        state.last_click -= Duration::from_millis(700);
1037        assert_eq!(
1038            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1039            1
1040        );
1041    }
1042
1043    #[test]
1044    fn test_double_click_spatial_tolerance() {
1045        let mut state = ClickState::new();
1046        assert_eq!(
1047            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1048            1
1049        );
1050        assert_eq!(
1051            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1052            2
1053        );
1054        assert_eq!(
1055            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1056            1
1057        );
1058        assert_eq!(
1059            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1060            1
1061        );
1062    }
1063}