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