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