window.rs

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