1 // Copyright 2019 The ChromiumOS Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 use std::collections::VecDeque; 6 use std::fmt; 7 use std::io; 8 use std::io::Error; 9 use std::io::ErrorKind; 10 use std::io::Write; 11 use std::iter::ExactSizeIterator; 12 13 use base::AsRawDescriptor; 14 use base::RawDescriptor; 15 use base::StreamChannel; 16 use data_model::zerocopy_from_reader; 17 use linux_input_sys::virtio_input_event; 18 use linux_input_sys::InputEventDecoder; 19 use serde::Deserialize; 20 use serde::Serialize; 21 use zerocopy::AsBytes; 22 23 const EVENT_SIZE: usize = virtio_input_event::SIZE; 24 const EVENT_BUFFER_LEN_MAX: usize = 64 * EVENT_SIZE; 25 26 // /// Half-way build `EventDevice` with only the `event_socket` defined. Finish building the 27 // /// `EventDevice` by using `status_socket`. 28 // pub struct PartialEventDevice(UnixStream); 29 30 // impl PartialEventDevice { 31 // /// Finish build `EventDevice` by providing the `status_socket`. 32 // pub fn status_socket(self, status_socket: UnixStream) -> EventDevice { 33 // EventDevice { 34 // event_socket: self.0, 35 // status_socket, 36 // } 37 // } 38 // } 39 40 #[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] 41 pub enum EventDeviceKind { 42 /// Produces relative mouse motions, wheel, and button clicks while the real mouse is captured. 43 Mouse, 44 /// Produces absolute motion and touch events from the display window's events. 45 Touchscreen, 46 /// Produces key events while the display window has focus. 47 Keyboard, 48 } 49 50 /// Encapsulates a virtual event device, such as a mouse or keyboard 51 #[derive(Deserialize, Serialize)] 52 pub struct EventDevice { 53 kind: EventDeviceKind, 54 event_buffer: VecDeque<u8>, 55 event_socket: StreamChannel, 56 } 57 58 impl EventDevice { new(kind: EventDeviceKind, mut event_socket: StreamChannel) -> EventDevice59 pub fn new(kind: EventDeviceKind, mut event_socket: StreamChannel) -> EventDevice { 60 let _ = event_socket.set_nonblocking(true); 61 EventDevice { 62 kind, 63 event_buffer: Default::default(), 64 event_socket, 65 } 66 } 67 68 #[inline] mouse(event_socket: StreamChannel) -> EventDevice69 pub fn mouse(event_socket: StreamChannel) -> EventDevice { 70 Self::new(EventDeviceKind::Mouse, event_socket) 71 } 72 73 #[inline] touchscreen(event_socket: StreamChannel) -> EventDevice74 pub fn touchscreen(event_socket: StreamChannel) -> EventDevice { 75 Self::new(EventDeviceKind::Touchscreen, event_socket) 76 } 77 78 #[inline] keyboard(event_socket: StreamChannel) -> EventDevice79 pub fn keyboard(event_socket: StreamChannel) -> EventDevice { 80 Self::new(EventDeviceKind::Keyboard, event_socket) 81 } 82 83 #[inline] kind(&self) -> EventDeviceKind84 pub fn kind(&self) -> EventDeviceKind { 85 self.kind 86 } 87 88 /// Flushes the buffered events that did not fit into the underlying transport, if any. 89 /// 90 /// Returns `Ok(true)` if, after this function returns, there all the buffer of events is 91 /// empty. flush_buffered_events(&mut self) -> io::Result<bool>92 pub fn flush_buffered_events(&mut self) -> io::Result<bool> { 93 while !self.event_buffer.is_empty() { 94 let written = self.event_socket.write(self.event_buffer.as_slices().0)?; 95 if written == 0 { 96 return Ok(false); 97 } 98 self.event_buffer.drain(..written); 99 } 100 Ok(true) 101 } 102 is_buffered_events_empty(&self) -> bool103 pub fn is_buffered_events_empty(&self) -> bool { 104 self.event_buffer.is_empty() 105 } 106 107 /// Determines if there is space in the event buffer for the given number 108 /// of events. The buffer is capped at `EVENT_BUFFER_LEN_MAX`. 109 #[inline] can_buffer_events(&self, num_events: usize) -> bool110 fn can_buffer_events(&self, num_events: usize) -> bool { 111 let event_bytes = match EVENT_SIZE.checked_mul(num_events) { 112 Some(bytes) => bytes, 113 None => return false, 114 }; 115 let free_bytes = EVENT_BUFFER_LEN_MAX.saturating_sub(self.event_buffer.len()); 116 117 free_bytes >= event_bytes 118 } 119 send_report<E: IntoIterator<Item = virtio_input_event>>( &mut self, events: E, ) -> io::Result<bool> where E::IntoIter: ExactSizeIterator,120 pub fn send_report<E: IntoIterator<Item = virtio_input_event>>( 121 &mut self, 122 events: E, 123 ) -> io::Result<bool> 124 where 125 E::IntoIter: ExactSizeIterator, 126 { 127 let it = events.into_iter(); 128 129 if !self.can_buffer_events(it.len() + 1) { 130 return Ok(false); 131 } 132 133 for event in it { 134 let bytes = event.as_bytes(); 135 self.event_buffer.extend(bytes.iter()); 136 } 137 138 self.event_buffer 139 .extend(virtio_input_event::syn().as_bytes().iter()); 140 141 self.flush_buffered_events() 142 } 143 144 /// Sends the given `event`, returning `Ok(true)` if, after this function returns, there are no 145 /// buffered events remaining. send_event_encoded(&mut self, event: virtio_input_event) -> io::Result<bool>146 pub fn send_event_encoded(&mut self, event: virtio_input_event) -> io::Result<bool> { 147 if !self.flush_buffered_events()? { 148 return Ok(false); 149 } 150 151 let bytes = event.as_bytes(); 152 let written = self.event_socket.write(bytes)?; 153 154 if written == bytes.len() { 155 return Ok(true); 156 } 157 158 if self.can_buffer_events(1) { 159 self.event_buffer.extend(bytes[written..].iter()); 160 } 161 162 Ok(false) 163 } 164 recv_event_encoded(&self) -> io::Result<virtio_input_event>165 pub fn recv_event_encoded(&self) -> io::Result<virtio_input_event> { 166 zerocopy_from_reader::<_, virtio_input_event>(&self.event_socket) 167 .map_err(|_| Error::new(ErrorKind::InvalidInput, "failed to read virtio_input_event")) 168 } 169 } 170 171 impl AsRawDescriptor for EventDevice { as_raw_descriptor(&self) -> RawDescriptor172 fn as_raw_descriptor(&self) -> RawDescriptor { 173 self.event_socket.as_raw_descriptor() 174 } 175 } 176 177 impl fmt::Debug for EventDevice { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result178 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 179 write!(f, "Event device ({:?})", self.kind) 180 } 181 } 182