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 ptr_eq(&self, other: &Self) -> bool {
255        Rc::ptr_eq(&self.state, &other.state)
256    }
257
258    pub fn frame(&self, request_frame_callback: bool) {
259        if request_frame_callback {
260            let state = self.state.borrow_mut();
261            state.surface.frame(&state.globals.qh, state.surface.id());
262            drop(state);
263        }
264        let mut cb = self.callbacks.borrow_mut();
265        if let Some(fun) = cb.request_frame.as_mut() {
266            fun();
267        }
268    }
269
270    pub fn handle_xdg_surface_event(&self, event: xdg_surface::Event) {
271        match event {
272            xdg_surface::Event::Configure { serial } => {
273                let mut state = self.state.borrow_mut();
274                state.xdg_surface.ack_configure(serial);
275                let request_frame_callback = !state.acknowledged_first_configure;
276                state.acknowledged_first_configure = true;
277                drop(state);
278                self.frame(request_frame_callback);
279            }
280            _ => {}
281        }
282    }
283
284    pub fn handle_toplevel_decoration_event(&self, event: zxdg_toplevel_decoration_v1::Event) {
285        match event {
286            zxdg_toplevel_decoration_v1::Event::Configure { mode } => match mode {
287                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
288                    self.set_decoration_state(WaylandDecorationState::Server)
289                }
290                WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
291                    self.set_decoration_state(WaylandDecorationState::Server)
292                }
293                WEnum::Value(_) => {
294                    log::warn!("Unknown decoration mode");
295                }
296                WEnum::Unknown(v) => {
297                    log::warn!("Unknown decoration mode: {}", v);
298                }
299            },
300            _ => {}
301        }
302    }
303
304    pub fn handle_fractional_scale_event(&self, event: wp_fractional_scale_v1::Event) {
305        match event {
306            wp_fractional_scale_v1::Event::PreferredScale { scale } => {
307                self.rescale(scale as f32 / 120.0);
308            }
309            _ => {}
310        }
311    }
312
313    pub fn handle_toplevel_event(&self, event: xdg_toplevel::Event) -> bool {
314        match event {
315            xdg_toplevel::Event::Configure {
316                width,
317                height,
318                states,
319            } => {
320                let width = NonZeroU32::new(width as u32);
321                let height = NonZeroU32::new(height as u32);
322                let fullscreen = states.contains(&(xdg_toplevel::State::Fullscreen as u8));
323                let maximized = states.contains(&(xdg_toplevel::State::Maximized as u8));
324                self.resize(width, height);
325                self.set_fullscreen(fullscreen);
326                let mut state = self.state.borrow_mut();
327                state.maximized = maximized;
328
329                false
330            }
331            xdg_toplevel::Event::Close => {
332                let mut cb = self.callbacks.borrow_mut();
333                if let Some(mut should_close) = cb.should_close.take() {
334                    let result = (should_close)();
335                    cb.should_close = Some(should_close);
336                    if result {
337                        drop(cb);
338                        self.close();
339                    }
340                    result
341                } else {
342                    true
343                }
344            }
345            _ => false,
346        }
347    }
348
349    pub fn handle_surface_event(
350        &self,
351        event: wl_surface::Event,
352        output_scales: HashMap<ObjectId, i32>,
353    ) {
354        let mut state = self.state.borrow_mut();
355
356        // We use `WpFractionalScale` instead to set the scale if it's available
357        if state.globals.fractional_scale_manager.is_some() {
358            return;
359        }
360
361        match event {
362            wl_surface::Event::Enter { output } => {
363                // We use `PreferredBufferScale` instead to set the scale if it's available
364                if state.surface.version() >= wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
365                    return;
366                }
367
368                state.outputs.insert(output.id());
369
370                let mut scale = 1;
371                for output in state.outputs.iter() {
372                    if let Some(s) = output_scales.get(output) {
373                        scale = scale.max(*s)
374                    }
375                }
376
377                state.surface.set_buffer_scale(scale);
378                drop(state);
379                self.rescale(scale as f32);
380            }
381            wl_surface::Event::Leave { output } => {
382                // We use `PreferredBufferScale` instead to set the scale if it's available
383                if state.surface.version() >= wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE {
384                    return;
385                }
386
387                state.outputs.remove(&output.id());
388
389                let mut scale = 1;
390                for output in state.outputs.iter() {
391                    if let Some(s) = output_scales.get(output) {
392                        scale = scale.max(*s)
393                    }
394                }
395
396                state.surface.set_buffer_scale(scale);
397                drop(state);
398                self.rescale(scale as f32);
399            }
400            wl_surface::Event::PreferredBufferScale { factor } => {
401                state.surface.set_buffer_scale(factor);
402                drop(state);
403                self.rescale(factor as f32);
404            }
405            _ => {}
406        }
407    }
408
409    pub fn set_size_and_scale(
410        &self,
411        width: Option<NonZeroU32>,
412        height: Option<NonZeroU32>,
413        scale: Option<f32>,
414    ) {
415        let (width, height, scale) = {
416            let mut state = self.state.borrow_mut();
417            if width.map_or(true, |width| width.get() == state.bounds.size.width)
418                && height.map_or(true, |height| height.get() == state.bounds.size.height)
419                && scale.map_or(true, |scale| scale == state.scale)
420            {
421                return;
422            }
423            if let Some(width) = width {
424                state.bounds.size.width = width.get();
425            }
426            if let Some(height) = height {
427                state.bounds.size.height = height.get();
428            }
429            if let Some(scale) = scale {
430                state.scale = scale;
431            }
432            let width = state.bounds.size.width;
433            let height = state.bounds.size.height;
434            let scale = state.scale;
435            state.renderer.update_drawable_size(size(
436                width as f64 * scale as f64,
437                height as f64 * scale as f64,
438            ));
439            (width, height, scale)
440        };
441
442        if let Some(ref mut fun) = self.callbacks.borrow_mut().resize {
443            fun(
444                Size {
445                    width: px(width as f32),
446                    height: px(height as f32),
447                },
448                scale,
449            );
450        }
451
452        {
453            let state = self.state.borrow();
454            if let Some(viewport) = &state.viewport {
455                viewport.set_destination(width as i32, height as i32);
456            }
457        }
458    }
459
460    pub fn resize(&self, width: Option<NonZeroU32>, height: Option<NonZeroU32>) {
461        self.set_size_and_scale(width, height, None);
462    }
463
464    pub fn rescale(&self, scale: f32) {
465        self.set_size_and_scale(None, None, Some(scale));
466    }
467
468    pub fn set_fullscreen(&self, fullscreen: bool) {
469        let mut state = self.state.borrow_mut();
470        state.fullscreen = fullscreen;
471
472        let mut callbacks = self.callbacks.borrow_mut();
473        if let Some(ref mut fun) = callbacks.fullscreen {
474            fun(fullscreen)
475        }
476    }
477
478    /// Notifies the window of the state of the decorations.
479    ///
480    /// # Note
481    ///
482    /// This API is indirectly called by the wayland compositor and
483    /// not meant to be called by a user who wishes to change the state
484    /// of the decorations. This is because the state of the decorations
485    /// is managed by the compositor and not the client.
486    pub fn set_decoration_state(&self, state: WaylandDecorationState) {
487        self.state.borrow_mut().decoration_state = state;
488    }
489
490    pub fn close(&self) {
491        let mut callbacks = self.callbacks.borrow_mut();
492        if let Some(fun) = callbacks.close.take() {
493            fun()
494        }
495    }
496
497    pub fn handle_input(&self, input: PlatformInput) {
498        if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
499            if !fun(input.clone()).propagate {
500                return;
501            }
502        }
503        if let PlatformInput::KeyDown(event) = input {
504            if let Some(ime_key) = &event.keystroke.ime_key {
505                let mut state = self.state.borrow_mut();
506                if let Some(mut input_handler) = state.input_handler.take() {
507                    drop(state);
508                    input_handler.replace_text_in_range(None, ime_key);
509                    self.state.borrow_mut().input_handler = Some(input_handler);
510                }
511            }
512        }
513    }
514
515    pub fn set_focused(&self, focus: bool) {
516        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
517            fun(focus);
518        }
519    }
520}
521
522impl rwh::HasWindowHandle for WaylandWindow {
523    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
524        unimplemented!()
525    }
526}
527impl rwh::HasDisplayHandle for WaylandWindow {
528    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
529        unimplemented!()
530    }
531}
532
533impl PlatformWindow for WaylandWindow {
534    fn bounds(&self) -> Bounds<DevicePixels> {
535        self.borrow().bounds.map(|p| DevicePixels(p as i32))
536    }
537
538    fn is_maximized(&self) -> bool {
539        self.borrow().maximized
540    }
541
542    fn is_minimized(&self) -> bool {
543        // This cannot be determined by the client
544        false
545    }
546
547    fn content_size(&self) -> Size<Pixels> {
548        let state = self.borrow();
549        Size {
550            width: Pixels(state.bounds.size.width as f32),
551            height: Pixels(state.bounds.size.height as f32),
552        }
553    }
554
555    fn scale_factor(&self) -> f32 {
556        self.borrow().scale
557    }
558
559    // todo(linux)
560    fn appearance(&self) -> WindowAppearance {
561        WindowAppearance::Light
562    }
563
564    // todo(linux)
565    fn display(&self) -> Rc<dyn PlatformDisplay> {
566        Rc::new(WaylandDisplay {})
567    }
568
569    // todo(linux)
570    fn mouse_position(&self) -> Point<Pixels> {
571        Point::default()
572    }
573
574    // todo(linux)
575    fn modifiers(&self) -> Modifiers {
576        crate::Modifiers::default()
577    }
578
579    fn as_any_mut(&mut self) -> &mut dyn Any {
580        self
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_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
668        self.0.callbacks.borrow_mut().fullscreen = Some(callback);
669    }
670
671    fn on_moved(&self, callback: Box<dyn FnMut()>) {
672        self.0.callbacks.borrow_mut().moved = Some(callback);
673    }
674
675    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
676        self.0.callbacks.borrow_mut().should_close = Some(callback);
677    }
678
679    fn on_close(&self, callback: Box<dyn FnOnce()>) {
680        self.0.callbacks.borrow_mut().close = Some(callback);
681    }
682
683    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
684        // todo(linux)
685    }
686
687    // todo(linux)
688    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
689        false
690    }
691
692    fn draw(&self, scene: &Scene) {
693        let mut state = self.borrow_mut();
694        state.renderer.draw(scene);
695    }
696
697    fn completed_frame(&self) {
698        let mut state = self.borrow_mut();
699        state.surface.commit();
700    }
701
702    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
703        let state = self.borrow();
704        state.renderer.sprite_atlas().clone()
705    }
706}
707
708#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
709pub enum WaylandDecorationState {
710    /// Decorations are to be provided by the client
711    Client,
712
713    /// Decorations are provided by the server
714    Server,
715}