window.rs

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