prefer to hold rgba8 rather than png data for kitty, sixel
I noticed when running the notcurses demo that we're spending a decent amount of time decoding png data whenever we need to re-do the texture atlas. Let's avoid that by allowing for ImageData at the termwiz layer to represent both the image file format and decoded rgba8 data. This commit is a bit muddy and also includes some stuff to try to delete placements from the model. It's not perfect by any means--more expensive than I want, and there's something funky that causes a large number of images to build up during some phases of the demo. refs: #986
This commit is contained in:
1 parent
503d3df368
commit
94d409d340
8 files changed
+308
-122
No files matched your search
+131
-39
@@ -5,7 +5,7 @@ use super::*;
|
||||
use crate::color::{ColorPalette, RgbColor};
|
||||
use anyhow::{bail, Context};
|
||||
use image::imageops::FilterType;
|
||||
use image::{GenericImageView, ImageFormat};
|
||||
use image::{DynamicImage, GenericImageView, ImageFormat, RgbImage, RgbaImage};
|
||||
use log::{debug, error};
|
||||
use num_traits::{FromPrimitive, ToPrimitive};
|
||||
use ordered_float::NotNan;
|
||||
@@ -15,8 +15,8 @@ use std::sync::mpsc::{channel, Sender};
|
||||
use std::sync::Arc;
|
||||
use terminfo::{Database, Value};
|
||||
use termwiz::escape::apc::{
|
||||
KittyImage, KittyImageCompression, KittyImageData, KittyImageFormat, KittyImagePlacement,
|
||||
KittyImageTransmit, KittyImageVerbosity,
|
||||
KittyImage, KittyImageCompression, KittyImageData, KittyImageDelete, KittyImageFormat,
|
||||
KittyImagePlacement, KittyImageTransmit, KittyImageVerbosity,
|
||||
};
|
||||
use termwiz::escape::csi::{
|
||||
Cursor, CursorStyle, DecPrivateMode, DecPrivateModeCode, Device, Edit, EraseInDisplay,
|
||||
@@ -31,7 +31,7 @@ use termwiz::escape::{
|
||||
Action, ControlCode, DeviceControlMode, Esc, EscCode, OneBased, OperatingSystemCommand, Sixel,
|
||||
SixelData, CSI,
|
||||
};
|
||||
use termwiz::image::{ImageCell, ImageData, TextureCoordinate};
|
||||
use termwiz::image::{ImageCell, ImageData, ImageDataType, TextureCoordinate};
|
||||
use termwiz::surface::{CursorShape, CursorVisibility};
|
||||
use url::Url;
|
||||
|
||||
@@ -45,7 +45,8 @@ lazy_static::lazy_static! {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct PlacementInfo {
|
||||
first_row: StableRowIndex,
|
||||
num_cells: usize,
|
||||
rows: usize,
|
||||
cols: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -75,6 +76,9 @@ struct ImageAttachParams {
|
||||
columns: Option<usize>,
|
||||
rows: Option<usize>,
|
||||
|
||||
image_id: u32,
|
||||
placement_id: Option<u32>,
|
||||
|
||||
style: ImageAttachStyle,
|
||||
|
||||
data: Arc<ImageData>,
|
||||
@@ -1599,7 +1603,7 @@ impl TerminalState {
|
||||
}
|
||||
|
||||
fn coalesce_kitty_accumulation(&mut self, img: KittyImage) -> anyhow::Result<KittyImage> {
|
||||
log::info!(
|
||||
log::trace!(
|
||||
"coalesce: accumulator={:#?} img:{:#?}",
|
||||
self.kitty_img.accumulator,
|
||||
img
|
||||
@@ -1696,12 +1700,12 @@ impl TerminalState {
|
||||
};
|
||||
|
||||
self.kitty_img.max_image_id = self.kitty_img.max_image_id.max(image_id);
|
||||
log::info!("transmit {:?}", transmit);
|
||||
|
||||
let data = transmit
|
||||
.data
|
||||
.load_data()
|
||||
.context("data should have been materialized in coalesce_kitty_accumulation")?;
|
||||
log::info!("data is {} in size", data.len());
|
||||
|
||||
let data = match transmit.compression {
|
||||
KittyImageCompression::None => data,
|
||||
@@ -1717,20 +1721,37 @@ impl TerminalState {
|
||||
}
|
||||
};
|
||||
|
||||
let format = match transmit.format {
|
||||
Some(KittyImageFormat::Rgb) => image::ColorType::Rgb8,
|
||||
_ => image::ColorType::Rgba8,
|
||||
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 mut png_image_data = vec![];
|
||||
let encoder = image::png::PngEncoder::new(&mut png_image_data);
|
||||
encoder
|
||||
.encode(&data, width, height, format)
|
||||
.context("encode data as PNG")?;
|
||||
let image_data = ImageDataType::Rgba8 {
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
};
|
||||
|
||||
self.raw_image_to_image_data(png_image_data.into_boxed_slice())
|
||||
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)
|
||||
}
|
||||
Some(KittyImageFormat::Png) => self.raw_image_to_image_data(data.into_boxed_slice()),
|
||||
};
|
||||
|
||||
self.kitty_img.id_to_data.insert(image_id, img);
|
||||
@@ -1767,6 +1788,14 @@ impl TerminalState {
|
||||
.ok_or_else(|| anyhow::anyhow!("image_number has no matching image id"))?,
|
||||
};
|
||||
|
||||
log::warn!(
|
||||
"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
|
||||
@@ -1774,8 +1803,13 @@ impl TerminalState {
|
||||
.ok_or_else(|| anyhow::anyhow!("no matching image id"))?,
|
||||
);
|
||||
|
||||
let decoded = image::load_from_memory(img.data()).context("decode png")?;
|
||||
let (image_width, image_height) = decoded.dimensions();
|
||||
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();
|
||||
|
||||
@@ -1793,6 +1827,8 @@ impl TerminalState {
|
||||
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
|
||||
@@ -1893,6 +1929,29 @@ impl TerminalState {
|
||||
} => {
|
||||
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.id_to_data.remove(&image_id);
|
||||
}
|
||||
}
|
||||
KittyImage::Delete { what, verbosity } => {
|
||||
log::warn!("unhandled KittyImage::Delete {:?} {:?}", what, verbosity);
|
||||
}
|
||||
@@ -1901,6 +1960,30 @@ impl TerminalState {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kitty_remove_placement(&mut self, image_id: u32, placement_id: Option<u32>) {
|
||||
if let Some(info) = self.kitty_img.placements.remove(&(image_id, placement_id)) {
|
||||
let screen = self.screen_mut();
|
||||
for idx in
|
||||
screen.stable_range(&(info.first_row..info.first_row + info.rows as StableRowIndex))
|
||||
{
|
||||
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();
|
||||
}
|
||||
} else {
|
||||
log::warn!("no placement matched i={} p={:?}", image_id, placement_id);
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"after remove: there are {} placements, {} images",
|
||||
self.kitty_img.placements.len(),
|
||||
self.kitty_img.id_to_data.len()
|
||||
);
|
||||
}
|
||||
|
||||
fn sixel(&mut self, sixel: Box<Sixel>) {
|
||||
let (width, height) = sixel.dimensions();
|
||||
|
||||
@@ -1913,14 +1996,14 @@ impl TerminalState {
|
||||
};
|
||||
|
||||
let mut image = if sixel.background_is_transparent {
|
||||
image::RgbaImage::new(width, height)
|
||||
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();
|
||||
image::RgbaImage::from_pixel(width, height, [red, green, blue, 0xffu8].into())
|
||||
RgbaImage::from_pixel(width, height, [red, green, blue, 0xffu8].into())
|
||||
};
|
||||
|
||||
let mut x = 0;
|
||||
@@ -1997,14 +2080,13 @@ impl TerminalState {
|
||||
}
|
||||
}
|
||||
|
||||
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 = ImageDataType::Rgba8 {
|
||||
width,
|
||||
height,
|
||||
data: image.into_vec().into_boxed_slice(),
|
||||
};
|
||||
|
||||
let image_data = self.raw_image_to_image_data(png_image_data.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,
|
||||
@@ -2019,20 +2101,25 @@ impl TerminalState {
|
||||
data: image_data,
|
||||
style: ImageAttachStyle::Sixel,
|
||||
z_index: 0,
|
||||
image_id: 0,
|
||||
placement_id: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// cache recent images and avoid assigning a new id for repeated data!
|
||||
fn raw_image_to_image_data(&mut self, raw_data: Box<[u8]>) -> Arc<ImageData> {
|
||||
fn raw_image_to_image_data(&mut self, data: ImageDataType) -> Arc<ImageData> {
|
||||
use sha2::Digest;
|
||||
let mut hasher = sha2::Sha256::new();
|
||||
hasher.update(&raw_data);
|
||||
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_raw_data(raw_data));
|
||||
let image_data = Arc::new(ImageData::with_data(data));
|
||||
self.image_cache.put(key, Arc::clone(&image_data));
|
||||
image_data
|
||||
}
|
||||
@@ -2060,7 +2147,6 @@ impl TerminalState {
|
||||
.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 num_cells = width_in_cells * height_in_cells;
|
||||
|
||||
let mut ypos =
|
||||
NotNan::new(params.source_origin_y as f32 / params.image_height as f32).unwrap();
|
||||
@@ -2104,6 +2190,8 @@ impl TerminalState {
|
||||
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),
|
||||
@@ -2136,7 +2224,8 @@ impl TerminalState {
|
||||
|
||||
PlacementInfo {
|
||||
first_row,
|
||||
num_cells,
|
||||
rows: height_in_cells,
|
||||
cols: width_in_cells,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2242,18 +2331,19 @@ impl TerminalState {
|
||||
(true, ImageFormat::Gif) | (true, ImageFormat::Png) | (false, _) => {
|
||||
// Don't resample things that might be animations,
|
||||
// or things that don't need resampling
|
||||
image.data
|
||||
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 mut data = vec![];
|
||||
match im.write_to(&mut data, ImageFormat::Png) {
|
||||
Ok(_) => data.into_boxed_slice(),
|
||||
Err(_) => image.data,
|
||||
let data = im.into_rgba8().into_vec().into_boxed_slice();
|
||||
ImageDataType::Rgba8 {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
data,
|
||||
}
|
||||
}
|
||||
Err(_) => image.data,
|
||||
Err(_) => ImageDataType::EncodedFile(image.data),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -2272,6 +2362,8 @@ impl TerminalState {
|
||||
rows: None,
|
||||
data: image_data,
|
||||
style: ImageAttachStyle::Iterm,
|
||||
image_id: 0,
|
||||
placement_id: None,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -378,6 +378,14 @@ impl CellAttributes {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn detach_image_with_placement(&mut self, image_id: u32, placement_id: Option<u32>) {
|
||||
if let Some(fat) = self.fat.as_mut() {
|
||||
fat.image
|
||||
.retain(|im| !im.matches_placement(image_id, placement_id));
|
||||
}
|
||||
self.deallocate_fat_attributes_if_none();
|
||||
}
|
||||
|
||||
/// Add an image attachement, preserving any existing attachments.
|
||||
/// The list of images is maintained in z-index order
|
||||
pub fn attach_image(&mut self, image: Box<ImageCell>) -> &mut Self {
|
||||
|
||||
+65
-18
@@ -3,13 +3,13 @@
|
||||
//! with image data.
|
||||
//! We're targeting the iTerm image protocol initially, with sixel as an obvious
|
||||
//! follow up.
|
||||
// Kitty has an extensive and complex graphics protocol that seems difficult
|
||||
// to model. Its docs are here:
|
||||
// <https://github.com/kovidgoyal/kitty/blob/master/docs/graphics-protocol.rst>
|
||||
// Both iTerm2 and Sixel appear to have semantics that allow replacing the
|
||||
// contents of a single chararcter cell with image data, whereas the kitty
|
||||
// protocol appears to track the images out of band as attachments with
|
||||
// z-order.
|
||||
//! Kitty has an extensive and complex graphics protocol
|
||||
//! whose docs are here:
|
||||
//! <https://github.com/kovidgoyal/kitty/blob/master/docs/graphics-protocol.rst>
|
||||
//! Both iTerm2 and Sixel appear to have semantics that allow replacing the
|
||||
//! contents of a single chararcter cell with image data, whereas the kitty
|
||||
//! protocol appears to track the images out of band as attachments with
|
||||
//! z-order.
|
||||
|
||||
use ordered_float::NotNan;
|
||||
#[cfg(feature = "use_serde")]
|
||||
@@ -88,6 +88,9 @@ pub struct ImageCell {
|
||||
/// of the cell
|
||||
display_offset_x: u32,
|
||||
display_offset_y: u32,
|
||||
|
||||
image_id: u32,
|
||||
placement_id: Option<u32>,
|
||||
}
|
||||
|
||||
impl ImageCell {
|
||||
@@ -96,7 +99,7 @@ impl ImageCell {
|
||||
bottom_right: TextureCoordinate,
|
||||
data: Arc<ImageData>,
|
||||
) -> Self {
|
||||
Self::with_z_index(top_left, bottom_right, data, 0, 0, 0)
|
||||
Self::with_z_index(top_left, bottom_right, data, 0, 0, 0, 0, None)
|
||||
}
|
||||
|
||||
pub fn with_z_index(
|
||||
@@ -106,6 +109,8 @@ impl ImageCell {
|
||||
z_index: i32,
|
||||
display_offset_x: u32,
|
||||
display_offset_y: u32,
|
||||
image_id: u32,
|
||||
placement_id: Option<u32>,
|
||||
) -> Self {
|
||||
Self {
|
||||
top_left,
|
||||
@@ -114,9 +119,15 @@ impl ImageCell {
|
||||
z_index,
|
||||
display_offset_x,
|
||||
display_offset_y,
|
||||
image_id,
|
||||
placement_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn matches_placement(&self, image_id: u32, placement_id: Option<u32>) -> bool {
|
||||
self.image_id == image_id && self.placement_id == placement_id
|
||||
}
|
||||
|
||||
pub fn top_left(&self) -> TextureCoordinate {
|
||||
self.top_left
|
||||
}
|
||||
@@ -146,30 +157,66 @@ static IMAGE_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicU
|
||||
|
||||
#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ImageData {
|
||||
id: usize,
|
||||
/// The image data bytes. Data is the native image file format
|
||||
data: Box<[u8]>,
|
||||
pub enum ImageDataType {
|
||||
/// Data is in the native image file format
|
||||
/// (best for file formats that have animated content)
|
||||
EncodedFile(Box<[u8]>),
|
||||
/// Data is RGBA u8 data
|
||||
Rgba8 {
|
||||
data: Box<[u8]>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ImageData {
|
||||
impl std::fmt::Debug for ImageDataType {
|
||||
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
fmt.debug_struct("ImageData")
|
||||
.field("id", &self.id)
|
||||
.field("data_of_len", &self.data.len())
|
||||
.finish()
|
||||
match self {
|
||||
Self::EncodedFile(data) => fmt
|
||||
.debug_struct("EncodedFile")
|
||||
.field("data_of_len", &data.len())
|
||||
.finish(),
|
||||
Self::Rgba8 {
|
||||
data,
|
||||
width,
|
||||
height,
|
||||
} => fmt
|
||||
.debug_struct("Rgba8")
|
||||
.field("data_of_len", &data.len())
|
||||
.field("width", &width)
|
||||
.field("height", &height)
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImageData {
|
||||
id: usize,
|
||||
data: ImageDataType,
|
||||
}
|
||||
|
||||
impl ImageData {
|
||||
/// Create a new ImageData struct with the provided raw data.
|
||||
pub fn with_raw_data(data: Box<[u8]>) -> Self {
|
||||
Self::with_data(ImageDataType::EncodedFile(data))
|
||||
}
|
||||
|
||||
pub fn with_data(data: ImageDataType) -> Self {
|
||||
let id = IMAGE_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed);
|
||||
Self { id, data }
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
match &self.data {
|
||||
ImageDataType::EncodedFile(d) => d.len(),
|
||||
ImageDataType::Rgba8 { data, .. } => data.len(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn data(&self) -> &[u8] {
|
||||
pub fn data(&self) -> &ImageDataType {
|
||||
&self.data
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::color::{ColorAttribute, ColorSpec};
|
||||
use crate::escape::csi::{Cursor, Edit, EraseInDisplay, EraseInLine, Sgr, CSI};
|
||||
use crate::escape::osc::{ITermDimension, ITermFileData, ITermProprietary, OperatingSystemCommand};
|
||||
use crate::escape::OneBased;
|
||||
use crate::image::TextureCoordinate;
|
||||
use crate::image::{ImageDataType, TextureCoordinate};
|
||||
use crate::render::RenderTty;
|
||||
use crate::surface::{Change, CursorShape, CursorVisibility, Position};
|
||||
use crate::Result;
|
||||
@@ -567,7 +567,12 @@ impl TerminfoRenderer {
|
||||
{
|
||||
// The whole image is requested, so we can send the
|
||||
// original image bytes over
|
||||
image.image.data().to_vec().into_boxed_slice()
|
||||
match image.image.data() {
|
||||
ImageDataType::EncodedFile(data) => {
|
||||
data.to_vec().into_boxed_slice()
|
||||
}
|
||||
ImageDataType::Rgba8 { .. } => unimplemented!(),
|
||||
}
|
||||
} else {
|
||||
// TODO: slice out the requested region of the image,
|
||||
// and encode as a PNG.
|
||||
|
||||
@@ -20,7 +20,7 @@ use std::ops::Range;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use termwiz::image::ImageData;
|
||||
use termwiz::image::{ImageData, ImageDataType};
|
||||
use tiny_skia::{FillRule, Paint, Path, PathBuilder, PixmapMut, Stroke, Transform};
|
||||
use wezterm_font::units::*;
|
||||
use wezterm_font::{FontConfiguration, GlyphInfo};
|
||||
@@ -3732,16 +3732,48 @@ impl BlockKey {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ImageFrameBitmap {
|
||||
Owned(::window::bitmaps::Image),
|
||||
Ref(Arc<ImageData>),
|
||||
}
|
||||
|
||||
impl BitmapImage for ImageFrameBitmap {
|
||||
unsafe fn pixel_data(&self) -> *const u8 {
|
||||
match self {
|
||||
Self::Owned(im) => im.pixel_data(),
|
||||
Self::Ref(im) => match im.data() {
|
||||
ImageDataType::EncodedFile(_) => unreachable!(),
|
||||
ImageDataType::Rgba8 { data, .. } => data.as_ptr(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn pixel_data_mut(&mut self) -> *mut u8 {
|
||||
panic!("cannot mutate ImageFrameBitmap");
|
||||
}
|
||||
|
||||
fn image_dimensions(&self) -> (usize, usize) {
|
||||
match self {
|
||||
Self::Owned(im) => im.image_dimensions(),
|
||||
Self::Ref(im) => match im.data() {
|
||||
ImageDataType::EncodedFile(_) => unreachable!(),
|
||||
ImageDataType::Rgba8 { width, height, .. } => (*width as usize, *height as usize),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ImageFrame {
|
||||
duration: Duration,
|
||||
image: ::window::bitmaps::Image,
|
||||
image: ImageFrameBitmap,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CachedImage {
|
||||
Animation(DecodedImage),
|
||||
SingleFrame,
|
||||
SingleFrame(ImageFrameBitmap),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -3756,7 +3788,7 @@ impl DecodedImage {
|
||||
let image = ::window::bitmaps::Image::new(1, 1);
|
||||
let frame = ImageFrame {
|
||||
duration: Duration::default(),
|
||||
image,
|
||||
image: ImageFrameBitmap::Owned(image),
|
||||
};
|
||||
Self {
|
||||
frame_start: Instant::now(),
|
||||
@@ -3774,7 +3806,11 @@ impl DecodedImage {
|
||||
let (w, h) = image.dimensions();
|
||||
let width = w as usize;
|
||||
let height = h as usize;
|
||||
let image = ::window::bitmaps::Image::from_raw(width, height, image.into_vec());
|
||||
let image = ImageFrameBitmap::Owned(::window::bitmaps::Image::from_raw(
|
||||
width,
|
||||
height,
|
||||
image.into_vec(),
|
||||
));
|
||||
ImageFrame { duration, image }
|
||||
})
|
||||
.collect();
|
||||
@@ -3786,11 +3822,20 @@ impl DecodedImage {
|
||||
}
|
||||
|
||||
fn with_single(image_data: &Arc<ImageData>) -> anyhow::Result<Self> {
|
||||
let image = image::load_from_memory(image_data.data())?.to_rgba8();
|
||||
let (width, height) = image.dimensions();
|
||||
let width = width as usize;
|
||||
let height = height as usize;
|
||||
let image = ::window::bitmaps::Image::from_raw(width, height, image.into_vec());
|
||||
let image = match image_data.data() {
|
||||
ImageDataType::EncodedFile(data) => {
|
||||
let image = image::load_from_memory(data)?.to_rgba8();
|
||||
let (width, height) = image.dimensions();
|
||||
let width = width as usize;
|
||||
let height = height as usize;
|
||||
ImageFrameBitmap::Owned(::window::bitmaps::Image::from_raw(
|
||||
width,
|
||||
height,
|
||||
image.into_vec(),
|
||||
))
|
||||
}
|
||||
ImageDataType::Rgba8 { .. } => ImageFrameBitmap::Ref(Arc::clone(image_data)),
|
||||
};
|
||||
Ok(Self {
|
||||
frame_start: Instant::now(),
|
||||
current_frame: 0,
|
||||
@@ -3802,29 +3847,34 @@ impl DecodedImage {
|
||||
}
|
||||
|
||||
fn load(image_data: &Arc<ImageData>) -> anyhow::Result<Self> {
|
||||
use image::{AnimationDecoder, ImageFormat};
|
||||
let format = image::guess_format(image_data.data())?;
|
||||
match format {
|
||||
ImageFormat::Gif => image::gif::GifDecoder::new(image_data.data())
|
||||
.and_then(|decoder| decoder.into_frames().collect_frames())
|
||||
.and_then(|frames| Ok(Self::with_frames(frames)))
|
||||
.or_else(|err| {
|
||||
log::error!(
|
||||
"Unable to parse animated gif: {:#}, trying as single frame",
|
||||
err
|
||||
);
|
||||
Self::with_single(image_data)
|
||||
}),
|
||||
ImageFormat::Png => {
|
||||
let decoder = image::png::PngDecoder::new(image_data.data())?;
|
||||
if decoder.is_apng() {
|
||||
let frames = decoder.apng().into_frames().collect_frames()?;
|
||||
Ok(Self::with_frames(frames))
|
||||
} else {
|
||||
Self::with_single(image_data)
|
||||
match image_data.data() {
|
||||
ImageDataType::Rgba8 { .. } => Self::with_single(image_data),
|
||||
ImageDataType::EncodedFile(data) => {
|
||||
use image::{AnimationDecoder, ImageFormat};
|
||||
let format = image::guess_format(data)?;
|
||||
match format {
|
||||
ImageFormat::Gif => image::gif::GifDecoder::new(&**data)
|
||||
.and_then(|decoder| decoder.into_frames().collect_frames())
|
||||
.and_then(|frames| Ok(Self::with_frames(frames)))
|
||||
.or_else(|err| {
|
||||
log::error!(
|
||||
"Unable to parse animated gif: {:#}, trying as single frame",
|
||||
err
|
||||
);
|
||||
Self::with_single(image_data)
|
||||
}),
|
||||
ImageFormat::Png => {
|
||||
let decoder = image::png::PngDecoder::new(&**data)?;
|
||||
if decoder.is_apng() {
|
||||
let frames = decoder.apng().into_frames().collect_frames()?;
|
||||
Ok(Self::with_frames(frames))
|
||||
} else {
|
||||
Self::with_single(image_data)
|
||||
}
|
||||
}
|
||||
_ => Self::with_single(image_data),
|
||||
}
|
||||
}
|
||||
_ => Self::with_single(image_data),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3907,7 +3957,7 @@ impl GlyphCache<SrgbTexture2d> {
|
||||
image_cache: LruCache::new(
|
||||
"glyph_cache.image_cache.hit.rate",
|
||||
"glyph_cache.image_cache.miss.rate",
|
||||
16,
|
||||
64, // FIXME: make configurable
|
||||
),
|
||||
frame_cache: HashMap::new(),
|
||||
atlas,
|
||||
@@ -3916,15 +3966,6 @@ impl GlyphCache<SrgbTexture2d> {
|
||||
block_glyphs: HashMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.atlas.clear();
|
||||
// self.image_cache.clear(); - relatively expensive to re-populate
|
||||
self.frame_cache.clear();
|
||||
self.glyph_cache.clear();
|
||||
self.line_glyphs.clear();
|
||||
self.block_glyphs.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Texture2d> GlyphCache<T> {
|
||||
@@ -4173,13 +4214,17 @@ impl<T: Texture2d> GlyphCache<T> {
|
||||
let id = image_data.id();
|
||||
if let Some(cached) = self.image_cache.get_mut(&id) {
|
||||
match cached {
|
||||
CachedImage::SingleFrame => {
|
||||
CachedImage::SingleFrame(im) => {
|
||||
// We can simply use the frame cache to manage
|
||||
// the texture space; the frame is always 0 for
|
||||
// a single frame
|
||||
if let Some(sprite) = self.frame_cache.get(&(id, 0)) {
|
||||
return Ok((sprite.clone(), None));
|
||||
}
|
||||
let sprite = self.atlas.allocate_with_padding(im, padding)?;
|
||||
self.frame_cache.insert((id, 0), sprite.clone());
|
||||
|
||||
return Ok((sprite, None));
|
||||
}
|
||||
CachedImage::Animation(decoded) => {
|
||||
let mut next = None;
|
||||
@@ -4221,7 +4266,8 @@ impl<T: Texture2d> GlyphCache<T> {
|
||||
}
|
||||
}
|
||||
|
||||
let decoded =
|
||||
// FIXME: add latency metric around this load
|
||||
let mut decoded =
|
||||
DecodedImage::load(image_data).or_else(|e| -> anyhow::Result<DecodedImage> {
|
||||
log::debug!("Failed to decode image: {:#}", e);
|
||||
// Use a placeholder instead
|
||||
@@ -4236,7 +4282,8 @@ impl<T: Texture2d> GlyphCache<T> {
|
||||
self.image_cache.put(id, CachedImage::Animation(decoded));
|
||||
Ok((sprite, next))
|
||||
} else {
|
||||
self.image_cache.put(id, CachedImage::SingleFrame);
|
||||
self.image_cache
|
||||
.put(id, CachedImage::SingleFrame(decoded.frames.remove(0).image));
|
||||
Ok((sprite, None))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,13 +242,6 @@ impl RenderState {
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
pub fn clear_texture_atlas(&mut self, metrics: &RenderMetrics) -> anyhow::Result<()> {
|
||||
let mut glyph_cache = self.glyph_cache.borrow_mut();
|
||||
glyph_cache.clear();
|
||||
self.util_sprites = UtilSprites::new(&mut glyph_cache, metrics)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn recreate_texture_atlas(
|
||||
&mut self,
|
||||
fonts: &Rc<FontConfiguration>,
|
||||
|
||||
@@ -42,7 +42,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use termwiz::hyperlink::Hyperlink;
|
||||
use termwiz::image::ImageData;
|
||||
use termwiz::image::{ImageData, ImageDataType};
|
||||
use wezterm_font::FontConfiguration;
|
||||
use wezterm_term::color::ColorPalette;
|
||||
use wezterm_term::input::LastMouseClick;
|
||||
@@ -357,8 +357,11 @@ fn reload_background_image(
|
||||
Some(p) => match std::fs::read(p) {
|
||||
Ok(data) => {
|
||||
if let Some(existing) = image {
|
||||
if existing.data() == &*data {
|
||||
return Some(Arc::clone(existing));
|
||||
match existing.data() {
|
||||
ImageDataType::EncodedFile(d) if &**d == &*data => {
|
||||
return Some(Arc::clone(existing));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(Arc::new(ImageData::with_raw_data(data.into_boxed_slice())))
|
||||
|
||||
@@ -1482,15 +1482,6 @@ impl super::TermWindow {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_texture_atlas(&mut self) -> anyhow::Result<()> {
|
||||
log::trace!("clear_texture_atlas");
|
||||
self.shape_cache.borrow_mut().clear();
|
||||
if let Some(render_state) = self.render_state.as_mut() {
|
||||
render_state.clear_texture_atlas(&self.render_metrics)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn recreate_texture_atlas(&mut self, size: Option<usize>) -> anyhow::Result<()> {
|
||||
self.shape_cache.borrow_mut().clear();
|
||||
if let Some(render_state) = self.render_state.as_mut() {
|
||||
|
||||
Reference in new issue
Block a user