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