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