use crate::error::{Error, Result};
use crate::object::{Dictionary, Object, Stream};
use crate::parser::{find, is_whitespace, Parser};
use crate::Limits;
#[derive(Debug, Clone, PartialEq)]
pub struct Operation {
pub operator: String,
pub operands: Vec<Object>,
}
impl Operation {
pub fn new(operator: &str, operands: Vec<Object>) -> Self {
Self { operator: operator.to_owned(), operands }
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Content {
pub operations: Vec<Operation>,
}
const MAX_OPERANDS: usize = 256;
impl Content {
pub fn parse(data: &[u8]) -> Result<Self> {
Self::parse_with(data, &Limits::default())
}
pub fn parse_with(data: &[u8], limits: &Limits) -> Result<Self> {
let mut p = Parser::for_content(data, limits.max_nesting);
let mut operations = Vec::new();
let mut operands: Vec<Object> = Vec::new();
loop {
p.skip_ws();
if p.at_end() {
break;
}
let before = p.pos;
match p.object() {
Ok(o) => {
if operands.len() >= MAX_OPERANDS {
operands.remove(0);
}
operands.push(o);
}
Err(e @ Error::Limit { .. }) => return Err(e),
Err(_) => {
p.pos = before;
let token = p.token();
if token.is_empty() {
p.pos += 1;
continue;
}
if token == b"BI" {
let image = inline_image(&mut p)?;
operands.clear();
operations.push(Operation { operator: "BI".into(), operands: vec![Object::Stream(image)] });
} else {
operations.push(Operation {
operator: String::from_utf8_lossy(token).into_owned(),
operands: std::mem::take(&mut operands),
});
}
}
}
}
Ok(Self { operations })
}
#[must_use]
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
for op in &self.operations {
if op.operator == "BI" {
if let Some(Object::Stream(image)) = op.operands.first() {
out.extend_from_slice(b"BI");
for (key, value) in image.dict.iter() {
if key == b"Length" {
continue;
}
out.push(b' ');
crate::writer::write_name(&mut out, key);
out.push(b' ');
crate::writer::write_object(&mut out, value, &|_| 0);
}
out.extend_from_slice(b"\nID\n");
out.extend_from_slice(image.raw());
out.extend_from_slice(b"\nEI\n");
continue;
}
}
for operand in &op.operands {
crate::writer::write_object(&mut out, operand, &|_| 0);
out.push(b' ');
}
out.extend_from_slice(op.operator.as_bytes());
out.push(b'\n');
}
out
}
}
fn inline_image(p: &mut Parser<'_>) -> Result<Stream> {
let mut dict = Dictionary::new();
loop {
p.skip_ws();
if p.at_end() {
return Err(Error::Syntax { offset: p.pos, message: "inline image has no ID" });
}
if p.eat_keyword(b"ID") {
break;
}
match p.object() {
Ok(Object::Name(key)) => {
p.skip_ws();
let before = p.pos;
match p.object() {
Ok(value) => dict.set(key, value),
Err(e @ Error::Limit { .. }) => return Err(e),
Err(_) => p.pos = before,
}
}
Ok(_) => {}
Err(e @ Error::Limit { .. }) => return Err(e),
Err(_) => {
if p.token().is_empty() {
p.pos += 1;
}
}
}
}
if p.peek().is_some_and(is_whitespace) {
p.pos += 1;
}
let start = p.pos.min(p.data.len());
let end = inline_image_end(p.data, start, &dict)
.ok_or(Error::Syntax { offset: start, message: "inline image has no EI" })?;
p.pos = end.1;
Ok(Stream::new(dict, p.data[start..end.0].to_vec()))
}
fn inline_image_end(data: &[u8], start: usize, dict: &Dictionary) -> Option<(usize, usize)> {
if let Some(len) = unfiltered_length(dict) {
if let Some(end) = start.checked_add(len).filter(|e| *e <= data.len()) {
let mut probe = Parser::for_content(data, 0);
probe.pos = end;
probe.skip_ws();
if probe.eat_keyword(b"EI") {
return Some((end, probe.pos));
}
}
}
let mut from = start;
while let Some(at) = find(data, b"EI", from) {
from = at + 1;
let alone = (at == start || is_whitespace(data[at - 1]))
&& data.get(at + 2).copied().is_none_or(is_whitespace);
if !alone {
continue;
}
let tail = &data[at + 2..data.len().min(at + 2 + 16)];
let texty = tail.iter().all(|b| is_whitespace(*b) || (0x20..0x7F).contains(b));
if texty {
let end = if at > start { at - 1 } else { at };
return Some((end.max(start), at + 2));
}
}
None
}
fn unfiltered_length(dict: &Dictionary) -> Option<usize> {
if dict.has(b"F") || dict.has(b"Filter") {
return None;
}
let get = |short: &[u8], long: &[u8]| dict.get(short).or_else(|| dict.get(long));
let int = |o: &Object| o.as_i64().ok().and_then(|v| usize::try_from(v).ok());
let width = get(b"W", b"Width").and_then(int)?;
let height = get(b"H", b"Height").and_then(int)?;
let mask = get(b"IM", b"ImageMask").and_then(|o| o.as_bool().ok()).unwrap_or(false);
let (components, bits) = if mask {
(1, 1)
} else {
let bits = get(b"BPC", b"BitsPerComponent").and_then(int)?;
let components = match get(b"CS", b"ColorSpace")?.as_name().ok()? {
b"G" | b"DeviceGray" | b"CalGray" | b"I" | b"Indexed" => 1,
b"RGB" | b"DeviceRGB" | b"CalRGB" => 3,
b"CMYK" | b"DeviceCMYK" => 4,
_ => return None,
};
(components, bits)
};
let row = width.checked_mul(components)?.checked_mul(bits)?.div_ceil(8);
row.checked_mul(height)
}
#[cfg(test)]
mod tests {
use super::*;
fn ops(data: &[u8]) -> Vec<(String, usize)> {
Content::parse(data)
.unwrap()
.operations
.into_iter()
.map(|o| (o.operator, o.operands.len()))
.collect()
}
#[test]
fn operators_and_operands() {
let c = Content::parse(b"q 1 0 0 1 10 20 cm /Im1 Do Q BT /F1 12 Tf (Hi) Tj [(a) -20 (b)] TJ ET").unwrap();
let names: Vec<&str> = c.operations.iter().map(|o| o.operator.as_str()).collect();
assert_eq!(names, ["q", "cm", "Do", "Q", "BT", "Tf", "Tj", "TJ", "ET"]);
assert_eq!(c.operations[1].operands.len(), 6);
assert_eq!(c.operations[2].operands[0], Object::name("Im1"));
assert_eq!(c.operations[6].operands[0], Object::string("Hi"));
assert_eq!(ops(b"f* T* (a) ' 1 2 (b) \""), [("f*".into(), 0), ("T*".into(), 0), ("'".into(), 1), ("\"".into(), 3)]);
}
#[test]
fn junk_is_skipped_not_fatal() {
assert_eq!(ops(b"} ) 1 0 0 rg >"), [("rg".into(), 3)]);
assert_eq!(ops(b""), []);
assert_eq!(ops(b" % only a comment"), []);
}
#[test]
fn inline_images() {
let c = Content::parse(b"q BI /W 2 /H 2 /BPC 8 /CS /G ID \x00 EI\nEI Q").unwrap();
assert_eq!(c.operations.len(), 3);
let image = c.operations[1].operands[0].as_stream().unwrap();
assert_eq!(image.raw(), b"\x00 EI");
assert_eq!(image.dict.get_i64(b"W"), Some(2));
let c = Content::parse(b"BI /W 9 /H 9 /F /Fl ID \x01\xFFEI\x02 EI\x80 EI Q").unwrap();
let image = c.operations[0].operands[0].as_stream().unwrap();
assert_eq!(image.raw(), b"\x01\xFFEI\x02 EI\x80");
assert_eq!(c.operations[1].operator, "Q");
assert!(Content::parse(b"BI /W 1 /H 1 /F /Fl ID \x00\x01\x02").is_err());
}
#[test]
fn round_trip() {
let src = b"q 1 0 0 1 10.5 -20 cm /Im1 Do Q BT /F1 12 Tf (a\\(b) Tj ET BI /W 1 /H 1 /BPC 8 /CS /G ID \x7f\nEI f";
let first = Content::parse(src).unwrap();
let second = Content::parse(&first.encode()).unwrap();
assert_eq!(first, second);
}
}