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
use anyhow::{anyhow, Result};
use std::{
    error::Error,
    fmt::{self, Display},
};

pub mod scancode;

// FIXME
pub const BTN_LEFT: u32 = 0x110;
pub const BTN_RIGHT: u32 = 0x111;
pub const BTN_MIDDLE: u32 = 0x112;
pub const BTN_BACK: u32 = 0x113;
pub const BTN_FORWARD: u32 = 0x114;

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum PointerEvent {
    Motion {
        time: u32,
        relative_x: f64,
        relative_y: f64,
    },
    Button {
        time: u32,
        button: u32,
        state: u32,
    },
    Axis {
        time: u32,
        axis: u8,
        value: f64,
    },
    AxisDiscrete120 {
        axis: u8,
        value: i32,
    },
    Frame {},
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum KeyboardEvent {
    Key {
        time: u32,
        key: u32,
        state: u8,
    },
    Modifiers {
        mods_depressed: u32,
        mods_latched: u32,
        mods_locked: u32,
        group: u32,
    },
}

#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Event {
    /// pointer event (motion / button / axis)
    Pointer(PointerEvent),
    /// keyboard events (key / modifiers)
    Keyboard(KeyboardEvent),
    /// enter event: request to enter a client.
    /// The client must release the pointer if it is grabbed
    /// and reply with a leave event, as soon as its ready to
    /// receive events
    Enter(),
    /// leave event: this client is now ready to receive events and will
    /// not send any events after until it sends an enter event
    Leave(),
    /// ping a client, to see if it is still alive. A client that does
    /// not respond with a pong event will be assumed to be offline.
    Ping(),
    /// response to a ping event: this event signals that a client
    /// is still alive but must otherwise be ignored
    Pong(),
    /// explicit disconnect request. The client will no longer
    /// send events until the next Enter event. All of its keys should be released.
    Disconnect(),
}

impl Display for PointerEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PointerEvent::Motion {
                time: _,
                relative_x,
                relative_y,
            } => write!(f, "motion({relative_x},{relative_y})"),
            PointerEvent::Button {
                time: _,
                button,
                state,
            } => {
                let str = match *button {
                    BTN_LEFT => Some("left"),
                    BTN_RIGHT => Some("right"),
                    BTN_MIDDLE => Some("middle"),
                    BTN_FORWARD => Some("forward"),
                    BTN_BACK => Some("back"),
                    _ => None,
                };
                if let Some(button) = str {
                    write!(f, "button({button}, {state})")
                } else {
                    write!(f, "button({button}, {state}")
                }
            }
            PointerEvent::Axis {
                time: _,
                axis,
                value,
            } => write!(f, "scroll({axis}, {value})"),
            PointerEvent::AxisDiscrete120 { axis, value } => {
                write!(f, "scroll-120 ({axis}, {value})")
            }
            PointerEvent::Frame {} => write!(f, "frame()"),
        }
    }
}

impl Display for KeyboardEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyboardEvent::Key {
                time: _,
                key,
                state,
            } => {
                let scan = scancode::Linux::try_from(*key);
                if let Ok(scan) = scan {
                    write!(f, "key({scan:?}, {state})")
                } else {
                    write!(f, "key({key}, {state})")
                }
            }
            KeyboardEvent::Modifiers {
                mods_depressed,
                mods_latched,
                mods_locked,
                group,
            } => write!(
                f,
                "modifiers({mods_depressed},{mods_latched},{mods_locked},{group})"
            ),
        }
    }
}

impl Display for Event {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Event::Pointer(p) => write!(f, "{}", p),
            Event::Keyboard(k) => write!(f, "{}", k),
            Event::Enter() => write!(f, "enter"),
            Event::Leave() => write!(f, "leave"),
            Event::Ping() => write!(f, "ping"),
            Event::Pong() => write!(f, "pong"),
            Event::Disconnect() => write!(f, "disconnect"),
        }
    }
}

impl Event {
    fn event_type(&self) -> EventType {
        match self {
            Self::Pointer(_) => EventType::Pointer,
            Self::Keyboard(_) => EventType::Keyboard,
            Self::Enter() => EventType::Enter,
            Self::Leave() => EventType::Leave,
            Self::Ping() => EventType::Ping,
            Self::Pong() => EventType::Pong,
            Self::Disconnect() => EventType::Disconnect,
        }
    }
}

impl PointerEvent {
    fn event_type(&self) -> PointerEventType {
        match self {
            Self::Motion { .. } => PointerEventType::Motion,
            Self::Button { .. } => PointerEventType::Button,
            Self::Axis { .. } => PointerEventType::Axis,
            Self::AxisDiscrete120 { .. } => PointerEventType::AxisDiscrete120,
            Self::Frame { .. } => PointerEventType::Frame,
        }
    }
}

impl KeyboardEvent {
    fn event_type(&self) -> KeyboardEventType {
        match self {
            KeyboardEvent::Key { .. } => KeyboardEventType::Key,
            KeyboardEvent::Modifiers { .. } => KeyboardEventType::Modifiers,
        }
    }
}

enum PointerEventType {
    Motion,
    Button,
    Axis,
    AxisDiscrete120,
    Frame,
}
enum KeyboardEventType {
    Key,
    Modifiers,
}
enum EventType {
    Pointer,
    Keyboard,
    Enter,
    Leave,
    Ping,
    Pong,
    Disconnect,
}

impl TryFrom<u8> for PointerEventType {
    type Error = anyhow::Error;

    fn try_from(value: u8) -> Result<Self> {
        match value {
            x if x == Self::Motion as u8 => Ok(Self::Motion),
            x if x == Self::Button as u8 => Ok(Self::Button),
            x if x == Self::Axis as u8 => Ok(Self::Axis),
            x if x == Self::AxisDiscrete120 as u8 => Ok(Self::AxisDiscrete120),
            x if x == Self::Frame as u8 => Ok(Self::Frame),
            _ => Err(anyhow!(ProtocolError {
                msg: format!("invalid pointer event type {}", value),
            })),
        }
    }
}

impl TryFrom<u8> for KeyboardEventType {
    type Error = anyhow::Error;

    fn try_from(value: u8) -> Result<Self> {
        match value {
            x if x == Self::Key as u8 => Ok(Self::Key),
            x if x == Self::Modifiers as u8 => Ok(Self::Modifiers),
            _ => Err(anyhow!(ProtocolError {
                msg: format!("invalid keyboard event type {}", value),
            })),
        }
    }
}

impl From<&Event> for Vec<u8> {
    fn from(event: &Event) -> Self {
        let event_id = vec![event.event_type() as u8];
        let event_data = match event {
            Event::Pointer(p) => p.into(),
            Event::Keyboard(k) => k.into(),
            Event::Enter() => vec![],
            Event::Leave() => vec![],
            Event::Ping() => vec![],
            Event::Pong() => vec![],
            Event::Disconnect() => vec![],
        };
        [event_id, event_data].concat()
    }
}

#[derive(Debug)]
struct ProtocolError {
    msg: String,
}

impl fmt::Display for ProtocolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Protocol violation: {}", self.msg)
    }
}
impl Error for ProtocolError {}

impl TryFrom<Vec<u8>> for Event {
    type Error = anyhow::Error;

    fn try_from(value: Vec<u8>) -> Result<Self> {
        let event_id = u8::from_be_bytes(value[..1].try_into()?);
        match event_id {
            i if i == (EventType::Pointer as u8) => Ok(Event::Pointer(value.try_into()?)),
            i if i == (EventType::Keyboard as u8) => Ok(Event::Keyboard(value.try_into()?)),
            i if i == (EventType::Enter as u8) => Ok(Event::Enter()),
            i if i == (EventType::Leave as u8) => Ok(Event::Leave()),
            i if i == (EventType::Ping as u8) => Ok(Event::Ping()),
            i if i == (EventType::Pong as u8) => Ok(Event::Pong()),
            i if i == (EventType::Disconnect as u8) => Ok(Event::Disconnect()),
            _ => Err(anyhow!(ProtocolError {
                msg: format!("invalid event_id {}", event_id),
            })),
        }
    }
}

impl From<&PointerEvent> for Vec<u8> {
    fn from(event: &PointerEvent) -> Self {
        let id = vec![event.event_type() as u8];
        let data = match event {
            PointerEvent::Motion {
                time,
                relative_x,
                relative_y,
            } => {
                let time = time.to_be_bytes();
                let relative_x = relative_x.to_be_bytes();
                let relative_y = relative_y.to_be_bytes();
                [&time[..], &relative_x[..], &relative_y[..]].concat()
            }
            PointerEvent::Button {
                time,
                button,
                state,
            } => {
                let time = time.to_be_bytes();
                let button = button.to_be_bytes();
                let state = state.to_be_bytes();
                [&time[..], &button[..], &state[..]].concat()
            }
            PointerEvent::Axis { time, axis, value } => {
                let time = time.to_be_bytes();
                let axis = axis.to_be_bytes();
                let value = value.to_be_bytes();
                [&time[..], &axis[..], &value[..]].concat()
            }
            PointerEvent::AxisDiscrete120 { axis, value } => {
                let axis = axis.to_be_bytes();
                let value = value.to_be_bytes();
                [&axis[..], &value[..]].concat()
            }
            PointerEvent::Frame {} => {
                vec![]
            }
        };
        [id, data].concat()
    }
}

impl TryFrom<Vec<u8>> for PointerEvent {
    type Error = anyhow::Error;

    fn try_from(data: Vec<u8>) -> Result<Self> {
        match data.get(1) {
            Some(id) => {
                let event_type = match id.to_owned().try_into() {
                    Ok(event_type) => event_type,
                    Err(e) => return Err(e),
                };
                match event_type {
                    PointerEventType::Motion => {
                        let time = match data.get(2..6) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 2".into(),
                                }))
                            }
                        };
                        let relative_x = match data.get(6..14) {
                            Some(d) => f64::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 8 Bytes at index 6".into(),
                                }))
                            }
                        };
                        let relative_y = match data.get(14..22) {
                            Some(d) => f64::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 8 Bytes at index 14".into(),
                                }))
                            }
                        };
                        Ok(Self::Motion {
                            time,
                            relative_x,
                            relative_y,
                        })
                    }
                    PointerEventType::Button => {
                        let time = match data.get(2..6) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 2".into(),
                                }))
                            }
                        };
                        let button = match data.get(6..10) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 10".into(),
                                }))
                            }
                        };
                        let state = match data.get(10..14) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 14".into(),
                                }))
                            }
                        };
                        Ok(Self::Button {
                            time,
                            button,
                            state,
                        })
                    }
                    PointerEventType::Axis => {
                        let time = match data.get(2..6) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 2".into(),
                                }))
                            }
                        };
                        let axis = match data.get(6) {
                            Some(d) => *d,
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 1 Byte at index 6".into(),
                                }));
                            }
                        };
                        let value = match data.get(7..15) {
                            Some(d) => f64::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 8 Bytes at index 7".into(),
                                }));
                            }
                        };
                        Ok(Self::Axis { time, axis, value })
                    }
                    PointerEventType::AxisDiscrete120 => {
                        let axis = match data.get(2) {
                            Some(d) => *d,
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 1 Byte at index 2".into(),
                                }));
                            }
                        };
                        let value = match data.get(3..7) {
                            Some(d) => i32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 3".into(),
                                }));
                            }
                        };
                        Ok(Self::AxisDiscrete120 { axis, value })
                    }
                    PointerEventType::Frame => Ok(Self::Frame {}),
                }
            }
            None => Err(anyhow!(ProtocolError {
                msg: "Expected an element at index 0".into(),
            })),
        }
    }
}

impl From<&KeyboardEvent> for Vec<u8> {
    fn from(event: &KeyboardEvent) -> Self {
        let id = vec![event.event_type() as u8];
        let data = match event {
            KeyboardEvent::Key { time, key, state } => {
                let time = time.to_be_bytes();
                let key = key.to_be_bytes();
                let state = state.to_be_bytes();
                [&time[..], &key[..], &state[..]].concat()
            }
            KeyboardEvent::Modifiers {
                mods_depressed,
                mods_latched,
                mods_locked,
                group,
            } => {
                let mods_depressed = mods_depressed.to_be_bytes();
                let mods_latched = mods_latched.to_be_bytes();
                let mods_locked = mods_locked.to_be_bytes();
                let group = group.to_be_bytes();
                [
                    &mods_depressed[..],
                    &mods_latched[..],
                    &mods_locked[..],
                    &group[..],
                ]
                .concat()
            }
        };
        [id, data].concat()
    }
}

impl TryFrom<Vec<u8>> for KeyboardEvent {
    type Error = anyhow::Error;

    fn try_from(data: Vec<u8>) -> Result<Self> {
        match data.get(1) {
            Some(id) => {
                let event_type = match id.to_owned().try_into() {
                    Ok(event_type) => event_type,
                    Err(e) => return Err(e),
                };
                match event_type {
                    KeyboardEventType::Key => {
                        let time = match data.get(2..6) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 6".into(),
                                }))
                            }
                        };
                        let key = match data.get(6..10) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 10".into(),
                                }))
                            }
                        };
                        let state = match data.get(10) {
                            Some(d) => *d,
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 1 Bytes at index 14".into(),
                                }))
                            }
                        };
                        Ok(KeyboardEvent::Key { time, key, state })
                    }
                    KeyboardEventType::Modifiers => {
                        let mods_depressed = match data.get(2..6) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 6".into(),
                                }))
                            }
                        };
                        let mods_latched = match data.get(6..10) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 10".into(),
                                }))
                            }
                        };
                        let mods_locked = match data.get(10..14) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 14".into(),
                                }))
                            }
                        };
                        let group = match data.get(14..18) {
                            Some(d) => u32::from_be_bytes(d.try_into()?),
                            None => {
                                return Err(anyhow!(ProtocolError {
                                    msg: "Expected 4 Bytes at index 18".into(),
                                }))
                            }
                        };
                        Ok(KeyboardEvent::Modifiers {
                            mods_depressed,
                            mods_latched,
                            mods_locked,
                            group,
                        })
                    }
                }
            }
            None => Err(anyhow!(ProtocolError {
                msg: "Expected an element at index 0".into(),
            })),
        }
    }
}