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()>>,
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 self.0
651 .state
652 .borrow_mut()
653 .renderer
654 .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
655 }
656
657 fn minimize(&self) {
658 unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
659 }
660
661 fn zoom(&self) {
662 unsafe {
663 if IsWindowVisible(self.0.hwnd).as_bool() {
664 ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
665 } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
666 status.state = WindowOpenState::Maximized;
667 }
668 }
669 }
670
671 fn toggle_fullscreen(&self) {
672 if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
673 self.0.toggle_fullscreen();
674 } else if let Some(status) = self.0.state.borrow_mut().initial_placement.as_mut() {
675 status.state = WindowOpenState::Fullscreen;
676 }
677 }
678
679 fn is_fullscreen(&self) -> bool {
680 self.0.state.borrow().is_fullscreen()
681 }
682
683 fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
684 self.0.state.borrow_mut().callbacks.request_frame = Some(callback);
685 }
686
687 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
688 self.0.state.borrow_mut().callbacks.input = Some(callback);
689 }
690
691 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
692 self.0.state.borrow_mut().callbacks.active_status_change = Some(callback);
693 }
694
695 fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
696
697 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
698 self.0.state.borrow_mut().callbacks.resize = Some(callback);
699 }
700
701 fn on_moved(&self, callback: Box<dyn FnMut()>) {
702 self.0.state.borrow_mut().callbacks.moved = Some(callback);
703 }
704
705 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
706 self.0.state.borrow_mut().callbacks.should_close = Some(callback);
707 }
708
709 fn on_close(&self, callback: Box<dyn FnOnce()>) {
710 self.0.state.borrow_mut().callbacks.close = Some(callback);
711 }
712
713 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
714 self.0.state.borrow_mut().callbacks.appearance_changed = Some(callback);
715 }
716
717 fn draw(&self, scene: &Scene) {
718 self.0.state.borrow_mut().renderer.draw(scene)
719 }
720
721 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
722 self.0.state.borrow().renderer.sprite_atlas().clone()
723 }
724
725 fn get_raw_handle(&self) -> HWND {
726 self.0.hwnd
727 }
728
729 fn gpu_specs(&self) -> Option<GPUSpecs> {
730 Some(self.0.state.borrow().renderer.gpu_specs())
731 }
732
733 fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>) {
734 // todo(windows)
735 }
736}
737
738#[implement(IDropTarget)]
739struct WindowsDragDropHandler(pub Rc<WindowsWindowStatePtr>);
740
741impl WindowsDragDropHandler {
742 fn handle_drag_drop(&self, input: PlatformInput) {
743 let mut lock = self.0.state.borrow_mut();
744 if let Some(mut func) = lock.callbacks.input.take() {
745 drop(lock);
746 func(input);
747 self.0.state.borrow_mut().callbacks.input = Some(func);
748 }
749 }
750}
751
752#[allow(non_snake_case)]
753impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
754 fn DragEnter(
755 &self,
756 pdataobj: Option<&IDataObject>,
757 _grfkeystate: MODIFIERKEYS_FLAGS,
758 pt: &POINTL,
759 pdweffect: *mut DROPEFFECT,
760 ) -> windows::core::Result<()> {
761 unsafe {
762 let Some(idata_obj) = pdataobj else {
763 log::info!("no dragging file or directory detected");
764 return Ok(());
765 };
766 let config = FORMATETC {
767 cfFormat: CF_HDROP.0,
768 ptd: std::ptr::null_mut() as _,
769 dwAspect: DVASPECT_CONTENT.0,
770 lindex: -1,
771 tymed: TYMED_HGLOBAL.0 as _,
772 };
773 if idata_obj.QueryGetData(&config as _) == S_OK {
774 *pdweffect = DROPEFFECT_LINK;
775 let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
776 return Ok(());
777 };
778 if idata.u.hGlobal.is_invalid() {
779 return Ok(());
780 }
781 let hdrop = idata.u.hGlobal.0 as *mut HDROP;
782 let mut paths = SmallVec::<[PathBuf; 2]>::new();
783 with_file_names(*hdrop, |file_name| {
784 if let Some(path) = PathBuf::from_str(&file_name).log_err() {
785 paths.push(path);
786 }
787 });
788 ReleaseStgMedium(&mut idata);
789 let mut cursor_position = POINT { x: pt.x, y: pt.y };
790 ScreenToClient(self.0.hwnd, &mut cursor_position)
791 .ok()
792 .log_err();
793 let scale_factor = self.0.state.borrow().scale_factor;
794 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
795 position: logical_point(
796 cursor_position.x as f32,
797 cursor_position.y as f32,
798 scale_factor,
799 ),
800 paths: ExternalPaths(paths),
801 });
802 self.handle_drag_drop(input);
803 } else {
804 *pdweffect = DROPEFFECT_NONE;
805 }
806 }
807 Ok(())
808 }
809
810 fn DragOver(
811 &self,
812 _grfkeystate: MODIFIERKEYS_FLAGS,
813 pt: &POINTL,
814 _pdweffect: *mut DROPEFFECT,
815 ) -> windows::core::Result<()> {
816 let mut cursor_position = POINT { x: pt.x, y: pt.y };
817 unsafe {
818 ScreenToClient(self.0.hwnd, &mut cursor_position)
819 .ok()
820 .log_err();
821 }
822 let scale_factor = self.0.state.borrow().scale_factor;
823 let input = PlatformInput::FileDrop(FileDropEvent::Pending {
824 position: logical_point(
825 cursor_position.x as f32,
826 cursor_position.y as f32,
827 scale_factor,
828 ),
829 });
830 self.handle_drag_drop(input);
831
832 Ok(())
833 }
834
835 fn DragLeave(&self) -> windows::core::Result<()> {
836 let input = PlatformInput::FileDrop(FileDropEvent::Exited);
837 self.handle_drag_drop(input);
838
839 Ok(())
840 }
841
842 fn Drop(
843 &self,
844 _pdataobj: Option<&IDataObject>,
845 _grfkeystate: MODIFIERKEYS_FLAGS,
846 pt: &POINTL,
847 _pdweffect: *mut DROPEFFECT,
848 ) -> windows::core::Result<()> {
849 let mut cursor_position = POINT { x: pt.x, y: pt.y };
850 unsafe {
851 ScreenToClient(self.0.hwnd, &mut cursor_position)
852 .ok()
853 .log_err();
854 }
855 let scale_factor = self.0.state.borrow().scale_factor;
856 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
857 position: logical_point(
858 cursor_position.x as f32,
859 cursor_position.y as f32,
860 scale_factor,
861 ),
862 });
863 self.handle_drag_drop(input);
864
865 Ok(())
866 }
867}
868
869#[derive(Debug)]
870pub(crate) struct ClickState {
871 button: MouseButton,
872 last_click: Instant,
873 last_position: Point<DevicePixels>,
874 double_click_spatial_tolerance_width: i32,
875 double_click_spatial_tolerance_height: i32,
876 double_click_interval: Duration,
877 pub(crate) current_count: usize,
878}
879
880impl ClickState {
881 pub fn new() -> Self {
882 let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
883 let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
884 let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
885
886 ClickState {
887 button: MouseButton::Left,
888 last_click: Instant::now(),
889 last_position: Point::default(),
890 double_click_spatial_tolerance_width,
891 double_click_spatial_tolerance_height,
892 double_click_interval,
893 current_count: 0,
894 }
895 }
896
897 /// update self and return the needed click count
898 pub fn update(&mut self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
899 if self.button == button && self.is_double_click(new_position) {
900 self.current_count += 1;
901 } else {
902 self.current_count = 1;
903 }
904 self.last_click = Instant::now();
905 self.last_position = new_position;
906 self.button = button;
907
908 self.current_count
909 }
910
911 pub fn system_update(&mut self) {
912 self.double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
913 self.double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
914 self.double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
915 }
916
917 #[inline]
918 fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
919 let diff = self.last_position - new_position;
920
921 self.last_click.elapsed() < self.double_click_interval
922 && diff.x.0.abs() <= self.double_click_spatial_tolerance_width
923 && diff.y.0.abs() <= self.double_click_spatial_tolerance_height
924 }
925}
926
927struct StyleAndBounds {
928 style: WINDOW_STYLE,
929 x: i32,
930 y: i32,
931 cx: i32,
932 cy: i32,
933}
934
935#[derive(Debug, Default, Clone, Copy)]
936pub(crate) struct WindowBorderOffset {
937 width_offset: i32,
938 height_offset: i32,
939}
940
941impl WindowBorderOffset {
942 pub(crate) fn update(&mut self, hwnd: HWND) -> anyhow::Result<()> {
943 let window_rect = unsafe {
944 let mut rect = std::mem::zeroed();
945 GetWindowRect(hwnd, &mut rect)?;
946 rect
947 };
948 let client_rect = unsafe {
949 let mut rect = std::mem::zeroed();
950 GetClientRect(hwnd, &mut rect)?;
951 rect
952 };
953 self.width_offset =
954 (window_rect.right - window_rect.left) - (client_rect.right - client_rect.left);
955 self.height_offset =
956 (window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top);
957 Ok(())
958 }
959}
960
961struct WindowOpenStatus {
962 placement: WINDOWPLACEMENT,
963 state: WindowOpenState,
964}
965
966enum WindowOpenState {
967 Maximized,
968 Fullscreen,
969 Windowed,
970}
971
972fn register_wnd_class(icon_handle: HICON) -> PCWSTR {
973 const CLASS_NAME: PCWSTR = w!("Zed::Window");
974
975 static ONCE: Once = Once::new();
976 ONCE.call_once(|| {
977 let wc = WNDCLASSW {
978 lpfnWndProc: Some(wnd_proc),
979 hIcon: icon_handle,
980 lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
981 style: CS_HREDRAW | CS_VREDRAW,
982 hInstance: get_module_handle().into(),
983 ..Default::default()
984 };
985 unsafe { RegisterClassW(&wc) };
986 });
987
988 CLASS_NAME
989}
990
991unsafe extern "system" fn wnd_proc(
992 hwnd: HWND,
993 msg: u32,
994 wparam: WPARAM,
995 lparam: LPARAM,
996) -> LRESULT {
997 if msg == WM_NCCREATE {
998 let cs = lparam.0 as *const CREATESTRUCTW;
999 let cs = unsafe { &*cs };
1000 let ctx = cs.lpCreateParams as *mut WindowCreateContext;
1001 let ctx = unsafe { &mut *ctx };
1002 let creation_result = WindowsWindowStatePtr::new(ctx, hwnd, cs);
1003 if creation_result.is_err() {
1004 ctx.inner = Some(creation_result);
1005 return LRESULT(0);
1006 }
1007 let weak = Box::new(Rc::downgrade(creation_result.as_ref().unwrap()));
1008 unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1009 ctx.inner = Some(creation_result);
1010 return LRESULT(1);
1011 }
1012 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
1013 if ptr.is_null() {
1014 return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1015 }
1016 let inner = unsafe { &*ptr };
1017 let r = if let Some(state) = inner.upgrade() {
1018 handle_msg(hwnd, msg, wparam, lparam, state)
1019 } else {
1020 unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1021 };
1022 if msg == WM_NCDESTROY {
1023 unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1024 unsafe { drop(Box::from_raw(ptr)) };
1025 }
1026 r
1027}
1028
1029pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
1030 if hwnd.is_invalid() {
1031 return None;
1032 }
1033
1034 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowStatePtr>;
1035 if !ptr.is_null() {
1036 let inner = unsafe { &*ptr };
1037 inner.upgrade()
1038 } else {
1039 None
1040 }
1041}
1042
1043fn get_module_handle() -> HMODULE {
1044 unsafe {
1045 let mut h_module = std::mem::zeroed();
1046 GetModuleHandleExW(
1047 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1048 windows::core::w!("ZedModule"),
1049 &mut h_module,
1050 )
1051 .expect("Unable to get module handle"); // this should never fail
1052
1053 h_module
1054 }
1055}
1056
1057fn register_drag_drop(state_ptr: Rc<WindowsWindowStatePtr>) -> Result<()> {
1058 let window_handle = state_ptr.hwnd;
1059 let handler = WindowsDragDropHandler(state_ptr);
1060 // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1061 // we call `RevokeDragDrop`.
1062 // So, it's safe to drop it here.
1063 let drag_drop_handler: IDropTarget = handler.into();
1064 unsafe {
1065 RegisterDragDrop(window_handle, &drag_drop_handler)
1066 .context("unable to register drag-drop event")?;
1067 }
1068 Ok(())
1069}
1070
1071fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: WindowBorderOffset) -> RECT {
1072 // NOTE:
1073 // The reason we're not using `AdjustWindowRectEx()` here is
1074 // that the size reported by this function is incorrect.
1075 // You can test it, and there are similar discussions online.
1076 // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1077 //
1078 // So we manually calculate these values here.
1079 let mut rect = RECT {
1080 left: bounds.left().0,
1081 top: bounds.top().0,
1082 right: bounds.right().0,
1083 bottom: bounds.bottom().0,
1084 };
1085 let left_offset = border_offset.width_offset / 2;
1086 let top_offset = border_offset.height_offset / 2;
1087 let right_offset = border_offset.width_offset - left_offset;
1088 let bottom_offset = border_offset.height_offset - top_offset;
1089 rect.left -= left_offset;
1090 rect.top -= top_offset;
1091 rect.right += right_offset;
1092 rect.bottom += bottom_offset;
1093 rect
1094}
1095
1096fn calculate_client_rect(
1097 rect: RECT,
1098 border_offset: WindowBorderOffset,
1099 scale_factor: f32,
1100) -> Bounds<Pixels> {
1101 let left_offset = border_offset.width_offset / 2;
1102 let top_offset = border_offset.height_offset / 2;
1103 let right_offset = border_offset.width_offset - left_offset;
1104 let bottom_offset = border_offset.height_offset - top_offset;
1105 let left = rect.left + left_offset;
1106 let top = rect.top + top_offset;
1107 let right = rect.right - right_offset;
1108 let bottom = rect.bottom - bottom_offset;
1109 let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1110 Bounds {
1111 origin: logical_point(left as f32, top as f32, scale_factor),
1112 size: physical_size.to_pixels(scale_factor),
1113 }
1114}
1115
1116fn retrieve_window_placement(
1117 hwnd: HWND,
1118 display: WindowsDisplay,
1119 initial_bounds: Bounds<Pixels>,
1120 scale_factor: f32,
1121 border_offset: WindowBorderOffset,
1122) -> Result<WINDOWPLACEMENT> {
1123 let mut placement = WINDOWPLACEMENT {
1124 length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1125 ..Default::default()
1126 };
1127 unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1128 // the bounds may be not inside the display
1129 let bounds = if display.check_given_bounds(initial_bounds) {
1130 initial_bounds
1131 } else {
1132 display.default_bounds()
1133 };
1134 let bounds = bounds.to_device_pixels(scale_factor);
1135 placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1136 Ok(placement)
1137}
1138
1139mod windows_renderer {
1140 use std::{num::NonZeroIsize, sync::Arc};
1141
1142 use blade_graphics as gpu;
1143 use raw_window_handle as rwh;
1144 use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::GWLP_HINSTANCE};
1145
1146 use crate::{
1147 get_window_long,
1148 platform::blade::{BladeRenderer, BladeSurfaceConfig},
1149 };
1150
1151 pub(super) fn windows_renderer(hwnd: HWND, transparent: bool) -> anyhow::Result<BladeRenderer> {
1152 let raw = RawWindow { hwnd };
1153 let gpu: Arc<gpu::Context> = Arc::new(
1154 unsafe {
1155 gpu::Context::init_windowed(
1156 &raw,
1157 gpu::ContextDesc {
1158 validation: false,
1159 capture: false,
1160 overlay: false,
1161 },
1162 )
1163 }
1164 .map_err(|e| anyhow::anyhow!("{:?}", e))?,
1165 );
1166 let config = BladeSurfaceConfig {
1167 size: gpu::Extent::default(),
1168 transparent,
1169 };
1170
1171 Ok(BladeRenderer::new(gpu, config))
1172 }
1173
1174 struct RawWindow {
1175 hwnd: HWND,
1176 }
1177
1178 impl rwh::HasWindowHandle for RawWindow {
1179 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1180 Ok(unsafe {
1181 let hwnd = NonZeroIsize::new_unchecked(self.hwnd.0 as isize);
1182 let mut handle = rwh::Win32WindowHandle::new(hwnd);
1183 let hinstance = get_window_long(self.hwnd, GWLP_HINSTANCE);
1184 handle.hinstance = NonZeroIsize::new(hinstance);
1185 rwh::WindowHandle::borrow_raw(handle.into())
1186 })
1187 }
1188 }
1189
1190 impl rwh::HasDisplayHandle for RawWindow {
1191 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1192 let handle = rwh::WindowsDisplayHandle::new();
1193 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
1194 }
1195 }
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200 use super::ClickState;
1201 use crate::{point, DevicePixels, MouseButton};
1202 use std::time::Duration;
1203
1204 #[test]
1205 fn test_double_click_interval() {
1206 let mut state = ClickState::new();
1207 assert_eq!(
1208 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1209 1
1210 );
1211 assert_eq!(
1212 state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1213 1
1214 );
1215 assert_eq!(
1216 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1217 1
1218 );
1219 assert_eq!(
1220 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1221 2
1222 );
1223 state.last_click -= Duration::from_millis(700);
1224 assert_eq!(
1225 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1226 1
1227 );
1228 }
1229
1230 #[test]
1231 fn test_double_click_spatial_tolerance() {
1232 let mut state = ClickState::new();
1233 assert_eq!(
1234 state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1235 1
1236 );
1237 assert_eq!(
1238 state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1239 2
1240 );
1241 assert_eq!(
1242 state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1243 1
1244 );
1245 assert_eq!(
1246 state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1247 1
1248 );
1249 }
1250}