From 4a77540e46478adfda6a8caeef9a29f718a146f5 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Thu, 26 Nov 2026 09:23:45 +0800 Subject: [PATCH] Implement XeTeX contextual interword spacing and shipout shaping --- crates/texrra-tex-core/src/execution/boxes.rs | 84 ++++++- .../src/execution/boxes/interword.rs | 227 ++++++++++++++++++ .../src/execution/diagnostics.rs | 9 +- .../texrra-tex-core/src/execution/engine.rs | 2 +- .../src/execution/engine/alignment.rs | 5 +- .../src/execution/engine/boxes.rs | 1 + .../src/execution/engine/display.rs | 4 +- .../src/execution/engine/list_tail.rs | 4 +- .../src/execution/engine/math.rs | 2 +- .../src/execution/engine/page.rs | 10 +- .../src/execution/engine/paragraphs.rs | 12 +- .../src/execution/format_image.rs | 6 +- .../src/execution/math_delimiter.rs | 1 + .../src/execution/math_fraction.rs | 1 + .../src/execution/paragraph.rs | 50 +++- .../src/execution/paragraph/break_cache.rs | 3 +- .../src/execution/paragraph/interword.rs | 63 +++++ .../execution/paragraph/native_hyphenation.rs | 6 +- .../src/execution/paragraph/protrusion.rs | 2 +- .../src/execution/paragraph_trace.rs | 4 +- .../src/execution/parameters.rs | 6 +- docs/P2_M1_PROGRESS.md | 23 ++ docs/PUBLISHER_TEMPLATE_MATRIX.md | 8 + 23 files changed, 491 insertions(+), 42 deletions(-) create mode 100644 crates/texrra-tex-core/src/execution/boxes/interword.rs create mode 100644 crates/texrra-tex-core/src/execution/paragraph/interword.rs diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index 4beee5d..85e8ee4 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -1,6 +1,7 @@ //! Owned native boxes. Packing follows tex.web hpack/vpackage, not page costs. use super::*; use crate::{HorizontalBox, HorizontalItem, Paragraph, ParagraphFont}; +mod interword; mod tail; pub(super) use tail::TailNodeRef; mod leaders; @@ -58,6 +59,9 @@ pub struct NativeBox { /// Original horizontal semantics, retained before paint-time glue setting. pub diagnostic: Vec, pub setting: GlueSetting, + // Prepared only on the disposable shipout box after its glue is set. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(super) interword_runs: Vec, pub badness: i32, pub diagnostic_eligible: bool, pub excess: i64, @@ -240,9 +244,9 @@ impl NativeBox { } match &b.content { BoxContent::Horizontal(nodes) => { - let order = super::direction::visual_order(nodes, rtl && !b.display); + let order = b.horizontal_order(nodes, rtl && !b.display); let order = order.as_deref(); - for index in 0..nodes.len() { + for index in 0..order.map_or(nodes.len(), <[_]>::len) { let (index, rtl) = order.map_or((index, false), |order| order[index]); match &nodes[index] { TextNode::Output(o) => out.push(o), @@ -358,6 +362,7 @@ impl NativeBox { | TextNode::MathBoundary { width: w, .. } | TextNode::AccentKern(w) | TextNode::AutoKern(w) + | TextNode::SpaceAdjustment(w) | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox { width: *w as i64, @@ -368,7 +373,7 @@ impl NativeBox { penalty: *n as i64, flagged: false, }, - TextNode::Glue(g) | TextNode::NamedGlue(g, _) => HorizontalItem::Glue { + TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) => HorizontalItem::Glue { width: g.width as i64 + self.setting.adjustment(*g, &mut cumulative, &mut previous), stretch: 0, @@ -388,13 +393,71 @@ impl NativeBox { }; Some(PackedHorizontal::Item(item)) }; - let Some(order) = super::direction::visual_order(nodes, rtl) else { + let Some(order) = self.horizontal_order(nodes, rtl) else { return Some(nodes.iter().filter_map(|node| pack(node).map(|item| (item, false))).collect()); }; - // Glue accumulates its rounding in logical order before the device - // reverses a span. Reuse those adjusted widths in visual order. - let mut logical: Vec<_> = nodes.iter().map(pack).collect(); - Some(order.into_iter().filter_map(|(i, rtl)| logical[i].take().map(|item| (item, rtl))).collect()) + // Accumulate glue rounding in logical order. Glues included in a + // reshaped word were resolved separately and do not update this total. + let retained = if self.interword_runs.is_empty() { + None + } else { + let mut retained = vec![false; nodes.len()]; + for &(index, _) in &order { + retained[index] = true; + } + Some(retained) + }; + let mut logical: Vec<_> = nodes.iter().enumerate() + .map(|(index, node)| { + if retained.as_ref().is_none_or(|retained| retained[index]) { + pack(node) + } else { + None + } + }) + .collect(); + for run in &self.interword_runs { + logical[run.nodes.start] = Some(PackedHorizontal::Item(HorizontalItem::Box( + crate::opentype::horizontal_box(&run.word), + ))); + } + Some(order.into_iter() + .filter_map(|(index, rtl)| logical[index].take().map(|item| (item, rtl))) + .collect()) + } + + fn horizontal_order(&self, nodes: &[TextNode], rtl: bool) -> Option> { + let order = super::direction::visual_order(nodes, rtl); + if self.interword_runs.is_empty() { + return order; + } + let order = order.unwrap_or_else(|| (0..nodes.len()).map(|index| (index, false)).collect()); + let mut removed = vec![false; nodes.len()]; + for run in &self.interword_runs { + removed[run.nodes.start + 1..run.nodes.end].fill(true); + for &effect in &run.effects { + removed[effect] = true; + } + } + let mut prepared = Vec::with_capacity(order.len()); + for (index, rtl) in order { + if removed[index] { + continue; + } + if let Ok(run) = self.interword_runs.binary_search_by_key(&index, |run| run.nodes.start) { + let effects = &self.interword_runs[run].effects; + if rtl { + prepared.extend(effects.iter().rev().map(|&effect| (effect, rtl))); + } + prepared.push((index, rtl)); + if !rtl { + prepared.extend(effects.iter().map(|&effect| (effect, rtl))); + } + } else { + prepared.push((index, rtl)); + } + } + Some(prepared) } pub fn node_count(&self) -> usize { @@ -599,6 +662,7 @@ pub(super) fn vpack( content: BoxContent::Vertical(nodes), diagnostic: Vec::new(), setting: set, + interword_runs: Vec::new(), badness, diagnostic_eligible, excess, @@ -666,9 +730,10 @@ pub(super) fn hpack_with_direction_report( | TextNode::MathBoundary { width: w, .. } | TextNode::AccentKern(w) | TextNode::AutoKern(w) + | TextNode::SpaceAdjustment(w) | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => width += *w as i64, - TextNode::Glue(g) | TextNode::NamedGlue(g, _) => { + TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) => { width += g.width as i64; flex(*g, &mut stretch, &mut shrink); } @@ -710,6 +775,7 @@ pub(super) fn hpack_with_direction_report( content: BoxContent::Horizontal(nodes), diagnostic, setting: set, + interword_runs: Vec::new(), badness, diagnostic_eligible, excess, diff --git a/crates/texrra-tex-core/src/execution/boxes/interword.rs b/crates/texrra-tex-core/src/execution/boxes/interword.rs new file mode 100644 index 0000000..ca2935e --- /dev/null +++ b/crates/texrra-tex-core/src/execution/boxes/interword.rs @@ -0,0 +1,227 @@ +//! Shape full native word sequences after horizontal glue has been set. + +use super::super::paragraph::interword::invisible; +use super::*; +use crate::{opentype::OpenTypeRun, provenance::PaintSource}; +use std::{ops::Range, sync::Arc}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(in crate::execution) struct Run { + pub(super) nodes: Range, + pub(super) word: Arc, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(super) effects: Vec, +} + +impl NativeBox { + pub(in crate::execution) fn prepare_interword_shipout( + &mut self, + limit: usize, + cancellation: Option<&Cancellation>, + ) -> Result { + let mut remaining = limit; + prepare(self, &mut remaining, cancellation)?; + Ok(limit - remaining) + } +} + +fn prepare( + packed: &mut NativeBox, + remaining: &mut usize, + cancellation: Option<&Cancellation>, +) -> Result<(), String> { + if cancellation.is_some_and(Cancellation::is_cancelled) { + return Err("native compilation cancelled".into()); + } + if packed.kind.is_unset() { + return Ok(()); + } + match &mut packed.content { + BoxContent::Horizontal(nodes) => { + packed.interword_runs = shape_row(nodes, packed.setting, remaining, cancellation)?; + for node in nodes { + let child = match node { + TextNode::Box(item) + | TextNode::MathChar(item) + | TextNode::Glyph { glyph: item, .. } => item.native_box.as_deref_mut(), + TextNode::Leaders(LeaderGlue { + pattern: LeaderPattern::Box(item), + .. + }) => Some(item.as_mut()), + _ => None, + }; + if let Some(child) = child { + prepare(child, remaining, cancellation)?; + } + } + } + BoxContent::Vertical(nodes) => { + for node in nodes { + let child = match node { + NativeVerticalNode::Box(item) + | NativeVerticalNode::Line(item) + | NativeVerticalNode::Leaders(LeaderGlue { + pattern: LeaderPattern::Box(item), + .. + }) => item, + _ => continue, + }; + prepare(child, remaining, cancellation)?; + } + } + } + Ok(()) +} + +fn shape_row( + nodes: &[TextNode], + setting: GlueSetting, + remaining: &mut usize, + cancellation: Option<&Cancellation>, +) -> Result, String> { + let next = |start: usize| { + let offset = nodes[start..].iter().position(|node| !invisible(node)); + offset.map_or(nodes.len(), |offset| start + offset) + }; + let mut runs = Vec::new(); + let mut moved_suffix_effects = false; + let mut index = 0; + while let Some(node) = nodes.get(index) { + let start = index; + index += 1; + let TextNode::OpenType(first) = node else { + continue; + }; + let mut text = String::new(); + let mut sources = Vec::new(); + let mut units = 0; + loop { + let mut word_index = next(index); + let space = match nodes.get(word_index) { + Some(TextNode::FontSpace(_, font, origin)) => { + Some((Some(*origin), *font == first.font.id)) + } + Some(TextNode::Glue(_)) => Some((None, false)), + _ => None, + }; + if let Some((_, canonical)) = space { + let adjustment = matches!( + nodes.get(word_index + 1), + Some(TextNode::SpaceAdjustment(_)) + ); + if !canonical && !adjustment { + break; + } + word_index = next(word_index + 1 + usize::from(adjustment)); + } + let Some(TextNode::OpenType(word)) = nodes.get(word_index) else { + break; + }; + if word.font.id != first.font.id { + break; + } + if index == start + 1 { + text.push_str(&first.text); + sources.extend(first.sources.iter().cloned()); + units = first.text.encode_utf16().count(); + } + if let Some((origin, _)) = space { + if let Some(origin) = origin { + sources.push((text.len(), PaintSource::token(origin))); + } + text.push(' '); + units += 1; + } + units += word.text.encode_utf16().count(); + if units > usize::from(u16::MAX) { + return Err("native justified OpenType word capacity exceeded".into()); + } + let offset = text.len(); + text.push_str(&word.text); + sources.extend( + word.sources + .iter() + .map(|(at, source)| (offset + at, source.clone())), + ); + index = word_index + 1; + } + if index == start + 1 { + continue; + } + if cancellation.is_some_and(Cancellation::is_cancelled) { + return Err("native compilation cancelled".into()); + } + let mut word = first.font.shape_mapped(text, sources, false)?; + *remaining = remaining + .checked_sub(word.glyphs.len()) + .ok_or("native justified OpenType shaping step limit exceeded")?; + let target = nodes[start..index] + .iter() + .map(|node| shipout_width(node, setting)) + .sum(); + word.actual_text = first.actual_text; + justify(&mut word, target)?; + let mut effects = Vec::new(); + if !moved_suffix_effects + && let Some(offset) = nodes[start + 1..index].iter().position(invisible) + { + // XDV relinks the first invisible node in the old run. The scan + // then follows its new link into the remaining horizontal list. + effects.push(start + 1 + offset); + effects.extend( + nodes[index..] + .iter() + .enumerate() + .filter_map(|(offset, node)| invisible(node).then_some(index + offset)), + ); + moved_suffix_effects = true; + } + runs.push(Run { + nodes: start..index, + word: Arc::new(word), + effects, + }); + } + Ok(runs) +} + +fn shipout_width(node: &TextNode, setting: GlueSetting) -> i64 { + match node { + TextNode::Glue(glue) | TextNode::FontSpace(glue, ..) => { + // XeTeX rounds each consumed space independently before joining. + let (mut cumulative, mut previous) = (0, 0); + i64::from(glue.width) + setting.adjustment(*glue, &mut cumulative, &mut previous) + } + TextNode::OpenType(word) => word.width, + TextNode::SpaceAdjustment(width) => i64::from(*width), + _ => 0, + } +} + +fn justify(word: &mut OpenTypeRun, target: i64) -> Result<(), String> { + let difference = target - word.width; + word.width = target; + if difference == 0 || word.glyphs.len() < 2 { + return Ok(()); + } + let space = word + .font + .face()? + .glyph_index(' ') + .map_or(0, |glyph| glyph.0); + let spaces = word.glyphs.iter().filter(|glyph| glyph.id == space).count(); + let total = if spaces == 0 { + word.glyphs.len() - 1 + } else { + spaces + }; + let mut consumed = 0; + for glyph in &mut word.glyphs { + glyph.x = + (glyph.x as f64 + difference as f64 * consumed as f64 / total as f64).round() as i64; + if spaces == 0 || glyph.id == space { + consumed += 1; + } + } + Ok(()) +} diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index ef8f32c..261093c 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -57,6 +57,7 @@ pub enum DiagnosticNode { Unsupported(String), AccentKern(i32), AutoKern(i32), + SpaceAdjustment(i32), MarginKern { width: i32, right: bool }, Direction(DirectionBoundary), } @@ -226,13 +227,14 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec { value: *g, name: Some(*p), }, - TextNode::Glue(g) => DiagnosticNode::Glue { + TextNode::Glue(g) | TextNode::FontSpace(g, _, _) => DiagnosticNode::Glue { value: *g, name: None, }, TextNode::Leaders(leader) => leader_node(leader), TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width), TextNode::AutoKern(width) => DiagnosticNode::AutoKern(*width), + TextNode::SpaceAdjustment(width) => DiagnosticNode::SpaceAdjustment(*width), TextNode::MarginKern { width, right, .. } => DiagnosticNode::MarginKern { width: *width, right: *right, @@ -522,6 +524,11 @@ impl Printer<'_> { self.number(i64::from(*width)); self.literal(" (for accent)"); } + DiagnosticNode::SpaceAdjustment(width) => { + self.command("kern"); + self.number(i64::from(*width)); + self.literal(" (space adjustment)"); + } DiagnosticNode::AutoKern(width) => { self.command("kern"); self.literal(" "); diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 71dd850..046cac8 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -3935,7 +3935,7 @@ impl Executor { } Explicitspace => { if self.paragraph.is_some() { - let space = self.explicit_space()?; + let space = self.explicit_space(Some(&token))?; self.paragraph.as_mut().unwrap().nodes.push(space); } } diff --git a/crates/texrra-tex-core/src/execution/engine/alignment.rs b/crates/texrra-tex-core/src/execution/engine/alignment.rs index 512ad45..31accc3 100644 --- a/crates/texrra-tex-core/src/execution/engine/alignment.rs +++ b/crates/texrra-tex-core/src/execution/engine/alignment.rs @@ -797,6 +797,7 @@ fn empty_alignment_box(width: i64, horizontal: bool, span: Span) -> NativeBox { }, diagnostic: Vec::new(), setting: GlueSetting::default(), + interword_runs: Vec::new(), badness: 0, diagnostic_eligible: false, excess: 0, @@ -857,7 +858,7 @@ fn set_alignment_cell( match &cell.content { BoxContent::Horizontal(v) => { for n in v { - if let TextNode::Glue(g) + if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n { @@ -1031,7 +1032,7 @@ fn mark_unset(b: &mut NativeBox, span: u8) -> Result<(), String> { match &b.content { BoxContent::Horizontal(v) => { for n in v { - if let TextNode::Glue(g) + if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n { diff --git a/crates/texrra-tex-core/src/execution/engine/boxes.rs b/crates/texrra-tex-core/src/execution/engine/boxes.rs index bed5474..6083803 100644 --- a/crates/texrra-tex-core/src/execution/engine/boxes.rs +++ b/crates/texrra-tex-core/src/execution/engine/boxes.rs @@ -522,6 +522,7 @@ impl Executor { content: BoxContent::Horizontal(Vec::new()), diagnostic: Vec::new(), setting: GlueSetting::default(), + interword_runs: Vec::new(), badness: 0, diagnostic_eligible: false, excess: 0, diff --git a/crates/texrra-tex-core/src/execution/engine/display.rs b/crates/texrra-tex-core/src/execution/engine/display.rs index 5654b14..ade7568 100644 --- a/crates/texrra-tex-core/src/execution/engine/display.rs +++ b/crates/texrra-tex-core/src/execution/engine/display.rs @@ -152,7 +152,7 @@ impl Executor { if b.width + q > width { let mut shrink = [0i64; 4]; for node in &material { - if let TextNode::Glue(g) + if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) = node { @@ -180,7 +180,7 @@ impl Executor { displacement = (width - b.width - e + 1).div_euclid(2); if matches!( material.first(), - Some(TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)) + Some(TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)) ) { displacement = 0; } diff --git a/crates/texrra-tex-core/src/execution/engine/list_tail.rs b/crates/texrra-tex-core/src/execution/engine/list_tail.rs index 653712d..cfe0d1d 100644 --- a/crates/texrra-tex-core/src/execution/engine/list_tail.rs +++ b/crates/texrra-tex-core/src/execution/engine/list_tail.rs @@ -17,10 +17,10 @@ impl Tail { } fn text(node: &TextNode) -> Self { match node { - TextNode::Glue(g) + TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false), - TextNode::Kern { width, .. } | TextNode::AccentKern(width) | TextNode::AutoKern(width) => { + TextNode::Kern { width, .. } | TextNode::AccentKern(width) | TextNode::AutoKern(width) | TextNode::SpaceAdjustment(width) => { Self::Kern(*width) } TextNode::Penalty(n) => Self::Penalty(*n), diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index 09d48b2..01123b1 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -767,7 +767,7 @@ impl Executor { _ => MathStyle::ScriptScript, })), Explicitspace => { - let space = match self.explicit_space()? { + let space = match self.explicit_space(None)? { TextNode::NamedGlue(glue, parameter) => { MathNode::ExplicitSpace(glue, Some(parameter)) } diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index e02c9a1..eb599f5 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -261,7 +261,7 @@ impl Executor { } pub(super) fn ship_box( &mut self, - b: NativeBox, + mut b: NativeBox, files: &mut impl SourceProvider, ) -> Result<(), Error> { self.native_page_mut()?; @@ -314,6 +314,14 @@ impl Executor { pdf, }; self.trace_shipout(&b, files)?; + if self.state.input_profile() == InputProfile::XeTeX + && self.read_parameter(Parameter::XeTeXinterwordspaceshaping).width() > 1 + { + let limit = self.limits.steps.saturating_sub(self.steps); + let work = b.prepare_interword_shipout(limit, self.cancellation.as_ref()) + .map_err(|error| self.error(error, b.span))?; + self.steps += work; + } let current = self.current; let (pdf_resource_entries, pdf_page_attributes) = if device.pdf.is_some() { ( diff --git a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs index 027fcfe..7d78845 100644 --- a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs +++ b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs @@ -142,7 +142,7 @@ impl Executor { }); Ok(()) } - pub(super) fn explicit_space(&mut self) -> Result { + pub(super) fn explicit_space(&mut self, token: Option<&Token>) -> Result { let glue = self.read_parameter(Parameter::Spaceskip).glue(); if glue != Glue::default() { return Ok(TextNode::NamedGlue(glue, Parameter::Spaceskip)); @@ -154,6 +154,13 @@ impl Executor { .fonts .font(self.state.text_font()) .map_err(|error| self.error(error, self.current))?; + if self.state.input_profile() == InputProfile::XeTeX && font.opentype().is_some() + && let Some(token) = token + { + return Ok(TextNode::FontSpace( + font.space(), self.state.text_font(), TokenOrigin::from(token), + )); + } Ok(TextNode::Glue(font.space())) } @@ -345,7 +352,7 @@ impl Executor { .insert(Dependency::Parameter(Parameter::Spaceskip)); self.reads .insert(Dependency::Parameter(Parameter::Xspaceskip)); - b.space(&self.state) + b.space(&self.state, TokenOrigin::from(token)) .map_err(|e| self.error(e, token.invocation.unwrap_or(token.span)))?; } return Ok(()); @@ -390,6 +397,7 @@ impl Executor { if self.state.input_profile() == InputProfile::XeTeX { self.reads.insert(Dependency::Parameter(Parameter::XeTeXuseglyphmetrics)); self.reads.insert(Dependency::Parameter(Parameter::XeTeXgenerateactualtext)); + self.reads.insert(Dependency::Parameter(Parameter::XeTeXinterwordspaceshaping)); if !self.restricted() { self.reads.insert(Dependency::Parameter(Parameter::XeTeXdashbreakstate)); } diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 23c574c..b469ca8 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,9 +8,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 72; -const COMPATIBLE_SCHEMAS: [u32; 39] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, SCHEMA, +const SCHEMA: u32 = 73; +const COMPATIBLE_SCHEMAS: [u32; 40] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/math_delimiter.rs b/crates/texrra-tex-core/src/execution/math_delimiter.rs index 5b85556..48c7786 100644 --- a/crates/texrra-tex-core/src/execution/math_delimiter.rs +++ b/crates/texrra-tex-core/src/execution/math_delimiter.rs @@ -329,6 +329,7 @@ fn delimiter_native_box(content: BoxContent, width: i64, height: i64, depth: i64 content, diagnostic, setting: GlueSetting::default(), + interword_runs: Vec::new(), badness: 0, diagnostic_eligible: false, excess: 0, diff --git a/crates/texrra-tex-core/src/execution/math_fraction.rs b/crates/texrra-tex-core/src/execution/math_fraction.rs index 1a94f45..1faf86c 100644 --- a/crates/texrra-tex-core/src/execution/math_fraction.rs +++ b/crates/texrra-tex-core/src/execution/math_fraction.rs @@ -125,6 +125,7 @@ impl Converter<'_> { content: BoxContent::Vertical(nodes), diagnostic: Vec::new(), setting: GlueSetting::default(), + interword_runs: Vec::new(), badness: 0, diagnostic_eligible: false, excess: 0, diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index 9574512..2fe9428 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -6,6 +6,7 @@ use crate::opentype::{OpenTypeFont, OpenTypeRun}; mod break_cache; mod expansion; +pub(super) mod interword; mod native_hyphenation; mod protrusion; pub(super) use protrusion::stored_margin_kern; @@ -81,6 +82,8 @@ pub enum TextNode { AutoKern(i32), MarginKern { width: i32, right: bool, font: FontId, slot: u16 }, Direction(DirectionBoundary), + FontSpace(Glue, FontId, TokenOrigin), + SpaceAdjustment(i32), } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct NativeParagraph { @@ -276,7 +279,8 @@ impl Builder { let original_end = run.text.chars().next_back(); let (text, sources) = run.font.map_text(run.text, run.sources)?; if self.restricted || !xetex { - return self.push_opentype(&run.font, text, sources, state); + self.push_opentype(&run.font, text, sources, state)?; + return self.adjust_interword_space(state); } let dash_breaks = state.parameter(Parameter::XeTeXdashbreakstate).width() > 0; @@ -317,6 +321,23 @@ impl Builder { if trailing_break { self.push_explicit_hyphen_break(run.font.id); } + self.adjust_interword_space(state) + } + + fn adjust_interword_space(&mut self, state: &State) -> Result<(), String> { + if state.input_profile() != InputProfile::XeTeX + || state.parameter(Parameter::XeTeXinterwordspaceshaping).width() <= 0 + { + return Ok(()); + } + if let Some((after_glue, width, work)) = interword::adjustment(&self.nodes, state)? { + self.font_steps = self.font_steps.checked_add(work) + .filter(|steps| *steps <= self.font_step_limit) + .ok_or("native OpenType shaping step limit exceeded")?; + if width != 0 { + self.nodes.insert(after_glue, TextNode::SpaceAdjustment(width)); + } + } Ok(()) } @@ -451,7 +472,7 @@ impl Builder { code }; } - pub fn space(&mut self, state: &State) -> Result<(), String> { + pub fn space(&mut self, state: &State, origin: TokenOrigin) -> Result<(), String> { self.finish_text(true, state)?; let f = state.fonts.font(state.text_font())?; let g = f.space(); @@ -505,6 +526,11 @@ impl Builder { }; self.nodes.push(match name { Some(name) => TextNode::NamedGlue(g, name), + None if factor == 1000 && s == Glue::default() + && state.input_profile() == InputProfile::XeTeX && f.opentype().is_some() => + { + TextNode::FontSpace(g, state.text_font(), origin) + } None => TextNode::Glue(g), }); Ok(()) @@ -533,10 +559,11 @@ pub(super) fn hyphen_node(state: &State, font: FontId, c: char, origin: TokenOri fn discardable(n: &TextNode) -> bool { matches!( n, - TextNode::Glue(_) + TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) | TextNode::Kern { .. } + | TextNode::SpaceAdjustment(_) | TextNode::MathBoundary { .. } | TextNode::Direction(_) | TextNode::Penalty(_) @@ -548,13 +575,14 @@ fn width(n: &TextNode) -> i64 { glyph.width } TextNode::OpenType(run) => run.width, - TextNode::Glue(g) + TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) => g.width as i64, TextNode::Rule(r) => r.dimensions().0, TextNode::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width), TextNode::Kern { width: n, .. } | TextNode::AccentKern(n) + | TextNode::SpaceAdjustment(n) | TextNode::AutoKern(n) | TextNode::MarginKern { width: n, .. } | TextNode::MathBoundary { width: n, .. } @@ -695,7 +723,7 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64) let mut shrink = 0; for g in std::iter::once(left) .chain(nodes.iter().filter_map(|n| { - if let TextNode::Glue(g) + if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n { @@ -715,7 +743,7 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64) .filter(|n| { !matches!( n, - TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) + TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) ) }) .map(width) @@ -1204,7 +1232,7 @@ fn pre_display_line_size( | TextNode::Indent(_) | TextNode::Rule(_) ); - if let TextNode::Glue(g) + if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n { @@ -1239,7 +1267,7 @@ pub(super) fn finish( if b.nodes.last().is_some_and(|n| { matches!( n, - TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) + TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) ) }) { b.nodes.pop(); @@ -1262,7 +1290,7 @@ pub(super) fn finish( .collect(); let shape = state.paragraph_shape().to_vec(); for n in &b.nodes { - if let TextNode::Glue(g) + if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n && g.shrink.order != 0 @@ -1528,7 +1556,7 @@ fn add_hyphens( .is_some_and(|n| { matches!( n, - TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) + TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) ) }) && !word.is_empty() @@ -1559,7 +1587,7 @@ fn add_hyphens( | TextNode::Insertion(_) | TextNode::Mark(_) | TextNode::Output(_) - | TextNode::Glue(_) + | TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) | TextNode::Penalty(_) diff --git a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs index a731092..a5eaa55 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs @@ -151,13 +151,14 @@ impl BreakNode { | TextNode::Output(_) | TextNode::MathChar(_) | TextNode::Indent(_) => Self::Content(width(node)), - TextNode::Glue(glue) + TextNode::Glue(glue) | TextNode::FontSpace(glue, _, _) | TextNode::NamedGlue(glue, _) | TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue), TextNode::AccentKern(width) => Self::AccentKern(*width), TextNode::MarginKern { width, .. } | TextNode::AutoKern(width) => { Self::Content(i64::from(*width)) } + TextNode::SpaceAdjustment(width) => Self::Kern { width: *width, explicit: false }, TextNode::Kern { width, explicit } => Self::Kern { width: *width, explicit: *explicit, diff --git a/crates/texrra-tex-core/src/execution/paragraph/interword.rs b/crates/texrra-tex-core/src/execution/paragraph/interword.rs new file mode 100644 index 0000000..fa55079 --- /dev/null +++ b/crates/texrra-tex-core/src/execution/paragraph/interword.rs @@ -0,0 +1,63 @@ +//! XeTeX contextual width measurement for an interword glue node. + +use super::*; + +pub(in crate::execution) fn invisible(node: &TextNode) -> bool { + matches!( + node, + TextNode::Language(_) + | TextNode::Penalty(_) + | TextNode::Insertion(_) + | TextNode::Mark(_) + | TextNode::Adjustment(_) + ) || matches!( + node, + TextNode::Output(OutputNode { + operation: OutputOperation::Open { .. } + | OutputOperation::Write { .. } + | OutputOperation::Close { .. } + | OutputOperation::Special { .. }, + .. + }) + ) +} + +pub(super) fn adjustment( + nodes: &[TextNode], + state: &State, +) -> Result, String> { + let Some((TextNode::OpenType(right), prefix)) = nodes.split_last() else { + return Ok(None); + }; + let mut preceding = prefix + .iter() + .enumerate() + .rev() + .filter(|(_, node)| !invisible(node)); + let Some(( + glue_index, + TextNode::Glue(_) + | TextNode::FontSpace(..) + | TextNode::NamedGlue(..) + | TextNode::Leaders(_), + )) = preceding.next() + else { + return Ok(None); + }; + let Some((_, TextNode::OpenType(left))) = preceding.next() else { + return Ok(None); + }; + if left.font.id != right.font.id { + return Ok(None); + } + + let text = format!("{} {}", left.text, right.text); + if text.encode_utf16().count() > usize::from(u16::MAX) { + return Err("native contextual OpenType word capacity exceeded".into()); + } + let joined = right.font.shape_mapped(text, Vec::new(), false)?; + let nominal_space = i64::from(state.fonts.font(right.font.id)?.space().width); + let width = joined.width - left.width - right.width - nominal_space; + let width = i32::try_from(width).map_err(|_| "native contextual space width overflow")?; + Ok(Some((glue_index + 1, width, joined.glyphs.len()))) +} diff --git a/crates/texrra-tex-core/src/execution/paragraph/native_hyphenation.rs b/crates/texrra-tex-core/src/execution/paragraph/native_hyphenation.rs index fe457b1..8ff7c34 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/native_hyphenation.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/native_hyphenation.rs @@ -21,11 +21,12 @@ pub(super) fn add_hyphens( match node { TextNode::Language(next) => language = *next, TextNode::Direction(_) + | TextNode::SpaceAdjustment(_) | TextNode::Output(_) | TextNode::Kern { explicit: false, .. } => {} - TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) => { + TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) => { after_glue = auto_breaking; } TextNode::MathBoundary { after, .. } => { @@ -197,12 +198,13 @@ fn following_nodes_allow_hyphenation(nodes: &[TextNode]) -> bool { | TextNode::Insertion(_) | TextNode::Mark(_) | TextNode::Output(_) - | TextNode::Glue(_) + | TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) | TextNode::Penalty(_) | TextNode::AccentKern(_) | TextNode::AutoKern(_) + | TextNode::SpaceAdjustment(_) | TextNode::Kern { explicit: true, .. } ) }) diff --git a/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs b/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs index 20c8133..9b693cd 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs @@ -123,7 +123,7 @@ fn skippable(node: &TextNode) -> bool { | TextNode::Kern { explicit: false, .. } | TextNode::Kern { width: 0, .. } => true, TextNode::Output(node) => node.dimensions().is_none(), - TextNode::Glue(glue) + TextNode::Glue(glue) | TextNode::FontSpace(glue, _, _) | TextNode::NamedGlue(glue, _) | TextNode::Leaders(LeaderGlue { glue, .. }) => glue.canonical_zero, TextNode::Discretionary { diff --git a/crates/texrra-tex-core/src/execution/paragraph_trace.rs b/crates/texrra-tex-core/src/execution/paragraph_trace.rs index 851d123..cf00ec6 100644 --- a/crates/texrra-tex-core/src/execution/paragraph_trace.rs +++ b/crates/texrra-tex-core/src/execution/paragraph_trace.rs @@ -215,7 +215,7 @@ impl Tracer { | TextNode::Mark(_) | TextNode::Output(_) => out.push_str("[]"), TextNode::Rule(_) => out.push('|'), - TextNode::Glue(g) + TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) => { if !g.canonical_zero { @@ -234,7 +234,7 @@ impl Tracer { i += usize::from(*replacement_count); } TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_) - | TextNode::AutoKern(_) | TextNode::MarginKern { .. } => {} + | TextNode::AutoKern(_) | TextNode::SpaceAdjustment(_) | TextNode::MarginKern { .. } => {} } i += 1; } diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index e2b8caa..4526015 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -127,6 +127,7 @@ pub enum Parameter { XeTeXprotrudechars, XeTeXhyphenatablelength, XeTeXgenerateactualtext, + XeTeXinterwordspaceshaping, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum ParameterValue { @@ -159,7 +160,7 @@ impl Parameter { ) } - pub(super) const XETEX: [Self; 7] = [ + pub(super) const XETEX: [Self; 8] = [ Self::XeTeXuseglyphmetrics, Self::XeTeXdashbreakstate, Self::Suppressfontnotfounderror, @@ -167,6 +168,7 @@ impl Parameter { Self::XeTeXprotrudechars, Self::XeTeXhyphenatablelength, Self::XeTeXgenerateactualtext, + Self::XeTeXinterwordspaceshaping, ]; pub const ALL: &'static [Self] = &[ @@ -292,6 +294,7 @@ impl Parameter { Self::XeTeXprotrudechars, Self::XeTeXhyphenatablelength, Self::XeTeXgenerateactualtext, + Self::XeTeXinterwordspaceshaping, ]; pub fn name(self) -> String { match self { @@ -302,6 +305,7 @@ impl Parameter { Self::XeTeXprotrudechars => "XeTeXprotrudechars".into(), Self::XeTeXhyphenatablelength => "XeTeXhyphenatablelength".into(), Self::XeTeXgenerateactualtext => "XeTeXgenerateactualtext".into(), + Self::XeTeXinterwordspaceshaping => "XeTeXinterwordspaceshaping".into(), _ => format!("{self:?}").to_ascii_lowercase(), } } diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 31468b7..70dd2ce 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,29 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### XeTeX 上下文词间距与跨词造型 + +`\XeTeXinterwordspaceshaping` 在扫描原生词时测量实际字体的 +上下文宽度,第一级把差量写成可在断行时舍弃的独立 kern。 +第二级在出页时按实际胶宽重新组合字形,保留已定行宽、词级 +ActualText 和来源。合并的胶与剩余胶分别按原版规则舍入。 +同一准备后的布局供字形、延迟写出和 specials 使用。 +[扫描期上下文宽度](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/xetex.web#L24584-L24654) +[出页合并与节点重连](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/xetex.web#L14713-L14833) +[跨词字形的宽度分配](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/XeTeX_ext.c#L1938-L1987) + +同源对照 19 页、100 个字形的编号、字号、顺序和坐标全部 +一致。验证跨空格连字、阿拉伯语、断行、显式胶、盒复制、出页时 +切换、1 sp 的舍入、ActualText、specials 位置和延迟写出。CFF +探针使用单独冻结的 GSUB、GPOS 特性。原样 ACL 复用同一 schema71、 +真实字体和实际辅助文件,PDF 与生成文件和上一版逐字节一致。 +schema73 可重载赋值和别名。12 项 XeTeX 定向测试通过。 + +三次跨文件切换至 1、2、0 时各复用 66 步、重放 2 次调用,只刷新 +第二页,PDF、SVG 和来源映射均与独立全量一致。回执 +`target/p3-xetex-interword/receipt.json` 的 SHA-256 为 +`009cbd22cb56042362e6c1baae2db3dc50a3b28a1857ce5aae915adb431461a8`。 + ### XeTeX 词级 PDF ActualText `\XeTeXgenerateactualtext` 随真实整数赋值和分组生效。新建原生词 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 1f60207..aa0eee8 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -758,6 +758,14 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX `target/p3-xdv-annotation/receipt.json`。 [链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形) +#### XeTeX 词间造型复编 + +原样 ACL 使用同一 schema71、真实字体与已收敛生成初态复编。 +默认 PDF 和 aux、out、bbl 与上一版逐字节一致。对照用例的 +跨词造型另在 `target/p3-xetex-interword/receipt.json` 核验, +原样模板的既有整页门槛继续保留。 +[上下文词间距阶段记录](P2_M1_PROGRESS.md#xetex-上下文词间距与跨词造型) + #### XeTeX 词级 PDF 标记复编 原样 ACL 继续加载同一 schema71 格式,以真实已收敛的生成文件