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