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