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