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