window.rs

   1#![deny(unsafe_op_in_unsafe_fn)]
   2
   3use std::{
   4    cell::{Cell, RefCell},
   5    num::NonZeroIsize,
   6    path::PathBuf,
   7    rc::{Rc, Weak},
   8    str::FromStr,
   9    sync::{Arc, Once, atomic::AtomicBool},
  10    time::{Duration, Instant},
  11};
  12
  13use ::util::ResultExt;
  14use anyhow::{Context as _, Result};
  15use futures::channel::oneshot::{self, Receiver};
  16use raw_window_handle as rwh;
  17use smallvec::SmallVec;
  18use windows::{
  19    Win32::{
  20        Foundation::*,
  21        Graphics::Dwm::*,
  22        Graphics::Gdi::*,
  23        System::{
  24            Com::*, Diagnostics::Debug::MessageBeep, LibraryLoader::*, Ole::*, SystemServices::*,
  25        },
  26        UI::{Controls::*, HiDpi::*, Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
  27    },
  28    core::*,
  29};
  30
  31use crate::direct_manipulation::DirectManipulationHandler;
  32use crate::*;
  33use gpui::*;
  34
  35pub(crate) struct WindowsWindow(pub Rc<WindowsWindowInner>);
  36
  37impl std::ops::Deref for WindowsWindow {
  38    type Target = WindowsWindowInner;
  39
  40    fn deref(&self) -> &Self::Target {
  41        &self.0
  42    }
  43}
  44
  45pub struct WindowsWindowState {
  46    pub origin: Cell<Point<Pixels>>,
  47    pub logical_size: Cell<Size<Pixels>>,
  48    pub min_size: Option<Size<Pixels>>,
  49    pub fullscreen_restore_bounds: Cell<Bounds<Pixels>>,
  50    pub border_offset: WindowBorderOffset,
  51    pub appearance: Cell<WindowAppearance>,
  52    pub background_appearance: Cell<WindowBackgroundAppearance>,
  53    pub scale_factor: Cell<f32>,
  54    pub restore_from_minimized: Cell<Option<Box<dyn FnMut(RequestFrameOptions)>>>,
  55
  56    pub callbacks: Callbacks,
  57    pub input_handler: Cell<Option<PlatformInputHandler>>,
  58    pub ime_enabled: Cell<bool>,
  59    pub pending_surrogate: Cell<Option<u16>>,
  60    pub last_reported_modifiers: Cell<Option<Modifiers>>,
  61    pub last_reported_capslock: Cell<Option<Capslock>>,
  62    pub hovered: Cell<bool>,
  63    pub direct_manipulation: DirectManipulationHandler,
  64
  65    pub renderer: RefCell<DirectXRenderer>,
  66
  67    pub click_state: ClickState,
  68    pub current_cursor: Cell<Option<HCURSOR>>,
  69    pub nc_button_pressed: Cell<Option<u32>>,
  70
  71    pub display: Cell<WindowsDisplay>,
  72    /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
  73    /// as resizing them has failed, causing us to have lost at least the render target.
  74    pub invalidate_devices: Arc<AtomicBool>,
  75    fullscreen: Cell<Option<StyleAndBounds>>,
  76    initial_placement: Cell<Option<WindowOpenStatus>>,
  77    hwnd: HWND,
  78}
  79
  80pub(crate) struct WindowsWindowInner {
  81    hwnd: HWND,
  82    drop_target_helper: IDropTargetHelper,
  83    pub(crate) state: WindowsWindowState,
  84    system_settings: WindowsSystemSettings,
  85    pub(crate) handle: AnyWindowHandle,
  86    pub(crate) hide_title_bar: bool,
  87    pub(crate) is_movable: bool,
  88    pub(crate) executor: ForegroundExecutor,
  89    pub(crate) validation_number: usize,
  90    pub(crate) main_receiver: PriorityQueueReceiver<RunnableVariant>,
  91    pub(crate) platform_window_handle: HWND,
  92    pub(crate) parent_hwnd: Option<HWND>,
  93}
  94
  95impl WindowsWindowState {
  96    fn new(
  97        hwnd: HWND,
  98        directx_devices: &DirectXDevices,
  99        window_params: &CREATESTRUCTW,
 100        current_cursor: Option<HCURSOR>,
 101        display: WindowsDisplay,
 102        min_size: Option<Size<Pixels>>,
 103        appearance: WindowAppearance,
 104        disable_direct_composition: bool,
 105        invalidate_devices: Arc<AtomicBool>,
 106    ) -> Result<Self> {
 107        let scale_factor = {
 108            let monitor_dpi = unsafe { GetDpiForWindow(hwnd) } as f32;
 109            monitor_dpi / USER_DEFAULT_SCREEN_DPI as f32
 110        };
 111        let origin = logical_point(window_params.x as f32, window_params.y as f32, scale_factor);
 112        let logical_size = {
 113            let physical_size = size(
 114                DevicePixels(window_params.cx),
 115                DevicePixels(window_params.cy),
 116            );
 117            physical_size.to_pixels(scale_factor)
 118        };
 119        let fullscreen_restore_bounds = Bounds {
 120            origin,
 121            size: logical_size,
 122        };
 123        let border_offset = WindowBorderOffset::default();
 124        let restore_from_minimized = None;
 125        let renderer = DirectXRenderer::new(hwnd, directx_devices, disable_direct_composition)
 126            .context("Creating DirectX renderer")?;
 127        let callbacks = Callbacks::default();
 128        let input_handler = None;
 129        let pending_surrogate = None;
 130        let last_reported_modifiers = None;
 131        let last_reported_capslock = None;
 132        let hovered = false;
 133        let click_state = ClickState::new();
 134        let nc_button_pressed = None;
 135        let fullscreen = None;
 136        let initial_placement = None;
 137
 138        let direct_manipulation = DirectManipulationHandler::new(hwnd, scale_factor)
 139            .context("initializing Direct Manipulation")?;
 140
 141        Ok(Self {
 142            origin: Cell::new(origin),
 143            logical_size: Cell::new(logical_size),
 144            fullscreen_restore_bounds: Cell::new(fullscreen_restore_bounds),
 145            border_offset,
 146            appearance: Cell::new(appearance),
 147            background_appearance: Cell::new(WindowBackgroundAppearance::Opaque),
 148            scale_factor: Cell::new(scale_factor),
 149            restore_from_minimized: Cell::new(restore_from_minimized),
 150            min_size,
 151            callbacks,
 152            input_handler: Cell::new(input_handler),
 153            ime_enabled: Cell::new(true),
 154            pending_surrogate: Cell::new(pending_surrogate),
 155            last_reported_modifiers: Cell::new(last_reported_modifiers),
 156            last_reported_capslock: Cell::new(last_reported_capslock),
 157            hovered: Cell::new(hovered),
 158            renderer: RefCell::new(renderer),
 159            click_state,
 160            current_cursor: Cell::new(current_cursor),
 161            nc_button_pressed: Cell::new(nc_button_pressed),
 162            display: Cell::new(display),
 163            fullscreen: Cell::new(fullscreen),
 164            initial_placement: Cell::new(initial_placement),
 165            hwnd,
 166            invalidate_devices,
 167            direct_manipulation,
 168        })
 169    }
 170
 171    #[inline]
 172    pub(crate) fn is_fullscreen(&self) -> bool {
 173        self.fullscreen.get().is_some()
 174    }
 175
 176    pub(crate) fn is_maximized(&self) -> bool {
 177        !self.is_fullscreen() && unsafe { IsZoomed(self.hwnd) }.as_bool()
 178    }
 179
 180    fn bounds(&self) -> Bounds<Pixels> {
 181        Bounds {
 182            origin: self.origin.get(),
 183            size: self.logical_size.get(),
 184        }
 185    }
 186
 187    // Calculate the bounds used for saving and whether the window is maximized.
 188    fn calculate_window_bounds(&self) -> (Bounds<Pixels>, bool) {
 189        let placement = unsafe {
 190            let mut placement = WINDOWPLACEMENT {
 191                length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
 192                ..Default::default()
 193            };
 194            GetWindowPlacement(self.hwnd, &mut placement)
 195                .context("failed to get window placement")
 196                .log_err();
 197            placement
 198        };
 199        (
 200            calculate_client_rect(
 201                placement.rcNormalPosition,
 202                &self.border_offset,
 203                self.scale_factor.get(),
 204            ),
 205            placement.showCmd == SW_SHOWMAXIMIZED.0 as u32,
 206        )
 207    }
 208
 209    fn window_bounds(&self) -> WindowBounds {
 210        let (bounds, maximized) = self.calculate_window_bounds();
 211
 212        if self.is_fullscreen() {
 213            WindowBounds::Fullscreen(self.fullscreen_restore_bounds.get())
 214        } else if maximized {
 215            WindowBounds::Maximized(bounds)
 216        } else {
 217            WindowBounds::Windowed(bounds)
 218        }
 219    }
 220
 221    /// get the logical size of the app's drawable area.
 222    ///
 223    /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
 224    /// whether the mouse collides with other elements of GPUI).
 225    fn content_size(&self) -> Size<Pixels> {
 226        self.logical_size.get()
 227    }
 228}
 229
 230impl WindowsWindowInner {
 231    fn new(context: &mut WindowCreateContext, hwnd: HWND, cs: &CREATESTRUCTW) -> Result<Rc<Self>> {
 232        let state = WindowsWindowState::new(
 233            hwnd,
 234            &context.directx_devices,
 235            cs,
 236            context.current_cursor,
 237            context.display,
 238            context.min_size,
 239            context.appearance,
 240            context.disable_direct_composition,
 241            context.invalidate_devices.clone(),
 242        )?;
 243
 244        Ok(Rc::new(Self {
 245            hwnd,
 246            drop_target_helper: context.drop_target_helper.clone(),
 247            state,
 248            handle: context.handle,
 249            hide_title_bar: context.hide_title_bar,
 250            is_movable: context.is_movable,
 251            executor: context.executor.clone(),
 252            validation_number: context.validation_number,
 253            main_receiver: context.main_receiver.clone(),
 254            platform_window_handle: context.platform_window_handle,
 255            system_settings: WindowsSystemSettings::new(),
 256            parent_hwnd: context.parent_hwnd,
 257        }))
 258    }
 259
 260    fn toggle_fullscreen(self: &Rc<Self>) {
 261        let this = self.clone();
 262        self.executor
 263            .spawn(async move {
 264                let StyleAndBounds {
 265                    style,
 266                    x,
 267                    y,
 268                    cx,
 269                    cy,
 270                } = match this.state.fullscreen.take() {
 271                    Some(state) => state,
 272                    None => {
 273                        let (window_bounds, _) = this.state.calculate_window_bounds();
 274                        this.state.fullscreen_restore_bounds.set(window_bounds);
 275
 276                        let style =
 277                            WINDOW_STYLE(unsafe { get_window_long(this.hwnd, GWL_STYLE) } as _);
 278                        let mut rc = RECT::default();
 279                        unsafe { GetWindowRect(this.hwnd, &mut rc) }
 280                            .context("failed to get window rect")
 281                            .log_err();
 282                        let _ = this.state.fullscreen.set(Some(StyleAndBounds {
 283                            style,
 284                            x: rc.left,
 285                            y: rc.top,
 286                            cx: rc.right - rc.left,
 287                            cy: rc.bottom - rc.top,
 288                        }));
 289                        let style = style
 290                            & !(WS_THICKFRAME
 291                                | WS_SYSMENU
 292                                | WS_MAXIMIZEBOX
 293                                | WS_MINIMIZEBOX
 294                                | WS_CAPTION);
 295                        let physical_bounds = this.state.display.get().physical_bounds();
 296                        StyleAndBounds {
 297                            style,
 298                            x: physical_bounds.left().0,
 299                            y: physical_bounds.top().0,
 300                            cx: physical_bounds.size.width.0,
 301                            cy: physical_bounds.size.height.0,
 302                        }
 303                    }
 304                };
 305                set_non_rude_hwnd(this.hwnd, !this.state.is_fullscreen());
 306                unsafe { set_window_long(this.hwnd, GWL_STYLE, style.0 as isize) };
 307                unsafe {
 308                    SetWindowPos(
 309                        this.hwnd,
 310                        None,
 311                        x,
 312                        y,
 313                        cx,
 314                        cy,
 315                        SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER,
 316                    )
 317                }
 318                .log_err();
 319            })
 320            .detach();
 321    }
 322
 323    fn set_window_placement(self: &Rc<Self>) -> Result<()> {
 324        let Some(open_status) = self.state.initial_placement.take() else {
 325            return Ok(());
 326        };
 327        match open_status.state {
 328            WindowOpenState::Maximized => unsafe {
 329                SetWindowPlacement(self.hwnd, &open_status.placement)
 330                    .context("failed to set window placement")?;
 331                ShowWindowAsync(self.hwnd, SW_MAXIMIZE).ok()?;
 332            },
 333            WindowOpenState::Fullscreen => {
 334                unsafe {
 335                    SetWindowPlacement(self.hwnd, &open_status.placement)
 336                        .context("failed to set window placement")?
 337                };
 338                self.toggle_fullscreen();
 339            }
 340            WindowOpenState::Windowed => unsafe {
 341                SetWindowPlacement(self.hwnd, &open_status.placement)
 342                    .context("failed to set window placement")?;
 343            },
 344        }
 345        Ok(())
 346    }
 347
 348    pub(crate) fn system_settings(&self) -> &WindowsSystemSettings {
 349        &self.system_settings
 350    }
 351}
 352
 353#[derive(Default)]
 354pub(crate) struct Callbacks {
 355    pub(crate) request_frame: Cell<Option<Box<dyn FnMut(RequestFrameOptions)>>>,
 356    pub(crate) input: Cell<Option<Box<dyn FnMut(PlatformInput) -> DispatchEventResult>>>,
 357    pub(crate) active_status_change: Cell<Option<Box<dyn FnMut(bool)>>>,
 358    pub(crate) hovered_status_change: Cell<Option<Box<dyn FnMut(bool)>>>,
 359    pub(crate) resize: Cell<Option<Box<dyn FnMut(Size<Pixels>, f32)>>>,
 360    pub(crate) moved: Cell<Option<Box<dyn FnMut()>>>,
 361    pub(crate) should_close: Cell<Option<Box<dyn FnMut() -> bool>>>,
 362    pub(crate) close: Cell<Option<Box<dyn FnOnce()>>>,
 363    pub(crate) hit_test_window_control: Cell<Option<Box<dyn FnMut() -> Option<WindowControlArea>>>>,
 364    pub(crate) appearance_changed: Cell<Option<Box<dyn FnMut()>>>,
 365}
 366
 367struct WindowCreateContext {
 368    inner: Option<Result<Rc<WindowsWindowInner>>>,
 369    handle: AnyWindowHandle,
 370    hide_title_bar: bool,
 371    display: WindowsDisplay,
 372    is_movable: bool,
 373    min_size: Option<Size<Pixels>>,
 374    executor: ForegroundExecutor,
 375    current_cursor: Option<HCURSOR>,
 376    drop_target_helper: IDropTargetHelper,
 377    validation_number: usize,
 378    main_receiver: PriorityQueueReceiver<RunnableVariant>,
 379    platform_window_handle: HWND,
 380    appearance: WindowAppearance,
 381    disable_direct_composition: bool,
 382    directx_devices: DirectXDevices,
 383    invalidate_devices: Arc<AtomicBool>,
 384    parent_hwnd: Option<HWND>,
 385}
 386
 387impl WindowsWindow {
 388    pub(crate) fn new(
 389        handle: AnyWindowHandle,
 390        params: WindowParams,
 391        creation_info: WindowCreationInfo,
 392    ) -> Result<Self> {
 393        let WindowCreationInfo {
 394            icon,
 395            executor,
 396            current_cursor,
 397            drop_target_helper,
 398            validation_number,
 399            main_receiver,
 400            platform_window_handle,
 401            disable_direct_composition,
 402            directx_devices,
 403            invalidate_devices,
 404        } = creation_info;
 405        register_window_class(icon);
 406        let parent_hwnd = if params.kind == WindowKind::Dialog {
 407            let parent_window = unsafe { GetActiveWindow() };
 408            if parent_window.is_invalid() {
 409                None
 410            } else {
 411                // Disable the parent window to make this dialog modal
 412                unsafe {
 413                    EnableWindow(parent_window, false).as_bool();
 414                };
 415                Some(parent_window)
 416            }
 417        } else {
 418            None
 419        };
 420        let hide_title_bar = params
 421            .titlebar
 422            .as_ref()
 423            .map(|titlebar| titlebar.appears_transparent)
 424            .unwrap_or(true);
 425        let window_name = HSTRING::from(
 426            params
 427                .titlebar
 428                .as_ref()
 429                .and_then(|titlebar| titlebar.title.as_ref())
 430                .map(|title| title.as_ref())
 431                .unwrap_or(""),
 432        );
 433
 434        let (mut dwexstyle, dwstyle) = if params.kind == WindowKind::PopUp {
 435            (WS_EX_TOOLWINDOW, WINDOW_STYLE(0x0))
 436        } else {
 437            let mut dwstyle = WS_SYSMENU;
 438
 439            if params.is_resizable {
 440                dwstyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
 441            }
 442
 443            if params.is_minimizable {
 444                dwstyle |= WS_MINIMIZEBOX;
 445            }
 446            let dwexstyle = if params.kind == WindowKind::Dialog {
 447                dwstyle |= WS_POPUP | WS_CAPTION;
 448                WS_EX_DLGMODALFRAME
 449            } else {
 450                WS_EX_APPWINDOW
 451            };
 452
 453            (dwexstyle, dwstyle)
 454        };
 455        if !disable_direct_composition {
 456            dwexstyle |= WS_EX_NOREDIRECTIONBITMAP;
 457        }
 458
 459        let hinstance = get_module_handle();
 460        let display = if let Some(display_id) = params.display_id {
 461            // if we obtain a display_id, then this ID must be valid.
 462            WindowsDisplay::new(display_id).unwrap()
 463        } else {
 464            WindowsDisplay::primary_monitor().unwrap()
 465        };
 466        let appearance = system_appearance().unwrap_or_default();
 467        let mut context = WindowCreateContext {
 468            inner: None,
 469            handle,
 470            hide_title_bar,
 471            display,
 472            is_movable: params.is_movable,
 473            min_size: params.window_min_size,
 474            executor,
 475            current_cursor,
 476            drop_target_helper,
 477            validation_number,
 478            main_receiver,
 479            platform_window_handle,
 480            appearance,
 481            disable_direct_composition,
 482            directx_devices,
 483            invalidate_devices,
 484            parent_hwnd,
 485        };
 486        let creation_result = unsafe {
 487            CreateWindowExW(
 488                dwexstyle,
 489                WINDOW_CLASS_NAME,
 490                &window_name,
 491                dwstyle,
 492                CW_USEDEFAULT,
 493                CW_USEDEFAULT,
 494                CW_USEDEFAULT,
 495                CW_USEDEFAULT,
 496                parent_hwnd,
 497                None,
 498                Some(hinstance.into()),
 499                Some(&context as *const _ as *const _),
 500            )
 501        };
 502
 503        // Failure to create a `WindowsWindowState` can cause window creation to fail,
 504        // so check the inner result first.
 505        let this = context.inner.take().transpose()?;
 506        let hwnd = creation_result?;
 507        let this = this.unwrap();
 508
 509        register_drag_drop(&this)?;
 510        set_non_rude_hwnd(hwnd, true);
 511        configure_dwm_dark_mode(hwnd, appearance);
 512        this.state.border_offset.update(hwnd)?;
 513        let placement = retrieve_window_placement(
 514            hwnd,
 515            display,
 516            params.bounds,
 517            this.state.scale_factor.get(),
 518            &this.state.border_offset,
 519        )?;
 520        if params.show {
 521            unsafe { SetWindowPlacement(hwnd, &placement)? };
 522        } else {
 523            this.state.initial_placement.set(Some(WindowOpenStatus {
 524                placement,
 525                state: WindowOpenState::Windowed,
 526            }));
 527        }
 528
 529        Ok(Self(this))
 530    }
 531}
 532
 533impl rwh::HasWindowHandle for WindowsWindow {
 534    fn window_handle(&self) -> std::result::Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 535        let raw = rwh::Win32WindowHandle::new(unsafe {
 536            NonZeroIsize::new_unchecked(self.0.hwnd.0 as isize)
 537        })
 538        .into();
 539        Ok(unsafe { rwh::WindowHandle::borrow_raw(raw) })
 540    }
 541}
 542
 543impl rwh::HasDisplayHandle for WindowsWindow {
 544    fn display_handle(&self) -> std::result::Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 545        Ok(rwh::DisplayHandle::windows())
 546    }
 547}
 548
 549impl Drop for WindowsWindow {
 550    fn drop(&mut self) {
 551        // clone this `Rc` to prevent early release of the pointer
 552        let this = self.0.clone();
 553        self.0
 554            .executor
 555            .spawn(async move {
 556                let handle = this.hwnd;
 557                unsafe {
 558                    RevokeDragDrop(handle).log_err();
 559                    DestroyWindow(handle).log_err();
 560                }
 561            })
 562            .detach();
 563    }
 564}
 565
 566impl PlatformWindow for WindowsWindow {
 567    fn bounds(&self) -> Bounds<Pixels> {
 568        self.state.bounds()
 569    }
 570
 571    fn is_maximized(&self) -> bool {
 572        self.state.is_maximized()
 573    }
 574
 575    fn window_bounds(&self) -> WindowBounds {
 576        self.state.window_bounds()
 577    }
 578
 579    /// get the logical size of the app's drawable area.
 580    ///
 581    /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
 582    /// whether the mouse collides with other elements of GPUI).
 583    fn content_size(&self) -> Size<Pixels> {
 584        self.state.content_size()
 585    }
 586
 587    fn resize(&mut self, size: Size<Pixels>) {
 588        let hwnd = self.0.hwnd;
 589        let bounds = gpui::bounds(self.bounds().origin, size).to_device_pixels(self.scale_factor());
 590        let rect = calculate_window_rect(bounds, &self.state.border_offset);
 591
 592        self.0
 593            .executor
 594            .spawn(async move {
 595                unsafe {
 596                    SetWindowPos(
 597                        hwnd,
 598                        None,
 599                        bounds.origin.x.0,
 600                        bounds.origin.y.0,
 601                        rect.right - rect.left,
 602                        rect.bottom - rect.top,
 603                        SWP_NOMOVE,
 604                    )
 605                    .context("unable to set window content size")
 606                    .log_err();
 607                }
 608            })
 609            .detach();
 610    }
 611
 612    fn scale_factor(&self) -> f32 {
 613        self.state.scale_factor.get()
 614    }
 615
 616    fn appearance(&self) -> WindowAppearance {
 617        self.state.appearance.get()
 618    }
 619
 620    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 621        Some(Rc::new(self.state.display.get()))
 622    }
 623
 624    fn mouse_position(&self) -> Point<Pixels> {
 625        let scale_factor = self.scale_factor();
 626        let point = unsafe {
 627            let mut point: POINT = std::mem::zeroed();
 628            GetCursorPos(&mut point)
 629                .context("unable to get cursor position")
 630                .log_err();
 631            ScreenToClient(self.0.hwnd, &mut point).ok().log_err();
 632            point
 633        };
 634        logical_point(point.x as f32, point.y as f32, scale_factor)
 635    }
 636
 637    fn modifiers(&self) -> Modifiers {
 638        current_modifiers()
 639    }
 640
 641    fn capslock(&self) -> Capslock {
 642        current_capslock()
 643    }
 644
 645    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 646        self.state.input_handler.set(Some(input_handler));
 647    }
 648
 649    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 650        self.state.input_handler.take()
 651    }
 652
 653    fn prompt(
 654        &self,
 655        level: PromptLevel,
 656        msg: &str,
 657        detail: Option<&str>,
 658        answers: &[PromptButton],
 659    ) -> Option<Receiver<usize>> {
 660        let (done_tx, done_rx) = oneshot::channel();
 661        let msg = msg.to_string();
 662        let detail_string = detail.map(|detail| detail.to_string());
 663        let handle = self.0.hwnd;
 664        let answers = answers.to_vec();
 665        self.0
 666            .executor
 667            .spawn(async move {
 668                unsafe {
 669                    let mut config = TASKDIALOGCONFIG::default();
 670                    config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;
 671                    config.hwndParent = handle;
 672                    let title;
 673                    let main_icon;
 674                    match level {
 675                        PromptLevel::Info => {
 676                            title = windows::core::w!("Info");
 677                            main_icon = TD_INFORMATION_ICON;
 678                        }
 679                        PromptLevel::Warning => {
 680                            title = windows::core::w!("Warning");
 681                            main_icon = TD_WARNING_ICON;
 682                        }
 683                        PromptLevel::Critical => {
 684                            title = windows::core::w!("Critical");
 685                            main_icon = TD_ERROR_ICON;
 686                        }
 687                    };
 688                    config.pszWindowTitle = title;
 689                    config.Anonymous1.pszMainIcon = main_icon;
 690                    let instruction = HSTRING::from(msg);
 691                    config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());
 692                    let hints_encoded;
 693                    if let Some(ref hints) = detail_string {
 694                        hints_encoded = HSTRING::from(hints);
 695                        config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());
 696                    };
 697                    let mut button_id_map = Vec::with_capacity(answers.len());
 698                    let mut buttons = Vec::new();
 699                    let mut btn_encoded = Vec::new();
 700                    for (index, btn) in answers.iter().enumerate() {
 701                        let encoded = HSTRING::from(btn.label().as_ref());
 702                        let button_id = match btn {
 703                            PromptButton::Ok(_) => IDOK.0,
 704                            PromptButton::Cancel(_) => IDCANCEL.0,
 705                            // the first few low integer values are reserved for known buttons
 706                            // so for simplicity we just go backwards from -1
 707                            PromptButton::Other(_) => -(index as i32) - 1,
 708                        };
 709                        button_id_map.push(button_id);
 710                        buttons.push(TASKDIALOG_BUTTON {
 711                            nButtonID: button_id,
 712                            pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),
 713                        });
 714                        btn_encoded.push(encoded);
 715                    }
 716                    config.cButtons = buttons.len() as _;
 717                    config.pButtons = buttons.as_ptr();
 718
 719                    config.pfCallback = None;
 720                    let mut res = std::mem::zeroed();
 721                    let _ = TaskDialogIndirect(&config, Some(&mut res), None, None)
 722                        .context("unable to create task dialog")
 723                        .log_err();
 724
 725                    if let Some(clicked) =
 726                        button_id_map.iter().position(|&button_id| button_id == res)
 727                    {
 728                        let _ = done_tx.send(clicked);
 729                    }
 730                }
 731            })
 732            .detach();
 733
 734        Some(done_rx)
 735    }
 736
 737    fn activate(&self) {
 738        let hwnd = self.0.hwnd;
 739        let this = self.0.clone();
 740        self.0
 741            .executor
 742            .spawn(async move {
 743                this.set_window_placement().log_err();
 744
 745                unsafe {
 746                    // If the window is minimized, restore it.
 747                    if IsIconic(hwnd).as_bool() {
 748                        ShowWindowAsync(hwnd, SW_RESTORE).ok().log_err();
 749                    }
 750
 751                    SetActiveWindow(hwnd).ok();
 752                    SetFocus(Some(hwnd)).ok();
 753                }
 754
 755                // premium ragebait by windows, this is needed because the window
 756                // must have received an input event to be able to set itself to foreground
 757                // so let's just simulate user input as that seems to be the most reliable way
 758                // some more info: https://gist.github.com/Aetopia/1581b40f00cc0cadc93a0e8ccb65dc8c
 759                // bonus: this bug also doesn't manifest if you have vs attached to the process
 760                let inputs = [
 761                    INPUT {
 762                        r#type: INPUT_KEYBOARD,
 763                        Anonymous: INPUT_0 {
 764                            ki: KEYBDINPUT {
 765                                wVk: VK_MENU,
 766                                dwFlags: KEYBD_EVENT_FLAGS(0),
 767                                ..Default::default()
 768                            },
 769                        },
 770                    },
 771                    INPUT {
 772                        r#type: INPUT_KEYBOARD,
 773                        Anonymous: INPUT_0 {
 774                            ki: KEYBDINPUT {
 775                                wVk: VK_MENU,
 776                                dwFlags: KEYEVENTF_KEYUP,
 777                                ..Default::default()
 778                            },
 779                        },
 780                    },
 781                ];
 782                unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };
 783
 784                // todo(windows)
 785                // crate `windows 0.56` reports true as Err
 786                unsafe { SetForegroundWindow(hwnd).as_bool() };
 787            })
 788            .detach();
 789    }
 790
 791    fn is_active(&self) -> bool {
 792        self.0.hwnd == unsafe { GetActiveWindow() }
 793    }
 794
 795    fn is_hovered(&self) -> bool {
 796        self.state.hovered.get()
 797    }
 798
 799    fn background_appearance(&self) -> WindowBackgroundAppearance {
 800        self.state.background_appearance.get()
 801    }
 802
 803    fn is_subpixel_rendering_supported(&self) -> bool {
 804        true
 805    }
 806
 807    fn set_title(&mut self, title: &str) {
 808        unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
 809            .inspect_err(|e| log::error!("Set title failed: {e}"))
 810            .ok();
 811    }
 812
 813    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
 814        self.state.background_appearance.set(background_appearance);
 815        let hwnd = self.0.hwnd;
 816
 817        // using Dwm APIs for Mica and MicaAlt backdrops.
 818        // others follow the set_window_composition_attribute approach
 819        match background_appearance {
 820            WindowBackgroundAppearance::Opaque => {
 821                set_window_composition_attribute(hwnd, None, 0);
 822            }
 823            WindowBackgroundAppearance::Transparent => {
 824                set_window_composition_attribute(hwnd, None, 2);
 825            }
 826            WindowBackgroundAppearance::Blurred => {
 827                set_window_composition_attribute(hwnd, Some((0, 0, 0, 0)), 4);
 828            }
 829            WindowBackgroundAppearance::MicaBackdrop => {
 830                // DWMSBT_MAINWINDOW => MicaBase
 831                dwm_set_window_composition_attribute(hwnd, 2);
 832            }
 833            WindowBackgroundAppearance::MicaAltBackdrop => {
 834                // DWMSBT_TABBEDWINDOW => MicaAlt
 835                dwm_set_window_composition_attribute(hwnd, 4);
 836            }
 837        }
 838    }
 839
 840    fn minimize(&self) {
 841        unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
 842    }
 843
 844    fn zoom(&self) {
 845        unsafe {
 846            if IsWindowVisible(self.0.hwnd).as_bool() {
 847                ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
 848            } else if let Some(mut status) = self.state.initial_placement.take() {
 849                status.state = WindowOpenState::Maximized;
 850                self.state.initial_placement.set(Some(status));
 851            }
 852        }
 853    }
 854
 855    fn toggle_fullscreen(&self) {
 856        if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
 857            self.0.toggle_fullscreen();
 858        } else if let Some(mut status) = self.state.initial_placement.take() {
 859            status.state = WindowOpenState::Fullscreen;
 860            self.state.initial_placement.set(Some(status));
 861        }
 862    }
 863
 864    fn is_fullscreen(&self) -> bool {
 865        self.state.is_fullscreen()
 866    }
 867
 868    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
 869        self.state.callbacks.request_frame.set(Some(callback));
 870    }
 871
 872    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
 873        self.state.callbacks.input.set(Some(callback));
 874    }
 875
 876    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 877        self.0
 878            .state
 879            .callbacks
 880            .active_status_change
 881            .set(Some(callback));
 882    }
 883
 884    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 885        self.0
 886            .state
 887            .callbacks
 888            .hovered_status_change
 889            .set(Some(callback));
 890    }
 891
 892    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 893        self.state.callbacks.resize.set(Some(callback));
 894    }
 895
 896    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 897        self.state.callbacks.moved.set(Some(callback));
 898    }
 899
 900    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 901        self.state.callbacks.should_close.set(Some(callback));
 902    }
 903
 904    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 905        self.state.callbacks.close.set(Some(callback));
 906    }
 907
 908    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
 909        self.0
 910            .state
 911            .callbacks
 912            .hit_test_window_control
 913            .set(Some(callback));
 914    }
 915
 916    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 917        self.0
 918            .state
 919            .callbacks
 920            .appearance_changed
 921            .set(Some(callback));
 922    }
 923
 924    fn draw(&self, scene: &Scene) {
 925        self.state
 926            .renderer
 927            .borrow_mut()
 928            .draw(scene, self.state.background_appearance.get())
 929            .log_err();
 930    }
 931
 932    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 933        self.state.renderer.borrow().sprite_atlas()
 934    }
 935
 936    fn get_raw_handle(&self) -> HWND {
 937        self.0.hwnd
 938    }
 939
 940    fn gpu_specs(&self) -> Option<GpuSpecs> {
 941        self.state.renderer.borrow().gpu_specs().log_err()
 942    }
 943
 944    fn update_ime_position(&self, bounds: Bounds<Pixels>) {
 945        let scale_factor = self.state.scale_factor.get();
 946        let caret_position = POINT {
 947            x: (bounds.origin.x.as_f32() * scale_factor) as i32,
 948            y: (bounds.origin.y.as_f32() * scale_factor) as i32
 949                + ((bounds.size.height.as_f32() * scale_factor) as i32 / 2),
 950        };
 951
 952        self.0.update_ime_position(self.0.hwnd, caret_position);
 953    }
 954
 955    fn play_system_bell(&self) {
 956        // MB_OK: The sound specified as the Windows Default Beep sound.
 957        let _ = unsafe { MessageBeep(MB_OK) };
 958    }
 959}
 960
 961#[implement(IDropTarget)]
 962struct WindowsDragDropHandler(pub Rc<WindowsWindowInner>);
 963
 964impl WindowsDragDropHandler {
 965    fn handle_drag_drop(&self, input: PlatformInput) {
 966        if let Some(mut func) = self.0.state.callbacks.input.take() {
 967            func(input);
 968            self.0.state.callbacks.input.set(Some(func));
 969        }
 970    }
 971}
 972
 973#[allow(non_snake_case)]
 974impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
 975    fn DragEnter(
 976        &self,
 977        pdataobj: windows::core::Ref<IDataObject>,
 978        _grfkeystate: MODIFIERKEYS_FLAGS,
 979        pt: &POINTL,
 980        pdweffect: *mut DROPEFFECT,
 981    ) -> windows::core::Result<()> {
 982        unsafe {
 983            let idata_obj = pdataobj.ok()?;
 984            let config = FORMATETC {
 985                cfFormat: CF_HDROP.0,
 986                ptd: std::ptr::null_mut() as _,
 987                dwAspect: DVASPECT_CONTENT.0,
 988                lindex: -1,
 989                tymed: TYMED_HGLOBAL.0 as _,
 990            };
 991            let cursor_position = POINT { x: pt.x, y: pt.y };
 992            if idata_obj.QueryGetData(&config as _) == S_OK {
 993                *pdweffect = DROPEFFECT_COPY;
 994                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 995                    return Ok(());
 996                };
 997                if idata.u.hGlobal.is_invalid() {
 998                    return Ok(());
 999                }
1000                let hdrop = HDROP(idata.u.hGlobal.0);
1001                let mut paths = SmallVec::<[PathBuf; 2]>::new();
1002                with_file_names(hdrop, |file_name| {
1003                    if let Some(path) = PathBuf::from_str(&file_name).log_err() {
1004                        paths.push(path);
1005                    }
1006                });
1007                ReleaseStgMedium(&mut idata);
1008                let mut cursor_position = cursor_position;
1009                ScreenToClient(self.0.hwnd, &mut cursor_position)
1010                    .ok()
1011                    .log_err();
1012                let scale_factor = self.0.state.scale_factor.get();
1013                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1014                    position: logical_point(
1015                        cursor_position.x as f32,
1016                        cursor_position.y as f32,
1017                        scale_factor,
1018                    ),
1019                    paths: ExternalPaths(paths),
1020                });
1021                self.handle_drag_drop(input);
1022            } else {
1023                *pdweffect = DROPEFFECT_NONE;
1024            }
1025            self.0
1026                .drop_target_helper
1027                .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)
1028                .log_err();
1029        }
1030        Ok(())
1031    }
1032
1033    fn DragOver(
1034        &self,
1035        _grfkeystate: MODIFIERKEYS_FLAGS,
1036        pt: &POINTL,
1037        pdweffect: *mut DROPEFFECT,
1038    ) -> windows::core::Result<()> {
1039        let mut cursor_position = POINT { x: pt.x, y: pt.y };
1040        unsafe {
1041            *pdweffect = DROPEFFECT_COPY;
1042            self.0
1043                .drop_target_helper
1044                .DragOver(&cursor_position, *pdweffect)
1045                .log_err();
1046            ScreenToClient(self.0.hwnd, &mut cursor_position)
1047                .ok()
1048                .log_err();
1049        }
1050        let scale_factor = self.0.state.scale_factor.get();
1051        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
1052            position: logical_point(
1053                cursor_position.x as f32,
1054                cursor_position.y as f32,
1055                scale_factor,
1056            ),
1057        });
1058        self.handle_drag_drop(input);
1059
1060        Ok(())
1061    }
1062
1063    fn DragLeave(&self) -> windows::core::Result<()> {
1064        unsafe {
1065            self.0.drop_target_helper.DragLeave().log_err();
1066        }
1067        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
1068        self.handle_drag_drop(input);
1069
1070        Ok(())
1071    }
1072
1073    fn Drop(
1074        &self,
1075        pdataobj: windows::core::Ref<IDataObject>,
1076        _grfkeystate: MODIFIERKEYS_FLAGS,
1077        pt: &POINTL,
1078        pdweffect: *mut DROPEFFECT,
1079    ) -> windows::core::Result<()> {
1080        let idata_obj = pdataobj.ok()?;
1081        let mut cursor_position = POINT { x: pt.x, y: pt.y };
1082        unsafe {
1083            *pdweffect = DROPEFFECT_COPY;
1084            self.0
1085                .drop_target_helper
1086                .Drop(idata_obj, &cursor_position, *pdweffect)
1087                .log_err();
1088            ScreenToClient(self.0.hwnd, &mut cursor_position)
1089                .ok()
1090                .log_err();
1091        }
1092        let scale_factor = self.0.state.scale_factor.get();
1093        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1094            position: logical_point(
1095                cursor_position.x as f32,
1096                cursor_position.y as f32,
1097                scale_factor,
1098            ),
1099        });
1100        self.handle_drag_drop(input);
1101
1102        Ok(())
1103    }
1104}
1105
1106#[derive(Debug, Clone)]
1107pub(crate) struct ClickState {
1108    button: Cell<MouseButton>,
1109    last_click: Cell<Instant>,
1110    last_position: Cell<Point<DevicePixels>>,
1111    double_click_spatial_tolerance_width: Cell<i32>,
1112    double_click_spatial_tolerance_height: Cell<i32>,
1113    double_click_interval: Cell<Duration>,
1114    pub(crate) current_count: Cell<usize>,
1115}
1116
1117impl ClickState {
1118    pub fn new() -> Self {
1119        let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
1120        let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
1121        let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
1122
1123        ClickState {
1124            button: Cell::new(MouseButton::Left),
1125            last_click: Cell::new(Instant::now()),
1126            last_position: Cell::new(Point::default()),
1127            double_click_spatial_tolerance_width: Cell::new(double_click_spatial_tolerance_width),
1128            double_click_spatial_tolerance_height: Cell::new(double_click_spatial_tolerance_height),
1129            double_click_interval: Cell::new(double_click_interval),
1130            current_count: Cell::new(0),
1131        }
1132    }
1133
1134    /// update self and return the needed click count
1135    pub fn update(&self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
1136        if self.button.get() == button && self.is_double_click(new_position) {
1137            self.current_count.update(|it| it + 1);
1138        } else {
1139            self.current_count.set(1);
1140        }
1141        self.last_click.set(Instant::now());
1142        self.last_position.set(new_position);
1143        self.button.set(button);
1144
1145        self.current_count.get()
1146    }
1147
1148    pub fn system_update(&self, wparam: usize) {
1149        match wparam {
1150            // SPI_SETDOUBLECLKWIDTH
1151            29 => self
1152                .double_click_spatial_tolerance_width
1153                .set(unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }),
1154            // SPI_SETDOUBLECLKHEIGHT
1155            30 => self
1156                .double_click_spatial_tolerance_height
1157                .set(unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }),
1158            // SPI_SETDOUBLECLICKTIME
1159            32 => self
1160                .double_click_interval
1161                .set(Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)),
1162            _ => {}
1163        }
1164    }
1165
1166    #[inline]
1167    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
1168        let diff = self.last_position.get() - new_position;
1169
1170        self.last_click.get().elapsed() < self.double_click_interval.get()
1171            && diff.x.0.abs() <= self.double_click_spatial_tolerance_width.get()
1172            && diff.y.0.abs() <= self.double_click_spatial_tolerance_height.get()
1173    }
1174}
1175
1176#[derive(Copy, Clone)]
1177struct StyleAndBounds {
1178    style: WINDOW_STYLE,
1179    x: i32,
1180    y: i32,
1181    cx: i32,
1182    cy: i32,
1183}
1184
1185#[repr(C)]
1186struct WINDOWCOMPOSITIONATTRIBDATA {
1187    attrib: u32,
1188    pv_data: *mut std::ffi::c_void,
1189    cb_data: usize,
1190}
1191
1192#[repr(C)]
1193struct AccentPolicy {
1194    accent_state: u32,
1195    accent_flags: u32,
1196    gradient_color: u32,
1197    animation_id: u32,
1198}
1199
1200type Color = (u8, u8, u8, u8);
1201
1202#[derive(Debug, Default, Clone)]
1203pub(crate) struct WindowBorderOffset {
1204    pub(crate) width_offset: Cell<i32>,
1205    pub(crate) height_offset: Cell<i32>,
1206}
1207
1208impl WindowBorderOffset {
1209    pub(crate) fn update(&self, hwnd: HWND) -> anyhow::Result<()> {
1210        let window_rect = unsafe {
1211            let mut rect = std::mem::zeroed();
1212            GetWindowRect(hwnd, &mut rect)?;
1213            rect
1214        };
1215        let client_rect = unsafe {
1216            let mut rect = std::mem::zeroed();
1217            GetClientRect(hwnd, &mut rect)?;
1218            rect
1219        };
1220        self.width_offset
1221            .set((window_rect.right - window_rect.left) - (client_rect.right - client_rect.left));
1222        self.height_offset
1223            .set((window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top));
1224        Ok(())
1225    }
1226}
1227
1228#[derive(Clone)]
1229struct WindowOpenStatus {
1230    placement: WINDOWPLACEMENT,
1231    state: WindowOpenState,
1232}
1233
1234#[derive(Clone, Copy)]
1235enum WindowOpenState {
1236    Maximized,
1237    Fullscreen,
1238    Windowed,
1239}
1240
1241const WINDOW_CLASS_NAME: PCWSTR = w!("Zed::Window");
1242
1243fn register_window_class(icon_handle: HICON) {
1244    static ONCE: Once = Once::new();
1245    ONCE.call_once(|| {
1246        let wc = WNDCLASSW {
1247            lpfnWndProc: Some(window_procedure),
1248            hIcon: icon_handle,
1249            lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
1250            style: CS_HREDRAW | CS_VREDRAW,
1251            hInstance: get_module_handle().into(),
1252            hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1253            ..Default::default()
1254        };
1255        unsafe { RegisterClassW(&wc) };
1256    });
1257}
1258
1259unsafe extern "system" fn window_procedure(
1260    hwnd: HWND,
1261    msg: u32,
1262    wparam: WPARAM,
1263    lparam: LPARAM,
1264) -> LRESULT {
1265    if msg == WM_NCCREATE {
1266        let window_params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1267        let window_creation_context = window_params.lpCreateParams as *mut WindowCreateContext;
1268        let window_creation_context = unsafe { &mut *window_creation_context };
1269        return match WindowsWindowInner::new(window_creation_context, hwnd, window_params) {
1270            Ok(window_state) => {
1271                let weak = Box::new(Rc::downgrade(&window_state));
1272                unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1273                window_creation_context.inner = Some(Ok(window_state));
1274                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1275            }
1276            Err(error) => {
1277                window_creation_context.inner = Some(Err(error));
1278                LRESULT(0)
1279            }
1280        };
1281    }
1282
1283    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1284    if ptr.is_null() {
1285        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1286    }
1287    let inner = unsafe { &*ptr };
1288    let result = if let Some(inner) = inner.upgrade() {
1289        inner.handle_msg(hwnd, msg, wparam, lparam)
1290    } else {
1291        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1292    };
1293
1294    if msg == WM_NCDESTROY {
1295        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1296        unsafe { drop(Box::from_raw(ptr)) };
1297    }
1298
1299    result
1300}
1301
1302pub(crate) fn window_from_hwnd(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
1303    if hwnd.is_invalid() {
1304        return None;
1305    }
1306
1307    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1308    if !ptr.is_null() {
1309        let inner = unsafe { &*ptr };
1310        inner.upgrade()
1311    } else {
1312        None
1313    }
1314}
1315
1316fn get_module_handle() -> HMODULE {
1317    unsafe {
1318        let mut h_module = std::mem::zeroed();
1319        GetModuleHandleExW(
1320            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1321            windows::core::w!("ZedModule"),
1322            &mut h_module,
1323        )
1324        .expect("Unable to get module handle"); // this should never fail
1325
1326        h_module
1327    }
1328}
1329
1330fn register_drag_drop(window: &Rc<WindowsWindowInner>) -> Result<()> {
1331    let window_handle = window.hwnd;
1332    let handler = WindowsDragDropHandler(window.clone());
1333    // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1334    // we call `RevokeDragDrop`.
1335    // So, it's safe to drop it here.
1336    let drag_drop_handler: IDropTarget = handler.into();
1337    unsafe {
1338        RegisterDragDrop(window_handle, &drag_drop_handler)
1339            .context("unable to register drag-drop event")?;
1340    }
1341    Ok(())
1342}
1343
1344fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: &WindowBorderOffset) -> RECT {
1345    // NOTE:
1346    // The reason we're not using `AdjustWindowRectEx()` here is
1347    // that the size reported by this function is incorrect.
1348    // You can test it, and there are similar discussions online.
1349    // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1350    //
1351    // So we manually calculate these values here.
1352    let mut rect = RECT {
1353        left: bounds.left().0,
1354        top: bounds.top().0,
1355        right: bounds.right().0,
1356        bottom: bounds.bottom().0,
1357    };
1358    let left_offset = border_offset.width_offset.get() / 2;
1359    let top_offset = border_offset.height_offset.get() / 2;
1360    let right_offset = border_offset.width_offset.get() - left_offset;
1361    let bottom_offset = border_offset.height_offset.get() - top_offset;
1362    rect.left -= left_offset;
1363    rect.top -= top_offset;
1364    rect.right += right_offset;
1365    rect.bottom += bottom_offset;
1366    rect
1367}
1368
1369fn calculate_client_rect(
1370    rect: RECT,
1371    border_offset: &WindowBorderOffset,
1372    scale_factor: f32,
1373) -> Bounds<Pixels> {
1374    let left_offset = border_offset.width_offset.get() / 2;
1375    let top_offset = border_offset.height_offset.get() / 2;
1376    let right_offset = border_offset.width_offset.get() - left_offset;
1377    let bottom_offset = border_offset.height_offset.get() - top_offset;
1378    let left = rect.left + left_offset;
1379    let top = rect.top + top_offset;
1380    let right = rect.right - right_offset;
1381    let bottom = rect.bottom - bottom_offset;
1382    let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1383    Bounds {
1384        origin: logical_point(left as f32, top as f32, scale_factor),
1385        size: physical_size.to_pixels(scale_factor),
1386    }
1387}
1388
1389fn retrieve_window_placement(
1390    hwnd: HWND,
1391    display: WindowsDisplay,
1392    initial_bounds: Bounds<Pixels>,
1393    scale_factor: f32,
1394    border_offset: &WindowBorderOffset,
1395) -> Result<WINDOWPLACEMENT> {
1396    let mut placement = WINDOWPLACEMENT {
1397        length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1398        ..Default::default()
1399    };
1400    unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1401    // the bounds may be not inside the display
1402    let bounds = if display.check_given_bounds(initial_bounds) {
1403        initial_bounds
1404    } else {
1405        display.default_bounds()
1406    };
1407    let bounds = bounds.to_device_pixels(scale_factor);
1408    placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1409    Ok(placement)
1410}
1411
1412fn dwm_set_window_composition_attribute(hwnd: HWND, backdrop_type: u32) {
1413    let mut version = unsafe { std::mem::zeroed() };
1414    let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1415
1416    // DWMWA_SYSTEMBACKDROP_TYPE is available only on version 22621 or later
1417    // using SetWindowCompositionAttributeType as a fallback
1418    if !status.is_ok() || version.dwBuildNumber < 22621 {
1419        return;
1420    }
1421
1422    unsafe {
1423        let result = DwmSetWindowAttribute(
1424            hwnd,
1425            DWMWA_SYSTEMBACKDROP_TYPE,
1426            &backdrop_type as *const _ as *const _,
1427            std::mem::size_of_val(&backdrop_type) as u32,
1428        );
1429
1430        if !result.is_ok() {
1431            return;
1432        }
1433    }
1434}
1435
1436fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1437    let mut version = unsafe { std::mem::zeroed() };
1438    let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1439
1440    if !status.is_ok() || version.dwBuildNumber < 17763 {
1441        return;
1442    }
1443
1444    unsafe {
1445        type SetWindowCompositionAttributeType =
1446            unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1447        let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1448        if let Some(user32) = GetModuleHandleA(module_name)
1449            .context("Unable to get user32.dll handle")
1450            .log_err()
1451        {
1452            let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1453            let set_window_composition_attribute: SetWindowCompositionAttributeType =
1454                std::mem::transmute(GetProcAddress(user32, func_name));
1455            let mut color = color.unwrap_or_default();
1456            let is_acrylic = state == 4;
1457            if is_acrylic && color.3 == 0 {
1458                color.3 = 1;
1459            }
1460            let accent = AccentPolicy {
1461                accent_state: state,
1462                accent_flags: if is_acrylic { 0 } else { 2 },
1463                gradient_color: (color.0 as u32)
1464                    | ((color.1 as u32) << 8)
1465                    | ((color.2 as u32) << 16)
1466                    | ((color.3 as u32) << 24),
1467                animation_id: 0,
1468            };
1469            let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1470                attrib: 0x13,
1471                pv_data: &accent as *const _ as *mut _,
1472                cb_data: std::mem::size_of::<AccentPolicy>(),
1473            };
1474            let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1475        }
1476    }
1477}
1478
1479// When the platform title bar is hidden, Windows may think that our application is meant to appear 'fullscreen'
1480// and will stop the taskbar from appearing on top of our window. Prevent this.
1481// https://devblogs.microsoft.com/oldnewthing/20250522-00/?p=111211
1482fn set_non_rude_hwnd(hwnd: HWND, non_rude: bool) {
1483    if non_rude {
1484        unsafe { SetPropW(hwnd, w!("NonRudeHWND"), Some(HANDLE(1 as _))) }.log_err();
1485    } else {
1486        unsafe { RemovePropW(hwnd, w!("NonRudeHWND")) }.log_err();
1487    }
1488}
1489
1490#[cfg(test)]
1491mod tests {
1492    use super::ClickState;
1493    use gpui::{DevicePixels, MouseButton, point};
1494    use std::time::Duration;
1495
1496    #[test]
1497    fn test_double_click_interval() {
1498        let state = ClickState::new();
1499        assert_eq!(
1500            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1501            1
1502        );
1503        assert_eq!(
1504            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1505            1
1506        );
1507        assert_eq!(
1508            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1509            1
1510        );
1511        assert_eq!(
1512            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1513            2
1514        );
1515        state
1516            .last_click
1517            .update(|it| it - Duration::from_millis(700));
1518        assert_eq!(
1519            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1520            1
1521        );
1522    }
1523
1524    #[test]
1525    fn test_double_click_spatial_tolerance() {
1526        let state = ClickState::new();
1527        assert_eq!(
1528            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1529            1
1530        );
1531        assert_eq!(
1532            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1533            2
1534        );
1535        assert_eq!(
1536            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1537            1
1538        );
1539        assert_eq!(
1540            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1541            1
1542        );
1543    }
1544}