1
//! SGR mouse reports (`ESC [ < Cb ; Cx ; Cy M` press, `... m` release) as
2
//! crossterm mouse events.
3

            
4
use crate::key_decoder::Decoded;
5
use ratatui::crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
6
use std::time::Instant;
7
use tui::transport::RawEvent;
8

            
9
/// Longest parameter run accepted before the report is dropped as garbage.
10
const MAX_PARAMS: usize = 32;
11

            
12
const MOTION: u16 = 32;
13
const WHEEL: u16 = 64;
14
const EXTRA_BUTTONS: u16 = 128;
15

            
16
/// Decodes the report that `input` starts: `ESC [ <` and then its parameters.
17
76
pub(crate) fn decode(input: &[u8]) -> Decoded {
18
76
    let body = input.get(3..).unwrap_or_default();
19
76
    let stop = body
20
76
        .iter()
21
76
        .enumerate()
22
546
        .find(|(_, b)| !(b.is_ascii_digit() || **b == b';'));
23
76
    match stop {
24
12
        None if body.len() >= MAX_PARAMS => Decoded::Skip(input.len()),
25
11
        None => Decoded::Incomplete,
26
52
        Some((end, b'M')) => report(&body[..end], true, end + 4),
27
10
        Some((end, b'm')) => report(&body[..end], false, end + 4),
28
        // The byte that broke the report starts whatever follows it.
29
2
        Some((end, _)) => Decoded::Skip(end + 3),
30
    }
31
76
}
32

            
33
62
fn report(params: &[u8], press: bool, consumed: usize) -> Decoded {
34
62
    match fields(params).and_then(|(cb, x, y)| event(cb, x, y, press)) {
35
47
        Some(mouse) => Decoded::Event(RawEvent::Mouse(mouse, Instant::now()), consumed),
36
15
        None => Decoded::Skip(consumed),
37
    }
38
62
}
39

            
40
62
fn fields(params: &[u8]) -> Option<(u16, u16, u16)> {
41
62
    let text = std::str::from_utf8(params).ok()?;
42
182
    let mut parts = text.split(';').map(|part| part.parse::<u16>().ok());
43
62
    let fields = (parts.next()??, parts.next()??, parts.next()??);
44
59
    parts.next().is_none().then_some(fields)
45
62
}
46

            
47
/// Coordinates arrive 1-based.
48
58
fn event(cb: u16, x: u16, y: u16, press: bool) -> Option<MouseEvent> {
49
    Some(MouseEvent {
50
58
        kind: kind(cb, press)?,
51
49
        column: x.checked_sub(1)?,
52
48
        row: y.checked_sub(1)?,
53
47
        modifiers: modifiers(cb),
54
    })
55
58
}
56

            
57
47
fn modifiers(cb: u16) -> KeyModifiers {
58
47
    [
59
47
        (4, KeyModifiers::SHIFT),
60
47
        (8, KeyModifiers::ALT),
61
47
        (16, KeyModifiers::CONTROL),
62
47
    ]
63
47
    .into_iter()
64
141
    .filter(|(bit, _)| cb & bit != 0)
65
47
    .fold(KeyModifiers::NONE, |all, (_, modifier)| all | modifier)
66
47
}
67

            
68
58
fn kind(cb: u16, press: bool) -> Option<MouseEventKind> {
69
58
    if cb & EXTRA_BUTTONS != 0 {
70
1
        return None;
71
57
    }
72
57
    let low = cb & 0b11;
73
57
    if cb & MOTION != 0 {
74
9
        return match press && cb & WHEEL == 0 {
75
6
            true => button(low).map(MouseEventKind::Drag),
76
3
            false => None,
77
        };
78
48
    }
79
48
    if cb & WHEEL != 0 {
80
25
        return match (press, low) {
81
5
            (true, 0) => Some(MouseEventKind::ScrollUp),
82
17
            (true, 1) => Some(MouseEventKind::ScrollDown),
83
3
            _ => None,
84
        };
85
23
    }
86
23
    let button = button(low)?;
87
22
    Some(if press {
88
15
        MouseEventKind::Down(button)
89
    } else {
90
7
        MouseEventKind::Up(button)
91
    })
92
58
}
93

            
94
/// The button bits of a report; 3 is "no button".
95
29
fn button(low: u16) -> Option<MouseButton> {
96
29
    match low {
97
23
        0 => Some(MouseButton::Left),
98
2
        1 => Some(MouseButton::Middle),
99
2
        2 => Some(MouseButton::Right),
100
2
        _ => None,
101
    }
102
29
}