termion/
event.rs

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
//! Mouse and key events.

use std::io::{Error, ErrorKind};
use std::str;

/// An event reported by the terminal.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Event {
    /// A key press.
    Key(Key),
    /// A mouse button press, release or wheel use at specific coordinates.
    Mouse(MouseEvent),
    /// An event that cannot currently be evaluated.
    Unsupported(Vec<u8>),
}

/// A mouse related event.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum MouseEvent {
    /// A mouse button was pressed.
    ///
    /// The coordinates are one-based.
    Press(MouseButton, u16, u16),
    /// A mouse button was released.
    ///
    /// The coordinates are one-based.
    Release(u16, u16),
    /// A mouse button is held over the given coordinates.
    ///
    /// The coordinates are one-based.
    Hold(u16, u16),
}

/// A mouse button.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum MouseButton {
    /// The left mouse button.
    Left,
    /// The right mouse button.
    Right,
    /// The middle mouse button.
    Middle,
    /// Mouse wheel is going up.
    ///
    /// This event is typically only used with Mouse::Press.
    WheelUp,
    /// Mouse wheel is going down.
    ///
    /// This event is typically only used with Mouse::Press.
    WheelDown,
}

/// A key.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Key {
    /// Backspace.
    Backspace,
    /// Left arrow.
    Left,
    /// Right arrow.
    Right,
    /// Up arrow.
    Up,
    /// Down arrow.
    Down,
    /// Home key.
    Home,
    /// End key.
    End,
    /// Page Up key.
    PageUp,
    /// Page Down key.
    PageDown,
    /// Delete key.
    Delete,
    /// Insert key.
    Insert,
    /// Function keys.
    ///
    /// Only function keys 1 through 12 are supported.
    F(u8),
    /// Normal character.
    Char(char),
    /// Alt modified character.
    Alt(char),
    /// Ctrl modified character.
    ///
    /// Note that certain keys may not be modifiable with `ctrl`, due to limitations of terminals.
    Ctrl(char),
    /// Null byte.
    Null,
    /// Esc key.
    Esc,

    #[doc(hidden)]
    __IsNotComplete,
}

/// Parse an Event from `item` and possibly subsequent bytes through `iter`.
pub fn parse_event<I>(item: u8, iter: &mut I) -> Result<Event, Error>
    where I: Iterator<Item = Result<u8, Error>>
{
    let error = Error::new(ErrorKind::Other, "Could not parse an event");
    match item {
        b'\x1B' => {
            // This is an escape character, leading a control sequence.
            Ok(match iter.next() {
                   Some(Ok(b'O')) => {
                match iter.next() {
                    // F1-F4
                    Some(Ok(val @ b'P'...b'S')) => Event::Key(Key::F(1 + val - b'P')),
                    _ => return Err(error),
                }
            }
                   Some(Ok(b'[')) => {
                // This is a CSI sequence.
                parse_csi(iter).ok_or(error)?
            }
                   Some(Ok(c)) => {
                let ch = parse_utf8_char(c, iter);
                Event::Key(Key::Alt(try!(ch)))
            }
                   Some(Err(_)) | None => return Err(error),
               })
        }
        b'\n' | b'\r' => Ok(Event::Key(Key::Char('\n'))),
        b'\t' => Ok(Event::Key(Key::Char('\t'))),
        b'\x7F' => Ok(Event::Key(Key::Backspace)),
        c @ b'\x01'...b'\x1A' => Ok(Event::Key(Key::Ctrl((c as u8 - 0x1 + b'a') as char))),
        c @ b'\x1C'...b'\x1F' => Ok(Event::Key(Key::Ctrl((c as u8 - 0x1C + b'4') as char))),
        b'\0' => Ok(Event::Key(Key::Null)),
        c => {
            Ok({
                   let ch = parse_utf8_char(c, iter);
                   Event::Key(Key::Char(try!(ch)))
               })
        }
    }
}

/// Parses a CSI sequence, just after reading ^[
///
/// Returns None if an unrecognized sequence is found.
fn parse_csi<I>(iter: &mut I) -> Option<Event>
    where I: Iterator<Item = Result<u8, Error>>
{
    Some(match iter.next() {
             Some(Ok(b'[')) => match iter.next() {
                 Some(Ok(val @ b'A'...b'E')) => Event::Key(Key::F(1 + val - b'A')),
                 _ => return None,
             },
             Some(Ok(b'D')) => Event::Key(Key::Left),
             Some(Ok(b'C')) => Event::Key(Key::Right),
             Some(Ok(b'A')) => Event::Key(Key::Up),
             Some(Ok(b'B')) => Event::Key(Key::Down),
             Some(Ok(b'H')) => Event::Key(Key::Home),
             Some(Ok(b'F')) => Event::Key(Key::End),
             Some(Ok(b'M')) => {
        // X10 emulation mouse encoding: ESC [ CB Cx Cy (6 characters only).
        let mut next = || iter.next().unwrap().unwrap();

        let cb = next() as i8 - 32;
        // (1, 1) are the coords for upper left.
        let cx = next().saturating_sub(32) as u16;
        let cy = next().saturating_sub(32) as u16;
        Event::Mouse(match cb & 0b11 {
                         0 => {
                             if cb & 0x40 != 0 {
                                 MouseEvent::Press(MouseButton::WheelUp, cx, cy)
                             } else {
                                 MouseEvent::Press(MouseButton::Left, cx, cy)
                             }
                         }
                         1 => {
                             if cb & 0x40 != 0 {
                                 MouseEvent::Press(MouseButton::WheelDown, cx, cy)
                             } else {
                                 MouseEvent::Press(MouseButton::Middle, cx, cy)
                             }
                         }
                         2 => MouseEvent::Press(MouseButton::Right, cx, cy),
                         3 => MouseEvent::Release(cx, cy),
                         _ => return None,
                     })
    }
             Some(Ok(b'<')) => {
        // xterm mouse encoding:
        // ESC [ < Cb ; Cx ; Cy (;) (M or m)
        let mut buf = Vec::new();
        let mut c = iter.next().unwrap().unwrap();
        while match c {
                  b'm' | b'M' => false,
                  _ => true,
              } {
            buf.push(c);
            c = iter.next().unwrap().unwrap();
        }
        let str_buf = String::from_utf8(buf).unwrap();
        let nums = &mut str_buf.split(';');

        let cb = nums.next()
            .unwrap()
            .parse::<u16>()
            .unwrap();
        let cx = nums.next()
            .unwrap()
            .parse::<u16>()
            .unwrap();
        let cy = nums.next()
            .unwrap()
            .parse::<u16>()
            .unwrap();

        let event = match cb {
            0...2 | 64...65 => {
                let button = match cb {
                    0 => MouseButton::Left,
                    1 => MouseButton::Middle,
                    2 => MouseButton::Right,
                    64 => MouseButton::WheelUp,
                    65 => MouseButton::WheelDown,
                    _ => unreachable!(),
                };
                match c {
                    b'M' => MouseEvent::Press(button, cx, cy),
                    b'm' => MouseEvent::Release(cx, cy),
                    _ => return None,
                }
            }
            32 => MouseEvent::Hold(cx, cy),
            3 => MouseEvent::Release(cx, cy),
            _ => return None,
        };

        Event::Mouse(event)
    }
             Some(Ok(c @ b'0'...b'9')) => {
        // Numbered escape code.
        let mut buf = Vec::new();
        buf.push(c);
        let mut c = iter.next().unwrap().unwrap();
        // The final byte of a CSI sequence can be in the range 64-126, so
        // let's keep reading anything else.
        while c < 64 || c > 126 {
            buf.push(c);
            c = iter.next().unwrap().unwrap();
        }

        match c {
            // rxvt mouse encoding:
            // ESC [ Cb ; Cx ; Cy ; M
            b'M' => {
                let str_buf = String::from_utf8(buf).unwrap();

                let nums: Vec<u16> = str_buf.split(';').map(|n| n.parse().unwrap()).collect();

                let cb = nums[0];
                let cx = nums[1];
                let cy = nums[2];

                let event = match cb {
                    32 => MouseEvent::Press(MouseButton::Left, cx, cy),
                    33 => MouseEvent::Press(MouseButton::Middle, cx, cy),
                    34 => MouseEvent::Press(MouseButton::Right, cx, cy),
                    35 => MouseEvent::Release(cx, cy),
                    64 => MouseEvent::Hold(cx, cy),
                    96 | 97 => MouseEvent::Press(MouseButton::WheelUp, cx, cy),
                    _ => return None,
                };

                Event::Mouse(event)
            }
            // Special key code.
            b'~' => {
                let str_buf = String::from_utf8(buf).unwrap();

                // This CSI sequence can be a list of semicolon-separated
                // numbers.
                let nums: Vec<u8> = str_buf.split(';').map(|n| n.parse().unwrap()).collect();

                if nums.is_empty() {
                    return None;
                }

                // TODO: handle multiple values for key modififiers (ex: values
                // [3, 2] means Shift+Delete)
                if nums.len() > 1 {
                    return None;
                }

                match nums[0] {
                    1 | 7 => Event::Key(Key::Home),
                    2 => Event::Key(Key::Insert),
                    3 => Event::Key(Key::Delete),
                    4 | 8 => Event::Key(Key::End),
                    5 => Event::Key(Key::PageUp),
                    6 => Event::Key(Key::PageDown),
                    v @ 11...15 => Event::Key(Key::F(v - 10)),
                    v @ 17...21 => Event::Key(Key::F(v - 11)),
                    v @ 23...24 => Event::Key(Key::F(v - 12)),
                    _ => return None,
                }
            }
            _ => return None,
        }
    }
             _ => return None,
         })

}

/// Parse `c` as either a single byte ASCII char or a variable size UTF-8 char.
fn parse_utf8_char<I>(c: u8, iter: &mut I) -> Result<char, Error>
    where I: Iterator<Item = Result<u8, Error>>
{
    let error = Err(Error::new(ErrorKind::Other, "Input character is not valid UTF-8"));
    if c.is_ascii() {
        Ok(c as char)
    } else {
        let bytes = &mut Vec::new();
        bytes.push(c);

        loop {
            match iter.next() {
                Some(Ok(next)) => {
                    bytes.push(next);
                    if let Ok(st) = str::from_utf8(bytes) {
                        return Ok(st.chars().next().unwrap());
                    }
                    if bytes.len() >= 4 {
                        return error;
                    }
                }
                _ => return error,
            }
        }
    }
}

#[cfg(test)]
#[test]
fn test_parse_utf8() {
    let st = "abcéŷ¤£€ù%323";
    let ref mut bytes = st.bytes().map(|x| Ok(x));
    let chars = st.chars();
    for c in chars {
        let b = bytes.next().unwrap().unwrap();
        assert!(c == parse_utf8_char(b, bytes).unwrap());
    }
}