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: flume::Receiver<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: flume::Receiver<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        // There is no such thing on Windows.
 925    }
 926}
 927
 928#[implement(IDropTarget)]
 929struct WindowsDragDropHandler(pub Rc<WindowsWindowInner>);
 930
 931impl WindowsDragDropHandler {
 932    fn handle_drag_drop(&self, input: PlatformInput) {
 933        if let Some(mut func) = self.0.state.callbacks.input.take() {
 934            func(input);
 935            self.0.state.callbacks.input.set(Some(func));
 936        }
 937    }
 938}
 939
 940#[allow(non_snake_case)]
 941impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
 942    fn DragEnter(
 943        &self,
 944        pdataobj: windows::core::Ref<IDataObject>,
 945        _grfkeystate: MODIFIERKEYS_FLAGS,
 946        pt: &POINTL,
 947        pdweffect: *mut DROPEFFECT,
 948    ) -> windows::core::Result<()> {
 949        unsafe {
 950            let idata_obj = pdataobj.ok()?;
 951            let config = FORMATETC {
 952                cfFormat: CF_HDROP.0,
 953                ptd: std::ptr::null_mut() as _,
 954                dwAspect: DVASPECT_CONTENT.0,
 955                lindex: -1,
 956                tymed: TYMED_HGLOBAL.0 as _,
 957            };
 958            let cursor_position = POINT { x: pt.x, y: pt.y };
 959            if idata_obj.QueryGetData(&config as _) == S_OK {
 960                *pdweffect = DROPEFFECT_COPY;
 961                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 962                    return Ok(());
 963                };
 964                if idata.u.hGlobal.is_invalid() {
 965                    return Ok(());
 966                }
 967                let hdrop = HDROP(idata.u.hGlobal.0);
 968                let mut paths = SmallVec::<[PathBuf; 2]>::new();
 969                with_file_names(hdrop, |file_name| {
 970                    if let Some(path) = PathBuf::from_str(&file_name).log_err() {
 971                        paths.push(path);
 972                    }
 973                });
 974                ReleaseStgMedium(&mut idata);
 975                let mut cursor_position = cursor_position;
 976                ScreenToClient(self.0.hwnd, &mut cursor_position)
 977                    .ok()
 978                    .log_err();
 979                let scale_factor = self.0.state.scale_factor.get();
 980                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 981                    position: logical_point(
 982                        cursor_position.x as f32,
 983                        cursor_position.y as f32,
 984                        scale_factor,
 985                    ),
 986                    paths: ExternalPaths(paths),
 987                });
 988                self.handle_drag_drop(input);
 989            } else {
 990                *pdweffect = DROPEFFECT_NONE;
 991            }
 992            self.0
 993                .drop_target_helper
 994                .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)
 995                .log_err();
 996        }
 997        Ok(())
 998    }
 999
1000    fn DragOver(
1001        &self,
1002        _grfkeystate: MODIFIERKEYS_FLAGS,
1003        pt: &POINTL,
1004        pdweffect: *mut DROPEFFECT,
1005    ) -> windows::core::Result<()> {
1006        let mut cursor_position = POINT { x: pt.x, y: pt.y };
1007        unsafe {
1008            *pdweffect = DROPEFFECT_COPY;
1009            self.0
1010                .drop_target_helper
1011                .DragOver(&cursor_position, *pdweffect)
1012                .log_err();
1013            ScreenToClient(self.0.hwnd, &mut cursor_position)
1014                .ok()
1015                .log_err();
1016        }
1017        let scale_factor = self.0.state.scale_factor.get();
1018        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
1019            position: logical_point(
1020                cursor_position.x as f32,
1021                cursor_position.y as f32,
1022                scale_factor,
1023            ),
1024        });
1025        self.handle_drag_drop(input);
1026
1027        Ok(())
1028    }
1029
1030    fn DragLeave(&self) -> windows::core::Result<()> {
1031        unsafe {
1032            self.0.drop_target_helper.DragLeave().log_err();
1033        }
1034        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
1035        self.handle_drag_drop(input);
1036
1037        Ok(())
1038    }
1039
1040    fn Drop(
1041        &self,
1042        pdataobj: windows::core::Ref<IDataObject>,
1043        _grfkeystate: MODIFIERKEYS_FLAGS,
1044        pt: &POINTL,
1045        pdweffect: *mut DROPEFFECT,
1046    ) -> windows::core::Result<()> {
1047        let idata_obj = pdataobj.ok()?;
1048        let mut cursor_position = POINT { x: pt.x, y: pt.y };
1049        unsafe {
1050            *pdweffect = DROPEFFECT_COPY;
1051            self.0
1052                .drop_target_helper
1053                .Drop(idata_obj, &cursor_position, *pdweffect)
1054                .log_err();
1055            ScreenToClient(self.0.hwnd, &mut cursor_position)
1056                .ok()
1057                .log_err();
1058        }
1059        let scale_factor = self.0.state.scale_factor.get();
1060        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1061            position: logical_point(
1062                cursor_position.x as f32,
1063                cursor_position.y as f32,
1064                scale_factor,
1065            ),
1066        });
1067        self.handle_drag_drop(input);
1068
1069        Ok(())
1070    }
1071}
1072
1073#[derive(Debug, Clone)]
1074pub(crate) struct ClickState {
1075    button: Cell<MouseButton>,
1076    last_click: Cell<Instant>,
1077    last_position: Cell<Point<DevicePixels>>,
1078    double_click_spatial_tolerance_width: Cell<i32>,
1079    double_click_spatial_tolerance_height: Cell<i32>,
1080    double_click_interval: Cell<Duration>,
1081    pub(crate) current_count: Cell<usize>,
1082}
1083
1084impl ClickState {
1085    pub fn new() -> Self {
1086        let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
1087        let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
1088        let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
1089
1090        ClickState {
1091            button: Cell::new(MouseButton::Left),
1092            last_click: Cell::new(Instant::now()),
1093            last_position: Cell::new(Point::default()),
1094            double_click_spatial_tolerance_width: Cell::new(double_click_spatial_tolerance_width),
1095            double_click_spatial_tolerance_height: Cell::new(double_click_spatial_tolerance_height),
1096            double_click_interval: Cell::new(double_click_interval),
1097            current_count: Cell::new(0),
1098        }
1099    }
1100
1101    /// update self and return the needed click count
1102    pub fn update(&self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
1103        if self.button.get() == button && self.is_double_click(new_position) {
1104            self.current_count.update(|it| it + 1);
1105        } else {
1106            self.current_count.set(1);
1107        }
1108        self.last_click.set(Instant::now());
1109        self.last_position.set(new_position);
1110        self.button.set(button);
1111
1112        self.current_count.get()
1113    }
1114
1115    pub fn system_update(&self, wparam: usize) {
1116        match wparam {
1117            // SPI_SETDOUBLECLKWIDTH
1118            29 => self
1119                .double_click_spatial_tolerance_width
1120                .set(unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }),
1121            // SPI_SETDOUBLECLKHEIGHT
1122            30 => self
1123                .double_click_spatial_tolerance_height
1124                .set(unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }),
1125            // SPI_SETDOUBLECLICKTIME
1126            32 => self
1127                .double_click_interval
1128                .set(Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)),
1129            _ => {}
1130        }
1131    }
1132
1133    #[inline]
1134    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
1135        let diff = self.last_position.get() - new_position;
1136
1137        self.last_click.get().elapsed() < self.double_click_interval.get()
1138            && diff.x.0.abs() <= self.double_click_spatial_tolerance_width.get()
1139            && diff.y.0.abs() <= self.double_click_spatial_tolerance_height.get()
1140    }
1141}
1142
1143#[derive(Copy, Clone)]
1144struct StyleAndBounds {
1145    style: WINDOW_STYLE,
1146    x: i32,
1147    y: i32,
1148    cx: i32,
1149    cy: i32,
1150}
1151
1152#[repr(C)]
1153struct WINDOWCOMPOSITIONATTRIBDATA {
1154    attrib: u32,
1155    pv_data: *mut std::ffi::c_void,
1156    cb_data: usize,
1157}
1158
1159#[repr(C)]
1160struct AccentPolicy {
1161    accent_state: u32,
1162    accent_flags: u32,
1163    gradient_color: u32,
1164    animation_id: u32,
1165}
1166
1167type Color = (u8, u8, u8, u8);
1168
1169#[derive(Debug, Default, Clone)]
1170pub(crate) struct WindowBorderOffset {
1171    pub(crate) width_offset: Cell<i32>,
1172    pub(crate) height_offset: Cell<i32>,
1173}
1174
1175impl WindowBorderOffset {
1176    pub(crate) fn update(&self, hwnd: HWND) -> anyhow::Result<()> {
1177        let window_rect = unsafe {
1178            let mut rect = std::mem::zeroed();
1179            GetWindowRect(hwnd, &mut rect)?;
1180            rect
1181        };
1182        let client_rect = unsafe {
1183            let mut rect = std::mem::zeroed();
1184            GetClientRect(hwnd, &mut rect)?;
1185            rect
1186        };
1187        self.width_offset
1188            .set((window_rect.right - window_rect.left) - (client_rect.right - client_rect.left));
1189        self.height_offset
1190            .set((window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top));
1191        Ok(())
1192    }
1193}
1194
1195#[derive(Clone)]
1196struct WindowOpenStatus {
1197    placement: WINDOWPLACEMENT,
1198    state: WindowOpenState,
1199}
1200
1201#[derive(Clone, Copy)]
1202enum WindowOpenState {
1203    Maximized,
1204    Fullscreen,
1205    Windowed,
1206}
1207
1208const WINDOW_CLASS_NAME: PCWSTR = w!("Zed::Window");
1209
1210fn register_window_class(icon_handle: HICON) {
1211    static ONCE: Once = Once::new();
1212    ONCE.call_once(|| {
1213        let wc = WNDCLASSW {
1214            lpfnWndProc: Some(window_procedure),
1215            hIcon: icon_handle,
1216            lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
1217            style: CS_HREDRAW | CS_VREDRAW,
1218            hInstance: get_module_handle().into(),
1219            hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1220            ..Default::default()
1221        };
1222        unsafe { RegisterClassW(&wc) };
1223    });
1224}
1225
1226unsafe extern "system" fn window_procedure(
1227    hwnd: HWND,
1228    msg: u32,
1229    wparam: WPARAM,
1230    lparam: LPARAM,
1231) -> LRESULT {
1232    if msg == WM_NCCREATE {
1233        let window_params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1234        let window_creation_context = window_params.lpCreateParams as *mut WindowCreateContext;
1235        let window_creation_context = unsafe { &mut *window_creation_context };
1236        return match WindowsWindowInner::new(window_creation_context, hwnd, window_params) {
1237            Ok(window_state) => {
1238                let weak = Box::new(Rc::downgrade(&window_state));
1239                unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1240                window_creation_context.inner = Some(Ok(window_state));
1241                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1242            }
1243            Err(error) => {
1244                window_creation_context.inner = Some(Err(error));
1245                LRESULT(0)
1246            }
1247        };
1248    }
1249
1250    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1251    if ptr.is_null() {
1252        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1253    }
1254    let inner = unsafe { &*ptr };
1255    let result = if let Some(inner) = inner.upgrade() {
1256        inner.handle_msg(hwnd, msg, wparam, lparam)
1257    } else {
1258        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1259    };
1260
1261    if msg == WM_NCDESTROY {
1262        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1263        unsafe { drop(Box::from_raw(ptr)) };
1264    }
1265
1266    result
1267}
1268
1269pub(crate) fn window_from_hwnd(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
1270    if hwnd.is_invalid() {
1271        return None;
1272    }
1273
1274    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1275    if !ptr.is_null() {
1276        let inner = unsafe { &*ptr };
1277        inner.upgrade()
1278    } else {
1279        None
1280    }
1281}
1282
1283fn get_module_handle() -> HMODULE {
1284    unsafe {
1285        let mut h_module = std::mem::zeroed();
1286        GetModuleHandleExW(
1287            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1288            windows::core::w!("ZedModule"),
1289            &mut h_module,
1290        )
1291        .expect("Unable to get module handle"); // this should never fail
1292
1293        h_module
1294    }
1295}
1296
1297fn register_drag_drop(window: &Rc<WindowsWindowInner>) -> Result<()> {
1298    let window_handle = window.hwnd;
1299    let handler = WindowsDragDropHandler(window.clone());
1300    // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1301    // we call `RevokeDragDrop`.
1302    // So, it's safe to drop it here.
1303    let drag_drop_handler: IDropTarget = handler.into();
1304    unsafe {
1305        RegisterDragDrop(window_handle, &drag_drop_handler)
1306            .context("unable to register drag-drop event")?;
1307    }
1308    Ok(())
1309}
1310
1311fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: &WindowBorderOffset) -> RECT {
1312    // NOTE:
1313    // The reason we're not using `AdjustWindowRectEx()` here is
1314    // that the size reported by this function is incorrect.
1315    // You can test it, and there are similar discussions online.
1316    // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1317    //
1318    // So we manually calculate these values here.
1319    let mut rect = RECT {
1320        left: bounds.left().0,
1321        top: bounds.top().0,
1322        right: bounds.right().0,
1323        bottom: bounds.bottom().0,
1324    };
1325    let left_offset = border_offset.width_offset.get() / 2;
1326    let top_offset = border_offset.height_offset.get() / 2;
1327    let right_offset = border_offset.width_offset.get() - left_offset;
1328    let bottom_offset = border_offset.height_offset.get() - top_offset;
1329    rect.left -= left_offset;
1330    rect.top -= top_offset;
1331    rect.right += right_offset;
1332    rect.bottom += bottom_offset;
1333    rect
1334}
1335
1336fn calculate_client_rect(
1337    rect: RECT,
1338    border_offset: &WindowBorderOffset,
1339    scale_factor: f32,
1340) -> Bounds<Pixels> {
1341    let left_offset = border_offset.width_offset.get() / 2;
1342    let top_offset = border_offset.height_offset.get() / 2;
1343    let right_offset = border_offset.width_offset.get() - left_offset;
1344    let bottom_offset = border_offset.height_offset.get() - top_offset;
1345    let left = rect.left + left_offset;
1346    let top = rect.top + top_offset;
1347    let right = rect.right - right_offset;
1348    let bottom = rect.bottom - bottom_offset;
1349    let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1350    Bounds {
1351        origin: logical_point(left as f32, top as f32, scale_factor),
1352        size: physical_size.to_pixels(scale_factor),
1353    }
1354}
1355
1356fn retrieve_window_placement(
1357    hwnd: HWND,
1358    display: WindowsDisplay,
1359    initial_bounds: Bounds<Pixels>,
1360    scale_factor: f32,
1361    border_offset: &WindowBorderOffset,
1362) -> Result<WINDOWPLACEMENT> {
1363    let mut placement = WINDOWPLACEMENT {
1364        length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1365        ..Default::default()
1366    };
1367    unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1368    // the bounds may be not inside the display
1369    let bounds = if display.check_given_bounds(initial_bounds) {
1370        initial_bounds
1371    } else {
1372        display.default_bounds()
1373    };
1374    let bounds = bounds.to_device_pixels(scale_factor);
1375    placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1376    Ok(placement)
1377}
1378
1379fn dwm_set_window_composition_attribute(hwnd: HWND, backdrop_type: u32) {
1380    let mut version = unsafe { std::mem::zeroed() };
1381    let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1382
1383    // DWMWA_SYSTEMBACKDROP_TYPE is available only on version 22621 or later
1384    // using SetWindowCompositionAttributeType as a fallback
1385    if !status.is_ok() || version.dwBuildNumber < 22621 {
1386        return;
1387    }
1388
1389    unsafe {
1390        let result = DwmSetWindowAttribute(
1391            hwnd,
1392            DWMWA_SYSTEMBACKDROP_TYPE,
1393            &backdrop_type as *const _ as *const _,
1394            std::mem::size_of_val(&backdrop_type) as u32,
1395        );
1396
1397        if !result.is_ok() {
1398            return;
1399        }
1400    }
1401}
1402
1403fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1404    let mut version = unsafe { std::mem::zeroed() };
1405    let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1406
1407    if !status.is_ok() || version.dwBuildNumber < 17763 {
1408        return;
1409    }
1410
1411    unsafe {
1412        type SetWindowCompositionAttributeType =
1413            unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1414        let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1415        if let Some(user32) = GetModuleHandleA(module_name)
1416            .context("Unable to get user32.dll handle")
1417            .log_err()
1418        {
1419            let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1420            let set_window_composition_attribute: SetWindowCompositionAttributeType =
1421                std::mem::transmute(GetProcAddress(user32, func_name));
1422            let mut color = color.unwrap_or_default();
1423            let is_acrylic = state == 4;
1424            if is_acrylic && color.3 == 0 {
1425                color.3 = 1;
1426            }
1427            let accent = AccentPolicy {
1428                accent_state: state,
1429                accent_flags: if is_acrylic { 0 } else { 2 },
1430                gradient_color: (color.0 as u32)
1431                    | ((color.1 as u32) << 8)
1432                    | ((color.2 as u32) << 16)
1433                    | ((color.3 as u32) << 24),
1434                animation_id: 0,
1435            };
1436            let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1437                attrib: 0x13,
1438                pv_data: &accent as *const _ as *mut _,
1439                cb_data: std::mem::size_of::<AccentPolicy>(),
1440            };
1441            let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1442        }
1443    }
1444}
1445
1446#[cfg(test)]
1447mod tests {
1448    use super::ClickState;
1449    use crate::{DevicePixels, MouseButton, point};
1450    use std::time::Duration;
1451
1452    #[test]
1453    fn test_double_click_interval() {
1454        let mut state = ClickState::new();
1455        assert_eq!(
1456            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1457            1
1458        );
1459        assert_eq!(
1460            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1461            1
1462        );
1463        assert_eq!(
1464            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1465            1
1466        );
1467        assert_eq!(
1468            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1469            2
1470        );
1471        state
1472            .last_click
1473            .update(|it| it - Duration::from_millis(700));
1474        assert_eq!(
1475            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1476            1
1477        );
1478    }
1479
1480    #[test]
1481    fn test_double_click_spatial_tolerance() {
1482        let mut state = ClickState::new();
1483        assert_eq!(
1484            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1485            1
1486        );
1487        assert_eq!(
1488            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1489            2
1490        );
1491        assert_eq!(
1492            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1493            1
1494        );
1495        assert_eq!(
1496            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1497            1
1498        );
1499    }
1500}