window.rs

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