interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / usb / hid.rs

326 lines · 10789 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! HID boot-protocol keyboard reports.
17//!
18//! Pure parsing: an 8-byte boot-protocol report in, key events out. No MMIO
19//! and no allocation, so the whole behaviour is host-tested. The decoder is
20//! make-only (key releases are ignored), and a fixed-capacity sink keeps the
21//! decoded text when the caller wants it as one string.
22
23/// Modifier bit positions in byte 0 of a boot-protocol report.
24pub mod modifier {
25 pub const LEFT_CTRL: u8 = 1 << 0;
26 pub const LEFT_SHIFT: u8 = 1 << 1;
27 pub const LEFT_ALT: u8 = 1 << 2;
28 pub const RIGHT_CTRL: u8 = 1 << 4;
29 pub const RIGHT_SHIFT: u8 = 1 << 5;
30 pub const RIGHT_ALT: u8 = 1 << 6;
31 pub const ANY_SHIFT: u8 = LEFT_SHIFT | RIGHT_SHIFT;
32}
33
34pub use modifier::{LEFT_ALT, LEFT_CTRL, LEFT_SHIFT, RIGHT_ALT, RIGHT_CTRL, RIGHT_SHIFT};
35
36/// One decoded key press. Releases never produce an event.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum KeyEvent {
39 /// A printable character, already shifted.
40 Char(char),
41 Enter,
42 Backspace,
43 Tab,
44 Escape,
45 /// Cursor keys arrive as ANSI escape sequences on the early console.
46 Up,
47 Down,
48 Left,
49 Right,
50}
51
52/// Length of a HID boot-protocol keyboard report.
53pub const BOOT_REPORT_LEN: usize = 8;
54const MAX_KEYS: usize = 6;
55
56/// Unshifted and shifted characters per usage ID, starting at usage 0x04:
57/// letters first, then digits, each pair unshifted then shifted.
58#[rustfmt::skip]
59const KEYMAP: &[u8] = b"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ\
60 1!2@3#4$5%6^7&8*9(0)";
61
62/// Usage 0x2c (space) and the punctuation row: usages 0x2c..=0x38, each pair
63/// unshifted then shifted. Usage 0x32 (non-US `#`/`~`) sits between `\` and `;`.
64#[rustfmt::skip]
65const PUNCT: &[u8] = b" -_=+[{]}\\|#~;:'\"`~,<.>/?";
66
67const USAGE_ENTER: u8 = 0x28;
68const USAGE_ESCAPE: u8 = 0x29;
69const USAGE_BACKSPACE: u8 = 0x2a;
70const USAGE_TAB: u8 = 0x2b;
71const USAGE_CAPS_LOCK: u8 = 0x39;
72const USAGE_F1: u8 = 0x3a;
73const USAGE_F12: u8 = 0x45;
74const USAGE_RIGHT_ARROW: u8 = 0x4f;
75const USAGE_LEFT_ARROW: u8 = 0x50;
76const USAGE_DOWN_ARROW: u8 = 0x51;
77const USAGE_UP_ARROW: u8 = 0x52;
78
79fn decode_usage(usage: u8, shift: bool) -> Option<KeyEvent> {
80 let c = match usage {
81 0x04..=0x27 => KEYMAP[usize::from(usage - 0x04) * 2 + usize::from(shift)],
82 USAGE_ENTER => return Some(KeyEvent::Enter),
83 USAGE_ESCAPE => return Some(KeyEvent::Escape),
84 USAGE_BACKSPACE => return Some(KeyEvent::Backspace),
85 USAGE_TAB => return Some(KeyEvent::Tab),
86 0x2c..=0x38 => PUNCT[usize::from(usage - 0x2c) * 2 + usize::from(shift)],
87 // Caps Lock and the function row are not echoed.
88 USAGE_CAPS_LOCK | USAGE_F1..=USAGE_F12 => return None,
89 USAGE_RIGHT_ARROW => return Some(KeyEvent::Right),
90 USAGE_LEFT_ARROW => return Some(KeyEvent::Left),
91 USAGE_DOWN_ARROW => return Some(KeyEvent::Down),
92 USAGE_UP_ARROW => return Some(KeyEvent::Up),
93 _ => return None,
94 };
95 Some(KeyEvent::Char(char::from(c)))
96}
97
98/// Stateless-format decoder: a key press is emitted once, on the first report
99/// containing it, and releases are ignored, so a key held across polls does
100/// not auto-repeat.
101pub struct BootKeyboardDecoder {
102 previous: [u8; MAX_KEYS],
103}
104
105impl Default for BootKeyboardDecoder {
106 fn default() -> Self {
107 Self::new()
108 }
109}
110
111impl BootKeyboardDecoder {
112 pub const fn new() -> Self {
113 Self {
114 previous: [0; MAX_KEYS],
115 }
116 }
117
118 /// Handle one 8-byte boot-protocol report, calling `emit` for every key
119 /// that is newly pressed relative to the previous report. Reports with a
120 /// rollover error (all usages 0x01) or a wrong length are ignored.
121 pub fn handle_report(&mut self, report: &[u8], mut emit: impl FnMut(KeyEvent)) {
122 if report.len() != BOOT_REPORT_LEN {
123 return;
124 }
125 let usages: [u8; MAX_KEYS] = report[2..8].try_into().unwrap_or([0; MAX_KEYS]);
126 if usages[0] == 0x01 {
127 // Phantom state during rollover: ignore this report entirely and
128 // do not treat it as a release.
129 return;
130 }
131 let shift = report[0] & modifier::ANY_SHIFT != 0;
132 for usage in usages {
133 if usage == 0 || self.previous.contains(&usage) {
134 continue;
135 }
136 if let Some(event) = decode_usage(usage, shift) {
137 emit(event);
138 }
139 }
140 self.previous = usages;
141 }
142}
143
144/// Fixed-capacity text collector for decoded keystrokes, heap-free.
145pub struct TextSink<const N: usize> {
146 bytes: [u8; N],
147 len: usize,
148}
149
150impl<const N: usize> Default for TextSink<N> {
151 fn default() -> Self {
152 Self::new()
153 }
154}
155
156impl<const N: usize> TextSink<N> {
157 pub const fn new() -> Self {
158 Self {
159 bytes: [0; N],
160 len: 0,
161 }
162 }
163
164 pub fn as_str(&self) -> &str {
165 // Only ASCII is ever pushed.
166 core::str::from_utf8(&self.bytes[..self.len]).unwrap_or("")
167 }
168
169 pub fn len(&self) -> usize {
170 self.len
171 }
172
173 pub fn is_empty(&self) -> bool {
174 self.len == 0
175 }
176
177 fn push(&mut self, byte: u8) {
178 if self.len < N {
179 self.bytes[self.len] = byte;
180 self.len += 1;
181 }
182 }
183
184 /// Record one event; cursor keys become their ANSI escape sequences.
185 pub fn record(&mut self, event: KeyEvent) {
186 match event {
187 KeyEvent::Char(c) => self.push(c as u8),
188 KeyEvent::Enter => self.push(b'\n'),
189 KeyEvent::Backspace => self.push(0x08),
190 KeyEvent::Tab => self.push(b'\t'),
191 KeyEvent::Escape => self.push(0x1b),
192 KeyEvent::Up => [0x1b, b'[', b'A'].iter().for_each(|b| self.push(*b)),
193 KeyEvent::Down => [0x1b, b'[', b'B'].iter().for_each(|b| self.push(*b)),
194 KeyEvent::Right => [0x1b, b'[', b'C'].iter().for_each(|b| self.push(*b)),
195 KeyEvent::Left => [0x1b, b'[', b'D'].iter().for_each(|b| self.push(*b)),
196 }
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 fn report(modifiers: u8, usages: [u8; MAX_KEYS]) -> [u8; BOOT_REPORT_LEN] {
205 let mut r = [0u8; BOOT_REPORT_LEN];
206 r[0] = modifiers;
207 r[2..8].copy_from_slice(&usages);
208 r
209 }
210
211 fn decode(decoder: &mut BootKeyboardDecoder, report: &[u8; BOOT_REPORT_LEN]) -> TextSink<16> {
212 let mut sink = TextSink::new();
213 decoder.handle_report(report, |e| sink.record(e));
214 sink
215 }
216
217 #[test]
218 fn letter_make_and_release_produces_one_character() {
219 let mut d = BootKeyboardDecoder::new();
220 assert_eq!(
221 decode(&mut d, &report(0, [0x04, 0, 0, 0, 0, 0])).as_str(),
222 "a"
223 );
224 assert_eq!(decode(&mut d, &report(0, [0; 6])).as_str(), "");
225 // Held keys do not repeat: same usage in consecutive reports is quiet.
226 assert_eq!(
227 decode(&mut d, &report(0, [0x04, 0, 0, 0, 0, 0])).as_str(),
228 "a"
229 );
230 assert_eq!(
231 decode(&mut d, &report(0, [0x04, 0, 0, 0, 0, 0])).as_str(),
232 ""
233 );
234 }
235
236 #[test]
237 fn shift_and_digits_use_the_shifted_column() {
238 let mut d = BootKeyboardDecoder::new();
239 assert_eq!(
240 decode(&mut d, &report(LEFT_SHIFT, [0x04, 0x1e, 0, 0, 0, 0])).as_str(),
241 "A!"
242 );
243 // Right shift works the same.
244 let mut d = BootKeyboardDecoder::new();
245 assert_eq!(
246 decode(&mut d, &report(RIGHT_SHIFT, [0x27, 0x28, 0, 0, 0, 0])).as_str(),
247 ")\n"
248 );
249 }
250
251 #[test]
252 fn punctuation_and_space_decode() {
253 let mut d = BootKeyboardDecoder::new();
254 assert_eq!(
255 decode(&mut d, &report(0, [0x2c, 0x2d, 0x36, 0x37, 0x38, 0])).as_str(),
256 " -,./"
257 );
258 let mut d = BootKeyboardDecoder::new();
259 assert_eq!(
260 decode(
261 &mut d,
262 &report(LEFT_SHIFT, [0x2f, 0x30, 0x31, 0x33, 0x34, 0x35])
263 )
264 .as_str(),
265 "{}|:\"~"
266 );
267 let mut d = BootKeyboardDecoder::new();
268 assert_eq!(
269 decode(
270 &mut d,
271 &report(LEFT_SHIFT, [0x2d, 0x2e, 0x32, 0x36, 0x37, 0x38])
272 )
273 .as_str(),
274 "_+~<>?"
275 );
276 }
277
278 #[test]
279 fn control_keys_and_arrows() {
280 let mut d = BootKeyboardDecoder::new();
281 let mut sink = TextSink::<32>::new();
282 d.handle_report(&report(0, [0x2a, 0x2b, 0x29, 0, 0, 0]), |e| sink.record(e));
283 d.handle_report(&report(0, [0; 6]), |e| sink.record(e));
284 d.handle_report(&report(0, [USAGE_UP_ARROW, 0, 0, 0, 0, 0]), |e| {
285 sink.record(e)
286 });
287 assert_eq!(sink.as_str(), "\x08\t\x1b\x1b[A");
288 }
289
290 #[test]
291 fn rollover_error_and_wrong_length_are_ignored() {
292 let mut d = BootKeyboardDecoder::new();
293 let phantom = report(0, [0x01, 0x01, 0x01, 0x01, 0x01, 0x01]);
294 assert_eq!(decode(&mut d, &phantom).as_str(), "");
295 // A rollover report does not count as a release.
296 d.handle_report(&report(0, [0x04, 0, 0, 0, 0, 0]), |_| {});
297 let mut sink = TextSink::<8>::new();
298 d.handle_report(&phantom, |e| sink.record(e));
299 d.handle_report(&report(0, [0x04, 0, 0, 0, 0, 0]), |e| sink.record(e));
300 assert!(sink.is_empty());
301 // Wrong length never decodes.
302 d.handle_report(&[0u8; 4], |_| panic!("no event"));
303 }
304
305 #[test]
306 fn unmapped_usages_are_dropped() {
307 let mut d = BootKeyboardDecoder::new();
308 assert_eq!(
309 decode(&mut d, &report(0, [USAGE_CAPS_LOCK, 0, 0, 0, 0, 0])).as_str(),
310 ""
311 );
312 assert_eq!(
313 decode(&mut d, &report(0, [USAGE_F1, USAGE_F12, 0, 0, 0, 0])).as_str(),
314 ""
315 );
316 }
317
318 #[test]
319 fn sink_truncates_instead_of_overflowing() {
320 let mut sink = TextSink::<4>::new();
321 for c in "hello".chars() {
322 sink.record(KeyEvent::Char(c));
323 }
324 assert_eq!(sink.as_str(), "hell");
325 }
326}