Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/proto/console/text/input.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / proto / console / text / input.rs` 410 lines ยท 14098 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 use crate::data_types::chars::CharConversionError; 4 use crate::proto::unsafe_protocol; 5 use crate::{Char16, Error, Event, Result, Status, StatusExt}; 6 use core::ffi::c_void; 7 use core::mem::MaybeUninit; 8 use core::{ptr, result}; 9 use uefi_raw::protocol::console::{ 10 InputKey, KeyData as RawKeyData, KeyNotifyFn, KeyShiftState, KeyState as RawKeyState, 11 KeyToggleState, SimpleTextInputExProtocol, SimpleTextInputProtocol, 12 }; 13 14 /// Simple Text Input [`Protocol`]. Interface for text-based input devices. 15 /// 16 /// [`Protocol`]: uefi::proto::Protocol 17 #[derive(Debug)] 18 #[repr(transparent)] 19 #[unsafe_protocol(SimpleTextInputProtocol::GUID)] 20 pub struct Input(SimpleTextInputProtocol); 21 22 impl Input { 23 /// Resets the input device hardware. 24 /// 25 /// The `extended_verification` parameter is used to request that UEFI 26 /// performs an extended check and reset of the input device. 27 /// 28 /// # Errors 29 /// 30 /// - `DeviceError` if the device is malfunctioning and cannot be reset. 31 pub fn reset(&mut self, extended_verification: bool) -> Result { 32 // SAFETY: The memory is valid. 33 unsafe { (self.0.reset)(&mut self.0, extended_verification.into()) }.to_result() 34 } 35 36 /// Reads the next keystroke from the input device, if any. 37 /// 38 /// Use [`wait_for_key_event`] with the [`boot::wait_for_event`] 39 /// interface in order to wait for a key to be pressed. 40 /// 41 /// [`boot::wait_for_event`]: crate::boot::wait_for_event 42 /// [`wait_for_key_event`]: Self::wait_for_key_event 43 /// 44 /// # Errors 45 /// 46 /// - [`Status::DEVICE_ERROR`] if there was an issue with the input device, 47 /// or if it reported a character that is not valid UCS-2 48 /// 49 /// # Examples 50 /// 51 /// ``` 52 /// use log::info; 53 /// use uefi::proto::console::text::{Input, Key, ScanCode}; 54 /// use uefi::{boot, char16, Result, ResultExt}; 55 /// 56 /// fn read_keyboard_events(input: &mut Input) -> Result { 57 /// loop { 58 /// // Pause until a keyboard event occurs. 59 /// let events = [input.wait_for_key_event().unwrap()]; 60 /// boot::wait_for_event(&events).discard_errdata()?; 61 /// 62 /// let u_key = char16!('u'); 63 /// match input.read_key()? { 64 /// // Example of handling a printable key: print a message when 65 /// // the 'u' key is pressed. 66 /// Some(Key::Printable(key)) if key == u_key => { 67 /// info!("the 'u' key was pressed"); 68 /// } 69 /// 70 /// // Example of handling a special key: exit the loop when the 71 /// // escape key is pressed. 72 /// Some(Key::Special(ScanCode::ESCAPE)) => { 73 /// break; 74 /// } 75 /// _ => {} 76 /// } 77 /// } 78 /// 79 /// Ok(()) 80 /// } 81 /// ``` 82 pub fn read_key(&mut self) -> Result> { 83 let mut key = MaybeUninit::::uninit(); 84 85 // SAFETY: The memory is valid. 86 let key = match unsafe { (self.0.read_key_stroke)(&mut self.0, key.as_mut_ptr()) } { 87 Status::NOT_READY => return Ok(None), 88 // SAFETY: The memory is valid. 89 other => other.to_result_with_val(|| unsafe { key.assume_init() })?, 90 }; 91 // The firmware reported a character that is not valid UCS-2. 92 let key = Key::try_from(key).map_err(|_| Error::from(Status::DEVICE_ERROR))?; 93 Ok(Some(key)) 94 } 95 96 /// Event to be used with [`boot::wait_for_event`] in order to wait 97 /// for a key to be available 98 /// 99 /// [`boot::wait_for_event`]: crate::boot::wait_for_event 100 pub fn wait_for_key_event(&self) -> Result { 101 // SAFETY: The memory is valid. 102 unsafe { Event::from_ptr(self.0.wait_for_key) }.ok_or(Error::from(Status::UNSUPPORTED)) 103 } 104 } 105 106 /// A key read from the console (high-level version) 107 #[derive(Debug, Copy, Clone, Eq, PartialEq)] 108 pub enum Key { 109 /// The key is associated with a printable Unicode character 110 Printable(Char16), 111 112 /// The key is special (arrow, function, multimedia...) 113 Special(ScanCode), 114 } 115 116 impl TryFrom for Key { 117 type Error = CharConversionError; 118 119 /// Fails if the key carries a character that is not valid UCS-2, such 120 /// as a surrogate code unit. 121 fn try_from(k: InputKey) -> result::Result { 122 if k.scan_code == ScanCode::NULL.0 { 123 Char16::try_from(k.unicode_char).map(Self::Printable) 124 } else { 125 Ok(Self::Special(ScanCode(k.scan_code))) 126 } 127 } 128 } 129 130 newtype_enum! { 131 /// A keyboard scan code 132 /// 133 /// Codes 0x8000 -> 0xFFFF are reserved for future OEM extensibility, therefore 134 /// this C enum is _not_ safe to model as a Rust enum (where the compiler must 135 /// know about all variants at compile time). 136 pub enum ScanCode: u16 => #[expect(missing_docs)] { 137 /// Null scan code, indicates that the Unicode character should be used. 138 NULL = 0x00, 139 /// Move cursor up 1 row. 140 UP = 0x01, 141 /// Move cursor down 1 row. 142 DOWN = 0x02, 143 /// Move cursor right 1 column. 144 RIGHT = 0x03, 145 /// Move cursor left 1 column. 146 LEFT = 0x04, 147 HOME = 0x05, 148 END = 0x06, 149 INSERT = 0x07, 150 DELETE = 0x08, 151 PAGE_UP = 0x09, 152 PAGE_DOWN = 0x0A, 153 FUNCTION_1 = 0x0B, 154 FUNCTION_2 = 0x0C, 155 FUNCTION_3 = 0x0D, 156 FUNCTION_4 = 0x0E, 157 FUNCTION_5 = 0x0F, 158 FUNCTION_6 = 0x10, 159 FUNCTION_7 = 0x11, 160 FUNCTION_8 = 0x12, 161 FUNCTION_9 = 0x13, 162 FUNCTION_10 = 0x14, 163 FUNCTION_11 = 0x15, 164 FUNCTION_12 = 0x16, 165 ESCAPE = 0x17, 166 167 FUNCTION_13 = 0x68, 168 FUNCTION_14 = 0x69, 169 FUNCTION_15 = 0x6A, 170 FUNCTION_16 = 0x6B, 171 FUNCTION_17 = 0x6C, 172 FUNCTION_18 = 0x6D, 173 FUNCTION_19 = 0x6E, 174 FUNCTION_20 = 0x6F, 175 FUNCTION_21 = 0x70, 176 FUNCTION_22 = 0x71, 177 FUNCTION_23 = 0x72, 178 FUNCTION_24 = 0x73, 179 180 MUTE = 0x7F, 181 VOLUME_UP = 0x80, 182 VOLUME_DOWN = 0x81, 183 184 BRIGHTNESS_UP = 0x100, 185 BRIGHTNESS_DOWN = 0x101, 186 SUSPEND = 0x102, 187 HIBERNATE = 0x103, 188 TOGGLE_DISPLAY = 0x104, 189 RECOVERY = 0x105, 190 EJECT = 0x106, 191 }} 192 193 /// Simple Text Input Ex [`Protocol`]. Extended Interface for text-based input devices. 194 /// 195 /// [`Protocol`]: uefi::proto::Protocol 196 #[derive(Debug)] 197 #[repr(transparent)] 198 #[unsafe_protocol(SimpleTextInputExProtocol::GUID)] 199 pub struct InputEx(SimpleTextInputExProtocol); 200 201 impl InputEx { 202 /// Resets the input device hardware. 203 /// 204 /// If the `extended_verification` parameter is true, then the firmware may 205 /// take an extended amount of time to verify the device is operating after 206 /// the reset. 207 /// 208 /// # Errors 209 /// 210 /// - `DeviceError` if the device is malfunctioning and cannot be reset. 211 pub fn reset(&mut self, extended_verification: bool) -> Result { 212 // SAFETY: The memory is valid. 213 unsafe { (self.0.reset)(&mut self.0, extended_verification.into()) }.to_result() 214 } 215 216 /// Reads the next keystroke from the input device, if any. 217 /// 218 /// Use [`wait_for_key_event`] with the [`boot::wait_for_event`] 219 /// interface in order to wait for a key to be pressed. 220 /// 221 /// [`boot::wait_for_event`]: crate::boot::wait_for_event 222 /// [`wait_for_key_event`]: Self::wait_for_key_event 223 /// 224 /// # Errors 225 /// 226 /// - [`Status::DEVICE_ERROR`] if there was an issue with the input device, 227 /// or if it reported a character that is not valid UCS-2 228 pub fn read_key(&mut self) -> Result> { 229 let mut key = MaybeUninit::::uninit(); 230 231 // SAFETY: The memory is valid. 232 let key = match unsafe { (self.0.read_key_stroke_ex)(&mut self.0, key.as_mut_ptr()) } { 233 Status::NOT_READY => return Ok(None), 234 // SAFETY: The memory is valid. 235 other => other.to_result_with_val(|| unsafe { key.assume_init() })?, 236 }; 237 // The firmware reported a character that is not valid UCS-2. 238 let key = KeyData::try_from(key).map_err(|_| Error::from(Status::DEVICE_ERROR))?; 239 Ok(Some(key)) 240 } 241 242 /// Sets certain state for the input device. 243 /// 244 /// By calling this function with [`KeyToggleState::EXPOSED`] set, this function 245 /// enables [`read_key`] to return incomplete keystrokes such as 246 /// the holding down of certain keys which are expressed as part of 247 /// [`KeyState`] when there is no [`KeyData`]. 248 /// 249 /// [`read_key`]: Self::read_key 250 /// 251 /// # Errors 252 /// 253 /// - `Unsupported` if the device does not support the ability to have its 254 /// state set or the requested state change was not supported. 255 pub fn set_state(&mut self, state: KeyToggleState) -> Result { 256 // SAFETY: The memory is valid. 257 unsafe { (self.0.set_state)(&mut self.0, &state) }.to_result() 258 } 259 260 /// Event to be used with [`boot::wait_for_event`] in order to wait 261 /// for a key to be available 262 /// 263 /// [`boot::wait_for_event`]: crate::boot::wait_for_event 264 pub fn wait_for_key_event(&self) -> Result { 265 // SAFETY: The memory is valid. 266 unsafe { Event::from_ptr(self.0.wait_for_key_ex) }.ok_or(Error::from(Status::UNSUPPORTED)) 267 } 268 269 /// Registers a function to be called when a specified key sequence is typed. 270 /// 271 /// The `key_data` defines the key combination (including shift/toggle states) 272 /// that will trigger the `notify_function`. 273 /// 274 /// # Errors 275 /// 276 /// - [`Status::OUT_OF_RESOURCES`] if the notification could not be registered. 277 /// - [`Status::INVALID_PARAMETER`] if the key sequence is invalid. 278 pub fn register_key_notify( 279 &mut self, 280 key_data: KeyData, 281 notify_function: KeyNotifyFn, 282 ) -> Result { 283 let mut handle = ptr::null_mut(); 284 285 // We must convert our high-level KeyData back to the raw format the firmware expects 286 let raw_key_data = RawKeyData { 287 key: InputKey { 288 scan_code: match key_data.key { 289 Key::Special(s) => s.0, 290 Key::Printable(_) => ScanCode::NULL.0, 291 }, 292 unicode_char: match key_data.key { 293 Key::Printable(c) => c.into(), 294 Key::Special(_) => 0, 295 }, 296 }, 297 key_state: RawKeyState { 298 key_shift_state: key_data 299 .key_state 300 .key_shift_state 301 .unwrap_or(KeyShiftState::empty()), 302 key_toggle_state: key_data 303 .key_state 304 .key_toggle_state 305 .unwrap_or(KeyToggleState::empty()), 306 }, 307 }; 308 309 // SAFETY: The memory is valid. 310 unsafe { 311 (self.0.register_key_notify)(&mut self.0, &raw_key_data, notify_function, &mut handle) 312 .to_result_with_val(|| KeyNotifyHandle(handle)) 313 } 314 } 315 316 /// Unregisters a key notification previously registered with [`register_key_notify`]. 317 /// 318 /// [`register_key_notify`]: Self::register_key_notify 319 /// 320 /// # Errors 321 /// 322 /// - [`Status::INVALID_PARAMETER`] if the handle is not valid. 323 pub fn unregister_key_notify(&mut self, handle: KeyNotifyHandle) -> Result { 324 // SAFETY: The memory is valid. 325 unsafe { (self.0.unregister_key_notify)(&mut self.0, handle.0) }.to_result() 326 } 327 } 328 329 /// A handle to a registered key notification. 330 #[derive(Debug, Copy, Clone, Eq, PartialEq)] 331 #[repr(transparent)] 332 pub struct KeyNotifyHandle(*mut c_void); 333 334 /// A key read from the console and associated keyboard state. 335 #[derive(Debug, Copy, Clone, Eq, PartialEq)] 336 pub struct KeyData { 337 /// The high-level representation of the key read from the console. 338 pub key: Key, 339 /// The associated keyboard state. 340 pub key_state: KeyState, 341 } 342 343 impl TryFrom for KeyData { 344 type Error = CharConversionError; 345 346 /// Fails if the key carries a character that is not valid UCS-2, see 347 /// [`Key::try_from`]. 348 fn try_from(k: RawKeyData) -> result::Result { 349 Ok(Self { 350 key: k.key.try_into()?, 351 key_state: k.key_state.into(), 352 }) 353 } 354 } 355 356 /// The state of various toggled attributes as well as input modifier values. 357 #[derive(Debug, Copy, Clone, Eq, PartialEq)] 358 pub struct KeyState { 359 /// The currently pressed shift modifiers for the input device. 360 pub key_shift_state: Option, 361 /// The current internal state of various toggled attributes. 362 pub key_toggle_state: Option, 363 } 364 365 impl From for KeyState { 366 fn from(key_state: RawKeyState) -> Self { 367 Self { 368 key_shift_state: if key_state.key_shift_state.contains(KeyShiftState::VALID) { 369 Some(key_state.key_shift_state) 370 } else { 371 None 372 }, 373 key_toggle_state: if key_state.key_toggle_state.contains(KeyToggleState::VALID) { 374 Some(key_state.key_toggle_state) 375 } else { 376 None 377 }, 378 } 379 } 380 } 381 382 #[cfg(test)] 383 mod tests { 384 use super::*; 385 386 #[test] 387 fn test_key_from_raw() { 388 let raw = InputKey { 389 scan_code: ScanCode::NULL.0, 390 unicode_char: u16::from(b'a'), 391 }; 392 assert_eq!( 393 Key::try_from(raw), 394 Ok(Key::Printable(Char16::try_from('a').unwrap())) 395 ); 396 397 let raw = InputKey { 398 scan_code: ScanCode::ESCAPE.0, 399 unicode_char: 0, 400 }; 401 assert_eq!(Key::try_from(raw), Ok(Key::Special(ScanCode::ESCAPE))); 402 403 // A surrogate is not a valid UCS-2 character. 404 let raw = InputKey { 405 scan_code: ScanCode::NULL.0, 406 unicode_char: 0xd800, 407 }; 408 assert!(Key::try_from(raw).is_err()); 409 } 410 }