#![allow(dead_code)]
use pdf2::{Dictionary, Document, Object, Stream};
use crate::geom::Matrix;
use crate::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PaintType {
Coloured,
Uncoloured,
}
#[derive(Debug, Clone)]
pub(crate) struct Tile {
pub(crate) bbox: [f64; 4],
pub(crate) matrix: Matrix,
pub(crate) x_step: f64,
pub(crate) y_step: f64,
pub(crate) paint_type: PaintType,
pub(crate) tiling_type: i64,
pub(crate) resources: Option<Dictionary>,
pub(crate) content: Vec<u8>,
}
impl Tile {
pub(crate) fn from_stream(document: &Document, stream: &Stream) -> Result<Self> {
let dict = stream.dict();
let bbox = dict
.get(b"BBox")
.and_then(rect_array)
.ok_or_else(|| Error::malformed("a tiling pattern without a /BBox"))?;
let x_step = dict
.get(b"XStep")
.and_then(Object::as_real)
.ok_or_else(|| Error::malformed("a tiling pattern without an /XStep"))?;
let y_step = dict
.get(b"YStep")
.and_then(Object::as_real)
.ok_or_else(|| Error::malformed("a tiling pattern without a /YStep"))?;
if x_step == 0.0 || y_step == 0.0 {
return Err(Error::malformed("a tiling pattern with a zero step"));
}
let paint_type = match dict.get(b"PaintType").and_then(Object::as_integer) {
Some(2) => PaintType::Uncoloured,
Some(1) | None => PaintType::Coloured,
Some(_) => {
return Err(Error::malformed(
"a tiling pattern with an unknown /PaintType",
));
}
};
let tiling_type = dict
.get(b"TilingType")
.and_then(Object::as_integer)
.unwrap_or(1);
let matrix = dict
.get(b"Matrix")
.and_then(matrix_array)
.unwrap_or(Matrix::IDENTITY);
let resources = match dict.get(b"Resources") {
Some(Object::Dictionary(resources)) => Some(resources.clone()),
_ => None,
};
let content = document.decode_stream(stream)?;
Ok(Self {
bbox,
matrix,
x_step,
y_step,
paint_type,
tiling_type,
resources,
content,
})
}
}
fn rect_array(object: &Object) -> Option<[f64; 4]> {
let items = object.as_array()?;
if items.len() < 4 {
return None;
}
let value = |index: usize| items.get(index).and_then(Object::as_real);
Some([value(0)?, value(1)?, value(2)?, value(3)?])
}
fn matrix_array(object: &Object) -> Option<Matrix> {
let items = object.as_array()?;
if items.len() < 6 {
return None;
}
let value = |index: usize| items.get(index).and_then(Object::as_real).unwrap_or(0.0);
Some(Matrix::new(
value(0),
value(1),
value(2),
value(3),
value(4),
value(5),
))
}