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