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