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