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(true);
 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    fn appearance(&self) -> WindowAppearance {
 387        system_appearance().log_err().unwrap_or_default()
 388    }
 389
 390    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 391        Some(Rc::new(self.0.state.borrow().display))
 392    }
 393
 394    fn mouse_position(&self) -> Point<Pixels> {
 395        let scale_factor = self.scale_factor();
 396        let point = unsafe {
 397            let mut point: POINT = std::mem::zeroed();
 398            GetCursorPos(&mut point)
 399                .context("unable to get cursor position")
 400                .log_err();
 401            ScreenToClient(self.0.hwnd, &mut point).ok().log_err();
 402            point
 403        };
 404        logical_point(point.x as f32, point.y as f32, scale_factor)
 405    }
 406
 407    fn modifiers(&self) -> Modifiers {
 408        current_modifiers()
 409    }
 410
 411    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 412        self.0.state.borrow_mut().input_handler = Some(input_handler);
 413    }
 414
 415    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 416        self.0.state.borrow_mut().input_handler.take()
 417    }
 418
 419    fn prompt(
 420        &self,
 421        level: PromptLevel,
 422        msg: &str,
 423        detail: Option<&str>,
 424        answers: &[&str],
 425    ) -> Option<Receiver<usize>> {
 426        let (done_tx, done_rx) = oneshot::channel();
 427        let msg = msg.to_string();
 428        let detail_string = match detail {
 429            Some(info) => Some(info.to_string()),
 430            None => None,
 431        };
 432        let answers = answers.iter().map(|s| s.to_string()).collect::<Vec<_>>();
 433        let handle = self.0.hwnd;
 434        self.0
 435            .executor
 436            .spawn(async move {
 437                unsafe {
 438                    let mut config;
 439                    config = std::mem::zeroed::<TASKDIALOGCONFIG>();
 440                    config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;
 441                    config.hwndParent = handle;
 442                    let title;
 443                    let main_icon;
 444                    match level {
 445                        crate::PromptLevel::Info => {
 446                            title = windows::core::w!("Info");
 447                            main_icon = TD_INFORMATION_ICON;
 448                        }
 449                        crate::PromptLevel::Warning => {
 450                            title = windows::core::w!("Warning");
 451                            main_icon = TD_WARNING_ICON;
 452                        }
 453                        crate::PromptLevel::Critical => {
 454                            title = windows::core::w!("Critical");
 455                            main_icon = TD_ERROR_ICON;
 456                        }
 457                    };
 458                    config.pszWindowTitle = title;
 459                    config.Anonymous1.pszMainIcon = main_icon;
 460                    let instruction = msg.encode_utf16().chain(Some(0)).collect_vec();
 461                    config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());
 462                    let hints_encoded;
 463                    if let Some(ref hints) = detail_string {
 464                        hints_encoded = hints.encode_utf16().chain(Some(0)).collect_vec();
 465                        config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());
 466                    };
 467                    let mut buttons = Vec::new();
 468                    let mut btn_encoded = Vec::new();
 469                    for (index, btn_string) in answers.iter().enumerate() {
 470                        let encoded = btn_string.encode_utf16().chain(Some(0)).collect_vec();
 471                        buttons.push(TASKDIALOG_BUTTON {
 472                            nButtonID: index as _,
 473                            pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),
 474                        });
 475                        btn_encoded.push(encoded);
 476                    }
 477                    config.cButtons = buttons.len() as _;
 478                    config.pButtons = buttons.as_ptr();
 479
 480                    config.pfCallback = None;
 481                    let mut res = std::mem::zeroed();
 482                    let _ = TaskDialogIndirect(&config, Some(&mut res), None, None)
 483                        .inspect_err(|e| log::error!("unable to create task dialog: {}", e));
 484
 485                    let _ = done_tx.send(res as usize);
 486                }
 487            })
 488            .detach();
 489
 490        Some(done_rx)
 491    }
 492
 493    fn activate(&self) {
 494        let hwnd = self.0.hwnd;
 495        unsafe { SetActiveWindow(hwnd) };
 496        unsafe { SetFocus(hwnd) };
 497        // todo(windows)
 498        // crate `windows 0.56` reports true as Err
 499        unsafe { SetForegroundWindow(hwnd).as_bool() };
 500    }
 501
 502    fn is_active(&self) -> bool {
 503        self.0.hwnd == unsafe { GetActiveWindow() }
 504    }
 505
 506    // is_hovered is unused on Windows. See WindowContext::is_window_hovered.
 507    fn is_hovered(&self) -> bool {
 508        false
 509    }
 510
 511    fn set_title(&mut self, title: &str) {
 512        unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
 513            .inspect_err(|e| log::error!("Set title failed: {e}"))
 514            .ok();
 515    }
 516
 517    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
 518        self.0
 519            .state
 520            .borrow_mut()
 521            .renderer
 522            .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
 523    }
 524
 525    fn minimize(&self) {
 526        unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
 527    }
 528
 529    fn zoom(&self) {
 530        unsafe { ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err() };
 531    }
 532
 533    fn toggle_fullscreen(&self) {
 534        let state_ptr = self.0.clone();
 535        self.0
 536            .executor
 537            .spawn(async move {
 538                let mut lock = state_ptr.state.borrow_mut();
 539                lock.fullscreen_restore_bounds = Bounds {
 540                    origin: lock.origin,
 541                    size: lock.logical_size,
 542                };
 543                let StyleAndBounds {
 544                    style,
 545                    x,
 546                    y,
 547                    cx,
 548                    cy,
 549                } = if let Some(state) = lock.fullscreen.take() {
 550                    state
 551                } else {
 552                    let style =
 553                        WINDOW_STYLE(unsafe { get_window_long(state_ptr.hwnd, GWL_STYLE) } as _);
 554                    let mut rc = RECT::default();
 555                    unsafe { GetWindowRect(state_ptr.hwnd, &mut rc) }.log_err();
 556                    let _ = lock.fullscreen.insert(StyleAndBounds {
 557                        style,
 558                        x: rc.left,
 559                        y: rc.top,
 560                        cx: rc.right - rc.left,
 561                        cy: rc.bottom - rc.top,
 562                    });
 563                    let style = style
 564                        & !(WS_THICKFRAME
 565                            | WS_SYSMENU
 566                            | WS_MAXIMIZEBOX
 567                            | WS_MINIMIZEBOX
 568                            | WS_CAPTION);
 569                    let physical_bounds = lock.display.physical_bounds();
 570                    StyleAndBounds {
 571                        style,
 572                        x: physical_bounds.left().0,
 573                        y: physical_bounds.top().0,
 574                        cx: physical_bounds.size.width.0,
 575                        cy: physical_bounds.size.height.0,
 576                    }
 577                };
 578                drop(lock);
 579                unsafe { set_window_long(state_ptr.hwnd, GWL_STYLE, style.0 as isize) };
 580                unsafe {
 581                    SetWindowPos(
 582                        state_ptr.hwnd,
 583                        HWND::default(),
 584                        x,
 585                        y,
 586                        cx,
 587                        cy,
 588                        SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER,
 589                    )
 590                }
 591                .log_err();
 592            })
 593            .detach();
 594    }
 595
 596    fn is_fullscreen(&self) -> bool {
 597        self.0.state.borrow().is_fullscreen()
 598    }
 599
 600    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
 601        self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
 602    }
 603
 604    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
 605        self.0.state.borrow_mut().callbacks.input = Some(callback);
 606    }
 607
 608    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 609        self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
 610    }
 611
 612    fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
 613
 614    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 615        self.0.state.borrow_mut().callbacks.resize = Some(callback);
 616    }
 617
 618    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 619        self.0.state.borrow_mut().callbacks.moved = Some(callback);
 620    }
 621
 622    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 623        self.0.state.borrow_mut().callbacks.should_close = Some(callback);
 624    }
 625
 626    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 627        self.0.state.borrow_mut().callbacks.close = Some(callback);
 628    }
 629
 630    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 631        self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
 632    }
 633
 634    fn draw(&self, scene: &Scene) {
 635        self.0.state.borrow_mut().renderer.draw(scene)
 636    }
 637
 638    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 639        self.0.state.borrow().renderer.sprite_atlas().clone()
 640    }
 641
 642    fn get_raw_handle(&self) -> HWND {
 643        self.0.hwnd
 644    }
 645}
 646
 647#[implement(IDropTarget)]
 648struct WindowsDragDropHandler(pub Rc<WindowsWindowStatePtr>);
 649
 650impl WindowsDragDropHandler {
 651    fn handle_drag_drop(&self, input: PlatformInput) {
 652        let mut lock = self.0.state.borrow_mut();
 653        if let Some(mut func) = lock.callbacks.input.take() {
 654            drop(lock);
 655            func(input);
 656            self.0.state.borrow_mut().callbacks.input = Some(func);
 657        }
 658    }
 659}
 660
 661#[allow(non_snake_case)]
 662impl IDropTarget_Impl for WindowsDragDropHandler {
 663    fn DragEnter(
 664        &self,
 665        pdataobj: Option<&IDataObject>,
 666        _grfkeystate: MODIFIERKEYS_FLAGS,
 667        pt: &POINTL,
 668        pdweffect: *mut DROPEFFECT,
 669    ) -> windows::core::Result<()> {
 670        unsafe {
 671            let Some(idata_obj) = pdataobj else {
 672                log::info!("no dragging file or directory detected");
 673                return Ok(());
 674            };
 675            let config = FORMATETC {
 676                cfFormat: CF_HDROP.0,
 677                ptd: std::ptr::null_mut() as _,
 678                dwAspect: DVASPECT_CONTENT.0,
 679                lindex: -1,
 680                tymed: TYMED_HGLOBAL.0 as _,
 681            };
 682            if idata_obj.QueryGetData(&config as _) == S_OK {
 683                *pdweffect = DROPEFFECT_LINK;
 684                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 685                    return Ok(());
 686                };
 687                if idata.u.hGlobal.is_invalid() {
 688                    return Ok(());
 689                }
 690                let hdrop = idata.u.hGlobal.0 as *mut HDROP;
 691                let mut paths = SmallVec::<[PathBuf; 2]>::new();
 692                let file_count = DragQueryFileW(*hdrop, DRAGDROP_GET_FILES_COUNT, None);
 693                for file_index in 0..file_count {
 694                    let filename_length = DragQueryFileW(*hdrop, file_index, None) as usize;
 695                    let mut buffer = vec![0u16; filename_length + 1];
 696                    let ret = DragQueryFileW(*hdrop, file_index, Some(buffer.as_mut_slice()));
 697                    if ret == 0 {
 698                        log::error!("unable to read file name");
 699                        continue;
 700                    }
 701                    if let Some(file_name) =
 702                        String::from_utf16(&buffer[0..filename_length]).log_err()
 703                    {
 704                        if let Some(path) = PathBuf::from_str(&file_name).log_err() {
 705                            paths.push(path);
 706                        }
 707                    }
 708                }
 709                ReleaseStgMedium(&mut idata);
 710                let mut cursor_position = POINT { x: pt.x, y: pt.y };
 711                ScreenToClient(self.0.hwnd, &mut cursor_position)
 712                    .ok()
 713                    .log_err();
 714                let scale_factor = self.0.state.borrow().scale_factor;
 715                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 716                    position: logical_point(
 717                        cursor_position.x as f32,
 718                        cursor_position.y as f32,
 719                        scale_factor,
 720                    ),
 721                    paths: ExternalPaths(paths),
 722                });
 723                self.handle_drag_drop(input);
 724            } else {
 725                *pdweffect = DROPEFFECT_NONE;
 726            }
 727        }
 728        Ok(())
 729    }
 730
 731    fn DragOver(
 732        &self,
 733        _grfkeystate: MODIFIERKEYS_FLAGS,
 734        pt: &POINTL,
 735        _pdweffect: *mut DROPEFFECT,
 736    ) -> windows::core::Result<()> {
 737        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 738        unsafe {
 739            ScreenToClient(self.0.hwnd, &mut cursor_position)
 740                .ok()
 741                .log_err();
 742        }
 743        let scale_factor = self.0.state.borrow().scale_factor;
 744        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
 745            position: logical_point(
 746                cursor_position.x as f32,
 747                cursor_position.y as f32,
 748                scale_factor,
 749            ),
 750        });
 751        self.handle_drag_drop(input);
 752
 753        Ok(())
 754    }
 755
 756    fn DragLeave(&self) -> windows::core::Result<()> {
 757        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
 758        self.handle_drag_drop(input);
 759
 760        Ok(())
 761    }
 762
 763    fn Drop(
 764        &self,
 765        _pdataobj: Option<&IDataObject>,
 766        _grfkeystate: MODIFIERKEYS_FLAGS,
 767        pt: &POINTL,
 768        _pdweffect: *mut DROPEFFECT,
 769    ) -> windows::core::Result<()> {
 770        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 771        unsafe {
 772            ScreenToClient(self.0.hwnd, &mut cursor_position)
 773                .ok()
 774                .log_err();
 775        }
 776        let scale_factor = self.0.state.borrow().scale_factor;
 777        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
 778            position: logical_point(
 779                cursor_position.x as f32,
 780                cursor_position.y as f32,
 781                scale_factor,
 782            ),
 783        });
 784        self.handle_drag_drop(input);
 785
 786        Ok(())
 787    }
 788}
 789
 790#[derive(Debug)]
 791pub(crate) struct ClickState {
 792    button: MouseButton,
 793    last_click: Instant,
 794    last_position: Point<DevicePixels>,
 795    double_click_spatial_tolerance_width: i32,
 796    double_click_spatial_tolerance_height: i32,
 797    double_click_interval: Duration,
 798    pub(crate) current_count: usize,
 799}
 800
 801impl ClickState {
 802    pub fn new() -> Self {
 803        let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
 804        let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
 805        let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
 806
 807        ClickState {
 808            button: MouseButton::Left,
 809            last_click: Instant::now(),
 810            last_position: Point::default(),
 811            double_click_spatial_tolerance_width,
 812            double_click_spatial_tolerance_height,
 813            double_click_interval,
 814            current_count: 0,
 815        }
 816    }
 817
 818    /// update self and return the needed click count
 819    pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
 820        if self.button == button && self.is_double_click(new_position) {
 821            self.current_count += 1;
 822        } else {
 823            self.current_count = 1;
 824        }
 825        self.last_click = Instant::now();
 826        self.last_position = new_position;
 827        self.button = button;
 828
 829        self.current_count
 830    }
 831
 832    pub fn system_update(&mut self) {
 833        self.double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
 834        self.double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
 835        self.double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
 836    }
 837
 838    #[inline]
 839    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
 840        let diff = self.last_position - new_position;
 841
 842        self.last_click.elapsed() < self.double_click_interval
 843            && diff.x.0.abs() <= self.double_click_spatial_tolerance_width
 844            && diff.y.0.abs() <= self.double_click_spatial_tolerance_height
 845    }
 846}
 847
 848struct StyleAndBounds {
 849    style: WINDOW_STYLE,
 850    x: i32,
 851    y: i32,
 852    cx: i32,
 853    cy: i32,
 854}
 855
 856fn register_wnd_class(icon_handle: HICON) -> PCWSTR {
 857    const CLASS_NAME: PCWSTR = w!("Zed::Window");
 858
 859    static ONCE: Once = Once::new();
 860    ONCE.call_once(|| {
 861        let wc = WNDCLASSW {
 862            lpfnWndProc: Some(wnd_proc),
 863            hIcon: icon_handle,
 864            lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
 865            style: CS_HREDRAW | CS_VREDRAW,
 866            hInstance: get_module_handle().into(),
 867            ..Default::default()
 868        };
 869        unsafe { RegisterClassW(&wc) };
 870    });
 871
 872    CLASS_NAME
 873}
 874
 875unsafe extern "system" fn wnd_proc(
 876    hwnd: HWND,
 877    msg: u32,
 878    wparam: WPARAM,
 879    lparam: LPARAM,
 880) -> LRESULT {
 881    if msg == WM_NCCREATE {
 882        let cs = lparam.0 as *const CREATESTRUCTW;
 883        let cs = unsafe { &*cs };
 884        let ctx = cs.lpCreateParams as *mut WindowCreateContext;
 885        let ctx = unsafe { &mut *ctx };
 886        let state_ptr = WindowsWindowStatePtr::new(ctx, hwnd, cs);
 887        let weak = Box::new(Rc::downgrade(&state_ptr));
 888        unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
 889        ctx.inner = Some(state_ptr);
 890        return LRESULT(1);
 891    }
 892    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 893    if ptr.is_null() {
 894        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
 895    }
 896    let inner = unsafe { &*ptr };
 897    let r = if let Some(state) = inner.upgrade() {
 898        handle_msg(hwnd, msg, wparam, lparam, state)
 899    } else {
 900        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
 901    };
 902    if msg == WM_NCDESTROY {
 903        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
 904        unsafe { drop(Box::from_raw(ptr)) };
 905    }
 906    r
 907}
 908
 909pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
 910    if hwnd == HWND(0) {
 911        return None;
 912    }
 913
 914    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 915    if !ptr.is_null() {
 916        let inner = unsafe { &*ptr };
 917        inner.upgrade()
 918    } else {
 919        None
 920    }
 921}
 922
 923fn get_module_handle() -> HMODULE {
 924    unsafe {
 925        let mut h_module = std::mem::zeroed();
 926        GetModuleHandleExW(
 927            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
 928            windows::core::w!("ZedModule"),
 929            &mut h_module,
 930        )
 931        .expect("Unable to get module handle"); // this should never fail
 932
 933        h_module
 934    }
 935}
 936
 937fn register_drag_drop(state_ptr: Rc<WindowsWindowStatePtr>) {
 938    let window_handle = state_ptr.hwnd;
 939    let handler = WindowsDragDropHandler(state_ptr);
 940    // The lifetime of `IDropTarget` is handled by Windows, it wont release untill
 941    // we call `RevokeDragDrop`.
 942    // So, it's safe to drop it here.
 943    let drag_drop_handler: IDropTarget = handler.into();
 944    unsafe {
 945        RegisterDragDrop(window_handle, &drag_drop_handler)
 946            .expect("unable to register drag-drop event")
 947    };
 948}
 949
 950// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-dragqueryfilew
 951const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
 952
 953mod windows_renderer {
 954    use std::{num::NonZeroIsize, sync::Arc};
 955
 956    use blade_graphics as gpu;
 957    use raw_window_handle as rwh;
 958    use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::GWLP_HINSTANCE};
 959
 960    use crate::{
 961        get_window_long,
 962        platform::blade::{BladeRenderer, BladeSurfaceConfig},
 963    };
 964
 965    pub(super) fn windows_renderer(hwnd: HWND, transparent: bool) -> BladeRenderer {
 966        let raw = RawWindow { hwnd: hwnd.0 };
 967        let gpu: Arc<gpu::Context> = Arc::new(
 968            unsafe {
 969                gpu::Context::init_windowed(
 970                    &raw,
 971                    gpu::ContextDesc {
 972                        validation: false,
 973                        capture: false,
 974                        overlay: false,
 975                    },
 976                )
 977            }
 978            .unwrap(),
 979        );
 980        let config = BladeSurfaceConfig {
 981            size: gpu::Extent::default(),
 982            transparent,
 983        };
 984
 985        BladeRenderer::new(gpu, config)
 986    }
 987
 988    struct RawWindow {
 989        hwnd: isize,
 990    }
 991
 992    impl rwh::HasWindowHandle for RawWindow {
 993        fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 994            Ok(unsafe {
 995                let hwnd = NonZeroIsize::new_unchecked(self.hwnd);
 996                let mut handle = rwh::Win32WindowHandle::new(hwnd);
 997                let hinstance = get_window_long(HWND(self.hwnd), GWLP_HINSTANCE);
 998                handle.hinstance = NonZeroIsize::new(hinstance);
 999                rwh::WindowHandle::borrow_raw(handle.into())
1000            })
1001        }
1002    }
1003
1004    impl rwh::HasDisplayHandle for RawWindow {
1005        fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1006            let handle = rwh::WindowsDisplayHandle::new();
1007            Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
1008        }
1009    }
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    use super::ClickState;
1015    use crate::{point, DevicePixels, MouseButton};
1016    use std::time::Duration;
1017
1018    #[test]
1019    fn test_double_click_interval() {
1020        let mut state = ClickState::new();
1021        assert_eq!(
1022            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1023            1
1024        );
1025        assert_eq!(
1026            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1027            1
1028        );
1029        assert_eq!(
1030            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1031            1
1032        );
1033        assert_eq!(
1034            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1035            2
1036        );
1037        state.last_click -= Duration::from_millis(700);
1038        assert_eq!(
1039            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1040            1
1041        );
1042    }
1043
1044    #[test]
1045    fn test_double_click_spatial_tolerance() {
1046        let mut state = ClickState::new();
1047        assert_eq!(
1048            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1049            1
1050        );
1051        assert_eq!(
1052            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1053            2
1054        );
1055        assert_eq!(
1056            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1057            1
1058        );
1059        assert_eq!(
1060            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1061            1
1062        );
1063    }
1064}