waybackend-cursor 0.10.1

Cursor implementation for waybackend
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
//! Wayland cursor implementation using `Waybackend` as the backend
//!
//! This crate was make by adapting the code in `wayland-cursor-rs`, from the `smithay` project.
//!
//! Key differences:
//!
//!  - we do not allow automatically setting cursor fallbacks. You'd have to do something manually
//!    every time
//!  - when loading a cursor, you must pass closures for running the wayland specific code. There
//!    are examples of how to do this in the documentation
use waybackend::{Waybackend, types::ObjectId};

#[derive(Debug)]
pub enum CursorLoadError {
    Io(rustix::io::Errno),
    EnvVar(std::env::VarError),
}

impl core::error::Error for CursorLoadError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            CursorLoadError::Io(errno) => errno.source(),
            CursorLoadError::EnvVar(var_error) => var_error.source(),
        }
    }

    fn cause(&self) -> Option<&dyn core::error::Error> {
        self.source()
    }
}

impl core::fmt::Display for CursorLoadError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "CursorLoadError: ")?;
        match self {
            CursorLoadError::Io(errno) => errno.fmt(f),
            CursorLoadError::EnvVar(var_error) => var_error.fmt(f),
        }
    }
}

pub struct CursorTheme {
    name: String,
    cursors: Vec<Cursor>,
    /// cursor size
    size: u32,
    wl_shm_pool: ObjectId,
    pool_size: u32,
    pool_len: u32,
    shm_fd: rustix::fd::OwnedFd,
}

impl CursorTheme {
    /// Use this to create the initial pool
    const INITIAL_POOL_SIZE: usize = 16 * 16 * 4;

    /// Tries to load the cursor theme from the `XCURSOR_THEME` and `XCURSOR_SIZE` environment variables
    ///
    /// See [`CursorTheme::load_from_name`] for an example of a `create_pool_fn`.
    #[inline]
    pub fn load_from_env<F>(mut size: u32, create_pool_fn: F) -> Result<Self, CursorLoadError>
    where
        F: FnOnce(&rustix::fd::OwnedFd, u32) -> ObjectId,
    {
        let name = &std::env::var("XCURSOR_THEME").map_err(CursorLoadError::EnvVar)?;

        if let Ok(var) = std::env::var("XCURSOR_SIZE")
            && let Ok(int) = var.parse()
        {
            size = int;
        }

        Self::load_from_name(name, size, create_pool_fn)
    }

    /// Tries to load the cursor theme from an `str`
    ///
    /// `create_pool_fn` is a function that takes the shm file descriptor and the initial size.
    /// Typically, it will look like this (note in the example we are loading the generatec wayland
    /// glue code with `waybackend-scanner` in a module called `wayland`):
    ///
    /// ```ignore
    /// use waybackend_cursor::CursorTheme;
    /// use waybackend::{types::ObjectId, objman, Waybackend};
    ///
    /// #[derive(Clone, Copy, Debug, PartialEq)]
    /// enum WaylandObject {
    ///     Display,
    ///     Shm,
    ///     ShmPool,
    ///     Buffer,
    ///     Surface,
    ///     // ...
    /// }
    ///
    /// fn load_cursor(
    ///     backend: &mut Waybackend,
    ///     objman: &mut objman::ObjectManager::<WaylandObject>,
    ///     wayland_shm: ObjectId) -> CursorTheme {
    ///     CursorTheme::load_from_name("default", 24, |fd, size| {
    ///         let shm_pool = objman.create(WaylandObject::ShmPool);
    ///         wayland::wl_shm::req::create_pool(
    ///             backend,
    ///             wayland_shm,
    ///             shm_pool,
    ///             fd,
    ///             size as i32,
    ///         )
    ///         .unwrap();
    ///         shm_pool
    ///     }).unwrap()
    /// }
    /// ```
    #[inline]
    pub fn load_from_name<F>(
        name: &str,
        size: u32,
        create_pool_fn: F,
    ) -> Result<Self, CursorLoadError>
    where
        F: FnOnce(&rustix::fd::OwnedFd, u32) -> ObjectId,
    {
        //  Create shm.
        let shm_fd = waybackend::shm::create().map_err(CursorLoadError::Io)?;
        rustix::fs::ftruncate(&shm_fd, Self::INITIAL_POOL_SIZE as u64)
            .map_err(CursorLoadError::Io)?;
        let wl_shm_pool = create_pool_fn(&shm_fd, size);

        let name = String::from(name);
        Ok(Self {
            name,
            size,
            pool_size: Self::INITIAL_POOL_SIZE as u32,
            pool_len: 0,
            cursors: Vec::new(),
            wl_shm_pool,
            shm_fd,
        })
    }

    /// Gets a cursor from the theme
    ///
    ///  - `backend` will be fed to the two functions.
    ///  - `create_buffer_fn` is a closure that returns  a `ObjectId`: the ObjectId of the
    ///    newly created wayland buffer. It accepts 6 inputs:
    ///    * backend (should be `waybackend::Waybackend`)
    ///    * the `wl_shm_pool` ObjectId
    ///    * offset (see the wayland protocol documentation)
    ///    * width  (see the wayland protocol documentation)
    ///    * height (see the wayland protocol documentation)
    ///    * stride (see the wayland protocol documentation)
    ///  - `resize_fn` is a closure that resizes the `wl_shm_pool`. It accepts 3 inputs:
    ///    * the backend (should be `waybackend::Waybackend`)
    ///    * the `wl_shm_pool` ObjectId
    ///    * the new size
    ///
    /// Here is an example of what this function call could look like:
    ///
    /// ```ignore
    /// use waybackend::{types::ObjectId, objman::Objman, Waybackend};
    /// use waybackend_cursor::{Cursor, CursorTheme};
    /// fn get_cursor(
    ///     cursor_theme: &mut CursorTheme,
    ///     backend: &mut Waybackend,
    ///     objman: &mut Objman,
    ///     name: &str,
    /// ) -> Option<&Cursor> {
    ///     cursor_theme.get_cursor(
    ///         name,
    ///         backend,
    ///         |backend, pool, offset, width, height, stride| {
    ///             // NOTE: you probably also want to store this buffer id somewhere
    ///             let buffer = objman.create(WaylandObject::Buffer);
    ///             wayland::wl_shm_pool::req::create_buffer(
    ///                 backend,
    ///                 pool,
    ///                 buffer,
    ///                 offset,
    ///                 width,
    ///                 height,
    ///                 stride,
    ///                 wayland::wl_shm::Format::argb8888,
    ///             )
    ///             .unwrap();
    ///             buffer
    ///         },
    ///         |backend, id, size| {
    ///             wayland::wl_shm_pool::req::resize(backend, id, size as i32).unwrap()
    ///         },
    ///     )
    /// }
    /// ```
    #[inline]
    pub fn get_cursor<F1, F2>(
        &mut self,
        name: &str,
        backend: &mut Waybackend,
        create_buffer_fn: F1,
        resize_fn: F2,
    ) -> Option<&Cursor>
    where
        F1: FnMut(&mut Waybackend, ObjectId, i32, i32, i32, i32) -> ObjectId,
        F2: FnMut(&mut Waybackend, ObjectId, u32),
    {
        match self.cursors.iter().position(|cursor| cursor.name == name) {
            Some(i) => Some(&self.cursors[i]),
            None => {
                let cursor =
                    self.load_cursor(name, self.size, backend, create_buffer_fn, resize_fn)?;
                self.cursors.push(cursor);
                self.cursors.last()
            }
        }
    }

    #[inline]
    fn load_cursor<F1, F2>(
        &mut self,
        name: &str,
        size: u32,
        backend: &mut Waybackend,
        create_buffer_fn: F1,
        resize_fn: F2,
    ) -> Option<Cursor>
    where
        F1: FnMut(&mut Waybackend, ObjectId, i32, i32, i32, i32) -> ObjectId,
        F2: FnMut(&mut Waybackend, ObjectId, u32),
    {
        use rustix::{buffer, fs, io};
        let icon_path = xcursor::CursorTheme::load(&self.name).load_icon(name)?;
        let icon_file = fs::open(icon_path, fs::OFlags::RDONLY, fs::Mode::RUSR).ok()?;

        let mut buf = Vec::with_capacity(4096);
        loop {
            match io::retry_on_intr(|| io::read(&icon_file, buffer::spare_capacity(&mut buf))) {
                Ok(0) => break,
                Err(_) => return None,
                Ok(_) => (),
            }

            if buf.capacity() == buf.len() {
                buf.reserve(buf.capacity() * 2);
            }
        }
        let images = xcursor::parser::parse_xcursor(&buf)?;

        Some(Cursor::new(
            name,
            self,
            &images,
            size,
            backend,
            create_buffer_fn,
            resize_fn,
        ))
    }

    #[inline]
    fn grow<F>(&mut self, backend: &mut Waybackend, size: u32, resize_fn: F)
    where
        F: FnOnce(&mut Waybackend, ObjectId, u32),
    {
        if size > self.pool_size {
            rustix::fs::ftruncate(&self.shm_fd, size as u64)
                .expect("failed to new cursor buffer length");
            resize_fn(backend, self.wl_shm_pool, size);
            self.pool_size = size;
        }
    }
}

pub struct Cursor {
    name: String,
    images: Vec<CursorImageBuffer>,
    total_duration: u32,
}

impl Cursor {
    #[inline]
    fn new<F1, F2>(
        name: &str,
        theme: &mut CursorTheme,
        images: &[xcursor::parser::Image],
        size: u32,
        backend: &mut Waybackend,
        mut create_buffer_fn: F1,
        mut resize_fn: F2,
    ) -> Self
    where
        F1: FnMut(&mut Waybackend, ObjectId, i32, i32, i32, i32) -> ObjectId,
        F2: FnMut(&mut Waybackend, ObjectId, u32),
    {
        let mut total_duration = 0;
        let f1 = &mut create_buffer_fn;
        let f2 = &mut resize_fn;
        let images: Vec<CursorImageBuffer> = Self::nearest_images(size, images)
            .map(|image| {
                let buffer =
                    CursorImageBuffer::new::<&mut F1, &mut F2>(theme, image, backend, f1, f2);
                total_duration += buffer.delay;

                buffer
            })
            .collect();

        Self {
            total_duration,
            name: String::from(name),
            images,
        }
    }

    #[inline]
    fn nearest_images(
        size: u32,
        images: &[xcursor::parser::Image],
    ) -> impl Iterator<Item = &xcursor::parser::Image> {
        // Follow the nominal size of the cursor to choose the nearest
        let nearest_image = images
            .iter()
            .min_by_key(|image| (size as i32 - image.size as i32).abs())
            .unwrap();
        images.iter().filter(move |image| {
            image.width == nearest_image.width && image.height == nearest_image.height
        })
    }

    /// Time is returned in milliseconds
    #[inline]
    pub fn frame_and_duration(&self, mut millis: u32) -> (usize, u32) {
        millis %= self.total_duration;
        let mut res = 0;
        for (i, img) in self.images.iter().enumerate() {
            if millis < img.delay {
                res = i;
                break;
            }
            millis -= img.delay;
        }

        (res, millis)
    }

    #[inline]
    pub fn images(&self) -> &[CursorImageBuffer] {
        &self.images
    }
}

pub struct CursorImageBuffer {
    wl_buffer: ObjectId,
    delay: u32,
    xhot: u32,
    yhot: u32,
    width: u32,
    height: u32,
}

impl CursorImageBuffer {
    /// Construct a new CursorImageBuffer
    ///
    /// This function appends the pixels of the image to the provided file,
    /// and constructs a wl_buffer on that data.
    #[inline]
    fn new<F1, F2>(
        theme: &mut CursorTheme,
        image: &xcursor::parser::Image,
        backend: &mut Waybackend,
        create_buffer_fn: F1,
        resize_fn: F2,
    ) -> Self
    where
        F1: FnOnce(&mut Waybackend, ObjectId, i32, i32, i32, i32) -> ObjectId,
        F2: FnOnce(&mut Waybackend, ObjectId, u32),
    {
        use rustix::mm::{MapFlags, ProtFlags, mmap, munmap};
        let buf = &image.pixels_rgba;
        let offset = theme.pool_len as u64;
        // Resize memory before writing to it to handle shm correctly.
        let new_size = offset + buf.len() as u64;
        theme.grow(backend, new_size as u32, resize_fn);
        let mmap = unsafe {
            mmap(
                core::ptr::null_mut(),
                new_size as usize,
                ProtFlags::READ | ProtFlags::WRITE,
                MapFlags::SHARED,
                &theme.shm_fd,
                0,
            )
        }
        .expect("failed to mmap cursor shared memory");
        {
            let slice = unsafe {
                core::slice::from_raw_parts_mut(mmap.cast::<u8>().add(offset as usize), buf.len())
            };
            slice.copy_from_slice(buf);
        }
        theme.pool_len += buf.len() as u32;

        let wl_buffer = create_buffer_fn(
            backend,
            theme.wl_shm_pool,
            offset as i32,
            image.width as i32,
            image.height as i32,
            (image.width * 4) as i32,
        );

        unsafe { munmap(mmap, new_size as usize).expect("failed to munmap cursor shared memory") };
        Self {
            wl_buffer,
            delay: image.delay,
            xhot: image.xhot,
            yhot: image.yhot,
            width: image.width,
            height: image.height,
        }
    }

    /// Dimensions of this image
    #[inline]
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Location of the pointer hotspot in this image
    #[inline]
    pub fn hotspot(&self) -> (u32, u32) {
        (self.xhot, self.yhot)
    }

    /// Time (in milliseconds) for which this image should be displayed
    #[inline]
    pub fn delay(&self) -> u32 {
        self.delay
    }

    /// The wayland buffer
    #[inline]
    pub fn wl_buffer(&self) -> ObjectId {
        self.wl_buffer
    }
}