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