Import named PDF pages and images in the XeLaTeX device
This commit is contained in:
1 parent
5ad5c40002
commit
d875b69280
10 files changed
+797
-292
No files matched your search
@@ -52,6 +52,8 @@ pub enum PdfGraphics {
|
||||
number: u32,
|
||||
options: super::xdv_navigation::FormOptions,
|
||||
source: crate::execution::TokenOrigin,
|
||||
#[serde(default)]
|
||||
imported_available: bool,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,174 +1,231 @@
|
||||
//! The xdvipdfmx raster image device special.
|
||||
use super::Affine;
|
||||
use crate::pdf_image::{PdfImage, PdfImageUse, real};
|
||||
use lopdf::{Object, content::Content};
|
||||
use std::{iter::Peekable, str::SplitAsciiWhitespace, sync::Arc};
|
||||
//! Image selection and placement from the xdvipdfmx device specials.
|
||||
use super::{
|
||||
Affine,
|
||||
xdv_navigation::FormOptions,
|
||||
xdv_object::{
|
||||
Dictionary, Position, Value, dictionary, identifier, parse_object_prefix, trim_pdf,
|
||||
},
|
||||
};
|
||||
use crate::pdf_image::{PageBox, PageSelection, PdfImage, PdfImageUse, PdfPageGeometry, real};
|
||||
use std::{iter::Peekable, sync::Arc};
|
||||
|
||||
pub(crate) struct ImageSpecial {
|
||||
pub file: String,
|
||||
pub attributes: Vec<u8>,
|
||||
pub name: Option<Vec<u8>>,
|
||||
pub(super) attributes: Dictionary,
|
||||
pub hidden: bool,
|
||||
bbox: Option<[f64; 4]>,
|
||||
dimensions: [Option<f64>; 3],
|
||||
transform: Affine,
|
||||
clip: bool,
|
||||
pub page: PageSelection,
|
||||
pub page_box: PageBox,
|
||||
pub placement: FormOptions,
|
||||
}
|
||||
|
||||
impl ImageSpecial {
|
||||
pub(crate) fn parse(data: &[u8], magnification: i32) -> Result<Option<Self>, String> {
|
||||
let Some(body) = data.trim_ascii_start().strip_prefix(b"pdf:") else {
|
||||
return Ok(None);
|
||||
pub(crate) fn parse(input: &[u8], position: Position) -> Result<(Self, Vec<String>), String> {
|
||||
let input = trim_pdf(input);
|
||||
let (name, input) = if input.starts_with(b"@") {
|
||||
let (name, rest) = identifier(input)?;
|
||||
(Some(name.to_vec()), rest)
|
||||
} else {
|
||||
(None, input)
|
||||
};
|
||||
let body = body.trim_ascii_start();
|
||||
let name_end = body
|
||||
let mut quoted = false;
|
||||
let mut escaped = false;
|
||||
let file_pos = input
|
||||
.iter()
|
||||
.position(|byte| byte.is_ascii_whitespace() || matches!(byte, b'(' | b'<'))
|
||||
.unwrap_or(body.len());
|
||||
if !matches!(&body[..name_end], b"image" | b"img") {
|
||||
return Ok(None);
|
||||
}
|
||||
let body = &body[name_end..];
|
||||
let file_pos = body
|
||||
.iter()
|
||||
.position(|byte| matches!(byte, b'(' | b'<'))
|
||||
.position(|&byte| {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if quoted && byte == b'\\' {
|
||||
escaped = true;
|
||||
} else if byte == b'"' {
|
||||
quoted = !quoted;
|
||||
} else if !quoted && matches!(byte, b'(' | b'<') {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
})
|
||||
.ok_or("missing XDV image filename string")?;
|
||||
let parameters =
|
||||
std::str::from_utf8(&body[..file_pos]).map_err(|error| error.to_string())?;
|
||||
let mut words = parameters.split_ascii_whitespace().peekable();
|
||||
let mut bbox = None;
|
||||
let mut dimensions = [None; 3];
|
||||
let mut clip = true;
|
||||
std::str::from_utf8(&input[..file_pos]).map_err(|_| "invalid XDV image options")?;
|
||||
let mut rest = parameters;
|
||||
let mut words = std::iter::from_fn(|| {
|
||||
rest = rest.trim_ascii_start();
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let end = if let Some(quoted) = rest.strip_prefix('"') {
|
||||
let mut escaped = false;
|
||||
quoted
|
||||
.bytes()
|
||||
.position(|byte| {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if byte == b'\\' {
|
||||
escaped = true;
|
||||
} else if byte == b'"' {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
})
|
||||
.map_or(rest.len(), |index| index + 2)
|
||||
} else {
|
||||
rest.bytes()
|
||||
.position(|byte| byte.is_ascii_whitespace())
|
||||
.unwrap_or(rest.len())
|
||||
};
|
||||
let (word, tail) = rest.split_at(end);
|
||||
rest = tail;
|
||||
Some(word)
|
||||
})
|
||||
.peekable();
|
||||
let mut page = 1;
|
||||
let mut destination = None;
|
||||
let mut page_box = PageBox::Crop;
|
||||
let mut hidden = false;
|
||||
let mut scales = [None; 2];
|
||||
let mut overall_scale = None;
|
||||
let mut rotation = 0.0;
|
||||
let mut matrix = None;
|
||||
let mut placement = FormOptions::default();
|
||||
while let Some(parameter) = words.next() {
|
||||
match parameter {
|
||||
"bbox" => {
|
||||
bbox = Some([
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
]);
|
||||
}
|
||||
"width" => dimensions[0] = Some(length(&mut words, magnification)?),
|
||||
"height" => dimensions[1] = Some(length(&mut words, magnification)?),
|
||||
"depth" => dimensions[2] = Some(length(&mut words, magnification)?),
|
||||
"scale" => overall_scale = Some(number(words.next())?),
|
||||
"xscale" => scales[0] = Some(number(words.next())?),
|
||||
"yscale" => scales[1] = Some(number(words.next())?),
|
||||
"rotate" => rotation = number(words.next())?,
|
||||
"matrix" => {
|
||||
matrix = Some(Affine([
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
]));
|
||||
}
|
||||
"clip" => clip = number(words.next())? != 0.0,
|
||||
"hide" => hidden = true,
|
||||
"page" if matches!(number(words.next())?, 0.0 | 1.0) => {}
|
||||
_ => return Err(format!("unsupported XDV raster image option {parameter}")),
|
||||
}
|
||||
}
|
||||
if overall_scale.is_some() && scales.iter().any(Option::is_some) {
|
||||
return Err("XDV image scale conflicts with an axis scale".into());
|
||||
}
|
||||
if dimensions[0].is_some() && scales[0].is_some() {
|
||||
scales[0] = None;
|
||||
} else if (dimensions[1].is_some() || dimensions[2].is_some()) && scales[1].is_some() {
|
||||
scales[1] = None;
|
||||
}
|
||||
let [sx, sy] = scales.map(|value| value.or(overall_scale).unwrap_or(1.0));
|
||||
let (sin, cos) = rotation.to_radians().sin_cos();
|
||||
let transform =
|
||||
matrix.unwrap_or(Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0]));
|
||||
|
||||
// The suffix shares the PDF string and dictionary grammar. Decode
|
||||
// the objects with the same parser used for native page resources.
|
||||
let mut pdf_objects = body[file_pos..].to_vec();
|
||||
pdf_objects.extend_from_slice(b"\nq");
|
||||
let parsed = Content::decode(&pdf_objects).map_err(|error| error.to_string())?;
|
||||
let [operation] = parsed.operations.as_slice() else {
|
||||
return Err("invalid PDF objects in XDV image special".into());
|
||||
};
|
||||
let (file, dictionary) = match operation.operands.as_slice() {
|
||||
[Object::String(file, _)] if operation.operator == "q" => (file, None),
|
||||
[Object::String(file, _), Object::Dictionary(dict)] if operation.operator == "q" => {
|
||||
(file, Some(dict))
|
||||
}
|
||||
_ => {
|
||||
return Err("expected filename and optional XDV image attribute dictionary".into());
|
||||
}
|
||||
};
|
||||
let file = String::from_utf8(file.clone()).map_err(|error| error.to_string())?;
|
||||
let mut attributes = Vec::new();
|
||||
if let Some(dictionary) = dictionary {
|
||||
for (key, value) in dictionary.iter() {
|
||||
match (key.as_slice(), value) {
|
||||
(b"Decode", Object::Array(values)) => {
|
||||
if values.is_empty() || values.len() % 2 != 0 {
|
||||
return Err("XDV image Decode array requires pairs".into());
|
||||
}
|
||||
attributes.extend_from_slice(b"/Decode [");
|
||||
for value in values {
|
||||
let number = match value {
|
||||
Object::Integer(value) => *value as f64,
|
||||
Object::Real(value) if value.is_finite() => *value,
|
||||
_ => {
|
||||
return Err(
|
||||
"XDV image Decode array requires finite numbers".into()
|
||||
);
|
||||
}
|
||||
};
|
||||
attributes.extend_from_slice(real(number).as_bytes());
|
||||
attributes.push(b' ');
|
||||
}
|
||||
attributes.extend_from_slice(b"] ");
|
||||
"page" => {
|
||||
let requested = number(words.next())?.trunc();
|
||||
if !(f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&requested) {
|
||||
return Err("XDV image page number out of range".into());
|
||||
}
|
||||
(b"Interpolate", Object::Boolean(value)) => {
|
||||
attributes.extend_from_slice(if *value {
|
||||
b"/Interpolate true "
|
||||
page = requested as i32;
|
||||
}
|
||||
"pagebox" => {
|
||||
page_box = match words.next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("mediabox") => PageBox::Media,
|
||||
Some("cropbox") => PageBox::Crop,
|
||||
Some("bleedbox") => PageBox::Bleed,
|
||||
Some("trimbox") => PageBox::Trim,
|
||||
Some("artbox") => PageBox::Art,
|
||||
_ => return Err("invalid XDV image page box".into()),
|
||||
};
|
||||
}
|
||||
"named" => {
|
||||
let word = words
|
||||
.next()
|
||||
.and_then(|word| word.strip_prefix('"'))
|
||||
.and_then(|word| word.strip_suffix('"'))
|
||||
.ok_or("expected quoted XDV image page destination")?;
|
||||
let mut bytes = word.bytes();
|
||||
let mut name = Vec::with_capacity(word.len());
|
||||
while let Some(byte) = bytes.next() {
|
||||
name.push(if byte == b'\\' {
|
||||
bytes
|
||||
.next()
|
||||
.ok_or("invalid XDV image page destination escape")?
|
||||
} else {
|
||||
b"/Interpolate false "
|
||||
byte
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unsupported XDV image attribute {}",
|
||||
String::from_utf8_lossy(key)
|
||||
));
|
||||
destination = Some(name);
|
||||
}
|
||||
word if placement.read_option(word, &mut words, position.magnification)? => {}
|
||||
word => return Err(format!("unsupported XDV image option {word}")),
|
||||
}
|
||||
}
|
||||
let warnings = placement.finish()?;
|
||||
let (Value::String(file), rest) = parse_object_prefix(&input[file_pos..], position)? else {
|
||||
return Err("expected XDV image filename string".into());
|
||||
};
|
||||
let attributes = if rest.is_empty() {
|
||||
Dictionary::new()
|
||||
} else {
|
||||
dictionary(rest, position)?
|
||||
};
|
||||
let file = String::from_utf8(file).map_err(|error| error.to_string())?;
|
||||
Ok((
|
||||
Self {
|
||||
file,
|
||||
name,
|
||||
attributes,
|
||||
hidden,
|
||||
page: destination.map_or(PageSelection::Number(page), PageSelection::Named),
|
||||
page_box,
|
||||
placement,
|
||||
},
|
||||
warnings,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn page_geometry(&self, geometry: PdfPageGeometry) -> ImportGeometry {
|
||||
ImportGeometry::page(geometry, &self.attributes)
|
||||
}
|
||||
|
||||
pub(crate) fn raster_attributes(&self) -> Result<Vec<u8>, String> {
|
||||
let mut attributes = Vec::new();
|
||||
for (key, value) in &self.attributes {
|
||||
match (key.as_slice(), value) {
|
||||
(b"Decode", Value::Array(values))
|
||||
if !values.is_empty() && values.len() % 2 == 0 =>
|
||||
{
|
||||
attributes.extend_from_slice(b"/Decode [");
|
||||
for value in values {
|
||||
let number = match value {
|
||||
Value::Integer(value) => *value as f64,
|
||||
Value::Real(value) => f64::from_bits(*value),
|
||||
_ => {
|
||||
return Err("XDV image Decode array requires finite numbers".into());
|
||||
}
|
||||
};
|
||||
attributes.extend_from_slice(real(number).as_bytes());
|
||||
attributes.push(b' ');
|
||||
}
|
||||
attributes.extend_from_slice(b"] ");
|
||||
}
|
||||
(b"Interpolate", Value::Boolean(value)) => {
|
||||
attributes.extend_from_slice(if *value {
|
||||
b"/Interpolate true "
|
||||
} else {
|
||||
b"/Interpolate false "
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unsupported XDV raster image attribute {}",
|
||||
String::from_utf8_lossy(key)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(Self {
|
||||
file,
|
||||
attributes,
|
||||
hidden,
|
||||
bbox,
|
||||
dimensions,
|
||||
transform,
|
||||
clip,
|
||||
}))
|
||||
Ok(attributes)
|
||||
}
|
||||
|
||||
pub(crate) fn place(&self, id: usize, image: Arc<PdfImage>) -> Result<PdfImageUse, String> {
|
||||
let [natural_w, natural_h] = image.extent();
|
||||
let ([pixels_w, pixels_h], _) = image
|
||||
pub(crate) fn place_raster(
|
||||
&self,
|
||||
id: usize,
|
||||
image: Arc<PdfImage>,
|
||||
) -> Result<PdfImageUse, String> {
|
||||
let (pixels, _) = image
|
||||
.raster_frame()
|
||||
.ok_or("XDV special needs a raster image")?;
|
||||
let [left, bottom, right, top] = self.bbox.unwrap_or([0.0, 0.0, natural_w, natural_h]);
|
||||
let (matrix, annotation_box) = self.placement.raster_transform(image.extent(), pixels)?;
|
||||
PdfImageUse::new_xdv_raster_special(
|
||||
id,
|
||||
image,
|
||||
matrix,
|
||||
annotation_box,
|
||||
self.placement.clip_enabled(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl FormOptions {
|
||||
pub(crate) fn raster_transform(
|
||||
self,
|
||||
[natural_w, natural_h]: [f64; 2],
|
||||
[pixels_w, pixels_h]: [i64; 2],
|
||||
) -> Result<(Affine, Option<[f64; 4]>), String> {
|
||||
let [left, bottom, right, top] = self
|
||||
.requested_box()
|
||||
.unwrap_or([0.0, 0.0, natural_w, natural_h]);
|
||||
let [box_w, box_h] = [right - left, top - bottom];
|
||||
if box_w <= 0.0 || box_h <= 0.0 {
|
||||
return Err("XDV image bounding box must have positive dimensions".into());
|
||||
}
|
||||
let [requested_w, requested_h, depth] = self.dimensions;
|
||||
let [requested_w, requested_h, depth] = self.dimensions();
|
||||
let requested_h = requested_h.or(depth.map(|_| 0.0));
|
||||
let depth = depth.unwrap_or(0.0);
|
||||
let [xscale, yscale] = [natural_w / box_w, natural_h / box_h];
|
||||
@@ -191,26 +248,104 @@ impl ImageSpecial {
|
||||
-left * width / natural_w,
|
||||
-bottom * height / natural_h - depth,
|
||||
]);
|
||||
let annotation_box = self.bbox.is_some().then_some([
|
||||
let annotation_box = self.requested_box().is_some().then_some([
|
||||
left / natural_w,
|
||||
bottom / natural_h,
|
||||
box_w / natural_w,
|
||||
box_h / natural_h,
|
||||
]);
|
||||
PdfImageUse::new_xdv_raster_special(
|
||||
id, image, self.transform.concatenate(sizing), annotation_box, self.clip,
|
||||
)
|
||||
Ok((self.affine().concatenate(sizing), annotation_box))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum ImportGeometry {
|
||||
Page { bounds: [u64; 4], fitting: [u64; 4] },
|
||||
Raster { extent: [u64; 2], pixels: [i64; 2] },
|
||||
}
|
||||
|
||||
impl ImportGeometry {
|
||||
fn page(geometry: PdfPageGeometry, attributes: &Dictionary) -> Self {
|
||||
let [left, bottom, right, top] = geometry.bounds;
|
||||
let rect = |points: [[f64; 2]; 4]| {
|
||||
let [x, y] = points[0];
|
||||
points[1..]
|
||||
.iter()
|
||||
.fold([x, y, x, y], |[l, b, r, t], &[x, y]| {
|
||||
[l.min(x), b.min(y), r.max(x), t.max(y)]
|
||||
})
|
||||
.map(f64::to_bits)
|
||||
};
|
||||
let normal = [[left, bottom], [right, bottom], [right, top], [left, top]]
|
||||
.map(|[x, y]| geometry.matrix.point(x, y));
|
||||
let mut sizing = normal;
|
||||
// The reference driver's stored fitting rectangle also samples the
|
||||
// unshifted lower edge and the transformed lower-right x-axis point.
|
||||
sizing[0][1] = bottom;
|
||||
sizing[1] = geometry.matrix.point(right, 0.0);
|
||||
let [l, b, r, t] = numeric_attribute(attributes, b"BBox").unwrap_or(geometry.bounds);
|
||||
let matrix = numeric_attribute(attributes, b"Matrix").map_or(geometry.matrix, Affine);
|
||||
let painted = [[l, b], [r, b], [r, t], [l, t]].map(|[x, y]| matrix.point(x, y));
|
||||
Self::Page {
|
||||
bounds: rect(painted),
|
||||
fitting: rect(sizing),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn place(
|
||||
&self,
|
||||
number: u32,
|
||||
options: FormOptions,
|
||||
available: bool,
|
||||
) -> Result<crate::pdf_device::forms::FormUse, String> {
|
||||
match *self {
|
||||
Self::Page { bounds, fitting } => options.place_xobject(
|
||||
number,
|
||||
bounds.map(f64::from_bits),
|
||||
available.then(|| fitting.map(f64::from_bits)),
|
||||
),
|
||||
Self::Raster { extent, pixels } => {
|
||||
let bounds = [0.0, 0.0, 1.0, 1.0];
|
||||
if !available {
|
||||
return options.place_xobject(number, bounds, None);
|
||||
}
|
||||
let (matrix, clip) =
|
||||
options.raster_transform(extent.map(f64::from_bits), pixels)?;
|
||||
let clip = clip
|
||||
.filter(|_| options.clip_enabled())
|
||||
.map(|[x, y, width, height]| [x, y, x + width, y + height]);
|
||||
FormOptions::placed(number, bounds, matrix, clip)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn numeric_attribute<const N: usize>(attributes: &Dictionary, name: &[u8]) -> Option<[f64; N]> {
|
||||
let Value::Array(values) = attributes.get(name)? else {
|
||||
return None;
|
||||
};
|
||||
if values.len() != N {
|
||||
return None;
|
||||
}
|
||||
let mut numbers = [0.0; N];
|
||||
for (number, value) in numbers.iter_mut().zip(values) {
|
||||
*number = match value {
|
||||
Value::Real(value) => f64::from_bits(*value),
|
||||
Value::Integer(value) => *value as f64,
|
||||
_ => return None,
|
||||
};
|
||||
}
|
||||
Some(numbers)
|
||||
}
|
||||
|
||||
pub(super) fn number(word: Option<&str>) -> Result<f64, &'static str> {
|
||||
word.and_then(|word| word.parse::<f64>().ok())
|
||||
.filter(|value| value.is_finite())
|
||||
.ok_or("invalid XDV image number")
|
||||
}
|
||||
|
||||
pub(super) fn length(
|
||||
words: &mut Peekable<SplitAsciiWhitespace<'_>>,
|
||||
pub(super) fn length<'a>(
|
||||
words: &mut Peekable<impl Iterator<Item = &'a str>>,
|
||||
magnification: i32,
|
||||
) -> Result<f64, &'static str> {
|
||||
let word = words.next().ok_or("missing XDV image length")?;
|
||||
|
||||
@@ -8,11 +8,13 @@ use crate::{
|
||||
pdf_device::{
|
||||
Affine, PdfGraphics, PdfLiteralMode,
|
||||
forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement},
|
||||
xdv_image::{length, number},
|
||||
xdv_image::{ImageSpecial, ImportGeometry, length, number},
|
||||
xdv_page_origin,
|
||||
},
|
||||
pdf_image::{PageBox, PageSelection},
|
||||
provenance::PaintSource,
|
||||
render::{DisplayItem, DisplayList},
|
||||
resources::ResourceVersion,
|
||||
};
|
||||
|
||||
use super::super::xdv_object::{identifier, trim_pdf};
|
||||
@@ -42,58 +44,71 @@ impl FormOptions {
|
||||
.peekable();
|
||||
let mut options = Self::default();
|
||||
while let Some(word) = words.next() {
|
||||
match word {
|
||||
"bbox" => {
|
||||
let mut bounds = [0; 4];
|
||||
for entry in &mut bounds {
|
||||
*entry = number(words.next())?.to_bits();
|
||||
}
|
||||
options.bbox = Some(bounds);
|
||||
}
|
||||
"width" | "height" | "depth" => {
|
||||
let index = match word {
|
||||
"width" => 0,
|
||||
"height" => 1,
|
||||
_ => 2,
|
||||
};
|
||||
options.size[index] = Some(length(&mut words, magnification)?.to_bits());
|
||||
}
|
||||
"scale" => options.scale = Some(number(words.next())?.to_bits()),
|
||||
"xscale" | "yscale" => {
|
||||
options.axis_scale[usize::from(word == "yscale")] =
|
||||
Some(number(words.next())?.to_bits());
|
||||
}
|
||||
"rotate" => options.rotation = Some(number(words.next())?.to_bits()),
|
||||
"matrix" => {
|
||||
let mut matrix = [0; 6];
|
||||
for entry in &mut matrix {
|
||||
*entry = number(words.next())?.to_bits();
|
||||
}
|
||||
options.matrix = Some(matrix);
|
||||
}
|
||||
"clip" => options.clip = Some(number(words.next())? != 0.0),
|
||||
"hide" => {}
|
||||
_ => return Err(format!("unsupported XDV form option {word}")),
|
||||
if word != "hide" && !options.read_option(word, &mut words, magnification)? {
|
||||
return Err(format!("unsupported XDV form option {word}"));
|
||||
}
|
||||
}
|
||||
if let Some(bounds) = options.bbox {
|
||||
let warnings = options.finish()?;
|
||||
Ok((options, warnings))
|
||||
}
|
||||
|
||||
pub(crate) fn read_option<'a>(
|
||||
&mut self,
|
||||
word: &str,
|
||||
words: &mut std::iter::Peekable<impl Iterator<Item = &'a str>>,
|
||||
magnification: i32,
|
||||
) -> Result<bool, String> {
|
||||
match word {
|
||||
"bbox" => {
|
||||
let mut bounds = [0; 4];
|
||||
for entry in &mut bounds {
|
||||
*entry = number(words.next())?.to_bits();
|
||||
}
|
||||
self.bbox = Some(bounds);
|
||||
}
|
||||
"width" | "height" | "depth" => {
|
||||
let index = match word {
|
||||
"width" => 0,
|
||||
"height" => 1,
|
||||
_ => 2,
|
||||
};
|
||||
self.size[index] = Some(length(words, magnification)?.to_bits());
|
||||
}
|
||||
"scale" => self.scale = Some(number(words.next())?.to_bits()),
|
||||
"xscale" | "yscale" => {
|
||||
self.axis_scale[usize::from(word == "yscale")] =
|
||||
Some(number(words.next())?.to_bits());
|
||||
}
|
||||
"rotate" => self.rotation = Some(number(words.next())?.to_bits()),
|
||||
"matrix" => {
|
||||
let mut matrix = [0; 6];
|
||||
for entry in &mut matrix {
|
||||
*entry = number(words.next())?.to_bits();
|
||||
}
|
||||
self.matrix = Some(matrix);
|
||||
}
|
||||
"clip" => self.clip = Some(number(words.next())? != 0.0),
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn finish(&mut self) -> Result<Vec<String>, String> {
|
||||
if let Some(bounds) = self.bbox {
|
||||
checked_box(bounds.map(f64::from_bits))?;
|
||||
}
|
||||
let [width, height, depth] = options.size;
|
||||
let [sx, sy] = options.axis_scale;
|
||||
let [width, height, depth] = self.size;
|
||||
let [sx, sy] = self.axis_scale;
|
||||
let warning = if width.is_some() && sx.is_some() {
|
||||
options.axis_scale[0] = Some(1.0f64.to_bits());
|
||||
self.axis_scale[0] = Some(1.0f64.to_bits());
|
||||
Some("Can't supply both width and xscale. Ignore xscale.")
|
||||
} else if (height.is_some() || depth.is_some()) && sy.is_some() {
|
||||
options.axis_scale[1] = Some(1.0f64.to_bits());
|
||||
self.axis_scale[1] = Some(1.0f64.to_bits());
|
||||
Some("Can't supply both height/depth and yscale. Ignore yscale.")
|
||||
} else if options.scale.is_some() && (sx.is_some() || sy.is_some()) {
|
||||
} else if self.scale.is_some() && (sx.is_some() || sy.is_some()) {
|
||||
return Err("XDV form scale conflicts with an axis scale".into());
|
||||
} else if options.matrix.is_some()
|
||||
&& (sx.is_some()
|
||||
|| sy.is_some()
|
||||
|| options.scale.is_some()
|
||||
|| options.rotation.is_some())
|
||||
} else if self.matrix.is_some()
|
||||
&& (sx.is_some() || sy.is_some() || self.scale.is_some() || self.rotation.is_some())
|
||||
{
|
||||
Some(
|
||||
"Can't supply transform matrix along with scales or rotate. Ignore scales and rotate.",
|
||||
@@ -101,7 +116,7 @@ impl FormOptions {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((options, warning.into_iter().map(String::from).collect()))
|
||||
Ok(warning.into_iter().map(String::from).collect())
|
||||
}
|
||||
|
||||
fn capture_bounds(self) -> Result<[u64; 4], String> {
|
||||
@@ -124,34 +139,35 @@ impl FormOptions {
|
||||
capture_y: Option<f64>,
|
||||
) -> Result<FormUse, String> {
|
||||
let captured = captured.map(f64::from_bits);
|
||||
let user_bbox = self.bbox.map(|values| values.map(f64::from_bits));
|
||||
let transform = if let Some(matrix) = self.matrix {
|
||||
Affine(matrix.map(f64::from_bits))
|
||||
} else {
|
||||
let [sx, sy] = self
|
||||
.axis_scale
|
||||
.map(|value| value.or(self.scale).map_or(1.0, f64::from_bits));
|
||||
let (sin, cos) = self
|
||||
.rotation
|
||||
.map_or(0.0, f64::from_bits)
|
||||
.to_radians()
|
||||
.sin_cos();
|
||||
Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0])
|
||||
};
|
||||
|
||||
// A reserved forward XObject uses the external matrix and explicit
|
||||
// clip at its use site. The driver has no Form dimensions there yet.
|
||||
let transform = if let Some(capture_y) = capture_y {
|
||||
let fitting = capture_y.map(|capture_y| {
|
||||
let [left, bottom, right, top] = captured;
|
||||
// xdvipdfmx 20260113 fits against a separate stored extent.
|
||||
// Its vertical samples are the unshifted lower edge and the
|
||||
// capture-origin-adjusted zero and upper edge (pdf_ximage_set_form).
|
||||
// The reference Form extent uses the unshifted lower edge and
|
||||
// the capture-origin-adjusted zero and upper edge.
|
||||
let y = [-capture_y, top - capture_y];
|
||||
let extent = y[0].max(y[1]).max(bottom) - y[0].min(y[1]).min(bottom);
|
||||
[
|
||||
left,
|
||||
y[0].min(y[1]).min(bottom),
|
||||
right,
|
||||
y[0].max(y[1]).max(bottom),
|
||||
]
|
||||
});
|
||||
self.place_xobject(number, captured, fitting)
|
||||
}
|
||||
|
||||
pub(crate) fn place_xobject(
|
||||
self,
|
||||
number: u32,
|
||||
captured: [f64; 4],
|
||||
fitting: Option<[f64; 4]>,
|
||||
) -> Result<FormUse, String> {
|
||||
let user_bbox = self.bbox.map(|values| values.map(f64::from_bits));
|
||||
let transform = self.affine();
|
||||
// A reserved forward reference has no natural dimensions yet.
|
||||
let transform = if let Some([left, bottom, right, top]) = fitting {
|
||||
let (natural, offset) = if let Some([x0, y0, x1, y1]) = user_bbox {
|
||||
([x1 - x0, y1 - y0], [-x0, -y0])
|
||||
} else {
|
||||
([right - left, extent], [0.0, 0.0])
|
||||
([right - left, top - bottom], [0.0, 0.0])
|
||||
};
|
||||
let [natural_x, natural_y] = natural.map(|n| if n == 0.0 { 1.0 } else { n });
|
||||
let [width, height, depth] = self.size.map(|v| v.map(f64::from_bits));
|
||||
@@ -174,12 +190,20 @@ impl FormOptions {
|
||||
} else {
|
||||
transform
|
||||
};
|
||||
let clip = user_bbox.filter(|_| self.clip_enabled());
|
||||
Self::placed(number, captured, transform, clip)
|
||||
}
|
||||
|
||||
pub(crate) fn placed(
|
||||
number: u32,
|
||||
captured: [f64; 4],
|
||||
transform: Affine,
|
||||
clip: Option<[f64; 4]>,
|
||||
) -> Result<FormUse, String> {
|
||||
let matrix = transform.0;
|
||||
if !matrix.iter().all(|value| value.is_finite()) {
|
||||
return Err("XDV form placement transform out of range".into());
|
||||
}
|
||||
|
||||
let clip = user_bbox.filter(|_| self.clip.unwrap_or(true));
|
||||
let [left, bottom, right, top] = if let Some([x0, y0, x1, y1]) = clip {
|
||||
let [left, bottom, right, top] = captured;
|
||||
let left = left.max(x0.min(x1));
|
||||
@@ -214,6 +238,33 @@ impl FormOptions {
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn affine(self) -> Affine {
|
||||
if let Some(matrix) = self.matrix {
|
||||
return Affine(matrix.map(f64::from_bits));
|
||||
}
|
||||
let [sx, sy] = self
|
||||
.axis_scale
|
||||
.map(|value| value.or(self.scale).map_or(1.0, f64::from_bits));
|
||||
let (sin, cos) = self
|
||||
.rotation
|
||||
.map_or(0.0, f64::from_bits)
|
||||
.to_radians()
|
||||
.sin_cos();
|
||||
Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0])
|
||||
}
|
||||
|
||||
pub(crate) fn requested_box(self) -> Option<[f64; 4]> {
|
||||
self.bbox.map(|values| values.map(f64::from_bits))
|
||||
}
|
||||
|
||||
pub(crate) fn dimensions(self) -> [Option<f64>; 3] {
|
||||
self.size.map(|value| value.map(f64::from_bits))
|
||||
}
|
||||
|
||||
pub(crate) fn clip_enabled(self) -> bool {
|
||||
self.clip.unwrap_or(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn to_sp(value: f64) -> Result<i64, String> {
|
||||
@@ -234,6 +285,12 @@ pub(super) struct Forms {
|
||||
names: BTreeMap<Vec<u8>, u32>,
|
||||
definitions: BTreeMap<u32, Definition>,
|
||||
active: Vec<Active>,
|
||||
#[serde(default)]
|
||||
next_number: u32,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
imports: BTreeMap<u32, usize>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
images: BTreeMap<usize, ImportedImage>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -250,21 +307,34 @@ struct Definition {
|
||||
resources: Dictionary,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
struct ImportedImage {
|
||||
geometry: ImportGeometry,
|
||||
version: ResourceVersion,
|
||||
page: PageSelection,
|
||||
page_box: PageBox,
|
||||
attributes: Dictionary,
|
||||
}
|
||||
|
||||
impl Forms {
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
self.names.is_empty()
|
||||
self.names.is_empty() && self.images.is_empty()
|
||||
}
|
||||
|
||||
pub(super) fn number(&self, name: &[u8]) -> Option<u32> {
|
||||
self.names.get(name).copied()
|
||||
}
|
||||
|
||||
fn register(&mut self, name: &[u8]) -> Result<u32, String> {
|
||||
if let Some(number) = self.number(name) {
|
||||
fn register(&mut self, name: Option<&[u8]>) -> Result<u32, String> {
|
||||
if let Some(number) = name.and_then(|name| self.number(name)) {
|
||||
return Ok(number);
|
||||
}
|
||||
let number = u32::try_from(self.names.len() + 1).map_err(|_| "XDV form limit exceeded")?;
|
||||
self.names.insert(name.to_vec(), number);
|
||||
let previous = self.next_number.max(self.names.len() as u32);
|
||||
let number = previous.checked_add(1).ok_or("XDV form limit exceeded")?;
|
||||
self.next_number = number;
|
||||
if let Some(name) = name {
|
||||
self.names.insert(name.to_vec(), number);
|
||||
}
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
@@ -273,6 +343,11 @@ impl Forms {
|
||||
.definitions
|
||||
.values()
|
||||
.flat_map(|entry| entry.attributes.values().chain(entry.resources.values()))
|
||||
.chain(
|
||||
self.images
|
||||
.values()
|
||||
.flat_map(|image| image.attributes.values()),
|
||||
)
|
||||
{
|
||||
value.collect_references(pending);
|
||||
}
|
||||
@@ -280,6 +355,106 @@ impl Forms {
|
||||
}
|
||||
|
||||
impl Navigation {
|
||||
pub(crate) fn reused_image(
|
||||
&self,
|
||||
special: &ImageSpecial,
|
||||
version: &ResourceVersion,
|
||||
) -> Option<(usize, ImportGeometry)> {
|
||||
self.forms.images.iter().find_map(|(&id, image)| {
|
||||
(image.version == *version
|
||||
&& image.page == special.page
|
||||
&& image.page_box == special.page_box
|
||||
&& image.attributes == special.attributes)
|
||||
.then(|| (id, image.geometry.clone()))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn import_image(
|
||||
&mut self,
|
||||
special: ImageSpecial,
|
||||
version: ResourceVersion,
|
||||
id: usize,
|
||||
geometry: ImportGeometry,
|
||||
source: TokenOrigin,
|
||||
payload: (usize, usize),
|
||||
) -> Result<Option<PdfGraphics>, String> {
|
||||
self.add_payload(payload.0, payload.1)?;
|
||||
let name = special.name.as_deref();
|
||||
let number = self.forms.register(name)?;
|
||||
if self.forms.definitions.contains_key(&number)
|
||||
|| self.forms.active.iter().any(|form| form.number == number)
|
||||
|| name.is_some_and(|name| self.objects.contains_key(name))
|
||||
|| self
|
||||
.forms
|
||||
.imports
|
||||
.get(&number)
|
||||
.is_some_and(|&other| other != id)
|
||||
{
|
||||
return Err("duplicate XDV XObject definition".into());
|
||||
}
|
||||
self.forms.images.entry(id).or_insert(ImportedImage {
|
||||
geometry,
|
||||
version,
|
||||
page: special.page,
|
||||
page_box: special.page_box,
|
||||
attributes: special.attributes,
|
||||
});
|
||||
self.forms.imports.insert(number, id);
|
||||
Ok((!special.hidden).then_some(PdfGraphics::XdvFormUse {
|
||||
number,
|
||||
options: special.placement,
|
||||
source,
|
||||
imported_available: true,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn bind_image_objects(
|
||||
&self,
|
||||
xobjects: &mut BTreeMap<u32, u32>,
|
||||
objects: &BTreeMap<usize, usize>,
|
||||
) -> Result<(), String> {
|
||||
for (&number, id) in &self.forms.imports {
|
||||
let object = *objects.get(id).ok_or("missing XDV image declaration")?;
|
||||
xobjects.insert(
|
||||
number,
|
||||
u32::try_from(object).map_err(|_| "PDF object ID out of range")?,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn write_image_attributes(
|
||||
&self,
|
||||
imported_objects: &BTreeMap<usize, usize>,
|
||||
references: &References<'_>,
|
||||
objects: &mut [Vec<u8>],
|
||||
) -> Result<(), String> {
|
||||
for (id, image) in &self.forms.images {
|
||||
if image.attributes.is_empty()
|
||||
|| matches!(image.geometry, ImportGeometry::Raster { .. })
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let attributes = output_dictionary(&image.attributes, references)?;
|
||||
let object = &mut objects[imported_objects[id] - 1];
|
||||
let end = object
|
||||
.windows(b"\nstream\n".len())
|
||||
.position(|bytes| bytes == b"\nstream\n")
|
||||
.ok_or("missing native XDV image stream")?;
|
||||
let Object::Dictionary(mut fields) = parse_value(&object[..end])? else {
|
||||
return Err("invalid native XDV image dictionary".into());
|
||||
};
|
||||
for (name, value) in &attributes {
|
||||
if name.as_slice() != b"Length" {
|
||||
fields.set(name.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
let encoded = encode_device_value(Object::Dictionary(fields))?;
|
||||
object.splice(..end, encoded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn form_special(
|
||||
&mut self,
|
||||
kind: &[u8],
|
||||
@@ -315,9 +490,10 @@ impl Navigation {
|
||||
}
|
||||
let (name, rest) = identifier(input)?;
|
||||
let (options, warnings) = FormOptions::parse(rest, position.magnification)?;
|
||||
let number = self.forms.register(name)?;
|
||||
let number = self.forms.register(Some(name))?;
|
||||
let command = if kind == b"bxobj" {
|
||||
if self.forms.definitions.contains_key(&number)
|
||||
|| self.forms.imports.contains_key(&number)
|
||||
|| self.forms.active.iter().any(|form| form.number == number)
|
||||
|| self.objects.contains_key(name)
|
||||
{
|
||||
@@ -339,6 +515,7 @@ impl Navigation {
|
||||
number,
|
||||
options,
|
||||
source,
|
||||
imported_available: self.forms.imports.contains_key(&number),
|
||||
}
|
||||
};
|
||||
Ok((command, warnings))
|
||||
@@ -443,19 +620,28 @@ impl Navigation {
|
||||
number,
|
||||
options,
|
||||
source,
|
||||
imported_available,
|
||||
},
|
||||
} => {
|
||||
let bounds = self
|
||||
.forms
|
||||
.definitions
|
||||
.get(&number)
|
||||
.ok_or("referenced XDV form is undefined")?
|
||||
.bounds;
|
||||
let form = options.place(
|
||||
number,
|
||||
bounds,
|
||||
capture_positions.get(&number).copied(),
|
||||
)?;
|
||||
let form = if let Some(import) = self.forms.imports.get(&number) {
|
||||
self.forms.images[import].geometry.place(
|
||||
number,
|
||||
options,
|
||||
imported_available,
|
||||
)?
|
||||
} else {
|
||||
let bounds = self
|
||||
.forms
|
||||
.definitions
|
||||
.get(&number)
|
||||
.ok_or("referenced XDV form is undefined")?
|
||||
.bounds;
|
||||
options.place(
|
||||
number,
|
||||
bounds,
|
||||
capture_positions.get(&number).copied(),
|
||||
)?
|
||||
};
|
||||
(
|
||||
DisplayItem::PdfForm { x, y, form },
|
||||
Some(PaintSource::token(source)),
|
||||
|
||||
Reference in new issue
Block a user