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