1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
// Copyright 2020 Sebastian Wiesner <sebastian@swsnr.de>
// Copyright 2019 Fabian Spillner <fabian.spillner@gmail.com>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Kitty terminal extensions.
use std::io::{Error, ErrorKind, Write};
use std::str;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use thiserror::Error;
use tracing::{event, instrument, Level};
use crate::resources::{InlineImageProtocol, MimeData};
use crate::terminal::size::PixelSize;
/// An error which occurred while rendering or writing an image with the Kitty image protocol.
#[derive(Debug, Error)]
pub enum KittyImageError {
/// A general IO error.
#[error("Failed to render kitty image: {0}")]
IoError(#[from] std::io::Error),
/// Processing a pixel image, e.g. for format conversion, failed
#[error("Failed to process pixel image: {0}")]
#[cfg(feature = "image-processing")]
ImageError(#[from] image::ImageError),
}
impl From<KittyImageError> for std::io::Error {
fn from(value: KittyImageError) -> Self {
std::io::Error::new(ErrorKind::Other, value)
}
}
/// The image format (PNG, RGB or RGBA) of the image bytes.
enum KittyFormat {
Png,
#[cfg(feature = "image-processing")]
Rgb,
#[cfg(feature = "image-processing")]
Rgba,
}
impl KittyFormat {
/// Return the control data value of the image format.
/// See the [documentation] for the reference and explanation.
///
/// [documentation]: https://sw.kovidgoyal.net/kitty/graphics-protocol.html#transferring-pixel-data
fn control_data_value(&self) -> &str {
match *self {
KittyFormat::Png => "100",
#[cfg(feature = "image-processing")]
KittyFormat::Rgb => "24",
#[cfg(feature = "image-processing")]
KittyFormat::Rgba => "32",
}
}
}
/// Holds the image bytes with its image format and dimensions.
struct KittyImage {
contents: Vec<u8>,
format: KittyFormat,
size: Option<PixelSize>,
}
impl KittyImage {
fn write_to(&self, writer: &mut dyn Write) -> Result<(), Error> {
let mut cmd_header: Vec<String> = vec![
"a=T".into(),
"t=d".into(),
format!("f={}", self.format.control_data_value()),
];
if let Some(size) = self.size {
cmd_header.push(format!("s={}", size.x));
cmd_header.push(format!("v={}", size.y));
}
let image_data = STANDARD.encode(&self.contents);
let image_data_chunks = image_data.as_bytes().chunks(4096);
let image_data_chunks_length = image_data_chunks.len();
for (i, data) in image_data_chunks.enumerate() {
if i < image_data_chunks_length - 1 {
cmd_header.push("m=1".into());
} else {
cmd_header.push("m=0".into());
}
write!(writer, "\x1b_G{};", cmd_header.join(","))?;
writer.write_all(data)?;
write!(writer, "\x1b\\")?;
// FIXME: Remove this? Why do we flush here?
writer.flush()?;
cmd_header.clear();
}
Ok(())
}
}
/// Provides access to printing images for kitty.
#[derive(Debug, Copy, Clone)]
pub struct KittyImages;
impl KittyImages {
/// Render mime data obtained from `url` and wrap it in a `KittyImage`.
///
/// This implemention processes the image to scale it to the given `terminal_size`, and
/// supports various pixel image types, as well as SVG.
#[cfg(feature = "image-processing")]
fn render(
self,
mime_data: MimeData,
terminal_size: PixelSize,
) -> Result<KittyImage, KittyImageError> {
use image::{GenericImageView, ImageFormat};
let image = if let Some("image/svg+xml") = mime_data.mime_type_essence() {
event!(Level::DEBUG, "Rendering mime data to SVG");
let png_data = crate::resources::svg::render_svg_to_png(&mime_data.data)?;
image::load_from_memory_with_format(&png_data, ImageFormat::Png)?
} else {
let image_format = mime_data
.mime_type
.as_ref()
.and_then(image::ImageFormat::from_mime_type);
match image_format {
// If we already have information about the mime type of the resource data let's
// use it, and trust whoever provided it to have gotten it right.
Some(format) => image::load_from_memory_with_format(&mime_data.data, format)?,
// If we don't know the mime type of the original data have image guess the format.
None => image::load_from_memory(&mime_data.data)?,
}
};
if mime_data.mime_type == Some(mime::IMAGE_PNG)
&& PixelSize::from_xy(image.dimensions()) <= terminal_size
{
event!(
Level::DEBUG,
"PNG image of appropriate size, rendering original data"
);
// If we know that the original data is in PNG format and of sufficient size we can
// discard the decoded image and instead render the original data directly.
//
// We kinda wasted the decoded image here (we do need it to check dimensions tho) but
// at least we don't have to encode it again.
Ok(self.render_as_png(mime_data.data))
} else {
event!(
Level::DEBUG,
"Image of other format or larger than terminal, rendering RGB data"
);
// The original data was not in PNG format, or we have to resize the image to terminal
// dimensions, so we need to encode the RGB data of the decoded image explicitly.
Ok(self.render_as_rgb_or_rgba(image, terminal_size))
}
}
/// Render mime data obtained from `url` and wrap it in a `KittyImage`.
///
/// This implementation does not support image processing, and only renders PNG images which
/// kitty supports directly.
#[cfg(not(feature = "image-processing"))]
fn render(
self,
mime_data: MimeData,
_terminal_size: PixelSize,
) -> Result<KittyImage, KittyImageError> {
match mime_data.mime_type {
Some(t) if t == mime::IMAGE_PNG => Ok(self.render_as_png(mime_data.data)),
_ => {
event!(
Level::DEBUG,
"Only PNG images supported without image-processing feature, but got {:?}",
mime_data.mime_type
);
Err(std::io::Error::new(
ErrorKind::Unsupported,
format!(
"Image data with mime type {:?} not supported",
mime_data.mime_type
),
)
.into())
}
}
}
/// Wrap the image bytes as PNG format in `KittyImage`.
fn render_as_png(self, contents: Vec<u8>) -> KittyImage {
KittyImage {
contents,
format: KittyFormat::Png,
size: None,
}
}
/// Render the image as RGB/RGBA format and wrap the image bytes in `KittyImage`.
///
/// If the image size exceeds `terminal_size` in either dimension scale the
/// image down to `terminal_size` (preserving aspect ratio).
#[cfg(feature = "image-processing")]
fn render_as_rgb_or_rgba(
self,
image: image::DynamicImage,
terminal_size: PixelSize,
) -> KittyImage {
use image::{ColorType, GenericImageView};
let format = match image.color() {
ColorType::L8 | ColorType::Rgb8 | ColorType::L16 | ColorType::Rgb16 => KittyFormat::Rgb,
// Default to RGBA format: We cannot match all colour types because
// ColorType is marked non-exhaustive, but RGBA is a safe default
// because we can convert any image to RGBA, at worth with additional
// runtime costs.
_ => KittyFormat::Rgba,
};
let image = if PixelSize::from_xy(image.dimensions()) <= terminal_size {
image
} else {
image.resize(
terminal_size.x,
terminal_size.y,
image::imageops::FilterType::Nearest,
)
};
let size = PixelSize::from_xy(image.dimensions());
KittyImage {
contents: match format {
KittyFormat::Rgb => image.into_rgb8().into_raw(),
_ => image.into_rgba8().into_raw(),
},
format,
size: Some(size),
}
}
}
/// Kitty's inline image protocol.
///
/// Kitty's escape sequence is like: Put the command key/value pairs together like "{}={}(,*)"
/// and write them along with the image bytes in 4096 bytes chunks to the stdout.
///
/// Its documentation gives the following python example:
///
/// ```python
/// import sys
/// from base64 import standard_b64encode
///
/// def serialize_gr_command(cmd, payload=None):
/// cmd = ','.join('{}={}'.format(k, v) for k, v in cmd.items())
/// ans = []
/// w = ans.append
/// w(b'\033_G'), w(cmd.encode('ascii'))
/// if payload:
/// w(b';')
/// w(payload)
/// w(b'\033\\')
/// return b''.join(ans)
///
/// def write_chunked(cmd, data):
/// cmd = {'a': 'T', 'f': 100}
/// data = standard_b64encode(data)
/// while data:
/// chunk, data = data[:4096], data[4096:]
/// m = 1 if data else 0
/// cmd['m'] = m
/// sys.stdout.buffer.write(serialize_gr_command(cmd, chunk))
/// sys.stdout.flush()
/// cmd.clear()
/// ```
///
/// See <https://sw.kovidgoyal.net/kitty/graphics-protocol.html#control-data-reference>
/// for reference.
impl InlineImageProtocol for KittyImages {
#[instrument(skip(self, writer, terminal_size))]
fn write_inline_image(
&self,
writer: &mut dyn Write,
resource_handler: &dyn crate::ResourceUrlHandler,
url: &url::Url,
terminal_size: &crate::TerminalSize,
) -> std::io::Result<()> {
let pixel_size = terminal_size.pixels.ok_or_else(|| {
Error::new(
ErrorKind::InvalidData,
"kitty did not report pixel size, cannot write image",
)
})?;
let mime_data = resource_handler.read_resource(url)?;
event!(
Level::DEBUG,
"Received data of mime type {:?}",
mime_data.mime_type
);
let image = self.render(mime_data, pixel_size)?;
image.write_to(writer)
}
}