waybackend 0.7.0

A simple, low-level wayland client implementation
Documentation
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! # Waybackend
//!
//! Welcome. Waybackend is a low-level wayland backend that allows you to do wayland stuff without
//! wrapping everything in `Arc`s.
//!
//! Start by calling [`waybackend::connect`](crate::connect).
#![no_std]

extern crate alloc;

use rustix::{
    fd::{FromRawFd, OwnedFd},
    net::AddressFamily,
};

use ::alloc::{boxed::Box, string::String, vec::Vec};

use types::ObjectId;

mod wayland;

pub use bitflags;
pub use rustix;
pub mod objman;
pub mod shm;
pub mod types;
pub mod wire;

pub use wire::Error;

/// This struct holds the message builder and the wayland file descriptor
///
/// To create this struct, use the [`connect()`] function.
pub struct Waybackend {
    /// the message builder incrementally builds up wire messages
    pub wire_msg_builder: wire::MessageBuilder,
    /// the wayland file descriptor. You can pass this to `poll` to poll events
    pub wayland_fd: OwnedFd,
}

impl Waybackend {
    #[inline]
    #[must_use]
    fn new(wayland_fd: OwnedFd) -> Self {
        Self {
            wire_msg_builder: wire::MessageBuilder::new(),
            wayland_fd,
        }
    }

    #[inline]
    pub fn flush(&mut self) -> Result<(), wire::Error> {
        self.wire_msg_builder.flush(&self.wayland_fd)
    }
}

use core::num::NonZeroU32;

/// The wayland display global object always has the same id: 1
pub const WL_DISPLAY: types::ObjectId = types::ObjectId::new(NonZeroU32::new(1).unwrap());

#[derive(Debug)]
pub enum ConnectionError {
    InvalidWaylandSocketEnvVar,
    InvalidSocketAddrFamily(rustix::net::AddressFamily),
    GetSocketNameFailed(rustix::io::Errno),
    SocketCreationFailed(rustix::io::Errno),
    ConnectionFailed(rustix::io::Errno),
}

impl core::fmt::Display for ConnectionError {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            ConnectionError::InvalidWaylandSocketEnvVar => write!(
                f,
                "WAYLAND_SOCKET environment variable contains a value we failed to parse"
            ),
            ConnectionError::InvalidSocketAddrFamily(actual) => write!(
                f,
                "socket address in WAYLAND_SOCKET is not a unix socket. It's actual address family is: {actual:?}"
            ),
            ConnectionError::GetSocketNameFailed(errno) => {
                write!(f, "failed to get socket name: {errno}")
            }
            ConnectionError::SocketCreationFailed(errno) => {
                write!(f, "failed to create socket: {errno}")
            }
            ConnectionError::ConnectionFailed(errno) => {
                write!(f, "failed to connect to the unix stream: {errno}")
            }
        }
    }
}

impl core::error::Error for ConnectionError {}

fn get_env(var: &core::ffi::CStr) -> Option<&'static core::ffi::CStr> {
    unsafe {
        let ptr = libc::getenv(var.as_ptr());
        if !ptr.is_null() {
            Some(core::ffi::CStr::from_ptr(ptr))
        } else {
            None
        }
    }
}

/// Mostly copy-pasted from `wayland-client.rs`
///
/// This will connect to the wayland server using several fallback heuristics.
///
/// It first tries the `WAYLAND_SOCKET` environment variable. Failing that, it tries to read the
/// `WAYLAND_DISPLAY` variable. If it isn't set, we default to `wayland-0`.
///
/// This will also create the auxiliary structs, [`ObjectManager`](objman::ObjectManager) and
/// [`Receiver`](wire::Receiver) that you will use to create new objects and receive messages
/// from the wire, respectively.
///
/// Returns a tuple with [`Waybackend`], that has  the wayland file descriptor and wire message
/// builder, and the two above mentioned structures.
///
/// The [`ObjectManager`](objman::ObjectManager) must be instantiated with an enum that represents
/// the wayland protocol you will be using (see the [`ObjectManager`](objman::ObjectManager)
/// documentation for details). Further, to instantiate it, you must pass the variant that
/// corresponds to the display. This is why this function also demands you pass in that variant as
/// a parameter. For example:
/// ```no_run
/// #[derive(Clone, Copy, PartialEq)]
/// enum WaylandProtocol {
///     Display,
///     Registry,
///     LayerShell,
///     //...
/// }
/// let (mut backend, mut objman, mut receiver) =
///     waybackend::connect(WaylandProtocol::Display).expect("failed to connect to wayland server");
/// ```
#[inline]
pub fn connect<T: Copy + PartialEq>(
    display: T,
) -> Result<(Waybackend, objman::ObjectManager<T>, wire::Receiver), ConnectionError> {
    let objman = objman::ObjectManager::new(display);
    let receiver = wire::Receiver::new();
    if let Some(txt) = get_env(c"WAYLAND_SOCKET") {
        // We should connect to the provided WAYLAND_SOCKET
        let fd = txt
            .to_str()
            .map(str::parse::<i32>)
            .map_err(|_| ConnectionError::InvalidWaylandSocketEnvVar)?
            .map_err(|_| ConnectionError::InvalidWaylandSocketEnvVar)?;

        let fd = unsafe { OwnedFd::from_raw_fd(fd) };
        match rustix::net::getsockname(&fd) {
            Ok(socket_addr) => {
                if socket_addr.address_family() == AddressFamily::UNIX {
                    Ok((Waybackend::new(fd), objman, receiver))
                } else {
                    Err(ConnectionError::InvalidSocketAddrFamily(
                        socket_addr.address_family(),
                    ))
                }
            }
            Err(e) => Err(ConnectionError::GetSocketNameFailed(e)),
        }
    } else {
        let socket_name = get_env(c"WAYLAND_DISPLAY").unwrap_or_else(|| {
            log::warn!("WAYLAND_DISPLAY is not set! Defaulting to wayland-0");
            c"wayland-0"
        });

        let unix_addr = if socket_name.to_bytes()[0] == b'/' {
            rustix::net::SocketAddrUnix::new(socket_name).unwrap()
        } else {
            use core::fmt::Write;
            let mut socket_fullpath = String::new();
            match get_env(c"XDG_RUNTIME_DIR") {
                Some(socket_path) => {
                    core::write!(&mut socket_fullpath, "{}/", socket_path.to_str().unwrap())
                        .unwrap()
                }
                None => {
                    log::warn!("XDG_RUNTIME_DIR is not set! Defaulting to /run/user/UID");
                    let uid = rustix::process::getuid();
                    core::write!(&mut socket_fullpath, "/run/user/{}/", uid.as_raw()).unwrap();
                }
            }

            core::write!(&mut socket_fullpath, "{}", socket_name.to_str().unwrap()).unwrap();
            rustix::net::SocketAddrUnix::new(socket_fullpath.as_str()).unwrap()
        };

        let socket = rustix::net::socket_with(
            rustix::net::AddressFamily::UNIX,
            rustix::net::SocketType::STREAM,
            rustix::net::SocketFlags::CLOEXEC,
            None,
        )
        .map_err(ConnectionError::SocketCreationFailed)?;

        rustix::net::connect(&socket, &unix_addr).map_err(ConnectionError::ConnectionFailed)?;
        Ok((Waybackend::new(socket), objman, receiver))
    }
}

#[derive(Debug)]
pub enum RoundtripError {
    WireError(wire::Error),
    WaylandError((ObjectId, u32, Box<str>)),
    MessageFromUnknownObject(ObjectId),
    UnexpectedDeleteId(u32),
}

impl core::fmt::Display for RoundtripError {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            RoundtripError::WireError(error) => {
                write!(f, "roundtrip failed due to wayland wire error: {error}")
            }
            RoundtripError::MessageFromUnknownObject(id) => {
                write!(f, "received message from unknown object of id: {id}")
            }
            RoundtripError::UnexpectedDeleteId(id) => {
                write!(
                    f,
                    "Received a delete_id message from the display for id: {id}.\n\
                    This should never happen during the roundtrip initialization.\n\
                    This wayland implementation is probably fucked."
                )
            }
            RoundtripError::WaylandError((id, code, msg)) => write!(
                f,
                "Wayland protocol error. Object: {id}. Code: {code}. Message: {msg}"
            ),
        }
    }
}

impl core::error::Error for RoundtripError {}

#[derive(Debug)]
/// A wayland global. Use this to bind the interfaces you want
pub struct Global {
    name: u32,
    interface: Box<str>,
    version: u32,
}

impl Global {
    #[inline]
    pub fn name(&self) -> u32 {
        self.name
    }

    #[inline]
    pub fn interface(&self) -> &str {
        &self.interface
    }

    #[inline]
    pub fn version(&self) -> u32 {
        self.version
    }

    #[inline]
    pub fn bind<T: Copy + PartialEq>(
        &self,
        backend: &mut crate::Waybackend,
        registry: ObjectId,
        objman: &mut objman::ObjectManager<T>,
        object: T,
    ) -> Result<(), wire::Error> {
        let id = objman.create(object);
        wayland::wl_registry::req::bind(
            backend,
            registry,
            self.name,
            id,
            &self.interface,
            self.version,
        )
    }
}

struct GlobalHandler {
    globals: Vec<Global>,
    error: Option<RoundtripError>,
    done: bool,
    delete_callback: bool,
}

impl GlobalHandler {
    fn new() -> Self {
        Self {
            globals: Vec::new(),
            error: None,
            done: false,
            delete_callback: false,
        }
    }
}

impl wayland::wl_display::EvHandler for GlobalHandler {
    fn error(&mut self, _: ObjectId, object_id: ObjectId, code: u32, message: &str) {
        self.error = Some(RoundtripError::WaylandError((
            object_id,
            code,
            Box::from(message),
        )));
    }

    fn delete_id(&mut self, _: ObjectId, id: u32) {
        if id != 3 {
            self.error = Some(RoundtripError::UnexpectedDeleteId(id));
        } else {
            self.delete_callback = true;
        }
    }
}

impl wayland::wl_registry::EvHandler for GlobalHandler {
    fn global(&mut self, _: ObjectId, name: u32, interface: &str, version: u32) {
        self.globals.push(Global {
            name,
            interface: Box::from(interface),
            version,
        });
    }

    fn global_remove(&mut self, _: ObjectId, name: u32) {
        self.globals.retain(|g| g.name != name)
    }
}

impl wayland::wl_callback::EvHandler for GlobalHandler {
    fn done(&mut self, _: ObjectId, _: u32) {
        self.done = true;
    }
}

/// Does a roundtrip to gather all the globals during program initialization
///
/// We return: a list of globals and whether or not you should delete the callback with id
/// `callback_id`.
#[inline]
pub fn roundtrip(
    backend: &mut Waybackend,
    receiver: &mut wire::Receiver,
    registry_id: ObjectId,
    callback_id: ObjectId,
) -> Result<(Vec<Global>, bool), RoundtripError> {
    let mut global_handler = GlobalHandler::new();
    wayland::wl_display::req::get_registry(backend, WL_DISPLAY, registry_id)
        .map_err(RoundtripError::WireError)?;
    wayland::wl_display::req::sync(backend, WL_DISPLAY, callback_id)
        .map_err(RoundtripError::WireError)?;
    backend.flush().map_err(RoundtripError::WireError)?;

    while !global_handler.done && global_handler.error.is_none() {
        let mut msgs = receiver
            .recv(&backend.wayland_fd)
            .map_err(RoundtripError::WireError)?;
        while let Some(sender_id) = msgs.next() {
            match sender_id.map_err(RoundtripError::WireError)? {
                WL_DISPLAY => wayland::wl_display::event(&mut global_handler, &mut msgs)
                    .map_err(RoundtripError::WireError)?,
                id if id == registry_id => {
                    wayland::wl_registry::event(&mut global_handler, &mut msgs)
                        .map_err(RoundtripError::WireError)?
                }
                id if id == callback_id => {
                    wayland::wl_callback::event(&mut global_handler, &mut msgs)
                        .map_err(RoundtripError::WireError)?
                }
                otherwise => return Err(RoundtripError::MessageFromUnknownObject(otherwise)),
            }
        }
    }

    if let Some(error) = global_handler.error {
        return Err(error);
    }

    Ok((global_handler.globals, global_handler.delete_callback))
}

/// This macro can help you bind all the globals you want to their equivalent `enum`.
///
/// # Panics
///
/// This macro will panic if binding the gloal fails.
///
/// Example usage:
/// ```no_run
/// # mod wayland {include!("../doc/wayland_protocols.rs");}
/// #[derive(Clone, Copy, PartialEq)]
/// enum WaylandObject {
///      Display,
///      Registry,
///      Callback,
///      Compositor,
///      Shm,
/// }
///
/// let (mut backend, mut objman, mut receiver) =
///      waybackend::connect(WaylandObject::Display).expect("failed to connect to wayland server");
/// let registry = objman.create(WaylandObject::Registry);
/// let callback = objman.create(WaylandObject::Callback);
/// let (globals, delete_callback) =
///      waybackend::roundtrip(&mut backend, &mut receiver, registry, callback)
///          .expect("failed to do initial roundtrip");
///
/// if delete_callback {
///     objman.remove(callback.get().get());
/// }
///
/// // Here, we assume the wayland protocol code was generated in a `wayland` module.
/// // Important is necessary because otherwise the macro cannot find the `NAME` constant in the
/// // interfaces
/// use wayland::*;
/// waybackend::bind_globals!(
///     backend,
///     objman,
///     registry,
///     globals,
///     (wl_compositor, WaylandObject::Compositor),
///     (wl_shm, WaylandObject::Shm),
/// );
/// ```
#[macro_export]
macro_rules! bind_globals {
    (
        $backend:ident,
        $objman:ident,
        $registry:ident,
        $globals:ident,
        $(($interface:ident, $object:path)),*$(,)?
    ) => {
        for global in $globals.iter() {
            match global.interface() {
                $(
                    $interface::NAME => {
                        global.bind(&mut $backend, $registry, &mut $objman, $object)
                            .expect("failed to bind global");
                    }
                )*
                _ => (),
            }
        }
    }
}

/// This macro can help you dispatch all the received wayland matches through the appropriate
/// protocol event handler.
///
/// # Panics
///
/// This macro will panic if dispatching the event failed. This can happen on malformed messages
/// from the wayland server.
///
/// Example usage:
/// ```no_run
/// use waybackend::{
///     Waybackend,
///     objman::ObjectManager,
///     types::ObjectId
/// };
///
/// #[derive(Clone, Copy, PartialEq)]
/// enum WaylandObject {
///      Display,
///      Registry,
///      Callback,
///      Compositor,
/// }
///
/// struct App {
///     backend: Waybackend,
///     objman: ObjectManager<WaylandObject>,
///     _registry: ObjectId,
///     callback: ObjectId,
///     should_exit: bool,
/// }
///
/// // implement all relevant handlers for App...
///
/// # impl App {
/// #     fn new(
/// #         mut backend: Waybackend,
/// #         mut objman: ObjectManager<WaylandObject>,
/// #     ) -> Self {
/// #         let registry = objman.get_first(WaylandObject::Registry).unwrap();
/// #         let callback = objman.create(WaylandObject::Callback);
/// #         wl_display::req::sync(&mut backend, waybackend::WL_DISPLAY, callback).unwrap();
/// #
/// #         Self {
/// #             backend,
/// #             objman,
/// #             _registry: registry,
/// #             callback,
/// #             should_exit: false,
/// #         }
/// #     }
/// # }
/// #
/// # impl wl_display::EvHandler for App {
/// #     fn error(&mut self, _sender_id: ObjectId, object_id: ObjectId, code: u32, message: &str) {
/// #         panic!("wayland error for object {object_id}, code {code}: {message}");
/// #     }
/// #
/// #     fn delete_id(&mut self, _sender_id: ObjectId, id: u32) {
/// #         self.objman.remove(id);
/// #     }
/// # }
/// #
/// # impl wl_registry::EvHandler for App {
/// #     fn global(&mut self, _sender_id: ObjectId, name: u32, interface: &str, version: u32) {
/// #         println!("GLOBAL: {interface} ({version}). Name: {name}")
/// #     }
/// #
/// #     fn global_remove(&mut self, _sender_id: ObjectId, name: u32) {
/// #         println!("GLOBAL_REMOVE: {name}")
/// #     }
/// # }
/// #
/// # impl wl_callback::EvHandler for App {
/// #     fn done(&mut self, sender_id: ObjectId, _callback_data: u32) {
/// #         println!("CALLBACK DONE: {sender_id}");
/// #         if sender_id == self.callback {
/// #             self.should_exit = true;
/// #         }
/// #     }
/// # }
/// #
/// # impl wl_compositor::EvHandler for App {}
/// #
/// # mod wayland {include!("../doc/wayland_protocols.rs");}
/// #
/// # let (mut backend, mut objman, mut receiver) =
/// #      waybackend::connect(WaylandObject::Display).expect("failed to connect to wayland server");
/// # let registry = objman.create(WaylandObject::Registry);
/// # let callback = objman.create(WaylandObject::Callback);
/// # let (globals, delete_callback) =
/// #      waybackend::roundtrip(&mut backend, &mut receiver, registry, callback)
/// #          .expect("failed to do initial roundtrip");
/// #
/// # if delete_callback {
/// #     objman.remove(callback.get().get());
/// # }
/// #
/// # use wayland::*;
/// # waybackend::bind_globals!(
/// #     backend,
/// #     objman,
/// #     registry,
/// #     globals,
/// #     (wl_compositor, WaylandObject::Compositor),
/// # );
///
/// // then, your event loop can look kind of like this:
///
/// let mut app = App::new(backend, objman);
/// app.backend.flush().unwrap();
/// while !app.should_exit {
///     let mut msgs = receiver.recv(&app.backend.wayland_fd).unwrap();
///     while let Some(sender_id) = msgs.next() {
///         let sender_id = sender_id.unwrap();
///         // Otherwise, we get the object type from the ObjectManager, and
///         // dispatch the handler accordingly
///         let sender = app.objman.get(sender_id).unwrap();
///         waybackend::match_enum_with_interface!(
///             app,
///             sender,
///             msgs,
///             (WaylandObject::Display, wl_display),
///             (WaylandObject::Registry, wl_registry),
///             (WaylandObject::Callback, wl_callback),
///             (WaylandObject::Compositor, wl_compositor),
///         );
///     }
/// }
/// ```
#[macro_export]
macro_rules! match_enum_with_interface {
    ($handler:ident, $object:ident, $msgs:ident, $(($variant:path, $interface:ident)),*$(,)?) => {
        match $object {
            $(
                $variant => {
                    $interface::event(&mut $handler, &mut $msgs)
                        .expect("failed to dispatch event handler");
                }
            )*
        }
    }
}