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