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