window.rs

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