use crate::filters::{self, FilterError};
use crate::lexer::{Lexer, Token, TokenKind};
pub const MAX_FORM_DEPTH: usize = 64;
use crate::object::{Dict, Name, ObjId, Object};
use crate::page_tree::Page;
use crate::span::ByteSpan;
use crate::view::DocumentView;
#[derive(Debug, Clone, PartialEq)]
pub struct ContentToken {
pub kind: ContentTokenKind,
pub span: ByteSpan,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ContentTokenKind {
Operand(Object),
Operator,
InlineImage {
params: Dict,
data: ByteSpan,
},
}
#[derive(Debug, Clone)]
pub struct ContentStream {
pub buf: Vec<u8>,
pub tokens: Vec<ContentToken>,
}
#[derive(Debug, Clone, Copy)]
pub struct Operation<'a> {
pub operands: &'a [ContentToken],
pub operator: &'a ContentToken,
}
impl<'a> Operation<'a> {
#[must_use]
pub fn operator_name(&self, buf: &'a [u8]) -> Option<&'a [u8]> {
match self.operator.kind {
ContentTokenKind::Operator => self.operator.span.slice(buf),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ContentError {
#[error(transparent)]
Lex(#[from] crate::lexer::LexError),
#[error("malformed operand at byte {0} of decoded content")]
BadOperand(usize),
#[error("operand nesting too deep at byte {0}")]
TooDeep(usize),
#[error("malformed inline image parameters at byte {0}")]
BadInlineParams(usize),
#[error("unterminated inline image starting at byte {0}")]
UnterminatedInlineImage(usize),
#[error("content stream decode failed: {0}")]
Decode(#[from] FilterError),
#[error("page Contents object is not a stream")]
NotAStream,
}
const MAX_OPERAND_DEPTH: usize = 64;
impl ContentStream {
pub fn from_page(view: &DocumentView<'_>, page: &Page) -> Result<Self, ContentError> {
let mut buf: Vec<u8> = Vec::new();
for (i, id) in page.contents.iter().enumerate() {
let obj = view.graph().value(*id).ok_or(ContentError::NotAStream)?;
let Object::Stream(stream) = obj else {
return Err(ContentError::NotAStream);
};
let raw = view
.slice(stream.data_span)
.ok_or(ContentError::NotAStream)?;
let decoded = filters::decode_stream(&stream.dict, raw)?;
if i > 0 && !decoded.is_empty() {
buf.push(b'\n');
}
buf.extend_from_slice(&decoded);
}
Self::parse(buf)
}
pub fn from_form(view: &DocumentView<'_>, id: ObjId) -> Result<Self, ContentError> {
let Some(Object::Stream(stream)) = view.graph().value(id) else {
return Err(ContentError::NotAStream);
};
let raw = view
.slice(stream.data_span)
.ok_or(ContentError::NotAStream)?;
Self::parse(filters::decode_stream(&stream.dict, raw)?)
}
pub fn parse(buf: Vec<u8>) -> Result<Self, ContentError> {
Self::parse_from(buf, Vec::new(), 0)
}
pub fn parse_from(
buf: Vec<u8>,
mut tokens: Vec<ContentToken>,
from: usize,
) -> Result<Self, ContentError> {
let mut capacity = TokenCapacity::default();
let total = buf.len();
let mut lexer = Lexer::at(&buf, from.min(total));
while let Some(tok) = lexer.next_token()? {
capacity.grow_if_full(&mut tokens, tok.span.start, total);
match tok.kind {
TokenKind::Keyword => {
if tok.lexeme(&buf) == Some(b"BI") {
let (token, resume_at) = parse_inline_image(&buf, &tok, &mut lexer)?;
tokens.push(token);
lexer = Lexer::at(&buf, resume_at);
} else {
match tok.lexeme(&buf) {
Some(b"true") => tokens.push(ContentToken {
kind: ContentTokenKind::Operand(Object::Boolean(true)),
span: tok.span,
}),
Some(b"false") => tokens.push(ContentToken {
kind: ContentTokenKind::Operand(Object::Boolean(false)),
span: tok.span,
}),
Some(b"null") => tokens.push(ContentToken {
kind: ContentTokenKind::Operand(Object::Null),
span: tok.span,
}),
_ => tokens.push(ContentToken {
kind: ContentTokenKind::Operator,
span: tok.span,
}),
}
}
}
_ => {
let (object, span) = assemble_operand(&buf, tok, &mut lexer, 0)?;
tokens.push(ContentToken {
kind: ContentTokenKind::Operand(object),
span,
});
}
}
}
Ok(Self { buf, tokens })
}
pub fn operations(&self) -> impl Iterator<Item = Operation<'_>> {
let mut run_start = 0usize;
self.tokens
.iter()
.enumerate()
.filter_map(move |(i, tok)| match tok.kind {
ContentTokenKind::Operand(_) => None,
_ => {
let operands = self.tokens.get(run_start..i).unwrap_or(&[]);
run_start = i + 1;
Some(Operation {
operands,
operator: tok,
})
}
})
}
}
#[derive(Debug, Default)]
struct TokenCapacity {
projections: u32,
}
impl TokenCapacity {
const MIN_SAMPLE: usize = 4096;
const MIN_CAPACITY: usize = 4;
fn grow_if_full(&mut self, tokens: &mut Vec<ContentToken>, consumed: usize, total: usize) {
if tokens.len() < tokens.capacity() {
return;
}
let cap = tokens.capacity();
let floor = cap.saturating_add(cap / 4).max(Self::MIN_CAPACITY);
let target = if tokens.len() >= Self::MIN_SAMPLE && consumed > 0 && total > consumed {
let projected = u128::from(tokens.len() as u64)
.saturating_mul(u128::from(total as u64))
/ u128::from(consumed as u64);
let divisor = if self.projections == 0 { 8 } else { 4 };
let with_margin = projected.saturating_add(projected / divisor);
self.projections = self.projections.saturating_add(1);
usize::try_from(with_margin)
.unwrap_or(usize::MAX)
.max(floor)
} else {
cap.saturating_mul(2).max(Self::MIN_CAPACITY)
};
tokens.reserve_exact(target.saturating_sub(tokens.len()));
}
}
fn assemble_operand(
buf: &[u8],
first: Token,
lexer: &mut Lexer<'_>,
depth: usize,
) -> Result<(Object, ByteSpan), ContentError> {
if depth > MAX_OPERAND_DEPTH {
return Err(ContentError::TooDeep(first.span.start));
}
let start = first.span.start;
match first.kind {
TokenKind::Integer(v) => Ok((Object::Integer(v), first.span)),
TokenKind::Real(v) => Ok((Object::Real(v), first.span)),
TokenKind::String(s) => Ok((Object::String(s), first.span)),
TokenKind::Name(n) => Ok((Object::Name(Name(n)), first.span)),
TokenKind::ArrayOpen => {
let mut items = Vec::new();
loop {
let Some(tok) = lexer.next_token()? else {
return Err(ContentError::BadOperand(start));
};
match tok.kind {
TokenKind::ArrayClose => {
return Ok((
Object::Array(items),
ByteSpan::from_range(start..tok.span.end()),
));
}
TokenKind::Keyword => match tok.lexeme(buf) {
Some(b"true") => items.push(Object::Boolean(true)),
Some(b"false") => items.push(Object::Boolean(false)),
Some(b"null") => items.push(Object::Null),
_ => return Err(ContentError::BadOperand(tok.span.start)),
},
_ => {
let (obj, _) = assemble_operand(buf, tok, lexer, depth + 1)?;
items.push(obj);
}
}
}
}
TokenKind::DictOpen => {
let mut dict = Dict::new();
loop {
let Some(tok) = lexer.next_token()? else {
return Err(ContentError::BadOperand(start));
};
match tok.kind {
TokenKind::DictClose => {
return Ok((
Object::Dict(dict),
ByteSpan::from_range(start..tok.span.end()),
));
}
TokenKind::Name(key) => {
let Some(value_tok) = lexer.next_token()? else {
return Err(ContentError::BadOperand(start));
};
let value = match value_tok.kind {
TokenKind::Keyword => match value_tok.lexeme(buf) {
Some(b"true") => Object::Boolean(true),
Some(b"false") => Object::Boolean(false),
Some(b"null") => Object::Null,
_ => return Err(ContentError::BadOperand(value_tok.span.start)),
},
_ => assemble_operand(buf, value_tok, lexer, depth + 1)?.0,
};
dict.insert(Name(key), value);
}
_ => return Err(ContentError::BadOperand(tok.span.start)),
}
}
}
_ => Err(ContentError::BadOperand(start)),
}
}
fn parse_inline_image(
buf: &[u8],
bi: &Token,
lexer: &mut Lexer<'_>,
) -> Result<(ContentToken, usize), ContentError> {
let mut params = Dict::new();
let id_end;
loop {
let Some(tok) = lexer.next_token()? else {
return Err(ContentError::BadInlineParams(bi.span.start));
};
match tok.kind {
TokenKind::Keyword if tok.lexeme(buf) == Some(b"ID") => {
id_end = tok.span.end();
break;
}
TokenKind::Name(key) => {
let Some(value_tok) = lexer.next_token()? else {
return Err(ContentError::BadInlineParams(bi.span.start));
};
let value = match value_tok.kind {
TokenKind::Keyword => match value_tok.lexeme(buf) {
Some(b"true") => Object::Boolean(true),
Some(b"false") => Object::Boolean(false),
Some(b"null") => Object::Null,
_ => return Err(ContentError::BadInlineParams(value_tok.span.start)),
},
_ => {
assemble_operand(buf, value_tok, lexer, 0)
.map_err(|_| ContentError::BadInlineParams(bi.span.start))?
.0
}
};
let key = normalize_key(&key);
let value = normalize_value(&key, value);
params.insert(key, value);
}
_ => return Err(ContentError::BadInlineParams(tok.span.start)),
}
}
let data_start = match (buf.get(id_end).copied(), buf.get(id_end + 1).copied()) {
(Some(b'\r'), Some(b'\n')) => id_end + 2,
(Some(b), _) if crate::lexer::is_whitespace(b) => id_end + 1,
_ => id_end,
};
let data_end = locate_inline_data_end(buf, data_start, ¶ms)
.ok_or(ContentError::UnterminatedInlineImage(bi.span.start))?;
let mut tail = Lexer::at(buf, data_end);
let Ok(Some(ei)) = tail.next_token() else {
return Err(ContentError::UnterminatedInlineImage(bi.span.start));
};
if !(matches!(ei.kind, TokenKind::Keyword) && ei.lexeme(buf) == Some(b"EI")) {
return Err(ContentError::UnterminatedInlineImage(bi.span.start));
}
Ok((
ContentToken {
kind: ContentTokenKind::InlineImage {
params,
data: ByteSpan::from_range(data_start..data_end),
},
span: ByteSpan::from_range(bi.span.start..ei.span.end()),
},
ei.span.end(),
))
}
fn locate_inline_data_end(buf: &[u8], start: usize, params: &Dict) -> Option<usize> {
let filters = inline_filters(params);
if filters.is_empty() {
if let Some(len) = unfiltered_data_len(params) {
let end = start.checked_add(len)?;
return (end <= buf.len()).then_some(end);
}
} else if let Some(first) = filters.first() {
let region = buf.get(start..)?;
match first.as_slice() {
b"ASCIIHexDecode" => {
let eod = region.iter().position(|&b| b == b'>')?;
return Some(start + eod + 1);
}
b"ASCII85Decode" => {
let eod = region.windows(2).position(|w| w == b"~>")?;
return Some(start + eod + 2);
}
_ => {}
}
}
let mut i = start;
while i + 1 < buf.len() {
if buf.get(i) == Some(&b'E')
&& buf.get(i + 1) == Some(&b'I')
&& i > start
&& buf
.get(i - 1)
.copied()
.is_some_and(crate::lexer::is_whitespace)
{
let after = buf.get(i + 2).copied();
let terminated = match after {
None => true,
Some(b) => crate::lexer::is_whitespace(b) || crate::lexer::is_delimiter(b),
};
if terminated {
return Some(i - 1);
}
}
i += 1;
}
None
}
fn unfiltered_data_len(params: &Dict) -> Option<usize> {
let get_u64 = |key: &[u8]| -> Option<u64> {
params
.get(key)
.and_then(Object::as_int)
.and_then(|v| u64::try_from(v).ok())
};
let w = get_u64(b"Width")?;
let h = get_u64(b"Height")?;
let image_mask = matches!(params.get(b"ImageMask"), Some(Object::Boolean(true)));
let bpc = if image_mask {
1
} else {
get_u64(b"BitsPerComponent")?
};
let colors = if image_mask {
1
} else {
match params.get(b"ColorSpace") {
Some(Object::Name(n)) => match n.as_bytes() {
b"DeviceRGB" => 3,
b"DeviceCMYK" => 4,
_ => 1,
},
Some(Object::Array(_)) => 1, _ => 1,
}
};
let row_bytes = (w.checked_mul(colors)?.checked_mul(bpc)?).div_ceil(8);
usize::try_from(row_bytes.checked_mul(h)?).ok()
}
fn inline_filters(params: &Dict) -> Vec<Vec<u8>> {
match params.get(b"Filter") {
Some(Object::Name(n)) => vec![n.as_bytes().to_vec()],
Some(Object::Array(items)) => items
.iter()
.filter_map(|o| o.as_name().map(|n| n.as_bytes().to_vec()))
.collect(),
_ => Vec::new(),
}
}
fn normalize_key(key: &[u8]) -> Name {
Name(
match key {
b"BPC" => &b"BitsPerComponent"[..],
b"CS" => b"ColorSpace",
b"D" => b"Decode",
b"DP" => b"DecodeParms",
b"F" => b"Filter",
b"H" => b"Height",
b"IM" => b"ImageMask",
b"I" => b"Interpolate", b"W" => b"Width",
other => other,
}
.to_vec(),
)
}
fn normalize_value(key: &Name, value: Object) -> Object {
fn map_name(bytes: &[u8]) -> Option<&'static [u8]> {
Some(match bytes {
b"G" => b"DeviceGray",
b"RGB" => b"DeviceRGB",
b"CMYK" => b"DeviceCMYK",
b"I" => b"Indexed",
b"AHx" => b"ASCIIHexDecode",
b"A85" => b"ASCII85Decode",
b"LZW" => b"LZWDecode",
b"Fl" => b"FlateDecode",
b"RL" => b"RunLengthDecode",
b"CCF" => b"CCITTFaxDecode",
b"DCT" => b"DCTDecode",
_ => return None,
})
}
if !matches!(key.as_bytes(), b"Filter" | b"ColorSpace") {
return value;
}
match value {
Object::Name(n) => match map_name(n.as_bytes()) {
Some(full) => Object::Name(Name(full.to_vec())),
None => Object::Name(n),
},
Object::Array(items) => Object::Array(
items
.into_iter()
.map(|o| match o {
Object::Name(n) => match map_name(n.as_bytes()) {
Some(full) => Object::Name(Name(full.to_vec())),
None => Object::Name(n),
},
other => other,
})
.collect(),
),
other => other,
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
mod tests {
use super::*;
fn parse(input: &[u8]) -> ContentStream {
ContentStream::parse(input.to_vec()).unwrap()
}
#[test]
fn parse_from_a_token_boundary_equals_a_whole_parse() {
let whole: &[u8] = b"q 1 0 0 1 5 5 cm BI /W 1 /H 1 /BPC 8 /CS /G ID x EI Q
0 0 m 9 9 l S";
let cut = 52;
let prefix = parse(whole.get(..cut).unwrap()).tokens;
let resumed = ContentStream::parse_from(whole.to_vec(), prefix, cut).unwrap();
assert_eq!(resumed.tokens, parse(whole).tokens);
}
fn ops(cs: &ContentStream) -> Vec<(Vec<u8>, Vec<Object>)> {
cs.operations()
.map(|op| {
let name = op.operator_name(&cs.buf).unwrap_or(b"<inline>").to_vec();
let operands = op
.operands
.iter()
.filter_map(|t| match &t.kind {
ContentTokenKind::Operand(o) => Some(o.clone()),
_ => None,
})
.collect();
(name, operands)
})
.collect()
}
#[test]
fn basic_operations_projection() {
let cs = parse(b"q 1 0 0 1 72 712 cm BT /F1 12 Tf (Hello) Tj ET Q");
let ops = ops(&cs);
let names: Vec<&[u8]> = ops.iter().map(|(n, _)| n.as_slice()).collect();
assert_eq!(
names,
vec![&b"q"[..], b"cm", b"BT", b"Tf", b"Tj", b"ET", b"Q"]
);
assert_eq!(ops[1].1.len(), 6);
assert_eq!(ops[3].1[0], Object::Name(Name::from(b"F1")));
assert_eq!(ops[4].1[0], Object::String(b"Hello".to_vec()));
}
#[test]
fn tj_array_is_one_operand_with_full_span() {
let buf: &[u8] = b"[(He)-20(llo)] TJ";
let cs = parse(buf);
let ops = ops(&cs);
assert_eq!(ops[0].0, b"TJ");
assert_eq!(ops[0].1.len(), 1, "the TJ array is ONE operand");
let ContentTokenKind::Operand(_) = &cs.tokens[0].kind else {
panic!("expected operand");
};
assert_eq!(cs.tokens[0].span.slice(buf).unwrap(), b"[(He)-20(llo)]");
}
#[test]
fn dict_operand_for_marked_content() {
let cs = parse(b"/OC << /Type /OCMD >> BDC EMC");
let ops = ops(&cs);
assert_eq!(ops[0].0, b"BDC");
assert_eq!(ops[0].1.len(), 2);
assert!(matches!(ops[0].1[1], Object::Dict(_)));
}
#[test]
fn keywords_true_false_null_are_operands_not_operators() {
let cs = parse(b"true false null gs");
let ops = ops(&cs);
assert_eq!(ops.len(), 1);
assert_eq!(ops[0].0, b"gs");
assert_eq!(ops[0].1.len(), 3);
}
#[test]
fn trailing_operands_without_operator_are_not_yielded() {
let cs = parse(b"q Q 1 2 3");
assert_eq!(ops(&cs).len(), 2);
assert_eq!(cs.tokens.len(), 5, "operand tokens preserved");
}
#[test]
fn unknown_operator_is_a_token_not_an_error() {
let cs = parse(b"1 2 frobnicate");
assert_eq!(ops(&cs)[0].0, b"frobnicate");
}
#[test]
fn inline_image_unfiltered_computed_length() {
let buf: &[u8] = b"BI /W 2 /H 2 /CS /G /BPC 8 ID \x45\x49\x00\xFF EI Q";
let cs = parse(buf);
let ContentTokenKind::InlineImage { params, data } = &cs.tokens[0].kind else {
panic!("expected inline image, got {:?}", cs.tokens[0].kind);
};
assert_eq!(data.slice(buf).unwrap(), b"\x45\x49\x00\xFF");
assert!(params.contains_key(b"Width"));
assert_eq!(
params
.get(b"ColorSpace")
.unwrap()
.as_name()
.unwrap()
.as_bytes(),
b"DeviceGray"
);
assert_eq!(ops(&cs).last().unwrap().0, b"Q");
assert!(cs.tokens[0].span.slice(buf).unwrap().starts_with(b"BI"));
assert!(cs.tokens[0].span.slice(buf).unwrap().ends_with(b"EI"));
}
#[test]
fn id_followed_by_crlf_consumes_both_bytes() {
let buf: &[u8] = b"BI /W 2 /H 2 /CS /G /BPC 8 ID\r\n\x01\x02\x03\x04 EI Q";
let cs = parse(buf);
let ContentTokenKind::InlineImage { data, .. } = &cs.tokens[0].kind else {
panic!("expected inline image, got {:?}", cs.tokens[0].kind);
};
assert_eq!(data.slice(buf).unwrap(), b"\x01\x02\x03\x04");
}
#[test]
fn id_followed_by_a_single_whitespace_consumes_exactly_one_byte() {
for (eol, first) in [
(&b"\r"[..], 0x01u8),
(b"\n", 0x0A),
(b" ", 0x0A),
(b"\t", 0x0A),
] {
let mut buf = b"BI /W 2 /H 2 /CS /G /BPC 8 ID".to_vec();
buf.extend_from_slice(eol);
buf.extend_from_slice(&[first, 0x02, 0x03, 0x04]);
buf.extend_from_slice(b" EI Q");
let cs = parse(&buf);
let ContentTokenKind::InlineImage { data, .. } = &cs.tokens[0].kind else {
panic!("expected inline image");
};
assert_eq!(
data.slice(&buf).unwrap(),
&[first, 0x02, 0x03, 0x04],
"eol {eol:?} must consume exactly one byte"
);
}
}
#[test]
fn inline_image_ascii_hex_self_terminates() {
let buf: &[u8] = b"BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID FF> EI";
let cs = parse(buf);
let ContentTokenKind::InlineImage { params, data } = &cs.tokens[0].kind else {
panic!("expected inline image");
};
assert_eq!(data.slice(buf).unwrap(), b"FF>");
assert_eq!(
params.get(b"Filter").unwrap().as_name().unwrap().as_bytes(),
b"ASCIIHexDecode"
);
}
#[test]
fn inline_image_filtered_falls_back_to_ei_scan() {
let buf: &[u8] = b"BI /W 1 /H 1 /CS /G /BPC 8 /F /Fl ID \x78\x9c\x63\x00\x00 EI";
let cs = parse(buf);
let ContentTokenKind::InlineImage { data, .. } = &cs.tokens[0].kind else {
panic!("expected inline image");
};
assert_eq!(data.slice(buf).unwrap(), b"\x78\x9c\x63\x00\x00");
}
#[test]
fn inline_image_interpolate_vs_indexed_disambiguation() {
let buf: &[u8] = b"BI /W 1 /H 1 /BPC 8 /I true /CS [/I /RGB 0 <000000>] ID \x00 EI";
let cs = parse(buf);
let ContentTokenKind::InlineImage { params, .. } = &cs.tokens[0].kind else {
panic!("expected inline image");
};
assert_eq!(params.get(b"Interpolate").unwrap(), &Object::Boolean(true));
let Object::Array(cs_arr) = params.get(b"ColorSpace").unwrap() else {
panic!("Indexed array expected");
};
assert_eq!(cs_arr[0].as_name().unwrap().as_bytes(), b"Indexed");
assert_eq!(cs_arr[1].as_name().unwrap().as_bytes(), b"DeviceRGB");
}
#[test]
fn unterminated_inline_image_is_error() {
let e =
ContentStream::parse(b"BI /W 9 /H 9 /CS /G /BPC 8 ID \x00\x01".to_vec()).unwrap_err();
assert!(matches!(e, ContentError::UnterminatedInlineImage(_)));
}
#[test]
fn reference_syntax_in_content_is_just_an_unknown_operator() {
let cs = parse(b"1 0 R");
let ops = ops(&cs);
assert_eq!(ops[0].0, b"R");
assert_eq!(ops[0].1.len(), 2);
}
#[test]
fn spans_recover_exact_source_for_every_token() {
let buf: &[u8] = b"q 0.5 0 0 0.5 0 0 cm /Im1 Do Q";
let cs = parse(buf);
let mut last_end = 0;
for t in &cs.tokens {
assert!(t.span.start >= last_end);
assert!(t.span.slice(buf).is_some());
last_end = t.span.end();
}
}
}