terminal 0.2.1

Unified API over different TUI libraries.
Documentation
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
use crate::{Color, Event, KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent};
use crosscurses::{mmask_t, Input};
use std::io::Write;

impl<W: Write> super::BackendImpl<W> {
    pub fn parse_next(&self, input: crosscurses::Input) -> Event {
        // Try to map the crosscurses input event to an `KeyEvent` with possible modifiers.
        let key_event = self.try_parse_key(input).map_or(
            self.try_map_shift_key(input).map_or(
                self.try_map_ctrl_key(input)
                    .map_or(self.try_map_ctrl_alt_key(input), Some),
                Some,
            ),
            Some,
        );

        match key_event {
            Some(key_event) => Event::Key(key_event),
            None => {
                // TODO, if your event is not mapped, feel free to add it.
                // Although other backends have to support it as well.
                // The point of this library is to support the most of the important keys.

                self.try_map_non_key_event(input)
                    .map_or(Event::Unknown, |e| e)
            }
        }
    }

    /// Matches on keys without modifiers, returns `None` if the key has modifiers or is not supported.
    pub fn try_parse_key(&self, input: crosscurses::Input) -> Option<KeyEvent> {
        let empty = KeyModifiers::empty();

        let key_code = match input {
            Input::Character(c) => match c {
                '\r' | '\n' => Some(KeyCode::Enter.into()),
                '\t' => Some(KeyCode::Tab.into()),
                '\x7F' => Some(KeyCode::Backspace.into()),
                '\u{8}' => Some(KeyCode::Backspace.into()),
                c @ '\x01'..='\x1A' => Some(KeyEvent::new(
                    KeyCode::Char((c as u8 - 0x1 + b'a') as char),
                    KeyModifiers::CONTROL,
                )),
                c @ '\x1C'..='\x1F' => Some(KeyEvent::new(
                    KeyCode::Char((c as u8 - 0x1C + b'4') as char),
                    KeyModifiers::CONTROL,
                )),
                _ if (c as u32) <= 26 => Some(KeyEvent::new(
                    KeyCode::Char((b'a' - 1 + c as u8) as char),
                    KeyModifiers::CONTROL,
                )),
                '\u{1b}' => Some(KeyCode::Esc.into()),
                c => Some(KeyCode::Char(c).into()),
            },
            Input::KeyDown => Some(KeyEvent {
                code: KeyCode::Down,
                modifiers: empty,
            }),
            Input::KeyUp => Some(KeyEvent {
                code: KeyCode::Up,
                modifiers: empty,
            }),
            Input::KeyLeft => Some(KeyEvent {
                code: KeyCode::Left,
                modifiers: empty,
            }),
            Input::KeyRight => Some(KeyEvent {
                code: KeyCode::Right,
                modifiers: empty,
            }),
            Input::KeyHome => Some(KeyEvent {
                code: KeyCode::Home,
                modifiers: empty,
            }),
            Input::KeyBackspace => Some(KeyEvent {
                code: KeyCode::Backspace,
                modifiers: empty,
            }),
            Input::KeyF0 => Some(KeyEvent {
                code: KeyCode::F(0),
                modifiers: empty,
            }),
            Input::KeyF1 => Some(KeyEvent {
                code: KeyCode::F(1),
                modifiers: empty,
            }),
            Input::KeyF2 => Some(KeyEvent {
                code: KeyCode::F(2),
                modifiers: empty,
            }),
            Input::KeyF3 => Some(KeyEvent {
                code: KeyCode::F(3),
                modifiers: empty,
            }),
            Input::KeyF4 => Some(KeyEvent {
                code: KeyCode::F(4),
                modifiers: empty,
            }),
            Input::KeyF5 => Some(KeyEvent {
                code: KeyCode::F(5),
                modifiers: empty,
            }),
            Input::KeyF6 => Some(KeyEvent {
                code: KeyCode::F(6),
                modifiers: empty,
            }),
            Input::KeyF7 => Some(KeyEvent {
                code: KeyCode::F(7),
                modifiers: empty,
            }),
            Input::KeyF8 => Some(KeyEvent {
                code: KeyCode::F(8),
                modifiers: empty,
            }),
            Input::KeyF9 => Some(KeyEvent {
                code: KeyCode::F(9),
                modifiers: empty,
            }),
            Input::KeyF10 => Some(KeyEvent {
                code: KeyCode::F(10),
                modifiers: empty,
            }),
            Input::KeyF11 => Some(KeyEvent {
                code: KeyCode::F(11),
                modifiers: empty,
            }),
            Input::KeyF12 => Some(KeyEvent {
                code: KeyCode::F(12),
                modifiers: empty,
            }),
            Input::KeyF13 => Some(KeyEvent {
                code: KeyCode::F(13),
                modifiers: empty,
            }),
            Input::KeyF14 => Some(KeyEvent {
                code: KeyCode::F(14),
                modifiers: empty,
            }),
            Input::KeyF15 => Some(KeyEvent {
                code: KeyCode::F(15),
                modifiers: empty,
            }),
            Input::KeyDL => Some(KeyEvent {
                code: KeyCode::Delete,
                modifiers: empty,
            }),
            Input::KeyIC => Some(KeyEvent {
                code: KeyCode::Insert,
                modifiers: empty,
            }),
            Input::KeyNPage => Some(KeyEvent {
                code: KeyCode::PageDown,
                modifiers: empty,
            }),
            Input::KeyPPage => Some(KeyEvent {
                code: KeyCode::PageUp,
                modifiers: empty,
            }),
            Input::KeyEnter => Some(KeyEvent {
                code: KeyCode::Enter,
                modifiers: empty,
            }),
            Input::KeyEnd => Some(KeyEvent {
                code: KeyCode::End,
                modifiers: empty,
            }),
            _ => None,
        };

        key_code.map(|e| e)
    }

    /// Matches on shift keys, returns `None` if the key does not have an SHIFT modifier or is not supported.
    pub fn try_map_shift_key(&self, input: crosscurses::Input) -> Option<KeyEvent> {
        let key_code = match input {
            Input::KeySF => Some(KeyCode::Down),
            Input::KeySR => Some(KeyCode::Up),
            Input::KeySTab => Some(KeyCode::Tab),
            Input::KeySDC => Some(KeyCode::Delete),
            Input::KeySEnd => Some(KeyCode::End),
            Input::KeySHome => Some(KeyCode::Home),
            Input::KeySIC => Some(KeyCode::Insert),
            Input::KeySLeft => Some(KeyCode::Left),
            Input::KeySNext => Some(KeyCode::PageDown),
            Input::KeySPrevious => Some(KeyCode::PageDown),
            Input::KeySPrint => Some(KeyCode::End),
            Input::KeySRight => Some(KeyCode::Right),
            Input::KeyBTab => Some(KeyCode::BackTab),
            _ => None,
        };

        key_code.map(|e| KeyEvent::new(e, KeyModifiers::SHIFT))
    }

    /// Matches on CTRL keys, returns `None` if the key does not have an CTRL modifier or is not supported.
    pub fn try_map_ctrl_key(&self, input: crosscurses::Input) -> Option<KeyEvent> {
        let key_code = match input {
            Input::KeyCTab => Some(KeyCode::Tab),
            _ => None,
        };

        key_code.map(|e| KeyEvent::new(e, KeyModifiers::CONTROL))
    }

    /// Matches on CTRL + ALT keys, returns `None` if the key does not have an SHIFT + ALT modifier or is not supported.
    pub fn try_map_ctrl_alt_key(&self, input: crosscurses::Input) -> Option<KeyEvent> {
        let key_code = match input {
            Input::KeyCATab => Some(KeyCode::Tab),
            _ => None,
        };

        key_code.map(|e| KeyEvent::new(e, KeyModifiers::CONTROL | KeyModifiers::ALT))
    }

    /// Matches on non key events, returns `None` if the key is not a non-key event or is not supported.
    pub fn try_map_non_key_event(&self, input: crosscurses::Input) -> Option<Event> {
        // No key event, handle non key events e.g resize
        match input {
            Input::KeyResize => {
                // Let crosscurses adjust their structures when the
                // window is resized.
                crosscurses::resize_term(0, 0);

                Some(Event::Resize)
            }
            Input::KeyMouse => Some(self.map_mouse_event()),
            Input::Unknown(code) => {
                Some(
                    self.key_codes
                        // crosscurses does some weird keycode mapping
                        .get(&(code + 256 + 48))
                        .cloned()
                        .unwrap_or_else(|| Event::Unknown),
                )
            }
            _ => None,
        }
    }

    fn map_mouse_event(&self) -> Event {
        let mut mevent = match crosscurses::getmouse() {
            Err(_) => return Event::Unknown,
            Ok(event) => event,
        };

        let shift = (mevent.bstate & crosscurses::BUTTON_SHIFT as mmask_t) != 0;
        let alt = (mevent.bstate & crosscurses::BUTTON_ALT as mmask_t) != 0;
        let ctrl = (mevent.bstate & crosscurses::BUTTON_CTRL as mmask_t) != 0;

        let mut modifiers = KeyModifiers::empty();

        if shift {
            modifiers |= KeyModifiers::SHIFT;
        }
        if ctrl {
            modifiers |= KeyModifiers::CONTROL;
        }
        if alt {
            modifiers |= KeyModifiers::ALT;
        }

        mevent.bstate &= !(crosscurses::BUTTON_SHIFT
            | crosscurses::BUTTON_ALT
            | crosscurses::BUTTON_CTRL) as mmask_t;

        let (x, y) = (mevent.x as u16, mevent.y as u16);

        if mevent.bstate == crosscurses::REPORT_MOUSE_POSITION as mmask_t {
            // The event is either a mouse drag event,
            // or a weird double-release event. :S
            self.last_btn()
                .map(|btn| Event::Mouse(MouseEvent::Drag(btn, x, y, modifiers)))
                .unwrap_or_else(|| {
                    // We got a mouse drag, but no last mouse pressed?
                    Event::Unknown
                })
        } else {
            // Identify the button
            let mut bare_event = mevent.bstate & ((1 << 25) - 1);

            let mut event = None;
            while bare_event != 0 {
                let single_event = 1 << bare_event.trailing_zeros();
                bare_event ^= single_event;

                // Process single_event
                self.on_mouse_event(
                    single_event,
                    |e| {
                        if event.is_none() {
                            event = Some(e);
                        } else {
                            self.update_stored_event(Event::Mouse(e));
                        }
                    },
                    x,
                    y,
                    modifiers,
                );
            }

            if let Some(event) = event {
                if let Some(btn) = event.button() {
                    self.update_last_btn(btn);
                }

                Event::Mouse(event)
            } else {
                // No event parsed?...
                Event::Unknown
            }
        }
    }

    /// Parse the given code into one or more event.
    ///
    /// If the given event code should expend into multiple events
    /// (for instance click expends into PRESS + RELEASE),
    /// the returned Vec will include those queued events.
    ///
    /// The main event is returned separately to avoid allocation in most cases.
    fn on_mouse_event<F>(
        &self,
        bare_event: mmask_t,
        mut f: F,
        x: u16,
        y: u16,
        modifiers: KeyModifiers,
    ) where
        F: FnMut(MouseEvent),
    {
        let button = self.map_mouse_button(bare_event);
        match bare_event {
            crosscurses::BUTTON4_PRESSED => f(MouseEvent::ScrollUp(x, y, modifiers)),
            crosscurses::BUTTON5_PRESSED => f(MouseEvent::ScrollDown(x, y, modifiers)),
            crosscurses::BUTTON1_RELEASED
            | crosscurses::BUTTON2_RELEASED
            | crosscurses::BUTTON3_RELEASED
            | crosscurses::BUTTON4_RELEASED
            | crosscurses::BUTTON5_RELEASED => f(MouseEvent::Up(button, x, y, modifiers)),
            crosscurses::BUTTON1_PRESSED
            | crosscurses::BUTTON2_PRESSED
            | crosscurses::BUTTON3_PRESSED => f(MouseEvent::Down(button, x, y, modifiers)),
            crosscurses::BUTTON1_CLICKED
            | crosscurses::BUTTON2_CLICKED
            | crosscurses::BUTTON3_CLICKED
            | crosscurses::BUTTON4_CLICKED
            | crosscurses::BUTTON5_CLICKED => {
                f(MouseEvent::Down(button, x, y, modifiers));
                f(MouseEvent::Up(button, x, y, modifiers));
            }
            // Well, we disabled click detection
            crosscurses::BUTTON1_DOUBLE_CLICKED
            | crosscurses::BUTTON2_DOUBLE_CLICKED
            | crosscurses::BUTTON3_DOUBLE_CLICKED
            | crosscurses::BUTTON4_DOUBLE_CLICKED
            | crosscurses::BUTTON5_DOUBLE_CLICKED => {
                for _ in 0..2 {
                    f(MouseEvent::Down(button, x, y, modifiers));
                    f(MouseEvent::Up(button, x, y, modifiers));
                }
            }
            crosscurses::BUTTON1_TRIPLE_CLICKED
            | crosscurses::BUTTON2_TRIPLE_CLICKED
            | crosscurses::BUTTON3_TRIPLE_CLICKED
            | crosscurses::BUTTON4_TRIPLE_CLICKED
            | crosscurses::BUTTON5_TRIPLE_CLICKED => {
                for _ in 0..3 {
                    f(MouseEvent::Down(button, x, y, modifiers));
                    f(MouseEvent::Up(button, x, y, modifiers));
                }
            }
            _ => { // Unknown event: {:032b}", bare_event }
            }
        }
    }

    /// Returns the Key enum corresponding to the given crosscurses event.
    fn map_mouse_button(&self, bare_event: mmask_t) -> MouseButton {
        match bare_event {
            crosscurses::BUTTON1_RELEASED
            | crosscurses::BUTTON1_PRESSED
            | crosscurses::BUTTON1_CLICKED
            | crosscurses::BUTTON1_DOUBLE_CLICKED
            | crosscurses::BUTTON1_TRIPLE_CLICKED => MouseButton::Left,
            crosscurses::BUTTON2_RELEASED
            | crosscurses::BUTTON2_PRESSED
            | crosscurses::BUTTON2_CLICKED
            | crosscurses::BUTTON2_DOUBLE_CLICKED
            | crosscurses::BUTTON2_TRIPLE_CLICKED => MouseButton::Middle,
            crosscurses::BUTTON3_RELEASED
            | crosscurses::BUTTON3_PRESSED
            | crosscurses::BUTTON3_CLICKED
            | crosscurses::BUTTON3_DOUBLE_CLICKED
            | crosscurses::BUTTON3_TRIPLE_CLICKED => MouseButton::Right,
            crosscurses::BUTTON4_RELEASED
            | crosscurses::BUTTON4_PRESSED
            | crosscurses::BUTTON4_CLICKED
            | crosscurses::BUTTON4_DOUBLE_CLICKED
            | crosscurses::BUTTON4_TRIPLE_CLICKED => MouseButton::Unknown,
            crosscurses::BUTTON5_RELEASED
            | crosscurses::BUTTON5_PRESSED
            | crosscurses::BUTTON5_CLICKED
            | crosscurses::BUTTON5_DOUBLE_CLICKED
            | crosscurses::BUTTON5_TRIPLE_CLICKED => MouseButton::Unknown,
            _ => MouseButton::Unknown,
        }
    }
}

pub fn find_closest(color: Color, max_colors: i16) -> i16 {
    // translate ansi value to rgb
    let color = if let Color::AnsiValue(val) = color {
        Color::from(val)
    } else {
        color
    };

    // translate to closest supported color.
    match color {
        // Dark colors
        Color::Black => crosscurses::COLOR_BLACK,
        Color::DarkRed => crosscurses::COLOR_RED,
        Color::DarkGreen => crosscurses::COLOR_GREEN,
        Color::DarkYellow => crosscurses::COLOR_YELLOW,
        Color::DarkBlue => crosscurses::COLOR_BLUE,
        Color::DarkMagenta => crosscurses::COLOR_MAGENTA,
        Color::DarkCyan => crosscurses::COLOR_CYAN,
        Color::Grey => crosscurses::COLOR_WHITE,

        // Light colors
        Color::Red => 9 % max_colors,
        Color::Green => 10 % max_colors,
        Color::Yellow => 11 % max_colors,
        Color::Blue => 12 % max_colors,
        Color::Magenta => 13 % max_colors,
        Color::Cyan => 14 % max_colors,
        Color::White => 15 % max_colors,
        Color::Rgb(r, g, b) if max_colors >= 256 => {
            // If r = g = b, it may be a grayscale value!
            if r == g && g == b && r != 0 && r < 250 {
                // Grayscale
                // (r = g = b) = 8 + 10 * n
                // (r - 8) / 10 = n
                let n = (r - 8) / 10;
                i16::from(232 + n)
            } else {
                // Generic RGB
                let r = 6 * u16::from(r) / 256;
                let g = 6 * u16::from(g) / 256;
                let b = 6 * u16::from(b) / 256;
                (16 + 36 * r + 6 * g + b) as i16
            }
        }
        Color::Rgb(r, g, b) => {
            let r = if r > 127 { 1 } else { 0 };
            let g = if g > 127 { 1 } else { 0 };
            let b = if b > 127 { 1 } else { 0 };
            (r + 2 * g + 4 * b) as i16
        }
        _ => -1, // -1 represents default color
    }
}