1use evdev::{AbsoluteAxisCode, Device, EventSummary, KeyCode};
2use pixelab_core::{Event, InputDevice, PixelabError, Point, TouchPad};
3use std::sync::mpsc::{channel, Receiver, Sender};
4use std::thread;
5use std::time::Duration;
6
7pub struct TouchPadReader {
8 tx: Sender<Event>,
9 rx: Receiver<Event>,
10 file_name: &'static str,
11}
12impl TouchPadReader {
13 pub fn new(file_name: &'static str) -> Self {
14 let (tx, rx) = channel::<Event>();
15 Self { tx, rx, file_name }
16 }
17 fn run(mut file: Device, tx: Sender<Event>) {
18 let mut action = TouchPad::Motion(Point::default());
19 let mut point = Point::default();
20 let mut update = false;
21 loop {
22 for event in file.fetch_events().unwrap() {
23 match event.destructure() {
25 EventSummary::AbsoluteAxis(_, AbsoluteAxisCode::ABS_X, x) => {
26 if point.x != x as u16 {
27 point.x = x as u16;
28 update = true;
29 }
30 }
31 EventSummary::AbsoluteAxis(_, AbsoluteAxisCode::ABS_Y, y) => {
32 if point.y != y as u16 {
33 point.y = y as u16;
34 update = true;
35 }
36 }
37 EventSummary::Key(_, KeyCode::BTN_TOUCH, 1) => {
38 action = TouchPad::Press(Point::default());
39 update = true;
40 }
41 EventSummary::Key(_, KeyCode::BTN_TOUCH, 0) => {
42 action = TouchPad::Release(Point::default());
43 update = true;
44 }
45 _ => {}
46 }
47 }
48 if update {
49 match action {
50 TouchPad::Press(_) => tx.send(Event::TouchPad(TouchPad::Press(point))).unwrap(),
51 TouchPad::Motion(_) => {
52 tx.send(Event::TouchPad(TouchPad::Motion(point))).unwrap()
53 }
54 TouchPad::Release(_) => {
55 tx.send(Event::TouchPad(TouchPad::Release(point))).unwrap()
56 }
57 }
58 action = TouchPad::Motion(Point::default());
59 update = false;
60 }
61 thread::sleep(Duration::from_millis(30));
62 }
63 }
64}
65impl InputDevice for TouchPadReader {
66 fn init(&mut self) -> Result<(), PixelabError> {
67 let tx = self.tx.clone();
68 let file = Device::open(self.file_name).expect("");
69 thread::spawn(move || Self::run(file, tx));
70 Ok(())
71 }
72
73 fn read(&mut self) -> Result<Event, PixelabError> {
74 match self.rx.try_recv() {
75 Ok(event) => Ok(event),
76 Err(_) => {
77 thread::sleep(Duration::from_millis(10));
78 Err(PixelabError::EmptyEvent)
79 }
80 }
81 }
82}