773 lines
34 KiB
Rust
773 lines
34 KiB
Rust
use super::super::boxes::{self, PackSpec, VerticalBuilder};
|
|
use super::*;
|
|
use crate::native_font::{JobVirtualFonts, NativeFont, VirtualGlyphs};
|
|
use std::collections::BTreeSet;
|
|
|
|
|
|
#[derive(Clone)]
|
|
pub(super) struct OutputFrame {
|
|
pub(super) depth: usize,
|
|
pub(super) span: Span,
|
|
pub(super) paragraph: Option<super::super::paragraph::Builder>,
|
|
pub(super) vertical: VerticalBuilder,
|
|
pub(super) math: Vec<super::super::math::MathBuilder>,
|
|
pub(super) display: Option<super::display::DisplayFrame>,
|
|
}
|
|
impl OutputFrame {
|
|
pub(super) fn collect_statistics(&self, c: &mut super::super::statistics::Collector) {
|
|
if let Some(p) = &self.paragraph {
|
|
c.paragraph_builder(p);
|
|
}
|
|
c.vertical(
|
|
&self.vertical.nodes,
|
|
super::super::statistics::Ownership::Active,
|
|
);
|
|
for m in &self.math {
|
|
c.math_builder(m);
|
|
}
|
|
}
|
|
}
|
|
/// Track the font identities the PDF device has encountered before the first
|
|
/// dedicated space. Checkpoints share this state until a later shipout writes it.
|
|
#[derive(Clone, Default)]
|
|
pub(super) struct PdfSpaceProbe {
|
|
history: crate::pdf::native_text::FontHistory,
|
|
virtuals: crate::native_font::VirtualPaintState,
|
|
cache: Arc<crate::native_font::NativeFontCache>,
|
|
observed_events: usize,
|
|
}
|
|
|
|
struct ShipoutFontUse {
|
|
before_output: usize,
|
|
font: Arc<NativeFont>,
|
|
slot: u8,
|
|
}
|
|
|
|
fn shipout_font_uses(
|
|
b: &NativeBox, programs: &JobVirtualFonts, fonts: &FontCatalog,
|
|
) -> Result<Vec<ShipoutFontUse>, String> {
|
|
let mut uses = Vec::new();
|
|
let mut seen = BTreeSet::new();
|
|
b.visit_shipout_font_uses(|before_output, font, slot| {
|
|
if (!programs.is_known_physical(font.id) || fonts.automatic_origin(font.id).is_some())
|
|
&& seen.insert((font.id, slot))
|
|
{
|
|
uses.push(ShipoutFontUse { before_output, font: font.clone(), slot });
|
|
}
|
|
})?;
|
|
Ok(uses)
|
|
}
|
|
|
|
impl Executor {
|
|
pub(super) fn outer_vertical(&self) -> bool {
|
|
self.box_frames.is_empty() && self.output_frame.is_none() && self.alignments.is_empty()
|
|
}
|
|
pub(super) fn native_page_mut(&mut self) -> Result<&mut NativePageState, Error> {
|
|
if self.native_page.is_none() {
|
|
return self.fail("native page/output execution requires a native job target");
|
|
}
|
|
self.reads.insert(Dependency::PageState);
|
|
Ok(self.native_page.as_mut().unwrap())
|
|
}
|
|
pub(super) fn page_dimension_value(&mut self, p: Primitive) -> Result<i32, Error> {
|
|
let value = self
|
|
.native_page_mut()?
|
|
.dimension(p.page_dimension().unwrap());
|
|
i32::try_from(value).map_err(|_| self.error("native page dimension overflow", self.current))
|
|
}
|
|
pub(super) fn request_page(&mut self) {
|
|
if self.outer_vertical() {
|
|
if let Some(page) = self.native_page.as_mut() {
|
|
page.requested = true;
|
|
}
|
|
}
|
|
}
|
|
pub(super) fn process_native_pages(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
while let Some(b) = self.pending_shipouts.pop_front() {
|
|
self.ship_box(b, files)?;
|
|
}
|
|
if self.native_page.is_none() {
|
|
return Ok(());
|
|
}
|
|
loop {
|
|
self.read_parameter(Parameter::Tracingpages);
|
|
let mut trace = Vec::new();
|
|
let next = self.native_page.as_mut().unwrap().advance(
|
|
&mut self.state,
|
|
&mut self.reads,
|
|
&mut self.steps,
|
|
self.limits.steps,
|
|
&mut trace,
|
|
);
|
|
for trace in trace {
|
|
let destination = if self.read_parameter(Parameter::Tracingonline).width() > 0 {
|
|
WriteDestination::TerminalAndLog
|
|
} else {
|
|
WriteDestination::Log
|
|
};
|
|
self.reads.insert(Dependency::NewLineChar);
|
|
let text = self.print_show_parts(&[&trace.text()])?;
|
|
self.diagnostic_bytes = self.diagnostic_bytes.saturating_add(text.len());
|
|
if self.diagnostic_bytes > self.limits.tokens {
|
|
return self.fail("native diagnostic output limit exceeded");
|
|
}
|
|
files
|
|
.observe_diagnostic(destination, &text)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
self.events.push(Event::PageTrace(Box::new(PageTraceReport {
|
|
trace,
|
|
text,
|
|
destination,
|
|
span: self.current,
|
|
})));
|
|
}
|
|
let next = next.map_err(|e| self.error(e, self.current))?;
|
|
let Some(next) = next else {
|
|
return Ok(());
|
|
};
|
|
self.reads.insert(Dependency::PageState);
|
|
for p in [Parameter::Vsize, Parameter::Maxdepth, Parameter::Topskip] {
|
|
self.reads.insert(Dependency::Parameter(p));
|
|
}
|
|
if self.state.box_register(255).is_some() {
|
|
return self.fail("native box255 is not void before output");
|
|
}
|
|
self.state.assign_parameter(
|
|
Parameter::Outputpenalty,
|
|
ParameterValue::Integer(next.penalty),
|
|
true,
|
|
);
|
|
for marks in self.state.page_marks.values_mut() {
|
|
if marks.bottom.is_some() {
|
|
marks.top = marks.bottom.clone();
|
|
marks.first = None;
|
|
}
|
|
}
|
|
for node in &next.nodes {
|
|
self.tick()?;
|
|
if let NativeVerticalNode::Mark(m) = node {
|
|
let marks = self.state.page_marks.entry(m.class).or_default();
|
|
if marks.first.is_none() {
|
|
marks.first = Some(m.tokens.clone());
|
|
}
|
|
marks.bottom = Some(m.tokens.clone());
|
|
}
|
|
}
|
|
for marks in self.state.page_marks.values_mut() {
|
|
if marks.first.is_none() {
|
|
marks.first = marks.top.clone();
|
|
}
|
|
}
|
|
let b = boxes::vpack(
|
|
next.nodes,
|
|
PackSpec::To(next.goal),
|
|
next.max_depth,
|
|
BoxKind::Vertical,
|
|
self.current,
|
|
)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
self.state.last_badness = b.badness;
|
|
self.account_box(&b)?;
|
|
self.state.set_box(255, Some(b));
|
|
self.reads
|
|
.insert(Dependency::TokenParameter(TokenParameter::Output));
|
|
if let Some(tokens) = self.state.token_parameter(TokenParameter::Output).cloned() {
|
|
let max = self.read_parameter(Parameter::Maxdeadcycles).width();
|
|
if self.native_page.as_ref().unwrap().dead_cycles >= max {
|
|
return self.fail("native output loop: too many consecutive dead cycles");
|
|
}
|
|
self.native_page.as_mut().unwrap().dead_cycles += 1;
|
|
self.native_page.as_mut().unwrap().output_active = true;
|
|
if self.inputs.len() >= self.limits.input_depth {
|
|
return self.fail("native output input stack limit exceeded");
|
|
}
|
|
self.output_frame = Some(OutputFrame {
|
|
depth: self.state.group_depth() + 1,
|
|
span: self.current,
|
|
paragraph: self.paragraph.take(),
|
|
vertical: std::mem::take(&mut self.vertical),
|
|
math: std::mem::take(&mut self.math),
|
|
display: self.display.take(),
|
|
});
|
|
self.inputs.push(InputFrame::Tokens {
|
|
tokens: tokens.iter().cloned().map(InputToken::from).collect(),
|
|
cursor: 0,
|
|
kind: TokenInputKind::Output,
|
|
});
|
|
self.begin_group(GroupKind::Output, files)?;
|
|
self.normal_paragraph(files)?;
|
|
let open = loop {
|
|
let t = self.expanded_non_space(files)?.token;
|
|
if self.primitive(&t) != Some(Primitive::Relax) {
|
|
break t;
|
|
}
|
|
};
|
|
if !matches!(
|
|
self.meaning(&open),
|
|
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
|
|
) {
|
|
return self.fail("expected opening brace in native output routine");
|
|
}
|
|
return Ok(());
|
|
}
|
|
let b = self.state.take_box(255).unwrap();
|
|
self.native_page
|
|
.as_mut()
|
|
.unwrap()
|
|
.resume_contributions(Vec::new());
|
|
self.ship_box(b, files)?;
|
|
}
|
|
}
|
|
pub(super) fn close_output_group(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<bool, Error> {
|
|
if !self
|
|
.output_frame
|
|
.as_ref()
|
|
.is_some_and(|f| f.depth == self.state.group_depth())
|
|
{
|
|
return Ok(false);
|
|
}
|
|
if !matches!(self.inputs.last(),Some(InputFrame::Tokens{tokens,cursor,kind:TokenInputKind::Output|TokenInputKind::BackedUp})if *cursor==tokens.len())
|
|
|| self.inputs.iter().any(|f| matches!(f, InputFrame::Tokens { tokens, cursor, kind: TokenInputKind::Output } if *cursor != tokens.len()))
|
|
{
|
|
return self.fail("unbalanced native output routine");
|
|
}
|
|
self.inputs.pop();
|
|
if matches!(self.inputs.last(),Some(InputFrame::Tokens{tokens,cursor,kind:TokenInputKind::Output})if *cursor==tokens.len())
|
|
{
|
|
self.inputs.pop();
|
|
}
|
|
self.end_paragraph(files)?;
|
|
self.finish_group(GroupKind::Output, self.current, files)?;
|
|
if self.state.box_register(255).is_some() {
|
|
return self.fail("native output routine did not empty box255");
|
|
}
|
|
let nodes = self.vertical.take_nodes();
|
|
let frame = self.output_frame.take().unwrap();
|
|
self.paragraph = frame.paragraph;
|
|
self.vertical = frame.vertical;
|
|
self.math = frame.math;
|
|
self.display = frame.display;
|
|
let page = self.native_page.as_mut().unwrap();
|
|
page.output_active = false;
|
|
page.resume_contributions(nodes);
|
|
page.requested = true;
|
|
Ok(true)
|
|
}
|
|
pub(super) fn ship_box(
|
|
&mut self,
|
|
b: NativeBox,
|
|
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;
|
|
if b.height > MAX_DIMEN
|
|
|| b.depth > MAX_DIMEN
|
|
|| b.height + b.depth + v_offset > MAX_DIMEN
|
|
|| b.width + h_offset > MAX_DIMEN
|
|
{
|
|
return self.fail("huge native page cannot be shipped out");
|
|
}
|
|
let magnification = self.prepare_magnification()?;
|
|
let pdf = self.pdf_page_data(files)?;
|
|
let unicode_pages = self.state.input_profile() != InputProfile::TeX8Bit;
|
|
// The XDV driver uses a physical sheet and origin, then applies
|
|
// magnification to the DVI movements relative to that origin.
|
|
let origin = |value| {
|
|
if unicode_pages {
|
|
crate::pdf_device::unmagnify(value, magnification)
|
|
} else {
|
|
value
|
|
}
|
|
};
|
|
let horizontal_origin =
|
|
origin(i64::from(self.read_parameter(Parameter::Pdfhorigin).width())) + h_offset;
|
|
let vertical_origin =
|
|
origin(i64::from(self.read_parameter(Parameter::Pdfvorigin).width())) + v_offset;
|
|
let mut page_width = i64::from(self.read_parameter(Parameter::Pdfpagewidth).width());
|
|
let requested_page_height = i64::from(self.read_parameter(Parameter::Pdfpageheight).width());
|
|
let default_canvas = |bp: i64| origin(bp * 803 * 65536 / 800);
|
|
if page_width == 0 {
|
|
page_width = if unicode_pages { default_canvas(612) } else { b.width + 2 * horizontal_origin };
|
|
}
|
|
let page_height = if requested_page_height != 0 {
|
|
requested_page_height
|
|
} else if unicode_pages {
|
|
default_canvas(792)
|
|
} else {
|
|
b.height + b.depth + 2 * vertical_origin
|
|
};
|
|
let device = ShipoutDevice {
|
|
magnification,
|
|
page_width,
|
|
page_height,
|
|
horizontal_origin,
|
|
vertical_origin,
|
|
pdf,
|
|
};
|
|
self.trace_shipout(&b, files)?;
|
|
let current = self.current;
|
|
let (pdf_resource_entries, pdf_page_attributes) = if device.pdf.is_some() {
|
|
(
|
|
self.pdf_token_parameter_bytes(TokenParameter::Pdfpageresources)?.into(),
|
|
self.pdf_token_parameter_bytes(TokenParameter::Pdfpageattr)?.into(),
|
|
)
|
|
} else {
|
|
(Default::default(), Default::default())
|
|
};
|
|
use crate::pdf_device::PdfDriver;
|
|
let xdv = device.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
|
|
let pdf_color_start = if xdv {
|
|
self.xdv_colors.start_page().into_iter().collect()
|
|
} else if device.pdf.is_some() {
|
|
self.pdf_colors.start_page()
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
let font_overrides = if device.pdf.is_some() {
|
|
self.reads.insert(Dependency::FontResources);
|
|
self.state.fonts.expansion_paint_fonts()
|
|
} else {
|
|
Default::default()
|
|
};
|
|
let mut shipout = NativeShipout {
|
|
box_node: b,
|
|
device,
|
|
font_overrides,
|
|
virtual_glyphs: None,
|
|
pdf_font_bindings: self.pdf_virtual_fonts.captured_font_bindings(),
|
|
pdf_color_start,
|
|
pdf_color_steps: Vec::new(),
|
|
pdf_graphics_steps: Vec::new(),
|
|
xdv_color_steps: Default::default(),
|
|
pdf_background: None,
|
|
pdf_special_images: Default::default(),
|
|
specials: Vec::new(),
|
|
pdf_text_spaces: None,
|
|
pdf_resource_entries,
|
|
pdf_page_attributes,
|
|
pdf_links: Default::default(),
|
|
};
|
|
let b = &shipout.box_node;
|
|
let device = &shipout.device;
|
|
let mut graphics_stack = Vec::new();
|
|
let mut xdv_graphics_stack = Vec::new();
|
|
let mut xdv_transform = crate::pdf_device::Affine::IDENTITY;
|
|
let (mut outputs, has_leaders) = b.output_nodes();
|
|
let leader_effects = if has_leaders {
|
|
let limit = self
|
|
.limits
|
|
.steps
|
|
.saturating_sub(self.steps)
|
|
.min(self.limits.tokens);
|
|
let effects = b
|
|
.leader_effects(limit, self.cancellation.as_ref())
|
|
.map_err(|error| self.error(error, b.span))?;
|
|
self.steps += effects.work;
|
|
Some(effects)
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(effects) = &leader_effects {
|
|
outputs = effects.outputs.iter().collect();
|
|
}
|
|
let mut link_depth = self.pdf_link_stack.len();
|
|
let has_link_material = link_depth != 0 || outputs.iter().any(|node| node.is_pdf_link());
|
|
let mut output_positions = if let Some(effects) = &leader_effects {
|
|
effects.output_positions.clone().into_iter()
|
|
} else if outputs.iter().any(|node| node.needs_shipout_position()) {
|
|
b.positioned_outputs().into_iter()
|
|
} else {
|
|
Vec::new().into_iter()
|
|
};
|
|
let mut font_uses = if device.pdf.is_some() {
|
|
shipout.virtual_glyphs = Some(VirtualGlyphs::new());
|
|
shipout_font_uses(b, &self.pdf_virtual_fonts, &self.state.fonts).map_err(|e| self.error(e, b.span))?
|
|
} else {
|
|
Vec::new()
|
|
}.into_iter().peekable();
|
|
use crate::pdf_device::text_spaces::SpaceOperation;
|
|
let automatic_spaces_at_start = self.pdf_interword_spaces;
|
|
let mut uses_automatic_spaces = automatic_spaces_at_start;
|
|
let mut has_space_nodes = false;
|
|
let mut has_explicit_space = false;
|
|
let mut pdf_objects = Vec::new();
|
|
for (index, output) in outputs.into_iter().enumerate() {
|
|
while font_uses.peek().is_some_and(|usage| usage.before_output == index) {
|
|
self.current = current;
|
|
self.prepare_virtual_glyph(
|
|
shipout.virtual_glyphs.as_mut().unwrap(), font_uses.next().unwrap(), files,
|
|
)?;
|
|
}
|
|
if self.pdf_loaded_space_font.is_none()
|
|
&& (uses_automatic_spaces || has_explicit_space)
|
|
&& matches!(
|
|
output.operation,
|
|
OutputOperation::Write { .. } | OutputOperation::PdfLiteral { shipout: true, .. }
|
|
| OutputOperation::Special { shipout: true, .. }
|
|
)
|
|
{
|
|
shipout.pdf_font_bindings = self.pdf_virtual_fonts.captured_font_bindings();
|
|
shipout.pdf_text_spaces =
|
|
Some(self.pdf_space_settings(automatic_spaces_at_start, uses_automatic_spaces));
|
|
self.current = output.span;
|
|
self.probe_pdf_space_font(&shipout, Some(index), files)?;
|
|
}
|
|
let position = if output.needs_shipout_position() {
|
|
Some(output_positions.next().ok_or_else(|| {
|
|
self.error("missing positioned native output node", output.span)
|
|
})?)
|
|
} else {
|
|
None
|
|
};
|
|
if let OutputOperation::PdfObject(number) = output.operation {
|
|
self.current = output.span;
|
|
self.tick()?;
|
|
if device.pdf.is_none() {
|
|
return self.fail("cannot ship a PDF object reference to DVI");
|
|
}
|
|
pdf_objects.push((number, output.span));
|
|
} else if let OutputOperation::PdfColor { stack, action } = &output.operation {
|
|
if device.pdf.is_none() {
|
|
return self.fail("cannot ship a PDF color operation to DVI");
|
|
}
|
|
shipout.pdf_color_steps.push(self.ship_pdf_color(*stack, action, output.span, files)?);
|
|
} else if let OutputOperation::Special { origin, .. } = &output.operation {
|
|
let special = self.resolve_special(
|
|
output, position.expect("special needs a shipout position"), files,
|
|
)?;
|
|
let point = xdv_transform.point(
|
|
(special.position[0] + horizontal_origin) as f64,
|
|
(special.position[1] + vertical_origin + b.height) as f64,
|
|
).map(|coordinate| coordinate.round() as i64);
|
|
let graphics_step = shipout.pdf_graphics_steps.len();
|
|
let graphics = if let Some(pdf) = &device.pdf {
|
|
if let Some(color) = xdv.then(|| self.xdv_colors.apply(&special.bytes)).flatten() {
|
|
let color = color.map_err(|error| self.error(error, special.span))?;
|
|
if let Some(warning) = color.warning {
|
|
files.observe_diagnostic(
|
|
WriteDestination::TerminalAndLog, &format!("xdvipdfmx: warning: {warning}\n"),
|
|
).map_err(|error| self.error(error, special.span))?;
|
|
}
|
|
if let Some(program) = color.program {
|
|
shipout.xdv_color_steps.insert(graphics_step, program);
|
|
}
|
|
None
|
|
} else if xdv && self.xdv_destination_special(&special, point, &mut shipout.pdf_links)? {
|
|
None
|
|
} else if xdv && let Some(image) = crate::pdf_device::xdv_image::ImageSpecial::parse(
|
|
&special.bytes, device.magnification,
|
|
).map_err(|error| self.error(error, special.span))?
|
|
{
|
|
if let Some(image) = self.ship_xdv_raster_special(image, special.span, files)? {
|
|
shipout.pdf_special_images.insert(
|
|
shipout.pdf_graphics_steps.len(),
|
|
(image, origin.unwrap_or(TokenOrigin {
|
|
span: special.span,
|
|
invocation: None,
|
|
})),
|
|
);
|
|
}
|
|
None
|
|
} else {
|
|
self.render_special(&special, pdf.driver, files)?
|
|
}
|
|
} else {
|
|
None
|
|
};
|
|
use crate::pdf_device::PdfGraphics;
|
|
match &graphics {
|
|
Some(PdfGraphics::Save) => {
|
|
xdv_graphics_stack.push((special.span, xdv_transform, self.xdv_colors.current()));
|
|
}
|
|
Some(operation @ (PdfGraphics::SaveMatrix(matrix) | PdfGraphics::Matrix(matrix))) => {
|
|
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
|
|
xdv_graphics_stack.push((special.span, xdv_transform, self.xdv_colors.current()));
|
|
}
|
|
let [x, y] = special.position;
|
|
let pivot = matrix.about(
|
|
(x + horizontal_origin) as f64,
|
|
(y + vertical_origin + b.height) as f64,
|
|
true,
|
|
);
|
|
xdv_transform = xdv_transform.concatenate(pivot);
|
|
}
|
|
Some(PdfGraphics::Restore { .. }) => {
|
|
let Some((_, previous, color_at_save)) = xdv_graphics_stack.pop() else {
|
|
return Err(self.error("unmatched XDV graphics restore", special.span));
|
|
};
|
|
xdv_transform = previous;
|
|
if let Some(program) = self.xdv_colors.restore_after_save(color_at_save) {
|
|
shipout.xdv_color_steps.insert(graphics_step, program);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
shipout.specials.push(special);
|
|
shipout.pdf_graphics_steps.push(graphics);
|
|
} else if output.is_pdf_graphics() {
|
|
if device.pdf.is_none() {
|
|
return self.fail("cannot ship a PDF graphics operation to DVI");
|
|
}
|
|
shipout.pdf_graphics_steps.push(Some(self.ship_pdf_graphics(
|
|
output,
|
|
position.expect("PDF graphics need a shipout position"),
|
|
&mut graphics_stack,
|
|
files,
|
|
)?));
|
|
} else if let OutputOperation::PdfSavePosition = output.operation {
|
|
self.current = output.span;
|
|
self.tick()?;
|
|
let [x, y] = position.expect("savepos needs a shipout position");
|
|
let (left, top, height) = if device.pdf.is_some() {
|
|
(horizontal_origin, vertical_origin, page_height)
|
|
} else {
|
|
const DVI_ORIGIN: i64 = 4_736_286;
|
|
let top = v_offset + DVI_ORIGIN;
|
|
let height = if requested_page_height == 0 {
|
|
b.height + b.depth + 2 * top
|
|
} else {
|
|
requested_page_height
|
|
};
|
|
(h_offset + DVI_ORIGIN, top, height)
|
|
};
|
|
self.state.pdf_last_position = [
|
|
i32::try_from(left + x)
|
|
.map_err(|_| self.error("horizontal saved position overflow", output.span))?,
|
|
i32::try_from(height - top - b.height - y)
|
|
.map_err(|_| self.error("vertical saved position overflow", output.span))?,
|
|
];
|
|
} else if let OutputOperation::PdfTextSpace(operation) = output.operation {
|
|
self.current = output.span;
|
|
self.tick()?;
|
|
if device.pdf.is_none() {
|
|
return self.fail("cannot ship a PDF text space operation to DVI");
|
|
}
|
|
has_space_nodes = true;
|
|
if let SpaceOperation::Automatic(enabled) = operation {
|
|
self.pdf_interword_spaces = enabled;
|
|
uses_automatic_spaces |= enabled;
|
|
} else {
|
|
has_explicit_space = true;
|
|
}
|
|
} else if let OutputOperation::PdfLink(link) = &output.operation {
|
|
use crate::pdf_device::links::LinkNode;
|
|
self.current = output.span;
|
|
self.tick()?;
|
|
if device.pdf.is_none() {
|
|
return self.fail("cannot ship a PDF link operation to DVI");
|
|
}
|
|
match link {
|
|
LinkNode::Start(_) if link_depth == 10 => {
|
|
return self.fail("PDF link stack capacity exceeded");
|
|
}
|
|
LinkNode::Start(_) => link_depth += 1,
|
|
LinkNode::End if link_depth == 0 => {
|
|
return self.fail("\\pdfendlink used without \\pdfstartlink");
|
|
}
|
|
LinkNode::End => link_depth -= 1,
|
|
LinkNode::Running(_) | LinkNode::Destination { .. } => {}
|
|
}
|
|
} else {
|
|
self.output_node(output, files)?;
|
|
}
|
|
}
|
|
if output_positions.next().is_some() {
|
|
return self.fail("unexpected positioned native output node");
|
|
}
|
|
if let Some(&(span, ..)) = xdv_graphics_stack.last() {
|
|
return Err(self.error("unclosed XDV graphics save at page shipout", span));
|
|
}
|
|
if let Some((_, span)) = graphics_stack.last() {
|
|
return Err(self.error(
|
|
format!(
|
|
"{} unmatched \\pdfsave after page shipout",
|
|
graphics_stack.len()
|
|
),
|
|
*span,
|
|
));
|
|
}
|
|
self.current = current;
|
|
for usage in font_uses {
|
|
self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, files)?;
|
|
}
|
|
shipout.pdf_font_bindings = self.pdf_virtual_fonts.captured_font_bindings();
|
|
let has_space_settings = has_space_nodes || automatic_spaces_at_start;
|
|
let probed_page = (uses_automatic_spaces || has_explicit_space)
|
|
&& self.pdf_loaded_space_font.is_none();
|
|
if has_space_settings {
|
|
shipout.pdf_text_spaces =
|
|
Some(self.pdf_space_settings(automatic_spaces_at_start, uses_automatic_spaces));
|
|
}
|
|
if probed_page {
|
|
self.probe_pdf_space_font(&shipout, None, files)?;
|
|
shipout.pdf_text_spaces.as_mut().unwrap().dedicated_font =
|
|
self.pdf_loaded_space_font.clone();
|
|
}
|
|
for (number, span) in pdf_objects {
|
|
self.current = span;
|
|
self.write_pdf_object(number, files)?;
|
|
}
|
|
if has_link_material {
|
|
let mut links = self.ship_pdf_link_material(
|
|
b, device, &shipout.pdf_graphics_steps, files,
|
|
)?;
|
|
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
|
|
shipout.pdf_links = links;
|
|
}
|
|
if let Some(pdf) = &mut shipout.device.pdf && xdv {
|
|
shipout.pdf_background = self.xdv_colors.background();
|
|
self.state.xdv_setup.apply_version(&mut pdf.file);
|
|
}
|
|
self.current = current;
|
|
self.native_page.as_mut().unwrap().dead_cycles = 0;
|
|
let before = self.statistics_before_shipout(&shipout.box_node, files)?;
|
|
self.shipped_pages += 1;
|
|
self.events.push(Event::Shipout(Box::new(shipout)));
|
|
if probed_page && let Some(probe) = self.pdf_space_probe.as_mut() {
|
|
Arc::make_mut(probe).observed_events = self.events.len();
|
|
}
|
|
self.statistics_after_shipout(before, files)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn pdf_space_settings(
|
|
&mut self,
|
|
automatic_at_start: bool,
|
|
uses_automatic: bool,
|
|
) -> crate::pdf_device::text_spaces::SpaceSettings {
|
|
use crate::pdf_device::text_spaces::SpaceSettings;
|
|
let parameters = if uses_automatic {
|
|
self.reads.insert(Dependency::FontResources);
|
|
self.state.fonts.fonts().iter().map(|font| {
|
|
let glue = font.space();
|
|
(glue.width, glue.shrink.amount)
|
|
}).collect()
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
SpaceSettings {
|
|
automatic_at_start,
|
|
dedicated_font: self.pdf_loaded_space_font.clone(),
|
|
parameters,
|
|
}
|
|
}
|
|
|
|
fn prepare_virtual_glyph(
|
|
&mut self, glyphs: &mut VirtualGlyphs, usage: ShipoutFontUse,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
self.check_cancellation()?;
|
|
let id = usage.font.id;
|
|
if self.pdf_virtual_fonts.is_known_physical(id)
|
|
&& self.state.fonts.automatic_origin(id).is_none()
|
|
{
|
|
return Ok(());
|
|
}
|
|
let defaults = self.font_defaults();
|
|
let (packet, work) = Arc::make_mut(&mut self.pdf_virtual_fonts).glyph(
|
|
&mut self.state.fonts, defaults, files, usage.font, usage.slot,
|
|
self.limits.steps.saturating_sub(self.steps), self.cancellation.as_ref(),
|
|
).map_err(|e| self.error(e, self.current))?;
|
|
self.steps += work;
|
|
if let Some(packet) = packet {
|
|
glyphs.entry(id).or_default().insert(usage.slot, packet);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn probe_pdf_space_font(
|
|
&mut self,
|
|
shipout: &NativeShipout,
|
|
before_output: Option<usize>,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
use crate::pdf::native_text::plan_spaces;
|
|
use crate::pdf_device::text_spaces::SpaceFontRequest;
|
|
|
|
let mut page = shipout.display_list_prefix(before_output)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
let mut shared = self.pdf_space_probe.take().unwrap_or_default();
|
|
let prior = Arc::make_mut(&mut shared);
|
|
for event in self.events.iter().skip(prior.observed_events) {
|
|
let Event::Shipout(shipped) = event else { continue };
|
|
self.check_cancellation()?;
|
|
let mut shipped = shipped.display_list().map_err(|e| self.error(e, self.current))?;
|
|
// Size sharing is based on the first actual use of a physical font,
|
|
// including on pages where space insertion was disabled.
|
|
shipped.pdf_text_spaces = None;
|
|
prior.cache.resolve_space_probe(
|
|
std::slice::from_mut(&mut shipped), &mut prior.virtuals, files,
|
|
).map_err(|e| self.error(e, self.current))?;
|
|
plan_spaces(&shipped, &mut prior.history, || unreachable!())
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
}
|
|
prior.observed_events = self.events.len();
|
|
let mut history = prior.history.clone();
|
|
// Resource lookups and device identities remain valid as the current
|
|
// page grows. Text and first-use order restart at the page boundary.
|
|
prior.cache.resolve_space_probe(
|
|
std::slice::from_mut(&mut page), &mut prior.virtuals, files,
|
|
).map_err(|e| self.error(e, self.current))?;
|
|
let needs_dedicated = plan_spaces(&page, &mut history, || Ok(None))
|
|
.map_err(|e| self.error(e, self.current))?
|
|
.is_none();
|
|
if needs_dedicated {
|
|
let request = self.pdf_space_font.clone().unwrap_or_else(|| SpaceFontRequest {
|
|
name: "pdftexspace".into(),
|
|
from: self.source_name(self.current),
|
|
});
|
|
let defaults = self.font_defaults();
|
|
self.reads.insert(Dependency::FontResources);
|
|
let font = self.state.fonts
|
|
.load_pdf_space(files, &request.name, &request.from, defaults)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
self.pdf_loaded_space_font = Some(font);
|
|
} else {
|
|
if before_output.is_none() {
|
|
prior.history = history;
|
|
}
|
|
self.pdf_space_probe = Some(shared);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn end_native_job(&mut self, token: Token) -> Result<bool, Error> {
|
|
if !self.outer_vertical() || self.paragraph.is_some() || !self.math.is_empty() {
|
|
return self.fail("end is not allowed in an internal native mode");
|
|
}
|
|
let page = self.native_page.as_ref().unwrap();
|
|
if page.nodes.is_empty() && page.contributions.is_empty() && page.dead_cycles == 0 {
|
|
return Ok(true);
|
|
}
|
|
self.unread(token.clone().into())?;
|
|
let width = self.read_parameter(Parameter::Hsize).width();
|
|
let b = boxes::hpack(Vec::new(), PackSpec::To(width), token.span, &self.state)
|
|
.map_err(|e| self.error(e, token.span))?;
|
|
let page = self.native_page.as_mut().unwrap();
|
|
// its_all_over appends directly, without append_to_vlist/baselineskip.
|
|
page.contributions
|
|
.push_back(NativeVerticalNode::Box(Box::new(b)));
|
|
page.contributions.push_back(NativeVerticalNode::Glue(Glue {
|
|
canonical_zero: false,
|
|
stretch: Flex {
|
|
amount: 65536,
|
|
order: 2,
|
|
},
|
|
..Glue::default()
|
|
}));
|
|
page.contributions
|
|
.push_back(NativeVerticalNode::Penalty(-1_073_741_824));
|
|
page.requested = true;
|
|
Ok(false)
|
|
}
|
|
}
|