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
 543// todo(windows)
 544impl rwh::HasDisplayHandle for WindowsWindow {
 545    fn display_handle(&self) -> std::result::Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 546        unimplemented!()
 547    }
 548}
 549
 550impl Drop for WindowsWindow {
 551    fn drop(&mut self) {
 552        // clone this `Rc` to prevent early release of the pointer
 553        let this = self.0.clone();
 554        self.0
 555            .executor
 556            .spawn(async move {
 557                let handle = this.hwnd;
 558                unsafe {
 559                    RevokeDragDrop(handle).log_err();
 560                    DestroyWindow(handle).log_err();
 561                }
 562            })
 563            .detach();
 564    }
 565}
 566
 567impl PlatformWindow for WindowsWindow {
 568    fn bounds(&self) -> Bounds<Pixels> {
 569        self.state.bounds()
 570    }
 571
 572    fn is_maximized(&self) -> bool {
 573        self.state.is_maximized()
 574    }
 575
 576    fn window_bounds(&self) -> WindowBounds {
 577        self.state.window_bounds()
 578    }
 579
 580    /// get the logical size of the app's drawable area.
 581    ///
 582    /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
 583    /// whether the mouse collides with other elements of GPUI).
 584    fn content_size(&self) -> Size<Pixels> {
 585        self.state.content_size()
 586    }
 587
 588    fn resize(&mut self, size: Size<Pixels>) {
 589        let hwnd = self.0.hwnd;
 590        let bounds = gpui::bounds(self.bounds().origin, size).to_device_pixels(self.scale_factor());
 591        let rect = calculate_window_rect(bounds, &self.state.border_offset);
 592
 593        self.0
 594            .executor
 595            .spawn(async move {
 596                unsafe {
 597                    SetWindowPos(
 598                        hwnd,
 599                        None,
 600                        bounds.origin.x.0,
 601                        bounds.origin.y.0,
 602                        rect.right - rect.left,
 603                        rect.bottom - rect.top,
 604                        SWP_NOMOVE,
 605                    )
 606                    .context("unable to set window content size")
 607                    .log_err();
 608                }
 609            })
 610            .detach();
 611    }
 612
 613    fn scale_factor(&self) -> f32 {
 614        self.state.scale_factor.get()
 615    }
 616
 617    fn appearance(&self) -> WindowAppearance {
 618        self.state.appearance.get()
 619    }
 620
 621    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 622        Some(Rc::new(self.state.display.get()))
 623    }
 624
 625    fn mouse_position(&self) -> Point<Pixels> {
 626        let scale_factor = self.scale_factor();
 627        let point = unsafe {
 628            let mut point: POINT = std::mem::zeroed();
 629            GetCursorPos(&mut point)
 630                .context("unable to get cursor position")
 631                .log_err();
 632            ScreenToClient(self.0.hwnd, &mut point).ok().log_err();
 633            point
 634        };
 635        logical_point(point.x as f32, point.y as f32, scale_factor)
 636    }
 637
 638    fn modifiers(&self) -> Modifiers {
 639        current_modifiers()
 640    }
 641
 642    fn capslock(&self) -> Capslock {
 643        current_capslock()
 644    }
 645
 646    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 647        self.state.input_handler.set(Some(input_handler));
 648    }
 649
 650    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 651        self.state.input_handler.take()
 652    }
 653
 654    fn prompt(
 655        &self,
 656        level: PromptLevel,
 657        msg: &str,
 658        detail: Option<&str>,
 659        answers: &[PromptButton],
 660    ) -> Option<Receiver<usize>> {
 661        let (done_tx, done_rx) = oneshot::channel();
 662        let msg = msg.to_string();
 663        let detail_string = detail.map(|detail| detail.to_string());
 664        let handle = self.0.hwnd;
 665        let answers = answers.to_vec();
 666        self.0
 667            .executor
 668            .spawn(async move {
 669                unsafe {
 670                    let mut config = TASKDIALOGCONFIG::default();
 671                    config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;
 672                    config.hwndParent = handle;
 673                    let title;
 674                    let main_icon;
 675                    match level {
 676                        PromptLevel::Info => {
 677                            title = windows::core::w!("Info");
 678                            main_icon = TD_INFORMATION_ICON;
 679                        }
 680                        PromptLevel::Warning => {
 681                            title = windows::core::w!("Warning");
 682                            main_icon = TD_WARNING_ICON;
 683                        }
 684                        PromptLevel::Critical => {
 685                            title = windows::core::w!("Critical");
 686                            main_icon = TD_ERROR_ICON;
 687                        }
 688                    };
 689                    config.pszWindowTitle = title;
 690                    config.Anonymous1.pszMainIcon = main_icon;
 691                    let instruction = HSTRING::from(msg);
 692                    config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());
 693                    let hints_encoded;
 694                    if let Some(ref hints) = detail_string {
 695                        hints_encoded = HSTRING::from(hints);
 696                        config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());
 697                    };
 698                    let mut button_id_map = Vec::with_capacity(answers.len());
 699                    let mut buttons = Vec::new();
 700                    let mut btn_encoded = Vec::new();
 701                    for (index, btn) in answers.iter().enumerate() {
 702                        let encoded = HSTRING::from(btn.label().as_ref());
 703                        let button_id = match btn {
 704                            PromptButton::Ok(_) => IDOK.0,
 705                            PromptButton::Cancel(_) => IDCANCEL.0,
 706                            // the first few low integer values are reserved for known buttons
 707                            // so for simplicity we just go backwards from -1
 708                            PromptButton::Other(_) => -(index as i32) - 1,
 709                        };
 710                        button_id_map.push(button_id);
 711                        buttons.push(TASKDIALOG_BUTTON {
 712                            nButtonID: button_id,
 713                            pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),
 714                        });
 715                        btn_encoded.push(encoded);
 716                    }
 717                    config.cButtons = buttons.len() as _;
 718                    config.pButtons = buttons.as_ptr();
 719
 720                    config.pfCallback = None;
 721                    let mut res = std::mem::zeroed();
 722                    let _ = TaskDialogIndirect(&config, Some(&mut res), None, None)
 723                        .context("unable to create task dialog")
 724                        .log_err();
 725
 726                    if let Some(clicked) =
 727                        button_id_map.iter().position(|&button_id| button_id == res)
 728                    {
 729                        let _ = done_tx.send(clicked);
 730                    }
 731                }
 732            })
 733            .detach();
 734
 735        Some(done_rx)
 736    }
 737
 738    fn activate(&self) {
 739        let hwnd = self.0.hwnd;
 740        let this = self.0.clone();
 741        self.0
 742            .executor
 743            .spawn(async move {
 744                this.set_window_placement().log_err();
 745
 746                unsafe {
 747                    // If the window is minimized, restore it.
 748                    if IsIconic(hwnd).as_bool() {
 749                        ShowWindowAsync(hwnd, SW_RESTORE).ok().log_err();
 750                    }
 751
 752                    SetActiveWindow(hwnd).ok();
 753                    SetFocus(Some(hwnd)).ok();
 754                }
 755
 756                // premium ragebait by windows, this is needed because the window
 757                // must have received an input event to be able to set itself to foreground
 758                // so let's just simulate user input as that seems to be the most reliable way
 759                // some more info: https://gist.github.com/Aetopia/1581b40f00cc0cadc93a0e8ccb65dc8c
 760                // bonus: this bug also doesn't manifest if you have vs attached to the process
 761                let inputs = [
 762                    INPUT {
 763                        r#type: INPUT_KEYBOARD,
 764                        Anonymous: INPUT_0 {
 765                            ki: KEYBDINPUT {
 766                                wVk: VK_MENU,
 767                                dwFlags: KEYBD_EVENT_FLAGS(0),
 768                                ..Default::default()
 769                            },
 770                        },
 771                    },
 772                    INPUT {
 773                        r#type: INPUT_KEYBOARD,
 774                        Anonymous: INPUT_0 {
 775                            ki: KEYBDINPUT {
 776                                wVk: VK_MENU,
 777                                dwFlags: KEYEVENTF_KEYUP,
 778                                ..Default::default()
 779                            },
 780                        },
 781                    },
 782                ];
 783                unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };
 784
 785                // todo(windows)
 786                // crate `windows 0.56` reports true as Err
 787                unsafe { SetForegroundWindow(hwnd).as_bool() };
 788            })
 789            .detach();
 790    }
 791
 792    fn is_active(&self) -> bool {
 793        self.0.hwnd == unsafe { GetActiveWindow() }
 794    }
 795
 796    fn is_hovered(&self) -> bool {
 797        self.state.hovered.get()
 798    }
 799
 800    fn background_appearance(&self) -> WindowBackgroundAppearance {
 801        self.state.background_appearance.get()
 802    }
 803
 804    fn is_subpixel_rendering_supported(&self) -> bool {
 805        true
 806    }
 807
 808    fn set_title(&mut self, title: &str) {
 809        unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
 810            .inspect_err(|e| log::error!("Set title failed: {e}"))
 811            .ok();
 812    }
 813
 814    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
 815        self.state.background_appearance.set(background_appearance);
 816        let hwnd = self.0.hwnd;
 817
 818        // using Dwm APIs for Mica and MicaAlt backdrops.
 819        // others follow the set_window_composition_attribute approach
 820        match background_appearance {
 821            WindowBackgroundAppearance::Opaque => {
 822                set_window_composition_attribute(hwnd, None, 0);
 823            }
 824            WindowBackgroundAppearance::Transparent => {
 825                set_window_composition_attribute(hwnd, None, 2);
 826            }
 827            WindowBackgroundAppearance::Blurred => {
 828                set_window_composition_attribute(hwnd, Some((0, 0, 0, 0)), 4);
 829            }
 830            WindowBackgroundAppearance::MicaBackdrop => {
 831                // DWMSBT_MAINWINDOW => MicaBase
 832                dwm_set_window_composition_attribute(hwnd, 2);
 833            }
 834            WindowBackgroundAppearance::MicaAltBackdrop => {
 835                // DWMSBT_TABBEDWINDOW => MicaAlt
 836                dwm_set_window_composition_attribute(hwnd, 4);
 837            }
 838        }
 839    }
 840
 841    fn minimize(&self) {
 842        unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
 843    }
 844
 845    fn zoom(&self) {
 846        unsafe {
 847            if IsWindowVisible(self.0.hwnd).as_bool() {
 848                ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
 849            } else if let Some(mut status) = self.state.initial_placement.take() {
 850                status.state = WindowOpenState::Maximized;
 851                self.state.initial_placement.set(Some(status));
 852            }
 853        }
 854    }
 855
 856    fn toggle_fullscreen(&self) {
 857        if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
 858            self.0.toggle_fullscreen();
 859        } else if let Some(mut status) = self.state.initial_placement.take() {
 860            status.state = WindowOpenState::Fullscreen;
 861            self.state.initial_placement.set(Some(status));
 862        }
 863    }
 864
 865    fn is_fullscreen(&self) -> bool {
 866        self.state.is_fullscreen()
 867    }
 868
 869    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
 870        self.state.callbacks.request_frame.set(Some(callback));
 871    }
 872
 873    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
 874        self.state.callbacks.input.set(Some(callback));
 875    }
 876
 877    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 878        self.0
 879            .state
 880            .callbacks
 881            .active_status_change
 882            .set(Some(callback));
 883    }
 884
 885    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 886        self.0
 887            .state
 888            .callbacks
 889            .hovered_status_change
 890            .set(Some(callback));
 891    }
 892
 893    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 894        self.state.callbacks.resize.set(Some(callback));
 895    }
 896
 897    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 898        self.state.callbacks.moved.set(Some(callback));
 899    }
 900
 901    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 902        self.state.callbacks.should_close.set(Some(callback));
 903    }
 904
 905    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 906        self.state.callbacks.close.set(Some(callback));
 907    }
 908
 909    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
 910        self.0
 911            .state
 912            .callbacks
 913            .hit_test_window_control
 914            .set(Some(callback));
 915    }
 916
 917    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 918        self.0
 919            .state
 920            .callbacks
 921            .appearance_changed
 922            .set(Some(callback));
 923    }
 924
 925    fn draw(&self, scene: &Scene) {
 926        self.state
 927            .renderer
 928            .borrow_mut()
 929            .draw(scene, self.state.background_appearance.get())
 930            .log_err();
 931    }
 932
 933    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 934        self.state.renderer.borrow().sprite_atlas()
 935    }
 936
 937    fn get_raw_handle(&self) -> HWND {
 938        self.0.hwnd
 939    }
 940
 941    fn gpu_specs(&self) -> Option<GpuSpecs> {
 942        self.state.renderer.borrow().gpu_specs().log_err()
 943    }
 944
 945    fn update_ime_position(&self, bounds: Bounds<Pixels>) {
 946        let scale_factor = self.state.scale_factor.get();
 947        let caret_position = POINT {
 948            x: (bounds.origin.x.as_f32() * scale_factor) as i32,
 949            y: (bounds.origin.y.as_f32() * scale_factor) as i32
 950                + ((bounds.size.height.as_f32() * scale_factor) as i32 / 2),
 951        };
 952
 953        self.0.update_ime_position(self.0.hwnd, caret_position);
 954    }
 955
 956    fn play_system_bell(&self) {
 957        // MB_OK: The sound specified as the Windows Default Beep sound.
 958        let _ = unsafe { MessageBeep(MB_OK) };
 959    }
 960}
 961
 962#[implement(IDropTarget)]
 963struct WindowsDragDropHandler(pub Rc<WindowsWindowInner>);
 964
 965impl WindowsDragDropHandler {
 966    fn handle_drag_drop(&self, input: PlatformInput) {
 967        if let Some(mut func) = self.0.state.callbacks.input.take() {
 968            func(input);
 969            self.0.state.callbacks.input.set(Some(func));
 970        }
 971    }
 972}
 973
 974#[allow(non_snake_case)]
 975impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
 976    fn DragEnter(
 977        &self,
 978        pdataobj: windows::core::Ref<IDataObject>,
 979        _grfkeystate: MODIFIERKEYS_FLAGS,
 980        pt: &POINTL,
 981        pdweffect: *mut DROPEFFECT,
 982    ) -> windows::core::Result<()> {
 983        unsafe {
 984            let idata_obj = pdataobj.ok()?;
 985            let config = FORMATETC {
 986                cfFormat: CF_HDROP.0,
 987                ptd: std::ptr::null_mut() as _,
 988                dwAspect: DVASPECT_CONTENT.0,
 989                lindex: -1,
 990                tymed: TYMED_HGLOBAL.0 as _,
 991            };
 992            let cursor_position = POINT { x: pt.x, y: pt.y };
 993            if idata_obj.QueryGetData(&config as _) == S_OK {
 994                *pdweffect = DROPEFFECT_COPY;
 995                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 996                    return Ok(());
 997                };
 998                if idata.u.hGlobal.is_invalid() {
 999                    return Ok(());
1000                }
1001                let hdrop = HDROP(idata.u.hGlobal.0);
1002                let mut paths = SmallVec::<[PathBuf; 2]>::new();
1003                with_file_names(hdrop, |file_name| {
1004                    if let Some(path) = PathBuf::from_str(&file_name).log_err() {
1005                        paths.push(path);
1006                    }
1007                });
1008                ReleaseStgMedium(&mut idata);
1009                let mut cursor_position = cursor_position;
1010                ScreenToClient(self.0.hwnd, &mut cursor_position)
1011                    .ok()
1012                    .log_err();
1013                let scale_factor = self.0.state.scale_factor.get();
1014                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1015                    position: logical_point(
1016                        cursor_position.x as f32,
1017                        cursor_position.y as f32,
1018                        scale_factor,
1019                    ),
1020                    paths: ExternalPaths(paths),
1021                });
1022                self.handle_drag_drop(input);
1023            } else {
1024                *pdweffect = DROPEFFECT_NONE;
1025            }
1026            self.0
1027                .drop_target_helper
1028                .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)
1029                .log_err();
1030        }
1031        Ok(())
1032    }
1033
1034    fn DragOver(
1035        &self,
1036        _grfkeystate: MODIFIERKEYS_FLAGS,
1037        pt: &POINTL,
1038        pdweffect: *mut DROPEFFECT,
1039    ) -> windows::core::Result<()> {
1040        let mut cursor_position = POINT { x: pt.x, y: pt.y };
1041        unsafe {
1042            *pdweffect = DROPEFFECT_COPY;
1043            self.0
1044                .drop_target_helper
1045                .DragOver(&cursor_position, *pdweffect)
1046                .log_err();
1047            ScreenToClient(self.0.hwnd, &mut cursor_position)
1048                .ok()
1049                .log_err();
1050        }
1051        let scale_factor = self.0.state.scale_factor.get();
1052        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
1053            position: logical_point(
1054                cursor_position.x as f32,
1055                cursor_position.y as f32,
1056                scale_factor,
1057            ),
1058        });
1059        self.handle_drag_drop(input);
1060
1061        Ok(())
1062    }
1063
1064    fn DragLeave(&self) -> windows::core::Result<()> {
1065        unsafe {
1066            self.0.drop_target_helper.DragLeave().log_err();
1067        }
1068        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
1069        self.handle_drag_drop(input);
1070
1071        Ok(())
1072    }
1073
1074    fn Drop(
1075        &self,
1076        pdataobj: windows::core::Ref<IDataObject>,
1077        _grfkeystate: MODIFIERKEYS_FLAGS,
1078        pt: &POINTL,
1079        pdweffect: *mut DROPEFFECT,
1080    ) -> windows::core::Result<()> {
1081        let idata_obj = pdataobj.ok()?;
1082        let mut cursor_position = POINT { x: pt.x, y: pt.y };
1083        unsafe {
1084            *pdweffect = DROPEFFECT_COPY;
1085            self.0
1086                .drop_target_helper
1087                .Drop(idata_obj, &cursor_position, *pdweffect)
1088                .log_err();
1089            ScreenToClient(self.0.hwnd, &mut cursor_position)
1090                .ok()
1091                .log_err();
1092        }
1093        let scale_factor = self.0.state.scale_factor.get();
1094        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1095            position: logical_point(
1096                cursor_position.x as f32,
1097                cursor_position.y as f32,
1098                scale_factor,
1099            ),
1100        });
1101        self.handle_drag_drop(input);
1102
1103        Ok(())
1104    }
1105}
1106
1107#[derive(Debug, Clone)]
1108pub(crate) struct ClickState {
1109    button: Cell<MouseButton>,
1110    last_click: Cell<Instant>,
1111    last_position: Cell<Point<DevicePixels>>,
1112    double_click_spatial_tolerance_width: Cell<i32>,
1113    double_click_spatial_tolerance_height: Cell<i32>,
1114    double_click_interval: Cell<Duration>,
1115    pub(crate) current_count: Cell<usize>,
1116}
1117
1118impl ClickState {
1119    pub fn new() -> Self {
1120        let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
1121        let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
1122        let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
1123
1124        ClickState {
1125            button: Cell::new(MouseButton::Left),
1126            last_click: Cell::new(Instant::now()),
1127            last_position: Cell::new(Point::default()),
1128            double_click_spatial_tolerance_width: Cell::new(double_click_spatial_tolerance_width),
1129            double_click_spatial_tolerance_height: Cell::new(double_click_spatial_tolerance_height),
1130            double_click_interval: Cell::new(double_click_interval),
1131            current_count: Cell::new(0),
1132        }
1133    }
1134
1135    /// update self and return the needed click count
1136    pub fn update(&self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
1137        if self.button.get() == button && self.is_double_click(new_position) {
1138            self.current_count.update(|it| it + 1);
1139        } else {
1140            self.current_count.set(1);
1141        }
1142        self.last_click.set(Instant::now());
1143        self.last_position.set(new_position);
1144        self.button.set(button);
1145
1146        self.current_count.get()
1147    }
1148
1149    pub fn system_update(&self, wparam: usize) {
1150        match wparam {
1151            // SPI_SETDOUBLECLKWIDTH
1152            29 => self
1153                .double_click_spatial_tolerance_width
1154                .set(unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }),
1155            // SPI_SETDOUBLECLKHEIGHT
1156            30 => self
1157                .double_click_spatial_tolerance_height
1158                .set(unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }),
1159            // SPI_SETDOUBLECLICKTIME
1160            32 => self
1161                .double_click_interval
1162                .set(Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)),
1163            _ => {}
1164        }
1165    }
1166
1167    #[inline]
1168    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
1169        let diff = self.last_position.get() - new_position;
1170
1171        self.last_click.get().elapsed() < self.double_click_interval.get()
1172            && diff.x.0.abs() <= self.double_click_spatial_tolerance_width.get()
1173            && diff.y.0.abs() <= self.double_click_spatial_tolerance_height.get()
1174    }
1175}
1176
1177#[derive(Copy, Clone)]
1178struct StyleAndBounds {
1179    style: WINDOW_STYLE,
1180    x: i32,
1181    y: i32,
1182    cx: i32,
1183    cy: i32,
1184}
1185
1186#[repr(C)]
1187struct WINDOWCOMPOSITIONATTRIBDATA {
1188    attrib: u32,
1189    pv_data: *mut std::ffi::c_void,
1190    cb_data: usize,
1191}
1192
1193#[repr(C)]
1194struct AccentPolicy {
1195    accent_state: u32,
1196    accent_flags: u32,
1197    gradient_color: u32,
1198    animation_id: u32,
1199}
1200
1201type Color = (u8, u8, u8, u8);
1202
1203#[derive(Debug, Default, Clone)]
1204pub(crate) struct WindowBorderOffset {
1205    pub(crate) width_offset: Cell<i32>,
1206    pub(crate) height_offset: Cell<i32>,
1207}
1208
1209impl WindowBorderOffset {
1210    pub(crate) fn update(&self, hwnd: HWND) -> anyhow::Result<()> {
1211        let window_rect = unsafe {
1212            let mut rect = std::mem::zeroed();
1213            GetWindowRect(hwnd, &mut rect)?;
1214            rect
1215        };
1216        let client_rect = unsafe {
1217            let mut rect = std::mem::zeroed();
1218            GetClientRect(hwnd, &mut rect)?;
1219            rect
1220        };
1221        self.width_offset
1222            .set((window_rect.right - window_rect.left) - (client_rect.right - client_rect.left));
1223        self.height_offset
1224            .set((window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top));
1225        Ok(())
1226    }
1227}
1228
1229#[derive(Clone)]
1230struct WindowOpenStatus {
1231    placement: WINDOWPLACEMENT,
1232    state: WindowOpenState,
1233}
1234
1235#[derive(Clone, Copy)]
1236enum WindowOpenState {
1237    Maximized,
1238    Fullscreen,
1239    Windowed,
1240}
1241
1242const WINDOW_CLASS_NAME: PCWSTR = w!("Zed::Window");
1243
1244fn register_window_class(icon_handle: HICON) {
1245    static ONCE: Once = Once::new();
1246    ONCE.call_once(|| {
1247        let wc = WNDCLASSW {
1248            lpfnWndProc: Some(window_procedure),
1249            hIcon: icon_handle,
1250            lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
1251            style: CS_HREDRAW | CS_VREDRAW,
1252            hInstance: get_module_handle().into(),
1253            hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1254            ..Default::default()
1255        };
1256        unsafe { RegisterClassW(&wc) };
1257    });
1258}
1259
1260unsafe extern "system" fn window_procedure(
1261    hwnd: HWND,
1262    msg: u32,
1263    wparam: WPARAM,
1264    lparam: LPARAM,
1265) -> LRESULT {
1266    if msg == WM_NCCREATE {
1267        let window_params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1268        let window_creation_context = window_params.lpCreateParams as *mut WindowCreateContext;
1269        let window_creation_context = unsafe { &mut *window_creation_context };
1270        return match WindowsWindowInner::new(window_creation_context, hwnd, window_params) {
1271            Ok(window_state) => {
1272                let weak = Box::new(Rc::downgrade(&window_state));
1273                unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1274                window_creation_context.inner = Some(Ok(window_state));
1275                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1276            }
1277            Err(error) => {
1278                window_creation_context.inner = Some(Err(error));
1279                LRESULT(0)
1280            }
1281        };
1282    }
1283
1284    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1285    if ptr.is_null() {
1286        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1287    }
1288    let inner = unsafe { &*ptr };
1289    let result = if let Some(inner) = inner.upgrade() {
1290        inner.handle_msg(hwnd, msg, wparam, lparam)
1291    } else {
1292        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1293    };
1294
1295    if msg == WM_NCDESTROY {
1296        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1297        unsafe { drop(Box::from_raw(ptr)) };
1298    }
1299
1300    result
1301}
1302
1303pub(crate) fn window_from_hwnd(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
1304    if hwnd.is_invalid() {
1305        return None;
1306    }
1307
1308    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1309    if !ptr.is_null() {
1310        let inner = unsafe { &*ptr };
1311        inner.upgrade()
1312    } else {
1313        None
1314    }
1315}
1316
1317fn get_module_handle() -> HMODULE {
1318    unsafe {
1319        let mut h_module = std::mem::zeroed();
1320        GetModuleHandleExW(
1321            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1322            windows::core::w!("ZedModule"),
1323            &mut h_module,
1324        )
1325        .expect("Unable to get module handle"); // this should never fail
1326
1327        h_module
1328    }
1329}
1330
1331fn register_drag_drop(window: &Rc<WindowsWindowInner>) -> Result<()> {
1332    let window_handle = window.hwnd;
1333    let handler = WindowsDragDropHandler(window.clone());
1334    // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1335    // we call `RevokeDragDrop`.
1336    // So, it's safe to drop it here.
1337    let drag_drop_handler: IDropTarget = handler.into();
1338    unsafe {
1339        RegisterDragDrop(window_handle, &drag_drop_handler)
1340            .context("unable to register drag-drop event")?;
1341    }
1342    Ok(())
1343}
1344
1345fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: &WindowBorderOffset) -> RECT {
1346    // NOTE:
1347    // The reason we're not using `AdjustWindowRectEx()` here is
1348    // that the size reported by this function is incorrect.
1349    // You can test it, and there are similar discussions online.
1350    // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1351    //
1352    // So we manually calculate these values here.
1353    let mut rect = RECT {
1354        left: bounds.left().0,
1355        top: bounds.top().0,
1356        right: bounds.right().0,
1357        bottom: bounds.bottom().0,
1358    };
1359    let left_offset = border_offset.width_offset.get() / 2;
1360    let top_offset = border_offset.height_offset.get() / 2;
1361    let right_offset = border_offset.width_offset.get() - left_offset;
1362    let bottom_offset = border_offset.height_offset.get() - top_offset;
1363    rect.left -= left_offset;
1364    rect.top -= top_offset;
1365    rect.right += right_offset;
1366    rect.bottom += bottom_offset;
1367    rect
1368}
1369
1370fn calculate_client_rect(
1371    rect: RECT,
1372    border_offset: &WindowBorderOffset,
1373    scale_factor: f32,
1374) -> Bounds<Pixels> {
1375    let left_offset = border_offset.width_offset.get() / 2;
1376    let top_offset = border_offset.height_offset.get() / 2;
1377    let right_offset = border_offset.width_offset.get() - left_offset;
1378    let bottom_offset = border_offset.height_offset.get() - top_offset;
1379    let left = rect.left + left_offset;
1380    let top = rect.top + top_offset;
1381    let right = rect.right - right_offset;
1382    let bottom = rect.bottom - bottom_offset;
1383    let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1384    Bounds {
1385        origin: logical_point(left as f32, top as f32, scale_factor),
1386        size: physical_size.to_pixels(scale_factor),
1387    }
1388}
1389
1390fn retrieve_window_placement(
1391    hwnd: HWND,
1392    display: WindowsDisplay,
1393    initial_bounds: Bounds<Pixels>,
1394    scale_factor: f32,
1395    border_offset: &WindowBorderOffset,
1396) -> Result<WINDOWPLACEMENT> {
1397    let mut placement = WINDOWPLACEMENT {
1398        length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1399        ..Default::default()
1400    };
1401    unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1402    // the bounds may be not inside the display
1403    let bounds = if display.check_given_bounds(initial_bounds) {
1404        initial_bounds
1405    } else {
1406        display.default_bounds()
1407    };
1408    let bounds = bounds.to_device_pixels(scale_factor);
1409    placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1410    Ok(placement)
1411}
1412
1413fn dwm_set_window_composition_attribute(hwnd: HWND, backdrop_type: u32) {
1414    let mut version = unsafe { std::mem::zeroed() };
1415    let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1416
1417    // DWMWA_SYSTEMBACKDROP_TYPE is available only on version 22621 or later
1418    // using SetWindowCompositionAttributeType as a fallback
1419    if !status.is_ok() || version.dwBuildNumber < 22621 {
1420        return;
1421    }
1422
1423    unsafe {
1424        let result = DwmSetWindowAttribute(
1425            hwnd,
1426            DWMWA_SYSTEMBACKDROP_TYPE,
1427            &backdrop_type as *const _ as *const _,
1428            std::mem::size_of_val(&backdrop_type) as u32,
1429        );
1430
1431        if !result.is_ok() {
1432            return;
1433        }
1434    }
1435}
1436
1437fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1438    let mut version = unsafe { std::mem::zeroed() };
1439    let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1440
1441    if !status.is_ok() || version.dwBuildNumber < 17763 {
1442        return;
1443    }
1444
1445    unsafe {
1446        type SetWindowCompositionAttributeType =
1447            unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1448        let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1449        if let Some(user32) = GetModuleHandleA(module_name)
1450            .context("Unable to get user32.dll handle")
1451            .log_err()
1452        {
1453            let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1454            let set_window_composition_attribute: SetWindowCompositionAttributeType =
1455                std::mem::transmute(GetProcAddress(user32, func_name));
1456            let mut color = color.unwrap_or_default();
1457            let is_acrylic = state == 4;
1458            if is_acrylic && color.3 == 0 {
1459                color.3 = 1;
1460            }
1461            let accent = AccentPolicy {
1462                accent_state: state,
1463                accent_flags: if is_acrylic { 0 } else { 2 },
1464                gradient_color: (color.0 as u32)
1465                    | ((color.1 as u32) << 8)
1466                    | ((color.2 as u32) << 16)
1467                    | ((color.3 as u32) << 24),
1468                animation_id: 0,
1469            };
1470            let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1471                attrib: 0x13,
1472                pv_data: &accent as *const _ as *mut _,
1473                cb_data: std::mem::size_of::<AccentPolicy>(),
1474            };
1475            let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1476        }
1477    }
1478}
1479
1480// When the platform title bar is hidden, Windows may think that our application is meant to appear 'fullscreen'
1481// and will stop the taskbar from appearing on top of our window. Prevent this.
1482// https://devblogs.microsoft.com/oldnewthing/20250522-00/?p=111211
1483fn set_non_rude_hwnd(hwnd: HWND, non_rude: bool) {
1484    if non_rude {
1485        unsafe { SetPropW(hwnd, w!("NonRudeHWND"), Some(HANDLE(1 as _))) }.log_err();
1486    } else {
1487        unsafe { RemovePropW(hwnd, w!("NonRudeHWND")) }.log_err();
1488    }
1489}
1490
1491#[cfg(test)]
1492mod tests {
1493    use super::ClickState;
1494    use gpui::{DevicePixels, MouseButton, point};
1495    use std::time::Duration;
1496
1497    #[test]
1498    fn test_double_click_interval() {
1499        let state = ClickState::new();
1500        assert_eq!(
1501            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1502            1
1503        );
1504        assert_eq!(
1505            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1506            1
1507        );
1508        assert_eq!(
1509            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1510            1
1511        );
1512        assert_eq!(
1513            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1514            2
1515        );
1516        state
1517            .last_click
1518            .update(|it| it - Duration::from_millis(700));
1519        assert_eq!(
1520            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1521            1
1522        );
1523    }
1524
1525    #[test]
1526    fn test_double_click_spatial_tolerance() {
1527        let state = ClickState::new();
1528        assert_eq!(
1529            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1530            1
1531        );
1532        assert_eq!(
1533            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1534            2
1535        );
1536        assert_eq!(
1537            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1538            1
1539        );
1540        assert_eq!(
1541            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1542            1
1543        );
1544    }
1545}