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