1#![deny(unsafe_op_in_unsafe_fn)]
2
3use std::{
4 cell::RefCell,
5 num::NonZeroIsize,
6 path::PathBuf,
7 rc::{Rc, Weak},
8 str::FromStr,
9 sync::{Arc, Once},
10 time::{Duration, Instant},
11};
12
13use ::util::ResultExt;
14use anyhow::{Context as _, Result};
15use async_task::Runnable;
16use futures::channel::oneshot::{self, Receiver};
17use raw_window_handle as rwh;
18use smallvec::SmallVec;
19use windows::{
20 Win32::{
21 Foundation::*,
22 Graphics::Gdi::*,
23 System::{Com::*, LibraryLoader::*, Ole::*, SystemServices::*},
24 UI::{Controls::*, HiDpi::*, Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
25 },
26 core::*,
27};
28
29use crate::platform::blade::{BladeContext, BladeRenderer};
30use crate::*;
31
32pub(crate) struct WindowsWindow(pub Rc<WindowsWindowStatePtr>);
33
34pub struct WindowsWindowState {
35 pub origin: Point<Pixels>,
36 pub logical_size: Size<Pixels>,
37 pub min_size: Option<Size<Pixels>>,
38 pub fullscreen_restore_bounds: Bounds<Pixels>,
39 pub border_offset: WindowBorderOffset,
40 pub appearance: WindowAppearance,
41 pub scale_factor: f32,
42 pub restore_from_minimized: Option<Box<dyn FnMut(RequestFrameOptions)>>,
43
44 pub callbacks: Callbacks,
45 pub input_handler: Option<PlatformInputHandler>,
46 pub pending_surrogate: Option<u16>,
47 pub last_reported_modifiers: Option<Modifiers>,
48 pub last_reported_capslock: Option<Capslock>,
49 pub system_key_handled: bool,
50 pub hovered: bool,
51
52 pub renderer: DirectXRenderer,
53
54 pub click_state: ClickState,
55 pub system_settings: WindowsSystemSettings,
56 pub current_cursor: Option<HCURSOR>,
57 pub nc_button_pressed: Option<u32>,
58
59 pub display: WindowsDisplay,
60 fullscreen: Option<StyleAndBounds>,
61 initial_placement: Option<WindowOpenStatus>,
62 hwnd: HWND,
63}
64
65pub(crate) struct WindowsWindowStatePtr {
66 hwnd: HWND,
67 this: Weak<Self>,
68 drop_target_helper: IDropTargetHelper,
69 pub(crate) state: RefCell<WindowsWindowState>,
70 pub(crate) handle: AnyWindowHandle,
71 pub(crate) hide_title_bar: bool,
72 pub(crate) is_movable: bool,
73 pub(crate) executor: ForegroundExecutor,
74 pub(crate) windows_version: WindowsVersion,
75 pub(crate) validation_number: usize,
76 pub(crate) main_receiver: flume::Receiver<Runnable>,
77 pub(crate) main_thread_id_win32: u32,
78}
79
80impl WindowsWindowState {
81 fn new(
82 hwnd: HWND,
83 transparent: bool,
84 cs: &CREATESTRUCTW,
85 current_cursor: Option<HCURSOR>,
86 display: WindowsDisplay,
87 gpu_context: &DirectXDevices,
88 min_size: Option<Size<Pixels>>,
89 appearance: WindowAppearance,
90 ) -> Result<Self> {
91 let scale_factor = {
92 let monitor_dpi = unsafe { GetDpiForWindow(hwnd) } as f32;
93 monitor_dpi / USER_DEFAULT_SCREEN_DPI as f32
94 };
95 let origin = logical_point(cs.x as f32, cs.y as f32, scale_factor);
96 let logical_size = {
97 let physical_size = size(DevicePixels(cs.cx), DevicePixels(cs.cy));
98 physical_size.to_pixels(scale_factor)
99 };
100 let fullscreen_restore_bounds = Bounds {
101 origin,
102 size: logical_size,
103 };
104 let border_offset = WindowBorderOffset::default();
105 let restore_from_minimized = None;
106 // let renderer = windows_renderer::init(gpu_context, hwnd, transparent)?;
107 let renderer = DirectXRenderer::new(gpu_context, hwnd, transparent)?;
108 let callbacks = Callbacks::default();
109 let input_handler = None;
110 let pending_surrogate = None;
111 let last_reported_modifiers = None;
112 let last_reported_capslock = None;
113 let system_key_handled = false;
114 let hovered = false;
115 let click_state = ClickState::new();
116 let system_settings = WindowsSystemSettings::new(display);
117 let nc_button_pressed = None;
118 let fullscreen = None;
119 let initial_placement = None;
120
121 Ok(Self {
122 origin,
123 logical_size,
124 fullscreen_restore_bounds,
125 border_offset,
126 appearance,
127 scale_factor,
128 restore_from_minimized,
129 min_size,
130 callbacks,
131 input_handler,
132 pending_surrogate,
133 last_reported_modifiers,
134 last_reported_capslock,
135 system_key_handled,
136 hovered,
137 renderer,
138 click_state,
139 system_settings,
140 current_cursor,
141 nc_button_pressed,
142 display,
143 fullscreen,
144 initial_placement,
145 hwnd,
146 })
147 }
148
149 #[inline]
150 pub(crate) fn is_fullscreen(&self) -> bool {
151 self.fullscreen.is_some()
152 }
153
154 pub(crate) fn is_maximized(&self) -> bool {
155 !self.is_fullscreen() && unsafe { IsZoomed(self.hwnd) }.as_bool()
156 }
157
158 fn bounds(&self) -> Bounds<Pixels> {
159 Bounds {
160 origin: self.origin,
161 size: self.logical_size,
162 }
163 }
164
165 // Calculate the bounds used for saving and whether the window is maximized.
166 fn calculate_window_bounds(&self) -> (Bounds<Pixels>, bool) {
167 let placement = unsafe {
168 let mut placement = WINDOWPLACEMENT {
169 length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
170 ..Default::default()
171 };
172 GetWindowPlacement(self.hwnd, &mut placement).log_err();
173 placement
174 };
175 (
176 calculate_client_rect(
177 placement.rcNormalPosition,
178 self.border_offset,
179 self.scale_factor,
180 ),
181 placement.showCmd == SW_SHOWMAXIMIZED.0 as u32,
182 )
183 }
184
185 fn window_bounds(&self) -> WindowBounds {
186 let (bounds, maximized) = self.calculate_window_bounds();
187
188 if self.is_fullscreen() {
189 WindowBounds::Fullscreen(self.fullscreen_restore_bounds)
190 } else if maximized {
191 WindowBounds::Maximized(bounds)
192 } else {
193 WindowBounds::Windowed(bounds)
194 }
195 }
196
197 /// get the logical size of the app's drawable area.
198 ///
199 /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
200 /// whether the mouse collides with other elements of GPUI).
201 fn content_size(&self) -> Size<Pixels> {
202 self.logical_size
203 }
204}
205
206impl WindowsWindowStatePtr {
207 fn new(context: &WindowCreateContext, hwnd: HWND, cs: &CREATESTRUCTW) -> Result<Rc<Self>> {
208 let state = RefCell::new(WindowsWindowState::new(
209 hwnd,
210 context.transparent,
211 cs,
212 context.current_cursor,
213 context.display,
214 context.gpu_context,
215 context.min_size,
216 context.appearance,
217 )?);
218
219 Ok(Rc::new_cyclic(|this| Self {
220 hwnd,
221 this: this.clone(),
222 drop_target_helper: context.drop_target_helper.clone(),
223 state,
224 handle: context.handle,
225 hide_title_bar: context.hide_title_bar,
226 is_movable: context.is_movable,
227 executor: context.executor.clone(),
228 windows_version: context.windows_version,
229 validation_number: context.validation_number,
230 main_receiver: context.main_receiver.clone(),
231 main_thread_id_win32: context.main_thread_id_win32,
232 }))
233 }
234
235 fn toggle_fullscreen(&self) {
236 let Some(state_ptr) = self.this.upgrade() else {
237 log::error!("Unable to toggle fullscreen: window has been dropped");
238 return;
239 };
240 self.executor
241 .spawn(async move {
242 let mut lock = state_ptr.state.borrow_mut();
243 let StyleAndBounds {
244 style,
245 x,
246 y,
247 cx,
248 cy,
249 } = if let Some(state) = lock.fullscreen.take() {
250 state
251 } else {
252 let (window_bounds, _) = lock.calculate_window_bounds();
253 lock.fullscreen_restore_bounds = window_bounds;
254 let style =
255 WINDOW_STYLE(unsafe { get_window_long(state_ptr.hwnd, GWL_STYLE) } as _);
256 let mut rc = RECT::default();
257 unsafe { GetWindowRect(state_ptr.hwnd, &mut rc) }.log_err();
258 let _ = lock.fullscreen.insert(StyleAndBounds {
259 style,
260 x: rc.left,
261 y: rc.top,
262 cx: rc.right - rc.left,
263 cy: rc.bottom - rc.top,
264 });
265 let style = style
266 & !(WS_THICKFRAME
267 | WS_SYSMENU
268 | WS_MAXIMIZEBOX
269 | WS_MINIMIZEBOX
270 | WS_CAPTION);
271 let physical_bounds = lock.display.physical_bounds();
272 StyleAndBounds {
273 style,
274 x: physical_bounds.left().0,
275 y: physical_bounds.top().0,
276 cx: physical_bounds.size.width.0,
277 cy: physical_bounds.size.height.0,
278 }
279 };
280 drop(lock);
281 unsafe { set_window_long(state_ptr.hwnd, GWL_STYLE, style.0 as isize) };
282 unsafe {
283 SetWindowPos(
284 state_ptr.hwnd,
285 None,
286 x,
287 y,
288 cx,
289 cy,
290 SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER,
291 )
292 }
293 .log_err();
294 })
295 .detach();
296 }
297
298 fn set_window_placement(&self) -> Result<()> {
299 let Some(open_status) = self.state.borrow_mut().initial_placement.take() else {
300 return Ok(());
301 };
302 match open_status.state {
303 WindowOpenState::Maximized => unsafe {
304 SetWindowPlacement(self.hwnd, &open_status.placement)?;
305 ShowWindowAsync(self.hwnd, SW_MAXIMIZE).ok()?;
306 },
307 WindowOpenState::Fullscreen => {
308 unsafe { SetWindowPlacement(self.hwnd, &open_status.placement)? };
309 self.toggle_fullscreen();
310 }
311 WindowOpenState::Windowed => unsafe {
312 SetWindowPlacement(self.hwnd, &open_status.placement)?;
313 },
314 }
315 Ok(())
316 }
317}
318
319#[derive(Default)]
320pub(crate) struct Callbacks {
321 pub(crate) request_frame: Option<Box<dyn FnMut(RequestFrameOptions)>>,
322 pub(crate) input: Option<Box<dyn FnMut(crate::PlatformInput) -> DispatchEventResult>>,
323 pub(crate) active_status_change: Option<Box<dyn FnMut(bool)>>,
324 pub(crate) hovered_status_change: Option<Box<dyn FnMut(bool)>>,
325 pub(crate) resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
326 pub(crate) moved: Option<Box<dyn FnMut()>>,
327 pub(crate) should_close: Option<Box<dyn FnMut() -> bool>>,
328 pub(crate) close: Option<Box<dyn FnOnce()>>,
329 pub(crate) hit_test_window_control: Option<Box<dyn FnMut() -> Option<WindowControlArea>>>,
330 pub(crate) appearance_changed: Option<Box<dyn FnMut()>>,
331}
332
333struct WindowCreateContext<'a> {
334 inner: Option<Result<Rc<WindowsWindowStatePtr>>>,
335 handle: AnyWindowHandle,
336 hide_title_bar: bool,
337 display: WindowsDisplay,
338 transparent: bool,
339 is_movable: bool,
340 min_size: Option<Size<Pixels>>,
341 executor: ForegroundExecutor,
342 current_cursor: Option<HCURSOR>,
343 windows_version: WindowsVersion,
344 drop_target_helper: IDropTargetHelper,
345 validation_number: usize,
346 main_receiver: flume::Receiver<Runnable>,
347 gpu_context: &'a DirectXDevices,
348 main_thread_id_win32: u32,
349 appearance: WindowAppearance,
350}
351
352impl WindowsWindow {
353 pub(crate) fn new(
354 handle: AnyWindowHandle,
355 params: WindowParams,
356 creation_info: WindowCreationInfo,
357 gpu_context: &DirectXDevices,
358 ) -> Result<Self> {
359 let WindowCreationInfo {
360 icon,
361 executor,
362 current_cursor,
363 windows_version,
364 drop_target_helper,
365 validation_number,
366 main_receiver,
367 main_thread_id_win32,
368 } = creation_info;
369 let classname = register_wnd_class(icon);
370 let hide_title_bar = params
371 .titlebar
372 .as_ref()
373 .map(|titlebar| titlebar.appears_transparent)
374 .unwrap_or(true);
375 let windowname = HSTRING::from(
376 params
377 .titlebar
378 .as_ref()
379 .and_then(|titlebar| titlebar.title.as_ref())
380 .map(|title| title.as_ref())
381 .unwrap_or(""),
382 );
383 let (dwexstyle, mut dwstyle) = if params.kind == WindowKind::PopUp {
384 (WS_EX_TOOLWINDOW | WS_EX_LAYERED, WINDOW_STYLE(0x0))
385 } else {
386 (
387 // WS_EX_APPWINDOW | WS_EX_LAYERED,
388 WS_EX_APPWINDOW,
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: true,
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 // todo(zjk)
712 // window_state
713 // .renderer
714 // .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
715
716 // match background_appearance {
717 // WindowBackgroundAppearance::Opaque => {
718 // // ACCENT_DISABLED
719 // set_window_composition_attribute(window_state.hwnd, None, 0);
720 // }
721 // WindowBackgroundAppearance::Transparent => {
722 // // Use ACCENT_ENABLE_TRANSPARENTGRADIENT for transparent background
723 // set_window_composition_attribute(window_state.hwnd, None, 2);
724 // }
725 // WindowBackgroundAppearance::Blurred => {
726 // // Enable acrylic blur
727 // // ACCENT_ENABLE_ACRYLICBLURBEHIND
728 // set_window_composition_attribute(window_state.hwnd, Some((0, 0, 0, 0)), 4);
729 // }
730 // }
731 }
732
733 fn minimize(&self) {
734 unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
735 }
736
737 fn zoom(&self) {
738 unsafe {
739 if IsWindowVisible(self.0.hwnd).as_bool() {
740 ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
741 } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
742 status.state = WindowOpenState::Maximized;
743 }
744 }
745 }
746
747 fn toggle_fullscreen(&self) {
748 if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
749 self.0.toggle_fullscreen();
750 } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
751 status.state = WindowOpenState::Fullscreen;
752 }
753 }
754
755 fn is_fullscreen(&self) -> bool {
756 self.0.state.borrow().is_fullscreen()
757 }
758
759 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
760 self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
761 }
762
763 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
764 self.0.state.borrow_mut().callbacks.input = Some(callback);
765 }
766
767 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
768 self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
769 }
770
771 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
772 self.0.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
773 }
774
775 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
776 self.0.state.borrow_mut().callbacks.resize = Some(callback);
777 }
778
779 fn on_moved(&self, callback: Box<dyn FnMut()>) {
780 self.0.state.borrow_mut().callbacks.moved = Some(callback);
781 }
782
783 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
784 self.0.state.borrow_mut().callbacks.should_close = Some(callback);
785 }
786
787 fn on_close(&self, callback: Box<dyn FnOnce()>) {
788 self.0.state.borrow_mut().callbacks.close = Some(callback);
789 }
790
791 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
792 self.0.state.borrow_mut().callbacks.hit_test_window_control = Some(callback);
793 }
794
795 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
796 self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
797 }
798
799 fn draw(&self, scene: &Scene) {
800 self.0.state.borrow_mut().renderer.draw(scene).log_err();
801 }
802
803 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
804 self.0.state.borrow().renderer.sprite_atlas()
805 }
806
807 fn get_raw_handle(&self) -> HWND {
808 self.0.hwnd
809 }
810
811 fn gpu_specs(&self) -> Option<GpuSpecs> {
812 // todo(zjk)
813 // Some(self.0.state.borrow().renderer.gpu_specs())
814 None
815 }
816
817 fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>) {
818 // todo(windows)
819 }
820}
821
822#[implement(IDropTarget)]
823struct WindowsDragDropHandler(pub Rc<WindowsWindowStatePtr>);
824
825impl WindowsDragDropHandler {
826 fn handle_drag_drop(&self, input: PlatformInput) {
827 let mut lock = self.0.state.borrow_mut();
828 if let Some(mut func) = lock.callbacks.input.take() {
829 drop(lock);
830 func(input);
831 self.0.state.borrow_mut().callbacks.input = Some(func);
832 }
833 }
834}
835
836#[allow(non_snake_case)]
837impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
838 fn DragEnter(
839 &self,
840 pdataobj: windows::core::Ref<IDataObject>,
841 _grfkeystate: MODIFIERKEYS_FLAGS,
842 pt: &POINTL,
843 pdweffect: *mut DROPEFFECT,
844 ) -> windows::core::Result<()> {
845 unsafe {
846 let idata_obj = pdataobj.ok()?;
847 let config = FORMATETC {
848 cfFormat: CF_HDROP.0,
849 ptd: std::ptr::null_mut() as _,
850 dwAspect: DVASPECT_CONTENT.0,
851 lindex: -1,
852 tymed: TYMED_HGLOBAL.0 as _,
853 };
854 let cursor_position = POINT { x: pt.x, y: pt.y };
855 if idata_obj.QueryGetData(&config as _) == S_OK {
856 *pdweffect = DROPEFFECT_COPY;
857 let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
858 return Ok(());
859 };
860 if idata.u.hGlobal.is_invalid() {
861 return Ok(());
862 }
863 let hdrop = idata.u.hGlobal.0 as *mut HDROP;
864 let mut paths = SmallVec::<[PathBuf; 2]>::new();
865 with_file_names(*hdrop, |file_name| {
866 if let Some(path) = PathBuf::from_str(&file_name).log_err() {
867 paths.push(path);
868 }
869 });
870 ReleaseStgMedium(&mut idata);
871 let mut cursor_position = cursor_position;
872 ScreenToClient(self.0.hwnd, &mut cursor_position)
873 .ok()
874 .log_err();
875 let scale_factor = self.0.state.borrow().scale_factor;
876 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
877 position: logical_point(
878 cursor_position.x as f32,
879 cursor_position.y as f32,
880 scale_factor,
881 ),
882 paths: ExternalPaths(paths),
883 });
884 self.handle_drag_drop(input);
885 } else {
886 *pdweffect = DROPEFFECT_NONE;
887 }
888 self.0
889 .drop_target_helper
890 .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)
891 .log_err();
892 }
893 Ok(())
894 }
895
896 fn DragOver(
897 &self,
898 _grfkeystate: MODIFIERKEYS_FLAGS,
899 pt: &POINTL,
900 pdweffect: *mut DROPEFFECT,
901 ) -> windows::core::Result<()> {
902 let mut cursor_position = POINT { x: pt.x, y: pt.y };
903 unsafe {
904 *pdweffect = DROPEFFECT_COPY;
905 self.0
906 .drop_target_helper
907 .DragOver(&cursor_position, *pdweffect)
908 .log_err();
909 ScreenToClient(self.0.hwnd, &mut cursor_position)
910 .ok()
911 .log_err();
912 }
913 let scale_factor = self.0.state.borrow().scale_factor;
914 let input = PlatformInput::FileDrop(FileDropEvent::Pending {
915 position: logical_point(
916 cursor_position.x as f32,
917 cursor_position.y as f32,
918 scale_factor,
919 ),
920 });
921 self.handle_drag_drop(input);
922
923 Ok(())
924 }
925
926 fn DragLeave(&self) -> windows::core::Result<()> {
927 unsafe {
928 self.0.drop_target_helper.DragLeave().log_err();
929 }
930 let input = PlatformInput::FileDrop(FileDropEvent::Exited);
931 self.handle_drag_drop(input);
932
933 Ok(())
934 }
935
936 fn Drop(
937 &self,
938 pdataobj: windows::core::Ref<IDataObject>,
939 _grfkeystate: MODIFIERKEYS_FLAGS,
940 pt: &POINTL,
941 pdweffect: *mut DROPEFFECT,
942 ) -> windows::core::Result<()> {
943 let idata_obj = pdataobj.ok()?;
944 let mut cursor_position = POINT { x: pt.x, y: pt.y };
945 unsafe {
946 *pdweffect = DROPEFFECT_COPY;
947 self.0
948 .drop_target_helper
949 .Drop(idata_obj, &cursor_position, *pdweffect)
950 .log_err();
951 ScreenToClient(self.0.hwnd, &mut cursor_position)
952 .ok()
953 .log_err();
954 }
955 let scale_factor = self.0.state.borrow().scale_factor;
956 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
957 position: logical_point(
958 cursor_position.x as f32,
959 cursor_position.y as f32,
960 scale_factor,
961 ),
962 });
963 self.handle_drag_drop(input);
964
965 Ok(())
966 }
967}
968
969#[derive(Debug, Clone, Copy)]
970pub(crate) struct ClickState {
971 button: MouseButton,
972 last_click: Instant,
973 last_position: Point<DevicePixels>,
974 double_click_spatial_tolerance_width: i32,
975 double_click_spatial_tolerance_height: i32,
976 double_click_interval: Duration,
977 pub(crate) current_count: usize,
978}
979
980impl ClickState {
981 pub fn new() -> Self {
982 let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
983 let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
984 let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
985
986 ClickState {
987 button: MouseButton::Left,
988 last_click: Instant::now(),
989 last_position: Point::default(),
990 double_click_spatial_tolerance_width,
991 double_click_spatial_tolerance_height,
992 double_click_interval,
993 current_count: 0,
994 }
995 }
996
997 /// update self and return the needed click count
998 pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
999 if self.button == button && self.is_double_click(new_position) {
1000 self.current_count += 1;
1001 } else {
1002 self.current_count = 1;
1003 }
1004 self.last_click = Instant::now();
1005 self.last_position = new_position;
1006 self.button = button;
1007
1008 self.current_count
1009 }
1010
1011 pub fn system_update(&mut self, wparam: usize) {
1012 match wparam {
1013 // SPI_SETDOUBLECLKWIDTH
1014 29 => {
1015 self.double_click_spatial_tolerance_width =
1016 unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }
1017 }
1018 // SPI_SETDOUBLECLKHEIGHT
1019 30 => {
1020 self.double_click_spatial_tolerance_height =
1021 unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }
1022 }
1023 // SPI_SETDOUBLECLICKTIME
1024 32 => {
1025 self.double_click_interval =
1026 Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)
1027 }
1028 _ => {}
1029 }
1030 }
1031
1032 #[inline]
1033 fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
1034 let diff = self.last_position - new_position;
1035
1036 self.last_click.elapsed() < self.double_click_interval
1037 && diff.x.0.abs() <= self.double_click_spatial_tolerance_width
1038 && diff.y.0.abs() <= self.double_click_spatial_tolerance_height
1039 }
1040}
1041
1042struct StyleAndBounds {
1043 style: WINDOW_STYLE,
1044 x: i32,
1045 y: i32,
1046 cx: i32,
1047 cy: i32,
1048}
1049
1050#[repr(C)]
1051struct WINDOWCOMPOSITIONATTRIBDATA {
1052 attrib: u32,
1053 pv_data: *mut std::ffi::c_void,
1054 cb_data: usize,
1055}
1056
1057#[repr(C)]
1058struct AccentPolicy {
1059 accent_state: u32,
1060 accent_flags: u32,
1061 gradient_color: u32,
1062 animation_id: u32,
1063}
1064
1065type Color = (u8, u8, u8, u8);
1066
1067#[derive(Debug, Default, Clone, Copy)]
1068pub(crate) struct WindowBorderOffset {
1069 pub(crate) width_offset: i32,
1070 pub(crate) height_offset: i32,
1071}
1072
1073impl WindowBorderOffset {
1074 pub(crate) fn update(&mut self, hwnd: HWND) -> anyhow::Result<()> {
1075 let window_rect = unsafe {
1076 let mut rect = std::mem::zeroed();
1077 GetWindowRect(hwnd, &mut rect)?;
1078 rect
1079 };
1080 let client_rect = unsafe {
1081 let mut rect = std::mem::zeroed();
1082 GetClientRect(hwnd, &mut rect)?;
1083 rect
1084 };
1085 self.width_offset =
1086 (window_rect.right - window_rect.left) - (client_rect.right - client_rect.left);
1087 self.height_offset =
1088 (window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top);
1089 Ok(())
1090 }
1091}
1092
1093struct WindowOpenStatus {
1094 placement: WINDOWPLACEMENT,
1095 state: WindowOpenState,
1096}
1097
1098enum WindowOpenState {
1099 Maximized,
1100 Fullscreen,
1101 Windowed,
1102}
1103
1104fn register_wnd_class(icon_handle: HICON) -> PCWSTR {
1105 const CLASS_NAME: PCWSTR = w!("Zed::Window");
1106
1107 static ONCE: Once = Once::new();
1108 ONCE.call_once(|| {
1109 let wc = WNDCLASSW {
1110 lpfnWndProc: Some(wnd_proc),
1111 hIcon: icon_handle,
1112 lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
1113 style: CS_HREDRAW | CS_VREDRAW,
1114 hInstance: get_module_handle().into(),
1115 hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1116 ..Default::default()
1117 };
1118 unsafe { RegisterClassW(&wc) };
1119 });
1120
1121 CLASS_NAME
1122}
1123
1124unsafe extern "system" fn wnd_proc(
1125 hwnd: HWND,
1126 msg: u32,
1127 wparam: WPARAM,
1128 lparam: LPARAM,
1129) -> LRESULT {
1130 if msg == WM_NCCREATE {
1131 let cs = lparam.0 as *const CREATESTRUCTW;
1132 let cs = unsafe { &*cs };
1133 let ctx = cs.lpCreateParams as *mut WindowCreateContext;
1134 let ctx = unsafe { &mut *ctx };
1135 let creation_result = WindowsWindowStatePtr::new(ctx, hwnd, cs);
1136 if creation_result.is_err() {
1137 ctx.inner = Some(creation_result);
1138 return LRESULT(0);
1139 }
1140 let weak = Box::new(Rc::downgrade(creation_result.as_ref().unwrap()));
1141 unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1142 ctx.inner = Some(creation_result);
1143 return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1144 }
1145 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
1146 if ptr.is_null() {
1147 return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1148 }
1149 let inner = unsafe { &*ptr };
1150 let r = if let Some(state) = inner.upgrade() {
1151 handle_msg(hwnd, msg, wparam, lparam, state)
1152 } else {
1153 unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1154 };
1155 if msg == WM_NCDESTROY {
1156 unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1157 unsafe { drop(Box::from_raw(ptr)) };
1158 }
1159 r
1160}
1161
1162pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
1163 if hwnd.is_invalid() {
1164 return None;
1165 }
1166
1167 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
1168 if !ptr.is_null() {
1169 let inner = unsafe { &*ptr };
1170 inner.upgrade()
1171 } else {
1172 None
1173 }
1174}
1175
1176fn get_module_handle() -> HMODULE {
1177 unsafe {
1178 let mut h_module = std::mem::zeroed();
1179 GetModuleHandleExW(
1180 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1181 windows::core::w!("ZedModule"),
1182 &mut h_module,
1183 )
1184 .expect("Unable to get module handle"); // this should never fail
1185
1186 h_module
1187 }
1188}
1189
1190fn register_drag_drop(state_ptr: Rc<WindowsWindowStatePtr>) -> Result<()> {
1191 let window_handle = state_ptr.hwnd;
1192 let handler = WindowsDragDropHandler(state_ptr);
1193 // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1194 // we call `RevokeDragDrop`.
1195 // So, it's safe to drop it here.
1196 let drag_drop_handler: IDropTarget = handler.into();
1197 unsafe {
1198 RegisterDragDrop(window_handle, &drag_drop_handler)
1199 .context("unable to register drag-drop event")?;
1200 }
1201 Ok(())
1202}
1203
1204fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: WindowBorderOffset) -> RECT {
1205 // NOTE:
1206 // The reason we're not using `AdjustWindowRectEx()` here is
1207 // that the size reported by this function is incorrect.
1208 // You can test it, and there are similar discussions online.
1209 // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1210 //
1211 // So we manually calculate these values here.
1212 let mut rect = RECT {
1213 left: bounds.left().0,
1214 top: bounds.top().0,
1215 right: bounds.right().0,
1216 bottom: bounds.bottom().0,
1217 };
1218 let left_offset = border_offset.width_offset / 2;
1219 let top_offset = border_offset.height_offset / 2;
1220 let right_offset = border_offset.width_offset - left_offset;
1221 let bottom_offset = border_offset.height_offset - top_offset;
1222 rect.left -= left_offset;
1223 rect.top -= top_offset;
1224 rect.right += right_offset;
1225 rect.bottom += bottom_offset;
1226 rect
1227}
1228
1229fn calculate_client_rect(
1230 rect: RECT,
1231 border_offset: WindowBorderOffset,
1232 scale_factor: f32,
1233) -> Bounds<Pixels> {
1234 let left_offset = border_offset.width_offset / 2;
1235 let top_offset = border_offset.height_offset / 2;
1236 let right_offset = border_offset.width_offset - left_offset;
1237 let bottom_offset = border_offset.height_offset - top_offset;
1238 let left = rect.left + left_offset;
1239 let top = rect.top + top_offset;
1240 let right = rect.right - right_offset;
1241 let bottom = rect.bottom - bottom_offset;
1242 let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1243 Bounds {
1244 origin: logical_point(left as f32, top as f32, scale_factor),
1245 size: physical_size.to_pixels(scale_factor),
1246 }
1247}
1248
1249fn retrieve_window_placement(
1250 hwnd: HWND,
1251 display: WindowsDisplay,
1252 initial_bounds: Bounds<Pixels>,
1253 scale_factor: f32,
1254 border_offset: WindowBorderOffset,
1255) -> Result<WINDOWPLACEMENT> {
1256 let mut placement = WINDOWPLACEMENT {
1257 length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1258 ..Default::default()
1259 };
1260 unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1261 // the bounds may be not inside the display
1262 let bounds = if display.check_given_bounds(initial_bounds) {
1263 initial_bounds
1264 } else {
1265 display.default_bounds()
1266 };
1267 let bounds = bounds.to_device_pixels(scale_factor);
1268 placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1269 Ok(placement)
1270}
1271
1272fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1273 let mut version = unsafe { std::mem::zeroed() };
1274 let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1275 if !status.is_ok() || version.dwBuildNumber < 17763 {
1276 return;
1277 }
1278
1279 unsafe {
1280 type SetWindowCompositionAttributeType =
1281 unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1282 let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1283 if let Some(user32) = GetModuleHandleA(module_name)
1284 .context("Unable to get user32.dll handle")
1285 .log_err()
1286 {
1287 let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1288 let set_window_composition_attribute: SetWindowCompositionAttributeType =
1289 std::mem::transmute(GetProcAddress(user32, func_name));
1290 let mut color = color.unwrap_or_default();
1291 let is_acrylic = state == 4;
1292 if is_acrylic && color.3 == 0 {
1293 color.3 = 1;
1294 }
1295 let accent = AccentPolicy {
1296 accent_state: state,
1297 accent_flags: if is_acrylic { 0 } else { 2 },
1298 gradient_color: (color.0 as u32)
1299 | ((color.1 as u32) << 8)
1300 | ((color.2 as u32) << 16)
1301 | ((color.3 as u32) << 24),
1302 animation_id: 0,
1303 };
1304 let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1305 attrib: 0x13,
1306 pv_data: &accent as *const _ as *mut _,
1307 cb_data: std::mem::size_of::<AccentPolicy>(),
1308 };
1309 let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1310 }
1311 }
1312}
1313
1314mod windows_renderer {
1315 use crate::platform::blade::{BladeContext, BladeRenderer, BladeSurfaceConfig};
1316 use raw_window_handle as rwh;
1317 use std::num::NonZeroIsize;
1318 use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::GWLP_HINSTANCE};
1319
1320 use crate::{get_window_long, show_error};
1321
1322 pub(super) fn init(
1323 context: &BladeContext,
1324 hwnd: HWND,
1325 transparent: bool,
1326 ) -> anyhow::Result<BladeRenderer> {
1327 let raw = RawWindow { hwnd };
1328 let config = BladeSurfaceConfig {
1329 size: Default::default(),
1330 transparent,
1331 };
1332 BladeRenderer::new(context, &raw, config)
1333 .inspect_err(|err| show_error("Failed to initialize BladeRenderer", err.to_string()))
1334 }
1335
1336 struct RawWindow {
1337 hwnd: HWND,
1338 }
1339
1340 impl rwh::HasWindowHandle for RawWindow {
1341 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1342 Ok(unsafe {
1343 let hwnd = NonZeroIsize::new_unchecked(self.hwnd.0 as isize);
1344 let mut handle = rwh::Win32WindowHandle::new(hwnd);
1345 let hinstance = get_window_long(self.hwnd, GWLP_HINSTANCE);
1346 handle.hinstance = NonZeroIsize::new(hinstance);
1347 rwh::WindowHandle::borrow_raw(handle.into())
1348 })
1349 }
1350 }
1351
1352 impl rwh::HasDisplayHandle for RawWindow {
1353 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1354 let handle = rwh::WindowsDisplayHandle::new();
1355 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
1356 }
1357 }
1358}
1359
1360#[cfg(test)]
1361mod tests {
1362 use super::ClickState;
1363 use crate::{DevicePixels, MouseButton, point};
1364 use std::time::Duration;
1365
1366 #[test]
1367 fn test_double_click_interval() {
1368 let mut state = ClickState::new();
1369 assert_eq!(
1370 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1371 1
1372 );
1373 assert_eq!(
1374 state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1375 1
1376 );
1377 assert_eq!(
1378 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1379 1
1380 );
1381 assert_eq!(
1382 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1383 2
1384 );
1385 state.last_click -= Duration::from_millis(700);
1386 assert_eq!(
1387 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1388 1
1389 );
1390 }
1391
1392 #[test]
1393 fn test_double_click_spatial_tolerance() {
1394 let mut state = ClickState::new();
1395 assert_eq!(
1396 state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1397 1
1398 );
1399 assert_eq!(
1400 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1401 2
1402 );
1403 assert_eq!(
1404 state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1405 1
1406 );
1407 assert_eq!(
1408 state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1409 1
1410 );
1411 }
1412}