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