Skip to main content

graphics/input/
input.rs

1use alloc::boxed::Box;
2use file_system::DirectCharacterDevice;
3use synchronization::Arc;
4
5use core::cell::Cell;
6use core::ffi::c_void;
7
8use crate::{Result, lvgl};
9
10use super::{InputKind, InputQueue, UserData, binding_callback_function};
11
12pub struct Input {
13    #[allow(dead_code)]
14    input_device: *mut lvgl::lv_indev_t,
15}
16
17impl Drop for Input {
18    fn drop(&mut self) {
19        // SAFETY: construction requires the owner to drop this live input
20        // under the graphics lock, before LVGL deinitializes.
21        unsafe {
22            let _ = Box::from_raw(lvgl::lv_indev_get_user_data(self.input_device) as *mut UserData);
23
24            lvgl::lv_indev_delete(self.input_device);
25
26            // User_data will be dropped here.
27        }
28    }
29}
30
31unsafe impl Send for Input {}
32
33unsafe impl Sync for Input {}
34
35impl Input {
36    /// Register a physical input device.
37    ///
38    /// # Safety
39    ///
40    /// LVGL must be initialized. Hold its lock during registration and
41    /// while dropping the returned input. Drop it before LVGL deinitializes.
42    pub unsafe fn new(device: &'static dyn DirectCharacterDevice, kind: InputKind) -> Result<Self> {
43        // SAFETY: the caller supplies the initialization and lock guarantees.
44        unsafe { Self::create(Some(device), None, kind) }
45    }
46
47    pub(crate) unsafe fn new_virtual(queue: Arc<InputQueue>, kind: InputKind) -> Result<Self> {
48        // SAFETY: the caller supplies the initialization and lock guarantees.
49        unsafe { Self::create(None, Some(queue), kind) }
50    }
51
52    unsafe fn create(
53        device: Option<&'static dyn DirectCharacterDevice>,
54        injected: Option<Arc<InputQueue>>,
55        kind: InputKind,
56    ) -> Result<Self> {
57        // User_data stays allocated until LVGL drops this input device.
58        let user_data = Box::new(UserData {
59            device,
60            injected,
61            events_read: Cell::new(0),
62            kind,
63        });
64
65        // SAFETY: LVGL is initialized and the caller holds the graphics lock.
66        let input_device = unsafe {
67            let input_device = lvgl::lv_indev_create();
68            lvgl::lv_indev_set_type(input_device, kind.into());
69            lvgl::lv_indev_set_read_cb(input_device, Some(binding_callback_function));
70            lvgl::lv_indev_set_user_data(input_device, Box::into_raw(user_data) as *mut c_void);
71
72            if kind == InputKind::Keypad {
73                let group = lvgl::lv_group_get_default();
74
75                lvgl::lv_indev_set_group(input_device, group);
76            }
77
78            input_device
79        };
80
81        Ok(Self { input_device })
82    }
83}