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