1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use std::fmt;
use std::str::FromStr;
// TODO: Add any extended keys sent by xterm or rxvt or whatever
/// A keypress
///
/// Note that not all possible combinations of keys can actually be
/// transmitted as an ANSI sequence. Often Ctrl is only recognised
/// with the 32 ASCII characters from `@` to `_`. Some of the Meta
/// combinations can only be generated by pressing Esc quickly
/// followed by the key.
#[derive(PartialEq, Eq)]
pub enum Key {
/// Printable character without Ctrl or Alt
Bare(char),
/// Control key combination. Note that some control keys are
/// passed through as specific values for convenience:
/// [`Key::Tab`] for `^I` (ASCII 9), [`Key::Return`] for `^M`
/// (ASCII 13), [`Key::Esc`] for `^[` (ASCII 27) and
/// [`Key::BackSp`] for `^?` (ASCII 127).
///
/// [`Key::BackSp`]: enum.Key.html#variant.BackSp
/// [`Key::Esc`]: enum.Key.html#variant.Esc
/// [`Key::Return`]: enum.Key.html#variant.Return
/// [`Key::Tab`]: enum.Key.html#variant.Tab
Ctrl(char),
/// Function key, F1 to F20
F(u32),
Tab,
Return,
BackSp,
Esc,
Up,
Down,
Left,
Right,
PgUp,
PgDn,
Home,
Insert,
Delete,
End,
/// Meta/Alt key combination
Meta(char),
/// Meta/Alt with Ctrl key combination
MetaCtrl(char),
/// Meta/Alt with function key F1 to F20
MetaF(u32),
MetaTab,
MetaReturn,
MetaBackSp,
MetaEsc,
MetaUp,
MetaDown,
MetaLeft,
MetaRight,
MetaPgUp,
MetaPgDn,
MetaHome,
MetaInsert,
MetaDelete,
MetaEnd,
/// Appears before pasted text on some terminals
PasteStart,
/// Appears after pasted text on some terminals
PasteEnd,
/// `Check` can be sent in a pause in typing, 300ms after the last
/// keypress. It's a good time to do field validation if that
/// validation is expensive. See [`Terminal::check`].
///
/// [`Terminal::check`]: struct.Terminal.html#method.check
Check,
/// `Invalid` is generated for a keypress which cannot be decoded,
/// e.g. invalid UTF-8 or some other problem
Invalid,
}
impl fmt::Debug for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl fmt::Display for Key {
/// Convert to a display string, using `M-` and `C-` prefixes for
/// Meta and Ctrl.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Key::Bare(ch) => write!(f, "{}", ch),
Key::Ctrl(ch) => write!(f, "C-{}", ch),
Key::F(num) => write!(f, "F{}", num),
Key::Tab => write!(f, "Tab"),
Key::Return => write!(f, "Return"),
Key::BackSp => write!(f, "BackSp"),
Key::Esc => write!(f, "Esc"),
Key::Up => write!(f, "Up"),
Key::Down => write!(f, "Down"),
Key::Left => write!(f, "Left"),
Key::Right => write!(f, "Right"),
Key::PgUp => write!(f, "PgUp"),
Key::PgDn => write!(f, "PgDn"),
Key::Home => write!(f, "Home"),
Key::Insert => write!(f, "Insert"),
Key::Delete => write!(f, "Delete"),
Key::End => write!(f, "End"),
Key::Meta(ch) => write!(f, "M-{}", ch),
Key::MetaCtrl(ch) => write!(f, "M-C-{}", ch),
Key::MetaF(num) => write!(f, "M-F{}", num),
Key::MetaTab => write!(f, "M-Tab"),
Key::MetaReturn => write!(f, "M-Return"),
Key::MetaBackSp => write!(f, "M-BackSp"),
Key::MetaEsc => write!(f, "M-Esc"),
Key::MetaUp => write!(f, "M-Up"),
Key::MetaDown => write!(f, "M-Down"),
Key::MetaLeft => write!(f, "M-Left"),
Key::MetaRight => write!(f, "M-Right"),
Key::MetaPgUp => write!(f, "M-PgUp"),
Key::MetaPgDn => write!(f, "M-PgDn"),
Key::MetaHome => write!(f, "M-Home"),
Key::MetaInsert => write!(f, "M-Insert"),
Key::MetaDelete => write!(f, "M-Delete"),
Key::MetaEnd => write!(f, "M-End"),
Key::PasteStart => write!(f, "PasteStart"),
Key::PasteEnd => write!(f, "PasteEnd"),
Key::Check => write!(f, "Check"),
Key::Invalid => write!(f, "Invalid"),
}
}
}
pub struct ParseKeyError {}
impl FromStr for Key {
type Err = ParseKeyError;
/// Convert back from the `Display` representation of a key
fn from_str(mut s: &str) -> Result<Key, ParseKeyError> {
let meta = if s.starts_with("M-") {
s = s.split_at(2).1;
true
} else {
false
};
let ctrl = if s.starts_with("C-") {
s = s.split_at(2).1;
true
} else {
false
};
let mut it = s.chars();
if let Some(ch) = it.next() {
if it.as_str().is_empty() {
return Ok(match (meta, ctrl) {
(false, false) => Key::Bare(ch),
(false, true) => Key::Ctrl(ch),
(true, false) => Key::Meta(ch),
(true, true) => Key::MetaCtrl(ch),
});
}
if ch == 'F' && !ctrl {
if let Ok(v) = it.as_str().parse::<u32>() {
if v >= 1 && v <= 20 {
return Ok(if meta { Key::MetaF(v) } else { Key::F(v) });
}
}
}
}
if !ctrl {
let keys = match s {
"Return" => (Key::Return, Key::MetaReturn),
"BackSp" => (Key::BackSp, Key::MetaBackSp),
"Esc" => (Key::Esc, Key::MetaEsc),
"Up" => (Key::Up, Key::MetaUp),
"Down" => (Key::Down, Key::MetaDown),
"Left" => (Key::Left, Key::MetaLeft),
"Right" => (Key::Right, Key::MetaRight),
"PgUp" => (Key::PgUp, Key::MetaPgUp),
"PgDn" => (Key::PgDn, Key::MetaPgDn),
"Home" => (Key::Home, Key::MetaHome),
"Insert" => (Key::Insert, Key::MetaInsert),
"Delete" => (Key::Delete, Key::MetaDelete),
"End" => (Key::End, Key::MetaEnd),
"PasteStart" if !meta => (Key::PasteStart, Key::PasteStart),
"PasteEnd" if !meta => (Key::PasteEnd, Key::PasteEnd),
"Check" if !meta => (Key::Check, Key::Check),
"Invalid" if !meta => (Key::Invalid, Key::Invalid),
_ => return Err(ParseKeyError {}),
};
return Ok(if meta { keys.1 } else { keys.0 });
}
Err(ParseKeyError {})
}
}
// For scanning over data
struct Scan<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Scan<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data, pos: 0 }
}
fn grab(&mut self, v: u8) -> bool {
if self.data.get(self.pos) == Some(&v) {
self.pos += 1;
true
} else {
false
}
}
fn len(&self) -> usize {
self.data.len() - self.pos
}
fn is_empty(&self) -> bool {
self.data.len() == self.pos
}
//fn rest<'b>(&self, data: &'b [u8]) -> &'b [u8] {
// &data[self.pos..]
//}
fn next(&mut self) -> Option<u8> {
if self.pos < self.data.len() {
self.pos += 1;
Some(self.data[self.pos - 1])
} else {
None
}
}
fn take(&mut self, count: usize) -> Option<&'a [u8]> {
if self.pos + count <= self.data.len() {
self.pos += count;
Some(&self.data[self.pos - count..self.pos])
} else {
None
}
}
fn grab_num(&mut self) -> Option<u32> {
let pos0 = self.pos;
let mut val = 0;
while self.pos < self.data.len()
&& self.data[self.pos] >= b'0'
&& self.data[self.pos] <= b'9'
{
val = val * 10 + u32::from(self.data[self.pos] - b'0');
self.pos += 1;
}
if self.pos > pos0 {
Some(val)
} else {
None
}
}
}
impl Key {
/// Add meta to a key if possible, otherwise return `None`
pub fn meta(&self) -> Option<Self> {
match self {
Key::Bare(ch) => Some(Key::Meta(*ch)),
Key::Ctrl(ch) => Some(Key::MetaCtrl(*ch)),
Key::F(num) => Some(Key::MetaF(*num)),
Key::Tab => Some(Key::MetaTab),
Key::Return => Some(Key::MetaReturn),
Key::BackSp => Some(Key::MetaBackSp),
Key::Esc => Some(Key::MetaEsc),
Key::Up => Some(Key::MetaUp),
Key::Down => Some(Key::MetaDown),
Key::Left => Some(Key::MetaLeft),
Key::Right => Some(Key::MetaRight),
Key::PgUp => Some(Key::MetaPgUp),
Key::PgDn => Some(Key::MetaPgDn),
Key::Home => Some(Key::MetaHome),
Key::Insert => Some(Key::MetaInsert),
Key::Delete => Some(Key::MetaDelete),
Key::End => Some(Key::MetaEnd),
_ => None,
}
}
/// Attempt to decode a keypress from data received from the
/// terminal. Will not decode a partial sequence at the end of
/// the buffer unless `force` is set. Returns count of bytes
/// consumed and the decoded key, or else `None`.
pub fn decode(data: &[u8], force: bool) -> Option<(usize, Key)> {
let mut sc = Scan::new(data);
let key = if sc.grab(27) {
if sc.grab(27) {
Self::decode_esc_esc(&mut sc, force)
} else {
Self::decode_esc(&mut sc, force)
}
} else {
Self::decode_bare(&mut sc, force)
};
match key {
Some(key) => Some((sc.pos, key)),
None => None,
}
}
// The expressions in these functions should either result in a
// key (which is then wrapped in `Some`), or should execute
// `return` directly to provide a return value.
fn decode_bare(sc: &mut Scan<'_>, force: bool) -> Option<Key> {
Some(match sc.next() {
Some(c) if c < 32 => match c {
9 => Key::Tab,
13 => Key::Return,
_ => Key::Ctrl((c + 64) as char),
},
Some(c) if c < 0x80 => match c {
127 => Key::BackSp,
_ => Key::Bare(c as char),
},
Some(c) if c < 0xC0 => Key::Invalid,
Some(c) => {
sc.pos -= 1;
let len = match c >> 4 {
15 => 4,
14 => 3,
_ => 2,
};
if let Some(seq) = sc.take(len) {
match std::str::from_utf8(seq).ok().and_then(|s| s.chars().next()) {
Some(c) => Key::Bare(c),
None => Key::Invalid,
}
} else if !force {
return None; // Wait for more
} else {
sc.take(sc.len());
Key::Invalid
}
}
None => return None, // Wait for more
})
}
fn decode_esc(sc: &mut Scan<'_>, force: bool) -> Option<Key> {
Some(if sc.is_empty() {
if !force {
return None; // Wait for more
}
Key::Esc
} else if sc.grab(b'O') {
return Self::decode_esc_o(sc, force);
} else if sc.grab(b'[') {
return Self::decode_esc_bracket(sc, force);
} else {
// Something other than 'O' or '[': See if it's Meta-(bare)
let mark = sc.pos;
if let Some(key) = Self::decode_bare(sc, force).and_then(|k| k.meta()) {
key
} else {
sc.pos = mark;
Key::Esc
}
})
}
fn decode_esc_o(sc: &mut Scan<'_>, force: bool) -> Option<Key> {
let mark = sc.pos;
Some(match sc.next() {
Some(b'P') => Key::F(1),
Some(b'Q') => Key::F(2),
Some(b'R') => Key::F(3),
Some(b'S') => Key::F(4),
None if !force => return None, // Wait for more
_ => {
sc.pos = mark;
Key::Meta('O')
}
})
}
fn decode_esc_bracket(sc: &mut Scan<'_>, force: bool) -> Option<Key> {
let mark = sc.pos;
Some(match sc.next() {
Some(b'A') => Key::Up,
Some(b'B') => Key::Down,
Some(b'C') => Key::Right,
Some(b'D') => Key::Left,
Some(b'[') => match sc.next() {
Some(b'A') => Key::F(1),
Some(b'B') => Key::F(2),
Some(b'C') => Key::F(3),
Some(b'D') => Key::F(4),
Some(b'E') => Key::F(5),
None if !force => return None, // Wait for more
_ => {
sc.pos = mark;
Key::Meta('[')
}
},
Some(b'0'..=b'9') => {
sc.pos -= 1;
let num = sc.grab_num().unwrap();
let mut _modf = None;
if sc.grab(b';') {
_modf = sc.grab_num();
if _modf.is_none() && sc.is_empty() {
if !force {
return None; // Wait for more
}
sc.pos = mark;
return Some(Key::Meta('['));
}
// If there's no number there, then just
// ignore the spurious ';'
}
if sc.grab(b'~') {
// TODO: Take account of the modifier value `modf`? Ignore for now
match num {
1 => Key::Home,
2 => Key::Insert,
3 => Key::Delete,
4 => Key::End,
5 => Key::PgUp,
6 => Key::PgDn,
11..=15 => Key::F(num - 10),
17..=21 => Key::F(num - 11),
23..=26 => Key::F(num - 12),
28..=29 => Key::F(num - 13),
31..=34 => Key::F(num - 14),
200 => Key::PasteStart,
201 => Key::PasteEnd,
_ => Key::Invalid,
}
} else if sc.is_empty() && !force {
return None; // Wait for more
} else {
// empty && force, or something other than ~
sc.pos = mark;
Key::Meta('[')
}
}
None if !force => return None, // Wait for more
_ => {
sc.pos = mark;
Key::Meta('[')
}
})
}
fn decode_esc_esc(sc: &mut Scan<'_>, force: bool) -> Option<Key> {
let mark = sc.pos;
Some(if sc.is_empty() {
if !force {
return None; // Wait for more
}
Key::MetaEsc
} else if let Some(key) = Self::decode_esc(sc, force).and_then(|k| k.meta()) {
key
} else {
sc.pos = mark;
Key::MetaEsc
})
}
}