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