wtrenderlib 0.1.0

Dependency-free terminal rendering primitives for RGB and RGBA frames
Documentation
use crate::{Error, FrameView, OwnedFrame, PixelFormat, ResizeMode, Result};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RgbaBackground(pub [u8; 3]);

fn source_pixel(frame: FrameView<'_>, x: usize, y: usize, background: [u8; 3]) -> [u8; 3] {
    let pixel = frame.pixel(x, y).expect("validated source coordinates");
    match frame.format() {
        PixelFormat::Rgb8 => [pixel[0], pixel[1], pixel[2]],
        PixelFormat::Rgba8 => {
            let alpha = u16::from(pixel[3]);
            [
                ((u16::from(pixel[0]) * alpha + u16::from(background[0]) * (255 - alpha) + 127)
                    / 255) as u8,
                ((u16::from(pixel[1]) * alpha + u16::from(background[1]) * (255 - alpha) + 127)
                    / 255) as u8,
                ((u16::from(pixel[2]) * alpha + u16::from(background[2]) * (255 - alpha) + 127)
                    / 255) as u8,
            ]
        }
    }
}

pub fn resize_frame(
    frame: FrameView<'_>,
    width: usize,
    height: usize,
    mode: ResizeMode,
    background: RgbaBackground,
) -> Result<OwnedFrame> {
    if width == 0 || height == 0 {
        return Err(Error::InvalidTargetSize);
    }
    let (source_width, source_height) = (frame.width(), frame.height());
    let (draw_width, draw_height) = match mode {
        ResizeMode::None => (source_width, source_height),
        ResizeMode::Stretch => (width, height),
        ResizeMode::Fit | ResizeMode::Fill => {
            let width_ratio = width as f64 / source_width as f64;
            let height_ratio = height as f64 / source_height as f64;
            let ratio = if mode == ResizeMode::Fit {
                width_ratio.min(height_ratio)
            } else {
                width_ratio.max(height_ratio)
            };
            (
                ((source_width as f64 * ratio).round() as usize).max(1),
                ((source_height as f64 * ratio).round() as usize).max(1),
            )
        }
    };
    let x_offset = width.saturating_sub(draw_width) / 2;
    let y_offset = height.saturating_sub(draw_height) / 2;
    let canvas_width = if mode == ResizeMode::None {
        draw_width
    } else {
        width
    };
    let canvas_height = if mode == ResizeMode::None {
        draw_height
    } else {
        height
    };
    let canvas_len = canvas_width
        .checked_mul(canvas_height)
        .and_then(|length| length.checked_mul(3))
        .ok_or(Error::DimensionOverflow)?;
    let mut canvas = vec![background.0[0]; canvas_len];
    for pixel in canvas.chunks_mut(3) {
        pixel[1] = background.0[1];
        pixel[2] = background.0[2];
    }
    for y in 0..draw_height {
        for x in 0..draw_width {
            let source_x = x * source_width / draw_width;
            let source_y = y * source_height / draw_height;
            let rgb = source_pixel(frame, source_x, source_y, background.0);
            let target_x = if mode == ResizeMode::None {
                x
            } else {
                x + x_offset
            };
            let target_y = if mode == ResizeMode::None {
                y
            } else {
                y + y_offset
            };
            if target_x < canvas_width && target_y < canvas_height {
                let index = (target_y * canvas_width + target_x) * 3;
                canvas[index..index + 3].copy_from_slice(&rgb);
            }
        }
    }
    OwnedFrame::new(canvas, canvas_width, canvas_height, PixelFormat::Rgb8)
}

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

    #[test]
    fn composites_transparent_pixel() {
        let frame = FrameView::new(&[255, 0, 0, 128], 1, 1, 4, PixelFormat::Rgba8).unwrap();
        let result = resize_frame(
            frame,
            1,
            1,
            ResizeMode::Stretch,
            RgbaBackground([0, 0, 255]),
        )
        .unwrap();
        assert_eq!(&result.into_inner(), &[128, 0, 127]);
    }

    #[test]
    fn fit_preserves_aspect_ratio() {
        let frame = FrameView::new(&[0; 12], 2, 2, 6, PixelFormat::Rgb8).unwrap();
        let result = resize_frame(frame, 4, 2, ResizeMode::Fit, RgbaBackground([0, 0, 0])).unwrap();
        assert_eq!(
            (result.as_view().width(), result.as_view().height()),
            (4, 2)
        );
    }
}