summary refs log tree commit diff
path: root/gpu_display/src/event_device.rs
blob: 673a10469821a78738e1ea4680e0808a71f10c64 (plain) (blame)
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
// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::collections::VecDeque;
use std::io::{self, Read, Write};
use std::iter::ExactSizeIterator;
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;

const EVENT_SIZE: usize = 4;
const EVENT_BUFFER_LEN_MAX: usize = 16 * EVENT_SIZE;

const EV_SYN: u16 = 0x00;
const EV_KEY: u16 = 0x01;
const EV_REL: u16 = 0x02;
const EV_ABS: u16 = 0x03;
const SYN_REPORT: u16 = 0;
const REL_X: u16 = 0x00;
const REL_Y: u16 = 0x01;
const ABS_X: u16 = 0x00;
const ABS_Y: u16 = 0x01;

// /// Half-way build `EventDevice` with only the `event_socket` defined. Finish building the
// /// `EventDevice` by using `status_socket`.
// pub struct PartialEventDevice(UnixStream);

// impl PartialEventDevice {
//     /// Finish build `EventDevice` by providing the `status_socket`.
//     pub fn status_socket(self, status_socket: UnixStream) -> EventDevice {
//         EventDevice {
//             event_socket: self.0,
//             status_socket,
//         }
//     }
// }

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum EventDeviceKind {
    /// Produces relative mouse motions, wheel, and button clicks while the real mouse is captured.
    Mouse,
    /// Produces absolute motion and touch events from the display window's events.
    Touchscreen,
    /// Produces key events while the display window has focus.
    Keyboard,
}

#[derive(Copy, Clone, Default, PartialEq, Eq, Debug)]
pub struct EventEncoded {
    pub type_: u16,
    pub code: u16,
    pub value: u32,
}

impl EventEncoded {
    #[inline]
    pub fn syn() -> EventEncoded {
        EventEncoded {
            type_: EV_SYN,
            code: SYN_REPORT,
            value: 0,
        }
    }

    #[inline]
    pub fn absolute(code: u16, value: u32) -> EventEncoded {
        EventEncoded {
            type_: EV_ABS,
            code,
            value,
        }
    }

    #[inline]
    pub fn absolute_x(x: u32) -> EventEncoded {
        Self::absolute(ABS_X, x)
    }

    #[inline]
    pub fn absolute_y(y: u32) -> EventEncoded {
        Self::absolute(ABS_Y, y)
    }

    #[inline]
    pub fn key(code: u16, pressed: bool) -> EventEncoded {
        EventEncoded {
            type_: EV_KEY,
            code,
            value: if pressed { 1 } else { 0 },
        }
    }

    #[inline]
    pub fn from_bytes(v: [u8; 8]) -> EventEncoded {
        EventEncoded {
            type_: u16::from_le_bytes([v[0], v[1]]),
            code: u16::from_le_bytes([v[2], v[3]]),
            value: u32::from_le_bytes([v[4], v[5], v[6], v[7]]),
        }
    }

    #[inline]
    pub fn to_bytes(&self) -> [u8; 8] {
        let a = self.type_.to_le_bytes();
        let b = self.code.to_le_bytes();
        let c = self.value.to_le_bytes();
        [a[0], a[1], b[0], b[1], c[0], c[1], c[2], c[3]]
    }
}

/// Encapsulates a virtual event device, such as a mouse or keyboard
pub struct EventDevice {
    kind: EventDeviceKind,
    event_buffer: VecDeque<u8>,
    event_socket: UnixStream,
}

impl EventDevice {
    pub fn new(kind: EventDeviceKind, event_socket: UnixStream) -> EventDevice {
        let _ = event_socket.set_nonblocking(true);
        EventDevice {
            kind,
            event_buffer: Default::default(),
            event_socket,
        }
    }

    #[inline]
    pub fn mouse(event_socket: UnixStream) -> EventDevice {
        Self::new(EventDeviceKind::Mouse, event_socket)
    }

    #[inline]
    pub fn touchscreen(event_socket: UnixStream) -> EventDevice {
        Self::new(EventDeviceKind::Touchscreen, event_socket)
    }

    #[inline]
    pub fn keyboard(event_socket: UnixStream) -> EventDevice {
        Self::new(EventDeviceKind::Keyboard, event_socket)
    }

    #[inline]
    pub fn kind(&self) -> EventDeviceKind {
        self.kind
    }

    /// Flushes the buffered events that did not fit into the underlying transport, if any.
    ///
    /// Returns `Ok(true)` if, after this function returns, there all the buffer of events is
    /// empty.
    pub fn flush_buffered_events(&mut self) -> io::Result<bool> {
        while !self.event_buffer.is_empty() {
            let written = self.event_socket.write(&self.event_buffer.as_slices().0)?;
            if written == 0 {
                return Ok(false);
            }
            self.event_buffer.drain(..written);
        }
        Ok(true)
    }

    pub fn is_buffered_events_empty(&self) -> bool {
        self.event_buffer.is_empty()
    }

    pub fn send_report<E: IntoIterator<Item = EventEncoded>>(
        &mut self,
        events: E,
    ) -> io::Result<bool>
    where
        E::IntoIter: ExactSizeIterator,
    {
        let it = events.into_iter();
        if self.event_buffer.len() > (EVENT_BUFFER_LEN_MAX - EVENT_SIZE * (it.len() + 1)) {
            return Ok(false);
        }

        for event in it {
            let bytes = event.to_bytes();
            self.event_buffer.extend(bytes.iter());
        }

        self.event_buffer
            .extend(EventEncoded::syn().to_bytes().iter());

        self.flush_buffered_events()
    }

    /// Sends the given `event`, returning `Ok(true)` if, after this function returns, there are no
    /// buffered events remaining.
    pub fn send_event_encoded(&mut self, event: EventEncoded) -> io::Result<bool> {
        if !self.flush_buffered_events()? {
            return Ok(false);
        }

        let bytes = event.to_bytes();
        let written = self.event_socket.write(&bytes)?;

        if written == bytes.len() {
            return Ok(true);
        }

        if self.event_buffer.len() <= (EVENT_BUFFER_LEN_MAX - EVENT_SIZE) {
            self.event_buffer.extend(bytes[written..].iter());
        }

        Ok(false)
    }

    pub fn recv_event_encoded(&self) -> io::Result<EventEncoded> {
        let mut event_bytes = [0; 8];
        (&self.event_socket).read_exact(&mut event_bytes)?;
        Ok(EventEncoded::from_bytes(event_bytes))
    }
}

impl AsRawFd for EventDevice {
    fn as_raw_fd(&self) -> RawFd {
        self.event_socket.as_raw_fd()
    }
}