refactor: split terminalstate into modules
Long overdue! Move the various image protocols into their own files, and the performer too!
This commit is contained in:
1 parent
29aaa075d6
commit
0f5494db98
10 files changed
+4621
-4553
No files matched your search
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::terminalstate::performer::Performer;
|
||||
use std::sync::Arc;
|
||||
use termwiz::escape::parser::Parser;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,181 @@
|
||||
use crate::{Position, StableRowIndex, TerminalState};
|
||||
use ordered_float::NotNan;
|
||||
use std::sync::Arc;
|
||||
use termwiz::cell::{Cell, CellAttributes};
|
||||
use termwiz::image::{ImageCell, ImageDataType};
|
||||
use termwiz::surface::change::ImageData;
|
||||
use termwiz::surface::TextureCoordinate;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct PlacementInfo {
|
||||
pub first_row: StableRowIndex,
|
||||
pub rows: usize,
|
||||
pub cols: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ImageAttachParams {
|
||||
/// Dimensions of the underlying ImageData, in pixels
|
||||
pub image_width: u32,
|
||||
pub image_height: u32,
|
||||
|
||||
/// Dimensions of the area of the image to be displayed, in pixels
|
||||
pub source_width: u32,
|
||||
pub source_height: u32,
|
||||
|
||||
/// Origin of the source data region, top left corner in pixels
|
||||
pub source_origin_x: u32,
|
||||
pub source_origin_y: u32,
|
||||
|
||||
/// When rendering in the cell, use this offset from the top left
|
||||
/// of the cell
|
||||
pub display_offset_x: u32,
|
||||
pub display_offset_y: u32,
|
||||
|
||||
/// Plane on which to display the image
|
||||
pub z_index: i32,
|
||||
|
||||
/// Desired number of cells to span.
|
||||
/// If None, then compute based on source_width and source_height
|
||||
pub columns: Option<usize>,
|
||||
pub rows: Option<usize>,
|
||||
|
||||
pub image_id: u32,
|
||||
pub placement_id: Option<u32>,
|
||||
|
||||
pub style: ImageAttachStyle,
|
||||
|
||||
pub data: Arc<ImageData>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ImageAttachStyle {
|
||||
Sixel,
|
||||
Iterm,
|
||||
Kitty,
|
||||
}
|
||||
|
||||
impl TerminalState {
|
||||
pub(crate) fn assign_image_to_cells(&mut self, params: ImageAttachParams) -> PlacementInfo {
|
||||
let physical_cols = self.screen().physical_cols;
|
||||
let physical_rows = self.screen().physical_rows;
|
||||
let cell_pixel_width = self.pixel_width / physical_cols;
|
||||
let cell_pixel_height = self.pixel_height / physical_rows;
|
||||
|
||||
let avail_width = params.image_width.saturating_sub(params.source_origin_x);
|
||||
let avail_height = params.image_height.saturating_sub(params.source_origin_y);
|
||||
let source_width = params.source_width.min(params.image_width).min(avail_width);
|
||||
let source_height = params
|
||||
.source_height
|
||||
.min(params.image_height)
|
||||
.min(avail_height);
|
||||
|
||||
let width_in_cells = params
|
||||
.columns
|
||||
.unwrap_or_else(|| (source_width as f32 / cell_pixel_width as f32).ceil() as usize);
|
||||
let height_in_cells = params
|
||||
.rows
|
||||
.unwrap_or_else(|| (source_height as f32 / cell_pixel_height as f32).ceil() as usize);
|
||||
|
||||
let first_row = self.screen().visible_row_to_stable_row(self.cursor.y);
|
||||
|
||||
let mut ypos =
|
||||
NotNan::new(params.source_origin_y as f32 / params.image_height as f32).unwrap();
|
||||
let start_xpos =
|
||||
NotNan::new(params.source_origin_x as f32 / params.image_width as f32).unwrap();
|
||||
|
||||
let cursor_x = self.cursor.x;
|
||||
let x_delta = (source_width as f32 / params.image_width as f32) / width_in_cells as f32;
|
||||
let y_delta = (source_height as f32 / params.image_height as f32) / height_in_cells as f32;
|
||||
log::debug!(
|
||||
"image is {}x{} cells, {:?}, x_delta:{} y_delta:{} ({}x{}@{}x{})",
|
||||
width_in_cells,
|
||||
height_in_cells,
|
||||
params,
|
||||
x_delta,
|
||||
y_delta,
|
||||
physical_cols,
|
||||
physical_rows,
|
||||
self.pixel_width,
|
||||
self.pixel_height
|
||||
);
|
||||
for _ in 0..height_in_cells {
|
||||
let mut xpos = start_xpos;
|
||||
let cursor_y = self.cursor.y;
|
||||
log::debug!(
|
||||
"setting cells for y={} x=[{}..{}]",
|
||||
cursor_y,
|
||||
cursor_x,
|
||||
cursor_x + width_in_cells
|
||||
);
|
||||
for x in 0..width_in_cells {
|
||||
let mut cell = self
|
||||
.screen()
|
||||
.get_cell(cursor_x + x, cursor_y)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Cell::new(' ', CellAttributes::default()));
|
||||
let img = Box::new(ImageCell::with_z_index(
|
||||
TextureCoordinate::new(xpos, ypos),
|
||||
TextureCoordinate::new(xpos + x_delta, ypos + y_delta),
|
||||
params.data.clone(),
|
||||
params.z_index,
|
||||
params.display_offset_x,
|
||||
params.display_offset_y,
|
||||
params.image_id,
|
||||
params.placement_id,
|
||||
));
|
||||
match params.style {
|
||||
ImageAttachStyle::Kitty => cell.attrs_mut().attach_image(img),
|
||||
ImageAttachStyle::Sixel | ImageAttachStyle::Iterm => {
|
||||
cell.attrs_mut().set_image(img)
|
||||
}
|
||||
};
|
||||
|
||||
self.screen_mut().set_cell(cursor_x + x, cursor_y, &cell);
|
||||
xpos += x_delta;
|
||||
}
|
||||
ypos += y_delta;
|
||||
self.new_line(false);
|
||||
}
|
||||
|
||||
// Sixel places the cursor under the left corner of the image,
|
||||
// unless sixel_scrolls_right is enabled.
|
||||
// iTerm places it after the bottom right corner.
|
||||
let bottom_right = match params.style {
|
||||
ImageAttachStyle::Kitty | ImageAttachStyle::Iterm => true,
|
||||
ImageAttachStyle::Sixel => self.sixel_scrolls_right,
|
||||
};
|
||||
|
||||
if bottom_right {
|
||||
self.set_cursor_pos(
|
||||
&Position::Relative(width_in_cells as i64),
|
||||
&Position::Relative(-1),
|
||||
);
|
||||
}
|
||||
|
||||
PlacementInfo {
|
||||
first_row,
|
||||
rows: height_in_cells,
|
||||
cols: width_in_cells,
|
||||
}
|
||||
}
|
||||
|
||||
/// cache recent images and avoid assigning a new id for repeated data!
|
||||
pub(crate) fn raw_image_to_image_data(&mut self, data: ImageDataType) -> Arc<ImageData> {
|
||||
use sha2::Digest;
|
||||
let mut hasher = sha2::Sha256::new();
|
||||
match &data {
|
||||
ImageDataType::EncodedFile(data) => hasher.update(data),
|
||||
ImageDataType::Rgba8 { data, .. } => hasher.update(data),
|
||||
};
|
||||
let key = hasher.finalize().into();
|
||||
|
||||
if let Some(item) = self.image_cache.get(&key) {
|
||||
Arc::clone(item)
|
||||
} else {
|
||||
let image_data = Arc::new(ImageData::with_data(data));
|
||||
self.image_cache.put(key, Arc::clone(&image_data));
|
||||
image_data
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use crate::terminalstate::image::*;
|
||||
use crate::TerminalState;
|
||||
use ::image::imageops::FilterType;
|
||||
use ::image::ImageFormat;
|
||||
use log::error;
|
||||
use termwiz::escape::osc::ITermFileData;
|
||||
use termwiz::image::ImageDataType;
|
||||
|
||||
impl TerminalState {
|
||||
pub(crate) fn set_image(&mut self, image: ITermFileData) {
|
||||
if !image.inline {
|
||||
error!(
|
||||
"Ignoring file download request name={:?} size={}",
|
||||
image.name,
|
||||
image.data.len()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
struct Info {
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: ImageFormat,
|
||||
}
|
||||
|
||||
fn dimensions(data: &[u8]) -> anyhow::Result<Info> {
|
||||
let reader =
|
||||
image::io::Reader::new(std::io::Cursor::new(data)).with_guessed_format()?;
|
||||
let format = reader
|
||||
.format()
|
||||
.ok_or_else(|| anyhow::anyhow!("unknown format!?"))?;
|
||||
let (width, height) = reader.into_dimensions()?;
|
||||
Ok(Info {
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
})
|
||||
}
|
||||
|
||||
let info = match dimensions(&image.data) {
|
||||
Ok(dims) => dims,
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Unable to decode image: {}: size={} {:?}",
|
||||
e,
|
||||
image.data.len(),
|
||||
image
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Figure out the dimensions.
|
||||
let physical_cols = self.screen().physical_cols;
|
||||
let physical_rows = self.screen().physical_rows;
|
||||
let cell_pixel_width = self.pixel_width / physical_cols;
|
||||
let cell_pixel_height = self.pixel_height / physical_rows;
|
||||
|
||||
let width = image.width.to_pixels(cell_pixel_width, physical_cols);
|
||||
let height = image.height.to_pixels(cell_pixel_height, physical_rows);
|
||||
|
||||
// Compute any Automatic dimensions
|
||||
let aspect = info.width as f32 / info.height as f32;
|
||||
|
||||
let (width, height) = match (width, height) {
|
||||
(None, None) => {
|
||||
// Take the image's native size
|
||||
let width = info.width as usize;
|
||||
let height = info.height as usize;
|
||||
// but ensure that it fits
|
||||
if width as usize > self.pixel_width || height as usize > self.pixel_height {
|
||||
let width = width as f32;
|
||||
let height = height as f32;
|
||||
let mut candidates = vec![];
|
||||
|
||||
let x_scale = self.pixel_width as f32 / width;
|
||||
if height * x_scale <= self.pixel_height as f32 {
|
||||
candidates.push((self.pixel_width, (height * x_scale) as usize));
|
||||
}
|
||||
let y_scale = self.pixel_height as f32 / height;
|
||||
if width * y_scale <= self.pixel_width as f32 {
|
||||
candidates.push(((width * y_scale) as usize, self.pixel_height));
|
||||
}
|
||||
|
||||
candidates.sort_by(|a, b| (a.0 * a.1).cmp(&(b.0 * b.1)));
|
||||
|
||||
candidates.pop().unwrap()
|
||||
} else {
|
||||
(width, height)
|
||||
}
|
||||
}
|
||||
(Some(w), None) => {
|
||||
let h = w as f32 / aspect;
|
||||
(w, h as usize)
|
||||
}
|
||||
(None, Some(h)) => {
|
||||
let w = h as f32 * aspect;
|
||||
(w as usize, h)
|
||||
}
|
||||
(Some(w), Some(_)) if image.preserve_aspect_ratio => {
|
||||
let h = w as f32 / aspect;
|
||||
(w, h as usize)
|
||||
}
|
||||
(Some(w), Some(h)) => (w, h),
|
||||
};
|
||||
|
||||
let downscaled = (width < info.width as usize) || (height < info.height as usize);
|
||||
let data = match (downscaled, info.format) {
|
||||
(true, ImageFormat::Gif) | (true, ImageFormat::Png) | (false, _) => {
|
||||
// Don't resample things that might be animations,
|
||||
// or things that don't need resampling
|
||||
ImageDataType::EncodedFile(image.data)
|
||||
}
|
||||
(true, _) => match ::image::load_from_memory(&image.data) {
|
||||
Ok(im) => {
|
||||
let im = im.resize_exact(width as u32, height as u32, FilterType::CatmullRom);
|
||||
let data = im.into_rgba8().into_vec().into_boxed_slice();
|
||||
ImageDataType::Rgba8 {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
data,
|
||||
}
|
||||
}
|
||||
Err(_) => ImageDataType::EncodedFile(image.data),
|
||||
},
|
||||
};
|
||||
|
||||
let image_data = self.raw_image_to_image_data(data);
|
||||
self.assign_image_to_cells(ImageAttachParams {
|
||||
image_width: width as u32,
|
||||
image_height: height as u32,
|
||||
source_width: width as u32,
|
||||
source_height: height as u32,
|
||||
source_origin_x: 0,
|
||||
source_origin_y: 0,
|
||||
display_offset_x: 0,
|
||||
display_offset_y: 0,
|
||||
z_index: 0,
|
||||
columns: None,
|
||||
rows: None,
|
||||
data: image_data,
|
||||
style: ImageAttachStyle::Iterm,
|
||||
image_id: 0,
|
||||
placement_id: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
use crate::input::*;
|
||||
use crate::TerminalState;
|
||||
use crate::{CSI, SS3};
|
||||
use anyhow::bail;
|
||||
use std::fmt::Write;
|
||||
|
||||
fn encode_modifiers(mods: KeyModifiers) -> u8 {
|
||||
let mut number = 0;
|
||||
if mods.contains(KeyModifiers::SHIFT) {
|
||||
number |= 1;
|
||||
}
|
||||
if mods.contains(KeyModifiers::ALT) {
|
||||
number |= 2;
|
||||
}
|
||||
if mods.contains(KeyModifiers::CTRL) {
|
||||
number |= 4;
|
||||
}
|
||||
number
|
||||
}
|
||||
|
||||
/// characters that when masked for CTRL could be an ascii control character
|
||||
/// or could be a key that a user legitimately wants to process in their
|
||||
/// terminal application
|
||||
fn is_ambiguous_ascii_ctrl(c: char) -> bool {
|
||||
match c {
|
||||
'i' | 'I' | 'm' | 'M' | '[' | '{' | '@' => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Map c to its Ctrl equivalent.
|
||||
/// In theory, this mapping is simply translating alpha characters
|
||||
/// to upper case and then masking them by 0x1f, but xterm inherits
|
||||
/// some built-in translation from legacy X11 so that are some
|
||||
/// aliased mappings and a couple that might be technically tied
|
||||
/// to US keyboard layout (particularly the punctuation characters
|
||||
/// produced in combination with SHIFT) that may not be 100%
|
||||
/// the right thing to do here for users with non-US layouts.
|
||||
fn ctrl_mapping(c: char) -> Option<char> {
|
||||
Some(match c {
|
||||
'@' | '`' | ' ' | '2' => '\x00',
|
||||
'A' | 'a' => '\x01',
|
||||
'B' | 'b' => '\x02',
|
||||
'C' | 'c' => '\x03',
|
||||
'D' | 'd' => '\x04',
|
||||
'E' | 'e' => '\x05',
|
||||
'F' | 'f' => '\x06',
|
||||
'G' | 'g' => '\x07',
|
||||
'H' | 'h' => '\x08',
|
||||
'I' | 'i' => '\x09',
|
||||
'J' | 'j' => '\x0a',
|
||||
'K' | 'k' => '\x0b',
|
||||
'L' | 'l' => '\x0c',
|
||||
'M' | 'm' => '\x0d',
|
||||
'N' | 'n' => '\x0e',
|
||||
'O' | 'o' => '\x0f',
|
||||
'P' | 'p' => '\x10',
|
||||
'Q' | 'q' => '\x11',
|
||||
'R' | 'r' => '\x12',
|
||||
'S' | 's' => '\x13',
|
||||
'T' | 't' => '\x14',
|
||||
'U' | 'u' => '\x15',
|
||||
'V' | 'v' => '\x16',
|
||||
'W' | 'w' => '\x17',
|
||||
'X' | 'x' => '\x18',
|
||||
'Y' | 'y' => '\x19',
|
||||
'Z' | 'z' => '\x1a',
|
||||
'[' | '3' | '{' => '\x1b',
|
||||
'\\' | '4' | '|' => '\x1c',
|
||||
']' | '5' | '}' => '\x1d',
|
||||
'^' | '6' | '~' => '\x1e',
|
||||
'_' | '7' | '/' => '\x1f',
|
||||
'8' | '?' => '\x7f', // `Delete`
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl TerminalState {
|
||||
fn csi_u_encode(&self, buf: &mut String, c: char, mods: KeyModifiers) -> anyhow::Result<()> {
|
||||
if self.config.enable_csi_u_key_encoding() {
|
||||
write!(buf, "\x1b[{};{}u", c as u32, 1 + encode_modifiers(mods))?;
|
||||
} else {
|
||||
let c = if mods.contains(KeyModifiers::CTRL) && ctrl_mapping(c).is_some() {
|
||||
ctrl_mapping(c).unwrap()
|
||||
} else {
|
||||
c
|
||||
};
|
||||
if mods.contains(KeyModifiers::ALT) {
|
||||
buf.push(0x1b as char);
|
||||
}
|
||||
write!(buf, "{}", c)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Processes a key_down event generated by the gui/render layer
|
||||
/// that is embedding the Terminal. This method translates the
|
||||
/// keycode into a sequence of bytes to send to the slave end
|
||||
/// of the pty via the `Write`-able object provided by the caller.
|
||||
#[allow(clippy::cognitive_complexity)]
|
||||
pub fn key_down(&mut self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()> {
|
||||
use crate::KeyCode::*;
|
||||
|
||||
let key = key.normalize_shift_to_upper_case(mods);
|
||||
// Normalize the modifier state for Char's that are uppercase; remove
|
||||
// the SHIFT modifier so that reduce ambiguity below
|
||||
let mods = match key {
|
||||
Char(c)
|
||||
if (c.is_ascii_punctuation() || c.is_ascii_uppercase())
|
||||
&& mods.contains(KeyModifiers::SHIFT) =>
|
||||
{
|
||||
mods & !KeyModifiers::SHIFT
|
||||
}
|
||||
_ => mods,
|
||||
};
|
||||
|
||||
// Normalize Backspace and Delete
|
||||
let key = match key {
|
||||
Char('\x7f') => Delete,
|
||||
Char('\x08') => Backspace,
|
||||
c => c,
|
||||
};
|
||||
|
||||
let mut buf = String::new();
|
||||
|
||||
// TODO: also respect self.application_keypad
|
||||
|
||||
let to_send = match key {
|
||||
Char(c)
|
||||
if is_ambiguous_ascii_ctrl(c)
|
||||
&& mods.contains(KeyModifiers::CTRL)
|
||||
&& self.config.enable_csi_u_key_encoding() =>
|
||||
{
|
||||
self.csi_u_encode(&mut buf, c, mods)?;
|
||||
buf.as_str()
|
||||
}
|
||||
Char(c) if c.is_ascii_uppercase() && mods.contains(KeyModifiers::CTRL) => {
|
||||
self.csi_u_encode(&mut buf, c, mods)?;
|
||||
buf.as_str()
|
||||
}
|
||||
|
||||
Char(c) if mods.contains(KeyModifiers::CTRL) && ctrl_mapping(c).is_some() => {
|
||||
let c = ctrl_mapping(c).unwrap();
|
||||
if mods.contains(KeyModifiers::ALT) {
|
||||
buf.push(0x1b as char);
|
||||
}
|
||||
buf.push(c);
|
||||
buf.as_str()
|
||||
}
|
||||
|
||||
// When alt is pressed, send escape first to indicate to the peer that
|
||||
// ALT is pressed. We do this only for ascii alnum characters because
|
||||
// eg: on macOS generates altgr style glyphs and keeps the ALT key
|
||||
// in the modifier set. This confuses eg: zsh which then just displays
|
||||
// <fffffffff> as the input, so we want to avoid that.
|
||||
Char(c)
|
||||
if (c.is_ascii_alphanumeric() || c.is_ascii_punctuation())
|
||||
&& mods.contains(KeyModifiers::ALT) =>
|
||||
{
|
||||
buf.push(0x1b as char);
|
||||
buf.push(c);
|
||||
buf.as_str()
|
||||
}
|
||||
|
||||
Enter | Escape | Backspace => {
|
||||
let c = match key {
|
||||
Enter => '\r',
|
||||
Escape => '\x1b',
|
||||
// Backspace sends the default VERASE which is confusingly
|
||||
// the DEL ascii codepoint
|
||||
Backspace => '\x7f',
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if mods.contains(KeyModifiers::SHIFT) || mods.contains(KeyModifiers::CTRL) {
|
||||
self.csi_u_encode(&mut buf, c, mods)?;
|
||||
} else {
|
||||
if mods.contains(KeyModifiers::ALT) {
|
||||
buf.push(0x1b as char);
|
||||
}
|
||||
buf.push(c);
|
||||
if self.newline_mode && key == Enter {
|
||||
buf.push(0x0a as char);
|
||||
}
|
||||
}
|
||||
buf.as_str()
|
||||
}
|
||||
|
||||
Tab => {
|
||||
if mods.contains(KeyModifiers::ALT) {
|
||||
buf.push(0x1b as char);
|
||||
}
|
||||
let mods = mods & !KeyModifiers::ALT;
|
||||
if mods == KeyModifiers::CTRL {
|
||||
buf.push_str("\x1b[9;5u");
|
||||
} else if mods == KeyModifiers::CTRL | KeyModifiers::SHIFT {
|
||||
buf.push_str("\x1b[1;5Z");
|
||||
} else if mods == KeyModifiers::SHIFT {
|
||||
buf.push_str("\x1b[Z");
|
||||
} else {
|
||||
buf.push('\t');
|
||||
}
|
||||
buf.as_str()
|
||||
}
|
||||
|
||||
Char(c) => {
|
||||
if mods.is_empty() {
|
||||
buf.push(c);
|
||||
} else {
|
||||
self.csi_u_encode(&mut buf, c, mods)?;
|
||||
}
|
||||
buf.as_str()
|
||||
}
|
||||
|
||||
Home
|
||||
| End
|
||||
| UpArrow
|
||||
| DownArrow
|
||||
| RightArrow
|
||||
| LeftArrow
|
||||
| ApplicationUpArrow
|
||||
| ApplicationDownArrow
|
||||
| ApplicationRightArrow
|
||||
| ApplicationLeftArrow => {
|
||||
let (force_app, c) = match key {
|
||||
UpArrow => (false, 'A'),
|
||||
DownArrow => (false, 'B'),
|
||||
RightArrow => (false, 'C'),
|
||||
LeftArrow => (false, 'D'),
|
||||
Home => (false, 'H'),
|
||||
End => (false, 'F'),
|
||||
ApplicationUpArrow => (true, 'A'),
|
||||
ApplicationDownArrow => (true, 'B'),
|
||||
ApplicationRightArrow => (true, 'C'),
|
||||
ApplicationLeftArrow => (true, 'D'),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let csi_or_ss3 = if force_app
|
||||
|| (
|
||||
self.application_cursor_keys
|
||||
// Strict reading of DECCKM suggests that application_cursor_keys
|
||||
// only applies when DECANM and DECKPAM are active, but that seems
|
||||
// to break unmodified cursor keys in vim
|
||||
/* && self.dec_ansi_mode && self.application_keypad */
|
||||
) {
|
||||
// Use SS3 in application mode
|
||||
SS3
|
||||
} else {
|
||||
// otherwise use regular CSI
|
||||
CSI
|
||||
};
|
||||
|
||||
if mods.contains(KeyModifiers::SHIFT) || mods.contains(KeyModifiers::CTRL) {
|
||||
write!(buf, "{}1;{}{}", CSI, 1 + encode_modifiers(mods), c)?;
|
||||
} else {
|
||||
if mods.contains(KeyModifiers::ALT) {
|
||||
buf.push(0x1b as char);
|
||||
}
|
||||
write!(buf, "{}{}", csi_or_ss3, c)?;
|
||||
}
|
||||
buf.as_str()
|
||||
}
|
||||
|
||||
PageUp | PageDown | Insert | Delete => {
|
||||
let c = match key {
|
||||
Insert => 2,
|
||||
Delete => 3,
|
||||
PageUp => 5,
|
||||
PageDown => 6,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
if mods.contains(KeyModifiers::SHIFT) || mods.contains(KeyModifiers::CTRL) {
|
||||
write!(buf, "\x1b[{};{}~", c, 1 + encode_modifiers(mods))?;
|
||||
} else {
|
||||
if mods.contains(KeyModifiers::ALT) {
|
||||
buf.push(0x1b as char);
|
||||
}
|
||||
write!(buf, "\x1b[{}~", c)?;
|
||||
}
|
||||
buf.as_str()
|
||||
}
|
||||
|
||||
Function(n) => {
|
||||
if mods.is_empty() && n < 5 {
|
||||
// F1-F4 are encoded using SS3 if there are no modifiers
|
||||
match n {
|
||||
1 => "\x1bOP",
|
||||
2 => "\x1bOQ",
|
||||
3 => "\x1bOR",
|
||||
4 => "\x1bOS",
|
||||
_ => unreachable!("wat?"),
|
||||
}
|
||||
} else {
|
||||
// Higher numbered F-keys plus modified F-keys are encoded
|
||||
// using CSI instead of SS3.
|
||||
let intro = match n {
|
||||
1 => "\x1b[11",
|
||||
2 => "\x1b[12",
|
||||
3 => "\x1b[13",
|
||||
4 => "\x1b[14",
|
||||
5 => "\x1b[15",
|
||||
6 => "\x1b[17",
|
||||
7 => "\x1b[18",
|
||||
8 => "\x1b[19",
|
||||
9 => "\x1b[20",
|
||||
10 => "\x1b[21",
|
||||
11 => "\x1b[23",
|
||||
12 => "\x1b[24",
|
||||
_ => bail!("unhandled fkey number {}", n),
|
||||
};
|
||||
let encoded_mods = encode_modifiers(mods);
|
||||
if encoded_mods == 0 {
|
||||
// If no modifiers are held, don't send the modifier
|
||||
// sequence, as the modifier encoding is a CSI-u extension.
|
||||
write!(buf, "{}~", intro)?;
|
||||
} else {
|
||||
write!(buf, "{};{}~", intro, 1 + encoded_mods)?;
|
||||
}
|
||||
buf.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: emit numpad sequences
|
||||
Numpad0 | Numpad1 | Numpad2 | Numpad3 | Numpad4 | Numpad5 | Numpad6 | Numpad7
|
||||
| Numpad8 | Numpad9 | Multiply | Add | Separator | Subtract | Decimal | Divide => "",
|
||||
|
||||
// Modifier keys pressed on their own don't expand to anything
|
||||
Control | LeftControl | RightControl | Alt | LeftAlt | RightAlt | Menu | LeftMenu
|
||||
| RightMenu | Super | Hyper | Shift | LeftShift | RightShift | Meta | LeftWindows
|
||||
| RightWindows | NumLock | ScrollLock => "",
|
||||
|
||||
Cancel | Clear | Pause | CapsLock | Select | Print | PrintScreen | Execute | Help
|
||||
| Applications | Sleep | BrowserBack | BrowserForward | BrowserRefresh
|
||||
| BrowserStop | BrowserSearch | BrowserFavorites | BrowserHome | VolumeMute
|
||||
| VolumeDown | VolumeUp | MediaNextTrack | MediaPrevTrack | MediaStop
|
||||
| MediaPlayPause | InternalPasteStart | InternalPasteEnd => "",
|
||||
};
|
||||
|
||||
// debug!("sending {:?}, {:?}", to_send, key);
|
||||
self.writer.write_all(to_send.as_bytes())?;
|
||||
self.writer.flush()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
use crate::terminalstate::image::*;
|
||||
use crate::terminalstate::{ImageAttachParams, PlacementInfo};
|
||||
use crate::{StableRowIndex, TerminalState};
|
||||
use ::image::{DynamicImage, GenericImageView, RgbImage};
|
||||
use anyhow::Context;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use termwiz::escape::apc::KittyImageData;
|
||||
use termwiz::escape::apc::{
|
||||
KittyImage, KittyImageCompression, KittyImageDelete, KittyImageFormat, KittyImagePlacement,
|
||||
KittyImageTransmit, KittyImageVerbosity,
|
||||
};
|
||||
use termwiz::image::ImageDataType;
|
||||
use termwiz::surface::change::ImageData;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct KittyImageState {
|
||||
accumulator: Vec<KittyImage>,
|
||||
max_image_id: u32,
|
||||
number_to_id: HashMap<u32, u32>,
|
||||
id_to_data: HashMap<u32, Arc<ImageData>>,
|
||||
placements: HashMap<(u32, Option<u32>), PlacementInfo>,
|
||||
used_memory: usize,
|
||||
}
|
||||
|
||||
impl KittyImageState {
|
||||
fn remove_data_for_id(&mut self, image_id: u32) {
|
||||
if let Some(data) = self.id_to_data.remove(&image_id) {
|
||||
self.used_memory = self.used_memory.saturating_sub(data.len());
|
||||
}
|
||||
}
|
||||
|
||||
fn record_id_to_data(&mut self, image_id: u32, data: Arc<ImageData>) {
|
||||
self.remove_data_for_id(image_id);
|
||||
self.prune_unreferenced();
|
||||
self.used_memory += data.len();
|
||||
self.id_to_data.insert(image_id, data);
|
||||
}
|
||||
|
||||
fn prune_unreferenced(&mut self) {
|
||||
let budget = 320 * 1024 * 1024; // FIXME: make this configurable
|
||||
if self.used_memory > budget {
|
||||
let referenced: HashSet<u32> = self.placements.keys().map(|(k, _)| *k).collect();
|
||||
let target = self.used_memory - budget;
|
||||
let mut freed = 0;
|
||||
self.id_to_data.retain(|id, data| {
|
||||
if referenced.contains(id) || freed > target {
|
||||
true
|
||||
} else {
|
||||
freed += data.len();
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
log::info!(
|
||||
"using {} RAM for images, pruned {}",
|
||||
self.used_memory,
|
||||
freed
|
||||
);
|
||||
self.used_memory = self.used_memory.saturating_sub(freed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TerminalState {
|
||||
fn kitty_img_place(
|
||||
&mut self,
|
||||
image_id: Option<u32>,
|
||||
image_number: Option<u32>,
|
||||
placement: KittyImagePlacement,
|
||||
verbosity: KittyImageVerbosity,
|
||||
) -> anyhow::Result<()> {
|
||||
let image_id = match image_id {
|
||||
Some(id) => id,
|
||||
None => *self
|
||||
.kitty_img
|
||||
.number_to_id
|
||||
.get(
|
||||
&image_number
|
||||
.ok_or_else(|| anyhow::anyhow!("no image_id or image_number specified!"))?,
|
||||
)
|
||||
.ok_or_else(|| anyhow::anyhow!("image_number has no matching image id"))?,
|
||||
};
|
||||
|
||||
log::trace!(
|
||||
"kitty_img_place image_id {:?} image_no {:?} placement {:?} verb {:?}",
|
||||
image_id,
|
||||
image_number,
|
||||
placement,
|
||||
verbosity
|
||||
);
|
||||
self.kitty_remove_placement(image_id, placement.placement_id);
|
||||
let img = Arc::clone(
|
||||
self.kitty_img
|
||||
.id_to_data
|
||||
.get(&image_id)
|
||||
.ok_or_else(|| anyhow::anyhow!("no matching image id"))?,
|
||||
);
|
||||
|
||||
let (image_width, image_height) = match img.data() {
|
||||
ImageDataType::EncodedFile(data) => {
|
||||
let decoded = ::image::load_from_memory(data).context("decode png")?;
|
||||
decoded.dimensions()
|
||||
}
|
||||
ImageDataType::Rgba8 { width, height, .. } => (*width, *height),
|
||||
};
|
||||
|
||||
let saved_cursor = self.cursor.clone();
|
||||
|
||||
let info = self.assign_image_to_cells(ImageAttachParams {
|
||||
image_width,
|
||||
image_height,
|
||||
source_width: placement.w.unwrap_or(image_width),
|
||||
source_height: placement.h.unwrap_or(image_height),
|
||||
source_origin_x: placement.x.unwrap_or(0),
|
||||
source_origin_y: placement.y.unwrap_or(0),
|
||||
display_offset_x: placement.x_offset.unwrap_or(0),
|
||||
display_offset_y: placement.y_offset.unwrap_or(0),
|
||||
data: img,
|
||||
style: ImageAttachStyle::Kitty,
|
||||
z_index: placement.z_index.unwrap_or(0),
|
||||
columns: placement.columns.map(|x| x as usize),
|
||||
rows: placement.rows.map(|x| x as usize),
|
||||
image_id,
|
||||
placement_id: placement.placement_id,
|
||||
});
|
||||
|
||||
self.kitty_img
|
||||
.placements
|
||||
.insert((image_id, placement.placement_id), info);
|
||||
log::trace!(
|
||||
"record placement for {} {:?}",
|
||||
image_id,
|
||||
placement.placement_id
|
||||
);
|
||||
|
||||
if placement.do_not_move_cursor {
|
||||
self.cursor = saved_cursor;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kitty_img_inner(&mut self, img: KittyImage) -> anyhow::Result<()> {
|
||||
match self
|
||||
.coalesce_kitty_accumulation(img)
|
||||
.context("coalesce_kitty_accumulation")?
|
||||
{
|
||||
KittyImage::TransmitData {
|
||||
transmit,
|
||||
verbosity,
|
||||
} => {
|
||||
self.kitty_img_transmit(transmit, verbosity)?;
|
||||
Ok(())
|
||||
}
|
||||
KittyImage::TransmitDataAndDisplay {
|
||||
transmit,
|
||||
placement,
|
||||
verbosity,
|
||||
} => {
|
||||
log::trace!("TransmitDataAndDisplay {:#?} {:#?}", transmit, placement);
|
||||
let image_number = transmit.image_number;
|
||||
let image_id = self.kitty_img_transmit(transmit, verbosity)?;
|
||||
self.kitty_img_place(Some(image_id), image_number, placement, verbosity)
|
||||
}
|
||||
_ => anyhow::bail!("impossible KittImage variant"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn kitty_img(&mut self, img: KittyImage) -> anyhow::Result<()> {
|
||||
log::trace!("{:?}", img);
|
||||
if !self.config.enable_kitty_graphics() {
|
||||
return Ok(());
|
||||
}
|
||||
match img {
|
||||
KittyImage::Query { transmit } => {
|
||||
let image_id = transmit.image_id.unwrap_or(0);
|
||||
let response = match transmit.data.load_data() {
|
||||
Ok(_) => {
|
||||
format!("\x1b_Gi={};OK\x1b\\", image_id)
|
||||
}
|
||||
Err(err) => {
|
||||
format!("\x1b_Gi={};ERROR:{:#}\x1b\\", image_id, err)
|
||||
}
|
||||
};
|
||||
|
||||
log::trace!("Query Response: {}", response.escape_debug());
|
||||
write!(self.writer, "{}", response).ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
KittyImage::TransmitData {
|
||||
transmit,
|
||||
verbosity,
|
||||
} => {
|
||||
let more_data_follows = transmit.more_data_follows;
|
||||
let img = KittyImage::TransmitData {
|
||||
transmit,
|
||||
verbosity,
|
||||
};
|
||||
if more_data_follows {
|
||||
self.kitty_img.accumulator.push(img);
|
||||
} else {
|
||||
self.kitty_img_inner(img)?;
|
||||
}
|
||||
}
|
||||
KittyImage::TransmitDataAndDisplay {
|
||||
transmit,
|
||||
placement,
|
||||
verbosity,
|
||||
} => {
|
||||
let more_data_follows = transmit.more_data_follows;
|
||||
let img = KittyImage::TransmitDataAndDisplay {
|
||||
transmit,
|
||||
placement,
|
||||
verbosity,
|
||||
};
|
||||
if more_data_follows {
|
||||
self.kitty_img.accumulator.push(img);
|
||||
} else {
|
||||
self.kitty_img_inner(img)?;
|
||||
}
|
||||
}
|
||||
KittyImage::Display {
|
||||
image_id,
|
||||
image_number,
|
||||
placement,
|
||||
verbosity,
|
||||
} => {
|
||||
self.kitty_img_place(image_id, image_number, placement, verbosity)?;
|
||||
}
|
||||
KittyImage::Delete {
|
||||
what:
|
||||
KittyImageDelete::ByImageId {
|
||||
image_id,
|
||||
placement_id,
|
||||
delete,
|
||||
},
|
||||
verbosity,
|
||||
} => {
|
||||
log::trace!(
|
||||
"remove a placement: image_id {} placement_id {:?} delete {} verb {:?}",
|
||||
image_id,
|
||||
placement_id,
|
||||
delete,
|
||||
verbosity
|
||||
);
|
||||
|
||||
self.kitty_remove_placement(image_id, placement_id);
|
||||
|
||||
if delete {
|
||||
self.kitty_img.remove_data_for_id(image_id);
|
||||
}
|
||||
}
|
||||
KittyImage::Delete { what, verbosity } => {
|
||||
log::warn!("unhandled KittyImage::Delete {:?} {:?}", what, verbosity);
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kitty_remove_placement_from_model(
|
||||
&mut self,
|
||||
image_id: u32,
|
||||
placement_id: Option<u32>,
|
||||
info: PlacementInfo,
|
||||
) {
|
||||
let screen = self.screen_mut();
|
||||
let range =
|
||||
screen.stable_range(&(info.first_row..info.first_row + info.rows as StableRowIndex));
|
||||
for idx in range {
|
||||
let line = screen.line_mut(idx);
|
||||
for c in line.cells_mut() {
|
||||
c.attrs_mut()
|
||||
.detach_image_with_placement(image_id, placement_id);
|
||||
}
|
||||
line.set_dirty();
|
||||
}
|
||||
}
|
||||
|
||||
fn kitty_remove_placement(&mut self, image_id: u32, placement_id: Option<u32>) {
|
||||
if placement_id.is_some() {
|
||||
if let Some(info) = self.kitty_img.placements.remove(&(image_id, placement_id)) {
|
||||
log::trace!("removed placement {} {:?}", image_id, placement_id);
|
||||
self.kitty_remove_placement_from_model(image_id, placement_id, info);
|
||||
}
|
||||
} else {
|
||||
let mut to_clear = vec![];
|
||||
for (id, p) in self.kitty_img.placements.keys() {
|
||||
if *id == image_id {
|
||||
to_clear.push(*p);
|
||||
}
|
||||
}
|
||||
for p in to_clear.into_iter() {
|
||||
if let Some(info) = self.kitty_img.placements.remove(&(image_id, p)) {
|
||||
self.kitty_remove_placement_from_model(image_id, p, info);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!(
|
||||
"after remove: there are {} placements, {} images, {} memory",
|
||||
self.kitty_img.placements.len(),
|
||||
self.kitty_img.id_to_data.len(),
|
||||
self.kitty_img.used_memory,
|
||||
);
|
||||
}
|
||||
|
||||
fn kitty_img_transmit(
|
||||
&mut self,
|
||||
transmit: KittyImageTransmit,
|
||||
verbosity: KittyImageVerbosity,
|
||||
) -> anyhow::Result<u32> {
|
||||
let (image_id, image_number) = match (transmit.image_id, transmit.image_number) {
|
||||
(Some(_), Some(_)) => {
|
||||
// TODO: send an EINVAL error back here
|
||||
anyhow::bail!("cannot use both i= and I= in the same request");
|
||||
}
|
||||
(None, None) => {
|
||||
// Assume image id 0
|
||||
(0, None)
|
||||
}
|
||||
(Some(id), None) => (id, None),
|
||||
(None, Some(no)) => {
|
||||
let id = self.kitty_img.max_image_id + 1;
|
||||
self.kitty_img.number_to_id.insert(no, id);
|
||||
(id, Some(no))
|
||||
}
|
||||
};
|
||||
|
||||
self.kitty_img.max_image_id = self.kitty_img.max_image_id.max(image_id);
|
||||
log::trace!("transmit {:?}", transmit);
|
||||
|
||||
let data = transmit
|
||||
.data
|
||||
.load_data()
|
||||
.context("data should have been materialized in coalesce_kitty_accumulation")?;
|
||||
|
||||
let data = match transmit.compression {
|
||||
KittyImageCompression::None => data,
|
||||
KittyImageCompression::Deflate => deflate::deflate_bytes(&data),
|
||||
};
|
||||
|
||||
let img = match transmit.format {
|
||||
None | Some(KittyImageFormat::Rgba) | Some(KittyImageFormat::Rgb) => {
|
||||
let (width, height) = match (transmit.width, transmit.height) {
|
||||
(Some(w), Some(h)) => (w, h),
|
||||
_ => {
|
||||
anyhow::bail!("missing width/height info for kitty img");
|
||||
}
|
||||
};
|
||||
|
||||
let data = match transmit.format {
|
||||
Some(KittyImageFormat::Rgb) => {
|
||||
let img = DynamicImage::ImageRgb8(
|
||||
RgbImage::from_vec(width, height, data)
|
||||
.ok_or_else(|| anyhow::anyhow!("failed to decode image"))?,
|
||||
);
|
||||
let img = img.into_rgba8();
|
||||
img.into_vec().into_boxed_slice()
|
||||
}
|
||||
_ => data.into_boxed_slice(),
|
||||
};
|
||||
|
||||
let image_data = ImageDataType::Rgba8 {
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
};
|
||||
|
||||
self.raw_image_to_image_data(image_data)
|
||||
}
|
||||
Some(KittyImageFormat::Png) => {
|
||||
let decoded = image::load_from_memory(&data).context("decode png")?;
|
||||
let (width, height) = decoded.dimensions();
|
||||
let data = decoded.into_rgba8().into_vec().into_boxed_slice();
|
||||
let image_data = ImageDataType::Rgba8 {
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
};
|
||||
self.raw_image_to_image_data(image_data)
|
||||
}
|
||||
};
|
||||
|
||||
self.kitty_img.record_id_to_data(image_id, img);
|
||||
|
||||
if let Some(no) = image_number {
|
||||
match verbosity {
|
||||
KittyImageVerbosity::Verbose => {
|
||||
write!(self.writer, "\x1b_Gi={},I={};OK\x1b\\", image_id, no).ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(image_id)
|
||||
}
|
||||
|
||||
fn coalesce_kitty_accumulation(&mut self, img: KittyImage) -> anyhow::Result<KittyImage> {
|
||||
log::trace!(
|
||||
"coalesce: accumulator={:#?} img:{:#?}",
|
||||
self.kitty_img.accumulator,
|
||||
img
|
||||
);
|
||||
if self.kitty_img.accumulator.is_empty() {
|
||||
Ok(img)
|
||||
} else {
|
||||
let mut data = vec![];
|
||||
let mut trans;
|
||||
let place;
|
||||
let final_verbosity = img.verbosity();
|
||||
|
||||
self.kitty_img.accumulator.push(img);
|
||||
|
||||
let mut empty_data = KittyImageData::Direct(String::new());
|
||||
match self.kitty_img.accumulator.remove(0) {
|
||||
KittyImage::TransmitData { transmit, .. } => {
|
||||
trans = transmit;
|
||||
place = None;
|
||||
std::mem::swap(&mut empty_data, &mut trans.data);
|
||||
}
|
||||
KittyImage::TransmitDataAndDisplay {
|
||||
transmit,
|
||||
placement,
|
||||
..
|
||||
} => {
|
||||
place = Some(placement);
|
||||
trans = transmit;
|
||||
std::mem::swap(&mut empty_data, &mut trans.data);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
data.push(empty_data);
|
||||
|
||||
for item in self.kitty_img.accumulator.drain(..) {
|
||||
match item {
|
||||
KittyImage::TransmitData { transmit, .. }
|
||||
| KittyImage::TransmitDataAndDisplay { transmit, .. } => {
|
||||
data.push(transmit.data);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
let mut b64_encoded = String::new();
|
||||
for data in data.into_iter() {
|
||||
match data {
|
||||
KittyImageData::Direct(b) => {
|
||||
b64_encoded.push_str(&b);
|
||||
}
|
||||
data => {
|
||||
anyhow::bail!("expected data chunks to be Direct data, found {:#?}", data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trans.data = KittyImageData::Direct(b64_encoded);
|
||||
|
||||
if let Some(placement) = place {
|
||||
Ok(KittyImage::TransmitDataAndDisplay {
|
||||
transmit: trans,
|
||||
placement,
|
||||
verbosity: final_verbosity,
|
||||
})
|
||||
} else {
|
||||
Ok(KittyImage::TransmitData {
|
||||
transmit: trans,
|
||||
verbosity: final_verbosity,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,221 @@
|
||||
use crate::input::*;
|
||||
use crate::TerminalState;
|
||||
use anyhow::bail;
|
||||
|
||||
impl TerminalState {
|
||||
/// Encode a coordinate value using X10 encoding.
|
||||
/// X10 has a theoretical maximum coordinate value of 255-33, but
|
||||
/// because we emit UTF-8 we are effectively capped at the maximum
|
||||
/// single byte character value of 127, with coordinates capping
|
||||
/// out at 127-33.
|
||||
/// This isn't "fixable" in X10 encoding, applications should
|
||||
/// use the superior SGR mouse encoding scheme instead.
|
||||
fn legacy_mouse_coord(position: i64) -> char {
|
||||
position.max(0).saturating_add(1 + 32).min(127) as u8 as char
|
||||
}
|
||||
|
||||
fn mouse_report_button_number(&self, event: &MouseEvent) -> i8 {
|
||||
let button = match event.button {
|
||||
MouseButton::None => self.current_mouse_button,
|
||||
b => b,
|
||||
};
|
||||
let mut code = match button {
|
||||
MouseButton::None => 3,
|
||||
MouseButton::Left => 0,
|
||||
MouseButton::Middle => 1,
|
||||
MouseButton::Right => 2,
|
||||
MouseButton::WheelUp(_) => 64,
|
||||
MouseButton::WheelDown(_) => 65,
|
||||
};
|
||||
|
||||
if event.modifiers.contains(KeyModifiers::SHIFT) {
|
||||
code += 4;
|
||||
}
|
||||
if event.modifiers.contains(KeyModifiers::ALT) {
|
||||
code += 8;
|
||||
}
|
||||
if event.modifiers.contains(KeyModifiers::CTRL) {
|
||||
code += 16;
|
||||
}
|
||||
|
||||
code
|
||||
}
|
||||
|
||||
fn mouse_wheel(&mut self, event: MouseEvent) -> anyhow::Result<()> {
|
||||
let button = self.mouse_report_button_number(&event);
|
||||
|
||||
if self.sgr_mouse
|
||||
&& (self.mouse_tracking || self.button_event_mouse || self.any_event_mouse)
|
||||
{
|
||||
write!(
|
||||
self.writer,
|
||||
"\x1b[<{};{};{}M",
|
||||
button,
|
||||
event.x + 1,
|
||||
event.y + 1
|
||||
)?;
|
||||
self.writer.flush()?;
|
||||
} else if self.mouse_tracking || self.button_event_mouse || self.any_event_mouse {
|
||||
write!(
|
||||
self.writer,
|
||||
"\x1b[M{}{}{}",
|
||||
(32 + button) as u8 as char,
|
||||
Self::legacy_mouse_coord(event.x as i64),
|
||||
Self::legacy_mouse_coord(event.y),
|
||||
)?;
|
||||
self.writer.flush()?;
|
||||
} else if self.screen.is_alt_screen_active() {
|
||||
// Send cursor keys instead (equivalent to xterm's alternateScroll mode)
|
||||
for _ in 0..self.config.alternate_buffer_wheel_scroll_speed() {
|
||||
self.key_down(
|
||||
match event.button {
|
||||
MouseButton::WheelDown(_) => KeyCode::DownArrow,
|
||||
MouseButton::WheelUp(_) => KeyCode::UpArrow,
|
||||
_ => bail!("unexpected mouse event"),
|
||||
},
|
||||
KeyModifiers::default(),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mouse_button_press(&mut self, event: MouseEvent) -> anyhow::Result<()> {
|
||||
self.current_mouse_button = event.button;
|
||||
|
||||
if !(self.mouse_tracking || self.button_event_mouse || self.any_event_mouse) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let button = self.mouse_report_button_number(&event);
|
||||
if self.sgr_mouse {
|
||||
write!(
|
||||
self.writer,
|
||||
"\x1b[<{};{};{}M",
|
||||
button,
|
||||
event.x + 1,
|
||||
event.y + 1
|
||||
)?;
|
||||
self.writer.flush()?;
|
||||
} else {
|
||||
write!(
|
||||
self.writer,
|
||||
"\x1b[M{}{}{}",
|
||||
(32 + button) as u8 as char,
|
||||
Self::legacy_mouse_coord(event.x as i64),
|
||||
Self::legacy_mouse_coord(event.y),
|
||||
)?;
|
||||
self.writer.flush()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mouse_button_release(&mut self, event: MouseEvent) -> anyhow::Result<()> {
|
||||
if self.current_mouse_button != MouseButton::None
|
||||
&& (self.mouse_tracking || self.button_event_mouse || self.any_event_mouse)
|
||||
{
|
||||
if self.sgr_mouse {
|
||||
let release_button = self.mouse_report_button_number(&event);
|
||||
self.current_mouse_button = MouseButton::None;
|
||||
write!(
|
||||
self.writer,
|
||||
"\x1b[<{};{};{}m",
|
||||
release_button,
|
||||
event.x + 1,
|
||||
event.y + 1
|
||||
)?;
|
||||
self.writer.flush()?;
|
||||
} else {
|
||||
let release_button = 3;
|
||||
self.current_mouse_button = MouseButton::None;
|
||||
write!(
|
||||
self.writer,
|
||||
"\x1b[M{}{}{}",
|
||||
(32 + release_button) as u8 as char,
|
||||
Self::legacy_mouse_coord(event.x as i64),
|
||||
Self::legacy_mouse_coord(event.y),
|
||||
)?;
|
||||
self.writer.flush()?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mouse_move(&mut self, event: MouseEvent) -> anyhow::Result<()> {
|
||||
let reportable = self.any_event_mouse || self.current_mouse_button != MouseButton::None;
|
||||
// Note: self.mouse_tracking on its own is for clicks, not drags!
|
||||
if reportable && (self.button_event_mouse || self.any_event_mouse) {
|
||||
match self.last_mouse_move.as_ref() {
|
||||
Some(last) if *last == event => {
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.last_mouse_move.replace(event.clone());
|
||||
|
||||
let button = 32 + self.mouse_report_button_number(&event);
|
||||
|
||||
if self.sgr_mouse {
|
||||
write!(
|
||||
self.writer,
|
||||
"\x1b[<{};{};{}M",
|
||||
button,
|
||||
event.x + 1,
|
||||
event.y + 1
|
||||
)?;
|
||||
self.writer.flush()?;
|
||||
} else {
|
||||
write!(
|
||||
self.writer,
|
||||
"\x1b[M{}{}{}",
|
||||
(32 + button) as u8 as char,
|
||||
Self::legacy_mouse_coord(event.x as i64),
|
||||
Self::legacy_mouse_coord(event.y),
|
||||
)?;
|
||||
self.writer.flush()?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Informs the terminal of a mouse event.
|
||||
/// If mouse reporting has been activated, the mouse event will be encoded
|
||||
/// appropriately and written to the associated writer.
|
||||
pub fn mouse_event(&mut self, mut event: MouseEvent) -> anyhow::Result<()> {
|
||||
// Clamp the mouse coordinates to the size of the model.
|
||||
// This situation can trigger for example when the
|
||||
// window is resized and leaves a partial row at the bottom of the
|
||||
// terminal. The mouse can move over that portion and the gui layer
|
||||
// can thus send us out-of-bounds row or column numbers. We want to
|
||||
// make sure that we clamp this and handle it nicely at the model layer.
|
||||
event.y = event.y.min(self.screen().physical_rows as i64 - 1);
|
||||
event.x = event.x.min(self.screen().physical_cols - 1);
|
||||
|
||||
match event {
|
||||
MouseEvent {
|
||||
kind: MouseEventKind::Press,
|
||||
button: MouseButton::WheelUp(_),
|
||||
..
|
||||
}
|
||||
| MouseEvent {
|
||||
kind: MouseEventKind::Press,
|
||||
button: MouseButton::WheelDown(_),
|
||||
..
|
||||
} => self.mouse_wheel(event),
|
||||
MouseEvent {
|
||||
kind: MouseEventKind::Press,
|
||||
..
|
||||
} => self.mouse_button_press(event),
|
||||
MouseEvent {
|
||||
kind: MouseEventKind::Release,
|
||||
..
|
||||
} => self.mouse_button_release(event),
|
||||
MouseEvent {
|
||||
kind: MouseEventKind::Move,
|
||||
..
|
||||
} => self.mouse_move(event),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,808 @@
|
||||
use crate::input::MouseButton;
|
||||
use crate::terminal::Alert;
|
||||
use crate::terminalstate::{default_color_map, CharSet, TabStop};
|
||||
use crate::{ClipboardSelection, Position, TerminalState, VisibleRowIndex};
|
||||
use crate::{DCS, ST};
|
||||
use log::{debug, error};
|
||||
use num_traits::FromPrimitive;
|
||||
use std::fmt::Write;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use termwiz::cell::{unicode_column_width, Cell, CellAttributes, SemanticType};
|
||||
use termwiz::escape::csi::EraseInDisplay;
|
||||
use termwiz::escape::osc::{
|
||||
ChangeColorPair, ColorOrQuery, FinalTermSemanticPrompt, ITermProprietary, Selection,
|
||||
};
|
||||
use termwiz::escape::{
|
||||
Action, ControlCode, DeviceControlMode, Esc, EscCode, OperatingSystemCommand, CSI,
|
||||
};
|
||||
use url::Url;
|
||||
|
||||
/// A helper struct for implementing `vtparse::VTActor` while compartmentalizing
|
||||
/// the terminal state and the embedding/host terminal interface
|
||||
pub(crate) struct Performer<'a> {
|
||||
pub state: &'a mut TerminalState,
|
||||
print: Option<String>,
|
||||
}
|
||||
|
||||
impl<'a> Deref for Performer<'a> {
|
||||
type Target = TerminalState;
|
||||
|
||||
fn deref(&self) -> &TerminalState {
|
||||
self.state
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> DerefMut for Performer<'a> {
|
||||
fn deref_mut(&mut self) -> &mut TerminalState {
|
||||
&mut self.state
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for Performer<'a> {
|
||||
fn drop(&mut self) {
|
||||
self.flush_print();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Performer<'a> {
|
||||
pub fn new(state: &'a mut TerminalState) -> Self {
|
||||
Self { state, print: None }
|
||||
}
|
||||
|
||||
fn flush_print(&mut self) {
|
||||
let p = match self.print.take() {
|
||||
Some(s) => s,
|
||||
None => return,
|
||||
};
|
||||
|
||||
let mut graphemes =
|
||||
unicode_segmentation::UnicodeSegmentation::graphemes(p.as_str(), true).peekable();
|
||||
|
||||
while let Some(g) = graphemes.next() {
|
||||
let g = if (self.shift_out && self.g1_charset == CharSet::DecLineDrawing)
|
||||
|| (!self.shift_out && self.g0_charset == CharSet::DecLineDrawing)
|
||||
{
|
||||
match g {
|
||||
"`" => "◆",
|
||||
"a" => "▒",
|
||||
"b" => "␉",
|
||||
"c" => "␌",
|
||||
"d" => "␍",
|
||||
"e" => "␊",
|
||||
"f" => "°",
|
||||
"g" => "±",
|
||||
"h" => "",
|
||||
"i" => "␋",
|
||||
"j" => "┘",
|
||||
"k" => "┐",
|
||||
"l" => "┌",
|
||||
"m" => "└",
|
||||
"n" => "┼",
|
||||
"o" => "⎺",
|
||||
"p" => "⎻",
|
||||
"q" => "─",
|
||||
"r" => "⎼",
|
||||
"s" => "⎽",
|
||||
"t" => "├",
|
||||
"u" => "┤",
|
||||
"v" => "┴",
|
||||
"w" => "┬",
|
||||
"x" => "│",
|
||||
"y" => "≤",
|
||||
"z" => "≥",
|
||||
"{" => "π",
|
||||
"|" => "≠",
|
||||
"}" => "£",
|
||||
"~" => "·",
|
||||
_ => g,
|
||||
}
|
||||
} else if (self.shift_out && self.g1_charset == CharSet::Uk)
|
||||
|| (!self.shift_out && self.g0_charset == CharSet::Uk)
|
||||
{
|
||||
match g {
|
||||
"#" => "£",
|
||||
_ => g,
|
||||
}
|
||||
} else {
|
||||
g
|
||||
};
|
||||
|
||||
if self.wrap_next {
|
||||
// Since we're implicitly moving the cursor to the next
|
||||
// line, we need to tag the current position as wrapped
|
||||
// so that we can correctly reflow it if the window is
|
||||
// resized.
|
||||
{
|
||||
let x = self.cursor.x;
|
||||
let y = self.cursor.y;
|
||||
let screen = self.screen_mut();
|
||||
if let Some(cell) = screen.cell_mut(x, y) {
|
||||
cell.attrs_mut().set_wrapped(true);
|
||||
}
|
||||
}
|
||||
self.new_line(true);
|
||||
}
|
||||
|
||||
let x = self.cursor.x;
|
||||
let y = self.cursor.y;
|
||||
let width = self.left_and_right_margins.end;
|
||||
|
||||
let pen = self.pen.clone();
|
||||
// the max(1) here is to ensure that we advance to the next cell
|
||||
// position for zero-width graphemes. We want to make sure that
|
||||
// they occupy a cell so that we can re-emit them when we output them.
|
||||
// If we didn't do this, then we'd effectively filter them out from
|
||||
// the model, which seems like a lossy design choice.
|
||||
let print_width = unicode_column_width(g).max(1);
|
||||
let is_last = graphemes.peek().is_none();
|
||||
let wrappable = x + print_width >= width;
|
||||
|
||||
let cell = Cell::new_grapheme(g, pen);
|
||||
|
||||
if self.insert {
|
||||
let margin = self.left_and_right_margins.end;
|
||||
let screen = self.screen_mut();
|
||||
for _ in x..x + print_width as usize {
|
||||
screen.insert_cell(x, y, margin);
|
||||
}
|
||||
}
|
||||
|
||||
// Assign the cell
|
||||
log::trace!(
|
||||
"print x={} y={} is_last={} print_width={} width={} cell={:?}",
|
||||
x,
|
||||
y,
|
||||
is_last,
|
||||
print_width,
|
||||
width,
|
||||
cell
|
||||
);
|
||||
self.screen_mut().set_cell(x, y, &cell);
|
||||
|
||||
if !wrappable {
|
||||
self.cursor.x += print_width;
|
||||
self.wrap_next = false;
|
||||
} else {
|
||||
self.wrap_next = self.dec_auto_wrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn perform(&mut self, action: Action) {
|
||||
debug!("perform {:?}", action);
|
||||
match action {
|
||||
Action::Print(c) => self.print(c),
|
||||
Action::Control(code) => self.control(code),
|
||||
Action::DeviceControl(ctrl) => self.device_control(ctrl),
|
||||
Action::OperatingSystemCommand(osc) => self.osc_dispatch(*osc),
|
||||
Action::Esc(esc) => self.esc_dispatch(esc),
|
||||
Action::CSI(csi) => self.csi_dispatch(csi),
|
||||
Action::Sixel(sixel) => self.sixel(sixel),
|
||||
Action::XtGetTcap(names) => self.xt_get_tcap(names),
|
||||
Action::KittyImage(img) => {
|
||||
self.flush_print();
|
||||
if let Err(err) = self.kitty_img(img) {
|
||||
log::error!("kitty_img: {:#}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn device_control(&mut self, ctrl: DeviceControlMode) {
|
||||
match &ctrl {
|
||||
DeviceControlMode::ShortDeviceControl(s) => {
|
||||
match (s.byte, s.intermediates.as_slice()) {
|
||||
(b'q', &[b'$']) => {
|
||||
// DECRQSS - Request Status String
|
||||
// https://vt100.net/docs/vt510-rm/DECRQSS.html
|
||||
// The response is described here:
|
||||
// https://vt100.net/docs/vt510-rm/DECRPSS.html
|
||||
// but note that *that* text has the validity value
|
||||
// inverted; there's a note about this in the xterm
|
||||
// ctlseqs docs.
|
||||
match s.data.as_slice() {
|
||||
&[b'"', b'p'] => {
|
||||
// DECSCL - select conformance level
|
||||
write!(self.writer, "{}1$r65;1\"p{}", DCS, ST).ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
&[b'r'] => {
|
||||
// DECSTBM - top and bottom margins
|
||||
let margins = self.top_and_bottom_margins.clone();
|
||||
write!(
|
||||
self.writer,
|
||||
"{}1$r{};{}r{}",
|
||||
DCS,
|
||||
margins.start + 1,
|
||||
margins.end,
|
||||
ST
|
||||
)
|
||||
.ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
&[b's'] => {
|
||||
// DECSLRM - left and right margins
|
||||
let margins = self.left_and_right_margins.clone();
|
||||
write!(
|
||||
self.writer,
|
||||
"{}1$r{};{}s{}",
|
||||
DCS,
|
||||
margins.start + 1,
|
||||
margins.end,
|
||||
ST
|
||||
)
|
||||
.ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
_ => {
|
||||
log::warn!("unhandled DECRQSS {:?}", s);
|
||||
// Reply that the request is invalid
|
||||
write!(self.writer, "{}0$r{}", DCS, ST).ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => log::warn!("unhandled {:?}", s),
|
||||
}
|
||||
}
|
||||
_ => match self.device_control_handler.as_mut() {
|
||||
Some(handler) => handler.handle_device_control(ctrl),
|
||||
None => log::warn!("unhandled {:?}", ctrl),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw a character to the screen
|
||||
fn print(&mut self, c: char) {
|
||||
// We buffer up the chars to increase the chances of correctly grouping graphemes into cells
|
||||
self.print.get_or_insert_with(String::new).push(c);
|
||||
}
|
||||
|
||||
fn control(&mut self, control: ControlCode) {
|
||||
self.flush_print();
|
||||
match control {
|
||||
ControlCode::LineFeed | ControlCode::VerticalTab | ControlCode::FormFeed => {
|
||||
if self.left_and_right_margins.contains(&self.cursor.x) {
|
||||
self.new_line(false);
|
||||
} else {
|
||||
// Do move down, but don't trigger a scroll when we're
|
||||
// outside of the left/right margins
|
||||
let old_y = self.cursor.y;
|
||||
let y = if old_y == self.top_and_bottom_margins.end - 1 {
|
||||
old_y
|
||||
} else {
|
||||
(old_y + 1).min(self.screen().physical_rows as i64 - 1)
|
||||
};
|
||||
self.screen_mut().dirty_line(old_y);
|
||||
self.screen_mut().dirty_line(y);
|
||||
self.cursor.y = y;
|
||||
self.wrap_next = false;
|
||||
}
|
||||
if self.newline_mode {
|
||||
self.cursor.x = 0;
|
||||
}
|
||||
}
|
||||
ControlCode::CarriageReturn => {
|
||||
if self.cursor.x >= self.left_and_right_margins.start {
|
||||
self.cursor.x = self.left_and_right_margins.start;
|
||||
} else {
|
||||
self.cursor.x = 0;
|
||||
}
|
||||
let y = self.cursor.y;
|
||||
self.wrap_next = false;
|
||||
self.screen_mut().dirty_line(y);
|
||||
}
|
||||
|
||||
ControlCode::Backspace => {
|
||||
if self.reverse_wraparound_mode
|
||||
&& self.dec_auto_wrap
|
||||
&& self.cursor.x == self.left_and_right_margins.start
|
||||
&& self.cursor.y == self.top_and_bottom_margins.start
|
||||
{
|
||||
// Backspace off the top-left wraps around to the bottom right
|
||||
let x_pos = Position::Absolute(self.left_and_right_margins.end as i64 - 1);
|
||||
let y_pos = Position::Absolute(self.top_and_bottom_margins.end - 1);
|
||||
self.set_cursor_pos(&x_pos, &y_pos);
|
||||
} else if self.reverse_wraparound_mode
|
||||
&& self.dec_auto_wrap
|
||||
&& self.cursor.x <= self.left_and_right_margins.start
|
||||
{
|
||||
// Backspace off the left wraps around to the prior line on the right
|
||||
let x_pos = Position::Absolute(self.left_and_right_margins.end as i64 - 1);
|
||||
let y_pos = Position::Relative(-1);
|
||||
self.set_cursor_pos(&x_pos, &y_pos);
|
||||
} else if self.reverse_wraparound_mode
|
||||
&& self.dec_auto_wrap
|
||||
&& self.cursor.x == self.left_and_right_margins.end - 1
|
||||
&& self.wrap_next
|
||||
{
|
||||
// If the cursor is in the last column and a character was
|
||||
// just output and reverse-wraparound is on then backspace
|
||||
// by 1 has no effect.
|
||||
} else if self.cursor.x == self.left_and_right_margins.start {
|
||||
// Respect the left margin and don't BS outside it
|
||||
} else {
|
||||
self.set_cursor_pos(&Position::Relative(-1), &Position::Relative(0));
|
||||
}
|
||||
}
|
||||
ControlCode::HorizontalTab => self.c0_horizontal_tab(),
|
||||
ControlCode::HTS => self.c1_hts(),
|
||||
ControlCode::IND => self.c1_index(),
|
||||
ControlCode::NEL => self.c1_nel(),
|
||||
ControlCode::Bell => {
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::Bell);
|
||||
} else {
|
||||
log::info!("Ding! (this is the bell)");
|
||||
}
|
||||
}
|
||||
ControlCode::RI => self.c1_reverse_index(),
|
||||
|
||||
// wezterm only supports UTF-8, so does not support the
|
||||
// DEC National Replacement Character Sets. However, it does
|
||||
// support the DEC Special Graphics character set used by
|
||||
// numerous ncurses applications. DEC Special Graphics can be
|
||||
// selected by ASCII Shift Out (0x0E, ^N) or by setting G0
|
||||
// via ESC ( 0 .
|
||||
ControlCode::ShiftIn => {
|
||||
self.shift_out = false;
|
||||
}
|
||||
ControlCode::ShiftOut => {
|
||||
self.shift_out = true;
|
||||
}
|
||||
|
||||
ControlCode::Enquiry => {
|
||||
let response = self.config.enq_answerback();
|
||||
if response.len() > 0 {
|
||||
write!(self.writer, "{}", response).ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
}
|
||||
|
||||
_ => log::warn!("unhandled ControlCode {:?}", control),
|
||||
}
|
||||
}
|
||||
|
||||
fn csi_dispatch(&mut self, csi: CSI) {
|
||||
self.flush_print();
|
||||
match csi {
|
||||
CSI::Sgr(sgr) => self.state.perform_csi_sgr(sgr),
|
||||
CSI::Cursor(cursor) => self.state.perform_csi_cursor(cursor),
|
||||
CSI::Edit(edit) => self.state.perform_csi_edit(edit),
|
||||
CSI::Mode(mode) => self.state.perform_csi_mode(mode),
|
||||
CSI::Device(dev) => self.state.perform_device(*dev),
|
||||
CSI::Mouse(mouse) => error!("mouse report sent by app? {:?}", mouse),
|
||||
CSI::Window(window) => self.state.perform_csi_window(window),
|
||||
CSI::Unspecified(unspec) => {
|
||||
log::warn!("unknown unspecified CSI: {:?}", format!("{}", unspec))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn esc_dispatch(&mut self, esc: Esc) {
|
||||
self.flush_print();
|
||||
match esc {
|
||||
Esc::Code(EscCode::StringTerminator) => {
|
||||
// String Terminator (ST); explicitly has nothing to do here, as its purpose is
|
||||
// handled implicitly through a state transition in the vtparse state tables.
|
||||
}
|
||||
Esc::Code(EscCode::DecApplicationKeyPad) => {
|
||||
debug!("DECKPAM on");
|
||||
self.application_keypad = true;
|
||||
}
|
||||
Esc::Code(EscCode::DecNormalKeyPad) => {
|
||||
debug!("DECKPAM off");
|
||||
self.application_keypad = false;
|
||||
}
|
||||
Esc::Code(EscCode::ReverseIndex) => self.c1_reverse_index(),
|
||||
Esc::Code(EscCode::Index) => self.c1_index(),
|
||||
Esc::Code(EscCode::NextLine) => self.c1_nel(),
|
||||
Esc::Code(EscCode::HorizontalTabSet) => self.c1_hts(),
|
||||
Esc::Code(EscCode::DecLineDrawingG0) => {
|
||||
self.g0_charset = CharSet::DecLineDrawing;
|
||||
}
|
||||
Esc::Code(EscCode::AsciiCharacterSetG0) => {
|
||||
self.g0_charset = CharSet::Ascii;
|
||||
}
|
||||
Esc::Code(EscCode::UkCharacterSetG0) => {
|
||||
self.g0_charset = CharSet::Uk;
|
||||
}
|
||||
Esc::Code(EscCode::DecLineDrawingG1) => {
|
||||
self.g1_charset = CharSet::DecLineDrawing;
|
||||
}
|
||||
Esc::Code(EscCode::AsciiCharacterSetG1) => {
|
||||
self.g1_charset = CharSet::Ascii;
|
||||
}
|
||||
Esc::Code(EscCode::UkCharacterSetG1) => {
|
||||
self.g1_charset = CharSet::Uk;
|
||||
}
|
||||
Esc::Code(EscCode::DecSaveCursorPosition) => self.dec_save_cursor(),
|
||||
Esc::Code(EscCode::DecRestoreCursorPosition) => self.dec_restore_cursor(),
|
||||
|
||||
Esc::Code(EscCode::DecDoubleHeightTopHalfLine) => {
|
||||
let idx = self.screen.phys_row(self.cursor.y);
|
||||
self.screen.line_mut(idx).set_double_height_top();
|
||||
}
|
||||
Esc::Code(EscCode::DecDoubleHeightBottomHalfLine) => {
|
||||
let idx = self.screen.phys_row(self.cursor.y);
|
||||
self.screen.line_mut(idx).set_double_height_bottom();
|
||||
}
|
||||
Esc::Code(EscCode::DecDoubleWidthLine) => {
|
||||
let idx = self.screen.phys_row(self.cursor.y);
|
||||
self.screen.line_mut(idx).set_double_width();
|
||||
}
|
||||
Esc::Code(EscCode::DecSingleWidthLine) => {
|
||||
let idx = self.screen.phys_row(self.cursor.y);
|
||||
self.screen.line_mut(idx).set_single_width();
|
||||
}
|
||||
|
||||
Esc::Code(EscCode::DecScreenAlignmentDisplay) => {
|
||||
// This one is just to make vttest happy;
|
||||
// its original purpose was for aligning the CRT.
|
||||
// https://vt100.net/docs/vt510-rm/DECALN.html
|
||||
|
||||
let screen = self.screen_mut();
|
||||
let col_range = 0..screen.physical_cols;
|
||||
for y in 0..screen.physical_rows as VisibleRowIndex {
|
||||
let line_idx = screen.phys_row(y);
|
||||
let line = screen.line_mut(line_idx);
|
||||
line.resize(col_range.end);
|
||||
line.fill_range(
|
||||
col_range.clone(),
|
||||
&Cell::new('E', CellAttributes::default()),
|
||||
);
|
||||
}
|
||||
|
||||
self.top_and_bottom_margins = 0..self.screen().physical_rows as VisibleRowIndex;
|
||||
self.left_and_right_margins = 0..self.screen().physical_cols;
|
||||
self.cursor = Default::default();
|
||||
}
|
||||
|
||||
// RIS resets a device to its initial state, i.e. the state it has after it is switched
|
||||
// on. This may imply, if applicable: remove tabulation stops, remove qualified areas,
|
||||
// reset graphic rendition, erase all positions, move active position to first
|
||||
// character position of first line.
|
||||
Esc::Code(EscCode::FullReset) => {
|
||||
self.pen = Default::default();
|
||||
self.cursor = Default::default();
|
||||
self.wrap_next = false;
|
||||
self.insert = false;
|
||||
self.dec_auto_wrap = true;
|
||||
self.reverse_wraparound_mode = false;
|
||||
self.reverse_video_mode = false;
|
||||
self.dec_origin_mode = false;
|
||||
self.use_private_color_registers_for_each_graphic = false;
|
||||
self.color_map = default_color_map();
|
||||
self.application_cursor_keys = false;
|
||||
self.sixel_scrolling = true;
|
||||
self.dec_ansi_mode = false;
|
||||
self.application_keypad = false;
|
||||
self.bracketed_paste = false;
|
||||
self.focus_tracking = false;
|
||||
self.sgr_mouse = false;
|
||||
self.sixel_scrolls_right = false;
|
||||
self.any_event_mouse = false;
|
||||
self.button_event_mouse = false;
|
||||
self.current_mouse_button = MouseButton::None;
|
||||
self.cursor_visible = true;
|
||||
self.g0_charset = CharSet::Ascii;
|
||||
self.g1_charset = CharSet::DecLineDrawing;
|
||||
self.shift_out = false;
|
||||
self.newline_mode = false;
|
||||
self.tabs = TabStop::new(self.screen().physical_cols, 8);
|
||||
self.palette.take();
|
||||
self.top_and_bottom_margins = 0..self.screen().physical_rows as VisibleRowIndex;
|
||||
self.left_and_right_margins = 0..self.screen().physical_cols;
|
||||
|
||||
self.screen.activate_primary_screen();
|
||||
self.erase_in_display(EraseInDisplay::EraseScrollback);
|
||||
self.erase_in_display(EraseInDisplay::EraseDisplay);
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::PaletteChanged);
|
||||
}
|
||||
}
|
||||
|
||||
_ => log::warn!("ESC: unhandled {:?}", esc),
|
||||
}
|
||||
}
|
||||
|
||||
fn osc_dispatch(&mut self, osc: OperatingSystemCommand) {
|
||||
self.flush_print();
|
||||
match osc {
|
||||
OperatingSystemCommand::SetIconNameSun(title)
|
||||
| OperatingSystemCommand::SetIconName(title) => {
|
||||
if title.is_empty() {
|
||||
self.icon_title = None;
|
||||
} else {
|
||||
self.icon_title = Some(title.clone());
|
||||
}
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::TitleMaybeChanged);
|
||||
}
|
||||
}
|
||||
OperatingSystemCommand::SetIconNameAndWindowTitle(title) => {
|
||||
self.icon_title.take();
|
||||
self.title = title.clone();
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::TitleMaybeChanged);
|
||||
}
|
||||
}
|
||||
|
||||
OperatingSystemCommand::SetWindowTitleSun(title)
|
||||
| OperatingSystemCommand::SetWindowTitle(title) => {
|
||||
self.title = title.clone();
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::TitleMaybeChanged);
|
||||
}
|
||||
}
|
||||
OperatingSystemCommand::SetHyperlink(link) => {
|
||||
self.set_hyperlink(link);
|
||||
}
|
||||
OperatingSystemCommand::Unspecified(unspec) => {
|
||||
let mut output = String::new();
|
||||
write!(&mut output, "Unhandled OSC ").ok();
|
||||
for item in unspec {
|
||||
write!(&mut output, " {}", String::from_utf8_lossy(&item)).ok();
|
||||
}
|
||||
log::warn!("{}", output);
|
||||
}
|
||||
|
||||
OperatingSystemCommand::ClearSelection(selection) => {
|
||||
let selection = selection_to_selection(selection);
|
||||
self.set_clipboard_contents(selection, None).ok();
|
||||
}
|
||||
OperatingSystemCommand::QuerySelection(_) => {}
|
||||
OperatingSystemCommand::SetSelection(selection, selection_data) => {
|
||||
let selection = selection_to_selection(selection);
|
||||
match self.set_clipboard_contents(selection, Some(selection_data)) {
|
||||
Ok(_) => (),
|
||||
Err(err) => error!("failed to set clipboard in response to OSC 52: {:?}", err),
|
||||
}
|
||||
}
|
||||
OperatingSystemCommand::ITermProprietary(iterm) => match iterm {
|
||||
ITermProprietary::File(image) => self.set_image(*image),
|
||||
ITermProprietary::SetUserVar { name, value } => {
|
||||
self.user_vars.insert(name, value);
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::TitleMaybeChanged);
|
||||
}
|
||||
}
|
||||
_ => log::warn!("unhandled iterm2: {:?}", iterm),
|
||||
},
|
||||
|
||||
OperatingSystemCommand::FinalTermSemanticPrompt(FinalTermSemanticPrompt::FreshLine) => {
|
||||
self.fresh_line();
|
||||
}
|
||||
OperatingSystemCommand::FinalTermSemanticPrompt(
|
||||
FinalTermSemanticPrompt::FreshLineAndStartPrompt { .. },
|
||||
) => {
|
||||
self.fresh_line();
|
||||
self.pen.set_semantic_type(SemanticType::Prompt);
|
||||
}
|
||||
OperatingSystemCommand::FinalTermSemanticPrompt(
|
||||
FinalTermSemanticPrompt::StartPrompt(_),
|
||||
) => {
|
||||
self.pen.set_semantic_type(SemanticType::Prompt);
|
||||
}
|
||||
OperatingSystemCommand::FinalTermSemanticPrompt(
|
||||
FinalTermSemanticPrompt::MarkEndOfCommandWithFreshLine { .. },
|
||||
) => {
|
||||
self.fresh_line();
|
||||
self.pen.set_semantic_type(SemanticType::Prompt);
|
||||
}
|
||||
OperatingSystemCommand::FinalTermSemanticPrompt(
|
||||
FinalTermSemanticPrompt::MarkEndOfPromptAndStartOfInputUntilNextMarker { .. },
|
||||
) => {
|
||||
self.pen.set_semantic_type(SemanticType::Input);
|
||||
}
|
||||
OperatingSystemCommand::FinalTermSemanticPrompt(
|
||||
FinalTermSemanticPrompt::MarkEndOfInputAndStartOfOutput { .. },
|
||||
) => {
|
||||
self.pen.set_semantic_type(SemanticType::Output);
|
||||
}
|
||||
|
||||
OperatingSystemCommand::FinalTermSemanticPrompt(
|
||||
FinalTermSemanticPrompt::CommandStatus { .. },
|
||||
) => {}
|
||||
|
||||
OperatingSystemCommand::FinalTermSemanticPrompt(ft) => {
|
||||
log::warn!("unhandled: {:?}", ft);
|
||||
}
|
||||
|
||||
OperatingSystemCommand::SystemNotification(message) => {
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::ToastNotification {
|
||||
title: None,
|
||||
body: message,
|
||||
focus: true,
|
||||
});
|
||||
} else {
|
||||
log::info!("Application sends SystemNotification: {}", message);
|
||||
}
|
||||
}
|
||||
OperatingSystemCommand::RxvtExtension(params) => {
|
||||
if let Some("notify") = params.get(0).map(String::as_str) {
|
||||
let title = params.get(1);
|
||||
let body = params.get(2);
|
||||
let (title, body) = match (title.cloned(), body.cloned()) {
|
||||
(Some(title), None) => (None, title),
|
||||
(Some(title), Some(body)) => (Some(title), body),
|
||||
_ => {
|
||||
log::warn!("malformed rxvt notify escape: {:?}", params);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::ToastNotification {
|
||||
title,
|
||||
body,
|
||||
focus: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
OperatingSystemCommand::CurrentWorkingDirectory(url) => {
|
||||
self.current_dir = Url::parse(&url).ok();
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::TitleMaybeChanged);
|
||||
}
|
||||
}
|
||||
OperatingSystemCommand::ChangeColorNumber(specs) => {
|
||||
log::trace!("ChangeColorNumber: {:?}", specs);
|
||||
for pair in specs {
|
||||
match pair.color {
|
||||
ColorOrQuery::Query => {
|
||||
let response =
|
||||
OperatingSystemCommand::ChangeColorNumber(vec![ChangeColorPair {
|
||||
palette_index: pair.palette_index,
|
||||
color: ColorOrQuery::Color(
|
||||
self.palette().colors.0[pair.palette_index as usize],
|
||||
),
|
||||
}]);
|
||||
write!(self.writer, "{}", response).ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
ColorOrQuery::Color(c) => {
|
||||
self.palette_mut().colors.0[pair.palette_index as usize] = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::PaletteChanged);
|
||||
}
|
||||
self.make_all_lines_dirty();
|
||||
}
|
||||
|
||||
OperatingSystemCommand::ResetColors(colors) => {
|
||||
log::trace!("ResetColors: {:?}", colors);
|
||||
if colors.is_empty() {
|
||||
// Reset all colors
|
||||
self.palette.take();
|
||||
} else {
|
||||
// Reset individual colors
|
||||
if self.palette.is_none() {
|
||||
// Already at the defaults
|
||||
} else {
|
||||
let base = self.config.color_palette();
|
||||
for c in colors {
|
||||
let c = c as usize;
|
||||
self.palette_mut().colors.0[c] = base.colors.0[c];
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::PaletteChanged);
|
||||
}
|
||||
}
|
||||
|
||||
OperatingSystemCommand::ChangeDynamicColors(first_color, colors) => {
|
||||
log::trace!("ChangeDynamicColors: {:?} {:?}", first_color, colors);
|
||||
use termwiz::escape::osc::DynamicColorNumber;
|
||||
let mut idx: u8 = first_color as u8;
|
||||
for color in colors {
|
||||
let which_color: Option<DynamicColorNumber> = FromPrimitive::from_u8(idx);
|
||||
log::trace!("ChangeDynamicColors item: {:?}", which_color);
|
||||
if let Some(which_color) = which_color {
|
||||
macro_rules! set_or_query {
|
||||
($name:ident) => {
|
||||
match color {
|
||||
ColorOrQuery::Query => {
|
||||
let response = OperatingSystemCommand::ChangeDynamicColors(
|
||||
which_color,
|
||||
vec![ColorOrQuery::Color(self.palette().$name)],
|
||||
);
|
||||
log::trace!("Color Query response {:?}", response);
|
||||
write!(self.writer, "{}", response).ok();
|
||||
self.writer.flush().ok();
|
||||
}
|
||||
ColorOrQuery::Color(c) => self.palette_mut().$name = c,
|
||||
}
|
||||
};
|
||||
}
|
||||
match which_color {
|
||||
DynamicColorNumber::TextForegroundColor => set_or_query!(foreground),
|
||||
DynamicColorNumber::TextBackgroundColor => set_or_query!(background),
|
||||
DynamicColorNumber::TextCursorColor => {
|
||||
if let ColorOrQuery::Color(c) = color {
|
||||
// We set the border to the background color; we don't
|
||||
// have an escape that sets that independently, and this
|
||||
// way just looks better.
|
||||
self.palette_mut().cursor_border = c;
|
||||
}
|
||||
set_or_query!(cursor_bg)
|
||||
}
|
||||
DynamicColorNumber::HighlightForegroundColor => {
|
||||
set_or_query!(selection_fg)
|
||||
}
|
||||
DynamicColorNumber::HighlightBackgroundColor => {
|
||||
set_or_query!(selection_bg)
|
||||
}
|
||||
DynamicColorNumber::MouseForegroundColor
|
||||
| DynamicColorNumber::MouseBackgroundColor
|
||||
| DynamicColorNumber::TektronixForegroundColor
|
||||
| DynamicColorNumber::TektronixBackgroundColor
|
||||
| DynamicColorNumber::TektronixCursorColor => {}
|
||||
}
|
||||
}
|
||||
idx += 1;
|
||||
}
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::PaletteChanged);
|
||||
}
|
||||
self.make_all_lines_dirty();
|
||||
}
|
||||
|
||||
OperatingSystemCommand::ResetDynamicColor(color) => {
|
||||
log::trace!("ResetDynamicColor: {:?}", color);
|
||||
use termwiz::escape::osc::DynamicColorNumber;
|
||||
let which_color: Option<DynamicColorNumber> = FromPrimitive::from_u8(color as u8);
|
||||
if let Some(which_color) = which_color {
|
||||
macro_rules! reset {
|
||||
($name:ident) => {
|
||||
if self.palette.is_none() {
|
||||
// Already at the defaults
|
||||
} else {
|
||||
let base = self.config.color_palette();
|
||||
self.palette_mut().$name = base.$name;
|
||||
}
|
||||
};
|
||||
}
|
||||
match which_color {
|
||||
DynamicColorNumber::TextForegroundColor => reset!(foreground),
|
||||
DynamicColorNumber::TextBackgroundColor => reset!(background),
|
||||
DynamicColorNumber::TextCursorColor => {
|
||||
reset!(cursor_bg);
|
||||
// Since we set the border to the bg, we consider it reset
|
||||
// by resetting the bg too!
|
||||
reset!(cursor_border);
|
||||
}
|
||||
DynamicColorNumber::HighlightForegroundColor => reset!(selection_fg),
|
||||
DynamicColorNumber::HighlightBackgroundColor => reset!(selection_bg),
|
||||
DynamicColorNumber::MouseForegroundColor
|
||||
| DynamicColorNumber::MouseBackgroundColor
|
||||
| DynamicColorNumber::TektronixForegroundColor
|
||||
| DynamicColorNumber::TektronixBackgroundColor
|
||||
| DynamicColorNumber::TektronixCursorColor => {}
|
||||
}
|
||||
}
|
||||
if let Some(handler) = self.alert_handler.as_mut() {
|
||||
handler.alert(Alert::PaletteChanged);
|
||||
}
|
||||
self.make_all_lines_dirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn selection_to_selection(sel: Selection) -> ClipboardSelection {
|
||||
match sel {
|
||||
Selection::CLIPBOARD => ClipboardSelection::Clipboard,
|
||||
Selection::PRIMARY => ClipboardSelection::PrimarySelection,
|
||||
// xterm will use a configurable selection in the NONE case
|
||||
Selection::NONE => ClipboardSelection::Clipboard,
|
||||
// otherwise we just use clipboard. Could potentially
|
||||
// also use the same fallback configuration as NONE,
|
||||
// if/when we add it
|
||||
_ => ClipboardSelection::Clipboard,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
use crate::terminalstate::image::*;
|
||||
use crate::terminalstate::{default_color_map, ImageAttachParams};
|
||||
use crate::TerminalState;
|
||||
use ::image::RgbaImage;
|
||||
use termwiz::color::RgbColor;
|
||||
use termwiz::escape::{Sixel, SixelData};
|
||||
use termwiz::image::ImageDataType;
|
||||
|
||||
impl TerminalState {
|
||||
pub(crate) fn sixel(&mut self, sixel: Box<Sixel>) {
|
||||
let (width, height) = sixel.dimensions();
|
||||
|
||||
let mut private_color_map;
|
||||
let color_map = if self.use_private_color_registers_for_each_graphic {
|
||||
private_color_map = default_color_map();
|
||||
&mut private_color_map
|
||||
} else {
|
||||
&mut self.color_map
|
||||
};
|
||||
|
||||
let mut image = if sixel.background_is_transparent {
|
||||
RgbaImage::new(width, height)
|
||||
} else {
|
||||
let background_color = color_map
|
||||
.get(&0)
|
||||
.cloned()
|
||||
.unwrap_or(RgbColor::new_8bpc(0, 0, 0));
|
||||
let (red, green, blue) = background_color.to_tuple_rgb8();
|
||||
RgbaImage::from_pixel(width, height, [red, green, blue, 0xffu8].into())
|
||||
};
|
||||
|
||||
let mut x = 0;
|
||||
let mut y = 0;
|
||||
let mut foreground_color = RgbColor::new_8bpc(0, 0xff, 0);
|
||||
|
||||
let mut emit_sixel = |d: &u8, foreground_color: &RgbColor, x: u32, y: u32| {
|
||||
let (red, green, blue) = foreground_color.to_tuple_rgb8();
|
||||
for bitno in 0..6 {
|
||||
if y + bitno >= height {
|
||||
break;
|
||||
}
|
||||
let on = (d & (1 << bitno)) != 0;
|
||||
if on {
|
||||
image.get_pixel_mut(x, y + bitno).0 = [red, green, blue, 0xffu8];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for d in &sixel.data {
|
||||
match d {
|
||||
SixelData::Data(d) => {
|
||||
emit_sixel(d, &foreground_color, x, y);
|
||||
x += 1;
|
||||
}
|
||||
|
||||
SixelData::Repeat { repeat_count, data } => {
|
||||
for _ in 0..*repeat_count {
|
||||
emit_sixel(data, &foreground_color, x, y);
|
||||
x += 1;
|
||||
}
|
||||
}
|
||||
|
||||
SixelData::CarriageReturn => x = 0,
|
||||
SixelData::NewLine => {
|
||||
x = 0;
|
||||
y += 6;
|
||||
}
|
||||
|
||||
SixelData::DefineColorMapRGB { color_number, rgb } => {
|
||||
color_map.insert(*color_number, *rgb);
|
||||
}
|
||||
|
||||
SixelData::DefineColorMapHSL {
|
||||
color_number,
|
||||
hue_angle,
|
||||
saturation,
|
||||
lightness,
|
||||
} => {
|
||||
use palette::encoding::pixel::Pixel;
|
||||
// Sixel's hue angles are: blue=0, red=120, green=240,
|
||||
// whereas Hsl has red=0, green=120, blue=240.
|
||||
// Looking at red, we need to rotate left by 120 to
|
||||
// go from sixel red to palette::RgbHue red.
|
||||
// Negative values wrap around the circle.
|
||||
// https://github.com/wez/wezterm/issues/775
|
||||
let angle = (*hue_angle as f32) - 120.0;
|
||||
let angle = if angle < 0. { 360.0 + angle } else { angle };
|
||||
let hue = palette::RgbHue::from_degrees(angle);
|
||||
let hsl =
|
||||
palette::Hsl::new(hue, *saturation as f32 / 100., *lightness as f32 / 100.);
|
||||
let rgb: palette::Srgb = hsl.into();
|
||||
let rgb: [u8; 3] = rgb.into_linear().into_format().into_raw();
|
||||
|
||||
color_map.insert(*color_number, RgbColor::new_8bpc(rgb[0], rgb[1], rgb[2]));
|
||||
}
|
||||
|
||||
SixelData::SelectColorMapEntry(n) => {
|
||||
foreground_color = color_map.get(n).cloned().unwrap_or_else(|| {
|
||||
log::error!("sixel selected noexistent colormap entry {}", n);
|
||||
RgbColor::new_8bpc(255, 255, 255)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let image_data = ImageDataType::Rgba8 {
|
||||
width,
|
||||
height,
|
||||
data: image.into_vec().into_boxed_slice(),
|
||||
};
|
||||
|
||||
let image_data = self.raw_image_to_image_data(image_data);
|
||||
self.assign_image_to_cells(ImageAttachParams {
|
||||
image_width: width,
|
||||
image_height: height,
|
||||
source_width: width,
|
||||
source_height: height,
|
||||
rows: None,
|
||||
columns: None,
|
||||
source_origin_x: 0,
|
||||
source_origin_y: 0,
|
||||
display_offset_x: 0,
|
||||
display_offset_y: 0,
|
||||
data: image_data,
|
||||
style: ImageAttachStyle::Sixel,
|
||||
z_index: 0,
|
||||
image_id: 0,
|
||||
placement_id: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user