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::*;
30use gpui::*;
31
32pub(crate) struct WindowsWindow(pub Rc<WindowsWindowInner>);
33
34impl std::ops::Deref for WindowsWindow {
35 type Target = WindowsWindowInner;
36
37 fn deref(&self) -> &Self::Target {
38 &self.0
39 }
40}
41
42pub struct WindowsWindowState {
43 pub origin: Cell<Point<Pixels>>,
44 pub logical_size: Cell<Size<Pixels>>,
45 pub min_size: Option<Size<Pixels>>,
46 pub fullscreen_restore_bounds: Cell<Bounds<Pixels>>,
47 pub border_offset: WindowBorderOffset,
48 pub appearance: Cell<WindowAppearance>,
49 pub background_appearance: Cell<WindowBackgroundAppearance>,
50 pub scale_factor: Cell<f32>,
51 pub restore_from_minimized: Cell<Option<Box<dyn FnMut(RequestFrameOptions)>>>,
52
53 pub callbacks: Callbacks,
54 pub input_handler: Cell<Option<PlatformInputHandler>>,
55 pub pending_surrogate: Cell<Option<u16>>,
56 pub last_reported_modifiers: Cell<Option<Modifiers>>,
57 pub last_reported_capslock: Cell<Option<Capslock>>,
58 pub hovered: Cell<bool>,
59
60 pub renderer: RefCell<DirectXRenderer>,
61
62 pub click_state: ClickState,
63 pub current_cursor: Cell<Option<HCURSOR>>,
64 pub nc_button_pressed: Cell<Option<u32>>,
65
66 pub display: Cell<WindowsDisplay>,
67 /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
68 /// as resizing them has failed, causing us to have lost at least the render target.
69 pub invalidate_devices: Arc<AtomicBool>,
70 fullscreen: Cell<Option<StyleAndBounds>>,
71 initial_placement: Cell<Option<WindowOpenStatus>>,
72 hwnd: HWND,
73}
74
75pub(crate) struct WindowsWindowInner {
76 hwnd: HWND,
77 drop_target_helper: IDropTargetHelper,
78 pub(crate) state: WindowsWindowState,
79 system_settings: WindowsSystemSettings,
80 pub(crate) handle: AnyWindowHandle,
81 pub(crate) hide_title_bar: bool,
82 pub(crate) is_movable: bool,
83 pub(crate) executor: ForegroundExecutor,
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 validation_number: context.validation_number,
243 main_receiver: context.main_receiver.clone(),
244 platform_window_handle: context.platform_window_handle,
245 system_settings: WindowsSystemSettings::new(),
246 parent_hwnd: context.parent_hwnd,
247 }))
248 }
249
250 fn toggle_fullscreen(self: &Rc<Self>) {
251 let this = self.clone();
252 self.executor
253 .spawn(async move {
254 let StyleAndBounds {
255 style,
256 x,
257 y,
258 cx,
259 cy,
260 } = match this.state.fullscreen.take() {
261 Some(state) => state,
262 None => {
263 let (window_bounds, _) = this.state.calculate_window_bounds();
264 this.state.fullscreen_restore_bounds.set(window_bounds);
265
266 let style =
267 WINDOW_STYLE(unsafe { get_window_long(this.hwnd, GWL_STYLE) } as _);
268 let mut rc = RECT::default();
269 unsafe { GetWindowRect(this.hwnd, &mut rc) }
270 .context("failed to get window rect")
271 .log_err();
272 let _ = this.state.fullscreen.set(Some(StyleAndBounds {
273 style,
274 x: rc.left,
275 y: rc.top,
276 cx: rc.right - rc.left,
277 cy: rc.bottom - rc.top,
278 }));
279 let style = style
280 & !(WS_THICKFRAME
281 | WS_SYSMENU
282 | WS_MAXIMIZEBOX
283 | WS_MINIMIZEBOX
284 | WS_CAPTION);
285 let physical_bounds = this.state.display.get().physical_bounds();
286 StyleAndBounds {
287 style,
288 x: physical_bounds.left().0,
289 y: physical_bounds.top().0,
290 cx: physical_bounds.size.width.0,
291 cy: physical_bounds.size.height.0,
292 }
293 }
294 };
295 set_non_rude_hwnd(this.hwnd, !this.state.is_fullscreen());
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(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 drop_target_helper: IDropTargetHelper,
367 validation_number: usize,
368 main_receiver: PriorityQueueReceiver<RunnableVariant>,
369 platform_window_handle: HWND,
370 appearance: WindowAppearance,
371 disable_direct_composition: bool,
372 directx_devices: DirectXDevices,
373 invalidate_devices: Arc<AtomicBool>,
374 parent_hwnd: Option<HWND>,
375}
376
377impl WindowsWindow {
378 pub(crate) fn new(
379 handle: AnyWindowHandle,
380 params: WindowParams,
381 creation_info: WindowCreationInfo,
382 ) -> Result<Self> {
383 let WindowCreationInfo {
384 icon,
385 executor,
386 current_cursor,
387 drop_target_helper,
388 validation_number,
389 main_receiver,
390 platform_window_handle,
391 disable_direct_composition,
392 directx_devices,
393 invalidate_devices,
394 } = creation_info;
395 register_window_class(icon);
396 let parent_hwnd = if params.kind == WindowKind::Dialog {
397 let parent_window = unsafe { GetActiveWindow() };
398 if parent_window.is_invalid() {
399 None
400 } else {
401 // Disable the parent window to make this dialog modal
402 unsafe {
403 EnableWindow(parent_window, false).as_bool();
404 };
405 Some(parent_window)
406 }
407 } else {
408 None
409 };
410 let hide_title_bar = params
411 .titlebar
412 .as_ref()
413 .map(|titlebar| titlebar.appears_transparent)
414 .unwrap_or(true);
415 let window_name = HSTRING::from(
416 params
417 .titlebar
418 .as_ref()
419 .and_then(|titlebar| titlebar.title.as_ref())
420 .map(|title| title.as_ref())
421 .unwrap_or(""),
422 );
423
424 let (mut dwexstyle, dwstyle) = if params.kind == WindowKind::PopUp {
425 (WS_EX_TOOLWINDOW, WINDOW_STYLE(0x0))
426 } else {
427 let mut dwstyle = WS_SYSMENU;
428
429 if params.is_resizable {
430 dwstyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
431 }
432
433 if params.is_minimizable {
434 dwstyle |= WS_MINIMIZEBOX;
435 }
436 let dwexstyle = if params.kind == WindowKind::Dialog {
437 dwstyle |= WS_POPUP | WS_CAPTION;
438 WS_EX_DLGMODALFRAME
439 } else {
440 WS_EX_APPWINDOW
441 };
442
443 (dwexstyle, dwstyle)
444 };
445 if !disable_direct_composition {
446 dwexstyle |= WS_EX_NOREDIRECTIONBITMAP;
447 }
448
449 let hinstance = get_module_handle();
450 let display = if let Some(display_id) = params.display_id {
451 // if we obtain a display_id, then this ID must be valid.
452 WindowsDisplay::new(display_id).unwrap()
453 } else {
454 WindowsDisplay::primary_monitor().unwrap()
455 };
456 let appearance = system_appearance().unwrap_or_default();
457 let mut context = WindowCreateContext {
458 inner: None,
459 handle,
460 hide_title_bar,
461 display,
462 is_movable: params.is_movable,
463 min_size: params.window_min_size,
464 executor,
465 current_cursor,
466 drop_target_helper,
467 validation_number,
468 main_receiver,
469 platform_window_handle,
470 appearance,
471 disable_direct_composition,
472 directx_devices,
473 invalidate_devices,
474 parent_hwnd,
475 };
476 let creation_result = unsafe {
477 CreateWindowExW(
478 dwexstyle,
479 WINDOW_CLASS_NAME,
480 &window_name,
481 dwstyle,
482 CW_USEDEFAULT,
483 CW_USEDEFAULT,
484 CW_USEDEFAULT,
485 CW_USEDEFAULT,
486 parent_hwnd,
487 None,
488 Some(hinstance.into()),
489 Some(&context as *const _ as *const _),
490 )
491 };
492
493 // Failure to create a `WindowsWindowState` can cause window creation to fail,
494 // so check the inner result first.
495 let this = context.inner.take().transpose()?;
496 let hwnd = creation_result?;
497 let this = this.unwrap();
498
499 register_drag_drop(&this)?;
500 set_non_rude_hwnd(hwnd, true);
501 configure_dwm_dark_mode(hwnd, appearance);
502 this.state.border_offset.update(hwnd)?;
503 let placement = retrieve_window_placement(
504 hwnd,
505 display,
506 params.bounds,
507 this.state.scale_factor.get(),
508 &this.state.border_offset,
509 )?;
510 if params.show {
511 unsafe { SetWindowPlacement(hwnd, &placement)? };
512 } else {
513 this.state.initial_placement.set(Some(WindowOpenStatus {
514 placement,
515 state: WindowOpenState::Windowed,
516 }));
517 }
518
519 Ok(Self(this))
520 }
521}
522
523impl rwh::HasWindowHandle for WindowsWindow {
524 fn window_handle(&self) -> std::result::Result<rwh::WindowHandle<'_>, rwh::HandleError> {
525 let raw = rwh::Win32WindowHandle::new(unsafe {
526 NonZeroIsize::new_unchecked(self.0.hwnd.0 as isize)
527 })
528 .into();
529 Ok(unsafe { rwh::WindowHandle::borrow_raw(raw) })
530 }
531}
532
533// todo(windows)
534impl rwh::HasDisplayHandle for WindowsWindow {
535 fn display_handle(&self) -> std::result::Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
536 unimplemented!()
537 }
538}
539
540impl Drop for WindowsWindow {
541 fn drop(&mut self) {
542 // clone this `Rc` to prevent early release of the pointer
543 let this = self.0.clone();
544 self.0
545 .executor
546 .spawn(async move {
547 let handle = this.hwnd;
548 unsafe {
549 RevokeDragDrop(handle).log_err();
550 DestroyWindow(handle).log_err();
551 }
552 })
553 .detach();
554 }
555}
556
557impl PlatformWindow for WindowsWindow {
558 fn bounds(&self) -> Bounds<Pixels> {
559 self.state.bounds()
560 }
561
562 fn is_maximized(&self) -> bool {
563 self.state.is_maximized()
564 }
565
566 fn window_bounds(&self) -> WindowBounds {
567 self.state.window_bounds()
568 }
569
570 /// get the logical size of the app's drawable area.
571 ///
572 /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
573 /// whether the mouse collides with other elements of GPUI).
574 fn content_size(&self) -> Size<Pixels> {
575 self.state.content_size()
576 }
577
578 fn resize(&mut self, size: Size<Pixels>) {
579 let hwnd = self.0.hwnd;
580 let bounds = gpui::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 PromptLevel::Info => {
667 title = windows::core::w!("Info");
668 main_icon = TD_INFORMATION_ICON;
669 }
670 PromptLevel::Warning => {
671 title = windows::core::w!("Warning");
672 main_icon = TD_WARNING_ICON;
673 }
674 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.as_f32() * scale_factor) as i32,
939 y: (bounds.origin.y.as_f32() * scale_factor) as i32
940 + ((bounds.size.height.as_f32() * 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 gpui::{DevicePixels, MouseButton, point};
1480 use std::time::Duration;
1481
1482 #[test]
1483 fn test_double_click_interval() {
1484 let 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 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}