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