Files
texrra-engine/crates/texrra-tex-core/src/pk.rs
T

292 lines
10 KiB
Rust

//! PK89 font packets and actual monochrome rasters, without a font substitute.
use std::collections::BTreeMap;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PkGlyph {
pub tfm_width: i32,
pub dx: i64,
pub dy: i64,
pub width: u32,
pub height: u32,
pub x_offset: i32,
pub y_offset: i32,
/// Top row first, MSB first, each row padded to a byte boundary.
pub bitmap: Vec<u8>,
}
impl PkGlyph {
pub fn pixel(&self, x: u32, y: u32) -> bool {
x < self.width
&& y < self.height
&& self.bitmap[(y * self.width.div_ceil(8) + x / 8) as usize] & (128 >> (x % 8)) != 0
}
pub fn bbox(&self) -> [i32; 4] {
let left = -self.x_offset;
let bottom = self.y_offset - self.height as i32 + 1;
[
left,
bottom,
left + self.width as i32 + 1,
bottom + self.height as i32,
]
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PkFont {
pub design_size: u32,
pub checksum: u32,
pub horizontal_pixels_per_point: u32,
pub vertical_pixels_per_point: u32,
pub glyphs: BTreeMap<u32, PkGlyph>,
}
struct Bytes<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Bytes<'a> {
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
let end = self.pos.checked_add(n).ok_or("PK byte offset overflow")?;
let value = self.data.get(self.pos..end).ok_or("truncated PK font")?;
self.pos = end;
Ok(value)
}
fn unsigned(&mut self, n: usize) -> Result<u32, String> {
Ok(self
.take(n)?
.iter()
.fold(0, |v, b| (v << 8) | u32::from(*b)))
}
fn signed(&mut self, n: usize) -> Result<i32, String> {
let v = self.unsigned(n)?;
Ok(((v << (32 - 8 * n)) as i32) >> (32 - 8 * n))
}
}
impl PkFont {
fn header(data: &[u8]) -> Result<(Self, Bytes<'_>), String> {
let mut b = Bytes { data, pos: 0 };
if b.unsigned(1)? != 247 || b.unsigned(1)? != 89 {
return Err("invalid PK89 preamble".into());
}
let comment = b.unsigned(1)? as usize;
b.take(comment)?;
let font = Self {
design_size: b.unsigned(4)?,
checksum: b.unsigned(4)?,
horizontal_pixels_per_point: b.unsigned(4)?,
vertical_pixels_per_point: b.unsigned(4)?,
glyphs: BTreeMap::new(),
};
if font.design_size == 0
|| font.horizontal_pixels_per_point == 0
|| font.vertical_pixels_per_point == 0
{
return Err("invalid PK design size or pixel density".into());
}
Ok((font, b))
}
pub fn density(data: &[u8]) -> Result<(u32, u32), String> {
let (font, _) = Self::header(data)?;
let dpi = |value: u32| ((u64::from(value) * 7227 + 3_276_800) / 6_553_600) as u32;
Ok((
dpi(font.horizontal_pixels_per_point),
dpi(font.vertical_pixels_per_point),
))
}
pub fn parse(data: &[u8]) -> Result<Self, String> {
let (mut font, mut b) = Self::header(data)?;
let mut total_bytes = 0usize;
loop {
let flag = b.unsigned(1)? as u8;
match flag {
0..=239 => {
let form = flag & 7;
let length = match form {
0..=3 => u32::from(form) * 256 + b.unsigned(1)?,
4..=6 => u32::from(form - 4) * 65536 + b.unsigned(2)?,
_ => b.unsigned(4)?,
};
let code = b.unsigned(if form == 7 { 4 } else { 1 })?;
let packet = b.take(length as usize)?;
let mut p = Bytes {
data: packet,
pos: 0,
};
let tfm_width = if form == 7 {
p.signed(4)?
} else {
p.unsigned(3)? as i32
};
let (dx, dy, n) = match form {
0..=3 => (i64::from(p.unsigned(1)?) * 65536, 0, 1),
4..=6 => (i64::from(p.unsigned(2)?) * 65536, 0, 2),
_ => (i64::from(p.signed(4)?), i64::from(p.signed(4)?), 4),
};
let width = p.unsigned(n)?;
let height = p.unsigned(n)?;
let x_offset = p.signed(n)?;
let y_offset = p.signed(n)?;
if width > 1_000_000
|| height > 1_000_000
|| x_offset.unsigned_abs() > (i32::MAX - 1_000_001) as u32
|| y_offset.unsigned_abs() > (i32::MAX - 1_000_001) as u32
{
return Err("PK glyph geometry exceeds capacity".into());
}
let pixels = u64::from(width) * u64::from(height);
if pixels > 32 * 1024 * 1024 {
return Err("PK glyph raster exceeds capacity".into());
}
let bitmap = raster(&packet[p.pos..], width, height, flag >> 4, flag & 8 != 0)?;
total_bytes += bitmap.len();
if total_bytes > 64 * 1024 * 1024 || font.glyphs.len() >= 65536 {
return Err("PK font raster exceeds capacity".into());
}
if font
.glyphs
.insert(
code,
PkGlyph {
tfm_width,
dx,
dy,
width,
height,
x_offset,
y_offset,
bitmap,
},
)
.is_some()
{
return Err(format!("duplicate PK glyph {code}"));
}
}
240..=243 => {
let n = b.unsigned(usize::from(flag - 239))?;
b.take(n as usize)?;
}
244 => {
b.take(4)?;
}
245 => {
if b.data[b.pos..].iter().any(|v| *v != 246) {
return Err("invalid PK postamble".into());
}
return Ok(font);
}
246 => {}
_ => return Err(format!("invalid PK opcode {flag}")),
}
}
}
}
struct Nybbles<'a> {
data: &'a [u8],
pos: usize,
}
impl Nybbles<'_> {
fn next(&mut self) -> Result<usize, String> {
let b = *self
.data
.get(self.pos / 2)
.ok_or("truncated PK run count")?;
let value = if self.pos % 2 == 0 { b >> 4 } else { b & 15 };
self.pos += 1;
Ok(usize::from(value))
}
fn number(&mut self, dyn_f: usize, repeat: &mut usize) -> Result<usize, String> {
let i = self.next()?;
if i == 0 {
let mut zeros = 1;
let mut n = self.next()?;
while n == 0 {
zeros += 1;
if zeros > 7 {
return Err("PK run count overflow".into());
}
n = self.next()?;
}
for _ in 0..zeros {
let next = self.next()?;
n = n
.checked_mul(16)
.and_then(|v| v.checked_add(next))
.ok_or("PK run count overflow")?;
}
Ok(n - 15 + (13 - dyn_f) * 16 + dyn_f)
} else if i <= dyn_f {
Ok(i)
} else if i < 14 {
Ok((i - dyn_f - 1) * 16 + self.next()? + dyn_f + 1)
} else {
if *repeat != 0 {
return Err("second PK repeat count for this row".into());
}
*repeat = 1;
if i == 14 {
*repeat = self.number(dyn_f, repeat)?;
}
self.number(dyn_f, repeat)
}
}
}
fn raster(data: &[u8], w: u32, h: u32, dyn_f: u8, mut black: bool) -> Result<Vec<u8>, String> {
let stride = w.div_ceil(8) as usize;
let mut result = vec![0u8; stride * h as usize];
if w == 0 || h == 0 {
if !data.is_empty() {
return Err("nonempty PK null raster".into());
}
return Ok(result);
}
if dyn_f == 14 {
let pixels = w as usize * h as usize;
if data.len() != pixels.div_ceil(8) {
return Err("invalid PK bitmap length".into());
}
for i in 0..pixels {
if data[i / 8] & (128 >> (i % 8)) != 0 {
let x = i % (w as usize);
let y = i / (w as usize);
result[y * stride + x / 8] |= 128 >> (x % 8);
}
}
} else {
let mut n = Nybbles { data, pos: 0 };
let (mut x, mut y, mut repeat) = (0usize, 0usize, 0usize);
while y < h as usize {
let mut count = n.number(usize::from(dyn_f), &mut repeat)?;
while count > 0 {
if y >= h as usize {
return Err("PK runs exceed glyph height".into());
}
let take = count.min(w as usize - x);
if black {
for j in x..x + take {
result[y * stride + j / 8] |= 128 >> (j % 8);
}
}
x += take;
count -= take;
if x == w as usize {
if repeat >= h as usize - y {
return Err("PK repeats exceed glyph height".into());
}
for row in y + 1..=y + repeat {
result.copy_within(y * stride..(y + 1) * stride, row * stride);
}
y += repeat + 1;
repeat = 0;
x = 0;
}
}
black = !black;
}
if x != 0 || n.pos.div_ceil(2) != data.len() {
return Err("invalid PK raster packet length".into());
}
}
Ok(result)
}