Advance native LaTeX execution and preview
This commit is contained in:
1 parent
91f9d76b16
commit
2741546ca8
414 files changed
+99872
-933
No files matched your search
@@ -0,0 +1,420 @@
|
||||
//! Embedded PDF pages and the resource objects reachable from their content.
|
||||
use crate::resources::{LoadedResource, ResourceVersion};
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
io::Write,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) enum PageBox {
|
||||
Media,
|
||||
#[default]
|
||||
Crop,
|
||||
Bleed,
|
||||
Trim,
|
||||
Art,
|
||||
}
|
||||
impl PageBox {
|
||||
fn keys(self) -> &'static [&'static [u8]] {
|
||||
match self {
|
||||
Self::Media => &[b"MediaBox"],
|
||||
Self::Crop => &[b"CropBox", b"MediaBox"],
|
||||
Self::Bleed => &[b"BleedBox", b"CropBox", b"MediaBox"],
|
||||
Self::Trim => &[b"TrimBox", b"CropBox", b"MediaBox"],
|
||||
Self::Art => &[b"ArtBox", b"CropBox", b"MediaBox"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfImage {
|
||||
pub version: ResourceVersion,
|
||||
pub page: usize,
|
||||
pub page_count: usize,
|
||||
pub natural: [i32; 2],
|
||||
extent: [u64; 2],
|
||||
objects: Vec<Vec<Part>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfImageUse {
|
||||
pub id: usize,
|
||||
pub image: Arc<PdfImage>,
|
||||
pub width: i64,
|
||||
pub height: i64,
|
||||
pub depth: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfImageObject {
|
||||
pub image: Arc<PdfImageUse>,
|
||||
pub attributes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl PdfImageUse {
|
||||
pub(crate) fn new(
|
||||
id: usize,
|
||||
image: PdfImage,
|
||||
requested: [Option<i32>; 3],
|
||||
) -> Result<Self, String> {
|
||||
let [w, h] = image.natural.map(i64::from);
|
||||
let [width, height, depth] = requested.map(|value| value.map(i64::from));
|
||||
let ratio = |value: i64, numerator: i64, denominator: i64| {
|
||||
let product = value * numerator;
|
||||
product.signum() * ((product.abs() + denominator / 2) / denominator)
|
||||
};
|
||||
let depth = depth.unwrap_or(0);
|
||||
let (width, height) = match (width, height) {
|
||||
(None, None) => (w, h - depth),
|
||||
(Some(width), None) => (width, ratio(width, h, w) - depth),
|
||||
(None, Some(height)) => (ratio(height + depth, w, h), height),
|
||||
(Some(width), Some(height)) => (width, height),
|
||||
};
|
||||
if [width, height, depth].iter().any(|v| v.abs() > 1073741823) {
|
||||
return Err("native PDF image dimension capacity exceeded".into());
|
||||
}
|
||||
Ok(Self {
|
||||
id,
|
||||
image: Arc::new(image),
|
||||
width,
|
||||
height,
|
||||
depth,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn dimensions(&self) -> (i64, i64, i64) {
|
||||
(self.width, self.height, self.depth)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
enum Part {
|
||||
Bytes(Vec<u8>),
|
||||
Ref(usize),
|
||||
}
|
||||
|
||||
pub(crate) fn real(value: f64) -> String {
|
||||
let body = format!("{value:.15}");
|
||||
body.trim_end_matches('0').trim_end_matches('.').to_owned()
|
||||
}
|
||||
|
||||
impl PdfImage {
|
||||
pub(crate) fn read(
|
||||
resource: LoadedResource,
|
||||
page: usize,
|
||||
kind: PageBox,
|
||||
) -> Result<Self, String> {
|
||||
let doc = Document::load_mem(&resource.data).map_err(|error| {
|
||||
format!(
|
||||
"could not parse PDF image {}: {error}",
|
||||
resource.version.path.display()
|
||||
)
|
||||
})?;
|
||||
if doc.trailer.has(b"Encrypt") {
|
||||
return Err("encrypted PDF image requires a decryption key".into());
|
||||
}
|
||||
let pages = doc.get_pages();
|
||||
let page_id = pages
|
||||
.get(&u32::try_from(page).map_err(|_| "required page does not exist")?)
|
||||
.copied()
|
||||
.ok_or("required page does not exist")?;
|
||||
let chain = page_chain(&doc, page_id)?;
|
||||
let inherited = |name: &[u8]| chain.iter().find_map(|dict| dict.get(name).ok());
|
||||
let bounds = kind
|
||||
.keys()
|
||||
.iter()
|
||||
.find_map(|key| inherited(key))
|
||||
.ok_or("PDF image has no page bounding box")?;
|
||||
let bounds = resolved(&doc, bounds)?
|
||||
.as_array()
|
||||
.map_err(|error| error.to_string())?;
|
||||
let [a, b, c, d] = bounds.as_slice() else {
|
||||
return Err("PDF image bounding box must contain four coordinates".into());
|
||||
};
|
||||
let (a, b, c, d) = (
|
||||
number(&doc, a)?,
|
||||
number(&doc, b)?,
|
||||
number(&doc, c)?,
|
||||
number(&doc, d)?,
|
||||
);
|
||||
let [left, bottom, right, top] = [a.min(c), b.min(d), a.max(c), b.max(d)];
|
||||
let rotation = inherited(b"Rotate")
|
||||
.map(|rotate| {
|
||||
resolved(&doc, rotate)?
|
||||
.as_i64()
|
||||
.map_err(|error| error.to_string())
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(0)
|
||||
.rem_euclid(360);
|
||||
let (matrix, width, height) = match rotation {
|
||||
0 => (
|
||||
[1.0, 0.0, 0.0, 1.0, -left, -bottom],
|
||||
right - left,
|
||||
top - bottom,
|
||||
),
|
||||
90 => (
|
||||
[0.0, -1.0, 1.0, 0.0, -bottom, right],
|
||||
top - bottom,
|
||||
right - left,
|
||||
),
|
||||
180 => (
|
||||
[-1.0, 0.0, 0.0, -1.0, right, top],
|
||||
right - left,
|
||||
top - bottom,
|
||||
),
|
||||
270 => (
|
||||
[0.0, 1.0, -1.0, 0.0, top, -left],
|
||||
top - bottom,
|
||||
right - left,
|
||||
),
|
||||
_ => return Err("PDF image rotation must be a multiple of 90 degrees".into()),
|
||||
};
|
||||
let sp = |bp: f64| -> Result<i32, String> {
|
||||
let value = (bp * 65536.0 * 803.0 / 800.0).round();
|
||||
if !(1.0..=1073741823.0).contains(&value) {
|
||||
return Err("invalid image dimensions".into());
|
||||
}
|
||||
Ok(value as i32)
|
||||
};
|
||||
let natural = [sp(width)?, sp(height)?];
|
||||
let mut contents = Vec::new();
|
||||
if let Ok(content) = chain[0].get(b"Contents") {
|
||||
read_contents(&doc, content, &mut contents, 0)?;
|
||||
}
|
||||
let array = |values: &[f64]| {
|
||||
values
|
||||
.iter()
|
||||
.map(|&v| real(v))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
};
|
||||
let mut graph = Graph {
|
||||
doc: &doc,
|
||||
ids: BTreeMap::new(),
|
||||
bodies: vec![Vec::new()],
|
||||
};
|
||||
let mut form = Vec::new();
|
||||
let header = format!(
|
||||
"/Type /XObject /Subtype /Form /FormType 1 /BBox [{}] /Matrix [{}] /Resources ",
|
||||
array(&[left, bottom, right, top]),
|
||||
array(&matrix)
|
||||
);
|
||||
form.push(Part::Bytes(header.into_bytes()));
|
||||
match inherited(b"Resources") {
|
||||
Some(resources) => graph.render(resources, &mut form, 0)?,
|
||||
None => form.push(Part::Bytes(b"<<>>".to_vec())),
|
||||
}
|
||||
if let Ok(group) = chain[0].get(b"Group") {
|
||||
form.push(Part::Bytes(b" /Group ".to_vec()));
|
||||
graph.render(group, &mut form, 0)?;
|
||||
}
|
||||
let mut stream = format!(" /Length {} >>\nstream\n", contents.len()).into_bytes();
|
||||
stream.extend(contents);
|
||||
stream.extend_from_slice(b"\nendstream");
|
||||
form.push(Part::Bytes(stream));
|
||||
graph.bodies[0] = form;
|
||||
Ok(Self {
|
||||
version: resource.version,
|
||||
page,
|
||||
page_count: pages.len(),
|
||||
natural,
|
||||
extent: [width.to_bits(), height.to_bits()],
|
||||
objects: graph.bodies,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn extent(&self) -> [f64; 2] {
|
||||
self.extent.map(f64::from_bits)
|
||||
}
|
||||
|
||||
pub(crate) fn append_to(&self, pdf: &mut Vec<Vec<u8>>, attributes: &[u8]) -> usize {
|
||||
let base = pdf.len() + 1;
|
||||
pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| {
|
||||
let mut body = Vec::new();
|
||||
if index == 0 {
|
||||
body.extend_from_slice(b"<< ");
|
||||
if !attributes.is_empty() {
|
||||
body.extend_from_slice(attributes);
|
||||
body.push(b'\n');
|
||||
}
|
||||
}
|
||||
for part in parts {
|
||||
match part {
|
||||
Part::Bytes(bytes) => body.extend_from_slice(bytes),
|
||||
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
|
||||
}
|
||||
}
|
||||
body
|
||||
}));
|
||||
base
|
||||
}
|
||||
}
|
||||
|
||||
fn page_chain(doc: &Document, mut id: ObjectId) -> Result<Vec<&Dictionary>, String> {
|
||||
let mut chain = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
loop {
|
||||
if chain.len() >= 64 || !seen.insert(id) {
|
||||
return Err("PDF image page tree is cyclic or too deep".into());
|
||||
}
|
||||
let dict = doc.get_dictionary(id).map_err(|error| error.to_string())?;
|
||||
chain.push(dict);
|
||||
let Ok(parent) = dict.get(b"Parent") else {
|
||||
return Ok(chain);
|
||||
};
|
||||
id = parent.as_reference().map_err(|error| error.to_string())?;
|
||||
}
|
||||
}
|
||||
|
||||
fn resolved<'a>(doc: &'a Document, mut object: &'a Object) -> Result<&'a Object, String> {
|
||||
for _ in 0..64 {
|
||||
let Object::Reference(id) = object else {
|
||||
return Ok(object);
|
||||
};
|
||||
object = doc.objects.get(id).ok_or("missing object in PDF image")?;
|
||||
}
|
||||
Err("PDF image object reference chain is too deep".into())
|
||||
}
|
||||
|
||||
fn number(doc: &Document, object: &Object) -> Result<f64, String> {
|
||||
let value = match resolved(doc, object)? {
|
||||
Object::Integer(value) => *value as f64,
|
||||
Object::Real(value) => *value,
|
||||
_ => return Err("PDF image bounding box contains a non-numeric value".into()),
|
||||
};
|
||||
if !value.is_finite() {
|
||||
return Err("PDF image bounding box contains a non-finite value".into());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn read_contents(
|
||||
doc: &Document,
|
||||
object: &Object,
|
||||
out: &mut Vec<u8>,
|
||||
depth: usize,
|
||||
) -> Result<(), String> {
|
||||
if depth >= 64 {
|
||||
return Err("PDF image contents are too deeply nested".into());
|
||||
}
|
||||
match resolved(doc, object)? {
|
||||
Object::Null => {}
|
||||
Object::Stream(stream) => {
|
||||
if stream.dict.has(b"Filter") {
|
||||
out.extend(
|
||||
stream
|
||||
.decompressed_content()
|
||||
.map_err(|error| error.to_string())?,
|
||||
);
|
||||
} else {
|
||||
out.extend_from_slice(&stream.content);
|
||||
}
|
||||
out.push(b'\n');
|
||||
}
|
||||
Object::Array(items) => {
|
||||
for item in items {
|
||||
read_contents(doc, item, out, depth + 1)?;
|
||||
}
|
||||
}
|
||||
_ => return Err("PDF image contents must be a stream or array of streams".into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Graph<'a> {
|
||||
doc: &'a Document,
|
||||
ids: BTreeMap<ObjectId, usize>,
|
||||
bodies: Vec<Vec<Part>>,
|
||||
}
|
||||
|
||||
impl Graph<'_> {
|
||||
fn render(&mut self, value: &Object, out: &mut Vec<Part>, depth: usize) -> Result<(), String> {
|
||||
if depth >= 128 {
|
||||
return Err("PDF image resource graph is too deeply nested".into());
|
||||
}
|
||||
let bytes = |out: &mut Vec<Part>, bytes: &[u8]| {
|
||||
if let Some(Part::Bytes(last)) = out.last_mut() {
|
||||
last.extend_from_slice(bytes);
|
||||
} else {
|
||||
out.push(Part::Bytes(bytes.to_vec()));
|
||||
}
|
||||
};
|
||||
match value {
|
||||
Object::Null => bytes(out, b"null"),
|
||||
Object::Boolean(true) => bytes(out, b"true"),
|
||||
Object::Boolean(false) => bytes(out, b"false"),
|
||||
Object::Integer(n) => bytes(out, n.to_string().as_bytes()),
|
||||
Object::Real(n) if n.is_finite() => bytes(out, real(*n).as_bytes()),
|
||||
Object::Real(_) => return Err("non-finite number in PDF image".into()),
|
||||
Object::Name(name) => {
|
||||
let mut encoded = vec![b'/'];
|
||||
for &ch in name {
|
||||
if (33..=126).contains(&ch) && !b"#%()<>[]{}/".contains(&ch) {
|
||||
encoded.push(ch);
|
||||
} else {
|
||||
write!(encoded, "#{ch:02X}").unwrap();
|
||||
}
|
||||
}
|
||||
bytes(out, &encoded);
|
||||
}
|
||||
Object::String(data, _) => {
|
||||
let mut encoded = vec![b'<'];
|
||||
for &ch in data {
|
||||
write!(encoded, "{ch:02X}").unwrap();
|
||||
}
|
||||
encoded.push(b'>');
|
||||
bytes(out, &encoded);
|
||||
}
|
||||
Object::Array(values) => {
|
||||
bytes(out, b"[");
|
||||
for child in values {
|
||||
self.render(child, out, depth + 1)?;
|
||||
bytes(out, b" ");
|
||||
}
|
||||
bytes(out, b"]");
|
||||
}
|
||||
Object::Dictionary(dict) => {
|
||||
bytes(out, b"<<");
|
||||
for (key, child) in dict.iter() {
|
||||
self.render(&Object::Name(key.clone()), out, depth + 1)?;
|
||||
bytes(out, b" ");
|
||||
self.render(child, out, depth + 1)?;
|
||||
bytes(out, b" ");
|
||||
}
|
||||
bytes(out, b">>");
|
||||
}
|
||||
Object::Stream(stream) => {
|
||||
let mut dict = stream.dict.clone();
|
||||
dict.set("Length", stream.content.len() as i64);
|
||||
self.render(&Object::Dictionary(dict), out, depth + 1)?;
|
||||
bytes(out, b"\nstream\n");
|
||||
bytes(out, &stream.content);
|
||||
bytes(out, b"\nendstream");
|
||||
}
|
||||
Object::Reference(id) => {
|
||||
let index = match self.ids.get(id) {
|
||||
Some(index) => *index,
|
||||
None => {
|
||||
let new_index = self.bodies.len();
|
||||
self.ids.insert(*id, new_index);
|
||||
self.bodies.push(Vec::new());
|
||||
let mut body = Vec::new();
|
||||
let object = self
|
||||
.doc
|
||||
.objects
|
||||
.get(id)
|
||||
.ok_or("missing resource object in PDF image")?;
|
||||
self.render(object, &mut body, depth + 1)?;
|
||||
self.bodies[new_index] = body;
|
||||
new_index
|
||||
}
|
||||
};
|
||||
out.push(Part::Ref(index));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user