sealed-surface 0.2.0

Non-extractable data surface: tables and timeseries as glyphs, never DOM text
Documentation
//! Software pixmap + in-crate PNG encoder (DEFLATE).

use crate::deflate;
use crate::error::Error;
use crate::font;
use crate::theme::Rgb;

/// RGB888 pixmap.
#[derive(Debug, Clone)]
pub struct Pixmap {
    width: u32,
    height: u32,
    data: Vec<u8>,
}

impl Pixmap {
    pub(crate) fn new(width: u32, height: u32, fill: Rgb) -> Result<Self, Error> {
        if width == 0 || height == 0 {
            return Err(Error::Raster("width and height must be > 0"));
        }
        let n = (width as usize)
            .checked_mul(height as usize)
            .and_then(|px| px.checked_mul(3))
            .ok_or(Error::Raster("pixmap too large"))?;
        let mut data = vec![0u8; n];
        for px in data.chunks_exact_mut(3) {
            px[0] = fill.r;
            px[1] = fill.g;
            px[2] = fill.b;
        }
        Ok(Self {
            width,
            height,
            data,
        })
    }

    /// Pixel width.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Pixel height.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    pub(crate) fn fill_rect(&mut self, x: u32, y: u32, w: u32, h: u32, color: Rgb) {
        let x1 = x.min(self.width);
        let y1 = y.min(self.height);
        let x2 = x.saturating_add(w).min(self.width);
        let y2 = y.saturating_add(h).min(self.height);
        if x1 >= x2 || y1 >= y2 {
            return;
        }
        let row_w = (x2 - x1) as usize;
        let stride = self.width as usize * 3;
        let first = (y1 as usize) * stride + (x1 as usize) * 3;
        {
            let row = &mut self.data[first..first + row_w * 3];
            for px in row.chunks_exact_mut(3) {
                px[0] = color.r;
                px[1] = color.g;
                px[2] = color.b;
            }
        }
        for yy in (y1 + 1)..y2 {
            let dest = (yy as usize) * stride + (x1 as usize) * 3;
            self.data.copy_within(first..first + row_w * 3, dest);
        }
    }

    pub(crate) fn hline(&mut self, x: u32, y: u32, w: u32, color: Rgb) {
        self.fill_rect(x, y, w, 1, color);
    }

    pub(crate) fn vline(&mut self, x: u32, y: u32, h: u32, color: Rgb) {
        self.fill_rect(x, y, 1, h, color);
    }

    pub(crate) fn line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Rgb) {
        let mut x = x0;
        let mut y = y0;
        let dx = (x1 - x0).abs();
        let sx = if x0 < x1 { 1 } else { -1 };
        let dy = -(y1 - y0).abs();
        let sy = if y0 < y1 { 1 } else { -1 };
        let mut err = dx + dy;
        loop {
            if x >= 0 && y >= 0 {
                self.put(x as u32, y as u32, color);
            }
            if x == x1 && y == y1 {
                break;
            }
            let e2 = 2 * err;
            if e2 >= dy {
                err += dy;
                x += sx;
            }
            if e2 <= dx {
                err += dx;
                y += sy;
            }
        }
    }

    pub(crate) fn put(&mut self, x: u32, y: u32, color: Rgb) {
        if x >= self.width || y >= self.height {
            return;
        }
        let i = ((y as usize) * (self.width as usize) + (x as usize)) * 3;
        self.data[i] = color.r;
        self.data[i + 1] = color.g;
        self.data[i + 2] = color.b;
    }

    pub(crate) fn text(&mut self, x: u32, y: u32, s: &str, color: Rgb, max_w: u32) {
        let mut cx = x;
        for ch in s.chars() {
            if cx.saturating_sub(x).saturating_add(font::ADVANCE) > max_w {
                break;
            }
            font::each_pixel(ch, |px, py| {
                self.put(cx.saturating_add(px), y.saturating_add(py), color);
            });
            cx = cx.saturating_add(font::ADVANCE);
        }
    }

    /// Encode PNG (8-bit RGB, no interlace).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Raster`] if the buffer is inconsistent.
    pub fn to_png(&self) -> Result<Vec<u8>, Error> {
        encode_png(self.width, self.height, &self.data)
    }
}

fn encode_png(width: u32, height: u32, rgb: &[u8]) -> Result<Vec<u8>, Error> {
    let expected = (width as usize)
        .checked_mul(height as usize)
        .and_then(|px| px.checked_mul(3))
        .ok_or(Error::Raster("png size overflow"))?;
    if rgb.len() != expected {
        return Err(Error::Raster("rgb length does not match dimensions"));
    }

    let mut raw = Vec::with_capacity((width as usize + 1) * height as usize * 3);
    for y in 0..height as usize {
        raw.push(0);
        let start = y * width as usize * 3;
        let end = start + width as usize * 3;
        raw.extend_from_slice(&rgb[start..end]);
    }

    let mut out = Vec::new();
    out.extend_from_slice(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
    let mut ihdr = Vec::new();
    ihdr.extend_from_slice(&width.to_be_bytes());
    ihdr.extend_from_slice(&height.to_be_bytes());
    ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
    write_chunk(&mut out, *b"IHDR", &ihdr);
    let deflated = deflate::zlib_deflate(&raw);
    write_chunk(&mut out, *b"IDAT", &deflated);
    write_chunk(&mut out, *b"IEND", &[]);
    Ok(out)
}

fn write_chunk(out: &mut Vec<u8>, ty: [u8; 4], data: &[u8]) {
    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
    out.extend_from_slice(&ty);
    out.extend_from_slice(data);
    let mut crc_in = Vec::with_capacity(4 + data.len());
    crc_in.extend_from_slice(&ty);
    crc_in.extend_from_slice(data);
    out.extend_from_slice(&crc32(&crc_in).to_be_bytes());
}

fn crc32(data: &[u8]) -> u32 {
    let mut crc = 0xFFFF_FFFFu32;
    for &b in data {
        let idx = ((crc ^ u32::from(b)) & 0xFF) as usize;
        crc = CRC_TABLE[idx] ^ (crc >> 8);
    }
    crc ^ 0xFFFF_FFFF
}

const CRC_TABLE: [u32; 256] = make_crc_table();

const fn make_crc_table() -> [u32; 256] {
    let mut table = [0u32; 256];
    let mut n = 0;
    while n < 256 {
        let mut c = n as u32;
        let mut k = 0;
        while k < 8 {
            if c & 1 != 0 {
                c = 0xEDB8_8320 ^ (c >> 1);
            } else {
                c >>= 1;
            }
            k += 1;
        }
        table[n] = c;
        n += 1;
    }
    table
}

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

    #[test]
    fn png_signature() {
        let pm = Pixmap::new(2, 2, Rgb::new(0, 0, 0)).expect("pixmap");
        let png = pm.to_png().expect("png");
        assert_eq!(&png[..8], &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
    }

    #[test]
    fn png_idat_roundtrip() {
        let mut pm = Pixmap::new(8, 4, Rgb::new(0x0b, 0x0d, 0x10)).expect("pixmap");
        pm.fill_rect(1, 1, 3, 2, Rgb::new(0x3d, 0x9e, 0xff));
        let png = pm.to_png().expect("png");
        let raw = extract_idat_inflate(&png).expect("idat");
        let mut expect = Vec::new();
        for y in 0..4u32 {
            expect.push(0);
            for x in 0..8u32 {
                let i = ((y * 8 + x) * 3) as usize;
                expect.extend_from_slice(&pm.data[i..i + 3]);
            }
        }
        assert_eq!(raw, expect);
    }

    #[test]
    fn png_deflate_beats_raw_for_flat_fill() {
        let pm = Pixmap::new(320, 180, Rgb::new(0x0b, 0x0d, 0x10)).expect("pixmap");
        let png = pm.to_png().expect("png");
        let raw_rgb = (320 * 180 * 3) as usize;
        assert!(
            png.len() < raw_rgb / 4,
            "compressed {} vs raw {}",
            png.len(),
            raw_rgb
        );
    }

    fn extract_idat_inflate(png: &[u8]) -> Result<Vec<u8>, &'static str> {
        let mut i = 8usize;
        let mut z = Vec::new();
        while i + 12 <= png.len() {
            let len = u32::from_be_bytes(png[i..i + 4].try_into().unwrap()) as usize;
            let ty = &png[i + 4..i + 8];
            let data = &png[i + 8..i + 8 + len];
            if ty == b"IDAT" {
                z.extend_from_slice(data);
            }
            if ty == b"IEND" {
                break;
            }
            i += 12 + len;
        }
        crate::deflate::zlib_inflate(&z)
    }
}