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
//! Fundamental types and traits for a wayland compositor
//!
//! This crate provides the scaffolding for writing a wayland compositor. It
//! defines the traits for per-client and server global contexts, and traits for
//! implementing wayland objects. It also provides helper for implementing these
//! traits.
//!
//! # Structure of a compositor
//!
//! Let's break down a wayland compositor by looking at its data flow. (I used
//! the word "data flow" loosely here.)
//!
//! A wayland compositor starts by creating a socket and listening on it. Once a
//! client connects to the socket, the compositor accepts the connection, and
//! creates a new per-client context for it. The per-client context contains the
//! object store, which will have a wl_display object already bound in it. The
//! client can issue requests to objects in its object store, by referring to
//! them with their object ID. The compositor handles these requests by calling
//! the wayland interface implementations associated with the objects.
//!
//! # How this crate fits in
//!
//! Function [`wayland_listener`] and [`wayland_listener_auto`] can be used to
//! create the socket for incoming connections.
//!
//! The traits in [`objects`](crate::objects) defines the interface of wayland
//! objects. You can choose to implement wayland objects with them and the
//! `RequestDispatch` traits generated from the wayland protocol spec (See the
//! `runa-wayland-protocols` crate). Or you can also use the `runa-orbiter`
//! crate which provides implementations for many of the wayland objects.
//!
//! The [`Client`](crate::client::traits::Client) trait defines the interface of
//! a per-client context. See its documentation for more details. That trait
//! explains how most of the other stuffs fit together.
//!
//! The [`Server`](crate::server::traits::Server) trait is responsible for
//! creating a new client context each time a new client connects. It also
//! provides access to the globals.

// We can drop trait_upcasting if necessary. `type_alias_impl_trait` is
// the indispensable feature here.
#![allow(incomplete_features)]
#![feature(type_alias_impl_trait, trait_upcasting)]
#![warn(
    missing_debug_implementations,
    missing_copy_implementations,
    missing_docs,
    rust_2018_idioms,
    single_use_lifetimes
)]

use futures_lite::stream::StreamExt;
use hashbrown::{hash_map, HashMap};
use thiserror::Error;

pub mod client;
pub mod error;
pub mod events;
pub mod globals;
pub mod objects;
pub mod provide_any;
pub mod server;
mod utils;

#[doc(hidden)]
pub mod __private {
    // Re-exports used by macros
    pub use runa_io::traits::{
        buf::AsyncBufReadWithFd,
        de::{Deserialize, Error as DeserError},
        ser::Serialize,
        WriteMessage,
    };
    pub use runa_wayland_protocols::wayland::wl_display;
    pub use runa_wayland_types as types;
    pub use static_assertions::assert_impl_all;
}

/// Errors that can be reported by a connection manager.
#[derive(Error, Debug)]
pub enum ConnectionManagerError<SE, LE> {
    /// Errors returned by the server type
    #[error("Server error: {0}")]
    Server(#[source] SE),
    /// I/O error
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    /// Errors returned by the listener
    #[error("Listener error: {0}")]
    Listener(#[source] LE),
}

/// A connection manager that accepts incoming connections from a listener, and
/// then calls
/// [`Server::new_connection`](crate::server::traits::Server::new_connection)
/// for each connection.
#[derive(Debug)]
pub struct ConnectionManager<S, Ctx> {
    listeners: S,
    ctx:       Ctx,
}

impl<S, Ctx, I, E> ConnectionManager<S, Ctx>
where
    S: futures_lite::stream::Stream<Item = Result<I, E>> + Unpin,
    Ctx: crate::server::traits::Server<Conn = I>,
{
    /// Create a new connection manager.
    ///
    /// # Arguments
    ///
    /// - `listeners`: A stream of incoming connections.
    /// - `ctx`: The server context.
    pub fn new(listeners: S, ctx: Ctx) -> Self {
        Self { listeners, ctx }
    }

    /// Run the connection manager.
    pub async fn run(&mut self) -> Result<(), ConnectionManagerError<Ctx::Error, E>> {
        while let Some(conn) = self.listeners.next().await {
            let conn = conn.map_err(ConnectionManagerError::Listener)?;
            self.ctx
                .new_connection(conn)
                .map_err(ConnectionManagerError::Server)?;
        }
        Ok(())
    }
}

/// Errors that can occur when creating a wayland listener.
#[derive(Error, Debug)]
pub enum ListenerError {
    /// I/O error
    #[error("I/O error: {0}")]
    SmolIo(#[from] std::io::Error),
    /// Error when accessing the xdg base directory
    #[error("xdg base directory error: {0}")]
    XdgBaseDirectory(#[from] xdg::BaseDirectoriesError),
    /// Unix error
    #[error("unix error: {0}")]
    Unix(#[from] rustix::io::Errno),
}

/// A guard that unlocks the lock file when dropped.
#[derive(Debug)]
pub struct FlockGuard {
    fd: rustix::fd::OwnedFd,
}

impl Drop for FlockGuard {
    fn drop(&mut self) {
        use rustix::fd::AsFd;
        rustix::fs::flock(self.fd.as_fd(), rustix::fs::FlockOperation::Unlock).unwrap();
    }
}

/// Create a `UnixListener` for accepting incoming connections from wayland
/// clients.
///
/// The path of the socket is determined by the `display` argument, as specified
/// by the wayland specification. This function also creates a lock file for the
/// socket. The lock file is used to prevent multiple compositor instances from
/// trying to use the same socket. The lock file is unlocked when the returned
/// [`FlockGuard`] is dropped.
pub fn wayland_listener(
    display: &str,
) -> Result<(std::os::unix::net::UnixListener, FlockGuard), ListenerError> {
    use rustix::fd::AsFd;
    let xdg_dirs = xdg::BaseDirectories::new()?;
    let path = xdg_dirs.place_runtime_file(display)?;
    let lock_path = xdg_dirs.place_runtime_file(format!("{display}.lock"))?;
    let lock = rustix::fs::openat(
        rustix::fs::cwd(),
        lock_path,
        rustix::fs::OFlags::CREATE,
        rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,
    )?;
    rustix::fs::flock(
        lock.as_fd(),
        rustix::fs::FlockOperation::NonBlockingLockExclusive,
    )?;
    // We successfully locked the file, so we can remove the socket file if that
    // exists.
    let _ = std::fs::remove_file(&path);
    Ok((std::os::unix::net::UnixListener::bind(path)?, FlockGuard {
        fd: lock,
    }))
}

/// Create a `UnixListener` for accepting incoming connections from wayland
/// clients.
///
/// Similar to [`wayland_listener`], but tries to find a free display number
/// automatically.
pub fn wayland_listener_auto(
) -> Result<(std::os::unix::net::UnixListener, FlockGuard), ListenerError> {
    const MAX_DISPLAYNO: u32 = 32;
    let mut last_err = None;
    for i in 0..MAX_DISPLAYNO {
        let display = format!("wayland-{i}");
        match wayland_listener(&display) {
            Ok((listener, guard)) => return Ok((listener, guard)),
            e @ Err(_) => {
                last_err = Some(e);
            },
        }
    }
    last_err.unwrap()
}

/// Event serial management. (WIP, not currently used)
///
/// This trait allocates serial numbers, while keeping track of allocated
/// numbers and their associated data.
///
/// Some expiration scheme might be employed by the implementation to free up
/// old serial numbers.
///
/// TODO: this is incomplete and not used.
#[allow(missing_docs)]
pub trait Serial {
    type Data;
    type Iter<'a>: Iterator<Item = (u32, &'a Self::Data)>
    where
        Self: 'a,
        Self::Data: 'a;
    /// Get the next serial number in sequence. A piece of data can be attached
    /// to each serial, storing, for example, what this event is about.
    fn next_serial(&mut self, data: Self::Data) -> u32;
    /// Get the data associated with the given serial.
    fn get(&self, serial: u32) -> Option<&Self::Data>;
    fn iter(&self) -> Self::Iter<'_>;
    /// Remove the serial number from the list of allocated serials.
    fn expire(&mut self, serial: u32) -> bool;
}

struct IdAlloc<D> {
    next: u32,
    data: HashMap<u32, D>,
}

impl<D> Default for IdAlloc<D> {
    fn default() -> Self {
        Self {
            // 0 is reserved for the null object
            next: 1,
            data: HashMap::new(),
        }
    }
}

impl<D> std::fmt::Debug for IdAlloc<D> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        struct DebugMap<'a, K, V>(&'a HashMap<K, V>);
        impl<K: std::fmt::Debug, V> std::fmt::Debug for DebugMap<'_, K, V> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_set().entries(self.0.keys()).finish()
            }
        }
        f.debug_struct("IdAlloc")
            .field("next", &self.next)
            .field("data", &DebugMap(&self.data))
            .finish()
    }
}

impl<D> Serial for IdAlloc<D> {
    type Data = D;
    type Iter<'a> = <&'a Self as IntoIterator>::IntoIter where Self: 'a;

    fn next_serial(&mut self, data: Self::Data) -> u32 {
        loop {
            // We could wrap around, so check for used IDs.
            // If the occupation rate is high, this could be slow. But IdAlloc is used for
            // things like allocating client/object IDs, so we expect at most a
            // few thousand IDs used at a time, out of 4 billion available.
            let id = self.next;
            self.next += 1;
            match self.data.entry(id) {
                hash_map::Entry::Vacant(e) => {
                    e.insert(data);
                    break id
                },
                hash_map::Entry::Occupied(_) => (),
            }
        }
    }

    fn get(&self, serial: u32) -> Option<&Self::Data> {
        self.data.get(&serial)
    }

    fn expire(&mut self, serial: u32) -> bool {
        self.data.remove(&serial).is_some()
    }

    fn iter(&self) -> Self::Iter<'_> {
        self.into_iter()
    }
}

#[doc(hidden)]
pub type IdIter<'a, D>
where
    D: 'a,
= impl Iterator<Item = (u32, &'a D)> + 'a;

impl<'a, D: 'a> IntoIterator for &'a IdAlloc<D> {
    type IntoIter = IdIter<'a, D> where Self: 'a;
    type Item = (u32, &'a D);

    fn into_iter(self) -> IdIter<'a, D> {
        self.data.iter().map(|(k, v)| (*k, v))
    }
}

/// Generate a corresponding Objects enum from a Globals enum.
///
/// # Example
///
/// ```rust
/// globals! {
///    type ClientContext = ClientContext;
///    #[derive(Debug)]
///    pub enum Globals {
///        Display(wl_server::objects::Display),
///        Registry(wl_server::objects::Registry),
///     }
/// }
/// ```
///
/// The name `Globals` and `Objects` can be changed.
///
/// This will generate a `From<Variant> for Globals` for each of the variants of
/// `Globals`. And for each global, a `From<Global::Object> for Objects` will be
/// generated.
///
/// `Objects` will be filled with variants from `Global::Object` for each of the
/// globals. It can also contain extra variants, for object types that aren't
/// associated with a particular global.
#[macro_export]
macro_rules! globals {
    (
        __internal, $ctx:ty, $(#[$attr:meta])* ($($vis:tt)?) enum $N:ident { $($var:ident($f:ty)),+ $(,)? }
    ) => {
        $(#[$attr])*
        $($vis)? enum $N {
            $($var($f)),*
        }
        $(
            impl From<$f> for $N {
                fn from(f: $f) -> Self {
                    $N::$var(f)
                }
            }
        )*
        impl $crate::globals::AnyGlobal for $N {
            type Object = <$ctx as $crate::client::traits::Client>::Object;
            fn interface(&self) -> &'static str {
                match self {
                    $(
                        $N::$var(f) => <$f as $crate::globals::MonoGlobal>::INTERFACE,
                    )*
                }
            }
            fn version(&self) -> u32 {
                match self {
                    $(
                        $N::$var(f) => <$f as $crate::globals::MonoGlobal>::VERSION,
                    )*
                }
            }
            fn new_object(&self) -> Self::Object {
                match self {
                    $(
                        $N::$var(f) => <$f as $crate::globals::MonoGlobal>::new_object().into(),
                    )*
                }
            }
            fn cast<T: 'static>(&self) -> Option<&T> {
                match self {
                    $(
                        $N::$var(f) => (f as &dyn ::std::any::Any).downcast_ref::<T>(),
                    )*
                }
            }
        }
        impl $crate::globals::Bind<$ctx> for $N {
            type BindFut<'a> = impl std::future::Future<Output = std::io::Result<()>> + 'a
            where
                Self: 'a;
            fn bind<'a>(&'a self, client: &'a mut $ctx, object_id: u32) -> Self::BindFut<'a> {
                async move {
                    Ok(match self {$(
                        $N::$var(f) => <$f as $crate::globals::Bind<$ctx>>::bind(f, client, object_id).await?,
                    )*})
                }
            }
        }
        impl $N {
            $($vis)? fn globals() -> impl Iterator<Item = $N> {
                [$(<$f as $crate::globals::MonoGlobal>::MAYBE_DEFAULT.map($N::$var)),*].into_iter().flatten()
            }
        }
    };
    (
        type ClientContext = $ctx:ty;
        $(#[$attr:meta])* pub enum $N:ident { $($var:ident($f:ty)),+ $(,)? }
    ) => {
        $crate::globals!(
            __internal,
            $ctx,
            $(#[$attr])* $(#[$attr])* (pub) enum $N { $($var($f)),* }
        );
    };
    (
        type ClientContext = $ctx:ty;
        $(#[$attr:meta])* enum $N:ident { $($var:ident($f:ty)),+ $(,)? }
    ) => {
        $crate::globals!(
            __internal,
            $ctx,
            $(#[$attr])* $(#[$attr])* () enum $N { $($var($f)),* }
        );
    };
}