wtrenderlib 0.1.0

Dependency-free terminal rendering primitives for RGB and RGBA frames
Documentation
use std::io::Write;

use crate::Result;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Iterm2Options {
    pub width_cells: Option<usize>,
    pub height_cells: Option<usize>,
    pub preserve_aspect_ratio: bool,
}

impl Default for Iterm2Options {
    fn default() -> Self {
        Self {
            width_cells: None,
            height_cells: None,
            preserve_aspect_ratio: true,
        }
    }
}

/// Writes an image already encoded as PNG, JPEG, or another iTerm2-supported format.
///
/// Keeping encoding outside the core preserves the dependency-free default build.
pub fn render_iterm2<W: Write>(
    encoded_image: &[u8],
    output: &mut W,
    options: Iterm2Options,
) -> Result<()> {
    output.write_all(b"\x1b]1337;File=inline=1")?;
    if let Some(width) = options.width_cells {
        write!(output, ";width={width}")?;
    }
    if let Some(height) = options.height_cells {
        write!(output, ";height={height}")?;
    }
    if options.preserve_aspect_ratio {
        output.write_all(b";preserveAspectRatio=1")?;
    }
    output.write_all(b":")?;
    encode_base64(encoded_image, output)?;
    output.write_all(b"\x07")?;
    Ok(())
}

fn encode_base64<W: Write>(input: &[u8], output: &mut W) -> Result<()> {
    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for chunk in input.chunks(3) {
        let a = chunk[0];
        let b = chunk.get(1).copied().unwrap_or(0);
        let c = chunk.get(2).copied().unwrap_or(0);
        output.write_all(&[
            TABLE[(a >> 2) as usize],
            TABLE[((a & 0x03) << 4 | b >> 4) as usize],
            if chunk.len() > 1 {
                TABLE[((b & 0x0f) << 2 | c >> 6) as usize]
            } else {
                b'='
            },
            if chunk.len() > 2 {
                TABLE[(c & 0x3f) as usize]
            } else {
                b'='
            },
        ])?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn emits_inline_image_sequence() {
        let mut output = Vec::new();
        render_iterm2(
            b"PNG",
            &mut output,
            Iterm2Options {
                width_cells: Some(20),
                height_cells: None,
                preserve_aspect_ratio: true,
            },
        )
        .unwrap();
        assert_eq!(
            String::from_utf8(output).unwrap(),
            "\x1b]1337;File=inline=1;width=20;preserveAspectRatio=1:UE5H\x07"
        );
    }
}