diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index d252d75..9c2a6ee 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -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 { diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 4e60cb0..9b203a4 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -40,6 +40,15 @@ fn pdf_resource_entries_empty(entries: &Arc<[u8]>) -> bool { impl NativeShipout { pub fn display_list(&self) -> Result { + 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, + ) -> Result { 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()); } diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 5880235..90a9ae4 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -221,6 +221,8 @@ pub struct Executor { pdf_running_links: bool, pdf_interword_spaces: bool, pdf_space_font: Option, + pdf_loaded_space_font: Option>, + pdf_space_probe: Option>, #[cfg(all(target_os = "linux", target_env = "gnu"))] pdf_last_match: Option>, pdf_catalog_tokens: Vec, @@ -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(), diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index fcff8e2..b9691b9 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -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, + 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, + 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 { if !self.outer_vertical() || self.paragraph.is_some() || !self.math.is_empty() { return self.fail("end is not allowed in an internal native mode"); diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index ce35032..af7ac95 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -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, 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(), diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index 710e7ca..ad5c2d7 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -13,6 +13,7 @@ use std::{ sync::{Arc, Mutex}, }; mod virtual_paint; +pub(crate) use virtual_paint::VirtualPaintState; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct NativeFontPaint { @@ -69,6 +70,8 @@ pub struct NativeFont { pub expansion: i32, #[serde(default, skip_serializing_if = "Option::is_none")] pub letter_spacing: Option, + #[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. @@ -233,7 +236,6 @@ fn verify_resource( Ok(resource) } -const SPACE_FONT_ID: u32 = u32::MAX; const MAX_TYPE1_PROGRAMS: usize = 16; const MAX_CACHED_PFB_BYTES: usize = 256 * 1024; @@ -301,7 +303,8 @@ impl NativeFontCache { pages: &mut [crate::render::DisplayList], files: &mut impl crate::execution::SourceProvider, ) -> 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()) { return resolve_physical_fonts(pages, files, self); } @@ -316,27 +319,28 @@ impl NativeFontCache { Ok(()) } - fn space_font( + pub(crate) fn resolve_space_probe( &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, device: Option, files: &mut impl crate::execution::SourceProvider, ) -> Result { - use crate::execution::{CommandName, FontCatalog, FontIntegers}; use crate::pdf_device::text_spaces::ResolvedSpaceFont; 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 { units: DisplayUnits::TeX, pdf: device, @@ -406,7 +410,7 @@ fn resolve_physical_fonts( .map(|p| p.file.clone()); let mut cache: BTreeMap<_, (NativeFontPaint, Arc)> = BTreeMap::new(); 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. Some(MapEntry { file: "pdftexspace.pfb".into(), encoding: None }) } else { diff --git a/crates/texrra-tex-core/src/native_font/virtual_paint.rs b/crates/texrra-tex-core/src/native_font/virtual_paint.rs index 51ffd78..e50ea20 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -14,12 +14,28 @@ struct LoadedVirtual { program: VirtualFont, } -struct Expansion<'a, F> { - files: &'a mut F, +#[derive(Clone)] +pub(crate) struct VirtualPaintState { virtuals: BTreeMap, Option>)>, local_fonts: BTreeMap<(String, String, i64), Arc>, expanded_fonts: BTreeMap<(FontId, i32), Arc>, 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, } @@ -53,7 +69,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { if ratio == 0 { return font; } - self.expanded_fonts + self.state.expanded_fonts .entry((font.id, ratio)) .or_insert_with(|| { Arc::new(NativeFont { @@ -73,7 +89,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { } fn lookup(&mut self, font: &Arc) -> Result>, 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) { return Err("native font ids from different jobs cannot share output".into()); } @@ -100,7 +116,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { } else { None }; - self.virtuals.insert(font.id, (font.clone(), vf.clone())); + self.state.virtuals.insert(font.id, (font.clone(), vf.clone())); Ok(vf) } @@ -112,7 +128,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { ) -> Result, String> { let size = TfmMetrics::scale_fix_word(local.scale, 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( &font.metrics, local.checksum, @@ -125,22 +141,24 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { let file = actual_resource(self.files, ResourceKind::Tfm, &name, from)?; let metrics = TfmMetrics::parse_at(&file.data, FontSize::At(size))?; check_metrics(&metrics, local.checksum, local.design_size, &name)?; - self.last_id = self + self.state.last_id = self + .state .last_id .checked_add(1) .ok_or("native device font capacity exceeded")?; let font = Arc::new(NativeFont { - id: FontId::for_device(self.last_id), + id: FontId::for_device(self.state.last_id), name: local.name.clone(), metrics: Arc::new(metrics), expansion: 0, letter_spacing: None, + pdf_space_font: false, resource: FontResource { version: file.version, data: Arc::new(file.data), }, }); - self.local_fonts.insert(key, font.clone()); + self.state.local_fonts.insert(key, font.clone()); Ok(font) } @@ -301,22 +319,19 @@ fn check_metrics( } pub(super) fn expand_pages( + state: &mut VirtualPaintState, pages: &[DisplayList], files: &mut impl SourceProvider, ) -> Result>, String> { let mut expansion = Expansion { files, - virtuals: BTreeMap::new(), - local_fonts: BTreeMap::new(), - expanded_fonts: BTreeMap::new(), - last_id: 0x7fff_ffff, + state, commands: 0, }; let mut uses_vf = false; for page in pages { for item in &page.items { if let DisplayItem::NativeGlyph { font, .. } = item { - expansion.last_id = expansion.last_id.max(font.id.index()); uses_vf |= expansion.is_virtual(font)?; } } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 3bacf4b..6d7d805 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -20,7 +20,7 @@ use crate::pdf_device::{ use crate::render::{DisplayItem, DisplayList, FontFace}; use crate::type1::Type1Font; #[path = "pdf_text.rs"] -mod native_text; +pub(crate) mod native_text; #[path = "pdf_objects.rs"] pub(crate) mod objects; #[path = "pdf_pk.rs"] @@ -648,7 +648,7 @@ impl PageContent { pub(crate) fn prepare_text_spaces( pages: &mut [DisplayList], mut resolve: impl FnMut( - &crate::pdf_device::text_spaces::SpaceFontRequest, + std::sync::Arc, Option, ) -> Result, ) -> Result<(), String> { @@ -660,13 +660,15 @@ pub(crate) fn prepare_text_spaces( for page in pages { let plan = native_text::plan_spaces(page, &mut fonts, || { 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 = resolve(request, page.pdf.clone())?; + let font = page.pdf_text_spaces.as_ref() + .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()); - Ok(font) - })?; + Ok(Some(font)) + })?.expect("PDF export always resolves the selected space font"); if page.pdf_text_spaces.is_some() { page.pdf_resources.needs_pdf_for_preview |= plan.spaces_in_previous_font || plan.dedicated.as_ref() diff --git a/crates/texrra-tex-core/src/pdf_device/text_spaces.rs b/crates/texrra-tex-core/src/pdf_device/text_spaces.rs index 103c71d..ee8826b 100644 --- a/crates/texrra-tex-core/src/pdf_device/text_spaces.rs +++ b/crates/texrra-tex-core/src/pdf_device/text_spaces.rs @@ -28,7 +28,8 @@ impl SpaceOperation { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct SpaceSettings { pub(crate) automatic_at_start: bool, - pub(crate) font: SpaceFontRequest, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) dedicated_font: Option>, pub(crate) parameters: Vec<(i32, i32)>, } diff --git a/crates/texrra-tex-core/src/pdf_text.rs b/crates/texrra-tex-core/src/pdf_text.rs index bf20f91..6a1ed08 100644 --- a/crates/texrra-tex-core/src/pdf_text.rs +++ b/crates/texrra-tex-core/src/pdf_text.rs @@ -210,8 +210,8 @@ impl NativeText { } } -#[derive(Default)] -pub(super) struct FontHistory { +#[derive(Clone, Default)] +pub(crate) struct FontHistory { used: BTreeSet, first_scalable: BTreeMap, } @@ -239,11 +239,12 @@ impl FontHistory { } /// 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, fonts: &mut FontHistory, - load: impl FnOnce() -> Result, -) -> Result { + load: impl FnOnce() -> Result, String>, +) -> Result, String> { let Some(settings) = &page.pdf_text_spaces else { for item in &page.items { if let DisplayItem::NativeGlyph { @@ -255,7 +256,7 @@ pub(super) fn plan_spaces( 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 mut automatic = settings.automatic_at_start; @@ -277,7 +278,10 @@ pub(super) fn plan_spaces( operation: SpaceOperation::Explicit, } => { 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(); fonts.record(&dedicated.font, &dedicated.paint); @@ -342,8 +346,10 @@ pub(super) fn plan_spaces( } else { space = Some(SpaceUse::Dedicated); 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(); fonts.record(&dedicated.font, &dedicated.paint); @@ -380,7 +386,7 @@ pub(super) fn plan_spaces( _ => NativeText::finish(&mut text, &mut out), } } - Ok(plan) + Ok(Some(plan)) } pub(super) fn rule( diff --git a/tests/native_pages.rs b/tests/native_pages.rs index d9b537d..ce54323 100644 --- a/tests/native_pages.rs +++ b/tests/native_pages.rs @@ -239,3 +239,58 @@ fn saved_pdf_position_is_observed_in_shipout_order() { ); 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(); +}