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