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