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