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
+331 -85

No files matched your search

@@ -208,6 +208,7 @@ pub(super) struct BoxLayout {
} }
pub(super) enum GeometryItem { pub(super) enum GeometryItem {
Output,
Paint(crate::math_engine_tex::PositionedItem), Paint(crate::math_engine_tex::PositionedItem),
PdfColor, PdfColor,
PdfGraphics { x: i64, y: i64 }, PdfGraphics { x: i64, y: i64 },
@@ -743,7 +744,11 @@ impl NativeBox {
emit(GeometryItem::PdfTextSpace { x, y, operation }); emit(GeometryItem::PdfTextSpace { x, y, operation });
return; 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 { if let Some(child) = &b.math_geometry {
for p in &child.items { for p in &child.items {
@@ -40,6 +40,15 @@ fn pdf_resource_entries_empty(entries: &Arc<[u8]>) -> bool {
impl NativeShipout { impl NativeShipout {
pub fn display_list(&self) -> Result<crate::render::DisplayList, String> { 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 { let mut page = crate::render::DisplayList {
width: self.device.page_width, width: self.device.page_width,
height: self.device.page_height, height: self.device.page_height,
@@ -67,8 +76,18 @@ impl NativeShipout {
let mut invalid_geometry = false; let mut invalid_geometry = false;
let mut missing_color_step = false; let mut missing_color_step = false;
let mut missing_graphics_step = false; let mut missing_graphics_step = false;
let mut output_index = 0;
let mut reached_boundary = false;
self.box_node.visit_geometry(|item| { self.box_node.visit_geometry(|item| {
if reached_boundary {
return;
}
let p = match item { 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::Paint(p) => p,
boxes::GeometryItem::PdfColor => { boxes::GeometryItem::PdfColor => {
match color_steps.next() { 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 { if invalid_geometry {
return Err("native shipout requires actual native glyph resources".into()); return Err("native shipout requires actual native glyph resources".into());
} }
@@ -221,6 +221,8 @@ pub struct Executor {
pdf_running_links: bool, pdf_running_links: bool,
pdf_interword_spaces: bool, pdf_interword_spaces: bool,
pdf_space_font: Option<crate::pdf_device::text_spaces::SpaceFontRequest>, 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"))] #[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>, pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
pdf_catalog_tokens: Vec<Token>, pdf_catalog_tokens: Vec<Token>,
@@ -387,6 +389,8 @@ impl Executor {
pdf_running_links: true, pdf_running_links: true,
pdf_interword_spaces: false, pdf_interword_spaces: false,
pdf_space_font: None, pdf_space_font: None,
pdf_loaded_space_font: None,
pdf_space_probe: None,
#[cfg(all(target_os = "linux", target_env = "gnu"))] #[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: None, pdf_last_match: None,
pdf_catalog_tokens: Vec::new(), 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 { impl Executor {
pub(super) fn outer_vertical(&self) -> bool { pub(super) fn outer_vertical(&self) -> bool {
self.box_frames.is_empty() && self.output_frame.is_none() && self.alignments.is_empty() self.box_frames.is_empty() && self.output_frame.is_none() && self.alignments.is_empty()
@@ -281,8 +291,19 @@ impl Executor {
} else { } else {
Vec::new() Vec::new()
}; };
let mut pdf_color_steps = Vec::new(); let mut shipout = NativeShipout {
let mut pdf_graphics_steps = Vec::new(); 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 graphics_stack = Vec::new();
let (mut outputs, has_leaders) = b.output_nodes(); let (mut outputs, has_leaders) = b.output_nodes();
let leader_effects = if has_leaders { let leader_effects = if has_leaders {
@@ -311,12 +332,25 @@ impl Executor {
} else { } else {
Vec::new().into_iter() 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 automatic_spaces_at_start = self.pdf_interword_spaces;
let mut uses_automatic_spaces = automatic_spaces_at_start; let mut uses_automatic_spaces = automatic_spaces_at_start;
let mut has_space_nodes = false; let mut has_space_nodes = false;
let mut has_explicit_space = false;
let mut pdf_objects = Vec::new(); 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() { let position = if output.needs_shipout_position() {
Some(output_positions.next().ok_or_else(|| { Some(output_positions.next().ok_or_else(|| {
self.error("missing positioned native output node", output.span) self.error("missing positioned native output node", output.span)
@@ -335,12 +369,12 @@ impl Executor {
if device.pdf.is_none() { if device.pdf.is_none() {
return self.fail("cannot ship a PDF color operation to DVI"); 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() { } else if output.is_pdf_graphics() {
if device.pdf.is_none() { if device.pdf.is_none() {
return self.fail("cannot ship a PDF graphics operation to DVI"); 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, output,
position.expect("PDF graphics need a shipout position"), position.expect("PDF graphics need a shipout position"),
&mut graphics_stack, &mut graphics_stack,
@@ -378,6 +412,8 @@ impl Executor {
if let SpaceOperation::Automatic(enabled) = operation { if let SpaceOperation::Automatic(enabled) = operation {
self.pdf_interword_spaces = enabled; self.pdf_interword_spaces = enabled;
uses_automatic_spaces |= enabled; uses_automatic_spaces |= enabled;
} else {
has_explicit_space = true;
} }
} else if let OutputOperation::PdfLink(link) = &output.operation { } else if let OutputOperation::PdfLink(link) = &output.operation {
use crate::pdf_device::links::LinkNode; use crate::pdf_device::links::LinkNode;
@@ -413,17 +449,47 @@ impl Executor {
*span, *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 { for (number, span) in pdf_objects {
self.current = span; self.current = span;
self.write_pdf_object(number, files)?; self.write_pdf_object(number, files)?;
} }
let pdf_links = if has_link_material { if has_link_material {
self.ship_pdf_link_material(&b, &device, &pdf_graphics_steps, files)? shipout.pdf_links = self.ship_pdf_link_material(
} else { b, device, &shipout.pdf_graphics_steps, files,
Default::default() )?;
}; }
let pdf_text_spaces = (has_space_nodes || automatic_spaces_at_start).then(|| { self.current = current;
let parameters = if uses_automatic_spaces { 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.reads.insert(Dependency::FontResources);
self.state.fonts.fonts().iter().map(|font| { self.state.fonts.fonts().iter().map(|font| {
let glue = font.space(); let glue = font.space();
@@ -433,32 +499,68 @@ impl Executor {
Vec::new() Vec::new()
}; };
SpaceSettings { SpaceSettings {
automatic_at_start: automatic_spaces_at_start, automatic_at_start,
font: self.pdf_space_font.clone().unwrap_or_else(|| SpaceFontRequest { dedicated_font: self.pdf_loaded_space_font.clone(),
name: "pdftexspace".into(),
from: self.source_name(current),
}),
parameters, 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),
}); });
self.current = current; let defaults = self.font_defaults();
self.native_page.as_mut().unwrap().dead_cycles = 0; self.reads.insert(Dependency::FontResources);
let before = self.statistics_before_shipout(&b, files)?; let font = self.state.fonts
self.shipped_pages += 1; .load_pdf_space(files, &request.name, &request.from, defaults)
self.events.push(Event::Shipout(Box::new(NativeShipout { .map_err(|e| self.error(e, self.current))?;
box_node: b, self.pdf_loaded_space_font = Some(font);
device, } else {
pdf_color_start, if before_output.is_none() {
pdf_color_steps, prior.history = history;
pdf_graphics_steps, }
pdf_text_spaces, self.pdf_space_probe = Some(shared);
pdf_resource_entries, }
pdf_page_attributes,
pdf_links,
})));
self.statistics_after_shipout(before, files)?;
Ok(()) Ok(())
} }
pub(super) fn end_native_job(&mut self, token: Token) -> Result<bool, Error> { 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() { if !self.outer_vertical() || self.paragraph.is_some() || !self.math.is_empty() {
return self.fail("end is not allowed in an internal native mode"); 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) 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( pub(super) fn letterspace(
&mut self, &mut self,
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
@@ -391,6 +420,7 @@ impl FontCatalog {
resource: self.resources[resource].clone(), resource: self.resources[resource].clone(),
expansion: 0, expansion: 0,
letter_spacing, letter_spacing,
pdf_space_font: false,
}); });
self.fonts.push(FontInstance { self.fonts.push(FontInstance {
name: name.into(), name: name.into(),
+22 -18
View File
@@ -13,6 +13,7 @@ use std::{
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
mod virtual_paint; mod virtual_paint;
pub(crate) use virtual_paint::VirtualPaintState;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct NativeFontPaint { pub struct NativeFontPaint {
@@ -69,6 +70,8 @@ pub struct NativeFont {
pub expansion: i32, pub expansion: i32,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub letter_spacing: Option<LetterspaceProgram>, pub letter_spacing: Option<LetterspaceProgram>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub(crate) pdf_space_font: bool,
} }
/// Virtual character packets use the selected font and an encoded right move. /// Virtual character packets use the selected font and an encoded right move.
@@ -233,7 +236,6 @@ fn verify_resource(
Ok(resource) Ok(resource)
} }
const SPACE_FONT_ID: u32 = u32::MAX;
const MAX_TYPE1_PROGRAMS: usize = 16; const MAX_TYPE1_PROGRAMS: usize = 16;
const MAX_CACHED_PFB_BYTES: usize = 256 * 1024; const MAX_CACHED_PFB_BYTES: usize = 256 * 1024;
@@ -301,7 +303,8 @@ impl NativeFontCache {
pages: &mut [crate::render::DisplayList], pages: &mut [crate::render::DisplayList],
files: &mut impl crate::execution::SourceProvider, files: &mut impl crate::execution::SourceProvider,
) -> Result<(), String> { ) -> Result<(), String> {
let expanded = virtual_paint::expand_pages(pages, files)?; let mut virtuals = virtual_paint::VirtualPaintState::default();
let expanded = virtual_paint::expand_pages(&mut virtuals, pages, files)?;
if expanded.is_none() && !pages.iter().any(|page| page.pdf_text_spaces.is_some()) { if expanded.is_none() && !pages.iter().any(|page| page.pdf_text_spaces.is_some()) {
return resolve_physical_fonts(pages, files, self); return resolve_physical_fonts(pages, files, self);
} }
@@ -316,27 +319,28 @@ impl NativeFontCache {
Ok(()) Ok(())
} }
fn space_font( pub(crate) fn resolve_space_probe(
&self, &self,
request: &crate::pdf_device::text_spaces::SpaceFontRequest, pages: &mut [crate::render::DisplayList],
virtuals: &mut VirtualPaintState,
files: &mut impl crate::execution::SourceProvider,
) -> Result<(), String> {
if let Some(expanded) = virtual_paint::expand_pages(virtuals, pages, files)? {
for (original, expanded) in pages.iter_mut().zip(expanded) {
*original = expanded;
}
}
resolve_physical_fonts(pages, files, self)
}
pub(crate) fn space_font(
&self,
font: Arc<NativeFont>,
device: Option<crate::pdf_device::PdfPageData>, device: Option<crate::pdf_device::PdfPageData>,
files: &mut impl crate::execution::SourceProvider, files: &mut impl crate::execution::SourceProvider,
) -> Result<crate::pdf_device::text_spaces::ResolvedSpaceFont, String> { ) -> Result<crate::pdf_device::text_spaces::ResolvedSpaceFont, String> {
use crate::execution::{CommandName, FontCatalog, FontIntegers};
use crate::pdf_device::text_spaces::ResolvedSpaceFont; use crate::pdf_device::text_spaces::ResolvedSpaceFont;
use crate::render::{DisplayItem, DisplayList, DisplayUnits}; use crate::render::{DisplayItem, DisplayList, DisplayUnits};
let mut catalog = FontCatalog::default();
let id = catalog.load(
files,
&request.name,
&request.from,
crate::tfm::FontSize::Design,
CommandName::Control(String::new()),
FontIntegers { hyphen: 45, skew: -1 },
)?;
let mut font = (**catalog.glyph_font(id)?).clone();
font.id = FontId::for_device(SPACE_FONT_ID);
let font = Arc::new(font);
let mut page = DisplayList { let mut page = DisplayList {
units: DisplayUnits::TeX, units: DisplayUnits::TeX,
pdf: device, pdf: device,
@@ -406,7 +410,7 @@ fn resolve_physical_fonts(
.map(|p| p.file.clone()); .map(|p| p.file.clone());
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new(); let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
for (id, (font, slots)) in used { for (id, (font, slots)) in used {
let entry = if id.index() == SPACE_FONT_ID && font.name == "pdftexspace" { let entry = if font.pdf_space_font && font.name == "pdftexspace" {
// The pdfTeX device adds its own map entry on first use. // The pdfTeX device adds its own map entry on first use.
Some(MapEntry { file: "pdftexspace.pfb".into(), encoding: None }) Some(MapEntry { file: "pdftexspace.pfb".into(), encoding: None })
} else { } else {
@@ -14,12 +14,28 @@ struct LoadedVirtual {
program: VirtualFont, program: VirtualFont,
} }
struct Expansion<'a, F> { #[derive(Clone)]
files: &'a mut F, pub(crate) struct VirtualPaintState {
virtuals: BTreeMap<FontId, (Arc<NativeFont>, Option<Arc<LoadedVirtual>>)>, virtuals: BTreeMap<FontId, (Arc<NativeFont>, Option<Arc<LoadedVirtual>>)>,
local_fonts: BTreeMap<(String, String, i64), Arc<NativeFont>>, local_fonts: BTreeMap<(String, String, i64), Arc<NativeFont>>,
expanded_fonts: BTreeMap<(FontId, i32), Arc<NativeFont>>, expanded_fonts: BTreeMap<(FontId, i32), Arc<NativeFont>>,
last_id: u32, last_id: u32,
}
impl Default for VirtualPaintState {
fn default() -> Self {
Self {
virtuals: BTreeMap::new(),
local_fonts: BTreeMap::new(),
expanded_fonts: BTreeMap::new(),
last_id: 0x7fff_ffff,
}
}
}
struct Expansion<'a, F> {
files: &'a mut F,
state: &'a mut VirtualPaintState,
commands: usize, commands: usize,
} }
@@ -53,7 +69,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
if ratio == 0 { if ratio == 0 {
return font; return font;
} }
self.expanded_fonts self.state.expanded_fonts
.entry((font.id, ratio)) .entry((font.id, ratio))
.or_insert_with(|| { .or_insert_with(|| {
Arc::new(NativeFont { Arc::new(NativeFont {
@@ -73,7 +89,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
} }
fn lookup(&mut self, font: &Arc<NativeFont>) -> Result<Option<Arc<LoadedVirtual>>, String> { fn lookup(&mut self, font: &Arc<NativeFont>) -> Result<Option<Arc<LoadedVirtual>>, String> {
if let Some((old, vf)) = self.virtuals.get(&font.id) { if let Some((old, vf)) = self.state.virtuals.get(&font.id) {
if !Arc::ptr_eq(old, font) && !old.same_base(font) { if !Arc::ptr_eq(old, font) && !old.same_base(font) {
return Err("native font ids from different jobs cannot share output".into()); return Err("native font ids from different jobs cannot share output".into());
} }
@@ -100,7 +116,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
} else { } else {
None None
}; };
self.virtuals.insert(font.id, (font.clone(), vf.clone())); self.state.virtuals.insert(font.id, (font.clone(), vf.clone()));
Ok(vf) Ok(vf)
} }
@@ -112,7 +128,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
) -> Result<Arc<NativeFont>, String> { ) -> Result<Arc<NativeFont>, String> {
let size = TfmMetrics::scale_fix_word(local.scale, size)?; let size = TfmMetrics::scale_fix_word(local.scale, size)?;
let key = (from.to_owned(), local.name.clone(), size); let key = (from.to_owned(), local.name.clone(), size);
if let Some(font) = self.local_fonts.get(&key) { if let Some(font) = self.state.local_fonts.get(&key) {
check_metrics( check_metrics(
&font.metrics, &font.metrics,
local.checksum, local.checksum,
@@ -125,22 +141,24 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
let file = actual_resource(self.files, ResourceKind::Tfm, &name, from)?; let file = actual_resource(self.files, ResourceKind::Tfm, &name, from)?;
let metrics = TfmMetrics::parse_at(&file.data, FontSize::At(size))?; let metrics = TfmMetrics::parse_at(&file.data, FontSize::At(size))?;
check_metrics(&metrics, local.checksum, local.design_size, &name)?; check_metrics(&metrics, local.checksum, local.design_size, &name)?;
self.last_id = self self.state.last_id = self
.state
.last_id .last_id
.checked_add(1) .checked_add(1)
.ok_or("native device font capacity exceeded")?; .ok_or("native device font capacity exceeded")?;
let font = Arc::new(NativeFont { let font = Arc::new(NativeFont {
id: FontId::for_device(self.last_id), id: FontId::for_device(self.state.last_id),
name: local.name.clone(), name: local.name.clone(),
metrics: Arc::new(metrics), metrics: Arc::new(metrics),
expansion: 0, expansion: 0,
letter_spacing: None, letter_spacing: None,
pdf_space_font: false,
resource: FontResource { resource: FontResource {
version: file.version, version: file.version,
data: Arc::new(file.data), data: Arc::new(file.data),
}, },
}); });
self.local_fonts.insert(key, font.clone()); self.state.local_fonts.insert(key, font.clone());
Ok(font) Ok(font)
} }
@@ -301,22 +319,19 @@ fn check_metrics(
} }
pub(super) fn expand_pages( pub(super) fn expand_pages(
state: &mut VirtualPaintState,
pages: &[DisplayList], pages: &[DisplayList],
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
) -> Result<Option<Vec<DisplayList>>, String> { ) -> Result<Option<Vec<DisplayList>>, String> {
let mut expansion = Expansion { let mut expansion = Expansion {
files, files,
virtuals: BTreeMap::new(), state,
local_fonts: BTreeMap::new(),
expanded_fonts: BTreeMap::new(),
last_id: 0x7fff_ffff,
commands: 0, commands: 0,
}; };
let mut uses_vf = false; let mut uses_vf = false;
for page in pages { for page in pages {
for item in &page.items { for item in &page.items {
if let DisplayItem::NativeGlyph { font, .. } = item { if let DisplayItem::NativeGlyph { font, .. } = item {
expansion.last_id = expansion.last_id.max(font.id.index());
uses_vf |= expansion.is_virtual(font)?; uses_vf |= expansion.is_virtual(font)?;
} }
} }
+9 -7
View File
@@ -20,7 +20,7 @@ use crate::pdf_device::{
use crate::render::{DisplayItem, DisplayList, FontFace}; use crate::render::{DisplayItem, DisplayList, FontFace};
use crate::type1::Type1Font; use crate::type1::Type1Font;
#[path = "pdf_text.rs"] #[path = "pdf_text.rs"]
mod native_text; pub(crate) mod native_text;
#[path = "pdf_objects.rs"] #[path = "pdf_objects.rs"]
pub(crate) mod objects; pub(crate) mod objects;
#[path = "pdf_pk.rs"] #[path = "pdf_pk.rs"]
@@ -648,7 +648,7 @@ impl PageContent {
pub(crate) fn prepare_text_spaces( pub(crate) fn prepare_text_spaces(
pages: &mut [DisplayList], pages: &mut [DisplayList],
mut resolve: impl FnMut( mut resolve: impl FnMut(
&crate::pdf_device::text_spaces::SpaceFontRequest, std::sync::Arc<crate::native_font::NativeFont>,
Option<crate::pdf_device::PdfPageData>, Option<crate::pdf_device::PdfPageData>,
) -> Result<crate::pdf_device::text_spaces::ResolvedSpaceFont, String>, ) -> Result<crate::pdf_device::text_spaces::ResolvedSpaceFont, String>,
) -> Result<(), String> { ) -> Result<(), String> {
@@ -660,13 +660,15 @@ pub(crate) fn prepare_text_spaces(
for page in pages { for page in pages {
let plan = native_text::plan_spaces(page, &mut fonts, || { let plan = native_text::plan_spaces(page, &mut fonts, || {
if let Some(font) = &selected { if let Some(font) = &selected {
return Ok(crate::pdf_device::text_spaces::ResolvedSpaceFont::clone(font)); return Ok(Some(crate::pdf_device::text_spaces::ResolvedSpaceFont::clone(font)));
} }
let request = &page.pdf_text_spaces.as_ref().expect("space settings for shipped node").font; let font = page.pdf_text_spaces.as_ref()
let font = resolve(request, page.pdf.clone())?; .and_then(|settings| settings.dedicated_font.clone())
.ok_or("PDF space planner requires the font selected during shipout")?;
let font = resolve(font, page.pdf.clone())?;
selected = Some(font.clone()); selected = Some(font.clone());
Ok(font) Ok(Some(font))
})?; })?.expect("PDF export always resolves the selected space font");
if page.pdf_text_spaces.is_some() { if page.pdf_text_spaces.is_some() {
page.pdf_resources.needs_pdf_for_preview |= plan.spaces_in_previous_font page.pdf_resources.needs_pdf_for_preview |= plan.spaces_in_previous_font
|| plan.dedicated.as_ref() || plan.dedicated.as_ref()
@@ -28,7 +28,8 @@ impl SpaceOperation {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpaceSettings { pub struct SpaceSettings {
pub(crate) automatic_at_start: bool, pub(crate) automatic_at_start: bool,
pub(crate) font: SpaceFontRequest, #[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) dedicated_font: Option<Arc<NativeFont>>,
pub(crate) parameters: Vec<(i32, i32)>, pub(crate) parameters: Vec<(i32, i32)>,
} }
+16 -10
View File
@@ -210,8 +210,8 @@ impl NativeText {
} }
} }
#[derive(Default)] #[derive(Clone, Default)]
pub(super) struct FontHistory { pub(crate) struct FontHistory {
used: BTreeSet<FontId>, used: BTreeSet<FontId>,
first_scalable: BTreeMap<String, FontId>, first_scalable: BTreeMap<String, FontId>,
} }
@@ -239,11 +239,12 @@ impl FontHistory {
} }
/// Determine real font use with the same text moves used by the PDF writer. /// Determine real font use with the same text moves used by the PDF writer.
pub(super) fn plan_spaces( /// A probe returns None as soon as it would first load the dedicated font.
pub(crate) fn plan_spaces(
page: &DisplayList, page: &DisplayList,
fonts: &mut FontHistory, fonts: &mut FontHistory,
load: impl FnOnce() -> Result<ResolvedSpaceFont, String>, load: impl FnOnce() -> Result<Option<ResolvedSpaceFont>, String>,
) -> Result<SpacePlan, String> { ) -> Result<Option<SpacePlan>, String> {
let Some(settings) = &page.pdf_text_spaces else { let Some(settings) = &page.pdf_text_spaces else {
for item in &page.items { for item in &page.items {
if let DisplayItem::NativeGlyph { if let DisplayItem::NativeGlyph {
@@ -255,7 +256,7 @@ pub(super) fn plan_spaces(
fonts.record(font, paint); fonts.record(font, paint);
} }
} }
return Ok(SpacePlan::default()); return Ok(Some(SpacePlan::default()));
}; };
let digits = page.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits); let digits = page.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits);
let mut automatic = settings.automatic_at_start; let mut automatic = settings.automatic_at_start;
@@ -277,7 +278,10 @@ pub(super) fn plan_spaces(
operation: SpaceOperation::Explicit, operation: SpaceOperation::Explicit,
} => { } => {
if plan.dedicated.is_none() { if plan.dedicated.is_none() {
plan.dedicated = Some(load.take().expect("space font loader used once")()?); let Some(font) = load.take().expect("space font loader used once")()? else {
return Ok(None);
};
plan.dedicated = Some(font);
} }
let dedicated = plan.dedicated.as_ref().unwrap(); let dedicated = plan.dedicated.as_ref().unwrap();
fonts.record(&dedicated.font, &dedicated.paint); fonts.record(&dedicated.font, &dedicated.paint);
@@ -342,8 +346,10 @@ pub(super) fn plan_spaces(
} else { } else {
space = Some(SpaceUse::Dedicated); space = Some(SpaceUse::Dedicated);
if plan.dedicated.is_none() { if plan.dedicated.is_none() {
plan.dedicated = let Some(font) = load.take().expect("space font loader used once")()? else {
Some(load.take().expect("space font loader used once")()?); return Ok(None);
};
plan.dedicated = Some(font);
} }
let dedicated = plan.dedicated.as_ref().unwrap(); let dedicated = plan.dedicated.as_ref().unwrap();
fonts.record(&dedicated.font, &dedicated.paint); fonts.record(&dedicated.font, &dedicated.paint);
@@ -380,7 +386,7 @@ pub(super) fn plan_spaces(
_ => NativeText::finish(&mut text, &mut out), _ => NativeText::finish(&mut text, &mut out),
} }
} }
Ok(plan) Ok(Some(plan))
} }
pub(super) fn rule( pub(super) fn rule(
+55
View File
@@ -239,3 +239,58 @@ fn saved_pdf_position_is_observed_in_shipout_order() {
); );
fs::remove_dir_all(work).unwrap(); fs::remove_dir_all(work).unwrap();
} }
#[test]
fn shipped_pdf_spaces_take_a_real_font_slot_in_output_order() {
let work = directory();
let space_tfm = Command::new("kpsewhich")
.arg("pdftexspace.tfm")
.output()
.unwrap();
assert!(space_tfm.status.success());
let space_tfm = String::from_utf8(space_tfm.stdout).unwrap();
let assets = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("crates/texrra-tex-core/assets");
let tfm_paths = std::env::join_paths([
assets.as_path(),
std::path::Path::new(space_tfm.trim()).parent().unwrap(),
])
.unwrap();
for (name, movement, succeeds) in [
("short", r"\kern1pt", true),
("automatic", r"\kern5pt", false),
("explicit", r"\pdffakespace", false),
] {
let path = work.join(format!("{name}.tex"));
let source = format!(
r"\catcode123=1 \catcode125=2
\pdfoutput=1 \font\roman=cmr10
\shipout\hbox{{\pdfinterwordspaceon\roman A%
\write16{{BEFORE=\the\fontdimen8\roman}}{movement} B%
\write16{{AFTER=\the\fontdimen9\roman}}}}
\end"
);
fs::write(&path, source).unwrap();
let pdf = work.join(format!("{name}.pdf"));
let output = native_fonts::command()
.args(["native", "--job", "--initex", "--etex"])
.env("TFMFONTS", &tfm_paths)
.arg(&path)
.arg(&pdf)
.current_dir(&work)
.output()
.unwrap();
let terminal = String::from_utf8_lossy(&output.stdout);
let error = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.success(), succeeds, "{name}: {terminal}\n{error}");
let log = fs::read_to_string(pdf.with_extension("log")).unwrap();
assert!(log.lines().any(|line| line == "BEFORE=0.0pt"), "{log}");
if succeeds {
assert!(log.lines().any(|line| line == "AFTER=0.0pt"), "{log}");
assert!(fs::read(&pdf).unwrap().starts_with(b"%PDF-"));
} else {
assert!(error.contains("font has 8 parameters"), "{name}: {error}");
assert!(!pdf.exists(), "{name}: incomplete job published a PDF");
}
}
fs::remove_dir_all(work).unwrap();
}