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