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