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