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