window.rs

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