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 unsafe { SetActiveWindow(hwnd).log_err() };
688 unsafe { SetFocus(Some(hwnd)).log_err() };
689
690 // premium ragebait by windows, this is needed because the window
691 // must have received an input event to be able to set itself to foreground
692 // so let's just simulate user input as that seems to be the most reliable way
693 // some more info: https://gist.github.com/Aetopia/1581b40f00cc0cadc93a0e8ccb65dc8c
694 // bonus: this bug also doesn't manifest if you have vs attached to the process
695 let inputs = [
696 INPUT {
697 r#type: INPUT_KEYBOARD,
698 Anonymous: INPUT_0 {
699 ki: KEYBDINPUT {
700 wVk: VK_MENU,
701 dwFlags: KEYBD_EVENT_FLAGS(0),
702 ..Default::default()
703 },
704 },
705 },
706 INPUT {
707 r#type: INPUT_KEYBOARD,
708 Anonymous: INPUT_0 {
709 ki: KEYBDINPUT {
710 wVk: VK_MENU,
711 dwFlags: KEYEVENTF_KEYUP,
712 ..Default::default()
713 },
714 },
715 },
716 ];
717 unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };
718
719 // todo(windows)
720 // crate `windows 0.56` reports true as Err
721 unsafe { SetForegroundWindow(hwnd).as_bool() };
722 })
723 .detach();
724 }
725
726 fn is_active(&self) -> bool {
727 self.0.hwnd == unsafe { GetActiveWindow() }
728 }
729
730 fn is_hovered(&self) -> bool {
731 self.0.state.borrow().hovered
732 }
733
734 fn set_title(&mut self, title: &str) {
735 unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
736 .inspect_err(|e| log::error!("Set title failed: {e}"))
737 .ok();
738 }
739
740 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
741 let hwnd = self.0.hwnd;
742
743 match background_appearance {
744 WindowBackgroundAppearance::Opaque => {
745 // ACCENT_DISABLED
746 set_window_composition_attribute(hwnd, None, 0);
747 }
748 WindowBackgroundAppearance::Transparent => {
749 // Use ACCENT_ENABLE_TRANSPARENTGRADIENT for transparent background
750 set_window_composition_attribute(hwnd, None, 2);
751 }
752 WindowBackgroundAppearance::Blurred => {
753 // Enable acrylic blur
754 // ACCENT_ENABLE_ACRYLICBLURBEHIND
755 set_window_composition_attribute(hwnd, Some((0, 0, 0, 0)), 4);
756 }
757 }
758 }
759
760 fn minimize(&self) {
761 unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
762 }
763
764 fn zoom(&self) {
765 unsafe {
766 if IsWindowVisible(self.0.hwnd).as_bool() {
767 ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
768 } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
769 status.state = WindowOpenState::Maximized;
770 }
771 }
772 }
773
774 fn toggle_fullscreen(&self) {
775 if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
776 self.0.toggle_fullscreen();
777 } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
778 status.state = WindowOpenState::Fullscreen;
779 }
780 }
781
782 fn is_fullscreen(&self) -> bool {
783 self.0.state.borrow().is_fullscreen()
784 }
785
786 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
787 self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
788 }
789
790 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
791 self.0.state.borrow_mut().callbacks.input = Some(callback);
792 }
793
794 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
795 self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
796 }
797
798 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
799 self.0.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
800 }
801
802 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
803 self.0.state.borrow_mut().callbacks.resize = Some(callback);
804 }
805
806 fn on_moved(&self, callback: Box<dyn FnMut()>) {
807 self.0.state.borrow_mut().callbacks.moved = Some(callback);
808 }
809
810 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
811 self.0.state.borrow_mut().callbacks.should_close = Some(callback);
812 }
813
814 fn on_close(&self, callback: Box<dyn FnOnce()>) {
815 self.0.state.borrow_mut().callbacks.close = Some(callback);
816 }
817
818 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
819 self.0.state.borrow_mut().callbacks.hit_test_window_control = Some(callback);
820 }
821
822 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
823 self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
824 }
825
826 fn draw(&self, scene: &Scene) {
827 self.0.state.borrow_mut().renderer.draw(scene).log_err();
828 }
829
830 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
831 self.0.state.borrow().renderer.sprite_atlas()
832 }
833
834 fn get_raw_handle(&self) -> HWND {
835 self.0.hwnd
836 }
837
838 fn gpu_specs(&self) -> Option<GpuSpecs> {
839 self.0.state.borrow().renderer.gpu_specs().log_err()
840 }
841
842 fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
843 // There is no such thing on Windows.
844 }
845}
846
847#[implement(IDropTarget)]
848struct WindowsDragDropHandler(pub Rc<WindowsWindowInner>);
849
850impl WindowsDragDropHandler {
851 fn handle_drag_drop(&self, input: PlatformInput) {
852 let mut lock = self.0.state.borrow_mut();
853 if let Some(mut func) = lock.callbacks.input.take() {
854 drop(lock);
855 func(input);
856 self.0.state.borrow_mut().callbacks.input = Some(func);
857 }
858 }
859}
860
861#[allow(non_snake_case)]
862impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
863 fn DragEnter(
864 &self,
865 pdataobj: windows::core::Ref<IDataObject>,
866 _grfkeystate: MODIFIERKEYS_FLAGS,
867 pt: &POINTL,
868 pdweffect: *mut DROPEFFECT,
869 ) -> windows::core::Result<()> {
870 unsafe {
871 let idata_obj = pdataobj.ok()?;
872 let config = FORMATETC {
873 cfFormat: CF_HDROP.0,
874 ptd: std::ptr::null_mut() as _,
875 dwAspect: DVASPECT_CONTENT.0,
876 lindex: -1,
877 tymed: TYMED_HGLOBAL.0 as _,
878 };
879 let cursor_position = POINT { x: pt.x, y: pt.y };
880 if idata_obj.QueryGetData(&config as _) == S_OK {
881 *pdweffect = DROPEFFECT_COPY;
882 let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
883 return Ok(());
884 };
885 if idata.u.hGlobal.is_invalid() {
886 return Ok(());
887 }
888 let hdrop = idata.u.hGlobal.0 as *mut HDROP;
889 let mut paths = SmallVec::<[PathBuf; 2]>::new();
890 with_file_names(*hdrop, |file_name| {
891 if let Some(path) = PathBuf::from_str(&file_name).log_err() {
892 paths.push(path);
893 }
894 });
895 ReleaseStgMedium(&mut idata);
896 let mut cursor_position = cursor_position;
897 ScreenToClient(self.0.hwnd, &mut cursor_position)
898 .ok()
899 .log_err();
900 let scale_factor = self.0.state.borrow().scale_factor;
901 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
902 position: logical_point(
903 cursor_position.x as f32,
904 cursor_position.y as f32,
905 scale_factor,
906 ),
907 paths: ExternalPaths(paths),
908 });
909 self.handle_drag_drop(input);
910 } else {
911 *pdweffect = DROPEFFECT_NONE;
912 }
913 self.0
914 .drop_target_helper
915 .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)
916 .log_err();
917 }
918 Ok(())
919 }
920
921 fn DragOver(
922 &self,
923 _grfkeystate: MODIFIERKEYS_FLAGS,
924 pt: &POINTL,
925 pdweffect: *mut DROPEFFECT,
926 ) -> windows::core::Result<()> {
927 let mut cursor_position = POINT { x: pt.x, y: pt.y };
928 unsafe {
929 *pdweffect = DROPEFFECT_COPY;
930 self.0
931 .drop_target_helper
932 .DragOver(&cursor_position, *pdweffect)
933 .log_err();
934 ScreenToClient(self.0.hwnd, &mut cursor_position)
935 .ok()
936 .log_err();
937 }
938 let scale_factor = self.0.state.borrow().scale_factor;
939 let input = PlatformInput::FileDrop(FileDropEvent::Pending {
940 position: logical_point(
941 cursor_position.x as f32,
942 cursor_position.y as f32,
943 scale_factor,
944 ),
945 });
946 self.handle_drag_drop(input);
947
948 Ok(())
949 }
950
951 fn DragLeave(&self) -> windows::core::Result<()> {
952 unsafe {
953 self.0.drop_target_helper.DragLeave().log_err();
954 }
955 let input = PlatformInput::FileDrop(FileDropEvent::Exited);
956 self.handle_drag_drop(input);
957
958 Ok(())
959 }
960
961 fn Drop(
962 &self,
963 pdataobj: windows::core::Ref<IDataObject>,
964 _grfkeystate: MODIFIERKEYS_FLAGS,
965 pt: &POINTL,
966 pdweffect: *mut DROPEFFECT,
967 ) -> windows::core::Result<()> {
968 let idata_obj = pdataobj.ok()?;
969 let mut cursor_position = POINT { x: pt.x, y: pt.y };
970 unsafe {
971 *pdweffect = DROPEFFECT_COPY;
972 self.0
973 .drop_target_helper
974 .Drop(idata_obj, &cursor_position, *pdweffect)
975 .log_err();
976 ScreenToClient(self.0.hwnd, &mut cursor_position)
977 .ok()
978 .log_err();
979 }
980 let scale_factor = self.0.state.borrow().scale_factor;
981 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
982 position: logical_point(
983 cursor_position.x as f32,
984 cursor_position.y as f32,
985 scale_factor,
986 ),
987 });
988 self.handle_drag_drop(input);
989
990 Ok(())
991 }
992}
993
994#[derive(Debug, Clone, Copy)]
995pub(crate) struct ClickState {
996 button: MouseButton,
997 last_click: Instant,
998 last_position: Point<DevicePixels>,
999 double_click_spatial_tolerance_width: i32,
1000 double_click_spatial_tolerance_height: i32,
1001 double_click_interval: Duration,
1002 pub(crate) current_count: usize,
1003}
1004
1005impl ClickState {
1006 pub fn new() -> Self {
1007 let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
1008 let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
1009 let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
1010
1011 ClickState {
1012 button: MouseButton::Left,
1013 last_click: Instant::now(),
1014 last_position: Point::default(),
1015 double_click_spatial_tolerance_width,
1016 double_click_spatial_tolerance_height,
1017 double_click_interval,
1018 current_count: 0,
1019 }
1020 }
1021
1022 /// update self and return the needed click count
1023 pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
1024 if self.button == button && self.is_double_click(new_position) {
1025 self.current_count += 1;
1026 } else {
1027 self.current_count = 1;
1028 }
1029 self.last_click = Instant::now();
1030 self.last_position = new_position;
1031 self.button = button;
1032
1033 self.current_count
1034 }
1035
1036 pub fn system_update(&mut self, wparam: usize) {
1037 match wparam {
1038 // SPI_SETDOUBLECLKWIDTH
1039 29 => {
1040 self.double_click_spatial_tolerance_width =
1041 unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }
1042 }
1043 // SPI_SETDOUBLECLKHEIGHT
1044 30 => {
1045 self.double_click_spatial_tolerance_height =
1046 unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }
1047 }
1048 // SPI_SETDOUBLECLICKTIME
1049 32 => {
1050 self.double_click_interval =
1051 Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)
1052 }
1053 _ => {}
1054 }
1055 }
1056
1057 #[inline]
1058 fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
1059 let diff = self.last_position - new_position;
1060
1061 self.last_click.elapsed() < self.double_click_interval
1062 && diff.x.0.abs() <= self.double_click_spatial_tolerance_width
1063 && diff.y.0.abs() <= self.double_click_spatial_tolerance_height
1064 }
1065}
1066
1067struct StyleAndBounds {
1068 style: WINDOW_STYLE,
1069 x: i32,
1070 y: i32,
1071 cx: i32,
1072 cy: i32,
1073}
1074
1075#[repr(C)]
1076struct WINDOWCOMPOSITIONATTRIBDATA {
1077 attrib: u32,
1078 pv_data: *mut std::ffi::c_void,
1079 cb_data: usize,
1080}
1081
1082#[repr(C)]
1083struct AccentPolicy {
1084 accent_state: u32,
1085 accent_flags: u32,
1086 gradient_color: u32,
1087 animation_id: u32,
1088}
1089
1090type Color = (u8, u8, u8, u8);
1091
1092#[derive(Debug, Default, Clone, Copy)]
1093pub(crate) struct WindowBorderOffset {
1094 pub(crate) width_offset: i32,
1095 pub(crate) height_offset: i32,
1096}
1097
1098impl WindowBorderOffset {
1099 pub(crate) fn update(&mut self, hwnd: HWND) -> anyhow::Result<()> {
1100 let window_rect = unsafe {
1101 let mut rect = std::mem::zeroed();
1102 GetWindowRect(hwnd, &mut rect)?;
1103 rect
1104 };
1105 let client_rect = unsafe {
1106 let mut rect = std::mem::zeroed();
1107 GetClientRect(hwnd, &mut rect)?;
1108 rect
1109 };
1110 self.width_offset =
1111 (window_rect.right - window_rect.left) - (client_rect.right - client_rect.left);
1112 self.height_offset =
1113 (window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top);
1114 Ok(())
1115 }
1116}
1117
1118struct WindowOpenStatus {
1119 placement: WINDOWPLACEMENT,
1120 state: WindowOpenState,
1121}
1122
1123enum WindowOpenState {
1124 Maximized,
1125 Fullscreen,
1126 Windowed,
1127}
1128
1129const WINDOW_CLASS_NAME: PCWSTR = w!("Zed::Window");
1130
1131fn register_window_class(icon_handle: HICON) {
1132 static ONCE: Once = Once::new();
1133 ONCE.call_once(|| {
1134 let wc = WNDCLASSW {
1135 lpfnWndProc: Some(window_procedure),
1136 hIcon: icon_handle,
1137 lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
1138 style: CS_HREDRAW | CS_VREDRAW,
1139 hInstance: get_module_handle().into(),
1140 hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1141 ..Default::default()
1142 };
1143 unsafe { RegisterClassW(&wc) };
1144 });
1145}
1146
1147unsafe extern "system" fn window_procedure(
1148 hwnd: HWND,
1149 msg: u32,
1150 wparam: WPARAM,
1151 lparam: LPARAM,
1152) -> LRESULT {
1153 if msg == WM_NCCREATE {
1154 let window_params = lparam.0 as *const CREATESTRUCTW;
1155 let window_params = unsafe { &*window_params };
1156 let window_creation_context = window_params.lpCreateParams as *mut WindowCreateContext;
1157 let window_creation_context = unsafe { &mut *window_creation_context };
1158 return match WindowsWindowInner::new(window_creation_context, hwnd, window_params) {
1159 Ok(window_state) => {
1160 let weak = Box::new(Rc::downgrade(&window_state));
1161 unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1162 window_creation_context.inner = Some(Ok(window_state));
1163 unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1164 }
1165 Err(error) => {
1166 window_creation_context.inner = Some(Err(error));
1167 LRESULT(0)
1168 }
1169 };
1170 }
1171
1172 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1173 if ptr.is_null() {
1174 return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1175 }
1176 let inner = unsafe { &*ptr };
1177 let result = if let Some(inner) = inner.upgrade() {
1178 inner.handle_msg(hwnd, msg, wparam, lparam)
1179 } else {
1180 unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1181 };
1182
1183 if msg == WM_NCDESTROY {
1184 unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1185 unsafe { drop(Box::from_raw(ptr)) };
1186 }
1187
1188 result
1189}
1190
1191pub(crate) fn window_from_hwnd(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
1192 if hwnd.is_invalid() {
1193 return None;
1194 }
1195
1196 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1197 if !ptr.is_null() {
1198 let inner = unsafe { &*ptr };
1199 inner.upgrade()
1200 } else {
1201 None
1202 }
1203}
1204
1205fn get_module_handle() -> HMODULE {
1206 unsafe {
1207 let mut h_module = std::mem::zeroed();
1208 GetModuleHandleExW(
1209 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1210 windows::core::w!("ZedModule"),
1211 &mut h_module,
1212 )
1213 .expect("Unable to get module handle"); // this should never fail
1214
1215 h_module
1216 }
1217}
1218
1219fn register_drag_drop(window: &Rc<WindowsWindowInner>) -> Result<()> {
1220 let window_handle = window.hwnd;
1221 let handler = WindowsDragDropHandler(window.clone());
1222 // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1223 // we call `RevokeDragDrop`.
1224 // So, it's safe to drop it here.
1225 let drag_drop_handler: IDropTarget = handler.into();
1226 unsafe {
1227 RegisterDragDrop(window_handle, &drag_drop_handler)
1228 .context("unable to register drag-drop event")?;
1229 }
1230 Ok(())
1231}
1232
1233fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: WindowBorderOffset) -> RECT {
1234 // NOTE:
1235 // The reason we're not using `AdjustWindowRectEx()` here is
1236 // that the size reported by this function is incorrect.
1237 // You can test it, and there are similar discussions online.
1238 // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1239 //
1240 // So we manually calculate these values here.
1241 let mut rect = RECT {
1242 left: bounds.left().0,
1243 top: bounds.top().0,
1244 right: bounds.right().0,
1245 bottom: bounds.bottom().0,
1246 };
1247 let left_offset = border_offset.width_offset / 2;
1248 let top_offset = border_offset.height_offset / 2;
1249 let right_offset = border_offset.width_offset - left_offset;
1250 let bottom_offset = border_offset.height_offset - top_offset;
1251 rect.left -= left_offset;
1252 rect.top -= top_offset;
1253 rect.right += right_offset;
1254 rect.bottom += bottom_offset;
1255 rect
1256}
1257
1258fn calculate_client_rect(
1259 rect: RECT,
1260 border_offset: WindowBorderOffset,
1261 scale_factor: f32,
1262) -> Bounds<Pixels> {
1263 let left_offset = border_offset.width_offset / 2;
1264 let top_offset = border_offset.height_offset / 2;
1265 let right_offset = border_offset.width_offset - left_offset;
1266 let bottom_offset = border_offset.height_offset - top_offset;
1267 let left = rect.left + left_offset;
1268 let top = rect.top + top_offset;
1269 let right = rect.right - right_offset;
1270 let bottom = rect.bottom - bottom_offset;
1271 let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1272 Bounds {
1273 origin: logical_point(left as f32, top as f32, scale_factor),
1274 size: physical_size.to_pixels(scale_factor),
1275 }
1276}
1277
1278fn retrieve_window_placement(
1279 hwnd: HWND,
1280 display: WindowsDisplay,
1281 initial_bounds: Bounds<Pixels>,
1282 scale_factor: f32,
1283 border_offset: WindowBorderOffset,
1284) -> Result<WINDOWPLACEMENT> {
1285 let mut placement = WINDOWPLACEMENT {
1286 length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1287 ..Default::default()
1288 };
1289 unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1290 // the bounds may be not inside the display
1291 let bounds = if display.check_given_bounds(initial_bounds) {
1292 initial_bounds
1293 } else {
1294 display.default_bounds()
1295 };
1296 let bounds = bounds.to_device_pixels(scale_factor);
1297 placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1298 Ok(placement)
1299}
1300
1301fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1302 let mut version = unsafe { std::mem::zeroed() };
1303 let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1304 if !status.is_ok() || version.dwBuildNumber < 17763 {
1305 return;
1306 }
1307
1308 unsafe {
1309 type SetWindowCompositionAttributeType =
1310 unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1311 let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1312 if let Some(user32) = GetModuleHandleA(module_name)
1313 .context("Unable to get user32.dll handle")
1314 .log_err()
1315 {
1316 let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1317 let set_window_composition_attribute: SetWindowCompositionAttributeType =
1318 std::mem::transmute(GetProcAddress(user32, func_name));
1319 let mut color = color.unwrap_or_default();
1320 let is_acrylic = state == 4;
1321 if is_acrylic && color.3 == 0 {
1322 color.3 = 1;
1323 }
1324 let accent = AccentPolicy {
1325 accent_state: state,
1326 accent_flags: if is_acrylic { 0 } else { 2 },
1327 gradient_color: (color.0 as u32)
1328 | ((color.1 as u32) << 8)
1329 | ((color.2 as u32) << 16)
1330 | ((color.3 as u32) << 24),
1331 animation_id: 0,
1332 };
1333 let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1334 attrib: 0x13,
1335 pv_data: &accent as *const _ as *mut _,
1336 cb_data: std::mem::size_of::<AccentPolicy>(),
1337 };
1338 let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1339 }
1340 }
1341}
1342
1343#[cfg(test)]
1344mod tests {
1345 use super::ClickState;
1346 use crate::{DevicePixels, MouseButton, point};
1347 use std::time::Duration;
1348
1349 #[test]
1350 fn test_double_click_interval() {
1351 let mut state = ClickState::new();
1352 assert_eq!(
1353 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1354 1
1355 );
1356 assert_eq!(
1357 state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1358 1
1359 );
1360 assert_eq!(
1361 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1362 1
1363 );
1364 assert_eq!(
1365 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1366 2
1367 );
1368 state.last_click -= Duration::from_millis(700);
1369 assert_eq!(
1370 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1371 1
1372 );
1373 }
1374
1375 #[test]
1376 fn test_double_click_spatial_tolerance() {
1377 let mut state = ClickState::new();
1378 assert_eq!(
1379 state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1380 1
1381 );
1382 assert_eq!(
1383 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1384 2
1385 );
1386 assert_eq!(
1387 state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1388 1
1389 );
1390 assert_eq!(
1391 state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1392 1
1393 );
1394 }
1395}