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