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