graphics/input/
data.rs

1use core::mem::transmute;
2
3use crate::{Point, lvgl};
4
5use super::{Key, State};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8#[repr(C)]
9pub struct InputData {
10    pub r#continue: bool,
11    pub point: Point,
12    pub state: State,
13    pub key: Key,
14}
15
16impl Default for InputData {
17    fn default() -> Self {
18        Self {
19            point: Point::default(),
20            state: State::default(),
21            key: Key::Character(0),
22            r#continue: false,
23        }
24    }
25}
26
27impl InputData {
28    pub const fn new(point: Point, state: State, key: Key, r#continue: bool) -> Self {
29        Self {
30            point,
31            state,
32            key,
33            r#continue,
34        }
35    }
36
37    pub const fn get_continue(&self) -> bool {
38        self.r#continue
39    }
40
41    pub const fn get_point(&self) -> &Point {
42        &self.point
43    }
44
45    pub const fn get_touch(&self) -> &State {
46        &self.state
47    }
48
49    pub const fn get_key(&self) -> Key {
50        self.key
51    }
52
53    pub const fn set_continue(&mut self, r#continue: bool) {
54        self.r#continue = r#continue;
55    }
56
57    pub fn set_point(&mut self, point: Point) {
58        self.point = point;
59    }
60
61    pub fn set_state(&mut self, touch: State) {
62        self.state = touch;
63    }
64
65    pub fn set_key(&mut self, key: Key) {
66        self.key = key;
67    }
68
69    pub fn set(&mut self, point: Point, touch: State) {
70        self.point = point;
71        self.state = touch;
72    }
73}
74
75impl TryFrom<&mut [u8]> for &mut InputData {
76    type Error = ();
77
78    fn try_from(value: &mut [u8]) -> Result<Self, Self::Error> {
79        if value.len() != size_of::<InputData>() {
80            return Err(());
81        }
82        if !(value.as_ptr() as usize).is_multiple_of(core::mem::align_of::<InputData>()) {
83            return Err(());
84        }
85
86        #[allow(clippy::transmute_ptr_to_ref)]
87        Ok(unsafe { transmute::<*mut u8, Self>(value.as_mut_ptr()) })
88    }
89}
90
91impl AsMut<[u8]> for InputData {
92    fn as_mut(&mut self) -> &mut [u8] {
93        unsafe { core::slice::from_raw_parts_mut(self as *mut _ as *mut u8, size_of::<Self>()) }
94    }
95}
96
97impl From<InputData> for lvgl::lv_indev_data_t {
98    fn from(value: InputData) -> lvgl::lv_indev_data_t {
99        let mut input_device_data = lvgl::lv_indev_data_t::default();
100
101        let state = value.get_touch();
102
103        if *state == State::Pressed {
104            input_device_data.point = (*value.get_point()).into();
105        }
106
107        input_device_data.state = (*state).into();
108        input_device_data.key = value.key.into();
109
110        input_device_data
111    }
112}