waxterm/input.rs
1/// Standard key events (always parsed by the framework).
2#[derive(Debug, PartialEq, Eq, Clone, Copy)]
3pub enum KeyPress {
4 Char(u8),
5 ArrowUp,
6 ArrowDown,
7 ArrowLeft,
8 ArrowRight,
9 Tab,
10 Enter,
11 Escape,
12 Backspace,
13 /// Ctrl+Space (NUL / 0x00) — start-menu trigger for the TUI shell chrome.
14 CtrlSpace,
15 /// Function keys F1–F12.
16 F(u8),
17 /// Mouse scroll wheel up.
18 ScrollUp,
19 /// Mouse scroll wheel down.
20 ScrollDown,
21}
22
23/// Custom OSC handler: receives bytes after `ESC ]`, returns `(command, bytes_consumed)`.
24/// `bytes_consumed` counts from the start of the OSC payload (after `ESC ]`).
25pub type OscHandler<C> = Box<dyn Fn(&[u8]) -> Option<(C, usize)>>;
26
27/// Extensible input parser.
28///
29/// Parses standard key sequences built-in, then dispatches `ESC ]` sequences
30/// to app-registered OSC handlers.
31pub struct InputParser<C> {
32 osc_handlers: Vec<OscHandler<C>>,
33}
34
35impl<C: From<KeyPress>> InputParser<C> {
36 pub fn new(osc_handlers: Vec<OscHandler<C>>) -> Self {
37 InputParser { osc_handlers }
38 }
39
40 /// Parse a byte buffer into a sequence of commands.
41 ///
42 /// Protocol:
43 /// - `ESC [ A/B/C/D` → ArrowUp/Down/Right/Left
44 /// - `ESC ] ...` → dispatched to app-registered OSC handlers
45 /// - `0x09` → Tab, `0x0D` → Enter, `0x1B` alone → Escape, `0x7F` → Backspace
46 /// - `0x00` → skipped (JS stdin heartbeat)
47 /// - anything else → `Char(byte)`
48 pub fn parse(&self, data: &[u8]) -> Vec<C> {
49 let mut cmds = Vec::new();
50 let mut i = 0;
51
52 while i < data.len() {
53 // NUL (0x00) = Ctrl+Space — used as start-menu trigger.
54 if data[i] == 0x00 {
55 cmds.push(C::from(KeyPress::CtrlSpace));
56 i += 1;
57 continue;
58 }
59
60 if data[i] == 0x1B {
61 // Need at least 1 more byte to determine escape type
62 if i + 1 < data.len() {
63 match data[i + 1] {
64 // ESC O → SS3 sequences: F1–F4
65 0x4F => {
66 if i + 2 < data.len() {
67 let fkey = match data[i + 2] {
68 b'P' => Some(KeyPress::F(1)),
69 b'Q' => Some(KeyPress::F(2)),
70 b'R' => Some(KeyPress::F(3)),
71 b'S' => Some(KeyPress::F(4)),
72 _ => None,
73 };
74 if let Some(k) = fkey {
75 cmds.push(C::from(k));
76 }
77 i += 3;
78 } else {
79 i += 1;
80 }
81 }
82 // ESC [ → CSI sequences: arrows + tilde-terminated F-keys
83 0x5B => {
84 if i + 2 < data.len() {
85 match data[i + 2] {
86 // Single-byte: arrow keys
87 b'A' => {
88 cmds.push(C::from(KeyPress::ArrowUp));
89 i += 3;
90 }
91 b'B' => {
92 cmds.push(C::from(KeyPress::ArrowDown));
93 i += 3;
94 }
95 b'C' => {
96 cmds.push(C::from(KeyPress::ArrowRight));
97 i += 3;
98 }
99 b'D' => {
100 cmds.push(C::from(KeyPress::ArrowLeft));
101 i += 3;
102 }
103 // Digit → tilde-terminated: ESC [ <num> ~
104 b'0'..=b'9' => {
105 // Scan for '~' terminator (max 4 bytes of digits)
106 let start = i + 2;
107 let end = data[start..]
108 .iter()
109 .position(|&b| b == b'~')
110 .map(|p| start + p);
111 if let Some(tilde_pos) = end {
112 let num_bytes = &data[start..tilde_pos];
113 let num: u32 =
114 num_bytes.iter().fold(0u32, |acc, &b| {
115 acc * 10 + u32::from(b - b'0')
116 });
117 // VT sequence number → F-key mapping
118 let fkey = match num {
119 11 => Some(KeyPress::F(1)),
120 12 => Some(KeyPress::F(2)),
121 13 => Some(KeyPress::F(3)),
122 14 => Some(KeyPress::F(4)),
123 15 => Some(KeyPress::F(5)),
124 17 => Some(KeyPress::F(6)),
125 18 => Some(KeyPress::F(7)),
126 19 => Some(KeyPress::F(8)),
127 20 => Some(KeyPress::F(9)),
128 21 => Some(KeyPress::F(10)),
129 23 => Some(KeyPress::F(11)),
130 24 => Some(KeyPress::F(12)),
131 _ => None,
132 };
133 if let Some(k) = fkey {
134 cmds.push(C::from(k));
135 }
136 i = tilde_pos + 1;
137 } else {
138 // No tilde found — incomplete, skip ESC
139 i += 1;
140 }
141 }
142 // SGR mouse: ESC [ < btn;col;row M/m
143 // btn 64 = scroll up, btn 65 = scroll down (press only, M terminator)
144 b'<' => {
145 let start = i + 3;
146 let end = data[start..]
147 .iter()
148 .position(|&b| b == b'M' || b == b'm');
149 if let Some(end_off) = end {
150 let term = data[start + end_off];
151 let params = &data[start..start + end_off];
152 // Parse btn from first param (before first ';')
153 if term == b'M' {
154 if let Some(semi) =
155 params.iter().position(|&b| b == b';')
156 {
157 if let Ok(btn_str) =
158 std::str::from_utf8(¶ms[..semi])
159 {
160 if let Ok(btn) = btn_str.parse::<u32>() {
161 if btn == 64 {
162 cmds.push(C::from(
163 KeyPress::ScrollUp,
164 ));
165 } else if btn == 65 {
166 cmds.push(C::from(
167 KeyPress::ScrollDown,
168 ));
169 }
170 }
171 }
172 }
173 }
174 i = start + end_off + 1;
175 } else {
176 i = start; // incomplete
177 }
178 }
179 // X10 mouse: ESC [ M btn cx cy (3 fixed bytes)
180 b'M' => {
181 i += if i + 5 < data.len() { 6 } else { data.len() };
182 }
183 _ => {
184 i += 3;
185 } // ignore unknown CSI sequences
186 }
187 } else {
188 // Incomplete CSI, skip ESC
189 i += 1;
190 }
191 }
192 // ESC ] → OSC sequences, dispatched to app handlers
193 0x5D => {
194 let osc_start = i + 2;
195 let osc_data = &data[osc_start..];
196 let mut handled = false;
197 for handler in &self.osc_handlers {
198 if let Some((cmd, consumed)) = handler(osc_data) {
199 cmds.push(cmd);
200 i = osc_start + consumed;
201 handled = true;
202 break;
203 }
204 }
205 if !handled {
206 // Unknown OSC, skip ESC ]
207 i += 2;
208 }
209 }
210 _ => {
211 // Unknown escape, treat ESC as Escape key
212 cmds.push(C::from(KeyPress::Escape));
213 i += 1;
214 }
215 }
216 } else {
217 // Trailing ESC with no following byte → Escape key
218 cmds.push(C::from(KeyPress::Escape));
219 i += 1;
220 }
221 } else {
222 // Standard single-byte keys
223 let key = match data[i] {
224 0x09 => KeyPress::Tab,
225 0x0D => KeyPress::Enter,
226 0x7F => KeyPress::Backspace,
227 b => KeyPress::Char(b),
228 };
229 cmds.push(C::from(key));
230 i += 1;
231 }
232 }
233
234 cmds
235 }
236}
237
238/// WASI stdin poller (non-blocking read from VFS).
239pub struct StdinPoller {
240 buf: [u8; 256],
241}
242
243impl StdinPoller {
244 pub fn new() -> Self {
245 StdinPoller { buf: [0u8; 256] }
246 }
247
248 /// Read any available bytes from stdin.
249 pub fn read(&mut self) -> &[u8] {
250 use std::io::Read;
251 match std::io::stdin().read(&mut self.buf) {
252 Ok(n) if n > 0 => &self.buf[..n],
253 _ => &[],
254 }
255 }
256}
257
258impl Default for StdinPoller {
259 fn default() -> Self {
260 Self::new()
261 }
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 fn parser() -> InputParser<KeyPress> {
269 InputParser::new(vec![])
270 }
271
272 #[test]
273 fn test_parse_single_keys() {
274 let data = [b' ', b'q', 0x09, b'1'];
275 let cmds = parser().parse(&data);
276 assert_eq!(cmds.len(), 4);
277 assert_eq!(cmds[0], KeyPress::Char(b' '));
278 assert_eq!(cmds[1], KeyPress::Char(b'q'));
279 assert_eq!(cmds[2], KeyPress::Tab);
280 assert_eq!(cmds[3], KeyPress::Char(b'1'));
281 }
282
283 #[test]
284 fn test_parse_arrows() {
285 let data = [0x1B, 0x5B, b'C', 0x1B, 0x5B, b'D'];
286 let cmds = parser().parse(&data);
287 assert_eq!(cmds.len(), 2);
288 assert_eq!(cmds[0], KeyPress::ArrowRight);
289 assert_eq!(cmds[1], KeyPress::ArrowLeft);
290 }
291
292 #[test]
293 fn test_parse_all_arrows() {
294 let data = [
295 0x1B, 0x5B, b'A', 0x1B, 0x5B, b'B', 0x1B, 0x5B, b'C', 0x1B, 0x5B, b'D',
296 ];
297 let cmds = parser().parse(&data);
298 assert_eq!(cmds.len(), 4);
299 assert_eq!(cmds[0], KeyPress::ArrowUp);
300 assert_eq!(cmds[1], KeyPress::ArrowDown);
301 assert_eq!(cmds[2], KeyPress::ArrowRight);
302 assert_eq!(cmds[3], KeyPress::ArrowLeft);
303 }
304
305 #[test]
306 fn test_parse_osc_handlers() {
307 // Register a custom OSC handler: ESC ] T <idx> → SelectTab
308 #[derive(Debug, PartialEq)]
309 enum Cmd {
310 Key(KeyPress),
311 SelectTab(u8),
312 }
313 impl From<KeyPress> for Cmd {
314 fn from(k: KeyPress) -> Self {
315 Cmd::Key(k)
316 }
317 }
318
319 let parser = InputParser::new(vec![Box::new(|data: &[u8]| {
320 if data.len() >= 2 && data[0] == b'T' {
321 Some((Cmd::SelectTab(data[1]), 2))
322 } else {
323 None
324 }
325 })]);
326
327 let data = [0x1B, 0x5D, b'T', 2, 0x1B, 0x5D, b'T', 0];
328 let cmds = parser.parse(&data);
329 assert_eq!(cmds.len(), 2);
330 assert_eq!(cmds[0], Cmd::SelectTab(2));
331 assert_eq!(cmds[1], Cmd::SelectTab(0));
332 }
333
334 #[test]
335 fn test_parse_mixed() {
336 let data = [b' ', 0x1B, 0x5B, b'C', b'q'];
337 let cmds = parser().parse(&data);
338 assert_eq!(cmds.len(), 3);
339 assert_eq!(cmds[0], KeyPress::Char(b' '));
340 assert_eq!(cmds[1], KeyPress::ArrowRight);
341 assert_eq!(cmds[2], KeyPress::Char(b'q'));
342 }
343
344 #[test]
345 fn test_nul_bytes_become_ctrl_space() {
346 let data = [0x00, b'a', 0x00, 0x00, b'b'];
347 let cmds = parser().parse(&data);
348 assert_eq!(cmds.len(), 5);
349 assert_eq!(cmds[0], KeyPress::CtrlSpace);
350 assert_eq!(cmds[1], KeyPress::Char(b'a'));
351 assert_eq!(cmds[2], KeyPress::CtrlSpace);
352 assert_eq!(cmds[3], KeyPress::CtrlSpace);
353 assert_eq!(cmds[4], KeyPress::Char(b'b'));
354 }
355
356 #[test]
357 fn test_special_keys() {
358 let data = [0x0D, 0x7F];
359 let cmds = parser().parse(&data);
360 assert_eq!(cmds.len(), 2);
361 assert_eq!(cmds[0], KeyPress::Enter);
362 assert_eq!(cmds[1], KeyPress::Backspace);
363 }
364
365 #[test]
366 fn test_trailing_escape() {
367 let data = [b'a', 0x1B];
368 let cmds = parser().parse(&data);
369 assert_eq!(cmds.len(), 2);
370 assert_eq!(cmds[0], KeyPress::Char(b'a'));
371 assert_eq!(cmds[1], KeyPress::Escape);
372 }
373}