window.rs

  1use std::any::Any;
  2use std::cell::{Ref, RefCell, RefMut};
  3use std::ffi::c_void;
  4use std::num::NonZeroU32;
  5use std::ptr::NonNull;
  6use std::rc::{Rc, Weak};
  7use std::sync::Arc;
  8
  9use blade_graphics as gpu;
 10use collections::{HashMap, HashSet};
 11use futures::channel::oneshot::Receiver;
 12use raw_window_handle as rwh;
 13use wayland_backend::client::ObjectId;
 14use wayland_client::WEnum;
 15use wayland_client::{protocol::wl_surface, Proxy};
 16use wayland_protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1;
 17use wayland_protocols::wp::viewporter::client::wp_viewport;
 18use wayland_protocols::xdg::decoration::zv1::client::zxdg_toplevel_decoration_v1;
 19use wayland_protocols::xdg::shell::client::xdg_surface;
 20use wayland_protocols::xdg::shell::client::xdg_toplevel::{self, WmCapabilities};
 21
 22use crate::platform::blade::BladeRenderer;
 23use crate::platform::linux::wayland::display::WaylandDisplay;
 24use crate::platform::{PlatformAtlas, PlatformInputHandler, PlatformWindow};
 25use crate::scene::Scene;
 26use crate::{
 27    px, size, Bounds, DevicePixels, Globals, Modifiers, Pixels, PlatformDisplay, PlatformInput,
 28    Point, PromptLevel, Size, WaylandClientState, WaylandClientStatePtr, WindowAppearance,
 29    WindowBackgroundAppearance, WindowParams,
 30};
 31
 32#[derive(Default)]
 33pub(crate) struct Callbacks {
 34    request_frame: Option<Box<dyn FnMut()>>,
 35    input: Option<Box<dyn FnMut(crate::PlatformInput) -> crate::DispatchEventResult>>,
 36    active_status_change: Option<Box<dyn FnMut(bool)>>,
 37    resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 38    fullscreen: Option<Box<dyn FnMut(bool)>>,
 39    moved: Option<Box<dyn FnMut()>>,
 40    should_close: Option<Box<dyn FnMut() -> bool>>,
 41    close: Option<Box<dyn FnOnce()>>,
 42    appearance_changed: Option<Box<dyn FnMut()>>,
 43}
 44
 45struct RawWindow {
 46    window: *mut c_void,
 47    display: *mut c_void,
 48}
 49
 50impl rwh::HasWindowHandle for RawWindow {
 51    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
 52        let window = NonNull::new(self.window).unwrap();
 53        let handle = rwh::WaylandWindowHandle::new(window);
 54        Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
 55    }
 56}
 57impl rwh::HasDisplayHandle for RawWindow {
 58    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
 59        let display = NonNull::new(self.display).unwrap();
 60        let handle = rwh::WaylandDisplayHandle::new(display);
 61        Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
 62    }
 63}
 64
 65pub struct WaylandWindowState {
 66    xdg_surface: xdg_surface::XdgSurface,
 67    acknowledged_first_configure: bool,
 68    pub surface: wl_surface::WlSurface,
 69    decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
 70    toplevel: xdg_toplevel::XdgToplevel,
 71    viewport: Option<wp_viewport::WpViewport>,
 72    outputs: HashSet<ObjectId>,
 73    globals: Globals,
 74    renderer: BladeRenderer,
 75    bounds: Bounds<u32>,
 76    scale: f32,
 77    input_handler: Option<PlatformInputHandler>,
 78    decoration_state: WaylandDecorationState,
 79    fullscreen: bool,
 80    maximized: bool,
 81    client: WaylandClientStatePtr,
 82    callbacks: Callbacks,
 83}
 84
 85#[derive(Clone)]
 86pub struct WaylandWindowStatePtr {
 87    state: Rc<RefCell<WaylandWindowState>>,
 88    callbacks: Rc<RefCell<Callbacks>>,
 89}
 90
 91impl WaylandWindowState {
 92    #[allow(clippy::too_many_arguments)]
 93    pub(crate) fn new(
 94        surface: wl_surface::WlSurface,
 95        xdg_surface: xdg_surface::XdgSurface,
 96        toplevel: xdg_toplevel::XdgToplevel,
 97        decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
 98        viewport: Option<wp_viewport::WpViewport>,
 99        client: WaylandClientStatePtr,
100        globals: Globals,
101        options: WindowParams,
102    ) -> Self {
103        let bounds = options.bounds.map(|p| p.0 as u32);
104
105        let raw = RawWindow {
106            window: surface.id().as_ptr().cast::<c_void>(),
107            display: surface
108                .backend()
109                .upgrade()
110                .unwrap()
111                .display_ptr()
112                .cast::<c_void>(),
113        };
114        let gpu = Arc::new(
115            unsafe {
116                gpu::Context::init_windowed(
117                    &raw,
118                    gpu::ContextDesc {
119                        validation: false,
120                        capture: false,
121                        overlay: false,
122                    },
123                )
124            }
125            .unwrap(),
126        );
127        let extent = gpu::Extent {
128            width: bounds.size.width,
129            height: bounds.size.height,
130            depth: 1,
131        };
132
133        Self {
134            xdg_surface,
135            acknowledged_first_configure: false,
136            surface,
137            decoration,
138            toplevel,
139            viewport,
140            globals,
141
142            outputs: HashSet::default(),
143
144            renderer: BladeRenderer::new(gpu, extent),
145            bounds,
146            scale: 1.0,
147            input_handler: None,
148            decoration_state: WaylandDecorationState::Client,
149            fullscreen: false,
150            maximized: false,
151            callbacks: Callbacks::default(),
152            client,
153        }
154    }
155}
156
157pub(crate) struct WaylandWindow(pub WaylandWindowStatePtr);
158
159impl Drop for WaylandWindow {
160    fn drop(&mut self) {
161        let mut state = self.0.state.borrow_mut();
162        let surface_id = state.surface.id();
163        let client = state.client.clone();
164
165        state.renderer.destroy();
166        if let Some(decoration) = &state.decoration {
167            decoration.destroy();
168        }
169        state.toplevel.destroy();
170        if let Some(viewport) = &state.viewport {
171            viewport.destroy();
172        }
173        state.xdg_surface.destroy();
174        state.surface.destroy();
175
176        let state_ptr = self.0.clone();
177        state
178            .globals
179            .executor
180            .spawn(async move {
181                state_ptr.close();
182                client.drop_window(&surface_id)
183            })
184            .detach();
185        drop(state);
186    }
187}
188
189impl WaylandWindow {
190    fn borrow(&self) -> Ref<WaylandWindowState> {
191        self.0.state.borrow()
192    }
193
194    fn borrow_mut(&self) -> RefMut<WaylandWindowState> {
195        self.0.state.borrow_mut()
196    }
197
198    pub fn new(
199        globals: Globals,
200        client: WaylandClientStatePtr,
201        params: WindowParams,
202    ) -> (Self, ObjectId) {
203        let surface = globals.compositor.create_surface(&globals.qh, ());
204        let xdg_surface = globals
205            .wm_base
206            .get_xdg_surface(&surface, &globals.qh, surface.id());
207        let toplevel = xdg_surface.get_toplevel(&globals.qh, surface.id());
208
209        if let Some(fractional_scale_manager) = globals.fractional_scale_manager.as_ref() {
210            fractional_scale_manager.get_fractional_scale(&surface, &globals.qh, surface.id());
211        }
212
213        // Attempt to set up window decorations based on the requested configuration
214        let decoration = globals
215            .decoration_manager
216            .as_ref()
217            .map(|decoration_manager| {
218                let decoration = decoration_manager.get_toplevel_decoration(
219                    &toplevel,
220                    &globals.qh,
221                    surface.id(),
222                );
223                decoration.set_mode(zxdg_toplevel_decoration_v1::Mode::ClientSide);
224                decoration
225            });
226
227        let viewport = globals
228            .viewporter
229            .as_ref()
230            .map(|viewporter| viewporter.get_viewport(&surface, &globals.qh, ()));
231
232        let this = Self(WaylandWindowStatePtr {
233            state: Rc::new(RefCell::new(WaylandWindowState::new(
234                surface.clone(),
235                xdg_surface,
236                toplevel,
237                decoration,
238                viewport,
239                client,
240                globals,
241                params,
242            ))),
243            callbacks: Rc::new(RefCell::new(Callbacks::default())),
244        });
245
246        // Kick things off
247        surface.commit();
248
249        (this, surface.id())
250    }
251}
252
253impl WaylandWindowStatePtr {
254    pub fn surface(&self) -> wl_surface::WlSurface {
255        self.state.borrow().surface.clone()
256    }
257
258    pub fn ptr_eq(&self, other: &Self) -> bool {
259        Rc::ptr_eq(&self.state, &other.state)
260    }
261
262    pub fn frame(&self, request_frame_callback: bool) {
263        if request_frame_callback {
264            let state = self.state.borrow_mut();
265            state.surface.frame(&state.globals.qh, state.surface.id());
266            drop(state);
267        }
268        let mut cb = self.callbacks.borrow_mut();
269        if let Some(fun) = cb.request_frame.as_mut() {
270            fun();
271        }
272    }
273
274    pub fn handle_xdg_surface_event(&self, event: xdg_surface::Event) {
275        match event {
276            xdg_surface::Event::Configure { serial } => {
277                let mut state = self.state.borrow_mut();
278                state.xdg_surface.ack_configure(serial);
279                let request_frame_callback = !state.acknowledged_first_configure;
280                state.acknowledged_first_configure = true;
281                drop(state);
282                self.frame(request_frame_callback);
283            }
284            _ => {}
285        }
286    }
287
288    pub fn handle_toplevel_decoration_event(&self, event: zxdg_toplevel_decoration_v1::Event) {
289        match event {
290            zxdg_toplevel_decoration_v1::Event::Configure { mode } => match mode {
291                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
292                    self.set_decoration_state(WaylandDecorationState::Server)
293                }
294                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
295                    self.set_decoration_state(WaylandDecorationState::Server)
296                }
297                WEnum::Value(_) => {
298                    log::warn!("Unknown decoration mode");
299                }
300                WEnum::Unknown(v) => {
301                    log::warn!("Unknown decoration mode: {}", v);
302                }
303            },
304            _ => {}
305        }
306    }
307
308    pub fn handle_fractional_scale_event(&self, event: wp_fractional_scale_v1::Event) {
309        match event {
310            wp_fractional_scale_v1::Event::PreferredScale { scale } => {
311                self.rescale(scale as f32 / 120.0);
312            }
313            _ => {}
314        }
315    }
316
317    pub fn handle_toplevel_event(&self, event: xdg_toplevel::Event) -> bool {
318        match event {
319            xdg_toplevel::Event::Configure {
320                width,
321                height,
322                states,
323            } => {
324                let width = NonZeroU32::new(width as u32);
325                let height = NonZeroU32::new(height as u32);
326                let fullscreen = states.contains(&(xdg_toplevel::State::Fullscreen as u8));
327                let maximized = states.contains(&(xdg_toplevel::State::Maximized as u8));
328                self.resize(width, height);
329                self.set_fullscreen(fullscreen);
330                let mut state = self.state.borrow_mut();
331                state.maximized = maximized;
332
333                false
334            }
335            xdg_toplevel::Event::Close => {
336                let mut cb = self.callbacks.borrow_mut();
337                if let Some(mut should_close) = cb.should_close.take() {
338                    let result = (should_close)();
339                    cb.should_close = Some(should_close);
340                    if result {
341                        drop(cb);
342                        self.close();
343                    }
344                    result
345                } else {
346                    true
347                }
348            }
349            _ => false,
350        }
351    }
352
353    pub fn handle_surface_event(
354        &self,
355        event: wl_surface::Event,
356        output_scales: HashMap<ObjectId, i32>,
357    ) {
358        let mut state = self.state.borrow_mut();
359
360        // We use `WpFractionalScale` instead to set the scale if it's available
361        if state.globals.fractional_scale_manager.is_some() {
362            return;
363        }
364
365        match event {
366            wl_surface::Event::Enter { output } => {
367                // We use `PreferredBufferScale` instead to set the scale if it's available
368                if state.surface.version() >= wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
369                    return;
370                }
371
372                state.outputs.insert(output.id());
373
374                let mut scale = 1;
375                for output in state.outputs.iter() {
376                    if let Some(s) = output_scales.get(output) {
377                        scale = scale.max(*s)
378                    }
379                }
380
381                state.surface.set_buffer_scale(scale);
382                drop(state);
383                self.rescale(scale as f32);
384            }
385            wl_surface::Event::Leave { output } => {
386                // We use `PreferredBufferScale` instead to set the scale if it's available
387                if state.surface.version() >= wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
388                    return;
389                }
390
391                state.outputs.remove(&output.id());
392
393                let mut scale = 1;
394                for output in state.outputs.iter() {
395                    if let Some(s) = output_scales.get(output) {
396                        scale = scale.max(*s)
397                    }
398                }
399
400                state.surface.set_buffer_scale(scale);
401                drop(state);
402                self.rescale(scale as f32);
403            }
404            wl_surface::Event::PreferredBufferScale { factor } => {
405                state.surface.set_buffer_scale(factor);
406                drop(state);
407                self.rescale(factor as f32);
408            }
409            _ => {}
410        }
411    }
412
413    pub fn set_size_and_scale(
414        &self,
415        width: Option<NonZeroU32>,
416        height: Option<NonZeroU32>,
417        scale: Option<f32>,
418    ) {
419        let (width, height, scale) = {
420            let mut state = self.state.borrow_mut();
421            if width.map_or(true, |width| width.get() == state.bounds.size.width)
422                && height.map_or(true, |height| height.get() == state.bounds.size.height)
423                && scale.map_or(true, |scale| scale == state.scale)
424            {
425                return;
426            }
427            if let Some(width) = width {
428                state.bounds.size.width = width.get();
429            }
430            if let Some(height) = height {
431                state.bounds.size.height = height.get();
432            }
433            if let Some(scale) = scale {
434                state.scale = scale;
435            }
436            let width = state.bounds.size.width;
437            let height = state.bounds.size.height;
438            let scale = state.scale;
439            state.renderer.update_drawable_size(size(
440                width as f64 * scale as f64,
441                height as f64 * scale as f64,
442            ));
443            (width, height, scale)
444        };
445
446        if let Some(ref mut fun) = self.callbacks.borrow_mut().resize {
447            fun(
448                Size {
449                    width: px(width as f32),
450                    height: px(height as f32),
451                },
452                scale,
453            );
454        }
455
456        {
457            let state = self.state.borrow();
458            if let Some(viewport) = &state.viewport {
459                viewport.set_destination(width as i32, height as i32);
460            }
461        }
462    }
463
464    pub fn resize(&self, width: Option<NonZeroU32>, height: Option<NonZeroU32>) {
465        self.set_size_and_scale(width, height, None);
466    }
467
468    pub fn rescale(&self, scale: f32) {
469        self.set_size_and_scale(None, None, Some(scale));
470    }
471
472    pub fn set_fullscreen(&self, fullscreen: bool) {
473        let mut state = self.state.borrow_mut();
474        state.fullscreen = fullscreen;
475
476        let mut callbacks = self.callbacks.borrow_mut();
477        if let Some(ref mut fun) = callbacks.fullscreen {
478            fun(fullscreen)
479        }
480    }
481
482    /// Notifies the window of the state of the decorations.
483    ///
484    /// # Note
485    ///
486    /// This API is indirectly called by the wayland compositor and
487    /// not meant to be called by a user who wishes to change the state
488    /// of the decorations. This is because the state of the decorations
489    /// is managed by the compositor and not the client.
490    pub fn set_decoration_state(&self, state: WaylandDecorationState) {
491        self.state.borrow_mut().decoration_state = state;
492    }
493
494    pub fn close(&self) {
495        let mut callbacks = self.callbacks.borrow_mut();
496        if let Some(fun) = callbacks.close.take() {
497            fun()
498        }
499    }
500
501    pub fn handle_input(&self, input: PlatformInput) {
502        if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
503            if !fun(input.clone()).propagate {
504                return;
505            }
506        }
507        if let PlatformInput::KeyDown(event) = input {
508            if let Some(ime_key) = &event.keystroke.ime_key {
509                let mut state = self.state.borrow_mut();
510                if let Some(mut input_handler) = state.input_handler.take() {
511                    drop(state);
512                    input_handler.replace_text_in_range(None, ime_key);
513                    self.state.borrow_mut().input_handler = Some(input_handler);
514                }
515            }
516        }
517    }
518
519    pub fn set_focused(&self, focus: bool) {
520        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
521            fun(focus);
522        }
523    }
524}
525
526impl rwh::HasWindowHandle for WaylandWindow {
527    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
528        unimplemented!()
529    }
530}
531impl rwh::HasDisplayHandle for WaylandWindow {
532    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
533        unimplemented!()
534    }
535}
536
537impl PlatformWindow for WaylandWindow {
538    fn bounds(&self) -> Bounds<DevicePixels> {
539        self.borrow().bounds.map(|p| DevicePixels(p as i32))
540    }
541
542    fn is_maximized(&self) -> bool {
543        self.borrow().maximized
544    }
545
546    fn is_minimized(&self) -> bool {
547        // This cannot be determined by the client
548        false
549    }
550
551    fn content_size(&self) -> Size<Pixels> {
552        let state = self.borrow();
553        Size {
554            width: Pixels(state.bounds.size.width as f32),
555            height: Pixels(state.bounds.size.height as f32),
556        }
557    }
558
559    fn scale_factor(&self) -> f32 {
560        self.borrow().scale
561    }
562
563    // todo(linux)
564    fn appearance(&self) -> WindowAppearance {
565        WindowAppearance::Light
566    }
567
568    // todo(linux)
569    fn display(&self) -> Rc<dyn PlatformDisplay> {
570        Rc::new(WaylandDisplay {})
571    }
572
573    // todo(linux)
574    fn mouse_position(&self) -> Point<Pixels> {
575        Point::default()
576    }
577
578    // todo(linux)
579    fn modifiers(&self) -> Modifiers {
580        crate::Modifiers::default()
581    }
582
583    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
584        self.borrow_mut().input_handler = Some(input_handler);
585    }
586
587    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
588        self.borrow_mut().input_handler.take()
589    }
590
591    fn prompt(
592        &self,
593        level: PromptLevel,
594        msg: &str,
595        detail: Option<&str>,
596        answers: &[&str],
597    ) -> Option<Receiver<usize>> {
598        None
599    }
600
601    fn activate(&self) {
602        // todo(linux)
603    }
604
605    // todo(linux)
606    fn is_active(&self) -> bool {
607        false
608    }
609
610    fn set_title(&mut self, title: &str) {
611        self.borrow_mut().toplevel.set_title(title.to_string());
612    }
613
614    fn set_app_id(&mut self, app_id: &str) {
615        self.borrow_mut().toplevel.set_app_id(app_id.to_owned());
616    }
617
618    fn set_background_appearance(&mut self, _background_appearance: WindowBackgroundAppearance) {
619        // todo(linux)
620    }
621
622    fn set_edited(&mut self, edited: bool) {
623        // todo(linux)
624    }
625
626    fn show_character_palette(&self) {
627        // todo(linux)
628    }
629
630    fn minimize(&self) {
631        self.borrow_mut().toplevel.set_minimized();
632    }
633
634    fn zoom(&self) {
635        // todo(linux)
636    }
637
638    fn toggle_fullscreen(&self) {
639        let state = self.borrow_mut();
640        if !state.fullscreen {
641            state.toplevel.set_fullscreen(None);
642        } else {
643            state.toplevel.unset_fullscreen();
644        }
645    }
646
647    fn is_fullscreen(&self) -> bool {
648        self.borrow().fullscreen
649    }
650
651    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
652        self.0.callbacks.borrow_mut().request_frame = Some(callback);
653    }
654
655    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
656        self.0.callbacks.borrow_mut().input = Some(callback);
657    }
658
659    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
660        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
661    }
662
663    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
664        self.0.callbacks.borrow_mut().resize = Some(callback);
665    }
666
667    fn on_moved(&self, callback: Box<dyn FnMut()>) {
668        self.0.callbacks.borrow_mut().moved = Some(callback);
669    }
670
671    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
672        self.0.callbacks.borrow_mut().should_close = Some(callback);
673    }
674
675    fn on_close(&self, callback: Box<dyn FnOnce()>) {
676        self.0.callbacks.borrow_mut().close = Some(callback);
677    }
678
679    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
680        // todo(linux)
681    }
682
683    fn draw(&self, scene: &Scene) {
684        let mut state = self.borrow_mut();
685        state.renderer.draw(scene);
686    }
687
688    fn completed_frame(&self) {
689        let mut state = self.borrow_mut();
690        state.surface.commit();
691    }
692
693    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
694        let state = self.borrow();
695        state.renderer.sprite_atlas().clone()
696    }
697}
698
699#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
700pub enum WaylandDecorationState {
701    /// Decorations are to be provided by the client
702    Client,
703
704    /// Decorations are provided by the server
705    Server,
706}