xref: /StarryEngine/starry_server/src/core/input/mod.rs (revision 731cae0674923fcc85c6e683a2eee596eb642796)
1 use std::{cell::RefCell, fs::File, io::Read, sync::Arc};
2 
3 use starry_client::base::event::Event;
4 
5 use self::inputs::{KeyboardInputHandler, MouseInputHandler};
6 
7 use super::window_manager::window_manager;
8 
9 pub mod inputs;
10 
11 static mut INPUT_MANAGER: Option<Arc<InputManager>> = None;
12 
input_manager() -> Option<Arc<InputManager>>13 pub fn input_manager() -> Option<Arc<InputManager>> {
14     unsafe { INPUT_MANAGER.clone() }
15 }
16 
17 /// 输入管理器
18 #[allow(dead_code)]
19 pub struct InputManager {
20     /// 轮询的文件数组
21     handlers: RefCell<Vec<Box<dyn InputHandler>>>,
22 }
23 
24 impl InputManager {
25     /// 创建输入管理器
new()26     pub fn new() {
27         let mut input_handlers = Vec::new();
28         input_handlers.push(MouseInputHandler::new() as Box<dyn InputHandler>);
29         input_handlers.push(KeyboardInputHandler::new() as Box<dyn InputHandler>);
30         let input_manager = InputManager {
31             handlers: RefCell::new(input_handlers),
32         };
33 
34         unsafe {
35             INPUT_MANAGER = Some(Arc::new(input_manager));
36         }
37 
38         // println!("[Init] Input_Manager created successfully!");
39     }
40 
41     /// 驱动所有输入处理器
polling_all(&self)42     pub fn polling_all(&self) {
43         // println!("[Info] Input_Manager polling all");
44         for handle in self.handlers.borrow_mut().iter_mut() {
45             handle.polling();
46         }
47     }
48 }
49 
50 /// 输入处理器需要实现的特性
51 #[allow(dead_code)]
52 pub trait InputHandler {
53     /// 获得监听的文件
get_listening_file(&mut self) -> &File54     fn get_listening_file(&mut self) -> &File;
55 
56     /// 设置监听的文件
set_listening_file(&mut self, file: File)57     fn set_listening_file(&mut self, file: File);
58 
59     /// 处理字节数据
handle(&mut self, packet: u8) -> Vec<Event>60     fn handle(&mut self, packet: u8) -> Vec<Event>;
61 
62     /// 轮询文件
polling(&mut self)63     fn polling(&mut self) {
64         let mut buf: [u8; 1024] = [0; 1024];
65         let mut file = self.get_listening_file();
66         let result = file.read(&mut buf);
67 
68         if result.is_err() {
69             println!("[Error] Filed to polling file {:?}", file);
70         } else {
71             let count = result.ok().unwrap();
72             // println!("[Info] Input_Handler polling read {:?} bytes", count);
73             for i in 0..count {
74                 let events = self.handle(buf[i]);
75                 window_manager().unwrap().send_events(events);
76             }
77         }
78     }
79 }
80