window.rs

  1#![deny(unsafe_op_in_unsafe_fn)]
  2// todo(windows): remove
  3#![allow(unused_variables)]
  4
  5use std::{
  6    any::Any,
  7    cell::{Cell, RefCell},
  8    ffi::c_void,
  9    num::NonZeroIsize,
 10    rc::{Rc, Weak},
 11    sync::{Arc, Once},
 12};
 13
 14use blade_graphics as gpu;
 15use futures::channel::oneshot::Receiver;
 16use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
 17use windows::{
 18    core::{w, HSTRING, PCWSTR},
 19    Win32::{
 20        Foundation::{FALSE, HINSTANCE, HWND, LPARAM, LRESULT, WPARAM},
 21        Graphics::Gdi::{BeginPaint, EndPaint, InvalidateRect, PAINTSTRUCT},
 22        System::SystemServices::{
 23            MK_LBUTTON, MK_MBUTTON, MK_RBUTTON, MK_XBUTTON1, MK_XBUTTON2, MODIFIERKEYS_FLAGS,
 24        },
 25        UI::{
 26            Input::KeyboardAndMouse::{
 27                GetKeyState, VIRTUAL_KEY, VK_BACK, VK_CONTROL, VK_DOWN, VK_END, VK_ESCAPE, VK_F1,
 28                VK_F24, VK_HOME, VK_INSERT, VK_LEFT, VK_LWIN, VK_MENU, VK_NEXT, VK_PRIOR,
 29                VK_RETURN, VK_RIGHT, VK_RWIN, VK_SHIFT, VK_SPACE, VK_TAB, VK_UP,
 30            },
 31            WindowsAndMessaging::{
 32                CreateWindowExW, DefWindowProcW, GetWindowLongPtrW, LoadCursorW, PostQuitMessage,
 33                RegisterClassW, SetWindowLongPtrW, SetWindowTextW, ShowWindow, CREATESTRUCTW,
 34                CW_USEDEFAULT, GWLP_USERDATA, HMENU, IDC_ARROW, SW_MAXIMIZE, SW_SHOW, WHEEL_DELTA,
 35                WINDOW_EX_STYLE, WINDOW_LONG_PTR_INDEX, WM_CHAR, WM_CLOSE, WM_DESTROY, WM_KEYDOWN,
 36                WM_KEYUP, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP,
 37                WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_MOVE, WM_NCCREATE, WM_NCDESTROY,
 38                WM_PAINT, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SIZE, WM_SYSCHAR, WM_SYSKEYDOWN,
 39                WM_SYSKEYUP, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSW, WS_OVERLAPPEDWINDOW,
 40                WS_VISIBLE, XBUTTON1, XBUTTON2,
 41            },
 42        },
 43    },
 44};
 45
 46use crate::{
 47    platform::blade::BladeRenderer, AnyWindowHandle, Bounds, GlobalPixels, HiLoWord, KeyDownEvent,
 48    KeyUpEvent, Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
 49    NavigationDirection, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
 50    PlatformInputHandler, PlatformWindow, Point, PromptLevel, Scene, ScrollDelta, Size, TouchPhase,
 51    WindowAppearance, WindowBounds, WindowOptions, WindowsDisplay, WindowsPlatformInner,
 52};
 53
 54#[derive(PartialEq)]
 55pub(crate) enum CallbackResult {
 56    /// handled by system or user callback
 57    Handled {
 58        /// `true` if user callback handled event
 59        by_callback: bool,
 60    },
 61    Unhandled,
 62}
 63
 64impl CallbackResult {
 65    pub fn is_handled(&self) -> bool {
 66        match self {
 67            Self::Handled { by_callback: _ } => true,
 68            _ => false,
 69        }
 70    }
 71}
 72
 73pub(crate) struct WindowsWindowInner {
 74    hwnd: HWND,
 75    origin: Cell<Point<GlobalPixels>>,
 76    size: Cell<Size<GlobalPixels>>,
 77    mouse_position: Cell<Point<Pixels>>,
 78    input_handler: Cell<Option<PlatformInputHandler>>,
 79    renderer: RefCell<BladeRenderer>,
 80    callbacks: RefCell<Callbacks>,
 81    platform_inner: Rc<WindowsPlatformInner>,
 82    handle: AnyWindowHandle,
 83}
 84
 85impl WindowsWindowInner {
 86    fn new(
 87        hwnd: HWND,
 88        cs: &CREATESTRUCTW,
 89        platform_inner: Rc<WindowsPlatformInner>,
 90        handle: AnyWindowHandle,
 91    ) -> Self {
 92        let origin = Cell::new(Point::new((cs.x as f64).into(), (cs.y as f64).into()));
 93        let size = Cell::new(Size {
 94            width: (cs.cx as f64).into(),
 95            height: (cs.cy as f64).into(),
 96        });
 97        let mouse_position = Cell::new(Point::default());
 98        let input_handler = Cell::new(None);
 99        struct RawWindow {
100            hwnd: *mut c_void,
101        }
102        unsafe impl blade_rwh::HasRawWindowHandle for RawWindow {
103            fn raw_window_handle(&self) -> blade_rwh::RawWindowHandle {
104                let mut handle = blade_rwh::Win32WindowHandle::empty();
105                handle.hwnd = self.hwnd;
106                handle.into()
107            }
108        }
109        unsafe impl blade_rwh::HasRawDisplayHandle for RawWindow {
110            fn raw_display_handle(&self) -> blade_rwh::RawDisplayHandle {
111                blade_rwh::WindowsDisplayHandle::empty().into()
112            }
113        }
114        let raw = RawWindow { hwnd: hwnd.0 as _ };
115        let gpu = Arc::new(
116            unsafe {
117                gpu::Context::init_windowed(
118                    &raw,
119                    gpu::ContextDesc {
120                        validation: false,
121                        capture: false,
122                        overlay: false,
123                    },
124                )
125            }
126            .unwrap(),
127        );
128        let extent = gpu::Extent {
129            width: 1,
130            height: 1,
131            depth: 1,
132        };
133        let renderer = RefCell::new(BladeRenderer::new(gpu, extent));
134        let callbacks = RefCell::new(Callbacks::default());
135        Self {
136            hwnd,
137            origin,
138            size,
139            mouse_position,
140            input_handler,
141            renderer,
142            callbacks,
143            platform_inner,
144            handle,
145        }
146    }
147
148    fn is_virtual_key_pressed(&self, vkey: VIRTUAL_KEY) -> bool {
149        unsafe { GetKeyState(vkey.0 as i32) < 0 }
150    }
151
152    fn current_modifiers(&self) -> Modifiers {
153        Modifiers {
154            control: self.is_virtual_key_pressed(VK_CONTROL),
155            alt: self.is_virtual_key_pressed(VK_MENU),
156            shift: self.is_virtual_key_pressed(VK_SHIFT),
157            command: self.is_virtual_key_pressed(VK_LWIN) || self.is_virtual_key_pressed(VK_RWIN),
158            function: false,
159        }
160    }
161
162    /// mark window client rect to be re-drawn
163    /// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-invalidaterect
164    pub(crate) fn invalidate_client_area(&self) {
165        unsafe { InvalidateRect(self.hwnd, None, FALSE) };
166    }
167
168    /// returns true if message is handled and should not dispatch
169    pub(crate) fn handle_immediate_msg(&self, msg: u32, wparam: WPARAM, lparam: LPARAM) -> bool {
170        match msg {
171            WM_KEYDOWN | WM_SYSKEYDOWN => self.handle_keydown_msg(wparam).is_handled(),
172            WM_KEYUP | WM_SYSKEYUP => self.handle_keyup_msg(wparam).is_handled(),
173            _ => false,
174        }
175    }
176
177    fn handle_msg(&self, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
178        log::debug!("msg: {msg}, wparam: {}, lparam: {}", wparam.0, lparam.0);
179        match msg {
180            WM_MOVE => self.handle_move_msg(lparam),
181            WM_SIZE => self.handle_size_msg(lparam),
182            WM_PAINT => self.handle_paint_msg(),
183            WM_CLOSE => self.handle_close_msg(msg, wparam, lparam),
184            WM_DESTROY => self.handle_destroy_msg(),
185            WM_MOUSEMOVE => self.handle_mouse_move_msg(lparam, wparam),
186            WM_LBUTTONDOWN => self.handle_mouse_down_msg(MouseButton::Left, lparam),
187            WM_RBUTTONDOWN => self.handle_mouse_down_msg(MouseButton::Right, lparam),
188            WM_MBUTTONDOWN => self.handle_mouse_down_msg(MouseButton::Middle, lparam),
189            WM_XBUTTONDOWN => {
190                let nav_dir = match wparam.hiword() {
191                    XBUTTON1 => Some(NavigationDirection::Forward),
192                    XBUTTON2 => Some(NavigationDirection::Back),
193                    _ => None,
194                };
195
196                if let Some(nav_dir) = nav_dir {
197                    self.handle_mouse_down_msg(MouseButton::Navigate(nav_dir), lparam)
198                } else {
199                    LRESULT(1)
200                }
201            }
202            WM_LBUTTONUP => self.handle_mouse_up_msg(MouseButton::Left, lparam),
203            WM_RBUTTONUP => self.handle_mouse_up_msg(MouseButton::Right, lparam),
204            WM_MBUTTONUP => self.handle_mouse_up_msg(MouseButton::Middle, lparam),
205            WM_XBUTTONUP => {
206                let nav_dir = match wparam.hiword() {
207                    XBUTTON1 => Some(NavigationDirection::Back),
208                    XBUTTON2 => Some(NavigationDirection::Forward),
209                    _ => None,
210                };
211
212                if let Some(nav_dir) = nav_dir {
213                    self.handle_mouse_up_msg(MouseButton::Navigate(nav_dir), lparam)
214                } else {
215                    LRESULT(1)
216                }
217            }
218            WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(wparam, lparam),
219            WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(wparam, lparam),
220            WM_CHAR | WM_SYSCHAR => self.handle_char_msg(wparam),
221            // These events are handled by the immediate handler
222            WM_KEYDOWN | WM_SYSKEYDOWN | WM_KEYUP | WM_SYSKEYUP => LRESULT(0),
223            _ => unsafe { DefWindowProcW(self.hwnd, msg, wparam, lparam) },
224        }
225    }
226
227    fn handle_move_msg(&self, lparam: LPARAM) -> LRESULT {
228        let x = lparam.signed_loword() as f64;
229        let y = lparam.signed_hiword() as f64;
230        self.origin.set(Point::new(x.into(), y.into()));
231        let mut callbacks = self.callbacks.borrow_mut();
232        if let Some(callback) = callbacks.moved.as_mut() {
233            callback()
234        }
235        LRESULT(0)
236    }
237
238    fn handle_size_msg(&self, lparam: LPARAM) -> LRESULT {
239        let width = lparam.loword().max(1) as f64;
240        let height = lparam.hiword().max(1) as f64;
241        self.renderer
242            .borrow_mut()
243            .update_drawable_size(Size { width, height });
244        let width = width.into();
245        let height = height.into();
246        self.size.set(Size { width, height });
247        let mut callbacks = self.callbacks.borrow_mut();
248        if let Some(callback) = callbacks.resize.as_mut() {
249            callback(
250                Size {
251                    width: Pixels(width.0),
252                    height: Pixels(height.0),
253                },
254                1.0,
255            );
256        }
257        self.invalidate_client_area();
258        LRESULT(0)
259    }
260
261    fn handle_paint_msg(&self) -> LRESULT {
262        let mut paint_struct = PAINTSTRUCT::default();
263        let hdc = unsafe { BeginPaint(self.hwnd, &mut paint_struct) };
264        let mut callbacks = self.callbacks.borrow_mut();
265        if let Some(request_frame) = callbacks.request_frame.as_mut() {
266            request_frame();
267        }
268        unsafe { EndPaint(self.hwnd, &paint_struct) };
269        LRESULT(0)
270    }
271
272    fn handle_close_msg(&self, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
273        let mut callbacks = self.callbacks.borrow_mut();
274        if let Some(callback) = callbacks.should_close.as_mut() {
275            if callback() {
276                return LRESULT(0);
277            }
278        }
279        drop(callbacks);
280        unsafe { DefWindowProcW(self.hwnd, msg, wparam, lparam) }
281    }
282
283    fn handle_destroy_msg(&self) -> LRESULT {
284        let mut callbacks = self.callbacks.borrow_mut();
285        if let Some(callback) = callbacks.close.take() {
286            callback()
287        }
288        let mut window_handles = self.platform_inner.window_handles.borrow_mut();
289        window_handles.remove(&self.handle);
290        if window_handles.is_empty() {
291            self.platform_inner
292                .foreground_executor
293                .spawn(async {
294                    unsafe { PostQuitMessage(0) };
295                })
296                .detach();
297        }
298        LRESULT(1)
299    }
300
301    fn handle_mouse_move_msg(&self, lparam: LPARAM, wparam: WPARAM) -> LRESULT {
302        let x = Pixels::from(lparam.signed_loword() as f32);
303        let y = Pixels::from(lparam.signed_hiword() as f32);
304        self.mouse_position.set(Point { x, y });
305        let mut callbacks = self.callbacks.borrow_mut();
306        if let Some(callback) = callbacks.input.as_mut() {
307            let pressed_button = match MODIFIERKEYS_FLAGS(wparam.loword() as u32) {
308                flags if flags.contains(MK_LBUTTON) => Some(MouseButton::Left),
309                flags if flags.contains(MK_RBUTTON) => Some(MouseButton::Right),
310                flags if flags.contains(MK_MBUTTON) => Some(MouseButton::Middle),
311                flags if flags.contains(MK_XBUTTON1) => {
312                    Some(MouseButton::Navigate(NavigationDirection::Back))
313                }
314                flags if flags.contains(MK_XBUTTON2) => {
315                    Some(MouseButton::Navigate(NavigationDirection::Forward))
316                }
317                _ => None,
318            };
319            let event = MouseMoveEvent {
320                position: Point { x, y },
321                pressed_button,
322                modifiers: self.current_modifiers(),
323            };
324            if callback(PlatformInput::MouseMove(event)) {
325                return LRESULT(0);
326            }
327        }
328        LRESULT(1)
329    }
330
331    fn parse_key_msg_keystroke(&self, wparam: WPARAM) -> Option<Keystroke> {
332        let vk_code = wparam.loword();
333
334        // 0-9 https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
335        if vk_code >= 0x30 && vk_code <= 0x39 {
336            let modifiers = self.current_modifiers();
337
338            if modifiers.shift {
339                return None;
340            }
341
342            let digit_char = (b'0' + ((vk_code - 0x30) as u8)) as char;
343            return Some(Keystroke {
344                modifiers,
345                key: digit_char.to_string(),
346                ime_key: Some(digit_char.to_string()),
347            });
348        }
349
350        // A-Z https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
351        if vk_code >= 0x41 && vk_code <= 0x5A {
352            let offset = (vk_code - 0x41) as u8;
353            let alpha_char = (b'a' + offset) as char;
354            let alpha_char_upper = (b'A' + offset) as char;
355            let modifiers = self.current_modifiers();
356            return Some(Keystroke {
357                modifiers,
358                key: alpha_char.to_string(),
359                ime_key: Some(if modifiers.shift {
360                    alpha_char_upper.to_string()
361                } else {
362                    alpha_char.to_string()
363                }),
364            });
365        }
366
367        if vk_code >= VK_F1.0 && vk_code <= VK_F24.0 {
368            let offset = vk_code - VK_F1.0;
369            return Some(Keystroke {
370                modifiers: self.current_modifiers(),
371                key: format!("f{}", offset + 1),
372                ime_key: None,
373            });
374        }
375
376        let key = match VIRTUAL_KEY(vk_code) {
377            VK_SPACE => Some(("space", Some(" "))),
378            VK_TAB => Some(("tab", Some("\t"))),
379            VK_BACK => Some(("backspace", None)),
380            VK_RETURN => Some(("enter", None)),
381            VK_UP => Some(("up", None)),
382            VK_DOWN => Some(("down", None)),
383            VK_RIGHT => Some(("right", None)),
384            VK_LEFT => Some(("left", None)),
385            VK_HOME => Some(("home", None)),
386            VK_END => Some(("end", None)),
387            VK_PRIOR => Some(("pageup", None)),
388            VK_NEXT => Some(("pagedown", None)),
389            VK_ESCAPE => Some(("escape", None)),
390            VK_INSERT => Some(("insert", None)),
391            _ => None,
392        };
393
394        if let Some((key, ime_key)) = key {
395            Some(Keystroke {
396                modifiers: self.current_modifiers(),
397                key: key.to_string(),
398                ime_key: ime_key.map(|k| k.to_string()),
399            })
400        } else {
401            None
402        }
403    }
404
405    fn handle_keydown_msg(&self, wparam: WPARAM) -> CallbackResult {
406        let mut callbacks = self.callbacks.borrow_mut();
407        let keystroke = self.parse_key_msg_keystroke(wparam);
408        if let Some(keystroke) = keystroke {
409            if let Some(callback) = callbacks.input.as_mut() {
410                let ime_key = keystroke.ime_key.clone();
411                let event = KeyDownEvent {
412                    keystroke,
413                    is_held: true,
414                };
415
416                if callback(PlatformInput::KeyDown(event)) {
417                    CallbackResult::Handled { by_callback: true }
418                } else if let Some(mut input_handler) = self.input_handler.take() {
419                    if let Some(ime_key) = ime_key {
420                        input_handler.replace_text_in_range(None, &ime_key);
421                    }
422                    self.input_handler.set(Some(input_handler));
423                    CallbackResult::Handled { by_callback: true }
424                } else {
425                    CallbackResult::Handled { by_callback: false }
426                }
427            } else {
428                CallbackResult::Handled { by_callback: false }
429            }
430        } else {
431            CallbackResult::Unhandled
432        }
433    }
434
435    fn handle_keyup_msg(&self, wparam: WPARAM) -> CallbackResult {
436        let mut callbacks = self.callbacks.borrow_mut();
437        let keystroke = self.parse_key_msg_keystroke(wparam);
438        if let Some(keystroke) = keystroke {
439            if let Some(callback) = callbacks.input.as_mut() {
440                let event = KeyUpEvent { keystroke };
441                let by_callback = callback(PlatformInput::KeyUp(event));
442                CallbackResult::Handled { by_callback }
443            } else {
444                CallbackResult::Handled { by_callback: false }
445            }
446        } else {
447            CallbackResult::Unhandled
448        }
449    }
450
451    fn handle_char_msg(&self, wparam: WPARAM) -> LRESULT {
452        let mut callbacks = self.callbacks.borrow_mut();
453        if let Some(callback) = callbacks.input.as_mut() {
454            let modifiers = self.current_modifiers();
455            let msg_char = wparam.0 as u8 as char;
456            let keystroke = Keystroke {
457                modifiers,
458                key: msg_char.to_string(),
459                ime_key: Some(msg_char.to_string()),
460            };
461            let ime_key = keystroke.ime_key.clone();
462            let event = KeyDownEvent {
463                keystroke,
464                is_held: false,
465            };
466
467            if callback(PlatformInput::KeyDown(event)) {
468                return LRESULT(0);
469            }
470
471            if let Some(mut input_handler) = self.input_handler.take() {
472                if let Some(ime_key) = ime_key {
473                    input_handler.replace_text_in_range(None, &ime_key);
474                }
475                self.input_handler.set(Some(input_handler));
476                return LRESULT(0);
477            }
478        }
479        return LRESULT(1);
480    }
481
482    fn handle_mouse_down_msg(&self, button: MouseButton, lparam: LPARAM) -> LRESULT {
483        let mut callbacks = self.callbacks.borrow_mut();
484        if let Some(callback) = callbacks.input.as_mut() {
485            let x = Pixels::from(lparam.signed_loword() as f32);
486            let y = Pixels::from(lparam.signed_hiword() as f32);
487            let event = MouseDownEvent {
488                button,
489                position: Point { x, y },
490                modifiers: self.current_modifiers(),
491                click_count: 1,
492            };
493            if callback(PlatformInput::MouseDown(event)) {
494                return LRESULT(0);
495            }
496        }
497        LRESULT(1)
498    }
499
500    fn handle_mouse_up_msg(&self, button: MouseButton, lparam: LPARAM) -> LRESULT {
501        let mut callbacks = self.callbacks.borrow_mut();
502        if let Some(callback) = callbacks.input.as_mut() {
503            let x = Pixels::from(lparam.signed_loword() as f32);
504            let y = Pixels::from(lparam.signed_hiword() as f32);
505            let event = MouseUpEvent {
506                button,
507                position: Point { x, y },
508                modifiers: self.current_modifiers(),
509                click_count: 1,
510            };
511            if callback(PlatformInput::MouseUp(event)) {
512                return LRESULT(0);
513            }
514        }
515        LRESULT(1)
516    }
517
518    fn handle_mouse_wheel_msg(&self, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
519        let mut callbacks = self.callbacks.borrow_mut();
520        if let Some(callback) = callbacks.input.as_mut() {
521            let x = Pixels::from(lparam.signed_loword() as f32);
522            let y = Pixels::from(lparam.signed_hiword() as f32);
523            let wheel_distance = (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32)
524                * self.platform_inner.settings.borrow().wheel_scroll_lines as f32;
525            let event = crate::ScrollWheelEvent {
526                position: Point { x, y },
527                delta: ScrollDelta::Lines(Point {
528                    x: 0.0,
529                    y: wheel_distance,
530                }),
531                modifiers: self.current_modifiers(),
532                touch_phase: TouchPhase::Moved,
533            };
534            callback(PlatformInput::ScrollWheel(event));
535            return LRESULT(0);
536        }
537        LRESULT(1)
538    }
539
540    fn handle_mouse_horizontal_wheel_msg(&self, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
541        let mut callbacks = self.callbacks.borrow_mut();
542        if let Some(callback) = callbacks.input.as_mut() {
543            let x = Pixels::from(lparam.signed_loword() as f32);
544            let y = Pixels::from(lparam.signed_hiword() as f32);
545            let wheel_distance = (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32)
546                * self.platform_inner.settings.borrow().wheel_scroll_chars as f32;
547            let event = crate::ScrollWheelEvent {
548                position: Point { x, y },
549                delta: ScrollDelta::Lines(Point {
550                    x: wheel_distance,
551                    y: 0.0,
552                }),
553                modifiers: self.current_modifiers(),
554                touch_phase: TouchPhase::Moved,
555            };
556            if callback(PlatformInput::ScrollWheel(event)) {
557                return LRESULT(0);
558            }
559        }
560        LRESULT(1)
561    }
562}
563
564#[derive(Default)]
565struct Callbacks {
566    request_frame: Option<Box<dyn FnMut()>>,
567    input: Option<Box<dyn FnMut(crate::PlatformInput) -> bool>>,
568    active_status_change: Option<Box<dyn FnMut(bool)>>,
569    resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
570    fullscreen: Option<Box<dyn FnMut(bool)>>,
571    moved: Option<Box<dyn FnMut()>>,
572    should_close: Option<Box<dyn FnMut() -> bool>>,
573    close: Option<Box<dyn FnOnce()>>,
574    appearance_changed: Option<Box<dyn FnMut()>>,
575}
576
577pub(crate) struct WindowsWindow {
578    inner: Rc<WindowsWindowInner>,
579}
580
581struct WindowCreateContext {
582    inner: Option<Rc<WindowsWindowInner>>,
583    platform_inner: Rc<WindowsPlatformInner>,
584    handle: AnyWindowHandle,
585}
586
587impl WindowsWindow {
588    pub(crate) fn new(
589        platform_inner: Rc<WindowsPlatformInner>,
590        handle: AnyWindowHandle,
591        options: WindowOptions,
592    ) -> Self {
593        let dwexstyle = WINDOW_EX_STYLE::default();
594        let classname = register_wnd_class();
595        let windowname = HSTRING::from(
596            options
597                .titlebar
598                .as_ref()
599                .and_then(|titlebar| titlebar.title.as_ref())
600                .map(|title| title.as_ref())
601                .unwrap_or(""),
602        );
603        let dwstyle = WS_OVERLAPPEDWINDOW & !WS_VISIBLE;
604        let mut x = CW_USEDEFAULT;
605        let mut y = CW_USEDEFAULT;
606        let mut nwidth = CW_USEDEFAULT;
607        let mut nheight = CW_USEDEFAULT;
608        match options.bounds {
609            WindowBounds::Fullscreen => {}
610            WindowBounds::Maximized => {}
611            WindowBounds::Fixed(bounds) => {
612                x = bounds.origin.x.0 as i32;
613                y = bounds.origin.y.0 as i32;
614                nwidth = bounds.size.width.0 as i32;
615                nheight = bounds.size.height.0 as i32;
616            }
617        };
618        let hwndparent = HWND::default();
619        let hmenu = HMENU::default();
620        let hinstance = HINSTANCE::default();
621        let mut context = WindowCreateContext {
622            inner: None,
623            platform_inner: platform_inner.clone(),
624            handle,
625        };
626        let lpparam = Some(&context as *const _ as *const _);
627        unsafe {
628            CreateWindowExW(
629                dwexstyle,
630                classname,
631                &windowname,
632                dwstyle,
633                x,
634                y,
635                nwidth,
636                nheight,
637                hwndparent,
638                hmenu,
639                hinstance,
640                lpparam,
641            )
642        };
643        let wnd = Self {
644            inner: context.inner.unwrap(),
645        };
646        platform_inner.window_handles.borrow_mut().insert(handle);
647        match options.bounds {
648            WindowBounds::Fullscreen => wnd.toggle_full_screen(),
649            WindowBounds::Maximized => wnd.maximize(),
650            WindowBounds::Fixed(_) => {}
651        }
652        unsafe { ShowWindow(wnd.inner.hwnd, SW_SHOW) };
653        wnd
654    }
655
656    fn maximize(&self) {
657        unsafe { ShowWindow(self.inner.hwnd, SW_MAXIMIZE) };
658    }
659}
660
661impl HasWindowHandle for WindowsWindow {
662    fn window_handle(
663        &self,
664    ) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
665        let raw = raw_window_handle::Win32WindowHandle::new(unsafe {
666            NonZeroIsize::new_unchecked(self.inner.hwnd.0)
667        })
668        .into();
669        Ok(unsafe { raw_window_handle::WindowHandle::borrow_raw(raw) })
670    }
671}
672
673// todo(windows)
674impl HasDisplayHandle for WindowsWindow {
675    fn display_handle(
676        &self,
677    ) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
678        unimplemented!()
679    }
680}
681
682impl PlatformWindow for WindowsWindow {
683    fn bounds(&self) -> WindowBounds {
684        WindowBounds::Fixed(Bounds {
685            origin: self.inner.origin.get(),
686            size: self.inner.size.get(),
687        })
688    }
689
690    // todo(windows)
691    fn content_size(&self) -> Size<Pixels> {
692        let size = self.inner.size.get();
693        Size {
694            width: size.width.0.into(),
695            height: size.height.0.into(),
696        }
697    }
698
699    // todo(windows)
700    fn scale_factor(&self) -> f32 {
701        1.0
702    }
703
704    // todo(windows)
705    fn titlebar_height(&self) -> Pixels {
706        20.0.into()
707    }
708
709    // todo(windows)
710    fn appearance(&self) -> WindowAppearance {
711        WindowAppearance::Dark
712    }
713
714    // todo(windows)
715    fn display(&self) -> Rc<dyn PlatformDisplay> {
716        Rc::new(WindowsDisplay::new())
717    }
718
719    fn mouse_position(&self) -> Point<Pixels> {
720        self.inner.mouse_position.get()
721    }
722
723    // todo(windows)
724    fn modifiers(&self) -> Modifiers {
725        Modifiers::none()
726    }
727
728    fn as_any_mut(&mut self) -> &mut dyn Any {
729        self
730    }
731
732    // todo(windows)
733    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
734        self.inner.input_handler.set(Some(input_handler));
735    }
736
737    // todo(windows)
738    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
739        self.inner.input_handler.take()
740    }
741
742    // todo(windows)
743    fn prompt(
744        &self,
745        level: PromptLevel,
746        msg: &str,
747        detail: Option<&str>,
748        answers: &[&str],
749    ) -> Option<Receiver<usize>> {
750        unimplemented!()
751    }
752
753    // todo(windows)
754    fn activate(&self) {}
755
756    // todo(windows)
757    fn set_title(&mut self, title: &str) {
758        unsafe { SetWindowTextW(self.inner.hwnd, &HSTRING::from(title)) }
759            .inspect_err(|e| log::error!("Set title failed: {e}"))
760            .ok();
761    }
762
763    // todo(windows)
764    fn set_edited(&mut self, edited: bool) {}
765
766    // todo(windows)
767    fn show_character_palette(&self) {}
768
769    // todo(windows)
770    fn minimize(&self) {}
771
772    // todo(windows)
773    fn zoom(&self) {}
774
775    // todo(windows)
776    fn toggle_full_screen(&self) {}
777
778    // todo(windows)
779    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
780        self.inner.callbacks.borrow_mut().request_frame = Some(callback);
781    }
782
783    // todo(windows)
784    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
785        self.inner.callbacks.borrow_mut().input = Some(callback);
786    }
787
788    // todo(windows)
789    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
790        self.inner.callbacks.borrow_mut().active_status_change = Some(callback);
791    }
792
793    // todo(windows)
794    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
795        self.inner.callbacks.borrow_mut().resize = Some(callback);
796    }
797
798    // todo(windows)
799    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
800        self.inner.callbacks.borrow_mut().fullscreen = Some(callback);
801    }
802
803    // todo(windows)
804    fn on_moved(&self, callback: Box<dyn FnMut()>) {
805        self.inner.callbacks.borrow_mut().moved = Some(callback);
806    }
807
808    // todo(windows)
809    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
810        self.inner.callbacks.borrow_mut().should_close = Some(callback);
811    }
812
813    // todo(windows)
814    fn on_close(&self, callback: Box<dyn FnOnce()>) {
815        self.inner.callbacks.borrow_mut().close = Some(callback);
816    }
817
818    // todo(windows)
819    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
820        self.inner.callbacks.borrow_mut().appearance_changed = Some(callback);
821    }
822
823    // todo(windows)
824    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
825        true
826    }
827
828    // todo(windows)
829    fn draw(&self, scene: &Scene) {
830        self.inner.renderer.borrow_mut().draw(scene)
831    }
832
833    // todo(windows)
834    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
835        self.inner.renderer.borrow().sprite_atlas().clone()
836    }
837}
838
839fn register_wnd_class() -> PCWSTR {
840    const CLASS_NAME: PCWSTR = w!("Zed::Window");
841
842    static ONCE: Once = Once::new();
843    ONCE.call_once(|| {
844        let wc = WNDCLASSW {
845            lpfnWndProc: Some(wnd_proc),
846            hCursor: unsafe { LoadCursorW(None, IDC_ARROW).ok().unwrap() },
847            lpszClassName: PCWSTR(CLASS_NAME.as_ptr()),
848            ..Default::default()
849        };
850        unsafe { RegisterClassW(&wc) };
851    });
852
853    CLASS_NAME
854}
855
856unsafe extern "system" fn wnd_proc(
857    hwnd: HWND,
858    msg: u32,
859    wparam: WPARAM,
860    lparam: LPARAM,
861) -> LRESULT {
862    if msg == WM_NCCREATE {
863        let cs = lparam.0 as *const CREATESTRUCTW;
864        let cs = unsafe { &*cs };
865        let ctx = cs.lpCreateParams as *mut WindowCreateContext;
866        let ctx = unsafe { &mut *ctx };
867        let inner = Rc::new(WindowsWindowInner::new(
868            hwnd,
869            cs,
870            ctx.platform_inner.clone(),
871            ctx.handle,
872        ));
873        let weak = Box::new(Rc::downgrade(&inner));
874        unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
875        ctx.inner = Some(inner);
876        return LRESULT(1);
877    }
878    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
879    if ptr.is_null() {
880        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
881    }
882    let inner = unsafe { &*ptr };
883    let r = if let Some(inner) = inner.upgrade() {
884        inner.handle_msg(msg, wparam, lparam)
885    } else {
886        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
887    };
888    if msg == WM_NCDESTROY {
889        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
890        unsafe { std::mem::drop(Box::from_raw(ptr)) };
891    }
892    r
893}
894
895pub(crate) fn try_get_window_inner(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
896    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
897    if !ptr.is_null() {
898        let inner = unsafe { &*ptr };
899        inner.upgrade()
900    } else {
901        None
902    }
903}
904
905unsafe fn get_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX) -> isize {
906    #[cfg(target_pointer_width = "64")]
907    unsafe {
908        GetWindowLongPtrW(hwnd, nindex)
909    }
910    #[cfg(target_pointer_width = "32")]
911    unsafe {
912        GetWindowLongW(hwnd, nindex) as isize
913    }
914}
915
916unsafe fn set_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX, dwnewlong: isize) -> isize {
917    #[cfg(target_pointer_width = "64")]
918    unsafe {
919        SetWindowLongPtrW(hwnd, nindex, dwnewlong)
920    }
921    #[cfg(target_pointer_width = "32")]
922    unsafe {
923        SetWindowLongW(hwnd, nindex, dwnewlong as i32) as isize
924    }
925}