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