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