diff --git a/Cargo.lock b/Cargo.lock index c8485952c..c69d5e7ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -316,6 +316,12 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e8c087f005730276d1096a652e92a8bacee2e2472bcc9715a74d2bec38b5820" +[[package]] +name = "bytemuck" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37fa13df2292ecb479ec23aa06f4507928bef07839be9ef15281411076629431" + [[package]] name = "byteorder" version = "1.3.4" @@ -699,6 +705,16 @@ dependencies = [ "byteorder", ] +[[package]] +name = "deflate" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e5d2a2273fed52a7f947ee55b092c4057025d7a3e04e5ecdbd25d6c3fb1bd7" +dependencies = [ + "adler32", + "byteorder", +] + [[package]] name = "difference" version = "2.0.0" @@ -1353,9 +1369,27 @@ dependencies = [ "num-iter", "num-rational", "num-traits 0.2.11", - "png", + "png 0.14.1", "scoped_threadpool", - "tiff", + "tiff 0.2.2", +] + +[[package]] +name = "image" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d534e95ad8b9d5aa614322d02352b4f1bf962254adcf02ac6f2def8be18498e8" +dependencies = [ + "bytemuck", + "byteorder", + "gif", + "jpeg-decoder", + "num-iter", + "num-rational", + "num-traits 0.2.11", + "png 0.16.4", + "scoped_threadpool", + "tiff 0.5.0", ] [[package]] @@ -2307,11 +2341,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63daf481fdd0defa2d1d2be15c674fbfa1b0fd71882c303a91f9a79b3252c359" dependencies = [ "bitflags 1.2.1", - "deflate", + "deflate 0.7.20", "inflate", "num-iter", ] +[[package]] +name = "png" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12faa637ed9ae3d3c881332e54b5ae2dba81cda9fc4bbce0faa1ba53abcead50" +dependencies = [ + "bitflags 1.2.1", + "crc32fast", + "deflate 0.8.4", + "inflate", +] + [[package]] name = "portable-pty" version = "0.3.0" @@ -3202,7 +3248,7 @@ version = "0.1.0" dependencies = [ "anyhow", "bitflags 1.2.1", - "image", + "image 0.23.5", "log", "num", "ordered-float", @@ -3339,6 +3385,17 @@ dependencies = [ "num-traits 0.2.11", ] +[[package]] +name = "tiff" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3b8a87c4da944c3f27e5943289171ac71a6150a79ff6bacfff06d159dfff2f" +dependencies = [ + "byteorder", + "lzw", + "miniz_oxide", +] + [[package]] name = "time" version = "0.1.43" @@ -3817,7 +3874,7 @@ dependencies = [ "hdrhistogram", "hostname", "http_req", - "image", + "image 0.21.3", "lazy_static", "leb128", "libc", diff --git a/term/Cargo.toml b/term/Cargo.toml index cc0e58f66..36a691e6c 100644 --- a/term/Cargo.toml +++ b/term/Cargo.toml @@ -7,7 +7,7 @@ edition = "2018" [dependencies] bitflags = "1.0" anyhow = "1.0" -image = "0.21" +image = "0.23" log = "0.4" num = "0.2" ordered-float = "1.0" diff --git a/term/src/terminalstate.rs b/term/src/terminalstate.rs index 9a6c9e96c..3ee281a0e 100644 --- a/term/src/terminalstate.rs +++ b/term/src/terminalstate.rs @@ -2,11 +2,12 @@ // and inclusive range #![cfg_attr(feature = "cargo-clippy", allow(clippy::range_plus_one))] use super::*; -use crate::color::ColorPalette; +use crate::color::{ColorPalette, RgbColor}; use anyhow::bail; use image::{self, GenericImageView}; use log::{debug, error}; use ordered_float::NotNan; +use std::collections::HashMap; use std::fmt::Write; use std::sync::Arc; use termwiz::escape::csi::{ @@ -15,7 +16,7 @@ use termwiz::escape::csi::{ }; use termwiz::escape::osc::{ChangeColorPair, ColorOrQuery, ITermFileData, ITermProprietary}; use termwiz::escape::{ - Action, ControlCode, Esc, EscCode, OneBased, OperatingSystemCommand, Sixel, CSI, + Action, ControlCode, Esc, EscCode, OneBased, OperatingSystemCommand, Sixel, SixelData, CSI, }; use termwiz::image::{ImageCell, ImageData, TextureCoordinate}; use termwiz::surface::CursorShape; @@ -210,6 +211,9 @@ pub struct TerminalState { /// on what sixel scrolling mode does sixel_scrolling: bool, + /// Graphics mode color register map. + color_map: HashMap, + /// When set, modifies the sequence of bytes sent for keys /// in the numeric keypad portion of the keyboard. application_keypad: bool, @@ -285,6 +289,10 @@ impl TerminalState { ) -> TerminalState { let screen = ScreenOrAlt::new(physical_rows, physical_cols, &config); + let mut color_map = HashMap::new(); + color_map.insert(0, RgbColor::new(0, 0, 0)); + color_map.insert(3, RgbColor::new(0, 255, 0)); + TerminalState { config, screen, @@ -299,7 +307,8 @@ impl TerminalState { insert: false, application_cursor_keys: false, dec_ansi_mode: false, - sixel_scrolling: false, + sixel_scrolling: true, + color_map, application_keypad: false, bracketed_paste: false, sgr_mouse: false, @@ -1014,7 +1023,161 @@ impl TerminalState { } } - fn sixel(&mut self, _sixel: Box) {} + fn sixel(&mut self, sixel: Box) { + let (width, height) = sixel.dimensions(); + + let mut image = if sixel.background_is_transparent { + image::RgbaImage::new(width, height) + } else { + let background_color = self + .color_map + .get(&0) + .cloned() + .unwrap_or(RgbColor::new(0, 0, 0)); + image::RgbaImage::from_pixel( + width, + height, + [ + background_color.red, + background_color.green, + background_color.blue, + 0xffu8, + ] + .into(), + ) + }; + + let mut x = 0; + let mut y = 0; + let mut foreground_color = RgbColor::new(0, 0xff, 0); + + let mut emit_sixel = |d: &u8, foreground_color: &RgbColor, x: u32, y: u32| { + 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 = [ + foreground_color.red, + foreground_color.green, + foreground_color.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 } => { + self.color_map.insert(*color_number, *rgb); + } + + SixelData::DefineColorMapHSL { + color_number, + hue_angle, + saturation, + lightness, + } => { + use palette::encoding::pixel::Pixel; + let hue = palette::RgbHue::from_degrees(*hue_angle as f32); + let hsl = + palette::Hsl::new(hue, *saturation as f32 / 100., *lightness as f32 / 100.); + let rgb: palette::Srgb = hsl.into(); + let rgb: [u8; 3] = palette::Srgb::from_linear(rgb.into_linear()) + .into_format() + .into_raw(); + + self.color_map + .insert(*color_number, RgbColor::new(rgb[0], rgb[1], rgb[2])); + } + + SixelData::SelectColorMapEntry(n) => { + foreground_color = self.color_map.get(n).cloned().unwrap_or_else(|| { + log::error!("sixel selected noexistent colormap entry {}", n); + RgbColor::new(255, 255, 255) + }); + } + } + } + + let mut png_image_data = Vec::new(); + let encoder = image::png::PNGEncoder::new(&mut png_image_data); + if let Err(e) = encoder.encode(&image.into_vec(), width, height, image::ColorType::Rgba8) { + error!("failed to encode sixel data into png: {}", e); + return; + } + + let image_data = Arc::new(ImageData::with_raw_data(png_image_data)); + self.assign_image_to_cells(width, height, image_data); + } + + fn assign_image_to_cells(&mut self, width: u32, height: u32, image_data: Arc) { + 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_in_cells = (width as f32 / cell_pixel_width as f32).ceil() as usize; + let height_in_cells = (height as f32 / cell_pixel_height as f32).ceil() as usize; + + let mut ypos = NotNan::new(0.0).unwrap(); + let cursor_x = self.cursor.x; + let x_delta = 1.0 / (width as f32 / (self.pixel_width as f32 / physical_cols as f32)); + let y_delta = 1.0 / (height as f32 / (self.pixel_height as f32 / physical_rows as f32)); + debug!( + "image is {}x{} cells, {}x{} pixels", + width_in_cells, height_in_cells, width, height + ); + for _ in 0..height_in_cells { + let mut xpos = NotNan::new(0.0).unwrap(); + let cursor_y = self.cursor.y; + debug!( + "setting cells for y={} x=[{}..{}]", + cursor_y, + cursor_x, + cursor_x + width_in_cells + ); + for x in 0..width_in_cells { + self.screen_mut().set_cell( + cursor_x + x, + cursor_y, // + y as VisibleRowIndex, + &Cell::new( + ' ', + CellAttributes::default() + .set_image(Some(Box::new(ImageCell::new( + TextureCoordinate::new(xpos, ypos), + TextureCoordinate::new(xpos + x_delta, ypos + y_delta), + image_data.clone(), + )))) + .clone(), + ), + ); + xpos += x_delta; + } + ypos += y_delta; + self.new_line(false); + } + } fn set_image(&mut self, image: ITermFileData) { if !image.inline { @@ -1068,73 +1231,8 @@ impl TerminalState { (Some(w), Some(h)) => (w, h), }; - let width_in_cells = (width as f32 / cell_pixel_width as f32).ceil() as usize; - let height_in_cells = (height as f32 / cell_pixel_height as f32).ceil() as usize; - - // TODO: defer this to the actual renderer - /* - let available_pixel_width = width_in_cells * cell_pixel_width; - let available_pixel_height = height_in_cells * cell_pixel_height; - - let resized_image = if image.preserve_aspect_ratio { - let resized = decoded_image.resize( - available_pixel_width as u32, - available_pixel_height as u32, - image::FilterType::Lanczos3, - ); - // Pad with black bars to preserve aspect ratio - // Assumption: new_rgba8 returns black/transparent pixels by default. - let dest = DynamicImage::new_rgba8(available_pixel_width, available_pixel_height); - dest.copy_from(resized, 0, 0); - dest - } else { - decoded_image.resize_exact( - available_pixel_width as u32, - available_pixel_height as u32, - image::FilterType::Lanczos3, - ) - }; - */ - let image_data = Arc::new(ImageData::with_raw_data(image.data)); - - let mut ypos = NotNan::new(0.0).unwrap(); - let cursor_x = self.cursor.x; - let x_delta = 1.0 / (width as f32 / (self.pixel_width as f32 / physical_cols as f32)); - let y_delta = 1.0 / (height as f32 / (self.pixel_height as f32 / physical_rows as f32)); - debug!( - "image is {}x{} cells, {}x{} pixels", - width_in_cells, height_in_cells, width, height - ); - for _ in 0..height_in_cells { - let mut xpos = NotNan::new(0.0).unwrap(); - let cursor_y = self.cursor.y; - debug!( - "setting cells for y={} x=[{}..{}]", - cursor_y, - cursor_x, - cursor_x + width_in_cells - ); - for x in 0..width_in_cells { - self.screen_mut().set_cell( - cursor_x + x, - cursor_y, // + y as VisibleRowIndex, - &Cell::new( - ' ', - CellAttributes::default() - .set_image(Some(Box::new(ImageCell::new( - TextureCoordinate::new(xpos, ypos), - TextureCoordinate::new(xpos + x_delta, ypos + y_delta), - image_data.clone(), - )))) - .clone(), - ), - ); - xpos += x_delta; - } - ypos += y_delta; - self.new_line(false); - } + self.assign_image_to_cells(width as u32, height as u32, image_data); // FIXME: check cursor positioning in iterm /* @@ -1962,7 +2060,7 @@ impl<'a> Performer<'a> { self.dec_auto_wrap = true; self.dec_origin_mode = false; self.application_cursor_keys = false; - self.sixel_scrolling = false; + self.sixel_scrolling = true; self.dec_ansi_mode = false; self.application_keypad = false; self.bracketed_paste = false; diff --git a/termwiz/src/escape/mod.rs b/termwiz/src/escape/mod.rs index f008c6300..feb3955af 100644 --- a/termwiz/src/escape/mod.rs +++ b/termwiz/src/escape/mod.rs @@ -104,6 +104,48 @@ pub struct Sixel { pub data: Vec, } +impl Sixel { + /// Returns the width, height of the image + pub fn dimensions(&self) -> (u32, u32) { + if let (Some(w), Some(h)) = (self.pixel_width, self.pixel_height) { + return (w, h); + } + + // Compute it by evaluating the sixel data + let mut max_x = 0; + let mut max_y = 0; + let mut x = 0; + let mut rows = 1; + + for d in &self.data { + match d { + SixelData::Data(_) => { + max_y = max_y.max(rows * 6); + x += 1 + } + SixelData::Repeat { repeat_count, .. } => { + max_y = max_y.max(rows * 6); + x += repeat_count + } + SixelData::SelectColorMapEntry(_) + | SixelData::DefineColorMapRGB { .. } + | SixelData::DefineColorMapHSL { .. } => {} + SixelData::NewLine => { + max_x = max_x.max(x); + x = 0; + rows += 1; + } + SixelData::CarriageReturn => { + max_x = max_x.max(x); + x = 0; + } + } + } + + (max_x, max_y) + } +} + impl Display for Sixel { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { if self.pixel_width.is_some() { @@ -167,12 +209,12 @@ pub enum SixelData { /// Set the specified color map entry to the specified /// linear RGB color value DefineColorMapRGB { - color_number: u8, + color_number: u16, rgb: crate::color::RgbColor, }, - DefineColorMapHLS { - color_number: u8, + DefineColorMapHSL { + color_number: u16, /// 0 to 360 degrees hue_angle: u16, /// 0 to 100 @@ -182,7 +224,7 @@ pub enum SixelData { }, /// Select the numbered color from the color map entry - SelectColorMapEntry(u8), + SelectColorMapEntry(u16), /// Move the x position to the left page border of the /// current sixel line. @@ -211,7 +253,7 @@ impl Display for SixelData { (b * 100.0) as u8 ) } - Self::DefineColorMapHLS { + Self::DefineColorMapHSL { color_number, hue_angle, lightness, diff --git a/termwiz/src/escape/parser/mod.rs b/termwiz/src/escape/parser/mod.rs index 96e7d2d7f..69d82defd 100644 --- a/termwiz/src/escape/parser/mod.rs +++ b/termwiz/src/escape/parser/mod.rs @@ -172,7 +172,7 @@ impl<'a, F: FnMut(Action)> VTActor for Performer<'a, F> { fn dcs_unhook(&mut self) { if let Some(mut sixel) = self.state.sixel.take() { - sixel.tick(true); + sixel.finish(); (self.callback)(Action::Sixel(Box::new(sixel.sixel))); } else { (self.callback)(Action::DeviceControl(DeviceControlMode::Exit)); @@ -240,7 +240,7 @@ impl SixelBuilder { let repeat_re = Regex::new("^!(\\d+)([\x3f-\x7e])").unwrap(); let raster_re = Regex::new("^\"(\\d+);(\\d+);(\\d+);(\\d+)").unwrap(); let colordef_re = Regex::new("^#(\\d+);(\\d+);(\\d+);(\\d+);(\\d+)").unwrap(); - let coloruse_re = Regex::new("^#(\\d+)([^;]|$)").unwrap(); + let coloruse_re = Regex::new("^#(\\d+)([^;\\d]|$)").unwrap(); Self { sixel: Sixel { @@ -262,10 +262,9 @@ impl SixelBuilder { fn push(&mut self, data: u8) { self.buf.push(data); - self.tick(false); } - fn tick(&mut self, is_final: bool) { + fn finish(&mut self) { fn cap_int(m: regex::bytes::Match) -> Option { let bytes = m.as_bytes(); // Safe because we matched digits from the regex @@ -273,36 +272,33 @@ impl SixelBuilder { s.parse::().ok() } - while !self.buf.is_empty() { - let data = self.buf[0]; + let mut remainder = &self.buf[..]; + + while !remainder.is_empty() { + let data = remainder[0]; if data == b'$' { self.sixel.data.push(SixelData::CarriageReturn); - self.buf.remove(0); + remainder = &remainder[1..]; continue; } if data == b'-' { self.sixel.data.push(SixelData::NewLine); - self.buf.remove(0); + remainder = &remainder[1..]; continue; } if data >= 0x3f && data <= 0x7e { self.sixel.data.push(SixelData::Data(data - 0x3f)); - self.buf.remove(0); + remainder = &remainder[1..]; continue; } - if let Some(c) = self.raster_re.captures(&self.buf) { + if let Some(c) = self.raster_re.captures(remainder) { let all = c.get(0).unwrap(); let matched_len = all.as_bytes().len(); - if !is_final && matched_len == self.buf.len() { - // ambiguous match - return; - } - let pan = cap_int(c.get(1).unwrap()).unwrap_or(2); let pad = cap_int(c.get(2).unwrap()).unwrap_or(1); let pixel_width = cap_int(c.get(3).unwrap()).unwrap_or(0); @@ -312,22 +308,18 @@ impl SixelBuilder { self.sixel.pad = pad; self.sixel.pixel_width.replace(pixel_width); self.sixel.pixel_height.replace(pixel_height); + self.sixel + .data + .reserve(pixel_width as usize * pixel_height as usize); - for _ in 0..matched_len { - self.buf.remove(0); - } + remainder = &remainder[matched_len..]; continue; } - if let Some(c) = self.coloruse_re.captures(&self.buf) { + if let Some(c) = self.coloruse_re.captures(remainder) { let all = c.get(0).unwrap(); let matched_len = all.as_bytes().len(); - if !is_final && matched_len == self.buf.len() { - // ambiguous match - return; - } - let color_number = cap_int(c.get(1).unwrap()).unwrap_or(0); self.sixel @@ -336,21 +328,14 @@ impl SixelBuilder { let pop_len = matched_len - c.get(2).unwrap().as_bytes().len(); - for _ in 0..pop_len { - self.buf.remove(0); - } + remainder = &remainder[pop_len..]; continue; } - if let Some(c) = self.colordef_re.captures(&self.buf) { + if let Some(c) = self.colordef_re.captures(remainder) { let all = c.get(0).unwrap(); let matched_len = all.as_bytes().len(); - if !is_final && matched_len == self.buf.len() { - // ambiguous match - return; - } - let color_number = cap_int(c.get(1).unwrap()).unwrap_or(0); let system = cap_int(c.get(2).unwrap()).unwrap_or(1); let a = cap_int(c.get(3).unwrap()).unwrap_or(0); @@ -358,7 +343,7 @@ impl SixelBuilder { let c = cap_int(c.get(5).unwrap()).unwrap_or(0); if system == 1 { - self.sixel.data.push(SixelData::DefineColorMapHLS { + self.sixel.data.push(SixelData::DefineColorMapHSL { color_number, hue_angle: a, lightness: b, @@ -374,13 +359,11 @@ impl SixelBuilder { .push(SixelData::DefineColorMapRGB { color_number, rgb }); } - for _ in 0..matched_len { - self.buf.remove(0); - } + remainder = &remainder[matched_len..]; continue; } - if let Some(c) = self.repeat_re.captures(&self.buf) { + if let Some(c) = self.repeat_re.captures(remainder) { let all = c.get(0).unwrap(); let matched_len = all.as_bytes().len(); @@ -389,12 +372,16 @@ impl SixelBuilder { self.sixel .data .push(SixelData::Repeat { repeat_count, data }); - for _ in 0..matched_len { - self.buf.remove(0); - } + remainder = &remainder[matched_len..]; continue; } + log::error!( + "finished sixel parse with {} bytes pending {:?}", + remainder.len(), + std::str::from_utf8(&remainder[0..24.min(remainder.len())]) + ); + break; } }