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