Lines
100 %
Functions
Branches
//! SGR mouse reports (`ESC [ < Cb ; Cx ; Cy M` press, `... m` release) as
//! crossterm mouse events.
use crate::key_decoder::Decoded;
use ratatui::crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use std::time::Instant;
use tui::transport::RawEvent;
/// Longest parameter run accepted before the report is dropped as garbage.
const MAX_PARAMS: usize = 32;
const MOTION: u16 = 32;
const WHEEL: u16 = 64;
const EXTRA_BUTTONS: u16 = 128;
/// Decodes the report that `input` starts: `ESC [ <` and then its parameters.
pub(crate) fn decode(input: &[u8]) -> Decoded {
let body = input.get(3..).unwrap_or_default();
let stop = body
.iter()
.enumerate()
.find(|(_, b)| !(b.is_ascii_digit() || **b == b';'));
match stop {
None if body.len() >= MAX_PARAMS => Decoded::Skip(input.len()),
None => Decoded::Incomplete,
Some((end, b'M')) => report(&body[..end], true, end + 4),
Some((end, b'm')) => report(&body[..end], false, end + 4),
// The byte that broke the report starts whatever follows it.
Some((end, _)) => Decoded::Skip(end + 3),
}
fn report(params: &[u8], press: bool, consumed: usize) -> Decoded {
match fields(params).and_then(|(cb, x, y)| event(cb, x, y, press)) {
Some(mouse) => Decoded::Event(RawEvent::Mouse(mouse, Instant::now()), consumed),
None => Decoded::Skip(consumed),
fn fields(params: &[u8]) -> Option<(u16, u16, u16)> {
let text = std::str::from_utf8(params).ok()?;
let mut parts = text.split(';').map(|part| part.parse::<u16>().ok());
let fields = (parts.next()??, parts.next()??, parts.next()??);
parts.next().is_none().then_some(fields)
/// Coordinates arrive 1-based.
fn event(cb: u16, x: u16, y: u16, press: bool) -> Option<MouseEvent> {
Some(MouseEvent {
kind: kind(cb, press)?,
column: x.checked_sub(1)?,
row: y.checked_sub(1)?,
modifiers: modifiers(cb),
})
fn modifiers(cb: u16) -> KeyModifiers {
[
(4, KeyModifiers::SHIFT),
(8, KeyModifiers::ALT),
(16, KeyModifiers::CONTROL),
]
.into_iter()
.filter(|(bit, _)| cb & bit != 0)
.fold(KeyModifiers::NONE, |all, (_, modifier)| all | modifier)
fn kind(cb: u16, press: bool) -> Option<MouseEventKind> {
if cb & EXTRA_BUTTONS != 0 {
return None;
let low = cb & 0b11;
if cb & MOTION != 0 {
return match press && cb & WHEEL == 0 {
true => button(low).map(MouseEventKind::Drag),
false => None,
};
if cb & WHEEL != 0 {
return match (press, low) {
(true, 0) => Some(MouseEventKind::ScrollUp),
(true, 1) => Some(MouseEventKind::ScrollDown),
_ => None,
let button = button(low)?;
Some(if press {
MouseEventKind::Down(button)
} else {
MouseEventKind::Up(button)
/// The button bits of a report; 3 is "no button".
fn button(low: u16) -> Option<MouseButton> {
match low {
0 => Some(MouseButton::Left),
1 => Some(MouseButton::Middle),
2 => Some(MouseButton::Right),