Capture and reuse XeLaTeX PDF form contents
This commit is contained in:
1 parent
009fde04f7
commit
c0e2346b05
16 files changed
+679
-26
No files matched your search
@@ -634,12 +634,15 @@ impl Executor {
|
|||||||
} else if xdv && crate::pdf_device::xdv_paper::Special::parse(&special.bytes).is_some() {
|
} else if xdv && crate::pdf_device::xdv_paper::Special::parse(&special.bytes).is_some() {
|
||||||
xdv_paper_specials.push(shipout.specials.len());
|
xdv_paper_specials.push(shipout.specials.len());
|
||||||
None
|
None
|
||||||
} else if xdv && super::specials::xdv_navigation_operand(&special.bytes).is_some() {
|
} else if xdv && let Some((kind, _)) = super::specials::xdv_navigation_operand(&special.bytes) {
|
||||||
|
if kind == b"bxobj" && let Some(program) = self.xdv_colors.start_page() {
|
||||||
|
shipout.xdv_color_steps.insert(graphics_step, program);
|
||||||
|
}
|
||||||
let point = xdv_transform.point(
|
let point = xdv_transform.point(
|
||||||
(special.position[0] + horizontal_origin) as f64,
|
(special.position[0] + horizontal_origin) as f64,
|
||||||
(special.position[1] + vertical_origin + b.height) as f64,
|
(special.position[1] + vertical_origin + b.height) as f64,
|
||||||
).map(|coordinate| coordinate.round() as i64);
|
).map(|coordinate| coordinate.round() as i64);
|
||||||
xdv_navigation.push((shipout.specials.len(), graphics_step, point));
|
xdv_navigation.push((shipout.specials.len(), graphics_step, point, *origin));
|
||||||
None
|
None
|
||||||
} else if xdv && self.xdv_setup_special(&special)? {
|
} else if xdv && self.xdv_setup_special(&special)? {
|
||||||
None
|
None
|
||||||
@@ -856,8 +859,8 @@ impl Executor {
|
|||||||
device.vertical_origin = offset + v_offset;
|
device.vertical_origin = offset + v_offset;
|
||||||
}
|
}
|
||||||
let delta = [device.horizontal_origin - horizontal_origin, device.vertical_origin - vertical_origin];
|
let delta = [device.horizontal_origin - horizontal_origin, device.vertical_origin - vertical_origin];
|
||||||
for (index, graphics_step, [x, y]) in xdv_navigation {
|
for (index, graphics_step, [x, y], origin) in xdv_navigation {
|
||||||
self.ship_xdv_navigation(
|
if let Some(operation) = self.ship_xdv_navigation(
|
||||||
&shipout.specials[index],
|
&shipout.specials[index],
|
||||||
crate::pdf_device::xdv_object::Position {
|
crate::pdf_device::xdv_object::Position {
|
||||||
page: self.shipped_pages + 1,
|
page: self.shipped_pages + 1,
|
||||||
@@ -865,8 +868,13 @@ impl Executor {
|
|||||||
height: device.page_height,
|
height: device.page_height,
|
||||||
magnification,
|
magnification,
|
||||||
},
|
},
|
||||||
graphics_step, &mut shipout.pdf_links, files,
|
graphics_step, &mut shipout.pdf_links, origin, files,
|
||||||
)?;
|
)? {
|
||||||
|
shipout.pdf_graphics_steps[graphics_step] = Some(operation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(navigation) = &self.state.xdv_navigation {
|
||||||
|
navigation.validate_form_boundary().map_err(|error| self.error(error, current))?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if xdv && let Some(navigation) = &mut self.state.xdv_navigation
|
if xdv && let Some(navigation) = &mut self.state.xdv_navigation
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ impl Executor {
|
|||||||
.reserve_form(limit)
|
.reserve_form(limit)
|
||||||
.map_err(|message| self.error(message, self.current))?;
|
.map_err(|message| self.error(message, self.current))?;
|
||||||
let form = FormUse {
|
let form = FormUse {
|
||||||
|
xdv: None,
|
||||||
number,
|
number,
|
||||||
width: box_node.width,
|
width: box_node.width,
|
||||||
height: box_node.height,
|
height: box_node.height,
|
||||||
|
|||||||
@@ -472,7 +472,9 @@ impl PdfLinkShipout {
|
|||||||
*matrix = previous;
|
*matrix = previous;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary) | None => {}
|
Some(PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary
|
||||||
|
| PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_)
|
||||||
|
| PdfGraphics::XdvFormUse { .. }) | None => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LinkPaint::RowStart(row) if !row.horizontal => {
|
LinkPaint::RowStart(row) if !row.horizontal => {
|
||||||
|
|||||||
@@ -56,8 +56,9 @@ impl Executor {
|
|||||||
position: crate::pdf_device::xdv_object::Position,
|
position: crate::pdf_device::xdv_object::Position,
|
||||||
graphics_step: usize,
|
graphics_step: usize,
|
||||||
links: &mut crate::pdf_device::links::PageLinks,
|
links: &mut crate::pdf_device::links::PageLinks,
|
||||||
|
origin: Option<TokenOrigin>,
|
||||||
files: &mut impl SourceProvider,
|
files: &mut impl SourceProvider,
|
||||||
) -> Result<(), Error> {
|
) -> Result<Option<PdfGraphics>, Error> {
|
||||||
let Some((kind, operands)) = xdv_navigation_operand(&special.bytes) else {
|
let Some((kind, operands)) = xdv_navigation_operand(&special.bytes) else {
|
||||||
return self.fail("missing shipped XDV navigation operands");
|
return self.fail("missing shipped XDV navigation operands");
|
||||||
};
|
};
|
||||||
@@ -66,10 +67,18 @@ impl Executor {
|
|||||||
operands, position.page, position.coordinates,
|
operands, position.page, position.coordinates,
|
||||||
).map_err(|error| self.error(error, special.span))?;
|
).map_err(|error| self.error(error, special.span))?;
|
||||||
links.xdv_destinations.push(destination);
|
links.xdv_destinations.push(destination);
|
||||||
return Ok(());
|
return Ok(None);
|
||||||
}
|
}
|
||||||
self.reads.insert(Dependency::PdfCatalogState);
|
self.reads.insert(Dependency::PdfCatalogState);
|
||||||
let warnings = if matches!(kind, b"docview" | b"outline" | b"pageresources") {
|
let mut graphics = None;
|
||||||
|
let warnings = if matches!(kind, b"bxobj" | b"exobj" | b"uxobj") {
|
||||||
|
let source = origin.unwrap_or(TokenOrigin { span: special.span, invocation: None });
|
||||||
|
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
|
||||||
|
let (operation, warnings) = navigation.form_special(kind, operands, position, source, self.limits.tokens)
|
||||||
|
.map_err(|error| self.error(error, special.span))?;
|
||||||
|
graphics = Some(operation);
|
||||||
|
Ok(warnings)
|
||||||
|
} else if matches!(kind, b"docview" | b"outline" | b"pageresources") {
|
||||||
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
|
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
|
||||||
if kind == b"docview" {
|
if kind == b"docview" {
|
||||||
navigation.merge_catalog(operands, position, self.limits.tokens)
|
navigation.merge_catalog(operands, position, self.limits.tokens)
|
||||||
@@ -100,7 +109,7 @@ impl Executor {
|
|||||||
files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
|
files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
|
||||||
.map_err(|error| self.error(error, special.span))?;
|
.map_err(|error| self.error(error, special.span))?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(graphics)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn xdv_setup_special(
|
pub(super) fn xdv_setup_special(
|
||||||
@@ -357,6 +366,9 @@ pub(super) fn xdv_navigation_operand(data: &[u8]) -> Option<(&'static [u8], &[u8
|
|||||||
(b"docview", b"docview"), (b"outline", b"outline"), (b"out", b"outline"),
|
(b"docview", b"docview"), (b"outline", b"outline"), (b"out", b"outline"),
|
||||||
(b"obj", b"obj"), (b"object", b"obj"), (b"put", b"put"), (b"close", b"close"),
|
(b"obj", b"obj"), (b"object", b"obj"), (b"put", b"put"), (b"close", b"close"),
|
||||||
(b"stream", b"stream"), (b"fstream", b"fstream"), (b"pageresources", b"pageresources"),
|
(b"stream", b"stream"), (b"fstream", b"fstream"), (b"pageresources", b"pageresources"),
|
||||||
|
(b"bxobj", b"bxobj"), (b"bform", b"bxobj"), (b"beginxobj", b"bxobj"),
|
||||||
|
(b"exobj", b"exobj"), (b"eform", b"exobj"), (b"endxobj", b"exobj"),
|
||||||
|
(b"uxobj", b"uxobj"), (b"usexobj", b"uxobj"),
|
||||||
] {
|
] {
|
||||||
if let Some(operands) = xdv_operand(body, name) {
|
if let Some(operands) = xdv_operand(body, name) {
|
||||||
return Some((kind, operands));
|
return Some((kind, operands));
|
||||||
|
|||||||
@@ -799,7 +799,7 @@ impl Execution {
|
|||||||
})?;
|
})?;
|
||||||
list.pdf_resources.attributes = form.attributes.clone().into();
|
list.pdf_resources.attributes = form.attributes.clone().into();
|
||||||
forms.push(crate::pdf_device::forms::FormDisplay {
|
forms.push(crate::pdf_device::forms::FormDisplay {
|
||||||
form: form.form, resource_number: form.resource_number, list,
|
form: form.form, resource_number: form.resource_number, list, xdv: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if let Event::Shipout(b) = e {
|
if let Event::Shipout(b) = e {
|
||||||
@@ -813,6 +813,11 @@ impl Execution {
|
|||||||
})?);
|
})?);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(navigation) = &self.state.xdv_navigation {
|
||||||
|
forms.extend(navigation.split_forms(&mut pages).map_err(|message| {
|
||||||
|
Error::at(&self.sources, self.state.input_profile(), message, Span::default())
|
||||||
|
})?);
|
||||||
|
}
|
||||||
if !self.state.pdf_draft_mode() {
|
if !self.state.pdf_draft_mode() {
|
||||||
self.resolve_page_graphics_resources(&mut pages)?;
|
self.resolve_page_graphics_resources(&mut pages)?;
|
||||||
if let Some(navigation) = &self.state.xdv_navigation {
|
if let Some(navigation) = &self.state.xdv_navigation {
|
||||||
|
|||||||
@@ -735,6 +735,7 @@ fn page_content(
|
|||||||
xdv_font_aliases: &BTreeMap<crate::execution::FontId, crate::execution::FontId>,
|
xdv_font_aliases: &BTreeMap<crate::execution::FontId, crate::execution::FontId>,
|
||||||
opentype: &BTreeMap<crate::execution::FontId, Arc<opentype_fonts::EmbeddedFont>>,
|
opentype: &BTreeMap<crate::execution::FontId, Arc<opentype_fonts::EmbeddedFont>>,
|
||||||
font_opacities: &BTreeMap<u8, String>,
|
font_opacities: &BTreeMap<u8, String>,
|
||||||
|
xdv_form: bool,
|
||||||
) -> Vec<u8> {
|
) -> Vec<u8> {
|
||||||
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
|
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
|
||||||
let pt = |n: i64| {
|
let pt = |n: i64| {
|
||||||
@@ -778,7 +779,14 @@ fn page_content(
|
|||||||
pt(-origin.v_offset)
|
pt(-origin.v_offset)
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
if xdv_form {
|
||||||
|
// Captured XDV content uses device-relative coordinates. Keep the
|
||||||
|
// logical origin used by glyphs and specials without emitting the
|
||||||
|
// enclosing sheet's translation into the Form stream.
|
||||||
|
content.origin.move_to(page_origin, list.units, digits);
|
||||||
|
} else {
|
||||||
content.move_origin(page_origin, list.units, digits);
|
content.move_origin(page_origin, list.units, digits);
|
||||||
|
}
|
||||||
let mut native_text: Option<NativeTextRun> = None;
|
let mut native_text: Option<NativeTextRun> = None;
|
||||||
let mut tex_text: Option<native_text::NativeText> = None;
|
let mut tex_text: Option<native_text::NativeText> = None;
|
||||||
let mut opentype_text = opentype_fonts::TextState::default();
|
let mut opentype_text = opentype_fonts::TextState::default();
|
||||||
@@ -1215,6 +1223,14 @@ fn page_content(
|
|||||||
}
|
}
|
||||||
DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {}
|
DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {}
|
||||||
DisplayItem::PdfForm { x, y, form } => {
|
DisplayItem::PdfForm { x, y, form } => {
|
||||||
|
if let Some(placement) = form.xdv {
|
||||||
|
let [a,b,c,d,e,f] = placement.matrix.map(f64::from_bits);
|
||||||
|
let tx = px(*x).parse::<f64>().expect("formatted XDV x") + e;
|
||||||
|
let ty = py(*y).parse::<f64>().expect("formatted XDV y") + f;
|
||||||
|
let [a,b,c,d,tx,ty] = [a,b,c,d,tx,ty].map(crate::pdf_image::real);
|
||||||
|
content.push_str(&format!("q {a} {b} {c} {d} {tx} {ty} cm /Fm{} Do Q\n", form.number));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
content.push_str(&format!(
|
content.push_str(&format!(
|
||||||
"q 1 0 0 1 {} {} cm /Fm{} Do Q\n", px(*x), py(*y + form.depth), form.number,
|
"q 1 0 0 1 {} {} cm /Fm{} Do Q\n", px(*x), py(*y + form.depth), form.number,
|
||||||
));
|
));
|
||||||
@@ -1275,6 +1291,9 @@ fn page_content(
|
|||||||
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {
|
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {
|
||||||
unreachable!("handled before graphics transforms")
|
unreachable!("handled before graphics transforms")
|
||||||
}
|
}
|
||||||
|
PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) | PdfGraphics::XdvFormUse { .. } => {
|
||||||
|
unreachable!("XDV form operations were projected before export")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2936,6 +2955,10 @@ fn write_pdf(
|
|||||||
);
|
);
|
||||||
(image.id, object)
|
(image.id, object)
|
||||||
}).collect();
|
}).collect();
|
||||||
|
for form in forms.iter().filter(|form| form.xdv.is_some()) {
|
||||||
|
objects.push(Vec::new());
|
||||||
|
device_objects.insert(form.form.number, objects.len() as u32);
|
||||||
|
}
|
||||||
let append_xobjects = |list: &DisplayList, xobjects: &mut String| -> Result<(), String> {
|
let append_xobjects = |list: &DisplayList, xobjects: &mut String| -> Result<(), String> {
|
||||||
let images = list
|
let images = list
|
||||||
.items
|
.items
|
||||||
@@ -3002,12 +3025,24 @@ fn write_pdf(
|
|||||||
}
|
}
|
||||||
fonts
|
fonts
|
||||||
};
|
};
|
||||||
|
let mut xdv_forms = Vec::new();
|
||||||
for (index, form) in forms.into_iter().enumerate() {
|
for (index, form) in forms.into_iter().enumerate() {
|
||||||
let list = &form.list;
|
let list = &form.list;
|
||||||
let slot = pages.len() + index;
|
let slot = pages.len() + index;
|
||||||
let mut xobjects = String::new();
|
let mut xobjects = String::new();
|
||||||
append_xobjects(list, &mut xobjects)?;
|
append_xobjects(list, &mut xobjects)?;
|
||||||
let fonts = mapped_font_resources(list);
|
let fonts = mapped_font_resources(list);
|
||||||
|
if form.xdv.is_some() {
|
||||||
|
let mut resources = format!("<< /Font << {fonts} >>");
|
||||||
|
if !xobjects.is_empty() {
|
||||||
|
resources.push_str(&format!(" /XObject << {xobjects} >>"));
|
||||||
|
}
|
||||||
|
resources.push_str(" >>");
|
||||||
|
let content = page_content(list, list.height, &BTreeMap::new(), faces, &cm_views,
|
||||||
|
&fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, &BTreeMap::new(), true);
|
||||||
|
xdv_forms.push((form, resources, content));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let digits = list.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits);
|
let digits = list.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits);
|
||||||
let width = crate::pdf_device::print_sp(form.form.width, digits);
|
let width = crate::pdf_device::print_sp(form.form.width, digits);
|
||||||
let height = crate::pdf_device::print_sp(form.form.height + form.form.depth, digits);
|
let height = crate::pdf_device::print_sp(form.form.height + form.form.depth, digits);
|
||||||
@@ -3036,7 +3071,7 @@ fn write_pdf(
|
|||||||
let font_opacities = remapped.as_ref().map_or(&no_font_opacity, |r| &r.font_opacities[slot]);
|
let font_opacities = remapped.as_ref().map_or(&no_font_opacity, |r| &r.font_opacities[slot]);
|
||||||
let content = page_content(
|
let content = page_content(
|
||||||
list, list.height, &names, faces, &cm_views,
|
list, list.height, &names, faces, &cm_views,
|
||||||
&fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, font_opacities,
|
&fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, font_opacities, false,
|
||||||
);
|
);
|
||||||
objects[device_objects[&form.form.number] as usize - 1] = objects::stream_bytes(
|
objects[device_objects[&form.form.number] as usize - 1] = objects::stream_bytes(
|
||||||
&entries, &content, list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression),
|
&entries, &content, list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression),
|
||||||
@@ -3227,6 +3262,7 @@ fn write_pdf(
|
|||||||
&xdv_font_aliases,
|
&xdv_font_aliases,
|
||||||
&opentype,
|
&opentype,
|
||||||
font_opacities,
|
font_opacities,
|
||||||
|
false,
|
||||||
);
|
);
|
||||||
let stream = objects::stream("", &content, list.pdf.as_ref().map_or(0, |p| p.stream_compression));
|
let stream = objects::stream("", &content, list.pdf.as_ref().map_or(0, |p| p.stream_compression));
|
||||||
if let Some(id) = content_slot {
|
if let Some(id) = content_slot {
|
||||||
@@ -3565,7 +3601,7 @@ fn write_pdf(
|
|||||||
destination.collect_references(&mut pending);
|
destination.collect_references(&mut pending);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let named_objects = xdv_objects.reserve_objects(pending, &mut objects)?;
|
let named_objects = xdv_objects.reserve_objects(pending, &mut objects, &device_objects)?;
|
||||||
let references = crate::pdf_device::xdv_object::References {
|
let references = crate::pdf_device::xdv_object::References {
|
||||||
pages: &navigation.pages,
|
pages: &navigation.pages,
|
||||||
named: &named_objects,
|
named: &named_objects,
|
||||||
@@ -3573,6 +3609,10 @@ fn write_pdf(
|
|||||||
let compression = pages[0].pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
|
let compression = pages[0].pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
|
||||||
xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?;
|
xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?;
|
||||||
if let Some(xdv) = xdv {
|
if let Some(xdv) = xdv {
|
||||||
|
for (form, resources, content) in xdv_forms {
|
||||||
|
let id = device_objects[&form.form.number] as usize;
|
||||||
|
objects[id - 1] = xdv.write_form(form, resources.as_bytes(), &content, &references, &mut objects, diagnostics)?;
|
||||||
|
}
|
||||||
xdv.write_page_dictionaries(pages, &references, &mut objects)?;
|
xdv.write_page_dictionaries(pages, &references, &mut objects)?;
|
||||||
xdv.write_page_resources(&references, &mut objects, diagnostics)?;
|
xdv.write_page_resources(&references, &mut objects, diagnostics)?;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,20 @@ pub struct FormUse {
|
|||||||
pub width: i64,
|
pub width: i64,
|
||||||
pub height: i64,
|
pub height: i64,
|
||||||
pub depth: i64,
|
pub depth: i64,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub(crate) xdv: Option<XdvPlacement>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct XdvPlacement {
|
||||||
|
pub(crate) matrix: [u64; 6],
|
||||||
|
pub(crate) bounds: [i64; 4],
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) struct XdvCanvas {
|
||||||
|
pub(crate) anchor: [i64; 2],
|
||||||
|
pub(crate) bounds: [i64; 4],
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
@@ -45,4 +59,5 @@ pub struct FormDisplay {
|
|||||||
pub form: FormUse,
|
pub form: FormUse,
|
||||||
pub resource_number: u32,
|
pub resource_number: u32,
|
||||||
pub list: DisplayList,
|
pub list: DisplayList,
|
||||||
|
pub(crate) xdv: Option<XdvCanvas>,
|
||||||
}
|
}
|
||||||
@@ -46,6 +46,13 @@ pub enum PdfGraphics {
|
|||||||
SaveMatrix(PdfMatrix),
|
SaveMatrix(PdfMatrix),
|
||||||
/// An XDV special switched the device from text to graphics mode.
|
/// An XDV special switched the device from text to graphics mode.
|
||||||
TextBoundary,
|
TextBoundary,
|
||||||
|
XdvFormBegin(u32),
|
||||||
|
XdvFormEnd(u32),
|
||||||
|
XdvFormUse {
|
||||||
|
number: u32,
|
||||||
|
options: super::xdv_navigation::FormOptions,
|
||||||
|
source: crate::execution::TokenOrigin,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ use super::xdv_object::{
|
|||||||
mod named_objects;
|
mod named_objects;
|
||||||
mod page_dictionaries;
|
mod page_dictionaries;
|
||||||
mod page_resources;
|
mod page_resources;
|
||||||
|
mod forms;
|
||||||
|
pub use forms::FormOptions;
|
||||||
|
use forms::Forms;
|
||||||
use page_resources::PageResources;
|
use page_resources::PageResources;
|
||||||
use page_dictionaries::PageDictionaries;
|
use page_dictionaries::PageDictionaries;
|
||||||
pub(crate) use named_objects::ObjectCommand;
|
pub(crate) use named_objects::ObjectCommand;
|
||||||
@@ -31,6 +34,8 @@ pub(crate) struct Navigation {
|
|||||||
page_dictionaries: PageDictionaries,
|
page_dictionaries: PageDictionaries,
|
||||||
#[serde(default, skip_serializing_if = "PageResources::is_empty")]
|
#[serde(default, skip_serializing_if = "PageResources::is_empty")]
|
||||||
page_resources: PageResources,
|
page_resources: PageResources,
|
||||||
|
#[serde(default, skip_serializing_if = "Forms::is_empty")]
|
||||||
|
forms: Forms,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
@@ -123,12 +128,14 @@ impl Navigation {
|
|||||||
}
|
}
|
||||||
self.page_dictionaries.collect_references(pending);
|
self.page_dictionaries.collect_references(pending);
|
||||||
self.page_resources.collect_references(pending);
|
self.page_resources.collect_references(pending);
|
||||||
|
self.forms.collect_references(pending);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn reserve_objects<'a>(
|
pub(crate) fn reserve_objects<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
mut pending: Vec<&'a [u8]>,
|
mut pending: Vec<&'a [u8]>,
|
||||||
objects: &mut Vec<Vec<u8>>,
|
objects: &mut Vec<Vec<u8>>,
|
||||||
|
device_objects: &BTreeMap<u32, u32>,
|
||||||
) -> Result<BTreeMap<Vec<u8>, u32>, String> {
|
) -> Result<BTreeMap<Vec<u8>, u32>, String> {
|
||||||
let mut names = BTreeSet::new();
|
let mut names = BTreeSet::new();
|
||||||
while let Some(name) = pending.pop() {
|
while let Some(name) = pending.pop() {
|
||||||
@@ -137,6 +144,9 @@ impl Navigation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
names.into_iter().map(|name| {
|
names.into_iter().map(|name| {
|
||||||
|
if let Some(number) = self.forms.number(name) {
|
||||||
|
return Ok((name.to_vec(), *device_objects.get(&number).ok_or("unallocated XDV form reference")?));
|
||||||
|
}
|
||||||
objects.push(Vec::new());
|
objects.push(Vec::new());
|
||||||
let id = u32::try_from(objects.len()).map_err(|_| "XDV PDF object ID out of range")?;
|
let id = u32::try_from(objects.len()).map_err(|_| "XDV PDF object ID out of range")?;
|
||||||
Ok((name.to_vec(), id))
|
Ok((name.to_vec(), id))
|
||||||
@@ -151,6 +161,9 @@ impl Navigation {
|
|||||||
diagnostics: &mut Vec<String>,
|
diagnostics: &mut Vec<String>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
for (name, &id) in references.named {
|
for (name, &id) in references.named {
|
||||||
|
if self.forms.number(name).is_some() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
objects[id as usize - 1] = if let Some(object) = self.objects.get(name) {
|
objects[id as usize - 1] = if let Some(object) = self.objects.get(name) {
|
||||||
object.pdf(references, compression)?
|
object.pdf(references, compression)?
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -0,0 +1,458 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use lopdf::{Dictionary as PdfDictionary, Object};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
execution::TokenOrigin,
|
||||||
|
pdf_device::{
|
||||||
|
Affine, DeviceOrigin, PdfGraphics,
|
||||||
|
forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement},
|
||||||
|
xdv_image::{length, number},
|
||||||
|
xdv_page_origin,
|
||||||
|
},
|
||||||
|
provenance::PaintSource,
|
||||||
|
render::{DisplayItem, DisplayList},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::super::xdv_object::{identifier, trim_pdf};
|
||||||
|
use super::{
|
||||||
|
Dictionary, Navigation, Position, References, dictionary, encode_device_value,
|
||||||
|
output_dictionary, page_resources::merge_output_resources, parse_value,
|
||||||
|
};
|
||||||
|
|
||||||
|
const SP_PER_BP: f64 = 65536.0 * 803.0 / 800.0;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
pub struct FormOptions {
|
||||||
|
bbox: Option<[u64; 4]>,
|
||||||
|
size: [Option<u64>; 3],
|
||||||
|
scale: [Option<u64>; 2],
|
||||||
|
offset: [u64; 2],
|
||||||
|
rotation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FormOptions {
|
||||||
|
fn parse(input: &[u8], magnification: i32) -> Result<Self, String> {
|
||||||
|
let mut words = std::str::from_utf8(input)
|
||||||
|
.map_err(|_| "invalid XDV form options")?
|
||||||
|
.split_ascii_whitespace()
|
||||||
|
.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());
|
||||||
|
}
|
||||||
|
"xoffset" | "yoffset" => {
|
||||||
|
options.offset[usize::from(word == "yoffset")] =
|
||||||
|
length(&mut words, magnification)?.to_bits();
|
||||||
|
}
|
||||||
|
"scale" => options.scale = [Some(number(words.next())?.to_bits()); 2],
|
||||||
|
"xscale" | "yscale" => {
|
||||||
|
options.scale[usize::from(word == "yscale")] =
|
||||||
|
Some(number(words.next())?.to_bits());
|
||||||
|
}
|
||||||
|
"rotate" => options.rotation = number(words.next())?.to_bits(),
|
||||||
|
_ => return Err(format!("unsupported XDV form option {word}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(options)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture_bounds(self) -> Result<[i64; 4], String> {
|
||||||
|
let [width, height, depth] = self.size.map(|v| v.map_or(0.0, f64::from_bits));
|
||||||
|
let bbox = self
|
||||||
|
.bbox
|
||||||
|
.map_or([0.0, -depth, width, height], |v| v.map(f64::from_bits));
|
||||||
|
let [left, bottom, right, top] = checked_box(bbox)?;
|
||||||
|
if left >= right || bottom >= top {
|
||||||
|
return Err("XDV form bounding box must have positive dimensions".into());
|
||||||
|
}
|
||||||
|
Ok([left, bottom, right, top])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn place(self, number: u32, bounds: [i64; 4]) -> Result<FormUse, String> {
|
||||||
|
if self.bbox.is_some() {
|
||||||
|
return Err("unsupported XDV form placement bounding box".into());
|
||||||
|
}
|
||||||
|
let [left, bottom, right, top] = bounds.map(|p| p as f64 / SP_PER_BP);
|
||||||
|
let natural = [right - left, top - bottom];
|
||||||
|
let [width, height, depth] = self.size.map(|v| v.map(f64::from_bits));
|
||||||
|
let vertical = height
|
||||||
|
.or(depth.map(|_| 0.0))
|
||||||
|
.map(|h| h + depth.unwrap_or(0.0));
|
||||||
|
let requested = [
|
||||||
|
width.map(|w| w / natural[0]),
|
||||||
|
vertical.map(|h| h / natural[1]),
|
||||||
|
];
|
||||||
|
let scales = self.scale.map(|v| v.map(f64::from_bits));
|
||||||
|
let sx = requested[0].or(scales[0]).or(requested[1]).unwrap_or(1.0);
|
||||||
|
let sy = requested[1].or(scales[1]).or(requested[0]).unwrap_or(1.0);
|
||||||
|
if sx == 0.0 || sy == 0.0 {
|
||||||
|
return Err("zero XDV form placement scale".into());
|
||||||
|
}
|
||||||
|
let [dx, dy] = self.offset.map(f64::from_bits);
|
||||||
|
let (sin, cos) = f64::from_bits(self.rotation).to_radians().sin_cos();
|
||||||
|
let matrix = [
|
||||||
|
cos * sx,
|
||||||
|
sin * sx,
|
||||||
|
-sin * sy,
|
||||||
|
cos * sy,
|
||||||
|
dx,
|
||||||
|
dy + vertical.map_or(0.0, |_| -depth.unwrap_or(0.0) - bottom * sy),
|
||||||
|
];
|
||||||
|
let transform = Affine(matrix);
|
||||||
|
let mut extent = [
|
||||||
|
f64::INFINITY,
|
||||||
|
f64::INFINITY,
|
||||||
|
f64::NEG_INFINITY,
|
||||||
|
f64::NEG_INFINITY,
|
||||||
|
];
|
||||||
|
for [x, y] in [[left, bottom], [left, top], [right, bottom], [right, top]] {
|
||||||
|
let [x, y] = transform.point(x, y);
|
||||||
|
extent = [
|
||||||
|
extent[0].min(x),
|
||||||
|
extent[1].min(y),
|
||||||
|
extent[2].max(x),
|
||||||
|
extent[3].max(y),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
let bounds = checked_box(extent)?;
|
||||||
|
Ok(FormUse {
|
||||||
|
number,
|
||||||
|
width: bounds[2] - bounds[0],
|
||||||
|
height: bounds[3],
|
||||||
|
depth: -bounds[1],
|
||||||
|
xdv: Some(XdvPlacement {
|
||||||
|
matrix: matrix.map(f64::to_bits),
|
||||||
|
bounds,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_sp(value: f64) -> Result<i64, String> {
|
||||||
|
let value = (value * SP_PER_BP).round();
|
||||||
|
if !(-1_073_741_823.0..=1_073_741_823.0).contains(&value) {
|
||||||
|
return Err("XDV form dimension out of range".into());
|
||||||
|
}
|
||||||
|
Ok(value as i64)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn checked_box(values: [f64; 4]) -> Result<[i64; 4], String> {
|
||||||
|
let [a, b, c, d] = values.map(to_sp);
|
||||||
|
Ok([a?, b?, c?, d?])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
pub(super) struct Forms {
|
||||||
|
names: BTreeMap<Vec<u8>, u32>,
|
||||||
|
definitions: BTreeMap<u32, Definition>,
|
||||||
|
active: Vec<Active>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
struct Active {
|
||||||
|
number: u32,
|
||||||
|
bounds: [i64; 4],
|
||||||
|
outer_resources: Dictionary,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
struct Definition {
|
||||||
|
bounds: [i64; 4],
|
||||||
|
attributes: Dictionary,
|
||||||
|
resources: Dictionary,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Forms {
|
||||||
|
pub(super) fn is_empty(&self) -> bool {
|
||||||
|
self.names.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) {
|
||||||
|
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);
|
||||||
|
Ok(number)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) {
|
||||||
|
for value in self
|
||||||
|
.definitions
|
||||||
|
.values()
|
||||||
|
.flat_map(|entry| entry.attributes.values().chain(entry.resources.values()))
|
||||||
|
{
|
||||||
|
value.collect_references(pending);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Navigation {
|
||||||
|
pub(crate) fn form_special(
|
||||||
|
&mut self,
|
||||||
|
kind: &[u8],
|
||||||
|
input: &[u8],
|
||||||
|
position: Position,
|
||||||
|
source: TokenOrigin,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<(PdfGraphics, Vec<String>), String> {
|
||||||
|
self.add_payload(input.len(), limit)?;
|
||||||
|
if kind == b"exobj" {
|
||||||
|
let attributes = if trim_pdf(input).is_empty() {
|
||||||
|
Dictionary::new()
|
||||||
|
} else {
|
||||||
|
dictionary(input, position)?
|
||||||
|
};
|
||||||
|
let form = self
|
||||||
|
.forms
|
||||||
|
.active
|
||||||
|
.pop()
|
||||||
|
.ok_or("XDV form capture was not started")?;
|
||||||
|
let warnings = self.merge_resources((*self.page_resources.defaults).clone(), true)?;
|
||||||
|
let resources =
|
||||||
|
std::mem::replace(&mut self.page_resources.current, form.outer_resources);
|
||||||
|
self.forms.definitions.insert(
|
||||||
|
form.number,
|
||||||
|
Definition {
|
||||||
|
bounds: form.bounds,
|
||||||
|
attributes,
|
||||||
|
resources,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return Ok((PdfGraphics::XdvFormEnd(form.number), warnings));
|
||||||
|
}
|
||||||
|
let (name, rest) = identifier(input)?;
|
||||||
|
let options = FormOptions::parse(rest, position.magnification)?;
|
||||||
|
let number = self.forms.register(name)?;
|
||||||
|
let command = if kind == b"bxobj" {
|
||||||
|
if self.forms.definitions.contains_key(&number)
|
||||||
|
|| self.forms.active.iter().any(|form| form.number == number)
|
||||||
|
|| self.objects.contains_key(name)
|
||||||
|
{
|
||||||
|
return Err("duplicate XDV form definition".into());
|
||||||
|
}
|
||||||
|
if self.forms.active.len() >= 64 {
|
||||||
|
return Err("XDV form nesting limit exceeded".into());
|
||||||
|
}
|
||||||
|
let bounds = options.capture_bounds()?;
|
||||||
|
let outer_resources = std::mem::take(&mut self.page_resources.current);
|
||||||
|
self.forms.active.push(Active {
|
||||||
|
number,
|
||||||
|
bounds,
|
||||||
|
outer_resources,
|
||||||
|
});
|
||||||
|
PdfGraphics::XdvFormBegin(number)
|
||||||
|
} else {
|
||||||
|
PdfGraphics::XdvFormUse {
|
||||||
|
number,
|
||||||
|
options,
|
||||||
|
source,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok((command, Vec::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn validate_form_boundary(&self) -> Result<(), &'static str> {
|
||||||
|
if self.forms.active.is_empty() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("unclosed XDV form capture at shipout")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn split_forms(
|
||||||
|
&self,
|
||||||
|
pages: &mut [DisplayList],
|
||||||
|
) -> Result<Vec<FormDisplay>, String> {
|
||||||
|
if self.forms.is_empty() {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
let mut forms = Vec::new();
|
||||||
|
for page in pages {
|
||||||
|
let mut captures: Vec<(u32, XdvCanvas, DisplayList)> = Vec::new();
|
||||||
|
let mut sources = std::mem::take(&mut page.sources);
|
||||||
|
let mut packets = page.prepared_virtual_glyphs.as_mut().map(std::mem::take);
|
||||||
|
for (index, item) in std::mem::take(&mut page.items).into_iter().enumerate() {
|
||||||
|
let origin = sources.remove(&index);
|
||||||
|
let packet = packets.as_mut().and_then(|packets| packets.remove(&index));
|
||||||
|
let (item, origin) = match item {
|
||||||
|
DisplayItem::PdfGraphics {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
operation: PdfGraphics::XdvFormBegin(number),
|
||||||
|
} => {
|
||||||
|
let bounds = self.forms.definitions[&number].bounds;
|
||||||
|
let list = DisplayList {
|
||||||
|
width: page.width,
|
||||||
|
height: page.height,
|
||||||
|
units: page.units,
|
||||||
|
magnification: page.magnification,
|
||||||
|
pdf: page.pdf.clone(),
|
||||||
|
pdf_font_bindings: page.pdf_font_bindings.clone(),
|
||||||
|
prepared_virtual_glyphs: packets.as_ref().map(|_| BTreeMap::new()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
captures.push((
|
||||||
|
number,
|
||||||
|
XdvCanvas {
|
||||||
|
anchor: [x, y],
|
||||||
|
bounds,
|
||||||
|
},
|
||||||
|
list,
|
||||||
|
));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
DisplayItem::PdfGraphics {
|
||||||
|
operation: PdfGraphics::XdvFormEnd(expected),
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let (number, geometry, list) =
|
||||||
|
captures.pop().ok_or("missing started XDV form")?;
|
||||||
|
if number != expected {
|
||||||
|
return Err("mismatched XDV form capture".into());
|
||||||
|
}
|
||||||
|
let form = FormOptions::default().place(number, geometry.bounds)?;
|
||||||
|
forms.push(FormDisplay {
|
||||||
|
form,
|
||||||
|
resource_number: 0,
|
||||||
|
list,
|
||||||
|
xdv: Some(geometry),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
DisplayItem::PdfGraphics {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
operation:
|
||||||
|
PdfGraphics::XdvFormUse {
|
||||||
|
number,
|
||||||
|
options,
|
||||||
|
source,
|
||||||
|
},
|
||||||
|
} => {
|
||||||
|
let bounds = self
|
||||||
|
.forms
|
||||||
|
.definitions
|
||||||
|
.get(&number)
|
||||||
|
.ok_or("referenced XDV form is undefined")?
|
||||||
|
.bounds;
|
||||||
|
let form = options.place(number, bounds)?;
|
||||||
|
(
|
||||||
|
DisplayItem::PdfForm { x, y, form },
|
||||||
|
Some(PaintSource::token(source)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
item => (item, origin),
|
||||||
|
};
|
||||||
|
let output = if let Some((_, _, form)) = captures.last_mut() {
|
||||||
|
form
|
||||||
|
} else {
|
||||||
|
&mut *page
|
||||||
|
};
|
||||||
|
if let Some(source) = origin {
|
||||||
|
output.sources.insert(output.items.len(), source);
|
||||||
|
}
|
||||||
|
if let Some(packet) = packet {
|
||||||
|
output
|
||||||
|
.prepared_virtual_glyphs
|
||||||
|
.as_mut()
|
||||||
|
.unwrap()
|
||||||
|
.insert(output.items.len(), packet);
|
||||||
|
}
|
||||||
|
output.items.push(item);
|
||||||
|
}
|
||||||
|
if !captures.is_empty() {
|
||||||
|
return Err("incomplete XDV form display list".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(forms)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn write_form(
|
||||||
|
&self,
|
||||||
|
form: &FormDisplay,
|
||||||
|
resources: &[u8],
|
||||||
|
content: &[u8],
|
||||||
|
references: &References<'_>,
|
||||||
|
objects: &mut [Vec<u8>],
|
||||||
|
diagnostics: &mut Vec<String>,
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
|
let geometry = form.xdv.expect("XDV form geometry");
|
||||||
|
let list = &form.list;
|
||||||
|
let magnification = f64::from(list.magnification) / 1000.0;
|
||||||
|
let scale = magnification / SP_PER_BP;
|
||||||
|
let digits = list.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits);
|
||||||
|
let mut origin = DeviceOrigin::default();
|
||||||
|
origin.move_to(
|
||||||
|
xdv_page_origin(list.units, list.height, list.magnification),
|
||||||
|
list.units,
|
||||||
|
digits,
|
||||||
|
);
|
||||||
|
let [x, y] = geometry.anchor;
|
||||||
|
let anchor = origin
|
||||||
|
.move_to([x, list.height - y], list.units, digits)
|
||||||
|
.unwrap_or([0, 0])
|
||||||
|
.map(|value| value as f64 * magnification / 10f64.powi(i32::from(digits)));
|
||||||
|
let round = |value: f64| (value * 1000.0).round() / 1000.0;
|
||||||
|
let mut attributes = PdfDictionary::new();
|
||||||
|
attributes.set("Type", Object::Name(b"XObject".to_vec()));
|
||||||
|
attributes.set("Subtype", Object::Name(b"Form".to_vec()));
|
||||||
|
attributes.set("FormType", 1);
|
||||||
|
let bbox = geometry
|
||||||
|
.bounds
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(axis, n)| Object::Real(round(anchor[axis % 2] + scale * n as f64)))
|
||||||
|
.collect();
|
||||||
|
attributes.set("BBox", Object::Array(bbox));
|
||||||
|
attributes.set(
|
||||||
|
"Matrix",
|
||||||
|
Object::Array(
|
||||||
|
[1.0, 0.0, 0.0, 1.0, round(-anchor[0]), round(-anchor[1])]
|
||||||
|
.map(Object::Real)
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
let definition = &self.forms.definitions[&form.form.number];
|
||||||
|
for (key, value) in &output_dictionary(&definition.attributes, references)? {
|
||||||
|
attributes.set(key.clone(), value.clone());
|
||||||
|
}
|
||||||
|
let Object::Dictionary(mut resources) = parse_value(resources)? else {
|
||||||
|
unreachable!("generated XDV form resources");
|
||||||
|
};
|
||||||
|
merge_output_resources(
|
||||||
|
&mut resources,
|
||||||
|
&definition.resources,
|
||||||
|
references,
|
||||||
|
objects,
|
||||||
|
diagnostics,
|
||||||
|
)?;
|
||||||
|
attributes.set("Resources", Object::Dictionary(resources));
|
||||||
|
let encoded = encode_device_value(Object::Dictionary(attributes))?;
|
||||||
|
Ok(crate::pdf::objects::stream_bytes(
|
||||||
|
&encoded[2..encoded.len() - 2],
|
||||||
|
content,
|
||||||
|
list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,8 +11,8 @@ use super::{
|
|||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
pub(super) struct PageResources {
|
pub(super) struct PageResources {
|
||||||
current: Dictionary,
|
pub(super) current: Dictionary,
|
||||||
defaults: Arc<Dictionary>,
|
pub(super) defaults: Arc<Dictionary>,
|
||||||
pages: BTreeMap<usize, Dictionary>,
|
pages: BTreeMap<usize, Dictionary>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,7 +58,7 @@ impl Navigation {
|
|||||||
Ok(messages)
|
Ok(messages)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn merge_resources(
|
pub(super) fn merge_resources(
|
||||||
&mut self,
|
&mut self,
|
||||||
additions: Dictionary,
|
additions: Dictionary,
|
||||||
deferred: bool,
|
deferred: bool,
|
||||||
@@ -131,6 +131,21 @@ impl Navigation {
|
|||||||
.as_dict()
|
.as_dict()
|
||||||
.map_err(|_| "expected inline XDV resource dictionary")?
|
.map_err(|_| "expected inline XDV resource dictionary")?
|
||||||
.clone();
|
.clone();
|
||||||
|
merge_output_resources(&mut resources, fields, references, objects, diagnostics)?;
|
||||||
|
dictionary.set("Resources", Object::Dictionary(resources));
|
||||||
|
objects[id - 1] = encode_device_value(Object::Dictionary(dictionary))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn merge_output_resources(
|
||||||
|
resources: &mut PdfDictionary,
|
||||||
|
fields: &Dictionary,
|
||||||
|
references: &References<'_>,
|
||||||
|
objects: &mut [Vec<u8>],
|
||||||
|
diagnostics: &mut Vec<String>,
|
||||||
|
) -> Result<(), String> {
|
||||||
for (category, new) in &output_dictionary(fields, references)? {
|
for (category, new) in &output_dictionary(fields, references)? {
|
||||||
let generated = resources.remove(category);
|
let generated = resources.remove(category);
|
||||||
let generated = generated
|
let generated = generated
|
||||||
@@ -161,11 +176,7 @@ impl Navigation {
|
|||||||
};
|
};
|
||||||
resources.set(category.clone(), effective);
|
resources.set(category.clone(), effective);
|
||||||
}
|
}
|
||||||
dictionary.set("Resources", Object::Dictionary(resources));
|
|
||||||
objects[id - 1] = encode_device_value(Object::Dictionary(dictionary))?;
|
|
||||||
}
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn category_fields<'a>(
|
fn category_fields<'a>(
|
||||||
|
|||||||
@@ -813,6 +813,8 @@ impl DisplayList {
|
|||||||
use crate::pdf_device::PdfGraphics;
|
use crate::pdf_device::PdfGraphics;
|
||||||
match operation {
|
match operation {
|
||||||
PdfGraphics::TextBoundary => {}
|
PdfGraphics::TextBoundary => {}
|
||||||
|
PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) |
|
||||||
|
PdfGraphics::XdvFormUse { .. } => unreachable!("projected XDV form"),
|
||||||
PdfGraphics::Literal { .. } => unreachable!("PDF literal requires PDF rendering"),
|
PdfGraphics::Literal { .. } => unreachable!("PDF literal requires PDF rendering"),
|
||||||
PdfGraphics::Save | PdfGraphics::Matrix(_) | PdfGraphics::SaveMatrix(_) => {
|
PdfGraphics::Save | PdfGraphics::Matrix(_) | PdfGraphics::SaveMatrix(_) => {
|
||||||
if matches!(operation, PdfGraphics::Save | PdfGraphics::SaveMatrix(_)) {
|
if matches!(operation, PdfGraphics::Save | PdfGraphics::SaveMatrix(_)) {
|
||||||
|
|||||||
@@ -344,6 +344,8 @@ impl SourceMap {
|
|||||||
}
|
}
|
||||||
match operation {
|
match operation {
|
||||||
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {}
|
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {}
|
||||||
|
PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) |
|
||||||
|
PdfGraphics::XdvFormUse { .. } => unreachable!("projected XDV form"),
|
||||||
PdfGraphics::Save => graphics_stack.push(transform),
|
PdfGraphics::Save => graphics_stack.push(transform),
|
||||||
PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix) => {
|
PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix) => {
|
||||||
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
|
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
|
||||||
@@ -471,11 +473,11 @@ impl SourceMap {
|
|||||||
)),
|
)),
|
||||||
DisplayItem::PdfForm { x, y, form } => Some((
|
DisplayItem::PdfForm { x, y, form } => Some((
|
||||||
PaintKind::PdfForm { number: form.number },
|
PaintKind::PdfForm { number: form.number },
|
||||||
Bounds {
|
if let Some(placement) = form.xdv {
|
||||||
x: *x,
|
let [left, bottom, right, top] = placement.bounds;
|
||||||
y: *y - form.height,
|
Bounds { x: *x + left, y: *y - top, width: right - left, height: top - bottom }
|
||||||
width: form.width,
|
} else {
|
||||||
height: form.height + form.depth,
|
Bounds { x: *x, y: *y - form.height, width: form.width, height: form.height + form.depth }
|
||||||
},
|
},
|
||||||
)),
|
)),
|
||||||
DisplayItem::PdfImage {
|
DisplayItem::PdfImage {
|
||||||
|
|||||||
@@ -215,6 +215,8 @@ impl PdfProjection {
|
|||||||
};
|
};
|
||||||
self.concatenate(matrix.about(x as f64, y as f64, false));
|
self.concatenate(matrix.about(x as f64, y as f64, false));
|
||||||
}
|
}
|
||||||
|
PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) |
|
||||||
|
PdfGraphics::XdvFormUse { .. } => unreachable!("projected XDV form"),
|
||||||
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {
|
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {
|
||||||
unreachable!("handled before graphics transforms")
|
unreachable!("handled before graphics transforms")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1009,3 +1009,48 @@ fn xdv_scoped_code_uses_shared_resource_categories_and_page_defaults() {
|
|||||||
assert_eq!(operations[style + 1].operator, "re");
|
assert_eq!(operations[style + 1].operator, "re");
|
||||||
assert_eq!(operations[style + 2].operator, "f");
|
assert_eq!(operations[style + 2].operator, "f");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xdv_form_capture_isolated_and_reused_as_one_indirect_object() {
|
||||||
|
use lopdf::Document;
|
||||||
|
use texrra_tex_core::{pdf::shipout_lists_to_native_pdf_document, render::DisplayItem};
|
||||||
|
|
||||||
|
let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX);
|
||||||
|
let result = Executor::new(state, Limits::default())
|
||||||
|
.with_native_pages()
|
||||||
|
.run(
|
||||||
|
source(r"\catcode123=1 \catcode125=2
|
||||||
|
\shipout\hbox{%
|
||||||
|
\special{pdf:bxobj @box width 30pt height 20pt}%
|
||||||
|
\special{pdf:put @resources << /ExtGState << /A << /ca 0.5 >> >> >>}%
|
||||||
|
\special{pdf:bcontent}\special{pdf:code q /A gs 0 0 10 10 re f Q}%
|
||||||
|
\special{pdf:econtent}%
|
||||||
|
\hbox to0pt{\vrule width5pt height7pt\hss}%
|
||||||
|
\special{pdf:exobj << /Group << /S /Transparency >> >>}%
|
||||||
|
\special{pdf:put @catalog << /Captured @box >>}%
|
||||||
|
\special{pdf:uxobj @box}}
|
||||||
|
\shipout\hbox{\kern20pt\special{pdf:usexobj @box}}
|
||||||
|
\end"),
|
||||||
|
&mut TestDevice,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let pages = result.shipout_display_lists().unwrap();
|
||||||
|
assert_eq!(pages[0].forms.len(), 1);
|
||||||
|
assert!(pages[0].forms[0].list.items.iter().any(|item| matches!(item, DisplayItem::Rule { .. })));
|
||||||
|
assert!(!pages[0].items.iter().any(|item| matches!(item, DisplayItem::Rule { .. })));
|
||||||
|
let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
|
||||||
|
let pdf = Document::load_mem(&output.bytes).unwrap();
|
||||||
|
let object = |page| pdf.get_object(page).unwrap().as_dict().unwrap()
|
||||||
|
.get(b"Resources").unwrap().as_dict().unwrap()
|
||||||
|
.get(b"XObject").unwrap().as_dict().unwrap()
|
||||||
|
.get(b"Fm1").unwrap().as_reference().unwrap();
|
||||||
|
let ids = pdf.get_pages();
|
||||||
|
let form = object(ids[&1]);
|
||||||
|
assert_eq!(object(ids[&2]), form);
|
||||||
|
assert_eq!(pdf.catalog().unwrap().get(b"Captured").unwrap().as_reference().unwrap(), form);
|
||||||
|
let stream = pdf.get_object(form).unwrap().as_stream().unwrap();
|
||||||
|
assert_eq!(stream.dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Form");
|
||||||
|
let resources = stream.dict.get(b"Resources").unwrap().as_dict().unwrap();
|
||||||
|
assert!(resources.get(b"ExtGState").unwrap().as_dict().unwrap().has(b"A"));
|
||||||
|
assert!(stream.dict.get(b"Group").unwrap().as_dict().unwrap().has(b"S"));
|
||||||
|
}
|
||||||
@@ -18,6 +18,36 @@
|
|||||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
||||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||||
|
|
||||||
|
## 2026-11-28 XeLaTeX 捕获式 PDF Form 与 TikZ 渐变
|
||||||
|
|
||||||
|
出页时执行 `pdf:bxobj`、`pdf:exobj` 和 `pdf:uxobj`,把实际
|
||||||
|
TeX 字形、规则和绘图捕获到 PDF Form。每层捕获保有自己的边界、
|
||||||
|
局部资源、内容和来源。放置、跨页前向引用和其他 PDF 字典共享
|
||||||
|
同一间接对象。捕获的初始颜色来自设备状态,持续的页面资源按
|
||||||
|
捕获边界合并。PDF 导出复用现有字体与绘图资源。
|
||||||
|
[参考驱动](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/dvipdfm-x/spc_pdfm.c)
|
||||||
|
|
||||||
|
原样 CTAN PGF 3.1.12 与真实 XeLaTeX 格式编译两页 TikZ 渐变。
|
||||||
|
另两组原语覆盖字形与绘图捕获、跨页放置、嵌套及继承颜色。
|
||||||
|
三组共六页,144 DPI 彩色图逐像素一致。前两组的 Form 引用、
|
||||||
|
资源和几何对照通过,article 的 aux 字节一致。首版 Form 坐标
|
||||||
|
舍入造成的 114 个边缘像素差异随证据保留,统一设备坐标后归零。
|
||||||
|
开发构建与九项定向回归通过。
|
||||||
|
|
||||||
|
三页会话经历三次修订,各复用 1,130 步。从后页修改前向 Form
|
||||||
|
更新两个使用页,移动第 2 页放置只更新该页,恢复更新前两页。
|
||||||
|
每轮 PDF、测量页、预览、来源映射和 aux 与独立全量编译一致。
|
||||||
|
|
||||||
|
嵌套 Form 同时显式指定宽、高、深时,已复现纵向缩放差异。样例
|
||||||
|
参考矩阵的纵向因子为 0.80132,原生为 1.428570870。下一步按
|
||||||
|
参考设备的 Form 固有边界、深度与放置变换完善尺寸语义。显式
|
||||||
|
放置 bbox 仍未接入。该失败保存在 `nested-geometry.log`。
|
||||||
|
[参考放置逻辑](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/pdfximage.c)
|
||||||
|
|
||||||
|
回执在 `target/p3-xdv-captured-forms/receipt.json`,SHA-256 为
|
||||||
|
`3f857f8958b9e858993bb5c08141d8cbd6d9e0d86e95ab32cc173e6191c6f919`。原样出版模板矩阵、发布版整体验收及 100 ms
|
||||||
|
可见延迟门槛继续按总目标执行。
|
||||||
|
|
||||||
## 2026-11-28 XeLaTeX 页面资源与 TikZ 透明叠印
|
## 2026-11-28 XeLaTeX 页面资源与 TikZ 透明叠印
|
||||||
|
|
||||||
`pdf:put @resources` 合并当前页资源,保留已登记的同名条目。
|
`pdf:put @resources` 合并当前页资源,保留已登记的同名条目。
|
||||||
|
|||||||
Reference in new issue
Block a user