softbuffer/wayland/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use crate::{
    error::{InitError, SwResultExt},
    util, Rect, SoftBufferError,
};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle};
use std::{
    cell::RefCell,
    num::{NonZeroI32, NonZeroU32},
    rc::Rc,
};
use wayland_client::{
    backend::{Backend, ObjectId},
    globals::{registry_queue_init, GlobalListContents},
    protocol::{wl_registry, wl_shm, wl_surface},
    Connection, Dispatch, EventQueue, Proxy, QueueHandle,
};

mod buffer;
use buffer::WaylandBuffer;

struct State;

pub struct WaylandDisplayImpl<D: ?Sized> {
    conn: Option<Connection>,
    event_queue: RefCell<EventQueue<State>>,
    qh: QueueHandle<State>,
    shm: wl_shm::WlShm,

    /// The object that owns the display handle.
    ///
    /// This has to be dropped *after* the `conn` field, because the `conn` field implicitly borrows
    /// this.
    _display: D,
}

impl<D: HasDisplayHandle + ?Sized> WaylandDisplayImpl<D> {
    pub(crate) fn new(display: D) -> Result<Self, InitError<D>>
    where
        D: Sized,
    {
        let raw = display.display_handle()?.as_raw();
        let wayland_handle = match raw {
            RawDisplayHandle::Wayland(w) => w.display,
            _ => return Err(InitError::Unsupported(display)),
        };

        let backend = unsafe { Backend::from_foreign_display(wayland_handle.as_ptr().cast()) };
        let conn = Connection::from_backend(backend);
        let (globals, event_queue) =
            registry_queue_init(&conn).swbuf_err("Failed to make round trip to server")?;
        let qh = event_queue.handle();
        let shm: wl_shm::WlShm = globals
            .bind(&qh, 1..=1, ())
            .swbuf_err("Failed to instantiate Wayland Shm")?;
        Ok(Self {
            conn: Some(conn),
            event_queue: RefCell::new(event_queue),
            qh,
            shm,
            _display: display,
        })
    }

    fn conn(&self) -> &Connection {
        self.conn.as_ref().unwrap()
    }
}

impl<D: ?Sized> Drop for WaylandDisplayImpl<D> {
    fn drop(&mut self) {
        // Make sure the connection is dropped first.
        self.conn = None;
    }
}

pub struct WaylandImpl<D: ?Sized, W: ?Sized> {
    display: Rc<WaylandDisplayImpl<D>>,
    surface: Option<wl_surface::WlSurface>,
    buffers: Option<(WaylandBuffer, WaylandBuffer)>,
    size: Option<(NonZeroI32, NonZeroI32)>,

    /// The pointer to the window object.
    ///
    /// This has to be dropped *after* the `surface` field, because the `surface` field implicitly
    /// borrows this.
    window_handle: W,
}

impl<D: HasDisplayHandle + ?Sized, W: HasWindowHandle> WaylandImpl<D, W> {
    pub(crate) fn new(window: W, display: Rc<WaylandDisplayImpl<D>>) -> Result<Self, InitError<W>> {
        // Get the raw Wayland window.
        let raw = window.window_handle()?.as_raw();
        let wayland_handle = match raw {
            RawWindowHandle::Wayland(w) => w.surface,
            _ => return Err(InitError::Unsupported(window)),
        };

        let surface_id = unsafe {
            ObjectId::from_ptr(
                wl_surface::WlSurface::interface(),
                wayland_handle.as_ptr().cast(),
            )
        }
        .swbuf_err("Failed to create proxy for surface ID.")?;
        let surface = wl_surface::WlSurface::from_id(display.conn(), surface_id)
            .swbuf_err("Failed to create proxy for surface ID.")?;
        Ok(Self {
            display,
            surface: Some(surface),
            buffers: Default::default(),
            size: None,
            window_handle: window,
        })
    }

    /// Get the inner window handle.
    #[inline]
    pub fn window(&self) -> &W {
        &self.window_handle
    }

    pub fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) -> Result<(), SoftBufferError> {
        self.size = Some(
            (|| {
                let width = NonZeroI32::try_from(width).ok()?;
                let height = NonZeroI32::try_from(height).ok()?;
                Some((width, height))
            })()
            .ok_or(SoftBufferError::SizeOutOfRange { width, height })?,
        );
        Ok(())
    }

    pub fn buffer_mut(&mut self) -> Result<BufferImpl<'_, D, W>, SoftBufferError> {
        let (width, height) = self
            .size
            .expect("Must set size of surface before calling `buffer_mut()`");

        if let Some((_front, back)) = &mut self.buffers {
            // Block if back buffer not released yet
            if !back.released() {
                let mut event_queue = self.display.event_queue.borrow_mut();
                while !back.released() {
                    event_queue.blocking_dispatch(&mut State).map_err(|err| {
                        SoftBufferError::PlatformError(
                            Some("Wayland dispatch failure".to_string()),
                            Some(Box::new(err)),
                        )
                    })?;
                }
            }

            // Resize, if buffer isn't large enough
            back.resize(width.get(), height.get());
        } else {
            // Allocate front and back buffer
            self.buffers = Some((
                WaylandBuffer::new(
                    &self.display.shm,
                    width.get(),
                    height.get(),
                    &self.display.qh,
                ),
                WaylandBuffer::new(
                    &self.display.shm,
                    width.get(),
                    height.get(),
                    &self.display.qh,
                ),
            ));
        };

        let age = self.buffers.as_mut().unwrap().1.age;
        Ok(BufferImpl {
            stack: util::BorrowStack::new(self, |buffer| {
                Ok(unsafe { buffer.buffers.as_mut().unwrap().1.mapped_mut() })
            })?,
            age,
        })
    }

    /// Fetch the buffer from the window.
    pub fn fetch(&mut self) -> Result<Vec<u32>, SoftBufferError> {
        Err(SoftBufferError::Unimplemented)
    }

    fn present_with_damage(&mut self, damage: &[Rect]) -> Result<(), SoftBufferError> {
        let _ = self
            .display
            .event_queue
            .borrow_mut()
            .dispatch_pending(&mut State);

        if let Some((front, back)) = &mut self.buffers {
            // Swap front and back buffer
            std::mem::swap(front, back);

            front.age = 1;
            if back.age != 0 {
                back.age += 1;
            }

            front.attach(self.surface.as_ref().unwrap());

            // Like Mesa's EGL/WSI implementation, we damage the whole buffer with `i32::MAX` if
            // the compositor doesn't support `damage_buffer`.
            // https://bugs.freedesktop.org/show_bug.cgi?id=78190
            if self.surface().version() < 4 {
                self.surface().damage(0, 0, i32::MAX, i32::MAX);
            } else {
                for rect in damage {
                    // Introduced in version 4, it is an error to use this request in version 3 or lower.
                    let (x, y, width, height) = (|| {
                        Some((
                            i32::try_from(rect.x).ok()?,
                            i32::try_from(rect.y).ok()?,
                            i32::try_from(rect.width.get()).ok()?,
                            i32::try_from(rect.height.get()).ok()?,
                        ))
                    })()
                    .ok_or(SoftBufferError::DamageOutOfRange { rect: *rect })?;
                    self.surface().damage_buffer(x, y, width, height);
                }
            }

            self.surface().commit();
        }

        let _ = self.display.event_queue.borrow_mut().flush();

        Ok(())
    }

    fn surface(&self) -> &wl_surface::WlSurface {
        self.surface.as_ref().unwrap()
    }
}

impl<D: ?Sized, W: ?Sized> Drop for WaylandImpl<D, W> {
    fn drop(&mut self) {
        // Make sure the surface is dropped first.
        self.surface = None;
    }
}

pub struct BufferImpl<'a, D: ?Sized, W> {
    stack: util::BorrowStack<'a, WaylandImpl<D, W>, [u32]>,
    age: u8,
}

impl<'a, D: HasDisplayHandle + ?Sized, W: HasWindowHandle> BufferImpl<'a, D, W> {
    #[inline]
    pub fn pixels(&self) -> &[u32] {
        self.stack.member()
    }

    #[inline]
    pub fn pixels_mut(&mut self) -> &mut [u32] {
        self.stack.member_mut()
    }

    pub fn age(&self) -> u8 {
        self.age
    }

    pub fn present_with_damage(self, damage: &[Rect]) -> Result<(), SoftBufferError> {
        self.stack.into_container().present_with_damage(damage)
    }

    pub fn present(self) -> Result<(), SoftBufferError> {
        let imp = self.stack.into_container();
        let (width, height) = imp
            .size
            .expect("Must set size of surface before calling `present()`");
        imp.present_with_damage(&[Rect {
            x: 0,
            y: 0,
            // We know width/height will be non-negative
            width: width.try_into().unwrap(),
            height: height.try_into().unwrap(),
        }])
    }
}

impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for State {
    fn event(
        _: &mut State,
        _: &wl_registry::WlRegistry,
        _: wl_registry::Event,
        _: &GlobalListContents,
        _: &Connection,
        _: &QueueHandle<State>,
    ) {
        // Ignore globals added after initialization
    }
}

impl Dispatch<wl_shm::WlShm, ()> for State {
    fn event(
        _: &mut State,
        _: &wl_shm::WlShm,
        _: wl_shm::Event,
        _: &(),
        _: &Connection,
        _: &QueueHandle<State>,
    ) {
    }
}