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