1 use super::InputHandler; 2 use bitflags::bitflags; 3 use starry_client::base::event::{ButtonEvent, Event, MouseRelativeEvent}; 4 use std::{fs::File, io::Read}; 5 6 const MOUSE_DEVICE_PATH: &str = "/dev/char/psmouse"; 7 8 bitflags! { 9 /// 鼠标状态掩码 10 #[derive(Default)] 11 pub struct MouseFlags: u8 { 12 /// 左键是否按下 13 const LEFT_BUTTON = 0b0000_0001; 14 15 /// 右键是否按下 16 const RIGHT_BUTTON = 0b0000_0010; 17 18 /// 滚轮是否按下 19 const MIDDLE_BUTTON = 0b0000_0100; 20 21 /// 鼠标是否启用 22 const ALWAYS_ONE = 0b0000_1000; 23 24 /// x轴移动方向是否为负 25 const X_SIGN = 0b0001_0000; 26 27 /// y轴移动方向是否为负 28 const Y_SIGN = 0b0010_0000; 29 30 /// x方向移动超出范围 31 const X_OVERFLOW = 0b0100_0000; 32 33 /// y方向移动超出范围 34 const Y_OVERFLOW = 0b1000_0000; 35 } 36 } 37 38 #[allow(dead_code)] 39 pub struct MouseInputHandler { 40 /// 读取的文件 41 file: File, 42 /// 当前数据包序号 43 packet_index: u8, 44 /// 鼠标状态 45 flags: MouseFlags, 46 /// x轴相对移动 47 dx: i16, 48 /// y轴相对移动 49 dy: i16, 50 /// 移动系数/灵敏度 51 scale: u8, 52 } 53 54 impl MouseInputHandler { 55 pub fn new() -> Box<MouseInputHandler> { 56 let file = File::open(MOUSE_DEVICE_PATH).expect("Fail to open mouse device"); 57 // println!("[Init] Mouse_Input_Handler created successfully!"); 58 Box::new(MouseInputHandler { 59 flags: MouseFlags::empty(), 60 packet_index: 0, 61 file: file, 62 dx: 0, 63 dy: 0, 64 scale: 1, 65 }) 66 } 67 } 68 69 impl InputHandler for MouseInputHandler { 70 fn get_listening_file(&mut self) -> &File { 71 self.file.by_ref() 72 } 73 74 fn set_listening_file(&mut self, file: File) { 75 self.file = file; 76 } 77 78 fn handle(&mut self, packet: u8) -> Vec<Event> { 79 // println!("[Info] Mouse_Input_Handler handle packet {:?}", packet); 80 /// 求补码 81 fn sign_extend(value: u8) -> i16 { 82 ((value as u16) | 0xFF00) as i16 83 } 84 85 let mut events: Vec<Event> = Vec::new(); 86 match self.packet_index { 87 0 => { 88 let flags = MouseFlags::from_bits_truncate(packet); 89 if flags.contains(MouseFlags::ALWAYS_ONE) { 90 self.flags = flags; 91 events.push(ButtonEvent::new(packet).to_event()); 92 } 93 } 94 1 => { 95 // 计算dx 96 if self.flags.contains(MouseFlags::X_OVERFLOW) { 97 self.dx = 0; 98 } else if self.flags.contains(MouseFlags::X_SIGN) { 99 self.dx = sign_extend(packet); 100 } else { 101 self.dx = packet as i16; 102 } 103 } 104 2 => { 105 // 计算dy 106 if self.flags.contains(MouseFlags::Y_OVERFLOW) { 107 self.dy = 0; 108 } else if self.flags.contains(MouseFlags::Y_SIGN) { 109 self.dy = sign_extend(packet); 110 } else { 111 self.dy = packet as i16; 112 } 113 114 // 传入移动事件 115 events.push( 116 MouseRelativeEvent { 117 dx: self.dx as i32 * self.scale as i32, 118 dy: self.dy as i32 * self.scale as i32, 119 } 120 .to_event(), 121 ); 122 } 123 _ => unreachable!(), 124 } 125 self.packet_index = (self.packet_index + 1) % 3; 126 return events; 127 } 128 } 129