Promote verified native PDF and box capacity support
This commit is contained in:
1 parent
3706afa483
commit
72ed779749
31 files changed
+1042
-78
No files matched your search
@@ -167,12 +167,15 @@ pub struct Executor {
|
||||
pdf_colors: crate::pdf_device::PdfColorStacks,
|
||||
pdf_link_stack: Vec<pdf_links::ActiveLink>,
|
||||
pdf_catalog_tokens: Vec<Token>,
|
||||
pdf_info_tokens: Vec<Token>,
|
||||
pdf_images: Vec<pdf_image::RegisteredImage>,
|
||||
input_position: Option<(usize, usize)>,
|
||||
paragraph: Option<super::paragraph::Builder>,
|
||||
vertical: super::boxes::VerticalBuilder,
|
||||
box_frames: Vec<boxes::BoxFrame>,
|
||||
box_nodes_created: usize,
|
||||
material_charge: usize,
|
||||
mark_cells_created: usize,
|
||||
diagnostic_bytes: usize,
|
||||
after_assignment: Option<Token>,
|
||||
after_group_tokens: usize,
|
||||
@@ -291,12 +294,15 @@ impl Executor {
|
||||
pdf_colors: Default::default(),
|
||||
pdf_link_stack: Vec::new(),
|
||||
pdf_catalog_tokens: Vec::new(),
|
||||
pdf_info_tokens: Vec::new(),
|
||||
pdf_images: Vec::new(),
|
||||
input_position: None,
|
||||
paragraph: None,
|
||||
vertical: super::boxes::VerticalBuilder::default(),
|
||||
box_frames: Vec::new(),
|
||||
box_nodes_created: 0,
|
||||
material_charge: 0,
|
||||
mark_cells_created: 0,
|
||||
diagnostic_bytes: 0,
|
||||
after_assignment: None,
|
||||
after_group_tokens: 0,
|
||||
@@ -3107,7 +3113,7 @@ impl Executor {
|
||||
result: Result<(), Error>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
if let Err(mut error) = result.and_then(|()| self.finish_pdf_catalog()) {
|
||||
if let Err(mut error) = result.and_then(|()| self.finish_pdf_dictionaries()) {
|
||||
if let Err(sink) = files.observe_error(&error) {
|
||||
error
|
||||
.message
|
||||
@@ -3195,8 +3201,10 @@ impl Executor {
|
||||
mut capture_boundary: impl FnMut(&Self, usize, &mut F),
|
||||
) -> Result<(), Error> {
|
||||
loop {
|
||||
self.check_box_capacity(None)?;
|
||||
capture_boundary(self, initial_depth, files);
|
||||
self.process_native_pages(files)?;
|
||||
self.check_box_capacity(None)?;
|
||||
let Some(input) = self.expanded(files)? else {
|
||||
break;
|
||||
};
|
||||
@@ -3530,6 +3538,7 @@ impl Executor {
|
||||
self.scan_pdf_link(primitive, token.span, files)?;
|
||||
}
|
||||
Pdfcatalog => self.scan_pdf_catalog(files)?,
|
||||
Pdfinfo => self.scan_pdf_info(files)?,
|
||||
Pdfximage => self.scan_pdf_image(&token, false, files)?,
|
||||
Pdfrefximage => self.reference_pdf_image(&token, files)?,
|
||||
_ => {
|
||||
@@ -3585,6 +3594,7 @@ impl Executor {
|
||||
}
|
||||
self.validate_pdf_final_state()?;
|
||||
self.end_paragraph(files)?;
|
||||
self.check_box_capacity(None)?;
|
||||
if self.state.group_depth() != initial_depth {
|
||||
return self.fail("unclosed native group at end of input");
|
||||
}
|
||||
|
||||
@@ -257,10 +257,7 @@ impl Executor {
|
||||
"improper native discretionary material: only glyphs, boxes, rules and kerns are allowed",
|
||||
);
|
||||
}
|
||||
self.box_nodes_created = self.box_nodes_created.saturating_add(part.len());
|
||||
if self.box_nodes_created > self.limits.tokens {
|
||||
return self.fail("native discretionary node capacity exceeded");
|
||||
}
|
||||
self.charge_box_material(part.len(), "native discretionary node capacity exceeded")?;
|
||||
disc.parts.push(part);
|
||||
if disc.parts.len() < 3 {
|
||||
return self.begin_discretionary_part(disc, files);
|
||||
@@ -313,10 +310,18 @@ impl Executor {
|
||||
}
|
||||
}
|
||||
pub(super) fn account_box(&mut self, b: &NativeBox) -> Result<(), Error> {
|
||||
self.box_nodes_created = self.box_nodes_created.saturating_add(b.node_count());
|
||||
if self.box_nodes_created > self.limits.tokens {
|
||||
return self.fail("native box node capacity exceeded");
|
||||
};
|
||||
self.charge_box_material(b.node_count(), "native box node capacity exceeded")
|
||||
}
|
||||
pub(super) fn charge_box_material(
|
||||
&mut self,
|
||||
nodes: usize,
|
||||
error: &'static str,
|
||||
) -> Result<(), Error> {
|
||||
self.box_nodes_created = self.box_nodes_created.saturating_add(nodes);
|
||||
if nodes > self.limits.tokens {
|
||||
return self.fail(error);
|
||||
}
|
||||
self.material_charge = self.material_charge.saturating_add(nodes);
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn scan_box(
|
||||
|
||||
@@ -21,10 +21,14 @@ impl Executor {
|
||||
0
|
||||
};
|
||||
let tokens = self.scan_expanded_group(files)?;
|
||||
self.box_nodes_created = self.box_nodes_created.saturating_add(1 + tokens.len());
|
||||
if self.box_nodes_created > self.limits.tokens {
|
||||
// Mark payload has its own cumulative limit. A transferred box is not
|
||||
// another allocation of the tokens stored in that box.
|
||||
let cells = 1 + tokens.len();
|
||||
self.mark_cells_created = self.mark_cells_created.saturating_add(cells);
|
||||
if self.mark_cells_created > self.limits.tokens {
|
||||
return self.fail("native mark token/node capacity exceeded");
|
||||
}
|
||||
self.charge_box_material(1, "native mark token/node capacity exceeded")?;
|
||||
let mark = NativeMark {
|
||||
class,
|
||||
tokens: tokens.into(),
|
||||
|
||||
@@ -88,10 +88,7 @@ impl Executor {
|
||||
return self.fail("native math family must be in 0..15");
|
||||
};
|
||||
self.optional_equals(files)?;
|
||||
let t = self.expanded_non_space(files)?.token;
|
||||
let Meaning::Font(font) = self.meaning(&t) else {
|
||||
return self.fail("expected actual native font selector");
|
||||
};
|
||||
let font = self.font_identifier(files)?;
|
||||
let size = match p {
|
||||
Primitive::Textfont => 0,
|
||||
Primitive::Scriptfont => 1,
|
||||
|
||||
@@ -229,6 +229,7 @@ impl Executor {
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
self.native_page_mut()?;
|
||||
self.check_box_capacity(Some(&b))?;
|
||||
let h_offset = i64::from(self.read_parameter(Parameter::Hoffset).width());
|
||||
let v_offset = i64::from(self.read_parameter(Parameter::Voffset).width());
|
||||
const MAX_DIMEN: i64 = 1_073_741_823;
|
||||
|
||||
@@ -135,21 +135,44 @@ impl Executor {
|
||||
}
|
||||
}
|
||||
|
||||
fn pdf_dictionary_enabled(
|
||||
&mut self,
|
||||
command: &str,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<bool, Error> {
|
||||
let enabled = self.read_parameter(Parameter::Pdfoutput).width() > 0;
|
||||
if !enabled {
|
||||
let text = format!(
|
||||
"pdfTeX warning (\\{command}): not allowed in DVI mode (\\pdfoutput <= 0); ignoring it"
|
||||
);
|
||||
files
|
||||
.observe_message(&text)
|
||||
.map_err(|error| self.error(error, self.current))?;
|
||||
self.events.push(Event::Message {
|
||||
text,
|
||||
span: self.current,
|
||||
});
|
||||
}
|
||||
Ok(enabled)
|
||||
}
|
||||
|
||||
pub(super) fn scan_pdf_info(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
|
||||
let enabled = self.pdf_dictionary_enabled("pdfinfo", files)?;
|
||||
let tokens = self.scan_pdf_tokens(files)?;
|
||||
if enabled {
|
||||
if self.pdf_info_tokens.len().saturating_add(tokens.len()) > self.limits.tokens {
|
||||
return self.fail("native PDF information token limit exceeded");
|
||||
}
|
||||
self.pdf_info_tokens.extend(tokens);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn scan_pdf_catalog(
|
||||
&mut self,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
let enabled = self.read_parameter(Parameter::Pdfoutput).width() > 0;
|
||||
if !enabled {
|
||||
let text = "pdfTeX warning (\\pdfcatalog): not allowed in DVI mode (\\pdfoutput <= 0); ignoring it";
|
||||
files
|
||||
.observe_message(text)
|
||||
.map_err(|error| self.error(error, self.current))?;
|
||||
self.events.push(Event::Message {
|
||||
text: text.into(),
|
||||
span: self.current,
|
||||
});
|
||||
}
|
||||
let enabled = self.pdf_dictionary_enabled("pdfcatalog", files)?;
|
||||
let tokens = self.scan_pdf_tokens(files)?;
|
||||
if enabled {
|
||||
if self.pdf_catalog_tokens.len().saturating_add(tokens.len()) > self.limits.tokens {
|
||||
@@ -181,7 +204,7 @@ impl Executor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn finish_pdf_catalog(&mut self) -> Result<(), Error> {
|
||||
pub(super) fn finish_pdf_dictionaries(&mut self) -> Result<(), Error> {
|
||||
if !self.pdf_catalog_tokens.is_empty() {
|
||||
let tokens = std::mem::take(&mut self.pdf_catalog_tokens);
|
||||
let bytes = self.pdf_token_bytes(&tokens)?;
|
||||
@@ -191,6 +214,10 @@ impl Executor {
|
||||
.entries
|
||||
.extend(bytes);
|
||||
}
|
||||
if !self.pdf_info_tokens.is_empty() {
|
||||
let tokens = std::mem::take(&mut self.pdf_info_tokens);
|
||||
self.state.pdf_info = self.pdf_token_bytes(&tokens)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,11 @@ impl Executor {
|
||||
match (command, self.pdf_images.last()) {
|
||||
(Primitive::Pdflastximage, Some(image)) => image.image.id as i32,
|
||||
(Primitive::Pdflastximagepages, Some(image)) => image.image.image.page_count as i32,
|
||||
(Primitive::Pdflastximagecolordepth, Some(image)) => image
|
||||
.image
|
||||
.image
|
||||
.jpeg_frame()
|
||||
.map_or(0, |(_, precision)| i32::from(precision)),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
@@ -58,9 +63,7 @@ impl Executor {
|
||||
return self.fail("native PDF image named destinations require PDF object support");
|
||||
}
|
||||
let page = if self.keyword("page", files)? {
|
||||
let page = self.integer(files)?;
|
||||
usize::try_from(page)
|
||||
.map_err(|_| self.error("required page does not exist", token.span))?
|
||||
self.integer(files)?
|
||||
} else {
|
||||
1
|
||||
};
|
||||
@@ -96,8 +99,29 @@ impl Executor {
|
||||
token.span,
|
||||
)
|
||||
})?;
|
||||
let image = PdfImage::read(source, page, page_box)
|
||||
.and_then(|image| PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions))
|
||||
let image = if PdfImage::is_jpeg(&source) {
|
||||
let resolution = self.read_parameter(Parameter::Pdfimageresolution).width();
|
||||
let version = (
|
||||
self.read_parameter(Parameter::Pdfmajorversion).width(),
|
||||
self.read_parameter(Parameter::Pdfminorversion).width(),
|
||||
);
|
||||
let (image, warning) = PdfImage::read_jpeg(source, resolution, version)
|
||||
.map_err(|error| self.error(error, token.span))?;
|
||||
if let Some(warning) = warning {
|
||||
files
|
||||
.observe_diagnostic(
|
||||
WriteDestination::TerminalAndLog,
|
||||
&format!("pdfTeX warning: pdftex: {warning}\n"),
|
||||
)
|
||||
.map_err(|error| self.error(error, token.span))?;
|
||||
}
|
||||
image
|
||||
} else {
|
||||
let page = usize::try_from(page)
|
||||
.map_err(|_| self.error("required page does not exist", token.span))?;
|
||||
PdfImage::read(source, page, page_box).map_err(|error| self.error(error, token.span))?
|
||||
};
|
||||
let image = PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions)
|
||||
.map_err(|error| self.error(error, token.span))?;
|
||||
let id = image.id;
|
||||
self.pdf_images.push(RegisteredImage {
|
||||
|
||||
@@ -18,6 +18,23 @@ impl Executor {
|
||||
pub(super) fn observe_resource_stacks(&mut self) {
|
||||
self.stack_peaks.include(&self.stack_usage());
|
||||
}
|
||||
|
||||
pub(super) fn check_box_capacity(&mut self, shipping: Option<&NativeBox>) -> Result<(), Error> {
|
||||
if self.material_charge <= self.limits.tokens {
|
||||
return Ok(());
|
||||
}
|
||||
// Packing can move existing lists or replace an old register. Recount
|
||||
// actual owners at an execution boundary before rejecting the job.
|
||||
let usage = self.resource_usage(shipping, None);
|
||||
self.material_charge = usage
|
||||
.active_material
|
||||
.records()
|
||||
.saturating_add(usage.retained_material.records());
|
||||
if self.material_charge > self.limits.tokens {
|
||||
return self.fail("native box node capacity exceeded");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn resource_usage(
|
||||
&self,
|
||||
shipping: Option<&NativeBox>,
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
path::Path,
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 23;
|
||||
const SCHEMA: u32 = 25;
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -14,8 +14,8 @@ pub enum JobParameter {
|
||||
Year,
|
||||
}
|
||||
|
||||
/// One real host-local timestamp, captured at job start. Tests may inject an
|
||||
/// explicit timestamp; absence is an error on access, never a fake zero date.
|
||||
/// The TeX time registers and PDF creation timestamp captured at job start.
|
||||
/// The host can supply a separate PDF date for reproducible builds.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct JobTime {
|
||||
pub year: i32,
|
||||
@@ -24,6 +24,8 @@ pub struct JobTime {
|
||||
pub minutes: i32,
|
||||
#[serde(default)]
|
||||
pdf_clock: Option<(u8, i16)>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pdf_calendar: Option<(i32, i32, i32, i32)>,
|
||||
}
|
||||
impl JobTime {
|
||||
pub fn new(year: i32, month: i32, day: i32, minutes: i32) -> Result<Self, &'static str> {
|
||||
@@ -44,6 +46,7 @@ impl JobTime {
|
||||
day,
|
||||
minutes,
|
||||
pdf_clock: None,
|
||||
pdf_calendar: None,
|
||||
})
|
||||
}
|
||||
/// Add the seconds and UTC offset supplied by the job host.
|
||||
@@ -56,11 +59,28 @@ impl JobTime {
|
||||
return Err("invalid host PDF creation timestamp");
|
||||
}
|
||||
self.pdf_clock = Some((seconds, offset_minutes));
|
||||
self.pdf_calendar = None;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Use the PDF timestamp from another host clock without changing TeX's registers.
|
||||
pub fn with_pdf_date(mut self, source: Self) -> Self {
|
||||
let calendar =
|
||||
source
|
||||
.pdf_calendar
|
||||
.unwrap_or((source.year, source.month, source.day, source.minutes));
|
||||
self.pdf_clock = source.pdf_clock;
|
||||
self.pdf_calendar = (source.pdf_clock.is_some()
|
||||
&& calendar != (self.year, self.month, self.day, self.minutes))
|
||||
.then_some(calendar);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pdf_creation_date(self) -> Option<String> {
|
||||
let (seconds, offset) = self.pdf_clock?;
|
||||
let (year, month, day, minutes) =
|
||||
self.pdf_calendar
|
||||
.unwrap_or((self.year, self.month, self.day, self.minutes));
|
||||
let zone = if offset == 0 {
|
||||
"Z".to_owned()
|
||||
} else {
|
||||
@@ -69,12 +89,9 @@ impl JobTime {
|
||||
format!("{sign}{:02}'{:02}'", offset / 60, offset % 60)
|
||||
};
|
||||
Some(format!(
|
||||
"D:{:04}{:02}{:02}{:02}{:02}{seconds:02}{zone}",
|
||||
self.year,
|
||||
self.month,
|
||||
self.day,
|
||||
self.minutes / 60,
|
||||
self.minutes % 60
|
||||
"D:{year:04}{month:02}{day:02}{:02}{:02}{seconds:02}{zone}",
|
||||
minutes / 60,
|
||||
minutes % 60
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,9 @@ pub enum Parameter {
|
||||
Pdfcompresslevel,
|
||||
Pdfdecimaldigits,
|
||||
Pdfpkresolution,
|
||||
Pdfimageresolution,
|
||||
Pdfgentounicode,
|
||||
Pdfinfoomitdate,
|
||||
Tracingcommands,
|
||||
Tracingrestores,
|
||||
Tracingassigns,
|
||||
@@ -124,7 +126,9 @@ impl Parameter {
|
||||
Self::Pdfcompresslevel,
|
||||
Self::Pdfdecimaldigits,
|
||||
Self::Pdfpkresolution,
|
||||
Self::Pdfimageresolution,
|
||||
Self::Pdfgentounicode,
|
||||
Self::Pdfinfoomitdate,
|
||||
Self::Tracingcommands,
|
||||
Self::Tracingrestores,
|
||||
Self::Tracingassigns,
|
||||
|
||||
@@ -109,6 +109,7 @@ pub enum Primitive {
|
||||
Pdfendlink,
|
||||
Pdfdest,
|
||||
Pdfcatalog,
|
||||
Pdfinfo,
|
||||
Pdfsetmatrix,
|
||||
Pdfrestore,
|
||||
Pdfglyphtounicode,
|
||||
@@ -597,6 +598,7 @@ pub struct State {
|
||||
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
|
||||
pub(super) pdf_info: Vec<u8>,
|
||||
pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap,
|
||||
pub(super) hyphenation: super::hyphenation::HyphenationData,
|
||||
}
|
||||
@@ -638,6 +640,7 @@ impl Default for State {
|
||||
output_mode_set: None,
|
||||
pdf_file_options: None,
|
||||
pdf_catalog: None,
|
||||
pdf_info: Vec::new(),
|
||||
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
|
||||
hyphenation: super::hyphenation::HyphenationData::default(),
|
||||
};
|
||||
@@ -859,6 +862,7 @@ impl Default for State {
|
||||
("pdfendlink", Pdfendlink),
|
||||
("pdfdest", Pdfdest),
|
||||
("pdfcatalog", Pdfcatalog),
|
||||
("pdfinfo", Pdfinfo),
|
||||
("pdfsetmatrix", Pdfsetmatrix),
|
||||
("pdfrestore", Pdfrestore),
|
||||
("pdfglyphtounicode", Pdfglyphtounicode),
|
||||
@@ -1245,6 +1249,7 @@ impl State {
|
||||
self.output_mode_set = None;
|
||||
self.pdf_file_options = None;
|
||||
self.pdf_catalog = None;
|
||||
self.pdf_info.clear();
|
||||
self
|
||||
}
|
||||
pub fn is_initex(&self) -> bool {
|
||||
@@ -1258,6 +1263,12 @@ impl State {
|
||||
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
|
||||
glyph_unicode: &self.glyph_unicode,
|
||||
catalog: self.pdf_catalog.as_deref(),
|
||||
info: crate::pdf_device::PdfInfo {
|
||||
entries: &self.pdf_info,
|
||||
date: (self.parameter(Parameter::Pdfinfoomitdate).width() == 0)
|
||||
.then_some(self.pdf_creation_date.as_deref())
|
||||
.flatten(),
|
||||
},
|
||||
}
|
||||
}
|
||||
/// Job-wide decoding choice; it is not a scoped TeX assignment.
|
||||
|
||||
@@ -112,6 +112,7 @@ pub struct ResourceUsage {
|
||||
/// Runtime events excluding statistics reports themselves.
|
||||
pub retained_events: usize,
|
||||
pub retained_shipouts: usize,
|
||||
/// Cumulative node visits charged by packing and copying operations, including transfers.
|
||||
pub box_nodes_created: usize,
|
||||
pub diagnostic_bytes_generated: usize,
|
||||
pub stacks: StackUsage,
|
||||
|
||||
@@ -850,13 +850,19 @@ fn page_content(
|
||||
height: image_height,
|
||||
image,
|
||||
} => {
|
||||
let [sx, sy] = if list.units == crate::render::DisplayUnits::TeX {
|
||||
let [sx, sy] = if image.image.jpeg_frame().is_some()
|
||||
&& list.units == crate::render::DisplayUnits::TeX
|
||||
{
|
||||
[
|
||||
crate::pdf_device::print_sp(*width, 4),
|
||||
crate::pdf_device::print_sp(*image_height, 4),
|
||||
]
|
||||
} else if list.units == crate::render::DisplayUnits::TeX {
|
||||
let [natural_width, natural_height] = image.image.natural;
|
||||
// pdfTeX out_image prints a six-decimal ratio of scaled
|
||||
// dimensions, while translation follows pdfdecimaldigits.
|
||||
let scale = |placed, natural| {
|
||||
let (coefficient, _) =
|
||||
crate::pdf_device::divide_scaled(placed, i64::from(natural), 6);
|
||||
let (coefficient, _) = crate::pdf_device::divide_scaled(placed, natural, 6);
|
||||
crate::pdf_device::print_decimal(coefficient, 6)
|
||||
};
|
||||
[
|
||||
@@ -1007,6 +1013,36 @@ fn metadata_object(metadata: &PdfMetadata) -> Option<String> {
|
||||
Some(format!("<< {} >>", fields.join(" ")))
|
||||
}
|
||||
|
||||
fn native_information_dictionary(info: crate::pdf_device::PdfInfo<'_>) -> Vec<u8> {
|
||||
// pdfTeX suppresses defaults based on the raw byte spelling anywhere in
|
||||
// the expanded list. Preserve the supplied PDF syntax verbatim.
|
||||
let supplied = |key: &[u8]| info.entries.windows(key.len()).any(|value| value == key);
|
||||
let mut object = b"<<\n".to_vec();
|
||||
if !supplied(b"/Producer") {
|
||||
object.extend_from_slice(b"/Producer (texrra Route-D native)\n");
|
||||
}
|
||||
if !info.entries.is_empty() {
|
||||
object.extend_from_slice(info.entries);
|
||||
object.push(b'\n');
|
||||
}
|
||||
if !supplied(b"/Creator") {
|
||||
object.extend_from_slice(b"/Creator (TeX)\n");
|
||||
}
|
||||
if let Some(date) = info.date {
|
||||
for key in ["CreationDate", "ModDate"] {
|
||||
let name = format!("/{key}");
|
||||
if !supplied(name.as_bytes()) {
|
||||
writeln!(&mut object, "{name} ({date})").unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
if !supplied(b"/Trapped") {
|
||||
object.extend_from_slice(b"/Trapped /False\n");
|
||||
}
|
||||
object.extend_from_slice(b">>");
|
||||
object
|
||||
}
|
||||
|
||||
/// Write several display lists as a multi-page PDF at the default page origin.
|
||||
pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8> {
|
||||
display_lists_to_pdf_with_origin(pages, page_height, PageOrigin::default())
|
||||
@@ -2207,6 +2243,22 @@ fn write_pdf(
|
||||
catalog.extend_from_slice(b" >>");
|
||||
objects[0] = catalog;
|
||||
|
||||
if let Some(level) = final_compression {
|
||||
let info = match unicode {
|
||||
Some(options) => native_information_dictionary(options.info),
|
||||
None => metadata_object(metadata)
|
||||
.map(String::into_bytes)
|
||||
.unwrap_or_else(|| b"<< /Producer (texrra Route-D native) >>".to_vec()),
|
||||
};
|
||||
objects.push(info);
|
||||
let options = &pages[0]
|
||||
.pdf
|
||||
.as_ref()
|
||||
.expect("validated native PDF options")
|
||||
.file;
|
||||
return objects::serialize(&objects, Some(objects.len()), options, level.max(0).min(9) as u8);
|
||||
}
|
||||
|
||||
let info_ref = match metadata_object(metadata) {
|
||||
Some(object) => {
|
||||
objects.push(object.into_bytes());
|
||||
@@ -2214,22 +2266,6 @@ fn write_pdf(
|
||||
}
|
||||
None => String::new(),
|
||||
};
|
||||
|
||||
if let Some(level) = final_compression {
|
||||
let info = if info_ref.is_empty() {
|
||||
objects.push(b"<< /Producer (texrra Route-D native) >>".to_vec());
|
||||
Some(objects.len())
|
||||
} else {
|
||||
Some(objects.len())
|
||||
};
|
||||
let options = &pages[0]
|
||||
.pdf
|
||||
.as_ref()
|
||||
.expect("validated native PDF options")
|
||||
.file;
|
||||
return objects::serialize(&objects, info, options, level.max(0).min(9) as u8);
|
||||
}
|
||||
|
||||
let mut pdf: Vec<u8> = b"%PDF-1.4\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (index, object) in objects.iter().enumerate() {
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
//! Actual PDF device state shared by execution, painting and serialization.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PdfInfo<'a> {
|
||||
pub entries: &'a [u8],
|
||||
pub date: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfFileOptions {
|
||||
pub major: i32,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Embedded PDF pages and the resource objects reachable from their content.
|
||||
//! Native image XObjects and the resource objects reachable from their content.
|
||||
mod jpeg;
|
||||
use crate::resources::{LoadedResource, ResourceVersion};
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId};
|
||||
use std::{
|
||||
@@ -33,7 +34,7 @@ pub struct PdfImage {
|
||||
pub version: ResourceVersion,
|
||||
pub page: usize,
|
||||
pub page_count: usize,
|
||||
pub natural: [i32; 2],
|
||||
pub natural: [i64; 2],
|
||||
extent: [u64; 2],
|
||||
objects: Vec<Vec<Part>>,
|
||||
}
|
||||
@@ -59,7 +60,9 @@ impl PdfImageUse {
|
||||
image: PdfImage,
|
||||
requested: [Option<i32>; 3],
|
||||
) -> Result<Self, String> {
|
||||
let [w, h] = image.natural.map(i64::from);
|
||||
let [w, h] = image.natural;
|
||||
let jpeg = image.jpeg_frame().map(|(size, _)| size.map(i64::from));
|
||||
let [aspect_width, aspect_height] = jpeg.unwrap_or([w, h]);
|
||||
let [width, height, depth] = requested.map(|value| value.map(i64::from));
|
||||
let ratio = |value: i64, numerator: i64, denominator: i64| {
|
||||
let product = value * numerator;
|
||||
@@ -67,9 +70,12 @@ impl PdfImageUse {
|
||||
};
|
||||
let depth = depth.unwrap_or(0);
|
||||
let (width, height) = match (width, height) {
|
||||
(None, None) if jpeg.is_some() && requested[2].is_some() => {
|
||||
(ratio(h, aspect_width, aspect_height), h - depth)
|
||||
}
|
||||
(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), None) => (width, ratio(width, aspect_height, aspect_width) - depth),
|
||||
(None, Some(height)) => (ratio(height + depth, aspect_width, aspect_height), height),
|
||||
(Some(width), Some(height)) => (width, height),
|
||||
};
|
||||
if [width, height, depth].iter().any(|v| v.abs() > 1073741823) {
|
||||
@@ -93,6 +99,11 @@ impl PdfImageUse {
|
||||
enum Part {
|
||||
Bytes(Vec<u8>),
|
||||
Ref(usize),
|
||||
Jpeg {
|
||||
size: [u16; 2],
|
||||
precision: u8,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) fn real(value: f64) -> String {
|
||||
@@ -101,6 +112,89 @@ pub(crate) fn real(value: f64) -> String {
|
||||
}
|
||||
|
||||
impl PdfImage {
|
||||
pub(crate) fn is_jpeg(resource: &LoadedResource) -> bool {
|
||||
resource.data.starts_with(jpeg::SIGNATURE)
|
||||
|| (!resource.data.starts_with(b"%PDF-")
|
||||
&& resource.version.path.extension().is_some_and(|extension| {
|
||||
extension.eq_ignore_ascii_case("jpg") || extension.eq_ignore_ascii_case("jpeg")
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn read_jpeg(
|
||||
resource: LoadedResource,
|
||||
fallback_resolution: i32,
|
||||
pdf_version: (i32, i32),
|
||||
) -> Result<(Self, Option<&'static str>), String> {
|
||||
let header = jpeg::read(&resource.data).map_err(|error| {
|
||||
format!(
|
||||
"could not parse JPEG image {}: {error}",
|
||||
resource.version.path.display()
|
||||
)
|
||||
})?;
|
||||
if header.progressive && pdf_version.0 == 1 && pdf_version.1 <= 2 {
|
||||
return Err("cannot use progressive DCT with PDF-1.2".into());
|
||||
}
|
||||
let [width, height] = header.size;
|
||||
let color = match header.components {
|
||||
1 => "/DeviceGray",
|
||||
3 => "/DeviceRGB",
|
||||
4 => "/DeviceCMYK /Decode [1 0 1 0 1 0 1 0]",
|
||||
_ => unreachable!("JPEG component count was checked"),
|
||||
};
|
||||
let mut density = header.density;
|
||||
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
|
||||
Some("too large image resolution ignored")
|
||||
} else if density != [0, 0] && density.contains(&0) {
|
||||
Some("too small image resolution ignored")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if warning.is_some() || density == [0, 0] {
|
||||
let default = fallback_resolution.clamp(0, 65_535) as u32;
|
||||
density = [if default == 0 { 72 } else { default }; 2];
|
||||
}
|
||||
let natural = std::array::from_fn(|axis| {
|
||||
// One hundred inches in TeX scaled points.
|
||||
let numerator = 473_628_672_i64 * i64::from(header.size[axis]);
|
||||
let denominator = 100 * i64::from(density[axis]);
|
||||
(numerator + denominator / 2) / denominator
|
||||
});
|
||||
let dictionary = format!(
|
||||
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
|
||||
/ColorSpace {color} /BitsPerComponent {} /Filter /DCTDecode /Length {} >>\nstream\n",
|
||||
header.precision,
|
||||
resource.data.len()
|
||||
);
|
||||
Ok((
|
||||
Self {
|
||||
version: resource.version,
|
||||
page: 1,
|
||||
page_count: 1,
|
||||
natural,
|
||||
extent: [1.0_f64.to_bits(); 2],
|
||||
objects: vec![vec![
|
||||
Part::Bytes(dictionary.into_bytes()),
|
||||
Part::Jpeg {
|
||||
size: header.size,
|
||||
precision: header.precision,
|
||||
bytes: resource.data,
|
||||
},
|
||||
Part::Bytes(b"\nendstream".to_vec()),
|
||||
]],
|
||||
},
|
||||
warning,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn jpeg_frame(&self) -> Option<([u16; 2], u8)> {
|
||||
self.objects.first()?.iter().find_map(|part| match part {
|
||||
Part::Jpeg {
|
||||
size, precision, ..
|
||||
} => Some((*size, *precision)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn read(
|
||||
resource: LoadedResource,
|
||||
page: usize,
|
||||
@@ -172,12 +266,12 @@ impl PdfImage {
|
||||
),
|
||||
_ => return Err("PDF image rotation must be a multiple of 90 degrees".into()),
|
||||
};
|
||||
let sp = |bp: f64| -> Result<i32, String> {
|
||||
let sp = |bp: f64| -> Result<i64, 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)
|
||||
Ok(value as i64)
|
||||
};
|
||||
let natural = [sp(width)?, sp(height)?];
|
||||
let mut contents = Vec::new();
|
||||
@@ -243,7 +337,7 @@ impl PdfImage {
|
||||
}
|
||||
for part in parts {
|
||||
match part {
|
||||
Part::Bytes(bytes) => body.extend_from_slice(bytes),
|
||||
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
|
||||
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! JPEG frame and density metadata. The encoded image stays in its original stream.
|
||||
|
||||
pub(super) const SIGNATURE: &[u8] = b"\xff\xd8";
|
||||
|
||||
pub(super) struct Header {
|
||||
pub size: [u16; 2],
|
||||
pub precision: u8,
|
||||
pub components: u8,
|
||||
pub density: [u32; 2],
|
||||
pub progressive: bool,
|
||||
}
|
||||
|
||||
pub(super) fn read(bytes: &[u8]) -> Result<Header, &'static str> {
|
||||
let mut rest = bytes
|
||||
.strip_prefix(SIGNATURE)
|
||||
.ok_or("missing JPEG signature")?;
|
||||
let mut density = [0, 0];
|
||||
let mut first = true;
|
||||
let truncated = "premature end of JPEG header";
|
||||
loop {
|
||||
rest = rest.strip_prefix(&[0xff]).ok_or("expected JPEG marker")?;
|
||||
while let Some(following) = rest.strip_prefix(&[0xff]) {
|
||||
rest = following;
|
||||
}
|
||||
let (&marker, remaining) = rest.split_first().ok_or(truncated)?;
|
||||
rest = remaining;
|
||||
match marker {
|
||||
0xd9 | 0xda => return Err("JPEG has no frame header"),
|
||||
0x01 | 0xd0..=0xd8 => {
|
||||
first = false;
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let length = usize::from(u16::from_be_bytes(
|
||||
rest.get(..2)
|
||||
.ok_or(truncated)?
|
||||
.try_into()
|
||||
.expect("two-byte JPEG length"),
|
||||
));
|
||||
let segment = rest.get(2..length).ok_or(truncated)?;
|
||||
rest = &rest[length..];
|
||||
|
||||
match marker {
|
||||
0xc0..=0xc3 => {
|
||||
let &[precision, h0, h1, w0, w1, components, ref table @ ..] = segment else {
|
||||
return Err(truncated);
|
||||
};
|
||||
if !matches!(components, 1 | 3 | 4) {
|
||||
return Err("unsupported JPEG color space");
|
||||
}
|
||||
if table.len() != 3 * usize::from(components) {
|
||||
return Err("invalid JPEG component table");
|
||||
}
|
||||
let size = [u16::from_be_bytes([w0, w1]), u16::from_be_bytes([h0, h1])];
|
||||
if size.contains(&0) || precision == 0 {
|
||||
return Err("invalid JPEG frame dimensions or precision");
|
||||
}
|
||||
return Ok(Header {
|
||||
size,
|
||||
precision,
|
||||
components,
|
||||
density,
|
||||
progressive: marker == 0xc2,
|
||||
});
|
||||
}
|
||||
0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => {
|
||||
return Err("unsupported JPEG compression");
|
||||
}
|
||||
0xe0 if first => {
|
||||
if let Some(&[_, _, unit, x0, x1, y0, y1, ..]) = segment.strip_prefix(b"JFIF\0") {
|
||||
let x = u32::from(u16::from_be_bytes([x0, x1]));
|
||||
let y = u32::from(u16::from_be_bytes([y0, y1]));
|
||||
density = match unit {
|
||||
1 => [x, y],
|
||||
2 => [x * 254 / 100, y * 254 / 100],
|
||||
_ => [0, 0],
|
||||
};
|
||||
if density.contains(&0) {
|
||||
density = [density[0].max(density[1]); 2];
|
||||
}
|
||||
}
|
||||
}
|
||||
0xe1 if first => {
|
||||
if let Some(tiff) = segment.strip_prefix(b"Exif\0") {
|
||||
let start = tiff
|
||||
.iter()
|
||||
.position(|&byte| byte != 0)
|
||||
.unwrap_or(tiff.len());
|
||||
density = exif_density(&tiff[start..]).unwrap_or([0, 0]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> {
|
||||
let little = match tiff.get(..2)? {
|
||||
b"II" => true,
|
||||
b"MM" => false,
|
||||
_ => return None,
|
||||
};
|
||||
let short = |at: usize| {
|
||||
let bytes = tiff.get(at..at.checked_add(2)?)?.try_into().ok()?;
|
||||
Some(if little {
|
||||
u16::from_le_bytes(bytes)
|
||||
} else {
|
||||
u16::from_be_bytes(bytes)
|
||||
})
|
||||
};
|
||||
let long = |at: usize| {
|
||||
let bytes = tiff.get(at..at.checked_add(4)?)?.try_into().ok()?;
|
||||
Some(if little {
|
||||
u32::from_le_bytes(bytes)
|
||||
} else {
|
||||
u32::from_be_bytes(bytes)
|
||||
})
|
||||
};
|
||||
if short(2)? != 42 {
|
||||
return None;
|
||||
}
|
||||
let start = usize::try_from(long(4)?).ok()?;
|
||||
let entries = usize::from(short(start)?);
|
||||
let start = start.checked_add(2)?;
|
||||
let end = start.checked_add(12 * entries)?;
|
||||
tiff.get(start..end)?;
|
||||
let mut density = [72, 72];
|
||||
let mut cm = false;
|
||||
for at in (start..end).step_by(12) {
|
||||
match (short(at)?, short(at + 2)?, long(at + 4)?) {
|
||||
(tag @ (282 | 283), 5, 1) => {
|
||||
let offset = usize::try_from(long(at + 8)?).ok()?;
|
||||
let numerator = long(offset)?;
|
||||
let denominator = long(offset.checked_add(4)?)?;
|
||||
if denominator != 0 {
|
||||
density[usize::from(tag == 283)] = numerator / denominator;
|
||||
}
|
||||
}
|
||||
(296, 3, 1) => cm = short(at + 8)? == 3,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if cm {
|
||||
density =
|
||||
density.map(|value| u32::try_from(u64::from(value) * 254 / 100).unwrap_or(u32::MAX));
|
||||
}
|
||||
Some(density)
|
||||
}
|
||||
@@ -129,6 +129,7 @@ pub struct PdfFinalOptions<'a> {
|
||||
pub generate_unicode: i32,
|
||||
pub glyph_unicode: &'a GlyphUnicodeMap,
|
||||
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
|
||||
pub info: crate::pdf_device::PdfInfo<'a>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in new issue
Block a user