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    fn gpu_specs(&self) -> Option<GPUSpecs> {
 659        Some(self.0.state.borrow().renderer.gpu_specs())
 660    }
 661}
 662
 663#[implement(IDropTarget)]
 664struct WindowsDragDropHandler(pub Rc<WindowsWindowStatePtr>);
 665
 666impl WindowsDragDropHandler {
 667    fn handle_drag_drop(&self, input: PlatformInput) {
 668        let mut lock = self.0.state.borrow_mut();
 669        if let Some(mut func) = lock.callbacks.input.take() {
 670            drop(lock);
 671            func(input);
 672            self.0.state.borrow_mut().callbacks.input = Some(func);
 673        }
 674    }
 675}
 676
 677#[allow(non_snake_case)]
 678impl IDropTarget_Impl for WindowsDragDropHandler {
 679    fn DragEnter(
 680        &self,
 681        pdataobj: Option<&IDataObject>,
 682        _grfkeystate: MODIFIERKEYS_FLAGS,
 683        pt: &POINTL,
 684        pdweffect: *mut DROPEFFECT,
 685    ) -> windows::core::Result<()> {
 686        unsafe {
 687            let Some(idata_obj) = pdataobj else {
 688                log::info!("no dragging file or directory detected");
 689                return Ok(());
 690            };
 691            let config = FORMATETC {
 692                cfFormat: CF_HDROP.0,
 693                ptd: std::ptr::null_mut() as _,
 694                dwAspect: DVASPECT_CONTENT.0,
 695                lindex: -1,
 696                tymed: TYMED_HGLOBAL.0 as _,
 697            };
 698            if idata_obj.QueryGetData(&config as _) == S_OK {
 699                *pdweffect = DROPEFFECT_LINK;
 700                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 701                    return Ok(());
 702                };
 703                if idata.u.hGlobal.is_invalid() {
 704                    return Ok(());
 705                }
 706                let hdrop = idata.u.hGlobal.0 as *mut HDROP;
 707                let mut paths = SmallVec::<[PathBuf; 2]>::new();
 708                let file_count = DragQueryFileW(*hdrop, DRAGDROP_GET_FILES_COUNT, None);
 709                for file_index in 0..file_count {
 710                    let filename_length = DragQueryFileW(*hdrop, file_index, None) as usize;
 711                    let mut buffer = vec![0u16; filename_length + 1];
 712                    let ret = DragQueryFileW(*hdrop, file_index, Some(buffer.as_mut_slice()));
 713                    if ret == 0 {
 714                        log::error!("unable to read file name");
 715                        continue;
 716                    }
 717                    if let Some(file_name) =
 718                        String::from_utf16(&buffer[0..filename_length]).log_err()
 719                    {
 720                        if let Some(path) = PathBuf::from_str(&file_name).log_err() {
 721                            paths.push(path);
 722                        }
 723                    }
 724                }
 725                ReleaseStgMedium(&mut idata);
 726                let mut cursor_position = POINT { x: pt.x, y: pt.y };
 727                ScreenToClient(self.0.hwnd, &mut cursor_position)
 728                    .ok()
 729                    .log_err();
 730                let scale_factor = self.0.state.borrow().scale_factor;
 731                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 732                    position: logical_point(
 733                        cursor_position.x as f32,
 734                        cursor_position.y as f32,
 735                        scale_factor,
 736                    ),
 737                    paths: ExternalPaths(paths),
 738                });
 739                self.handle_drag_drop(input);
 740            } else {
 741                *pdweffect = DROPEFFECT_NONE;
 742            }
 743        }
 744        Ok(())
 745    }
 746
 747    fn DragOver(
 748        &self,
 749        _grfkeystate: MODIFIERKEYS_FLAGS,
 750        pt: &POINTL,
 751        _pdweffect: *mut DROPEFFECT,
 752    ) -> windows::core::Result<()> {
 753        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 754        unsafe {
 755            ScreenToClient(self.0.hwnd, &mut cursor_position)
 756                .ok()
 757                .log_err();
 758        }
 759        let scale_factor = self.0.state.borrow().scale_factor;
 760        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
 761            position: logical_point(
 762                cursor_position.x as f32,
 763                cursor_position.y as f32,
 764                scale_factor,
 765            ),
 766        });
 767        self.handle_drag_drop(input);
 768
 769        Ok(())
 770    }
 771
 772    fn DragLeave(&self) -> windows::core::Result<()> {
 773        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
 774        self.handle_drag_drop(input);
 775
 776        Ok(())
 777    }
 778
 779    fn Drop(
 780        &self,
 781        _pdataobj: Option<&IDataObject>,
 782        _grfkeystate: MODIFIERKEYS_FLAGS,
 783        pt: &POINTL,
 784        _pdweffect: *mut DROPEFFECT,
 785    ) -> windows::core::Result<()> {
 786        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 787        unsafe {
 788            ScreenToClient(self.0.hwnd, &mut cursor_position)
 789                .ok()
 790                .log_err();
 791        }
 792        let scale_factor = self.0.state.borrow().scale_factor;
 793        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
 794            position: logical_point(
 795                cursor_position.x as f32,
 796                cursor_position.y as f32,
 797                scale_factor,
 798            ),
 799        });
 800        self.handle_drag_drop(input);
 801
 802        Ok(())
 803    }
 804}
 805
 806#[derive(Debug)]
 807pub(crate) struct ClickState {
 808    button: MouseButton,
 809    last_click: Instant,
 810    last_position: Point<DevicePixels>,
 811    double_click_spatial_tolerance_width: i32,
 812    double_click_spatial_tolerance_height: i32,
 813    double_click_interval: Duration,
 814    pub(crate) current_count: usize,
 815}
 816
 817impl ClickState {
 818    pub fn new() -> Self {
 819        let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
 820        let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
 821        let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
 822
 823        ClickState {
 824            button: MouseButton::Left,
 825            last_click: Instant::now(),
 826            last_position: Point::default(),
 827            double_click_spatial_tolerance_width,
 828            double_click_spatial_tolerance_height,
 829            double_click_interval,
 830            current_count: 0,
 831        }
 832    }
 833
 834    /// update self and return the needed click count
 835    pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
 836        if self.button == button && self.is_double_click(new_position) {
 837            self.current_count += 1;
 838        } else {
 839            self.current_count = 1;
 840        }
 841        self.last_click = Instant::now();
 842        self.last_position = new_position;
 843        self.button = button;
 844
 845        self.current_count
 846    }
 847
 848    pub fn system_update(&mut self) {
 849        self.double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
 850        self.double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
 851        self.double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
 852    }
 853
 854    #[inline]
 855    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
 856        let diff = self.last_position - new_position;
 857
 858        self.last_click.elapsed() < self.double_click_interval
 859            && diff.x.0.abs() <= self.double_click_spatial_tolerance_width
 860            && diff.y.0.abs() <= self.double_click_spatial_tolerance_height
 861    }
 862}
 863
 864struct StyleAndBounds {
 865    style: WINDOW_STYLE,
 866    x: i32,
 867    y: i32,
 868    cx: i32,
 869    cy: i32,
 870}
 871
 872#[derive(Debug, Default, Clone, Copy)]
 873pub(crate) struct WindowBorderOffset {
 874    width_offset: i32,
 875    height_offset: i32,
 876}
 877
 878impl WindowBorderOffset {
 879    pub(crate) fn udpate(&mut self, hwnd: HWND) -> anyhow::Result<()> {
 880        let window_rect = unsafe {
 881            let mut rect = std::mem::zeroed();
 882            GetWindowRect(hwnd, &mut rect)?;
 883            rect
 884        };
 885        let client_rect = unsafe {
 886            let mut rect = std::mem::zeroed();
 887            GetClientRect(hwnd, &mut rect)?;
 888            rect
 889        };
 890        self.width_offset =
 891            (window_rect.right - window_rect.left) - (client_rect.right - client_rect.left);
 892        self.height_offset =
 893            (window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top);
 894        Ok(())
 895    }
 896}
 897
 898fn register_wnd_class(icon_handle: HICON) -> PCWSTR {
 899    const CLASS_NAME: PCWSTR = w!("Zed::Window");
 900
 901    static ONCE: Once = Once::new();
 902    ONCE.call_once(|| {
 903        let wc = WNDCLASSW {
 904            lpfnWndProc: Some(wnd_proc),
 905            hIcon: icon_handle,
 906            lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
 907            style: CS_HREDRAW | CS_VREDRAW,
 908            hInstance: get_module_handle().into(),
 909            ..Default::default()
 910        };
 911        unsafe { RegisterClassW(&wc) };
 912    });
 913
 914    CLASS_NAME
 915}
 916
 917unsafe extern "system" fn wnd_proc(
 918    hwnd: HWND,
 919    msg: u32,
 920    wparam: WPARAM,
 921    lparam: LPARAM,
 922) -> LRESULT {
 923    if msg == WM_NCCREATE {
 924        let cs = lparam.0 as *const CREATESTRUCTW;
 925        let cs = unsafe { &*cs };
 926        let ctx = cs.lpCreateParams as *mut WindowCreateContext;
 927        let ctx = unsafe { &mut *ctx };
 928        let creation_result = WindowsWindowStatePtr::new(ctx, hwnd, cs);
 929        if creation_result.is_err() {
 930            ctx.inner = Some(creation_result);
 931            return LRESULT(0);
 932        }
 933        let weak = Box::new(Rc::downgrade(creation_result.as_ref().unwrap()));
 934        unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
 935        ctx.inner = Some(creation_result);
 936        return LRESULT(1);
 937    }
 938    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 939    if ptr.is_null() {
 940        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
 941    }
 942    let inner = unsafe { &*ptr };
 943    let r = if let Some(state) = inner.upgrade() {
 944        handle_msg(hwnd, msg, wparam, lparam, state)
 945    } else {
 946        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
 947    };
 948    if msg == WM_NCDESTROY {
 949        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
 950        unsafe { drop(Box::from_raw(ptr)) };
 951    }
 952    r
 953}
 954
 955pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
 956    if hwnd == HWND(0) {
 957        return None;
 958    }
 959
 960    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
 961    if !ptr.is_null() {
 962        let inner = unsafe { &*ptr };
 963        inner.upgrade()
 964    } else {
 965        None
 966    }
 967}
 968
 969fn get_module_handle() -> HMODULE {
 970    unsafe {
 971        let mut h_module = std::mem::zeroed();
 972        GetModuleHandleExW(
 973            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
 974            windows::core::w!("ZedModule"),
 975            &mut h_module,
 976        )
 977        .expect("Unable to get module handle"); // this should never fail
 978
 979        h_module
 980    }
 981}
 982
 983fn register_drag_drop(state_ptr: Rc<WindowsWindowStatePtr>) -> Result<()> {
 984    let window_handle = state_ptr.hwnd;
 985    let handler = WindowsDragDropHandler(state_ptr);
 986    // The lifetime of `IDropTarget` is handled by Windows, it wont release untill
 987    // we call `RevokeDragDrop`.
 988    // So, it's safe to drop it here.
 989    let drag_drop_handler: IDropTarget = handler.into();
 990    unsafe {
 991        RegisterDragDrop(window_handle, &drag_drop_handler)
 992            .context("unable to register drag-drop event")?;
 993    }
 994    Ok(())
 995}
 996
 997fn calcualte_window_rect(bounds: Bounds<DevicePixels>, border_offset: WindowBorderOffset) -> RECT {
 998    // NOTE:
 999    // The reason that not using `AdjustWindowRectEx()` here is
1000    // that the size reported by this function is incorrect.
1001    // You can test it, and there are similar discussions online.
1002    // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1003    //
1004    // So we manually calculate these values here.
1005    let mut rect = RECT {
1006        left: bounds.left().0,
1007        top: bounds.top().0,
1008        right: bounds.right().0,
1009        bottom: bounds.bottom().0,
1010    };
1011    let left_offset = border_offset.width_offset / 2;
1012    let top_offset = border_offset.height_offset / 2;
1013    let right_offset = border_offset.width_offset - left_offset;
1014    let bottom_offet = border_offset.height_offset - top_offset;
1015    rect.left -= left_offset;
1016    rect.top -= top_offset;
1017    rect.right += right_offset;
1018    rect.bottom += bottom_offet;
1019    rect
1020}
1021
1022fn calculate_client_rect(
1023    rect: RECT,
1024    border_offset: WindowBorderOffset,
1025    scale_factor: f32,
1026) -> Bounds<Pixels> {
1027    let left_offset = border_offset.width_offset / 2;
1028    let top_offset = border_offset.height_offset / 2;
1029    let right_offset = border_offset.width_offset - left_offset;
1030    let bottom_offet = border_offset.height_offset - top_offset;
1031    let left = rect.left + left_offset;
1032    let top = rect.top + top_offset;
1033    let right = rect.right - right_offset;
1034    let bottom = rect.bottom - bottom_offet;
1035    let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1036    Bounds {
1037        origin: logical_point(left as f32, top as f32, scale_factor),
1038        size: physical_size.to_pixels(scale_factor),
1039    }
1040}
1041
1042// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-dragqueryfilew
1043const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
1044
1045mod windows_renderer {
1046    use std::{num::NonZeroIsize, sync::Arc};
1047
1048    use blade_graphics as gpu;
1049    use raw_window_handle as rwh;
1050    use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::GWLP_HINSTANCE};
1051
1052    use crate::{
1053        get_window_long,
1054        platform::blade::{BladeRenderer, BladeSurfaceConfig},
1055    };
1056
1057    pub(super) fn windows_renderer(hwnd: HWND, transparent: bool) -> anyhow::Result<BladeRenderer> {
1058        let raw = RawWindow { hwnd: hwnd.0 };
1059        let gpu: Arc<gpu::Context> = Arc::new(
1060            unsafe {
1061                gpu::Context::init_windowed(
1062                    &raw,
1063                    gpu::ContextDesc {
1064                        validation: false,
1065                        capture: false,
1066                        overlay: false,
1067                    },
1068                )
1069            }
1070            .map_err(|e| anyhow::anyhow!("{:?}", e))?,
1071        );
1072        let config = BladeSurfaceConfig {
1073            size: gpu::Extent::default(),
1074            transparent,
1075        };
1076
1077        Ok(BladeRenderer::new(gpu, config))
1078    }
1079
1080    struct RawWindow {
1081        hwnd: isize,
1082    }
1083
1084    impl rwh::HasWindowHandle for RawWindow {
1085        fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1086            Ok(unsafe {
1087                let hwnd = NonZeroIsize::new_unchecked(self.hwnd);
1088                let mut handle = rwh::Win32WindowHandle::new(hwnd);
1089                let hinstance = get_window_long(HWND(self.hwnd), GWLP_HINSTANCE);
1090                handle.hinstance = NonZeroIsize::new(hinstance);
1091                rwh::WindowHandle::borrow_raw(handle.into())
1092            })
1093        }
1094    }
1095
1096    impl rwh::HasDisplayHandle for RawWindow {
1097        fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1098            let handle = rwh::WindowsDisplayHandle::new();
1099            Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
1100        }
1101    }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106    use super::ClickState;
1107    use crate::{point, DevicePixels, MouseButton};
1108    use std::time::Duration;
1109
1110    #[test]
1111    fn test_double_click_interval() {
1112        let mut state = ClickState::new();
1113        assert_eq!(
1114            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1115            1
1116        );
1117        assert_eq!(
1118            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1119            1
1120        );
1121        assert_eq!(
1122            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1123            1
1124        );
1125        assert_eq!(
1126            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1127            2
1128        );
1129        state.last_click -= Duration::from_millis(700);
1130        assert_eq!(
1131            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1132            1
1133        );
1134    }
1135
1136    #[test]
1137    fn test_double_click_spatial_tolerance() {
1138        let mut state = ClickState::new();
1139        assert_eq!(
1140            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1141            1
1142        );
1143        assert_eq!(
1144            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1145            2
1146        );
1147        assert_eq!(
1148            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1149            1
1150        );
1151        assert_eq!(
1152            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1153            1
1154        );
1155    }
1156}