window.rs

  1use std::any::Any;
  2use std::cell::RefCell;
  3use std::ffi::c_void;
  4use std::num::NonZeroU32;
  5use std::rc::Rc;
  6use std::sync::Arc;
  7
  8use blade_graphics as gpu;
  9use blade_rwh::{HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle};
 10use collections::HashSet;
 11use futures::channel::oneshot::Receiver;
 12use raw_window_handle::{
 13    DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle,
 14};
 15use wayland_backend::client::ObjectId;
 16use wayland_client::{protocol::wl_surface, Proxy};
 17use wayland_protocols::wp::viewporter::client::wp_viewport;
 18use wayland_protocols::xdg::shell::client::xdg_toplevel;
 19
 20use crate::platform::blade::BladeRenderer;
 21use crate::platform::linux::wayland::display::WaylandDisplay;
 22use crate::platform::{PlatformAtlas, PlatformInputHandler, PlatformWindow};
 23use crate::scene::Scene;
 24use crate::{
 25    px, size, Bounds, Modifiers, Pixels, PlatformDisplay, PlatformInput, Point, PromptLevel, Size,
 26    WindowAppearance, WindowBounds, WindowOptions,
 27};
 28
 29#[derive(Default)]
 30pub(crate) struct Callbacks {
 31    request_frame: Option<Box<dyn FnMut()>>,
 32    input: Option<Box<dyn FnMut(crate::PlatformInput) -> bool>>,
 33    active_status_change: Option<Box<dyn FnMut(bool)>>,
 34    resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 35    fullscreen: Option<Box<dyn FnMut(bool)>>,
 36    moved: Option<Box<dyn FnMut()>>,
 37    should_close: Option<Box<dyn FnMut() -> bool>>,
 38    close: Option<Box<dyn FnOnce()>>,
 39    appearance_changed: Option<Box<dyn FnMut()>>,
 40}
 41
 42struct WaylandWindowInner {
 43    renderer: BladeRenderer,
 44    bounds: Bounds<u32>,
 45    scale: f32,
 46    fullscreen: bool,
 47    input_handler: Option<PlatformInputHandler>,
 48    decoration_state: WaylandDecorationState,
 49}
 50
 51struct RawWindow {
 52    window: *mut c_void,
 53    display: *mut c_void,
 54}
 55
 56unsafe impl HasRawWindowHandle for RawWindow {
 57    fn raw_window_handle(&self) -> RawWindowHandle {
 58        let mut wh = blade_rwh::WaylandWindowHandle::empty();
 59        wh.surface = self.window;
 60        wh.into()
 61    }
 62}
 63
 64unsafe impl HasRawDisplayHandle for RawWindow {
 65    fn raw_display_handle(&self) -> RawDisplayHandle {
 66        let mut dh = blade_rwh::WaylandDisplayHandle::empty();
 67        dh.display = self.display;
 68        dh.into()
 69    }
 70}
 71
 72impl WaylandWindowInner {
 73    fn new(wl_surf: &Arc<wl_surface::WlSurface>, bounds: Bounds<u32>) -> Self {
 74        let raw = RawWindow {
 75            window: wl_surf.id().as_ptr().cast::<c_void>(),
 76            display: wl_surf
 77                .backend()
 78                .upgrade()
 79                .unwrap()
 80                .display_ptr()
 81                .cast::<c_void>(),
 82        };
 83        let gpu = Arc::new(
 84            unsafe {
 85                gpu::Context::init_windowed(
 86                    &raw,
 87                    gpu::ContextDesc {
 88                        validation: false,
 89                        capture: false,
 90                        overlay: false,
 91                    },
 92                )
 93            }
 94            .unwrap(),
 95        );
 96        let extent = gpu::Extent {
 97            width: bounds.size.width,
 98            height: bounds.size.height,
 99            depth: 1,
100        };
101        Self {
102            renderer: BladeRenderer::new(gpu, extent),
103            bounds,
104            scale: 1.0,
105            fullscreen: false,
106            input_handler: None,
107
108            // On wayland, decorations are by default provided by the client
109            decoration_state: WaylandDecorationState::Client,
110        }
111    }
112}
113
114pub(crate) struct WaylandWindowState {
115    inner: RefCell<WaylandWindowInner>,
116    pub(crate) callbacks: RefCell<Callbacks>,
117    pub(crate) surface: Arc<wl_surface::WlSurface>,
118    pub(crate) toplevel: Arc<xdg_toplevel::XdgToplevel>,
119    pub(crate) outputs: RefCell<HashSet<ObjectId>>,
120    viewport: Option<wp_viewport::WpViewport>,
121}
122
123impl WaylandWindowState {
124    pub(crate) fn new(
125        wl_surf: Arc<wl_surface::WlSurface>,
126        viewport: Option<wp_viewport::WpViewport>,
127        toplevel: Arc<xdg_toplevel::XdgToplevel>,
128        options: WindowOptions,
129    ) -> Self {
130        if options.bounds == WindowBounds::Maximized {
131            toplevel.set_maximized();
132        } else if options.bounds == WindowBounds::Fullscreen {
133            toplevel.set_fullscreen(None);
134        }
135
136        let bounds: Bounds<u32> = match options.bounds {
137            WindowBounds::Fullscreen | WindowBounds::Maximized => Bounds {
138                origin: Point::default(),
139                size: Size {
140                    width: 500,
141                    height: 500,
142                }, // todo(implement)
143            },
144            WindowBounds::Fixed(bounds) => bounds.map(|p| p.0 as u32),
145        };
146
147        Self {
148            surface: Arc::clone(&wl_surf),
149            inner: RefCell::new(WaylandWindowInner::new(&wl_surf, bounds)),
150            callbacks: RefCell::new(Callbacks::default()),
151            outputs: RefCell::new(HashSet::default()),
152            toplevel,
153            viewport,
154        }
155    }
156
157    pub fn update(&self) {
158        let mut cb = self.callbacks.borrow_mut();
159        if let Some(mut fun) = cb.request_frame.take() {
160            drop(cb);
161            fun();
162            self.callbacks.borrow_mut().request_frame = Some(fun);
163        }
164    }
165
166    pub fn set_size_and_scale(
167        &self,
168        width: Option<NonZeroU32>,
169        height: Option<NonZeroU32>,
170        scale: Option<f32>,
171    ) {
172        let (width, height, scale) = {
173            let mut inner = self.inner.borrow_mut();
174            if width.map_or(true, |width| width.get() == inner.bounds.size.width)
175                && height.map_or(true, |height| height.get() == inner.bounds.size.height)
176                && scale.map_or(true, |scale| scale == inner.scale)
177            {
178                return;
179            }
180            if let Some(width) = width {
181                inner.bounds.size.width = width.get();
182            }
183            if let Some(height) = height {
184                inner.bounds.size.height = height.get();
185            }
186            if let Some(scale) = scale {
187                inner.scale = scale;
188            }
189            let width = inner.bounds.size.width;
190            let height = inner.bounds.size.height;
191            let scale = inner.scale;
192            inner.renderer.update_drawable_size(size(
193                width as f64 * scale as f64,
194                height as f64 * scale as f64,
195            ));
196            (width, height, scale)
197        };
198
199        if let Some(ref mut fun) = self.callbacks.borrow_mut().resize {
200            fun(
201                Size {
202                    width: px(width as f32),
203                    height: px(height as f32),
204                },
205                scale,
206            );
207        }
208
209        if let Some(viewport) = &self.viewport {
210            viewport.set_destination(width as i32, height as i32);
211        }
212    }
213
214    pub fn resize(&self, width: Option<NonZeroU32>, height: Option<NonZeroU32>) {
215        let scale = self.inner.borrow_mut().scale;
216        self.set_size_and_scale(width, height, None);
217    }
218
219    pub fn rescale(&self, scale: f32) {
220        self.set_size_and_scale(None, None, Some(scale));
221    }
222
223    pub fn set_fullscreen(&self, fullscreen: bool) {
224        let mut callbacks = self.callbacks.borrow_mut();
225        if let Some(ref mut fun) = callbacks.fullscreen {
226            fun(fullscreen)
227        }
228        self.inner.borrow_mut().fullscreen = fullscreen;
229    }
230
231    /// Notifies the window of the state of the decorations.
232    ///
233    /// # Note
234    ///
235    /// This API is indirectly called by the wayland compositor and
236    /// not meant to be called by a user who wishes to change the state
237    /// of the decorations. This is because the state of the decorations
238    /// is managed by the compositor and not the client.
239    pub fn set_decoration_state(&self, state: WaylandDecorationState) {
240        self.inner.borrow_mut().decoration_state = state;
241        log::trace!("Window decorations are now handled by {:?}", state);
242        // todo(linux) - Handle this properly
243    }
244
245    pub fn close(&self) {
246        let mut callbacks = self.callbacks.borrow_mut();
247        if let Some(fun) = callbacks.close.take() {
248            fun()
249        }
250        self.toplevel.destroy();
251    }
252
253    pub fn handle_input(&self, input: PlatformInput) {
254        if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
255            if fun(input.clone()) {
256                return;
257            }
258        }
259        if let PlatformInput::KeyDown(event) = input {
260            let mut inner = self.inner.borrow_mut();
261            if let Some(ref mut input_handler) = inner.input_handler {
262                if let Some(ime_key) = &event.keystroke.ime_key {
263                    input_handler.replace_text_in_range(None, ime_key);
264                }
265            }
266        }
267    }
268
269    pub fn set_focused(&self, focus: bool) {
270        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
271            fun(focus);
272        }
273    }
274}
275
276#[derive(Clone)]
277pub(crate) struct WaylandWindow(pub(crate) Rc<WaylandWindowState>);
278
279impl HasWindowHandle for WaylandWindow {
280    fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
281        unimplemented!()
282    }
283}
284
285impl HasDisplayHandle for WaylandWindow {
286    fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
287        unimplemented!()
288    }
289}
290
291impl PlatformWindow for WaylandWindow {
292    // todo(linux)
293    fn bounds(&self) -> WindowBounds {
294        WindowBounds::Maximized
295    }
296
297    fn content_size(&self) -> Size<Pixels> {
298        let inner = self.0.inner.borrow_mut();
299        Size {
300            width: Pixels(inner.bounds.size.width as f32),
301            height: Pixels(inner.bounds.size.height as f32),
302        }
303    }
304
305    fn scale_factor(&self) -> f32 {
306        self.0.inner.borrow_mut().scale
307    }
308
309    // todo(linux)
310    fn titlebar_height(&self) -> Pixels {
311        unimplemented!()
312    }
313
314    // todo(linux)
315    fn appearance(&self) -> WindowAppearance {
316        WindowAppearance::Light
317    }
318
319    // todo(linux)
320    fn display(&self) -> Rc<dyn PlatformDisplay> {
321        Rc::new(WaylandDisplay {})
322    }
323
324    // todo(linux)
325    fn mouse_position(&self) -> Point<Pixels> {
326        Point::default()
327    }
328
329    // todo(linux)
330    fn modifiers(&self) -> Modifiers {
331        crate::Modifiers::default()
332    }
333
334    // todo(linux)
335    fn as_any_mut(&mut self) -> &mut dyn Any {
336        unimplemented!()
337    }
338
339    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
340        self.0.inner.borrow_mut().input_handler = Some(input_handler);
341    }
342
343    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
344        self.0.inner.borrow_mut().input_handler.take()
345    }
346
347    fn prompt(
348        &self,
349        level: PromptLevel,
350        msg: &str,
351        detail: Option<&str>,
352        answers: &[&str],
353    ) -> Option<Receiver<usize>> {
354        None
355    }
356
357    fn activate(&self) {
358        // todo(linux)
359    }
360
361    fn set_title(&mut self, title: &str) {
362        self.0.toplevel.set_title(title.to_string());
363    }
364
365    fn set_edited(&mut self, edited: bool) {
366        // todo(linux)
367    }
368
369    fn show_character_palette(&self) {
370        // todo(linux)
371    }
372
373    fn minimize(&self) {
374        self.0.toplevel.set_minimized();
375    }
376
377    fn zoom(&self) {
378        // todo(linux)
379    }
380
381    fn toggle_full_screen(&self) {
382        if !self.0.inner.borrow_mut().fullscreen {
383            self.0.toplevel.set_fullscreen(None);
384        } else {
385            self.0.toplevel.unset_fullscreen();
386        }
387    }
388
389    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
390        self.0.callbacks.borrow_mut().request_frame = Some(callback);
391    }
392
393    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
394        self.0.callbacks.borrow_mut().input = Some(callback);
395    }
396
397    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
398        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
399    }
400
401    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
402        self.0.callbacks.borrow_mut().resize = Some(callback);
403    }
404
405    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
406        self.0.callbacks.borrow_mut().fullscreen = Some(callback);
407    }
408
409    fn on_moved(&self, callback: Box<dyn FnMut()>) {
410        self.0.callbacks.borrow_mut().moved = Some(callback);
411    }
412
413    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
414        self.0.callbacks.borrow_mut().should_close = Some(callback);
415    }
416
417    fn on_close(&self, callback: Box<dyn FnOnce()>) {
418        self.0.callbacks.borrow_mut().close = Some(callback);
419    }
420
421    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
422        // todo(linux)
423    }
424
425    // todo(linux)
426    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
427        false
428    }
429
430    fn draw(&self, scene: &Scene) {
431        let mut inner = self.0.inner.borrow_mut();
432        inner.renderer.draw(scene);
433    }
434
435    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
436        let inner = self.0.inner.borrow_mut();
437        inner.renderer.sprite_atlas().clone()
438    }
439}
440
441#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
442pub enum WaylandDecorationState {
443    /// Decorations are to be provided by the client
444    Client,
445
446    /// Decorations are provided by the server
447    Server,
448}