xref: /StarryEngine/starry_server/src/core/input/mod.rs (revision 45e1715779ec63c9948d677df0dab834e236e747)
1 use std::{
2     fs::File,
3     io::Read,
4     sync::{Arc, RwLock},
5 };
6 
7 use starry_client::base::event::Event;
8 
9 use self::inputs::MouseInputHandler;
10 
11 use super::window_manager::window_manager;
12 
13 pub mod inputs;
14 
15 static mut INPUT_MANAGER: Option<Arc<InputManager>> = None;
16 
17 pub fn input_manager() -> Option<Arc<InputManager>> {
18     unsafe { INPUT_MANAGER.clone() }
19 }
20 
21 /// 输入管理器
22 #[allow(dead_code)]
23 pub struct InputManager {
24     /// 数据锁
25     data: RwLock<InputManagerData>,
26 }
27 
28 pub struct InputManagerData {
29     /// 轮询的文件数组
30     handlers: Vec<Box<dyn InputHandler>>,
31 }
32 
33 impl InputManager {
34     /// 创建输入管理器
35     pub fn new(){
36         let mut input_handlers = Vec::new();
37         // TODO: 通过设备检测添加
38         input_handlers.push(MouseInputHandler::new() as Box<dyn InputHandler>);
39         // TODO: 处理键盘输入
40         let input_manager = InputManager {
41             data: RwLock::new(InputManagerData {
42                 handlers: input_handlers,
43             }),
44         };
45 
46         unsafe {
47             INPUT_MANAGER = Some(Arc::new(input_manager));
48         }
49 
50         // println!("[Init] Input_Manager created successfully!");
51     }
52 
53     /// 轮询所有输入设备
54     pub fn polling_all(&self) {
55         // println!("[Info] Input_Manager polling all");
56         let mut guard = self.data.write().unwrap();
57         for handle in guard.handlers.iter_mut() {
58             handle.polling();
59         }
60     }
61 }
62 
63 /// 输入处理器需要实现的特性
64 #[allow(dead_code)]
65 pub trait InputHandler {
66     /// 获得监听的文件
67     fn get_listening_file(&mut self) -> &File;
68 
69     /// 设置监听的文件
70     fn set_listening_file(&mut self, file: File);
71 
72     /// 处理字节数据
73     fn handle(&mut self, packet: u8) -> Vec<Event>;
74 
75     /// 轮询文件
76     fn polling(&mut self) {
77         let mut buf: [u8; 1024] = [0; 1024];
78         // TODO: 错误信息提示相应文件路径
79         let count = self
80         .get_listening_file()
81         .read(&mut buf)
82             .expect("[Error] Fail to polling file");
83         // println!("[Info] Input_Handler polling read {:?} bytes", count);
84         for i in 0..count {
85             let events = self.handle(buf[i]);
86             window_manager().unwrap().send_events(events);
87         }
88     }
89 }
90