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