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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use std::{
    collections::{hash_map::Entry, HashMap},
    env, iter, mem,
    sync::{Arc, Mutex},
};

use wayland_backend::{client::InvalidId, smallvec::SmallVec};
use wayland_client::{
    protocol::{
        wl_pointer::{self, WlPointer},
        wl_seat::WlSeat,
        wl_shm::WlShm,
        wl_surface::WlSurface,
    },
    Connection, Dispatch, Proxy, QueueHandle, WEnum,
};
use wayland_cursor::{Cursor, CursorTheme};
use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::WpCursorShapeDeviceV1;

use crate::{
    compositor::{SurfaceData, SurfaceDataExt},
    error::GlobalError,
};

use super::SeatState;

#[doc(inline)]
pub use cursor_icon::{CursorIcon, ParseError as CursorIconParseError};

pub mod cursor_shape;

use cursor_shape::cursor_icon_to_shape;

/* From linux/input-event-codes.h - the buttons usually used by mice */
pub const BTN_LEFT: u32 = 0x110;
pub const BTN_RIGHT: u32 = 0x111;
pub const BTN_MIDDLE: u32 = 0x112;
/// The fourth non-scroll button, which is often used as "back" in web browsers.
pub const BTN_SIDE: u32 = 0x113;
/// The fifth non-scroll button, which is often used as "forward" in web browsers.
pub const BTN_EXTRA: u32 = 0x114;

/// See also [`BTN_EXTRA`].
pub const BTN_FORWARD: u32 = 0x115;
/// See also [`BTN_SIDE`].
pub const BTN_BACK: u32 = 0x116;
pub const BTN_TASK: u32 = 0x117;

/// Describes a scroll along one axis
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct AxisScroll {
    /// The scroll measured in pixels.
    pub absolute: f64,

    /// The scroll measured in steps.
    ///
    /// Note: this might always be zero if the scrolling is due to a touchpad or other continuous
    /// source.
    pub discrete: i32,

    /// The scroll was stopped.
    ///
    /// Generally this is encountered when hardware indicates the end of some continuous scrolling.
    pub stop: bool,
}

impl AxisScroll {
    /// Returns true if there was no movement along this axis.
    pub fn is_none(&self) -> bool {
        *self == Self::default()
    }

    fn merge(&mut self, other: &Self) {
        self.absolute += other.absolute;
        self.discrete += other.discrete;
        self.stop |= other.stop;
    }
}

/// A single pointer event.
#[derive(Debug, Clone)]
pub struct PointerEvent {
    pub surface: WlSurface,
    pub position: (f64, f64),
    pub kind: PointerEventKind,
}

#[derive(Debug, Clone)]
pub enum PointerEventKind {
    Enter {
        serial: u32,
    },
    Leave {
        serial: u32,
    },
    Motion {
        time: u32,
    },
    Press {
        time: u32,
        button: u32,
        serial: u32,
    },
    Release {
        time: u32,
        button: u32,
        serial: u32,
    },
    Axis {
        time: u32,
        horizontal: AxisScroll,
        vertical: AxisScroll,
        source: Option<wl_pointer::AxisSource>,
    },
}

pub trait PointerHandler: Sized {
    /// One or more pointer events are available.
    ///
    /// Multiple related events may be grouped together in a single frame.  Some examples:
    ///
    /// - A drag that terminates outside the surface may send the Release and Leave events as one frame
    /// - Movement from one surface to another may send the Enter and Leave events in one frame
    fn pointer_frame(
        &mut self,
        conn: &Connection,
        qh: &QueueHandle<Self>,
        pointer: &WlPointer,
        events: &[PointerEvent],
    );
}

#[derive(Debug)]
pub struct PointerData {
    seat: WlSeat,
    pub(crate) inner: Mutex<PointerDataInner>,
}

impl PointerData {
    pub fn new(seat: WlSeat) -> Self {
        Self { seat, inner: Default::default() }
    }

    /// The seat associated with this pointer.
    pub fn seat(&self) -> &WlSeat {
        &self.seat
    }

    /// Serial from the latest [`PointerEventKind::Enter`] event.
    pub fn latest_enter_serial(&self) -> Option<u32> {
        self.inner.lock().unwrap().latest_enter
    }

    /// Serial from the latest button [`PointerEventKind::Press`] and
    /// [`PointerEventKind::Release`] events.
    pub fn latest_button_serial(&self) -> Option<u32> {
        self.inner.lock().unwrap().latest_btn
    }
}

pub trait PointerDataExt: Send + Sync {
    fn pointer_data(&self) -> &PointerData;
}

impl PointerDataExt for PointerData {
    fn pointer_data(&self) -> &PointerData {
        self
    }
}

#[macro_export]
macro_rules! delegate_pointer {
    ($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => {
        $crate::delegate_pointer!(@{ $(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty }; pointer: []);
        $crate::delegate_pointer!(@{ $(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty }; pointer-only: $crate::seat::pointer::PointerData);
    };
    ($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty, pointer: [$($pointer_data:ty),* $(,)?]) => {
        $crate::delegate_pointer!(@{ $(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty }; pointer: [ $($pointer_data),* ]);
    };
    (@{$($ty:tt)*}; pointer: []) => {
        $crate::reexports::client::delegate_dispatch!($($ty)*:
            [
                $crate::reexports::protocols::wp::cursor_shape::v1::client::wp_cursor_shape_manager_v1::WpCursorShapeManagerV1: $crate::globals::GlobalData
            ] => $crate::seat::pointer::cursor_shape::CursorShapeManager
        );
        $crate::reexports::client::delegate_dispatch!($($ty)*:
            [
                $crate::reexports::protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::WpCursorShapeDeviceV1: $crate::globals::GlobalData
            ] => $crate::seat::pointer::cursor_shape::CursorShapeManager
        );
    };
    (@{$($ty:tt)*}; pointer-only: $pointer_data:ty) => {
        $crate::reexports::client::delegate_dispatch!($($ty)*:
            [
                $crate::reexports::client::protocol::wl_pointer::WlPointer: $pointer_data
            ] => $crate::seat::SeatState
        );
    };
    (@$ty:tt; pointer: [$($pointer:ty),*]) => {
        $crate::delegate_pointer!(@$ty; pointer: []);
        $( $crate::delegate_pointer!(@$ty; pointer-only: $pointer); )*
    }
}

#[derive(Debug, Default)]
pub(crate) struct PointerDataInner {
    /// Surface the pointer most recently entered
    pub(crate) surface: Option<WlSurface>,
    /// Position relative to the surface
    pub(crate) position: (f64, f64),

    /// List of pending events.  Only used for version >= 5.
    pub(crate) pending: SmallVec<[PointerEvent; 3]>,

    /// The serial of the latest enter event for the pointer
    pub(crate) latest_enter: Option<u32>,

    /// The serial of the latest enter event for the pointer
    pub(crate) latest_btn: Option<u32>,
}

impl<D, U> Dispatch<WlPointer, U, D> for SeatState
where
    D: Dispatch<WlPointer, U> + PointerHandler,
    U: PointerDataExt,
{
    fn event(
        data: &mut D,
        pointer: &WlPointer,
        event: wl_pointer::Event,
        udata: &U,
        conn: &Connection,
        qh: &QueueHandle<D>,
    ) {
        let udata = udata.pointer_data();
        let mut guard = udata.inner.lock().unwrap();
        let mut leave_surface = None;
        let kind = match event {
            wl_pointer::Event::Enter { surface, surface_x, surface_y, serial } => {
                guard.surface = Some(surface);
                guard.position = (surface_x, surface_y);
                guard.latest_enter.replace(serial);

                PointerEventKind::Enter { serial }
            }

            wl_pointer::Event::Leave { surface, serial } => {
                if guard.surface.as_ref() == Some(&surface) {
                    guard.surface = None;
                }
                leave_surface = Some(surface);

                PointerEventKind::Leave { serial }
            }

            wl_pointer::Event::Motion { time, surface_x, surface_y } => {
                guard.position = (surface_x, surface_y);

                PointerEventKind::Motion { time }
            }

            wl_pointer::Event::Button { time, button, state, serial } => {
                guard.latest_btn.replace(serial);
                match state {
                    WEnum::Value(wl_pointer::ButtonState::Pressed) => {
                        PointerEventKind::Press { time, button, serial }
                    }
                    WEnum::Value(wl_pointer::ButtonState::Released) => {
                        PointerEventKind::Release { time, button, serial }
                    }
                    WEnum::Unknown(unknown) => {
                        log::warn!(target: "sctk", "{}: invalid pointer button state: {:x}", pointer.id(), unknown);
                        return;
                    }
                    _ => unreachable!(),
                }
            }
            // Axis logical events.
            wl_pointer::Event::Axis { time, axis, value } => match axis {
                WEnum::Value(axis) => {
                    let (mut horizontal, mut vertical) = <(AxisScroll, AxisScroll)>::default();
                    match axis {
                        wl_pointer::Axis::VerticalScroll => {
                            vertical.absolute = value;
                        }
                        wl_pointer::Axis::HorizontalScroll => {
                            horizontal.absolute = value;
                        }
                        _ => unreachable!(),
                    };

                    PointerEventKind::Axis { time, horizontal, vertical, source: None }
                }
                WEnum::Unknown(unknown) => {
                    log::warn!(target: "sctk", "{}: invalid pointer axis: {:x}", pointer.id(), unknown);
                    return;
                }
            },

            wl_pointer::Event::AxisSource { axis_source } => match axis_source {
                WEnum::Value(source) => PointerEventKind::Axis {
                    horizontal: AxisScroll::default(),
                    vertical: AxisScroll::default(),
                    source: Some(source),
                    time: 0,
                },
                WEnum::Unknown(unknown) => {
                    log::warn!(target: "sctk", "unknown pointer axis source: {:x}", unknown);
                    return;
                }
            },

            wl_pointer::Event::AxisStop { time, axis } => match axis {
                WEnum::Value(axis) => {
                    let (mut horizontal, mut vertical) = <(AxisScroll, AxisScroll)>::default();
                    match axis {
                        wl_pointer::Axis::VerticalScroll => vertical.stop = true,
                        wl_pointer::Axis::HorizontalScroll => horizontal.stop = true,

                        _ => unreachable!(),
                    }

                    PointerEventKind::Axis { time, horizontal, vertical, source: None }
                }

                WEnum::Unknown(unknown) => {
                    log::warn!(target: "sctk", "{}: invalid pointer axis: {:x}", pointer.id(), unknown);
                    return;
                }
            },

            wl_pointer::Event::AxisDiscrete { axis, discrete } => match axis {
                WEnum::Value(axis) => {
                    let (mut horizontal, mut vertical) = <(AxisScroll, AxisScroll)>::default();
                    match axis {
                        wl_pointer::Axis::VerticalScroll => {
                            vertical.discrete = discrete;
                        }

                        wl_pointer::Axis::HorizontalScroll => {
                            horizontal.discrete = discrete;
                        }

                        _ => unreachable!(),
                    };

                    PointerEventKind::Axis { time: 0, horizontal, vertical, source: None }
                }

                WEnum::Unknown(unknown) => {
                    log::warn!(target: "sctk", "{}: invalid pointer axis: {:x}", pointer.id(), unknown);
                    return;
                }
            },

            wl_pointer::Event::Frame => {
                let pending = mem::take(&mut guard.pending);
                drop(guard);
                if !pending.is_empty() {
                    data.pointer_frame(conn, qh, pointer, &pending);
                }
                return;
            }

            _ => unreachable!(),
        };

        let surface = match (leave_surface, &guard.surface) {
            (Some(surface), _) => surface,
            (None, Some(surface)) => surface.clone(),
            (None, None) => {
                log::warn!(target: "sctk", "{}: got pointer event {:?} without an entered surface", pointer.id(), kind);
                return;
            }
        };

        let event = PointerEvent { surface, position: guard.position, kind };

        if pointer.version() < 5 {
            drop(guard);
            // No Frame events, send right away
            data.pointer_frame(conn, qh, pointer, &[event]);
        } else {
            // Merge a new Axis event with the previous event to create an event with more
            // information and potentially diagonal scrolling.
            if let (
                Some(PointerEvent {
                    kind:
                        PointerEventKind::Axis { time: ot, horizontal: oh, vertical: ov, source: os },
                    ..
                }),
                PointerEvent {
                    kind:
                        PointerEventKind::Axis { time: nt, horizontal: nh, vertical: nv, source: ns },
                    ..
                },
            ) = (guard.pending.last_mut(), &event)
            {
                // A time of 0 is "don't know", so avoid using it if possible.
                if *ot == 0 {
                    *ot = *nt;
                }
                oh.merge(nh);
                ov.merge(nv);
                *os = os.or(*ns);
                return;
            }

            guard.pending.push(event);
        }
    }
}

/// Pointer themeing
#[derive(Debug)]
pub struct ThemedPointer<U = PointerData, S = SurfaceData> {
    pub(super) themes: Arc<Mutex<Themes>>,
    /// The underlying wl_pointer.
    pub(super) pointer: WlPointer,
    pub(super) shm: WlShm,
    /// The surface owned by the cursor to present the icon.
    pub(super) surface: WlSurface,
    pub(super) shape_device: Option<WpCursorShapeDeviceV1>,
    pub(super) _marker: std::marker::PhantomData<U>,
    pub(super) _surface_data: std::marker::PhantomData<S>,
}

impl<U: PointerDataExt + 'static, S: SurfaceDataExt + 'static> ThemedPointer<U, S> {
    /// Set the cursor to the given [`CursorIcon`].
    ///
    /// The cursor icon should be reloaded on every [`PointerEventKind::Enter`] event.
    pub fn set_cursor(&self, conn: &Connection, icon: CursorIcon) -> Result<(), PointerThemeError> {
        let serial = match self
            .pointer
            .data::<U>()
            .and_then(|data| data.pointer_data().latest_enter_serial())
        {
            Some(serial) => serial,
            None => return Err(PointerThemeError::MissingEnterSerial),
        };

        if let Some(shape_device) = self.shape_device.as_ref() {
            shape_device.set_shape(serial, cursor_icon_to_shape(icon));
            Ok(())
        } else {
            self.set_cursor_legacy(conn, serial, icon)
        }
    }

    /// The legacy method of loading the cursor from the system cursor
    /// theme instead of relying on compositor to set the cursor.
    fn set_cursor_legacy(
        &self,
        conn: &Connection,
        serial: u32,
        icon: CursorIcon,
    ) -> Result<(), PointerThemeError> {
        let mut themes = self.themes.lock().unwrap();

        let scale = self.surface.data::<S>().unwrap().surface_data().scale_factor();
        for cursor_icon_name in iter::once(&icon.name()).chain(icon.alt_names().iter()) {
            if let Some(cursor) = themes
                .get_cursor(conn, cursor_icon_name, scale as u32, &self.shm)
                .map_err(PointerThemeError::InvalidId)?
            {
                let image = &cursor[0];
                let (w, h) = image.dimensions();
                let (hx, hy) = image.hotspot();

                self.surface.set_buffer_scale(scale);
                self.surface.attach(Some(image), 0, 0);

                if self.surface.version() >= 4 {
                    self.surface.damage_buffer(0, 0, w as i32, h as i32);
                } else {
                    // Fallback for the old old surface.
                    self.surface.damage(0, 0, w as i32 / scale, h as i32 / scale);
                }

                // Commit the surface to place the cursor image in the compositor's memory.
                self.surface.commit();

                // Set the pointer surface to change the pointer.
                self.pointer.set_cursor(
                    serial,
                    Some(&self.surface),
                    hx as i32 / scale,
                    hy as i32 / scale,
                );

                return Ok(());
            }
        }

        Err(PointerThemeError::CursorNotFound)
    }

    /// Hide the cursor by providing empty surface for it.
    ///
    /// The cursor should be hidden on every [`PointerEventKind::Enter`] event.
    pub fn hide_cursor(&self) -> Result<(), PointerThemeError> {
        let data = self.pointer.data::<U>();
        if let Some(serial) = data.and_then(|data| data.pointer_data().latest_enter_serial()) {
            self.pointer.set_cursor(serial, None, 0, 0);
            Ok(())
        } else {
            Err(PointerThemeError::MissingEnterSerial)
        }
    }

    /// The [`WlPointer`] associated with this [`ThemedPointer`].
    pub fn pointer(&self) -> &WlPointer {
        &self.pointer
    }

    /// The associated [`WlSurface`] with this [`ThemedPointer`].
    pub fn surface(&self) -> &WlSurface {
        &self.surface
    }
}

impl<U, S> Drop for ThemedPointer<U, S> {
    fn drop(&mut self) {
        if let Some(shape_device) = self.shape_device.take() {
            shape_device.destroy();
        }

        if self.pointer.version() >= 3 {
            self.pointer.release();
        }
        self.surface.destroy();
    }
}

/// Specifies which cursor theme should be used by the theme manager.
#[derive(Debug)]
pub enum ThemeSpec<'a> {
    /// Use this specific theme with the given base size.
    Named {
        /// Name of the cursor theme.
        name: &'a str,

        /// Base size of the cursor names.
        ///
        /// Note this size assumes a scale factor of 1. Cursor image sizes may be multiplied by the base size
        /// for HiDPI outputs.
        size: u32,
    },

    /// Use the system provided theme
    ///
    /// In this case SCTK will read the `XCURSOR_THEME` and
    /// `XCURSOR_SIZE` environment variables to figure out the
    /// theme to use.
    System,
}

impl<'a> Default for ThemeSpec<'a> {
    fn default() -> Self {
        Self::System
    }
}

/// An error indicating that the cursor was not found.
#[derive(Debug, thiserror::Error)]
pub enum PointerThemeError {
    /// An invalid ObjectId was used.
    #[error("Invalid ObjectId")]
    InvalidId(InvalidId),

    /// A global error occurred.
    #[error("A Global Error occured")]
    GlobalError(GlobalError),

    /// The requested cursor was not found.
    #[error("Cursor not found")]
    CursorNotFound,

    /// There has been no enter event yet for the pointer.
    #[error("Missing enter event serial")]
    MissingEnterSerial,
}

#[derive(Debug)]
pub(crate) struct Themes {
    name: String,
    size: u32,
    // Scale -> CursorTheme
    themes: HashMap<u32, CursorTheme>,
}

impl Default for Themes {
    fn default() -> Self {
        Themes::new(ThemeSpec::default())
    }
}

impl Themes {
    pub(crate) fn new(spec: ThemeSpec) -> Themes {
        let (name, size) = match spec {
            ThemeSpec::Named { name, size } => (name.into(), size),
            ThemeSpec::System => {
                let name = env::var("XCURSOR_THEME").ok().unwrap_or_else(|| "default".into());
                let size = env::var("XCURSOR_SIZE").ok().and_then(|s| s.parse().ok()).unwrap_or(24);
                (name, size)
            }
        };

        Themes { name, size, themes: HashMap::new() }
    }

    fn get_cursor(
        &mut self,
        conn: &Connection,
        name: &str,
        scale: u32,
        shm: &WlShm,
    ) -> Result<Option<&Cursor>, InvalidId> {
        // Check if the theme has been initialized at the specified scale.
        if let Entry::Vacant(e) = self.themes.entry(scale) {
            // Initialize the theme for the specified scale
            let theme = CursorTheme::load_from_name(
                conn,
                shm.clone(), // TODO: Does the cursor theme need to clone wl_shm?
                &self.name,
                self.size * scale,
            )?;

            e.insert(theme);
        }

        let theme = self.themes.get_mut(&scale).unwrap();

        Ok(theme.get_cursor(name))
    }
}