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