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