1#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
6pub struct KeyMods {
7 pub ctrl: bool,
8 pub alt: bool,
9 pub shift: bool,
10}
11
12impl KeyMods {
13 pub const NONE: KeyMods = KeyMods {
14 ctrl: false,
15 alt: false,
16 shift: false,
17 };
18 pub const CTRL: KeyMods = KeyMods {
19 ctrl: true,
20 alt: false,
21 shift: false,
22 };
23 pub const ALT: KeyMods = KeyMods {
24 ctrl: false,
25 alt: true,
26 shift: false,
27 };
28 pub const SHIFT: KeyMods = KeyMods {
29 ctrl: false,
30 alt: false,
31 shift: true,
32 };
33}
34
35#[derive(Clone, Copy, PartialEq, Eq, Debug)]
36pub enum KeyCode {
37 Char(char),
38 Enter,
39 Esc,
40 Backspace,
41 Tab,
42 Delete,
43 Insert,
44 Left,
45 Right,
46 Up,
47 Down,
48 Home,
49 End,
50 PageUp,
51 PageDown,
52}
53
54#[derive(Clone, Copy, PartialEq, Eq, Debug)]
55pub struct Key {
56 pub code: KeyCode,
57 pub mods: KeyMods,
58}
59
60#[derive(Clone, Copy, PartialEq, Eq, Debug)]
61pub enum MouseButton {
62 Left,
63 Middle,
64 Right,
65}
66
67#[derive(Clone, Copy, PartialEq, Eq, Debug)]
68pub enum MouseKind {
69 Down(MouseButton),
70 Up,
71 Drag,
72 Moved,
73 ScrollUp,
74 ScrollDown,
75}
76
77#[derive(Clone, Copy, PartialEq, Eq, Debug)]
78pub struct Mouse {
79 pub kind: MouseKind,
80 pub col: u16,
82 pub row: u16,
83}
84
85#[derive(Clone, PartialEq, Eq, Debug)]
86pub enum Event {
87 Key(Key),
88 Mouse(Mouse),
89 Resize(u16, u16),
90 Paste(String),
92}
93
94fn key(code: KeyCode, mods: KeyMods) -> Event {
95 Event::Key(Key { code, mods })
96}
97
98pub fn parse(buf: &mut Vec<u8>) -> Option<Event> {
101 if buf.is_empty() {
102 return None;
103 }
104
105 let b0 = buf[0];
106 if b0 == 0x1b {
107 return parse_escape(buf);
108 }
109
110 let ev = match b0 {
113 b'\r' => Some((key(KeyCode::Enter, KeyMods::NONE), 1)),
114 b'\n' => Some((key(KeyCode::Enter, KeyMods::SHIFT), 1)),
115 0x7f | 0x08 => Some((key(KeyCode::Backspace, KeyMods::NONE), 1)),
116 b'\t' => Some((key(KeyCode::Tab, KeyMods::NONE), 1)),
117 0x01..=0x1a => {
118 let ch = (b0 - 1 + b'a') as char;
120 Some((key(KeyCode::Char(ch), KeyMods::CTRL), 1))
121 }
122 0x1c => Some((key(KeyCode::Char('\\'), KeyMods::CTRL), 1)),
123 0x1d => Some((key(KeyCode::Char(']'), KeyMods::CTRL), 1)),
124 0x1e => Some((key(KeyCode::Char('^'), KeyMods::CTRL), 1)),
125 0x1f => Some((key(KeyCode::Char('_'), KeyMods::CTRL), 1)),
126 _ => None,
127 };
128 if let Some((event, n)) = ev {
129 buf.drain(0..n);
130 return Some(event);
131 }
132
133 let len = utf8_len(b0);
135 if buf.len() < len {
136 return None; }
138 let ch = std::str::from_utf8(&buf[0..len])
139 .ok()
140 .and_then(|s| s.chars().next());
141 buf.drain(0..len);
142 ch.map(|c| key(KeyCode::Char(c), KeyMods::NONE))
143}
144
145fn parse_escape(buf: &mut Vec<u8>) -> Option<Event> {
146 if buf.len() == 1 {
150 return None;
151 }
152
153 match buf[1] {
154 b'[' => parse_csi(buf),
155 b'O' => parse_ss3(buf),
156 b'\r' => {
158 buf.drain(0..2);
159 Some(key(KeyCode::Enter, KeyMods::ALT))
160 }
161 b'\n' => {
163 buf.drain(0..2);
164 Some(key(KeyCode::Enter, KeyMods::ALT))
165 }
166 c if c >= 0x20 => {
168 let len = utf8_len(c);
169 if buf.len() < 1 + len {
170 return None;
171 }
172 let ch = std::str::from_utf8(&buf[1..1 + len])
173 .ok()
174 .and_then(|s| s.chars().next());
175 buf.drain(0..1 + len);
176 ch.map(|c| key(KeyCode::Char(c), KeyMods::ALT))
177 }
178 _ => {
179 buf.drain(0..1);
180 Some(key(KeyCode::Esc, KeyMods::NONE))
181 }
182 }
183}
184
185fn parse_ss3(buf: &mut Vec<u8>) -> Option<Event> {
186 if buf.len() < 3 {
187 return None;
188 }
189 let code = match buf[2] {
190 b'A' => KeyCode::Up,
191 b'B' => KeyCode::Down,
192 b'C' => KeyCode::Right,
193 b'D' => KeyCode::Left,
194 b'H' => KeyCode::Home,
195 b'F' => KeyCode::End,
196 _ => {
197 buf.drain(0..3);
198 return None;
199 }
200 };
201 buf.drain(0..3);
202 Some(key(code, KeyMods::NONE))
203}
204
205fn parse_csi(buf: &mut Vec<u8>) -> Option<Event> {
206 if buf.len() >= 3 && buf[2] == b'<' {
208 return parse_sgr_mouse(buf);
209 }
210
211 let mut end = None;
213 for (i, &b) in buf.iter().enumerate().skip(2) {
214 if (0x40..=0x7e).contains(&b) {
215 end = Some(i);
216 break;
217 }
218 }
219 let end = end?; let final_byte = buf[end];
221 let params = parse_params(&buf[2..end]);
222
223 if final_byte == b'~' && params.first() == Some(&200) {
226 return parse_bracketed_paste(buf, end);
227 }
228
229 let event = match final_byte {
230 b'A' => Some(key(KeyCode::Up, mods_from_csi(¶ms, 1))),
231 b'B' => Some(key(KeyCode::Down, mods_from_csi(¶ms, 1))),
232 b'C' => Some(key(KeyCode::Right, mods_from_csi(¶ms, 1))),
233 b'D' => Some(key(KeyCode::Left, mods_from_csi(¶ms, 1))),
234 b'H' => Some(key(KeyCode::Home, mods_from_csi(¶ms, 1))),
235 b'F' => Some(key(KeyCode::End, mods_from_csi(¶ms, 1))),
236 b'u' => parse_csi_u(&buf[2..end]),
238 b'~' => parse_csi_tilde(¶ms),
239 _ => None,
240 };
241
242 buf.drain(0..=end);
243 event
244}
245
246fn parse_bracketed_paste(buf: &mut Vec<u8>, start_end: usize) -> Option<Event> {
249 const END: &[u8] = b"\x1b[201~";
250 let content_at = start_end + 1;
251 let Some(rel) = find_bytes(&buf[content_at..], END) else {
252 return None; };
254 let content = &buf[content_at..content_at + rel];
255 let paste = match std::str::from_utf8(content) {
256 Ok(s) => s.to_string(),
257 Err(_) => String::from_utf8_lossy(content).into_owned(),
258 };
259 buf.drain(0..content_at + rel + END.len());
260 Some(Event::Paste(paste))
261}
262
263fn find_bytes(hay: &[u8], needle: &[u8]) -> Option<usize> {
264 if needle.is_empty() || hay.len() < needle.len() {
265 return None;
266 }
267 hay.windows(needle.len()).position(|w| w == needle)
268}
269
270fn parse_csi_u(raw: &[u8]) -> Option<Event> {
273 let fields = parse_param_fields(raw);
274 let code = *fields.first()?.first()?;
275 let mods_field = fields.get(1);
276 let mods = mods_from_param(mods_field.and_then(|f| f.first()).copied());
277 let event_type = mods_field.and_then(|f| f.get(1)).copied().unwrap_or(1);
278 if event_type == 3 {
280 return None;
281 }
282 keycode_from_number(code).map(|c| key(c, mods))
283}
284
285fn parse_csi_tilde(params: &[u32]) -> Option<Event> {
287 if params.first() == Some(&27) && params.len() >= 3 {
289 let mods = mods_from_param(Some(params[1]));
290 return keycode_from_number(params[2]).map(|c| key(c, mods));
291 }
292
293 let id = *params.first().unwrap_or(&0);
294 let mods = mods_from_csi(params, 0);
295 let code = match id {
296 1 | 7 => KeyCode::Home,
297 2 => KeyCode::Insert,
298 4 | 8 => KeyCode::End,
299 3 => KeyCode::Delete,
300 5 => KeyCode::PageUp,
301 6 => KeyCode::PageDown,
302 13 => KeyCode::Enter, _ => return None,
304 };
305 Some(key(code, mods))
306}
307
308fn keycode_from_number(n: u32) -> Option<KeyCode> {
309 match n {
310 9 => Some(KeyCode::Tab),
311 13 => Some(KeyCode::Enter),
312 27 => Some(KeyCode::Esc),
313 127 => Some(KeyCode::Backspace),
314 c if (32..0x110000).contains(&c) => char::from_u32(c).map(KeyCode::Char),
316 _ => None,
317 }
318}
319
320fn mods_from_param(p: Option<u32>) -> KeyMods {
322 let m = p.unwrap_or(1).saturating_sub(1);
323 KeyMods {
324 shift: m & 1 != 0,
325 alt: m & 2 != 0,
326 ctrl: m & 4 != 0,
327 }
328}
329
330fn mods_from_csi(params: &[u32], _base_idx: usize) -> KeyMods {
333 if params.len() >= 2 {
334 mods_from_param(Some(params[1]))
335 } else {
336 KeyMods::NONE
337 }
338}
339
340fn parse_params(raw: &[u8]) -> Vec<u32> {
341 parse_param_fields(raw)
342 .into_iter()
343 .map(|f| f.into_iter().next().unwrap_or(0))
344 .collect()
345}
346
347fn parse_param_fields(raw: &[u8]) -> Vec<Vec<u32>> {
349 if raw.is_empty() {
350 return Vec::new();
351 }
352 std::str::from_utf8(raw)
353 .unwrap_or("")
354 .split(';')
355 .map(|p| p.split(':').map(|s| s.parse().unwrap_or(0)).collect())
356 .collect()
357}
358
359fn parse_sgr_mouse(buf: &mut Vec<u8>) -> Option<Event> {
360 let mut end = None;
362 for (i, &b) in buf.iter().enumerate().skip(3) {
363 if b == b'M' || b == b'm' {
364 end = Some(i);
365 break;
366 }
367 }
368 let end = end?;
369 let released = buf[end] == b'm';
370 let body = std::str::from_utf8(&buf[3..end]).ok()?;
371 let mut it = body.split(';');
372 let cb: u16 = it.next()?.parse().ok()?;
373 let cx: u16 = it.next()?.parse().ok()?;
374 let cy: u16 = it.next()?.parse().ok()?;
375 buf.drain(0..=end);
376
377 let col = cx.saturating_sub(1);
378 let row = cy.saturating_sub(1);
379
380 let kind = if cb & 0x40 != 0 {
381 if cb & 0x1 == 0 {
382 MouseKind::ScrollUp
383 } else {
384 MouseKind::ScrollDown
385 }
386 } else if released {
387 MouseKind::Up
388 } else if cb & 0x20 != 0 {
389 if cb & 0x3 == 3 {
391 MouseKind::Moved
392 } else {
393 MouseKind::Drag
394 }
395 } else {
396 match cb & 0x3 {
397 0 => MouseKind::Down(MouseButton::Left),
398 1 => MouseKind::Down(MouseButton::Middle),
399 2 => MouseKind::Down(MouseButton::Right),
400 _ => MouseKind::Moved,
401 }
402 };
403
404 Some(Event::Mouse(Mouse { kind, col, row }))
405}
406
407fn utf8_len(b: u8) -> usize {
408 if b < 0x80 {
409 1
410 } else if b >> 5 == 0b110 {
411 2
412 } else if b >> 4 == 0b1110 {
413 3
414 } else if b >> 3 == 0b11110 {
415 4
416 } else {
417 1
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424
425 #[test]
426 fn plain_char_and_ctrl() {
427 let mut b = b"a".to_vec();
428 assert_eq!(parse(&mut b), Some(key(KeyCode::Char('a'), KeyMods::NONE)));
429 assert!(b.is_empty());
430
431 let mut b = vec![0x03]; assert_eq!(parse(&mut b), Some(key(KeyCode::Char('c'), KeyMods::CTRL)));
433 }
434
435 #[test]
436 fn parses_ctrl_close_bracket() {
437 let mut bytes = vec![0x1d];
438 assert_eq!(
439 parse(&mut bytes),
440 Some(key(KeyCode::Char(']'), KeyMods::CTRL))
441 );
442 assert!(bytes.is_empty());
443 }
444
445 #[test]
446 fn arrows_and_enter() {
447 let mut b = b"\x1b[A".to_vec();
448 assert_eq!(parse(&mut b), Some(key(KeyCode::Up, KeyMods::NONE)));
449 let mut b = b"\r".to_vec();
450 assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::NONE)));
451 }
452
453 #[test]
454 fn newline_is_shift_enter() {
455 let mut b = b"\n".to_vec();
456 assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));
457 }
458
459 #[test]
460 fn alt_enter() {
461 let mut b = b"\x1b\r".to_vec();
462 assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::ALT)));
463 }
464
465 #[test]
466 fn shift_enter_kitty_and_xterm() {
467 let mut b = b"\x1b[13;2u".to_vec();
468 assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));
469
470 let mut b = b"\x1b[27;2;13~".to_vec();
471 assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));
472
473 let mut b = b"\x1b[13;2~".to_vec();
475 assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));
476
477 let mut b = b"\x1b[13;2:1u".to_vec();
479 assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::SHIFT)));
480 }
481
482 #[test]
483 fn kitty_release_is_ignored() {
484 let mut b = b"\x1b[100;1:1u\x1b[100;1:3u".to_vec();
486 assert_eq!(parse(&mut b), Some(key(KeyCode::Char('d'), KeyMods::NONE)));
487 assert_eq!(parse(&mut b), None);
488 assert!(b.is_empty());
489 }
490
491 #[test]
492 fn kitty_cyrillic_and_utf8() {
493 let mut b = b"\x1b[1072u".to_vec();
495 assert_eq!(parse(&mut b), Some(key(KeyCode::Char('а'), KeyMods::NONE)));
496
497 let mut b = "б".as_bytes().to_vec();
498 assert_eq!(parse(&mut b), Some(key(KeyCode::Char('б'), KeyMods::NONE)));
499 }
500
501 #[test]
502 fn ctrl_enter_and_ctrl_letter_via_modify_other_keys() {
503 let mut b = b"\x1b[27;5;13~".to_vec();
504 assert_eq!(parse(&mut b), Some(key(KeyCode::Enter, KeyMods::CTRL)));
505
506 let mut b = b"\x1b[27;5;99~".to_vec();
508 assert_eq!(parse(&mut b), Some(key(KeyCode::Char('c'), KeyMods::CTRL)));
509 }
510
511 #[test]
512 fn shift_arrow() {
513 let mut b = b"\x1b[1;2A".to_vec();
514 assert_eq!(parse(&mut b), Some(key(KeyCode::Up, KeyMods::SHIFT)));
515 }
516
517 #[test]
518 fn sgr_mouse_click_and_wheel() {
519 let mut b = b"\x1b[<0;10;5M".to_vec();
520 assert_eq!(
521 parse(&mut b),
522 Some(Event::Mouse(Mouse {
523 kind: MouseKind::Down(MouseButton::Left),
524 col: 9,
525 row: 4,
526 }))
527 );
528 let mut b = b"\x1b[<64;3;3M".to_vec();
529 assert_eq!(
530 parse(&mut b),
531 Some(Event::Mouse(Mouse {
532 kind: MouseKind::ScrollUp,
533 col: 2,
534 row: 2,
535 }))
536 );
537 }
538
539 #[test]
540 fn incomplete_waits() {
541 let mut b = b"\x1b[".to_vec();
542 assert_eq!(parse(&mut b), None);
543 assert_eq!(b, b"\x1b[");
544 }
545
546 #[test]
547 fn lone_esc_waits_for_disambiguation() {
548 let mut b = vec![0x1b];
549 assert_eq!(parse(&mut b), None);
550 assert_eq!(b, vec![0x1b]);
551 b.extend_from_slice(b"[<0;10;5M");
553 assert!(matches!(parse(&mut b), Some(Event::Mouse(_))));
554 }
555
556 #[test]
557 fn utf8_multibyte() {
558 let mut b = "→".as_bytes().to_vec();
559 assert_eq!(parse(&mut b), Some(key(KeyCode::Char('→'), KeyMods::NONE)));
560 }
561
562 #[test]
563 fn bracketed_paste() {
564 let mut b = b"\x1b[200~sk-abc123\x1b[201~".to_vec();
565 assert_eq!(parse(&mut b), Some(Event::Paste("sk-abc123".into())));
566 assert!(b.is_empty());
567 }
568
569 #[test]
570 fn insert_and_shift_insert() {
571 let mut b = b"\x1b[2~".to_vec();
572 assert_eq!(parse(&mut b), Some(key(KeyCode::Insert, KeyMods::NONE)));
573 let mut b = b"\x1b[2;2~".to_vec();
574 assert_eq!(parse(&mut b), Some(key(KeyCode::Insert, KeyMods::SHIFT)));
575 }
576
577 #[test]
578 fn bracketed_paste_incomplete_waits() {
579 let mut b = b"\x1b[200~partial".to_vec();
580 assert_eq!(parse(&mut b), None);
581 assert_eq!(b, b"\x1b[200~partial");
582 }
583}