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