Allocate dedicated PDF spaces in the native font catalog at shipout

This commit is contained in:
gloamxun committed 2026-11-21 07:11:48 +08:00
1 parent 4bd7f1e08e
commit 584b708487
11 files changed
+339 -93

No files matched your search

@@ -208,6 +208,7 @@ pub(super) struct BoxLayout {
}
pub(super) enum GeometryItem {
Output,
Paint(crate::math_engine_tex::PositionedItem),
PdfColor,
PdfGraphics { x: i64, y: i64 },
@@ -743,7 +744,11 @@ impl NativeBox {
emit(GeometryItem::PdfTextSpace { x, y, operation });
return;
}
BoxPaint::RowStart(_) | BoxPaint::PdfLink(_, _) | BoxPaint::Output(_) => return,
BoxPaint::Output(_) => {
emit(GeometryItem::Output);
return;
}
BoxPaint::RowStart(_) | BoxPaint::PdfLink(_, _) => return,
};
if let Some(child) = &b.math_geometry {
for p in &child.items {
@@ -40,6 +40,15 @@ fn pdf_resource_entries_empty(entries: &Arc<[u8]>) -> bool {
impl NativeShipout {
pub fn display_list(&self) -> Result<crate::render::DisplayList, String> {
self.display_list_prefix(None)
}
/// Use the same packed geometry up to, but excluding, a deferred output
/// that is about to expand tokens against the live TeX state.
pub(super) fn display_list_prefix(
&self,
before_output: Option<usize>,
) -> Result<crate::render::DisplayList, String> {
let mut page = crate::render::DisplayList {
width: self.device.page_width,
height: self.device.page_height,
@@ -67,8 +76,18 @@ impl NativeShipout {
let mut invalid_geometry = false;
let mut missing_color_step = false;
let mut missing_graphics_step = false;
let mut output_index = 0;
let mut reached_boundary = false;
self.box_node.visit_geometry(|item| {
if reached_boundary {
return;
}
let p = match item {
boxes::GeometryItem::Output => {
reached_boundary = before_output == Some(output_index);
output_index += 1;
return;
}
boxes::GeometryItem::Paint(p) => p,
boxes::GeometryItem::PdfColor => {
match color_steps.next() {
@@ -141,6 +160,9 @@ impl NativeShipout {
}
});
})?;
if before_output.is_some() && !reached_boundary {
return Err("missing deferred output boundary in its packed list".into());
}
if invalid_geometry {
return Err("native shipout requires actual native glyph resources".into());
}
@@ -221,6 +221,8 @@ pub struct Executor {
pdf_running_links: bool,
pdf_interword_spaces: bool,
pdf_space_font: Option<crate::pdf_device::text_spaces::SpaceFontRequest>,
pdf_loaded_space_font: Option<Arc<crate::native_font::NativeFont>>,
pdf_space_probe: Option<Arc<page::PdfSpaceProbe>>,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
pdf_catalog_tokens: Vec<Token>,
@@ -387,6 +389,8 @@ impl Executor {
pdf_running_links: true,
pdf_interword_spaces: false,
pdf_space_font: None,
pdf_loaded_space_font: None,
pdf_space_probe: None,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: None,
pdf_catalog_tokens: Vec::new(),
@@ -24,6 +24,16 @@ impl OutputFrame {
}
}
}
/// 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,
}
impl Executor {
pub(super) fn outer_vertical(&self) -> bool {
self.box_frames.is_empty() && self.output_frame.is_none() && self.alignments.is_empty()
@@ -281,8 +291,19 @@ impl Executor {
} else {
Vec::new()
};
let mut pdf_color_steps = Vec::new();
let mut pdf_graphics_steps = Vec::new();
let mut shipout = NativeShipout {
box_node: b,
device,
pdf_color_start,
pdf_color_steps: Vec::new(),
pdf_graphics_steps: 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 outputs, has_leaders) = b.output_nodes();
let leader_effects = if has_leaders {
@@ -311,12 +332,25 @@ impl Executor {
} else {
Vec::new().into_iter()
};
use crate::pdf_device::text_spaces::{SpaceFontRequest, SpaceOperation, SpaceSettings};
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 output in outputs {
for (index, output) in outputs.into_iter().enumerate() {
if self.pdf_loaded_space_font.is_none()
&& (uses_automatic_spaces || has_explicit_space)
&& matches!(
output.operation,
OutputOperation::Write { .. } | OutputOperation::PdfLiteral { shipout: true, .. }
)
{
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)
@@ -335,12 +369,12 @@ impl Executor {
if device.pdf.is_none() {
return self.fail("cannot ship a PDF color operation to DVI");
}
pdf_color_steps.push(self.ship_pdf_color(*stack, action, output.span, files)?);
shipout.pdf_color_steps.push(self.ship_pdf_color(*stack, action, output.span, files)?);
} else if output.is_pdf_graphics() {
if device.pdf.is_none() {
return self.fail("cannot ship a PDF graphics operation to DVI");
}
pdf_graphics_steps.push(self.ship_pdf_graphics(
shipout.pdf_graphics_steps.push(self.ship_pdf_graphics(
output,
position.expect("PDF graphics need a shipout position"),
&mut graphics_stack,
@@ -378,6 +412,8 @@ impl Executor {
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;
@@ -413,52 +449,118 @@ impl Executor {
*span,
));
}
self.current = current;
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)?;
}
let pdf_links = if has_link_material {
self.ship_pdf_link_material(&b, &device, &pdf_graphics_steps, files)?
} else {
Default::default()
};
let pdf_text_spaces = (has_space_nodes || automatic_spaces_at_start).then(|| {
let parameters = if uses_automatic_spaces {
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: automatic_spaces_at_start,
font: self.pdf_space_font.clone().unwrap_or_else(|| SpaceFontRequest {
name: "pdftexspace".into(),
from: self.source_name(current),
}),
parameters,
}
});
if has_link_material {
shipout.pdf_links = self.ship_pdf_link_material(
b, device, &shipout.pdf_graphics_steps, files,
)?;
}
self.current = current;
self.native_page.as_mut().unwrap().dead_cycles = 0;
let before = self.statistics_before_shipout(&b, files)?;
let before = self.statistics_before_shipout(&shipout.box_node, files)?;
self.shipped_pages += 1;
self.events.push(Event::Shipout(Box::new(NativeShipout {
box_node: b,
device,
pdf_color_start,
pdf_color_steps,
pdf_graphics_steps,
pdf_text_spaces,
pdf_resource_entries,
pdf_page_attributes,
pdf_links,
})));
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 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");
@@ -292,6 +292,35 @@ impl FontCatalog {
self.insert_font((name, area), loaded, metrics, selector, defaults, None)
}
/// The PDF device reads a new design-size font directly, as opposed to
/// an explicit font definition which may reuse an existing instance.
pub(super) fn load_pdf_space(
&mut self,
files: &mut impl SourceProvider,
filename: &str,
from: &str,
defaults: FontIntegers,
) -> Result<Arc<NativeFont>, String> {
self.check_font_capacity()?;
let (area, name) = filename
.rsplit_once('/')
.map_or(("", filename), |(area, name)| (&filename[..area.len() + 1], name));
let name = name.strip_suffix(".tfm").unwrap_or(name);
let (loaded, metrics) =
Self::read_tfm(files, &format!("{area}{name}.tfm"), from, FontSize::Design)?;
let id = self.insert_font(
(name, area),
loaded,
metrics,
CommandName::Control(String::new()),
defaults,
None,
)?;
let font = self.fonts[id.index() as usize].glyph_font.as_mut().unwrap();
Arc::make_mut(font).pdf_space_font = true;
Ok(font.clone())
}
pub(super) fn letterspace(
&mut self,
files: &mut impl SourceProvider,
@@ -391,6 +420,7 @@ impl FontCatalog {
resource: self.resources[resource].clone(),
expansion: 0,
letter_spacing,
pdf_space_font: false,
});
self.fonts.push(FontInstance {
name: name.into(),