From 514a2d334488a1d359ba63b268480a3093ad5e7a Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 03:09:10 +0800 Subject: [PATCH] Write PDF interword spaces with actual device fonts --- crates/texrra-tex-core/src/execution/boxes.rs | 8 + .../texrra-tex-core/src/execution/device.rs | 11 + .../src/execution/diagnostics.rs | 3 + .../texrra-tex-core/src/execution/engine.rs | 10 + .../src/execution/engine/device.rs | 29 ++ .../src/execution/engine/math.rs | 1 + .../src/execution/engine/page.rs | 35 ++ .../src/execution/format_image.rs | 2 +- crates/texrra-tex-core/src/execution/job.rs | 1 + crates/texrra-tex-core/src/execution/state.rs | 8 + crates/texrra-tex-core/src/native_font.rs | 77 +++- .../src/native_font/virtual_paint.rs | 2 + crates/texrra-tex-core/src/pdf.rs | 77 +++- crates/texrra-tex-core/src/pdf_device.rs | 1 + .../src/pdf_device/text_spaces.rs | 60 ++++ crates/texrra-tex-core/src/pdf_text.rs | 338 +++++++++++++++--- crates/texrra-tex-core/src/render.rs | 17 +- crates/texrra-tex-core/src/source_map.rs | 2 +- .../src/source_map/pdf_projection.rs | 10 + .../tests/execution_fractions.rs | 2 +- .../tests/execution_pdf_unicode.rs | 2 +- .../tests/execution_vcenter.rs | 2 +- docs/P2_M1_PROGRESS.md | 29 ++ src/native_job.rs | 2 +- 24 files changed, 664 insertions(+), 65 deletions(-) create mode 100644 crates/texrra-tex-core/src/pdf_device/text_spaces.rs diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index 088b85d..ffb57b1 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -150,6 +150,7 @@ pub(super) enum BoxPaint<'a> { Box(&'a HorizontalBox), PdfColor, PdfGraphics, + PdfTextSpace(crate::pdf_device::text_spaces::SpaceOperation), RowStart(RowLayout), PdfLink(&'a OutputNode, Option), Output(&'a OutputNode), @@ -209,6 +210,7 @@ pub(super) enum GeometryItem { Paint(crate::math_engine_tex::PositionedItem), PdfColor, PdfGraphics { x: i64, y: i64 }, + PdfTextSpace { x: i64, y: i64, operation: crate::pdf_device::text_spaces::SpaceOperation }, } impl NativeBox { @@ -734,6 +736,10 @@ impl NativeBox { emit(GeometryItem::PdfGraphics { x, y }); return; } + BoxPaint::PdfTextSpace(operation) => { + emit(GeometryItem::PdfTextSpace { x, y, operation }); + return; + } BoxPaint::RowStart(_) | BoxPaint::PdfLink(_, _) | BoxPaint::Output(_) => return, }; if let Some(child) = &b.math_geometry { @@ -977,6 +983,8 @@ fn walk_output( emit(x, y, BoxPaint::PdfColor); } else if node.is_pdf_graphics() { emit(x, y, BoxPaint::PdfGraphics); + } else if let OutputOperation::PdfTextSpace(operation) = node.operation { + emit(x, y, BoxPaint::PdfTextSpace(operation)); } else if links && node.is_pdf_link() { emit(x, y, BoxPaint::PdfLink(node, row)); } diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 9e2cac9..1ed37e3 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -25,6 +25,8 @@ pub struct NativeShipout { pub(super) pdf_color_steps: Vec>>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) pdf_graphics_steps: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) pdf_text_spaces: Option, #[serde(default, skip_serializing_if = "pdf_resource_entries_empty")] pub(super) pdf_resource_entries: Arc<[u8]>, #[serde(default, skip_serializing_if = "crate::pdf_device::links::PageLinks::is_empty")] @@ -43,6 +45,7 @@ impl NativeShipout { units: crate::render::DisplayUnits::TeX, pdf: self.device.pdf.clone(), pdf_links: self.pdf_links.clone(), + pdf_text_spaces: self.pdf_text_spaces.clone(), pdf_resources: crate::pdf_device::page_resources::PageResources { entries: self.pdf_resource_entries.clone(), ..Default::default() @@ -74,6 +77,14 @@ impl NativeShipout { } return; } + boxes::GeometryItem::PdfTextSpace { x, y, operation } => { + page.items.push(DisplayItem::PdfTextSpace { + x: self.device.horizontal_origin + x, + y: self.device.vertical_origin + self.box_node.height + y, + operation, + }); + return; + } boxes::GeometryItem::PdfGraphics { x, y } => { if let Some(operation) = graphics_steps.next() { page.items.push(DisplayItem::PdfGraphics { diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index 6cadd90..9f36b02 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -606,6 +606,9 @@ impl Printer<'_> { } OutputOperation::PdfSave => self.command("pdfsave"), OutputOperation::PdfRestore => self.command("pdfrestore"), + OutputOperation::PdfTextSpace(operation) => { + self.command(operation.name()); + } OutputOperation::PdfLink(node) => { use crate::pdf_device::links::LinkNode; self.command(match node { diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 739f09c..03ef155 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -219,6 +219,8 @@ pub struct Executor { pdf_colors: crate::pdf_device::PdfColorStacks, pdf_link_stack: Vec, pdf_running_links: bool, + pdf_interword_spaces: bool, + pdf_space_font: Option, #[cfg(all(target_os = "linux", target_env = "gnu"))] pdf_last_match: Option>, pdf_catalog_tokens: Vec, @@ -384,6 +386,8 @@ impl Executor { pdf_colors: Default::default(), pdf_link_stack: Vec::new(), pdf_running_links: true, + pdf_interword_spaces: false, + pdf_space_font: None, #[cfg(all(target_os = "linux", target_env = "gnu"))] pdf_last_match: None, pdf_catalog_tokens: Vec::new(), @@ -2814,6 +2818,9 @@ impl Executor { OutputOperation::PdfColor { .. } => { return self.fail("PDF color operation requires native PDF paint"); } + OutputOperation::PdfTextSpace(_) => { + return self.fail("PDF text space operation requires a positioned shipout"); + } OutputOperation::PdfLink(_) => { return self.fail("PDF link operation requires a positioned shipout"); } @@ -3794,6 +3801,9 @@ impl Executor { Pdfstartlink | Pdfendlink | Pdfdest | Pdfrunninglinkoff | Pdfrunninglinkon => { self.scan_pdf_link(primitive, token.span, files)?; } + Pdfinterwordspaceon | Pdfinterwordspaceoff | Pdffakespace | Pdfspacefont => { + self.scan_pdf_space(primitive, token.span, files)?; + } Pdfsetrandomseed => { let seed = self.integer(files)?; self.reads.insert(Dependency::PdfRandomState); diff --git a/crates/texrra-tex-core/src/execution/engine/device.rs b/crates/texrra-tex-core/src/execution/engine/device.rs index eb5cff3..bae1eee 100644 --- a/crates/texrra-tex-core/src/execution/engine/device.rs +++ b/crates/texrra-tex-core/src/execution/engine/device.rs @@ -69,6 +69,35 @@ impl Executor { } Ok(()) } + pub(super) fn scan_pdf_space( + &mut self, + command: Primitive, + span: Span, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + use crate::pdf_device::text_spaces::{SpaceFontRequest, SpaceOperation}; + if self.read_parameter(Parameter::Pdfoutput).width() <= 0 { + return self.fail("PDF text space operation not allowed in DVI mode"); + } + let operation = match command { + Primitive::Pdfspacefont => { + let tokens = self.scan_expanded_group(files)?; + self.pdf_space_font = Some(SpaceFontRequest { + name: self.token_list_text(&tokens), + from: self.source_name(span), + }); + return Ok(()); + } + Primitive::Pdfinterwordspaceon => SpaceOperation::Automatic(true), + Primitive::Pdfinterwordspaceoff => SpaceOperation::Automatic(false), + Primitive::Pdffakespace => SpaceOperation::Explicit, + _ => unreachable!(), + }; + self.defer_output(OutputNode { + operation: OutputOperation::PdfTextSpace(operation), + span, + }) + } pub(super) fn pdf_page_data( &mut self, files: &mut impl SourceProvider, diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index b4f0921..0d40c0c 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -550,6 +550,7 @@ impl Executor { | Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfcatalog | Pdfoutline | Pdfglyphtounicode | Pdffontattr | Pdfnobuiltintounicode | Pdfrunninglinkoff | Pdfrunninglinkon + | Pdfinterwordspaceon | Pdfinterwordspaceoff | Pdffakespace | Pdfspacefont | Ignorespaces | Unskip | Unkern | Unpenalty => { return Ok(false); } diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 616e22e..34a71df 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -310,6 +310,10 @@ impl Executor { } else { Vec::new().into_iter() }; + use crate::pdf_device::text_spaces::{SpaceFontRequest, SpaceOperation, SpaceSettings}; + 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 pdf_objects = Vec::new(); for output in outputs { if let OutputOperation::PdfObject(number) = output.operation { @@ -337,6 +341,17 @@ impl Executor { &mut graphics_stack, files, )?); + } 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 if let OutputOperation::PdfLink(link) = &output.operation { use crate::pdf_device::links::LinkNode; self.current = output.span; @@ -380,6 +395,25 @@ impl Executor { } 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, + } + }); self.current = current; self.native_page.as_mut().unwrap().dead_cycles = 0; let before = self.statistics_before_shipout(&b, files)?; @@ -390,6 +424,7 @@ impl Executor { pdf_color_start, pdf_color_steps, pdf_graphics_steps, + pdf_text_spaces, pdf_resource_entries, pdf_links, }))); diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index d0448f6..9b1f8f7 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,7 +8,7 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 41; +const SCHEMA: u32 = 42; const COMPATIBLE_SCHEMAS: [u32; 12] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, SCHEMA]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/job.rs b/crates/texrra-tex-core/src/execution/job.rs index 5383470..115b56b 100644 --- a/crates/texrra-tex-core/src/execution/job.rs +++ b/crates/texrra-tex-core/src/execution/job.rs @@ -241,6 +241,7 @@ pub enum OutputOperation { PdfSave, PdfSetMatrix(Vec), PdfRestore, + PdfTextSpace(crate::pdf_device::text_spaces::SpaceOperation), PdfLink(crate::pdf_device::links::LinkNode), PdfImage { image: std::sync::Arc, diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 3aaed4e..72770df 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -109,6 +109,10 @@ pub enum Primitive { Pdfendlink, Pdfrunninglinkoff, Pdfrunninglinkon, + Pdfinterwordspaceon, + Pdfinterwordspaceoff, + Pdffakespace, + Pdfspacefont, Pdfdest, Pdfcatalog, Pdfoutline, @@ -990,6 +994,10 @@ impl Default for State { ("pdfendlink", Pdfendlink), ("pdfrunninglinkoff", Pdfrunninglinkoff), ("pdfrunninglinkon", Pdfrunninglinkon), + ("pdfinterwordspaceon", Pdfinterwordspaceon), + ("pdfinterwordspaceoff", Pdfinterwordspaceoff), + ("pdffakespace", Pdffakespace), + ("pdfspacefont", Pdfspacefont), ("pdfdest", Pdfdest), ("pdfcatalog", Pdfcatalog), ("pdfoutline", Pdfoutline), diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index d3e7ee1..98d5888 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -25,6 +25,13 @@ pub struct NativeFontPaint { } impl NativeFontPaint { + pub(crate) fn has_pdf_space(&self, font: &NativeFont) -> bool { + // pdfTeX requires the space name in an actual map re-encoding. + matches!(self.program, NativeFontProgram::Type1(_)) + && self.resources.len() == 3 + && self.encoding[32] == "space" + && font.metrics().width(' ') > 65_782 + } pub(crate) fn type1_resource(&self) -> Option<&crate::resources::ResourceVersion> { match &self.program { NativeFontProgram::Type1(_) => { @@ -216,6 +223,7 @@ 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; @@ -283,15 +291,61 @@ impl NativeFontCache { pages: &mut [crate::render::DisplayList], files: &mut impl crate::execution::SourceProvider, ) -> Result<(), String> { - if let Some(mut expanded) = virtual_paint::expand_pages(pages, files)? { - resolve_physical_fonts(&mut expanded, files, self)?; - for (original, resolved) in pages.iter_mut().zip(expanded) { - *original = resolved; - } - Ok(()) - } else { - resolve_physical_fonts(pages, files, self) + let expanded = virtual_paint::expand_pages(pages, files)?; + if expanded.is_none() && !pages.iter().any(|page| page.pdf_text_spaces.is_some()) { + return resolve_physical_fonts(pages, files, self); } + let mut resolved = expanded.unwrap_or_else(|| pages.to_vec()); + resolve_physical_fonts(&mut resolved, files, self)?; + crate::pdf::prepare_text_spaces(&mut resolved, |font, device| { + self.space_font(font, device, files) + })?; + for (original, resolved) in pages.iter_mut().zip(resolved) { + *original = resolved; + } + Ok(()) + } + + fn space_font( + &self, + request: &crate::pdf_device::text_spaces::SpaceFontRequest, + 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, + items: vec![DisplayItem::NativeGlyph { + x: 0, + y: 0, + size: font.size_sp(), + font: font.clone(), + slot: b' ', + character: ' ', + paint: None, + }], + ..DisplayList::default() + }; + resolve_physical_fonts(std::slice::from_mut(&mut page), files, self)?; + let DisplayItem::NativeGlyph { paint: Some(paint), .. } = page.items.pop().unwrap() else { + unreachable!("space font slot must be resolved"); + }; + Ok(ResolvedSpaceFont { font, paint }) } } @@ -342,7 +396,12 @@ 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 = map_entry(&map.data, &font.name)?; + let entry = if id.index() == SPACE_FONT_ID && font.name == "pdftexspace" { + // The pdfTeX device adds its own map entry on first use. + Some(MapEntry { file: "pdftexspace.pfb".into(), encoding: None }) + } else { + map_entry(&map.data, &font.name)? + }; let Some(entry) = entry else { let (resolution, digits) = if let Some(device) = &device { (device.pk_resolution, device.decimal_digits) 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 e164210..92357fb 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -293,6 +293,8 @@ pub(super) fn expand_pages( units: page.units, pdf: page.pdf.clone(), pdf_resources: page.pdf_resources.clone(), + pdf_links: page.pdf_links.clone(), + pdf_text_spaces: page.pdf_text_spaces.clone(), images: page.images.clone(), ..DisplayList::default() }; diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 8d429ad..40d1161 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -613,15 +613,24 @@ fn write_type0_font( struct PageContent { bytes: Vec, origin: crate::pdf_device::DeviceOrigin, + measuring: bool, } impl PageContent { + fn measuring() -> Self { + Self { measuring: true, ..Self::default() } + } + fn push_str(&mut self, text: &str) { - self.bytes.extend_from_slice(text.as_bytes()); + if !self.measuring { + self.bytes.extend_from_slice(text.as_bytes()); + } } fn push(&mut self, byte: u8) { - self.bytes.push(byte); + if !self.measuring { + self.bytes.push(byte); + } } fn move_origin(&mut self, point: [i64; 2], units: crate::render::DisplayUnits, digits: u8) { @@ -636,6 +645,38 @@ impl PageContent { } } +pub(crate) fn prepare_text_spaces( + pages: &mut [DisplayList], + mut resolve: impl FnMut( + &crate::pdf_device::text_spaces::SpaceFontRequest, + Option, + ) -> Result, +) -> Result<(), String> { + if !pages.iter().any(|page| page.pdf_text_spaces.is_some()) { + return Ok(()); + } + let mut fonts = native_text::FontHistory::default(); + let mut selected = None; + 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)); + } + let request = &page.pdf_text_spaces.as_ref().expect("space settings for shipped node").font; + let font = resolve(request, page.pdf.clone())?; + selected = Some(font.clone()); + Ok(font) + })?; + if page.pdf_text_spaces.is_some() { + page.pdf_resources.needs_pdf_for_preview |= plan.spaces_in_previous_font + || plan.dedicated.as_ref() + .is_some_and(|font| !font.paint.glyph_paths[&b' '].is_empty()); + page.pdf_space_plan = Some(plan); + } + } + Ok(()) +} + fn page_content( list: &DisplayList, height: i64, @@ -681,7 +722,20 @@ fn page_content( } let mut native_text: Option = None; let mut tex_text: Option = None; - for item in &list.items { + for (index, item) in list.items.iter().enumerate() { + if let DisplayItem::PdfTextSpace { x, y, operation } = item { + if let Some(dedicated) = list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()) + && *operation == crate::pdf_device::text_spaces::SpaceOperation::Explicit + { + if tex_text.is_none() { + content.move_origin([0, 0], list.units, digits); + } + native_text::NativeText::explicit_space( + &mut tex_text, &mut content, *x, *y, height, digits, dedicated, + ); + } + continue; + } if let DisplayItem::PdfGraphics { x, y, @@ -728,6 +782,8 @@ fn page_content( *slot, height, digits, + list.pdf_space_plan.as_ref().and_then(|plan| plan.before_glyph.get(&index)).copied(), + list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()), ); continue; } @@ -980,7 +1036,7 @@ fn page_content( pt(*height) )); } - DisplayItem::Link { .. } => {} + DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {} DisplayItem::PdfImageObject(_) => {} DisplayItem::Fill([r, g, b]) => { content.push_str(&format!( @@ -1291,6 +1347,9 @@ fn native_pdf( if !(1..=32768).contains(&page.magnification) { return Err("invalid native page magnification".into()); } + if page.pdf_text_spaces.is_some() && page.pdf_space_plan.is_none() { + return Err("native PDF text spaces require actual font resolution".into()); + } for item in &page.items { match item { DisplayItem::Text {..} | DisplayItem::MathGlyph {..} => return Err("native PDF requires actual native font snapshots, not legacy text or master glyphs".into()), @@ -1919,6 +1978,16 @@ fn write_pdf( } } } + for plan in pages.iter().filter_map(|page| page.pdf_space_plan.as_ref()) { + for id in &plan.in_font { + native_used.get_mut(id).expect("painted space font").2.insert(b' ', ' '); + } + if let Some(font) = &plan.dedicated { + native_used.entry(font.font.id).or_insert_with(|| ( + font.font.clone(), font.paint.clone(), BTreeMap::from([(b' ', ' ')]), + )); + } + } let mut native_font_ids = BTreeMap::new(); for (id, (face, paint, used)) in native_used { native_font_ids.insert( diff --git a/crates/texrra-tex-core/src/pdf_device.rs b/crates/texrra-tex-core/src/pdf_device.rs index 9e60fc4..f30aecc 100644 --- a/crates/texrra-tex-core/src/pdf_device.rs +++ b/crates/texrra-tex-core/src/pdf_device.rs @@ -81,6 +81,7 @@ pub use color::{PdfColorProgram, PdfColorStackAction}; pub(crate) use graphics::{Affine, DeviceOrigin}; pub use graphics::{PdfGraphics, PdfLiteralMode, PdfMatrix}; pub mod catalog; +pub mod text_spaces; pub mod links; #[doc(hidden)] diff --git a/crates/texrra-tex-core/src/pdf_device/text_spaces.rs b/crates/texrra-tex-core/src/pdf_device/text_spaces.rs new file mode 100644 index 0000000..103c71d --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/text_spaces.rs @@ -0,0 +1,60 @@ +//! Interword space operations in the PDF device. These whatsits have no TeX dimensions. +use crate::{ + execution::FontId, + native_font::{NativeFont, NativeFontPaint}, +}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum SpaceOperation { + Automatic(bool), + Explicit, +} + +impl SpaceOperation { + pub(crate) fn name(self) -> &'static str { + match self { + Self::Automatic(true) => "pdfinterwordspaceon", + Self::Automatic(false) => "pdfinterwordspaceoff", + Self::Explicit => "pdffakespace", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpaceSettings { + pub(crate) automatic_at_start: bool, + pub(crate) font: SpaceFontRequest, + pub(crate) parameters: Vec<(i32, i32)>, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct SpaceFontRequest { + pub name: String, + pub from: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ResolvedSpaceFont { + pub font: Arc, + pub paint: Arc, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SpaceUse { + InFont, + Dedicated, +} + +/// Resolved spaces are indexed by paint order, after virtual font expansion. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SpacePlan { + pub(crate) before_glyph: BTreeMap, + pub(crate) in_font: BTreeSet, + pub(crate) dedicated: Option, + pub(crate) spaces_in_previous_font: bool, +} diff --git a/crates/texrra-tex-core/src/pdf_text.rs b/crates/texrra-tex-core/src/pdf_text.rs index eff2a75..bf20f91 100644 --- a/crates/texrra-tex-core/src/pdf_text.rs +++ b/crates/texrra-tex-core/src/pdf_text.rs @@ -3,8 +3,15 @@ use super::PageContent; use crate::{ execution::FontId, native_font::NativeFont, - pdf_device::{divide_scaled, print_decimal, print_sp}, + pdf_device::{ + PdfGraphics, PdfLiteralMode, divide_scaled, print_decimal, print_sp, + text_spaces::{ResolvedSpaceFont, SpaceOperation, SpacePlan, SpaceUse}, + }, + render::{DisplayItem, DisplayList}, }; +use std::collections::{BTreeMap, BTreeSet}; + +const ONE_BP: i64 = 65_782; pub(super) struct NativeText { font: Option, effective_size: i64, @@ -25,6 +32,8 @@ impl NativeText { slot: u8, height: i64, digits: u8, + space: Option, + dedicated: Option<&ResolvedSpaceFont>, ) { let first = text.is_none(); let state = text.get_or_insert_with(|| { @@ -39,46 +48,39 @@ impl NativeText { opened: false, } }); - if state.font != Some(font.id) { - state.close_string(out); - let (number, size) = divide_scaled(font.size_sp(), 6_578_176, 6); - state.effective_size = size; - state.font = Some(font.id); - out.push_str(&format!( - "/N{} {} Tf\n", - font.id.index(), - print_decimal(number, 4) - )); + if space == Some(SpaceUse::InFont) { + out.push_str("<20>"); + let (_, size) = divide_scaled(font.size_sp(), 6_578_176, 6); + state.delta_h += Self::char_advance(font, paint, b' ', size); } + if space == Some(SpaceUse::Dedicated) { + let dedicated = dedicated.expect("resolved PDF space font"); + state.select_font(out, &dedicated.font); + out.push_str("( ) Tj\n"); + } + state.select_font(out, font); if state.expansion != font.expansion { state.close_string(out); state.expansion = font.expansion; - out.push_str(&format!( - "{} Tz\n", - print_decimal(i64::from(1000 + font.expansion), 1) - )); + if !out.measuring { + out.push_str(&format!( + "{} Tz\n", + print_decimal(i64::from(1000 + font.expansion), 1) + )); + } } - let horizontal_size = if font.expansion == 0 { - state.effective_size - } else { - crate::pdf_device::magnify(state.effective_size, 1000 + font.expansion) - }; - let (mut shift, shift_out) = - divide_scaled(x - state.start_h - state.delta_h, horizontal_size, 3); - let minimum = divide_scaled(6_578_176, 10i64.pow(u32::from(digits) + 2), 0).0; - let (v, v_out) = if (state.v - y).abs() >= minimum { - divide_scaled(state.v - y, 6_578_176, digits + 2) - } else { - (0, 0) - }; - if first || v != 0 || shift.abs() >= 32768 { + let (mut shift, shift_out) = state.horizontal_move(x, state.effective_size, font.expansion); + let (v, v_out) = state.vertical_move(y, digits); + if first || v != 0 || shift.abs() >= 32768 || space == Some(SpaceUse::Dedicated) { state.close_string(out); let (h, h_out) = divide_scaled(x - state.start_h, 6_578_176, digits + 2); - out.push_str(&format!( - "{} {} Td\n", - print_decimal(h, digits), - print_decimal(v, digits) - )); + if !out.measuring { + out.push_str(&format!( + "{} {} Td\n", + print_decimal(h, digits), + print_decimal(v, digits) + )); + } state.start_h += h_out; state.v -= v_out; state.delta_h = 0; @@ -89,27 +91,102 @@ impl NativeText { state.opened = true; } if shift != 0 { - out.push_str(&format!(" {} ", -shift)); + if !out.measuring { + out.push_str(&format!(" {} ", -shift)); + } state.delta_h += shift_out; } - out.push_str(&format!("<{slot:02X}>")); + if !out.measuring { + out.push_str(&format!("<{slot:02X}>")); + } + state.delta_h += Self::char_advance(font, paint, slot, state.effective_size); + } + + fn select_font(&mut self, out: &mut PageContent, font: &NativeFont) { + if self.font != Some(font.id) { + self.close_string(out); + let (number, size) = divide_scaled(font.size_sp(), 6_578_176, 6); + self.effective_size = size; + self.font = Some(font.id); + if !out.measuring { + out.push_str(&format!( + "/N{} {} Tf\n", + font.id.index(), + print_decimal(number, 4) + )); + } + } + } + + fn char_advance( + font: &NativeFont, + paint: &crate::native_font::NativeFontPaint, + slot: u8, + size: i64, + ) -> i64 { let advance = match &paint.program { crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot], crate::native_font::NativeFontProgram::Type1(_) => { - divide_scaled( - font.metrics().width(char::from(slot)), - state.effective_size, - 4, - ) - .1 + divide_scaled(font.metrics().width(char::from(slot)), size, 4).1 } }; - state.delta_h += if font.expansion == 0 { + if font.expansion == 0 { advance } else { crate::pdf_device::magnify(advance, 1000 + font.expansion) - }; + } } + + fn horizontal_move(&self, x: i64, size: i64, expansion: i32) -> (i64, i64) { + divide_scaled( + x - self.start_h - self.delta_h, + Self::expanded_size(size, expansion), + 3, + ) + } + + fn expanded_size(size: i64, expansion: i32) -> i64 { + if expansion == 0 { + size + } else { + crate::pdf_device::magnify(size, 1000 + expansion) + } + } + + fn vertical_move(&self, y: i64, digits: u8) -> (i64, i64) { + let minimum = divide_scaled(6_578_176, 10i64.pow(u32::from(digits) + 2), 0).0; + if (self.v - y).abs() >= minimum { + divide_scaled(self.v - y, 6_578_176, digits + 2) + } else { + (0, 0) + } + } + + pub(super) fn explicit_space( + text: &mut Option, + out: &mut PageContent, + x: i64, + y: i64, + height: i64, + digits: u8, + dedicated: &ResolvedSpaceFont, + ) { + Self::glyph( + text, + out, + x, + y, + &dedicated.font, + &dedicated.paint, + b' ', + height, + digits, + None, + None, + ); + Self::break_string(text, out); + } + fn close_string(&mut self, out: &mut PageContent) { if self.opened { out.push_str("] TJ\n"); @@ -133,6 +210,179 @@ impl NativeText { } } +#[derive(Default)] +pub(super) struct FontHistory { + used: BTreeSet, + first_scalable: BTreeMap, +} + +impl FontHistory { + fn record(&mut self, font: &NativeFont, paint: &crate::native_font::NativeFontPaint) { + if self.used.insert(font.id) + && matches!( + paint.program, + crate::native_font::NativeFontProgram::Type1(_) + ) + && !self.first_scalable.contains_key(&font.name) + { + self.first_scalable.insert(font.name.clone(), font.id); + } + } + + fn has_space(&self, font: &NativeFont, paint: &crate::native_font::NativeFontPaint) -> bool { + // Only the first font for a shared scalable TFM gets the space test. + self.first_scalable + .get(&font.name) + .is_none_or(|id| *id == font.id) + && paint.has_pdf_space(font) + } +} + +/// Determine real font use with the same text moves used by the PDF writer. +pub(super) fn plan_spaces( + page: &DisplayList, + fonts: &mut FontHistory, + load: impl FnOnce() -> Result, +) -> Result { + let Some(settings) = &page.pdf_text_spaces else { + for item in &page.items { + if let DisplayItem::NativeGlyph { + font, + paint: Some(paint), + .. + } = item + { + fonts.record(font, paint); + } + } + return Ok(SpacePlan::default()); + }; + let digits = page.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits); + let mut automatic = settings.automatic_at_start; + let mut plan = SpacePlan::default(); + let mut load = Some(load); + let mut text: Option = None; + let mut out = PageContent::measuring(); + for (index, item) in page.items.iter().enumerate() { + match item { + DisplayItem::PdfTextSpace { + operation: SpaceOperation::Automatic(enabled), + .. + } => { + automatic = *enabled; + } + DisplayItem::PdfTextSpace { + x, + y, + operation: SpaceOperation::Explicit, + } => { + if plan.dedicated.is_none() { + plan.dedicated = Some(load.take().expect("space font loader used once")()?); + } + let dedicated = plan.dedicated.as_ref().unwrap(); + fonts.record(&dedicated.font, &dedicated.paint); + NativeText::explicit_space( + &mut text, + &mut out, + *x, + *y, + page.height, + digits, + dedicated, + ); + } + DisplayItem::NativeGlyph { + x, + y, + font, + paint, + slot, + .. + } => { + let paint = paint + .as_ref() + .ok_or("native font was not resolved before planning PDF text spaces")?; + let (_, size) = divide_scaled(font.size_sp(), 6_578_176, 6); + if NativeText::expanded_size(size, font.expansion) <= 0 { + return Err("native PDF font size rounds to zero in the pdfTeX profile".into()); + } + let already_used = fonts.used.contains(&font.id); + fonts.record(font, paint); + let mut space = None; + if let Some(cursor) = &text + && automatic + { + let (width, shrink) = settings + .parameters + .get(font.id.index() as usize) + .copied() + .unwrap_or_else(|| { + ( + font.metrics().param(1) as i32, + font.metrics().param(3) as i32, + ) + }); + let prior_size = NativeText::expanded_size(size, cursor.expansion); + let movement = if prior_size > 0 { + cursor.horizontal_move(*x, size, cursor.expansion).1 + } else { + 0 + }; + if i64::from(width) > ONE_BP + && movement > i64::from(width) - i64::from(shrink) - ONE_BP / 10 + && cursor.vertical_move(*y, digits).0 == 0 + { + if fonts.has_space(font, paint) { + if cursor.opened && (cursor.font == Some(font.id) || already_used) { + space = Some(SpaceUse::InFont); + let previous = cursor.font.expect("open text string has a font"); + plan.in_font.insert(previous); + plan.spaces_in_previous_font |= previous != font.id; + } + } else { + space = Some(SpaceUse::Dedicated); + if plan.dedicated.is_none() { + plan.dedicated = + Some(load.take().expect("space font loader used once")()?); + } + let dedicated = plan.dedicated.as_ref().unwrap(); + fonts.record(&dedicated.font, &dedicated.paint); + } + } + } + if let Some(space) = space { + plan.before_glyph.insert(index, space); + } + NativeText::glyph( + &mut text, + &mut out, + *x, + *y, + font, + paint, + *slot, + page.height, + digits, + space, + plan.dedicated.as_ref(), + ); + } + DisplayItem::PdfGraphics { + operation: + PdfGraphics::Literal { + mode: PdfLiteralMode::Direct, + .. + }, + .. + } => { + NativeText::break_string(&mut text, &mut out); + } + _ => NativeText::finish(&mut text, &mut out), + } + } + Ok(plan) +} + pub(super) fn rule( out: &mut PageContent, x: i64, diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 18d53c3..dfe61e9 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -128,6 +128,11 @@ pub enum DisplayItem { y: i64, operation: crate::pdf_device::PdfGraphics, }, + PdfTextSpace { + x: i64, + y: i64, + operation: crate::pdf_device::text_spaces::SpaceOperation, + }, Special(String), } @@ -247,6 +252,8 @@ pub struct DisplayList { pub units: DisplayUnits, pub pdf: Option, pub pdf_links: crate::pdf_device::links::PageLinks, + pub pdf_text_spaces: Option, + pub pdf_space_plan: Option, pub pdf_resources: crate::pdf_device::page_resources::PageResources, } impl Default for DisplayList { @@ -261,6 +268,8 @@ impl Default for DisplayList { units: DisplayUnits::PostScript, pdf: None, pdf_links: Default::default(), + pdf_text_spaces: None, + pdf_space_plan: None, pdf_resources: Default::default(), } } @@ -322,7 +331,10 @@ impl DisplayList { && self.items.iter().zip(&other.items).all(|(left, right)| { match (left.native_svg_glyph(), right.native_svg_glyph()) { (Some(Ok(left)), Some(Ok(right))) => left == right, - (None, None) => left == right, + (None, None) => { + left == right || matches!((left, right), + (DisplayItem::PdfTextSpace { .. }, DisplayItem::PdfTextSpace { .. })) + } _ => false, } }) @@ -376,6 +388,7 @@ impl DisplayList { | DisplayItem::Image { x, y, .. } | DisplayItem::PdfImage { x, y, .. } | DisplayItem::PdfGraphics { x, y, .. } + | DisplayItem::PdfTextSpace { x, y, .. } | DisplayItem::Link { x, y, .. } => { *x += dx; *y += dy; @@ -634,7 +647,7 @@ impl DisplayList { *thickness as f64 / 65_536.0 )); } - DisplayItem::Link { .. } => {} + DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {} DisplayItem::Special(content) => { out.push_str(&format!( " diff --git a/crates/texrra-tex-core/src/source_map.rs b/crates/texrra-tex-core/src/source_map.rs index d417d77..92a085a 100644 --- a/crates/texrra-tex-core/src/source_map.rs +++ b/crates/texrra-tex-core/src/source_map.rs @@ -326,7 +326,7 @@ impl SourceMap { // Color controls change graphics state and occupy no geometry. if matches!( item, - DisplayItem::PdfColor(_) | DisplayItem::PdfImageObject(_) + DisplayItem::PdfColor(_) | DisplayItem::PdfImageObject(_) | DisplayItem::PdfTextSpace { .. } ) { continue; } diff --git a/crates/texrra-tex-core/src/source_map/pdf_projection.rs b/crates/texrra-tex-core/src/source_map/pdf_projection.rs index 0fabd83..5d8df19 100644 --- a/crates/texrra-tex-core/src/source_map/pdf_projection.rs +++ b/crates/texrra-tex-core/src/source_map/pdf_projection.rs @@ -162,6 +162,16 @@ impl PdfProjection { } return None; } + DisplayItem::PdfTextSpace { operation, .. } => { + if *operation == crate::pdf_device::text_spaces::SpaceOperation::Explicit + && self.units == DisplayUnits::TeX && !self.text_active + { + self.move_origin([0, 0]); + self.text_active = true; + self.modified_text_position = false; + } + return None; + } DisplayItem::NativeGlyph { .. } if self.units == DisplayUnits::TeX => { if !self.text_active { self.move_origin([0, 0]); diff --git a/crates/texrra-tex-core/tests/execution_fractions.rs b/crates/texrra-tex-core/tests/execution_fractions.rs index bc3a298..dae25c1 100644 --- a/crates/texrra-tex-core/tests/execution_fractions.rs +++ b/crates/texrra-tex-core/tests/execution_fractions.rs @@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 41); + assert_eq!(payload["schema"], 42); let state = State::initex().with_etex(); let loaded = FormatImage::decode(&bytes) .unwrap() diff --git a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs index f5fd731..4ce6102 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs @@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); let original: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(original["schema"], 41); + assert_eq!(original["schema"], 42); for (schema, expected) in [ (1, "incompatible native format"), (2, "incompatible native format"), diff --git a/crates/texrra-tex-core/tests/execution_vcenter.rs b/crates/texrra-tex-core/tests/execution_vcenter.rs index d6977ad..efa1f68 100644 --- a/crates/texrra-tex-core/tests/execution_vcenter.rs +++ b/crates/texrra-tex-core/tests/execution_vcenter.rs @@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 41); + assert_eq!(payload["schema"], 42); let executor = FormatImage::decode(&bytes) .unwrap() .new_job( diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 0411e89..e84261b 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1178,6 +1178,35 @@ schema41 的定向对照从自定义文件 CMap 与内建 CMap 分别提取出 - `receipt.json` 为 `39935858ea599a9f24af122487bd8dbe302174107ae08264707b2e344ec380d9`。 - `checkpoint/receipt.json` 为 `232cf92c3e493e7825fe3fa9433054d9464eaf5735797e02a27ef51d329da025`。 +### PDF 词间空格设备 + +schema42 接入 \pdfinterwordspaceon、\pdfinterwordspaceoff、\pdffakespace 和 +\pdfspacefont。开关随实际横纵列表发页,页间状态进入检查点。自动写出根据 +发页时 fontdimen2、fontdimen4 和真实文本游标的同基线水平位移决定。字体映射 +带有效 space 重编码且实际文本段可写入时使用现有字体的32号槽。其他需要空格的 +位置按设备规则使用真实专用字体,保持实际字形位置与 TeX 原始列表尺寸。 +[pdfTeX 的文本游标与词间空格](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L16219-L16369) + +首次需要专用字体时读取实际 TFM、字体映射、编码和字体文件。作业复用该选择, +即使之后扫描 \pdfspacefont。默认 PdfTeX-Space 按设备的真实映射读取。 +定向对照覆盖开启和关闭、显式空格、重编码字体、自选字体、未发页盒、 +逐页修改字体胶水参数及资源延迟加载。七页的文字提取、空格写出位置分类和 +144 DPI 灰度图一致。改第二页开关的续编复用878步,PDF、SVG 和归一化来源 +映射与独立零复用一致,两页无需重发。 +[pdfTeX 的字槽和专用字体映射](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/mapfile.c#L625-L641) + +已复现的字体表边界:专用字体在原生 PDF 写出准备阶段取得,因此仍可在首次 +空格发页后扩展原文本字体的 fontdimen9。参考在发页加载专用字体后拒绝该 +扩展。保留两端输入、PDF 与状态码,后续把首次实际字体使用接到发页时的 +TeX 字体表。 +[pdfTeX 的专用字体初始化](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L16219-L16227) + +回执在 `target/p3-pdf-interword-space-native`。 + +- `native/receipt.json` 为 `5203808e780042731b724536068e7ebed10abb3202496d7552f548e18459d340`。 +- `checkpoint/receipt.json` 为 `67a0c0c71b84129dccdd725858da24e2cfef6cc95cb98b4bf129a0176bfef4d7`。 +- `font-table-{reference,native}` 保存已复现的字体表差异。 + ### PDF 字面中的矩阵与来源映射 来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和 diff --git a/src/native_job.rs b/src/native_job.rs index 4a9b3e4..336f61a 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -808,7 +808,7 @@ impl Files { "id":image.id, "page":image.image.page, "resource":image.image.version, })); } - DisplayItem::PdfImageObject(_) | DisplayItem::PdfColor(_) => {} + DisplayItem::PdfImageObject(_) | DisplayItem::PdfColor(_) | DisplayItem::PdfTextSpace { .. } => {} DisplayItem::PdfGraphics { x, y, operation } => { paint_order.push(json!(["pdf_graphics", graphics.len()])); graphics.push(json!({"x": x, "y": y, "operation": operation}));