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