window.rs

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