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().unwrap()?;
 457        let hwnd = creation_result?;
 458
 459        register_drag_drop(&this)?;
 460        configure_dwm_dark_mode(hwnd, appearance);
 461        this.state.borrow_mut().border_offset.update(hwnd)?;
 462        let placement = retrieve_window_placement(
 463            hwnd,
 464            display,
 465            params.bounds,
 466            this.state.borrow().scale_factor,
 467            this.state.borrow().border_offset,
 468        )?;
 469        if params.show {
 470            unsafe { SetWindowPlacement(hwnd, &placement)? };
 471        } else {
 472            this.state.borrow_mut().initial_placement = Some(WindowOpenStatus {
 473                placement,
 474                state: WindowOpenState::Windowed,
 475            });
 476        }
 477
 478        Ok(Self(this))
 479    }
 480}
 481
 482impl rwh::HasWindowHandle for WindowsWindow {
 483    fn window_handle(&self) -> std::result::Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 484        let raw = rwh::Win32WindowHandle::new(unsafe {
 485            NonZeroIsize::new_unchecked(self.0.hwnd.0 as isize)
 486        })
 487        .into();
 488        Ok(unsafe { rwh::WindowHandle::borrow_raw(raw) })
 489    }
 490}
 491
 492// todo(windows)
 493impl rwh::HasDisplayHandle for WindowsWindow {
 494    fn display_handle(&self) -> std::result::Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 495        unimplemented!()
 496    }
 497}
 498
 499impl Drop for WindowsWindow {
 500    fn drop(&mut self) {
 501        // clone this `Rc` to prevent early release of the pointer
 502        let this = self.0.clone();
 503        self.0
 504            .executor
 505            .spawn(async move {
 506                let handle = this.hwnd;
 507                unsafe {
 508                    RevokeDragDrop(handle).log_err();
 509                    DestroyWindow(handle).log_err();
 510                }
 511            })
 512            .detach();
 513    }
 514}
 515
 516impl PlatformWindow for WindowsWindow {
 517    fn bounds(&self) -> Bounds<Pixels> {
 518        self.0.state.borrow().bounds()
 519    }
 520
 521    fn is_maximized(&self) -> bool {
 522        self.0.state.borrow().is_maximized()
 523    }
 524
 525    fn window_bounds(&self) -> WindowBounds {
 526        self.0.state.borrow().window_bounds()
 527    }
 528
 529    /// get the logical size of the app's drawable area.
 530    ///
 531    /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
 532    /// whether the mouse collides with other elements of GPUI).
 533    fn content_size(&self) -> Size<Pixels> {
 534        self.0.state.borrow().content_size()
 535    }
 536
 537    fn resize(&mut self, size: Size<Pixels>) {
 538        let hwnd = self.0.hwnd;
 539        let bounds =
 540            crate::bounds(self.bounds().origin, size).to_device_pixels(self.scale_factor());
 541        let rect = calculate_window_rect(bounds, self.0.state.borrow().border_offset);
 542
 543        self.0
 544            .executor
 545            .spawn(async move {
 546                unsafe {
 547                    SetWindowPos(
 548                        hwnd,
 549                        None,
 550                        bounds.origin.x.0,
 551                        bounds.origin.y.0,
 552                        rect.right - rect.left,
 553                        rect.bottom - rect.top,
 554                        SWP_NOMOVE,
 555                    )
 556                    .context("unable to set window content size")
 557                    .log_err();
 558                }
 559            })
 560            .detach();
 561    }
 562
 563    fn scale_factor(&self) -> f32 {
 564        self.0.state.borrow().scale_factor
 565    }
 566
 567    fn appearance(&self) -> WindowAppearance {
 568        self.0.state.borrow().appearance
 569    }
 570
 571    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 572        Some(Rc::new(self.0.state.borrow().display))
 573    }
 574
 575    fn mouse_position(&self) -> Point<Pixels> {
 576        let scale_factor = self.scale_factor();
 577        let point = unsafe {
 578            let mut point: POINT = std::mem::zeroed();
 579            GetCursorPos(&mut point)
 580                .context("unable to get cursor position")
 581                .log_err();
 582            ScreenToClient(self.0.hwnd, &mut point).ok().log_err();
 583            point
 584        };
 585        logical_point(point.x as f32, point.y as f32, scale_factor)
 586    }
 587
 588    fn modifiers(&self) -> Modifiers {
 589        current_modifiers()
 590    }
 591
 592    fn capslock(&self) -> Capslock {
 593        current_capslock()
 594    }
 595
 596    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 597        self.0.state.borrow_mut().input_handler = Some(input_handler);
 598    }
 599
 600    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 601        self.0.state.borrow_mut().input_handler.take()
 602    }
 603
 604    fn prompt(
 605        &self,
 606        level: PromptLevel,
 607        msg: &str,
 608        detail: Option<&str>,
 609        answers: &[PromptButton],
 610    ) -> Option<Receiver<usize>> {
 611        let (done_tx, done_rx) = oneshot::channel();
 612        let msg = msg.to_string();
 613        let detail_string = detail.map(|detail| detail.to_string());
 614        let handle = self.0.hwnd;
 615        let answers = answers.to_vec();
 616        self.0
 617            .executor
 618            .spawn(async move {
 619                unsafe {
 620                    let mut config = TASKDIALOGCONFIG::default();
 621                    config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;
 622                    config.hwndParent = handle;
 623                    let title;
 624                    let main_icon;
 625                    match level {
 626                        crate::PromptLevel::Info => {
 627                            title = windows::core::w!("Info");
 628                            main_icon = TD_INFORMATION_ICON;
 629                        }
 630                        crate::PromptLevel::Warning => {
 631                            title = windows::core::w!("Warning");
 632                            main_icon = TD_WARNING_ICON;
 633                        }
 634                        crate::PromptLevel::Critical => {
 635                            title = windows::core::w!("Critical");
 636                            main_icon = TD_ERROR_ICON;
 637                        }
 638                    };
 639                    config.pszWindowTitle = title;
 640                    config.Anonymous1.pszMainIcon = main_icon;
 641                    let instruction = HSTRING::from(msg);
 642                    config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());
 643                    let hints_encoded;
 644                    if let Some(ref hints) = detail_string {
 645                        hints_encoded = HSTRING::from(hints);
 646                        config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());
 647                    };
 648                    let mut button_id_map = Vec::with_capacity(answers.len());
 649                    let mut buttons = Vec::new();
 650                    let mut btn_encoded = Vec::new();
 651                    for (index, btn) in answers.iter().enumerate() {
 652                        let encoded = HSTRING::from(btn.label().as_ref());
 653                        let button_id = match btn {
 654                            PromptButton::Ok(_) => IDOK.0,
 655                            PromptButton::Cancel(_) => IDCANCEL.0,
 656                            // the first few low integer values are reserved for known buttons
 657                            // so for simplicity we just go backwards from -1
 658                            PromptButton::Other(_) => -(index as i32) - 1,
 659                        };
 660                        button_id_map.push(button_id);
 661                        buttons.push(TASKDIALOG_BUTTON {
 662                            nButtonID: button_id,
 663                            pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),
 664                        });
 665                        btn_encoded.push(encoded);
 666                    }
 667                    config.cButtons = buttons.len() as _;
 668                    config.pButtons = buttons.as_ptr();
 669
 670                    config.pfCallback = None;
 671                    let mut res = std::mem::zeroed();
 672                    let _ = TaskDialogIndirect(&config, Some(&mut res), None, None)
 673                        .context("unable to create task dialog")
 674                        .log_err();
 675
 676                    if let Some(clicked) =
 677                        button_id_map.iter().position(|&button_id| button_id == res)
 678                    {
 679                        let _ = done_tx.send(clicked);
 680                    }
 681                }
 682            })
 683            .detach();
 684
 685        Some(done_rx)
 686    }
 687
 688    fn activate(&self) {
 689        let hwnd = self.0.hwnd;
 690        let this = self.0.clone();
 691        self.0
 692            .executor
 693            .spawn(async move {
 694                this.set_window_placement().log_err();
 695
 696                unsafe {
 697                    // If the window is minimized, restore it.
 698                    if IsIconic(hwnd).as_bool() {
 699                        ShowWindowAsync(hwnd, SW_RESTORE).ok().log_err();
 700                    }
 701
 702                    SetActiveWindow(hwnd).log_err();
 703                    SetFocus(Some(hwnd)).log_err();
 704                }
 705
 706                // premium ragebait by windows, this is needed because the window
 707                // must have received an input event to be able to set itself to foreground
 708                // so let's just simulate user input as that seems to be the most reliable way
 709                // some more info: https://gist.github.com/Aetopia/1581b40f00cc0cadc93a0e8ccb65dc8c
 710                // bonus: this bug also doesn't manifest if you have vs attached to the process
 711                let inputs = [
 712                    INPUT {
 713                        r#type: INPUT_KEYBOARD,
 714                        Anonymous: INPUT_0 {
 715                            ki: KEYBDINPUT {
 716                                wVk: VK_MENU,
 717                                dwFlags: KEYBD_EVENT_FLAGS(0),
 718                                ..Default::default()
 719                            },
 720                        },
 721                    },
 722                    INPUT {
 723                        r#type: INPUT_KEYBOARD,
 724                        Anonymous: INPUT_0 {
 725                            ki: KEYBDINPUT {
 726                                wVk: VK_MENU,
 727                                dwFlags: KEYEVENTF_KEYUP,
 728                                ..Default::default()
 729                            },
 730                        },
 731                    },
 732                ];
 733                unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };
 734
 735                // todo(windows)
 736                // crate `windows 0.56` reports true as Err
 737                unsafe { SetForegroundWindow(hwnd).as_bool() };
 738            })
 739            .detach();
 740    }
 741
 742    fn is_active(&self) -> bool {
 743        self.0.hwnd == unsafe { GetActiveWindow() }
 744    }
 745
 746    fn is_hovered(&self) -> bool {
 747        self.0.state.borrow().hovered
 748    }
 749
 750    fn set_title(&mut self, title: &str) {
 751        unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
 752            .inspect_err(|e| log::error!("Set title failed: {e}"))
 753            .ok();
 754    }
 755
 756    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
 757        let hwnd = self.0.hwnd;
 758
 759        match background_appearance {
 760            WindowBackgroundAppearance::Opaque => {
 761                // ACCENT_DISABLED
 762                set_window_composition_attribute(hwnd, None, 0);
 763            }
 764            WindowBackgroundAppearance::Transparent => {
 765                // Use ACCENT_ENABLE_TRANSPARENTGRADIENT for transparent background
 766                set_window_composition_attribute(hwnd, None, 2);
 767            }
 768            WindowBackgroundAppearance::Blurred => {
 769                // Enable acrylic blur
 770                // ACCENT_ENABLE_ACRYLICBLURBEHIND
 771                set_window_composition_attribute(hwnd, Some((0, 0, 0, 0)), 4);
 772            }
 773        }
 774    }
 775
 776    fn minimize(&self) {
 777        unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
 778    }
 779
 780    fn zoom(&self) {
 781        unsafe {
 782            if IsWindowVisible(self.0.hwnd).as_bool() {
 783                ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
 784            } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
 785                status.state = WindowOpenState::Maximized;
 786            }
 787        }
 788    }
 789
 790    fn toggle_fullscreen(&self) {
 791        if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
 792            self.0.toggle_fullscreen();
 793        } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
 794            status.state = WindowOpenState::Fullscreen;
 795        }
 796    }
 797
 798    fn is_fullscreen(&self) -> bool {
 799        self.0.state.borrow().is_fullscreen()
 800    }
 801
 802    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
 803        self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
 804    }
 805
 806    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
 807        self.0.state.borrow_mut().callbacks.input = Some(callback);
 808    }
 809
 810    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 811        self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
 812    }
 813
 814    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 815        self.0.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
 816    }
 817
 818    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 819        self.0.state.borrow_mut().callbacks.resize = Some(callback);
 820    }
 821
 822    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 823        self.0.state.borrow_mut().callbacks.moved = Some(callback);
 824    }
 825
 826    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 827        self.0.state.borrow_mut().callbacks.should_close = Some(callback);
 828    }
 829
 830    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 831        self.0.state.borrow_mut().callbacks.close = Some(callback);
 832    }
 833
 834    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
 835        self.0.state.borrow_mut().callbacks.hit_test_window_control = Some(callback);
 836    }
 837
 838    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 839        self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
 840    }
 841
 842    fn draw(&self, scene: &Scene) {
 843        self.0.state.borrow_mut().renderer.draw(scene).log_err();
 844    }
 845
 846    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 847        self.0.state.borrow().renderer.sprite_atlas()
 848    }
 849
 850    fn get_raw_handle(&self) -> HWND {
 851        self.0.hwnd
 852    }
 853
 854    fn gpu_specs(&self) -> Option<GpuSpecs> {
 855        self.0.state.borrow().renderer.gpu_specs().log_err()
 856    }
 857
 858    fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
 859        // There is no such thing on Windows.
 860    }
 861}
 862
 863#[implement(IDropTarget)]
 864struct WindowsDragDropHandler(pub Rc<WindowsWindowInner>);
 865
 866impl WindowsDragDropHandler {
 867    fn handle_drag_drop(&self, input: PlatformInput) {
 868        let mut lock = self.0.state.borrow_mut();
 869        if let Some(mut func) = lock.callbacks.input.take() {
 870            drop(lock);
 871            func(input);
 872            self.0.state.borrow_mut().callbacks.input = Some(func);
 873        }
 874    }
 875}
 876
 877#[allow(non_snake_case)]
 878impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
 879    fn DragEnter(
 880        &self,
 881        pdataobj: windows::core::Ref<IDataObject>,
 882        _grfkeystate: MODIFIERKEYS_FLAGS,
 883        pt: &POINTL,
 884        pdweffect: *mut DROPEFFECT,
 885    ) -> windows::core::Result<()> {
 886        unsafe {
 887            let idata_obj = pdataobj.ok()?;
 888            let config = FORMATETC {
 889                cfFormat: CF_HDROP.0,
 890                ptd: std::ptr::null_mut() as _,
 891                dwAspect: DVASPECT_CONTENT.0,
 892                lindex: -1,
 893                tymed: TYMED_HGLOBAL.0 as _,
 894            };
 895            let cursor_position = POINT { x: pt.x, y: pt.y };
 896            if idata_obj.QueryGetData(&config as _) == S_OK {
 897                *pdweffect = DROPEFFECT_COPY;
 898                let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
 899                    return Ok(());
 900                };
 901                if idata.u.hGlobal.is_invalid() {
 902                    return Ok(());
 903                }
 904                let hdrop = HDROP(idata.u.hGlobal.0);
 905                let mut paths = SmallVec::<[PathBuf; 2]>::new();
 906                with_file_names(hdrop, |file_name| {
 907                    if let Some(path) = PathBuf::from_str(&file_name).log_err() {
 908                        paths.push(path);
 909                    }
 910                });
 911                ReleaseStgMedium(&mut idata);
 912                let mut cursor_position = cursor_position;
 913                ScreenToClient(self.0.hwnd, &mut cursor_position)
 914                    .ok()
 915                    .log_err();
 916                let scale_factor = self.0.state.borrow().scale_factor;
 917                let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 918                    position: logical_point(
 919                        cursor_position.x as f32,
 920                        cursor_position.y as f32,
 921                        scale_factor,
 922                    ),
 923                    paths: ExternalPaths(paths),
 924                });
 925                self.handle_drag_drop(input);
 926            } else {
 927                *pdweffect = DROPEFFECT_NONE;
 928            }
 929            self.0
 930                .drop_target_helper
 931                .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)
 932                .log_err();
 933        }
 934        Ok(())
 935    }
 936
 937    fn DragOver(
 938        &self,
 939        _grfkeystate: MODIFIERKEYS_FLAGS,
 940        pt: &POINTL,
 941        pdweffect: *mut DROPEFFECT,
 942    ) -> windows::core::Result<()> {
 943        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 944        unsafe {
 945            *pdweffect = DROPEFFECT_COPY;
 946            self.0
 947                .drop_target_helper
 948                .DragOver(&cursor_position, *pdweffect)
 949                .log_err();
 950            ScreenToClient(self.0.hwnd, &mut cursor_position)
 951                .ok()
 952                .log_err();
 953        }
 954        let scale_factor = self.0.state.borrow().scale_factor;
 955        let input = PlatformInput::FileDrop(FileDropEvent::Pending {
 956            position: logical_point(
 957                cursor_position.x as f32,
 958                cursor_position.y as f32,
 959                scale_factor,
 960            ),
 961        });
 962        self.handle_drag_drop(input);
 963
 964        Ok(())
 965    }
 966
 967    fn DragLeave(&self) -> windows::core::Result<()> {
 968        unsafe {
 969            self.0.drop_target_helper.DragLeave().log_err();
 970        }
 971        let input = PlatformInput::FileDrop(FileDropEvent::Exited);
 972        self.handle_drag_drop(input);
 973
 974        Ok(())
 975    }
 976
 977    fn Drop(
 978        &self,
 979        pdataobj: windows::core::Ref<IDataObject>,
 980        _grfkeystate: MODIFIERKEYS_FLAGS,
 981        pt: &POINTL,
 982        pdweffect: *mut DROPEFFECT,
 983    ) -> windows::core::Result<()> {
 984        let idata_obj = pdataobj.ok()?;
 985        let mut cursor_position = POINT { x: pt.x, y: pt.y };
 986        unsafe {
 987            *pdweffect = DROPEFFECT_COPY;
 988            self.0
 989                .drop_target_helper
 990                .Drop(idata_obj, &cursor_position, *pdweffect)
 991                .log_err();
 992            ScreenToClient(self.0.hwnd, &mut cursor_position)
 993                .ok()
 994                .log_err();
 995        }
 996        let scale_factor = self.0.state.borrow().scale_factor;
 997        let input = PlatformInput::FileDrop(FileDropEvent::Submit {
 998            position: logical_point(
 999                cursor_position.x as f32,
1000                cursor_position.y as f32,
1001                scale_factor,
1002            ),
1003        });
1004        self.handle_drag_drop(input);
1005
1006        Ok(())
1007    }
1008}
1009
1010#[derive(Debug, Clone, Copy)]
1011pub(crate) struct ClickState {
1012    button: MouseButton,
1013    last_click: Instant,
1014    last_position: Point<DevicePixels>,
1015    double_click_spatial_tolerance_width: i32,
1016    double_click_spatial_tolerance_height: i32,
1017    double_click_interval: Duration,
1018    pub(crate) current_count: usize,
1019}
1020
1021impl ClickState {
1022    pub fn new() -> Self {
1023        let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
1024        let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
1025        let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
1026
1027        ClickState {
1028            button: MouseButton::Left,
1029            last_click: Instant::now(),
1030            last_position: Point::default(),
1031            double_click_spatial_tolerance_width,
1032            double_click_spatial_tolerance_height,
1033            double_click_interval,
1034            current_count: 0,
1035        }
1036    }
1037
1038    /// update self and return the needed click count
1039    pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
1040        if self.button == button && self.is_double_click(new_position) {
1041            self.current_count += 1;
1042        } else {
1043            self.current_count = 1;
1044        }
1045        self.last_click = Instant::now();
1046        self.last_position = new_position;
1047        self.button = button;
1048
1049        self.current_count
1050    }
1051
1052    pub fn system_update(&mut self, wparam: usize) {
1053        match wparam {
1054            // SPI_SETDOUBLECLKWIDTH
1055            29 => {
1056                self.double_click_spatial_tolerance_width =
1057                    unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }
1058            }
1059            // SPI_SETDOUBLECLKHEIGHT
1060            30 => {
1061                self.double_click_spatial_tolerance_height =
1062                    unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }
1063            }
1064            // SPI_SETDOUBLECLICKTIME
1065            32 => {
1066                self.double_click_interval =
1067                    Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)
1068            }
1069            _ => {}
1070        }
1071    }
1072
1073    #[inline]
1074    fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
1075        let diff = self.last_position - new_position;
1076
1077        self.last_click.elapsed() < self.double_click_interval
1078            && diff.x.0.abs() <= self.double_click_spatial_tolerance_width
1079            && diff.y.0.abs() <= self.double_click_spatial_tolerance_height
1080    }
1081}
1082
1083struct StyleAndBounds {
1084    style: WINDOW_STYLE,
1085    x: i32,
1086    y: i32,
1087    cx: i32,
1088    cy: i32,
1089}
1090
1091#[repr(C)]
1092struct WINDOWCOMPOSITIONATTRIBDATA {
1093    attrib: u32,
1094    pv_data: *mut std::ffi::c_void,
1095    cb_data: usize,
1096}
1097
1098#[repr(C)]
1099struct AccentPolicy {
1100    accent_state: u32,
1101    accent_flags: u32,
1102    gradient_color: u32,
1103    animation_id: u32,
1104}
1105
1106type Color = (u8, u8, u8, u8);
1107
1108#[derive(Debug, Default, Clone, Copy)]
1109pub(crate) struct WindowBorderOffset {
1110    pub(crate) width_offset: i32,
1111    pub(crate) height_offset: i32,
1112}
1113
1114impl WindowBorderOffset {
1115    pub(crate) fn update(&mut self, hwnd: HWND) -> anyhow::Result<()> {
1116        let window_rect = unsafe {
1117            let mut rect = std::mem::zeroed();
1118            GetWindowRect(hwnd, &mut rect)?;
1119            rect
1120        };
1121        let client_rect = unsafe {
1122            let mut rect = std::mem::zeroed();
1123            GetClientRect(hwnd, &mut rect)?;
1124            rect
1125        };
1126        self.width_offset =
1127            (window_rect.right - window_rect.left) - (client_rect.right - client_rect.left);
1128        self.height_offset =
1129            (window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top);
1130        Ok(())
1131    }
1132}
1133
1134struct WindowOpenStatus {
1135    placement: WINDOWPLACEMENT,
1136    state: WindowOpenState,
1137}
1138
1139enum WindowOpenState {
1140    Maximized,
1141    Fullscreen,
1142    Windowed,
1143}
1144
1145const WINDOW_CLASS_NAME: PCWSTR = w!("Zed::Window");
1146
1147fn register_window_class(icon_handle: HICON) {
1148    static ONCE: Once = Once::new();
1149    ONCE.call_once(|| {
1150        let wc = WNDCLASSW {
1151            lpfnWndProc: Some(window_procedure),
1152            hIcon: icon_handle,
1153            lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
1154            style: CS_HREDRAW | CS_VREDRAW,
1155            hInstance: get_module_handle().into(),
1156            hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1157            ..Default::default()
1158        };
1159        unsafe { RegisterClassW(&wc) };
1160    });
1161}
1162
1163unsafe extern "system" fn window_procedure(
1164    hwnd: HWND,
1165    msg: u32,
1166    wparam: WPARAM,
1167    lparam: LPARAM,
1168) -> LRESULT {
1169    if msg == WM_NCCREATE {
1170        let window_params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1171        let window_creation_context = window_params.lpCreateParams as *mut WindowCreateContext;
1172        let window_creation_context = unsafe { &mut *window_creation_context };
1173        return match WindowsWindowInner::new(window_creation_context, hwnd, window_params) {
1174            Ok(window_state) => {
1175                let weak = Box::new(Rc::downgrade(&window_state));
1176                unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1177                window_creation_context.inner = Some(Ok(window_state));
1178                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1179            }
1180            Err(error) => {
1181                window_creation_context.inner = Some(Err(error));
1182                LRESULT(0)
1183            }
1184        };
1185    }
1186
1187    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1188    if ptr.is_null() {
1189        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1190    }
1191    let inner = unsafe { &*ptr };
1192    let result = if let Some(inner) = inner.upgrade() {
1193        inner.handle_msg(hwnd, msg, wparam, lparam)
1194    } else {
1195        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1196    };
1197
1198    if msg == WM_NCDESTROY {
1199        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1200        unsafe { drop(Box::from_raw(ptr)) };
1201    }
1202
1203    result
1204}
1205
1206pub(crate) fn window_from_hwnd(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
1207    if hwnd.is_invalid() {
1208        return None;
1209    }
1210
1211    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1212    if !ptr.is_null() {
1213        let inner = unsafe { &*ptr };
1214        inner.upgrade()
1215    } else {
1216        None
1217    }
1218}
1219
1220fn get_module_handle() -> HMODULE {
1221    unsafe {
1222        let mut h_module = std::mem::zeroed();
1223        GetModuleHandleExW(
1224            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1225            windows::core::w!("ZedModule"),
1226            &mut h_module,
1227        )
1228        .expect("Unable to get module handle"); // this should never fail
1229
1230        h_module
1231    }
1232}
1233
1234fn register_drag_drop(window: &Rc<WindowsWindowInner>) -> Result<()> {
1235    let window_handle = window.hwnd;
1236    let handler = WindowsDragDropHandler(window.clone());
1237    // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1238    // we call `RevokeDragDrop`.
1239    // So, it's safe to drop it here.
1240    let drag_drop_handler: IDropTarget = handler.into();
1241    unsafe {
1242        RegisterDragDrop(window_handle, &drag_drop_handler)
1243            .context("unable to register drag-drop event")?;
1244    }
1245    Ok(())
1246}
1247
1248fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: WindowBorderOffset) -> RECT {
1249    // NOTE:
1250    // The reason we're not using `AdjustWindowRectEx()` here is
1251    // that the size reported by this function is incorrect.
1252    // You can test it, and there are similar discussions online.
1253    // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1254    //
1255    // So we manually calculate these values here.
1256    let mut rect = RECT {
1257        left: bounds.left().0,
1258        top: bounds.top().0,
1259        right: bounds.right().0,
1260        bottom: bounds.bottom().0,
1261    };
1262    let left_offset = border_offset.width_offset / 2;
1263    let top_offset = border_offset.height_offset / 2;
1264    let right_offset = border_offset.width_offset - left_offset;
1265    let bottom_offset = border_offset.height_offset - top_offset;
1266    rect.left -= left_offset;
1267    rect.top -= top_offset;
1268    rect.right += right_offset;
1269    rect.bottom += bottom_offset;
1270    rect
1271}
1272
1273fn calculate_client_rect(
1274    rect: RECT,
1275    border_offset: WindowBorderOffset,
1276    scale_factor: f32,
1277) -> Bounds<Pixels> {
1278    let left_offset = border_offset.width_offset / 2;
1279    let top_offset = border_offset.height_offset / 2;
1280    let right_offset = border_offset.width_offset - left_offset;
1281    let bottom_offset = border_offset.height_offset - top_offset;
1282    let left = rect.left + left_offset;
1283    let top = rect.top + top_offset;
1284    let right = rect.right - right_offset;
1285    let bottom = rect.bottom - bottom_offset;
1286    let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1287    Bounds {
1288        origin: logical_point(left as f32, top as f32, scale_factor),
1289        size: physical_size.to_pixels(scale_factor),
1290    }
1291}
1292
1293fn retrieve_window_placement(
1294    hwnd: HWND,
1295    display: WindowsDisplay,
1296    initial_bounds: Bounds<Pixels>,
1297    scale_factor: f32,
1298    border_offset: WindowBorderOffset,
1299) -> Result<WINDOWPLACEMENT> {
1300    let mut placement = WINDOWPLACEMENT {
1301        length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1302        ..Default::default()
1303    };
1304    unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1305    // the bounds may be not inside the display
1306    let bounds = if display.check_given_bounds(initial_bounds) {
1307        initial_bounds
1308    } else {
1309        display.default_bounds()
1310    };
1311    let bounds = bounds.to_device_pixels(scale_factor);
1312    placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1313    Ok(placement)
1314}
1315
1316fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1317    let mut version = unsafe { std::mem::zeroed() };
1318    let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1319    if !status.is_ok() || version.dwBuildNumber < 17763 {
1320        return;
1321    }
1322
1323    unsafe {
1324        type SetWindowCompositionAttributeType =
1325            unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1326        let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1327        if let Some(user32) = GetModuleHandleA(module_name)
1328            .context("Unable to get user32.dll handle")
1329            .log_err()
1330        {
1331            let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1332            let set_window_composition_attribute: SetWindowCompositionAttributeType =
1333                std::mem::transmute(GetProcAddress(user32, func_name));
1334            let mut color = color.unwrap_or_default();
1335            let is_acrylic = state == 4;
1336            if is_acrylic && color.3 == 0 {
1337                color.3 = 1;
1338            }
1339            let accent = AccentPolicy {
1340                accent_state: state,
1341                accent_flags: if is_acrylic { 0 } else { 2 },
1342                gradient_color: (color.0 as u32)
1343                    | ((color.1 as u32) << 8)
1344                    | ((color.2 as u32) << 16)
1345                    | ((color.3 as u32) << 24),
1346                animation_id: 0,
1347            };
1348            let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1349                attrib: 0x13,
1350                pv_data: &accent as *const _ as *mut _,
1351                cb_data: std::mem::size_of::<AccentPolicy>(),
1352            };
1353            let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1354        }
1355    }
1356}
1357
1358#[cfg(test)]
1359mod tests {
1360    use super::ClickState;
1361    use crate::{DevicePixels, MouseButton, point};
1362    use std::time::Duration;
1363
1364    #[test]
1365    fn test_double_click_interval() {
1366        let mut state = ClickState::new();
1367        assert_eq!(
1368            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1369            1
1370        );
1371        assert_eq!(
1372            state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1373            1
1374        );
1375        assert_eq!(
1376            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1377            1
1378        );
1379        assert_eq!(
1380            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1381            2
1382        );
1383        state.last_click -= Duration::from_millis(700);
1384        assert_eq!(
1385            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1386            1
1387        );
1388    }
1389
1390    #[test]
1391    fn test_double_click_spatial_tolerance() {
1392        let mut state = ClickState::new();
1393        assert_eq!(
1394            state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1395            1
1396        );
1397        assert_eq!(
1398            state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1399            2
1400        );
1401        assert_eq!(
1402            state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1403            1
1404        );
1405        assert_eq!(
1406            state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1407            1
1408        );
1409    }
1410}