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 capslock(&self) -> Capslock {
563 current_capslock()
564 }
565
566 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
567 self.0.state.borrow_mut().input_handler = Some(input_handler);
568 }
569
570 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
571 self.0.state.borrow_mut().input_handler.take()
572 }
573
574 fn prompt(
575 &self,
576 level: PromptLevel,
577 msg: &str,
578 detail: Option<&str>,
579 answers: &[PromptButton],
580 ) -> Option<Receiver<usize>> {
581 let (done_tx, done_rx) = oneshot::channel();
582 let msg = msg.to_string();
583 let detail_string = match detail {
584 Some(info) => Some(info.to_string()),
585 None => None,
586 };
587 let handle = self.0.hwnd;
588 let answers = answers.to_vec();
589 self.0
590 .executor
591 .spawn(async move {
592 unsafe {
593 let mut config = TASKDIALOGCONFIG::default();
594 config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;
595 config.hwndParent = handle;
596 let title;
597 let main_icon;
598 match level {
599 crate::PromptLevel::Info => {
600 title = windows::core::w!("Info");
601 main_icon = TD_INFORMATION_ICON;
602 }
603 crate::PromptLevel::Warning => {
604 title = windows::core::w!("Warning");
605 main_icon = TD_WARNING_ICON;
606 }
607 crate::PromptLevel::Critical => {
608 title = windows::core::w!("Critical");
609 main_icon = TD_ERROR_ICON;
610 }
611 };
612 config.pszWindowTitle = title;
613 config.Anonymous1.pszMainIcon = main_icon;
614 let instruction = HSTRING::from(msg);
615 config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());
616 let hints_encoded;
617 if let Some(ref hints) = detail_string {
618 hints_encoded = HSTRING::from(hints);
619 config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());
620 };
621 let mut button_id_map = Vec::with_capacity(answers.len());
622 let mut buttons = Vec::new();
623 let mut btn_encoded = Vec::new();
624 for (index, btn) in answers.iter().enumerate() {
625 let encoded = HSTRING::from(btn.label().as_ref());
626 let button_id = if btn.is_cancel() {
627 IDCANCEL.0
628 } else {
629 index as i32 - 100
630 };
631 button_id_map.push(button_id);
632 buttons.push(TASKDIALOG_BUTTON {
633 nButtonID: button_id,
634 pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),
635 });
636 btn_encoded.push(encoded);
637 }
638 config.cButtons = buttons.len() as _;
639 config.pButtons = buttons.as_ptr();
640
641 config.pfCallback = None;
642 let mut res = std::mem::zeroed();
643 let _ = TaskDialogIndirect(&config, Some(&mut res), None, None)
644 .context("unable to create task dialog")
645 .log_err();
646
647 let clicked = button_id_map
648 .iter()
649 .position(|&button_id| button_id == res)
650 .unwrap();
651 let _ = done_tx.send(clicked);
652 }
653 })
654 .detach();
655
656 Some(done_rx)
657 }
658
659 fn activate(&self) {
660 let hwnd = self.0.hwnd;
661 let this = self.0.clone();
662 self.0
663 .executor
664 .spawn(async move {
665 this.set_window_placement().log_err();
666 unsafe { SetActiveWindow(hwnd).log_err() };
667 unsafe { SetFocus(Some(hwnd)).log_err() };
668 // todo(windows)
669 // crate `windows 0.56` reports true as Err
670 unsafe { SetForegroundWindow(hwnd).as_bool() };
671 })
672 .detach();
673 }
674
675 fn is_active(&self) -> bool {
676 self.0.hwnd == unsafe { GetActiveWindow() }
677 }
678
679 fn is_hovered(&self) -> bool {
680 self.0.state.borrow().hovered
681 }
682
683 fn set_title(&mut self, title: &str) {
684 unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
685 .inspect_err(|e| log::error!("Set title failed: {e}"))
686 .ok();
687 }
688
689 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
690 let mut window_state = self.0.state.borrow_mut();
691 window_state
692 .renderer
693 .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
694
695 match background_appearance {
696 WindowBackgroundAppearance::Opaque => {
697 // ACCENT_DISABLED
698 set_window_composition_attribute(window_state.hwnd, None, 0);
699 }
700 WindowBackgroundAppearance::Transparent => {
701 // Use ACCENT_ENABLE_TRANSPARENTGRADIENT for transparent background
702 set_window_composition_attribute(window_state.hwnd, None, 2);
703 }
704 WindowBackgroundAppearance::Blurred => {
705 // Enable acrylic blur
706 // ACCENT_ENABLE_ACRYLICBLURBEHIND
707 set_window_composition_attribute(window_state.hwnd, Some((0, 0, 0, 0)), 4);
708 }
709 }
710 }
711
712 fn minimize(&self) {
713 unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
714 }
715
716 fn zoom(&self) {
717 unsafe {
718 if IsWindowVisible(self.0.hwnd).as_bool() {
719 ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
720 } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
721 status.state = WindowOpenState::Maximized;
722 }
723 }
724 }
725
726 fn toggle_fullscreen(&self) {
727 if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
728 self.0.toggle_fullscreen();
729 } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
730 status.state = WindowOpenState::Fullscreen;
731 }
732 }
733
734 fn is_fullscreen(&self) -> bool {
735 self.0.state.borrow().is_fullscreen()
736 }
737
738 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
739 self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
740 }
741
742 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
743 self.0.state.borrow_mut().callbacks.input = Some(callback);
744 }
745
746 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
747 self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
748 }
749
750 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
751 self.0.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
752 }
753
754 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
755 self.0.state.borrow_mut().callbacks.resize = Some(callback);
756 }
757
758 fn on_moved(&self, callback: Box<dyn FnMut()>) {
759 self.0.state.borrow_mut().callbacks.moved = Some(callback);
760 }
761
762 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
763 self.0.state.borrow_mut().callbacks.should_close = Some(callback);
764 }
765
766 fn on_close(&self, callback: Box<dyn FnOnce()>) {
767 self.0.state.borrow_mut().callbacks.close = Some(callback);
768 }
769
770 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
771 self.0.state.borrow_mut().callbacks.hit_test_window_control = Some(callback);
772 }
773
774 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
775 self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
776 }
777
778 fn draw(&self, scene: &Scene) {
779 self.0.state.borrow_mut().renderer.draw(scene)
780 }
781
782 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
783 self.0.state.borrow().renderer.sprite_atlas().clone()
784 }
785
786 fn get_raw_handle(&self) -> HWND {
787 self.0.hwnd
788 }
789
790 fn gpu_specs(&self) -> Option<GpuSpecs> {
791 Some(self.0.state.borrow().renderer.gpu_specs())
792 }
793
794 fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>) {
795 // todo(windows)
796 }
797}
798
799#[implement(IDropTarget)]
800struct WindowsDragDropHandler(pub Rc<WindowsWindowStatePtr>);
801
802impl WindowsDragDropHandler {
803 fn handle_drag_drop(&self, input: PlatformInput) {
804 let mut lock = self.0.state.borrow_mut();
805 if let Some(mut func) = lock.callbacks.input.take() {
806 drop(lock);
807 func(input);
808 self.0.state.borrow_mut().callbacks.input = Some(func);
809 }
810 }
811}
812
813#[allow(non_snake_case)]
814impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
815 fn DragEnter(
816 &self,
817 pdataobj: windows::core::Ref<IDataObject>,
818 _grfkeystate: MODIFIERKEYS_FLAGS,
819 pt: &POINTL,
820 pdweffect: *mut DROPEFFECT,
821 ) -> windows::core::Result<()> {
822 unsafe {
823 let idata_obj = pdataobj.ok()?;
824 let config = FORMATETC {
825 cfFormat: CF_HDROP.0,
826 ptd: std::ptr::null_mut() as _,
827 dwAspect: DVASPECT_CONTENT.0,
828 lindex: -1,
829 tymed: TYMED_HGLOBAL.0 as _,
830 };
831 if idata_obj.QueryGetData(&config as _) == S_OK {
832 *pdweffect = DROPEFFECT_LINK;
833 let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
834 return Ok(());
835 };
836 if idata.u.hGlobal.is_invalid() {
837 return Ok(());
838 }
839 let hdrop = idata.u.hGlobal.0 as *mut HDROP;
840 let mut paths = SmallVec::<[PathBuf; 2]>::new();
841 with_file_names(*hdrop, |file_name| {
842 if let Some(path) = PathBuf::from_str(&file_name).log_err() {
843 paths.push(path);
844 }
845 });
846 ReleaseStgMedium(&mut idata);
847 let mut cursor_position = POINT { x: pt.x, y: pt.y };
848 ScreenToClient(self.0.hwnd, &mut cursor_position)
849 .ok()
850 .log_err();
851 let scale_factor = self.0.state.borrow().scale_factor;
852 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
853 position: logical_point(
854 cursor_position.x as f32,
855 cursor_position.y as f32,
856 scale_factor,
857 ),
858 paths: ExternalPaths(paths),
859 });
860 self.handle_drag_drop(input);
861 } else {
862 *pdweffect = DROPEFFECT_NONE;
863 }
864 }
865 Ok(())
866 }
867
868 fn DragOver(
869 &self,
870 _grfkeystate: MODIFIERKEYS_FLAGS,
871 pt: &POINTL,
872 _pdweffect: *mut DROPEFFECT,
873 ) -> windows::core::Result<()> {
874 let mut cursor_position = POINT { x: pt.x, y: pt.y };
875 unsafe {
876 ScreenToClient(self.0.hwnd, &mut cursor_position)
877 .ok()
878 .log_err();
879 }
880 let scale_factor = self.0.state.borrow().scale_factor;
881 let input = PlatformInput::FileDrop(FileDropEvent::Pending {
882 position: logical_point(
883 cursor_position.x as f32,
884 cursor_position.y as f32,
885 scale_factor,
886 ),
887 });
888 self.handle_drag_drop(input);
889
890 Ok(())
891 }
892
893 fn DragLeave(&self) -> windows::core::Result<()> {
894 let input = PlatformInput::FileDrop(FileDropEvent::Exited);
895 self.handle_drag_drop(input);
896
897 Ok(())
898 }
899
900 fn Drop(
901 &self,
902 _pdataobj: windows::core::Ref<IDataObject>,
903 _grfkeystate: MODIFIERKEYS_FLAGS,
904 pt: &POINTL,
905 _pdweffect: *mut DROPEFFECT,
906 ) -> windows::core::Result<()> {
907 let mut cursor_position = POINT { x: pt.x, y: pt.y };
908 unsafe {
909 ScreenToClient(self.0.hwnd, &mut cursor_position)
910 .ok()
911 .log_err();
912 }
913 let scale_factor = self.0.state.borrow().scale_factor;
914 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
915 position: logical_point(
916 cursor_position.x as f32,
917 cursor_position.y as f32,
918 scale_factor,
919 ),
920 });
921 self.handle_drag_drop(input);
922
923 Ok(())
924 }
925}
926
927#[derive(Debug)]
928pub(crate) struct ClickState {
929 button: MouseButton,
930 last_click: Instant,
931 last_position: Point<DevicePixels>,
932 double_click_spatial_tolerance_width: i32,
933 double_click_spatial_tolerance_height: i32,
934 double_click_interval: Duration,
935 pub(crate) current_count: usize,
936}
937
938impl ClickState {
939 pub fn new() -> Self {
940 let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
941 let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
942 let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
943
944 ClickState {
945 button: MouseButton::Left,
946 last_click: Instant::now(),
947 last_position: Point::default(),
948 double_click_spatial_tolerance_width,
949 double_click_spatial_tolerance_height,
950 double_click_interval,
951 current_count: 0,
952 }
953 }
954
955 /// update self and return the needed click count
956 pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
957 if self.button == button && self.is_double_click(new_position) {
958 self.current_count += 1;
959 } else {
960 self.current_count = 1;
961 }
962 self.last_click = Instant::now();
963 self.last_position = new_position;
964 self.button = button;
965
966 self.current_count
967 }
968
969 pub fn system_update(&mut self) {
970 self.double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
971 self.double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
972 self.double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
973 }
974
975 #[inline]
976 fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
977 let diff = self.last_position - new_position;
978
979 self.last_click.elapsed() < self.double_click_interval
980 && diff.x.0.abs() <= self.double_click_spatial_tolerance_width
981 && diff.y.0.abs() <= self.double_click_spatial_tolerance_height
982 }
983}
984
985struct StyleAndBounds {
986 style: WINDOW_STYLE,
987 x: i32,
988 y: i32,
989 cx: i32,
990 cy: i32,
991}
992
993#[repr(C)]
994struct WINDOWCOMPOSITIONATTRIBDATA {
995 attrib: u32,
996 pv_data: *mut std::ffi::c_void,
997 cb_data: usize,
998}
999
1000#[repr(C)]
1001struct AccentPolicy {
1002 accent_state: u32,
1003 accent_flags: u32,
1004 gradient_color: u32,
1005 animation_id: u32,
1006}
1007
1008type Color = (u8, u8, u8, u8);
1009
1010#[derive(Debug, Default, Clone, Copy)]
1011pub(crate) struct WindowBorderOffset {
1012 pub(crate) width_offset: i32,
1013 pub(crate) height_offset: i32,
1014}
1015
1016impl WindowBorderOffset {
1017 pub(crate) fn update(&mut self, hwnd: HWND) -> anyhow::Result<()> {
1018 let window_rect = unsafe {
1019 let mut rect = std::mem::zeroed();
1020 GetWindowRect(hwnd, &mut rect)?;
1021 rect
1022 };
1023 let client_rect = unsafe {
1024 let mut rect = std::mem::zeroed();
1025 GetClientRect(hwnd, &mut rect)?;
1026 rect
1027 };
1028 self.width_offset =
1029 (window_rect.right - window_rect.left) - (client_rect.right - client_rect.left);
1030 self.height_offset =
1031 (window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top);
1032 Ok(())
1033 }
1034}
1035
1036struct WindowOpenStatus {
1037 placement: WINDOWPLACEMENT,
1038 state: WindowOpenState,
1039}
1040
1041enum WindowOpenState {
1042 Maximized,
1043 Fullscreen,
1044 Windowed,
1045}
1046
1047fn register_wnd_class(icon_handle: HICON) -> PCWSTR {
1048 const CLASS_NAME: PCWSTR = w!("Zed::Window");
1049
1050 static ONCE: Once = Once::new();
1051 ONCE.call_once(|| {
1052 let wc = WNDCLASSW {
1053 lpfnWndProc: Some(wnd_proc),
1054 hIcon: icon_handle,
1055 lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
1056 style: CS_HREDRAW | CS_VREDRAW,
1057 hInstance: get_module_handle().into(),
1058 hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1059 ..Default::default()
1060 };
1061 unsafe { RegisterClassW(&wc) };
1062 });
1063
1064 CLASS_NAME
1065}
1066
1067unsafe extern "system" fn wnd_proc(
1068 hwnd: HWND,
1069 msg: u32,
1070 wparam: WPARAM,
1071 lparam: LPARAM,
1072) -> LRESULT {
1073 if msg == WM_NCCREATE {
1074 let cs = lparam.0 as *const CREATESTRUCTW;
1075 let cs = unsafe { &*cs };
1076 let ctx = cs.lpCreateParams as *mut WindowCreateContext;
1077 let ctx = unsafe { &mut *ctx };
1078 let creation_result = WindowsWindowStatePtr::new(ctx, hwnd, cs);
1079 if creation_result.is_err() {
1080 ctx.inner = Some(creation_result);
1081 return LRESULT(0);
1082 }
1083 let weak = Box::new(Rc::downgrade(creation_result.as_ref().unwrap()));
1084 unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1085 ctx.inner = Some(creation_result);
1086 return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1087 }
1088 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
1089 if ptr.is_null() {
1090 return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1091 }
1092 let inner = unsafe { &*ptr };
1093 let r = if let Some(state) = inner.upgrade() {
1094 handle_msg(hwnd, msg, wparam, lparam, state)
1095 } else {
1096 unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1097 };
1098 if msg == WM_NCDESTROY {
1099 unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1100 unsafe { drop(Box::from_raw(ptr)) };
1101 }
1102 r
1103}
1104
1105pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
1106 if hwnd.is_invalid() {
1107 return None;
1108 }
1109
1110 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
1111 if !ptr.is_null() {
1112 let inner = unsafe { &*ptr };
1113 inner.upgrade()
1114 } else {
1115 None
1116 }
1117}
1118
1119fn get_module_handle() -> HMODULE {
1120 unsafe {
1121 let mut h_module = std::mem::zeroed();
1122 GetModuleHandleExW(
1123 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1124 windows::core::w!("ZedModule"),
1125 &mut h_module,
1126 )
1127 .expect("Unable to get module handle"); // this should never fail
1128
1129 h_module
1130 }
1131}
1132
1133fn register_drag_drop(state_ptr: Rc<WindowsWindowStatePtr>) -> Result<()> {
1134 let window_handle = state_ptr.hwnd;
1135 let handler = WindowsDragDropHandler(state_ptr);
1136 // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1137 // we call `RevokeDragDrop`.
1138 // So, it's safe to drop it here.
1139 let drag_drop_handler: IDropTarget = handler.into();
1140 unsafe {
1141 RegisterDragDrop(window_handle, &drag_drop_handler)
1142 .context("unable to register drag-drop event")?;
1143 }
1144 Ok(())
1145}
1146
1147fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: WindowBorderOffset) -> RECT {
1148 // NOTE:
1149 // The reason we're not using `AdjustWindowRectEx()` here is
1150 // that the size reported by this function is incorrect.
1151 // You can test it, and there are similar discussions online.
1152 // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1153 //
1154 // So we manually calculate these values here.
1155 let mut rect = RECT {
1156 left: bounds.left().0,
1157 top: bounds.top().0,
1158 right: bounds.right().0,
1159 bottom: bounds.bottom().0,
1160 };
1161 let left_offset = border_offset.width_offset / 2;
1162 let top_offset = border_offset.height_offset / 2;
1163 let right_offset = border_offset.width_offset - left_offset;
1164 let bottom_offset = border_offset.height_offset - top_offset;
1165 rect.left -= left_offset;
1166 rect.top -= top_offset;
1167 rect.right += right_offset;
1168 rect.bottom += bottom_offset;
1169 rect
1170}
1171
1172fn calculate_client_rect(
1173 rect: RECT,
1174 border_offset: WindowBorderOffset,
1175 scale_factor: f32,
1176) -> Bounds<Pixels> {
1177 let left_offset = border_offset.width_offset / 2;
1178 let top_offset = border_offset.height_offset / 2;
1179 let right_offset = border_offset.width_offset - left_offset;
1180 let bottom_offset = border_offset.height_offset - top_offset;
1181 let left = rect.left + left_offset;
1182 let top = rect.top + top_offset;
1183 let right = rect.right - right_offset;
1184 let bottom = rect.bottom - bottom_offset;
1185 let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1186 Bounds {
1187 origin: logical_point(left as f32, top as f32, scale_factor),
1188 size: physical_size.to_pixels(scale_factor),
1189 }
1190}
1191
1192fn retrieve_window_placement(
1193 hwnd: HWND,
1194 display: WindowsDisplay,
1195 initial_bounds: Bounds<Pixels>,
1196 scale_factor: f32,
1197 border_offset: WindowBorderOffset,
1198) -> Result<WINDOWPLACEMENT> {
1199 let mut placement = WINDOWPLACEMENT {
1200 length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1201 ..Default::default()
1202 };
1203 unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1204 // the bounds may be not inside the display
1205 let bounds = if display.check_given_bounds(initial_bounds) {
1206 initial_bounds
1207 } else {
1208 display.default_bounds()
1209 };
1210 let bounds = bounds.to_device_pixels(scale_factor);
1211 placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1212 Ok(placement)
1213}
1214
1215fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1216 let mut version = unsafe { std::mem::zeroed() };
1217 let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1218 if !status.is_ok() || version.dwBuildNumber < 17763 {
1219 return;
1220 }
1221
1222 unsafe {
1223 type SetWindowCompositionAttributeType =
1224 unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1225 let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1226 let user32 = GetModuleHandleA(module_name);
1227 if user32.is_ok() {
1228 let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1229 let set_window_composition_attribute: SetWindowCompositionAttributeType =
1230 std::mem::transmute(GetProcAddress(user32.unwrap(), func_name));
1231 let mut color = color.unwrap_or_default();
1232 let is_acrylic = state == 4;
1233 if is_acrylic && color.3 == 0 {
1234 color.3 = 1;
1235 }
1236 let accent = AccentPolicy {
1237 accent_state: state,
1238 accent_flags: if is_acrylic { 0 } else { 2 },
1239 gradient_color: (color.0 as u32)
1240 | ((color.1 as u32) << 8)
1241 | ((color.2 as u32) << 16)
1242 | ((color.3 as u32) << 24),
1243 animation_id: 0,
1244 };
1245 let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1246 attrib: 0x13,
1247 pv_data: &accent as *const _ as *mut _,
1248 cb_data: std::mem::size_of::<AccentPolicy>(),
1249 };
1250 let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1251 } else {
1252 let _ = user32
1253 .inspect_err(|e| log::error!("Error getting module: {e}"))
1254 .ok();
1255 }
1256 }
1257}
1258
1259mod windows_renderer {
1260 use crate::platform::blade::{BladeContext, BladeRenderer, BladeSurfaceConfig};
1261 use raw_window_handle as rwh;
1262 use std::num::NonZeroIsize;
1263 use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::GWLP_HINSTANCE};
1264
1265 use crate::{get_window_long, show_error};
1266
1267 pub(super) fn init(
1268 context: &BladeContext,
1269 hwnd: HWND,
1270 transparent: bool,
1271 ) -> anyhow::Result<BladeRenderer> {
1272 let raw = RawWindow { hwnd };
1273 let config = BladeSurfaceConfig {
1274 size: Default::default(),
1275 transparent,
1276 };
1277 BladeRenderer::new(context, &raw, config).inspect_err(|err| {
1278 show_error(
1279 "Error: Zed failed to initialize BladeRenderer",
1280 err.to_string(),
1281 )
1282 })
1283 }
1284
1285 struct RawWindow {
1286 hwnd: HWND,
1287 }
1288
1289 impl rwh::HasWindowHandle for RawWindow {
1290 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1291 Ok(unsafe {
1292 let hwnd = NonZeroIsize::new_unchecked(self.hwnd.0 as isize);
1293 let mut handle = rwh::Win32WindowHandle::new(hwnd);
1294 let hinstance = get_window_long(self.hwnd, GWLP_HINSTANCE);
1295 handle.hinstance = NonZeroIsize::new(hinstance);
1296 rwh::WindowHandle::borrow_raw(handle.into())
1297 })
1298 }
1299 }
1300
1301 impl rwh::HasDisplayHandle for RawWindow {
1302 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1303 let handle = rwh::WindowsDisplayHandle::new();
1304 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
1305 }
1306 }
1307}
1308
1309#[cfg(test)]
1310mod tests {
1311 use super::ClickState;
1312 use crate::{DevicePixels, MouseButton, point};
1313 use std::time::Duration;
1314
1315 #[test]
1316 fn test_double_click_interval() {
1317 let mut state = ClickState::new();
1318 assert_eq!(
1319 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1320 1
1321 );
1322 assert_eq!(
1323 state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1324 1
1325 );
1326 assert_eq!(
1327 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1328 1
1329 );
1330 assert_eq!(
1331 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1332 2
1333 );
1334 state.last_click -= Duration::from_millis(700);
1335 assert_eq!(
1336 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1337 1
1338 );
1339 }
1340
1341 #[test]
1342 fn test_double_click_spatial_tolerance() {
1343 let mut state = ClickState::new();
1344 assert_eq!(
1345 state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1346 1
1347 );
1348 assert_eq!(
1349 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1350 2
1351 );
1352 assert_eq!(
1353 state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1354 1
1355 );
1356 assert_eq!(
1357 state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1358 1
1359 );
1360 }
1361}