diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index b350fd3..088b85d 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -333,6 +333,7 @@ impl NativeBox { TextNode::Indent(w) | TextNode::MathBoundary { width: w, .. } | TextNode::AccentKern(w) + | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox { width: *w as i64, ..HorizontalBox::default() @@ -614,6 +615,7 @@ pub(super) fn hpack( TextNode::Indent(w) | TextNode::MathBoundary { width: w, .. } | TextNode::AccentKern(w) + | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => width += *w as i64, TextNode::Glue(g) | TextNode::NamedGlue(g, _) => { width += g.width as i64; diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index e5b176f..a5333e2 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -51,6 +51,7 @@ pub enum DiagnosticNode { Output(OutputNode), Unsupported(String), AccentKern(i32), + MarginKern { width: i32, right: bool }, } /// A semantic view, without recursively copying the box's painted contents. #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] @@ -211,6 +212,10 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec { }, TextNode::Leaders(leader) => leader_node(leader), TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width), + TextNode::MarginKern { width, right, .. } => DiagnosticNode::MarginKern { + width: *width, + right: *right, + }, TextNode::Kern { width, explicit } => DiagnosticNode::Kern { width: *width, explicit: *explicit, @@ -473,6 +478,11 @@ impl Printer<'_> { &format!("{prefix}."), )?; } + DiagnosticNode::MarginKern { width, right } => { + self.command("kern"); + self.number(i64::from(*width)); + self.literal(if *right { " (right margin)" } else { " (left margin)" }); + } DiagnosticNode::AccentKern(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 11fd362..8a98c88 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -1988,6 +1988,16 @@ impl Executor { Ok(()) } + fn font_character_target( + &mut self, files: &mut impl SourceProvider, + ) -> Result<(FontId, u8), Error> { + let font = self.font_identifier(files)?; + let slot = self.integer(files)?; + let slot = u8::try_from(slot).map_err(|_| { + self.error("font character code must be in 0..255", self.current) + })?; + Ok((font, slot)) + } fn internal_integer_from( &mut self, next: InputToken, @@ -2012,6 +2022,10 @@ impl Executor { } Ok(value.width()) } + Meaning::Primitive(p @ (Primitive::Lpcode | Primitive::Rpcode)) => { + let (font, slot) = self.font_character_target(files)?; + Ok(self.state.fonts.protrusion_code(font, slot, p == Primitive::Rpcode)) + } Meaning::Primitive(p @ (Primitive::Hyphenchar | Primitive::Skewchar)) => { let font = self.font_identifier(files)?; let values = self.state.font_integers(font); @@ -3847,6 +3861,12 @@ impl Executor { matches!(primitive, Some(Edef | Xdef)), files, )?, + Some(Lpcode | Rpcode) => { + let (font, slot) = self.font_character_target(files)?; + self.optional_equals(files)?; + let code = self.integer(files)?; + self.state.fonts.set_protrusion_code(font, slot, primitive == Some(Rpcode), code); + } Some(Hyphenchar | Skewchar) => { let font = self.font_identifier(files)?; self.optional_equals(files)?; diff --git a/crates/texrra-tex-core/src/execution/engine/boxes.rs b/crates/texrra-tex-core/src/execution/engine/boxes.rs index cd961e6..f470218 100644 --- a/crates/texrra-tex-core/src/execution/engine/boxes.rs +++ b/crates/texrra-tex-core/src/execution/engine/boxes.rs @@ -165,7 +165,9 @@ impl Executor { .as_mut() .expect("unhbox starts an actual paragraph") .nodes - .extend(nodes), + .extend( + nodes.into_iter().filter(|node| !matches!(node, TextNode::MarginKern { .. })), + ), BoxContent::Vertical(nodes) => self.append_unboxed_vertical(nodes), } Ok(()) diff --git a/crates/texrra-tex-core/src/execution/engine/display.rs b/crates/texrra-tex-core/src/execution/engine/display.rs index eba3b84..2a9b0e2 100644 --- a/crates/texrra-tex-core/src/execution/engine/display.rs +++ b/crates/texrra-tex-core/src/execution/engine/display.rs @@ -407,6 +407,8 @@ impl Executor { | Font | Fontdimen | Hyphenchar + | Lpcode + | Rpcode | Skewchar | Textfont | Scriptfont 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 2bc40dd..cc1dec1 100644 --- a/crates/texrra-tex-core/src/execution/engine/list_tail.rs +++ b/crates/texrra-tex-core/src/execution/engine/list_tail.rs @@ -22,6 +22,7 @@ impl Tail { | TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false), TextNode::Kern { width, .. } | TextNode::AccentKern(width) => Self::Kern(*width), TextNode::Penalty(n) => Self::Penalty(*n), + TextNode::MarginKern { .. } => Self::Other(15), TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }), TextNode::MathChar(_) => Self::Other(0), TextNode::Box(b) => Self::Other(b.native_box.as_ref().map_or(1, |b| { diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index 8a46a03..51eff22 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -783,7 +783,7 @@ impl Executor { | Lccode | Uccode | Lowercase | Uppercase | Hyphenation | Patterns | Mathcode | Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip | Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline - | Font | Fontdimen | Hyphenchar | Skewchar | Textfont | Scriptfont + | Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Textfont | Scriptfont | Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time | Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage | Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen diff --git a/crates/texrra-tex-core/src/execution/engine/quantities.rs b/crates/texrra-tex-core/src/execution/engine/quantities.rs index ae20828..2cfa819 100644 --- a/crates/texrra-tex-core/src/execution/engine/quantities.rs +++ b/crates/texrra-tex-core/src/execution/engine/quantities.rs @@ -223,6 +223,8 @@ impl Executor { | Primitive::Prevgraf | Primitive::Spacefactor | Primitive::Hyphenchar + | Primitive::Lpcode + | Primitive::Rpcode | Primitive::Skewchar ) ) diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index 86f62b8..9b3b848 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -6,7 +6,7 @@ use crate::{ tfm::{FontSize, TfmMetrics}, }; use sha2::{Digest, Sha256}; -use std::sync::Arc; +use std::{collections::BTreeMap, sync::Arc}; #[derive( Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, @@ -144,6 +144,8 @@ pub struct FontCatalog { resources: Vec, parameter_words: usize, limits: FontLimits, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + protrusion: BTreeMap>, } impl Default for FontCatalog { fn default() -> Self { @@ -173,6 +175,7 @@ impl FontCatalog { resources: Vec::new(), parameter_words: 7, limits, + protrusion: BTreeMap::new(), }) } pub fn fonts(&self) -> &[FontInstance] { @@ -316,6 +319,18 @@ impl FontCatalog { self.fonts[id.0 as usize].parameters[index] = value; Ok(()) } + pub(super) fn protrusion_code(&self, font: FontId, slot: u8, right: bool) -> i32 { + self.protrusion.get(&font).and_then(|font| font.get(&slot)) + .map_or(0, |codes| i32::from(codes[usize::from(right)])) + } + pub(super) fn set_protrusion_code( + &mut self, font: FontId, slot: u8, right: bool, code: i32, + ) { + let code = code.clamp(-1000, 1000) as i16; + if code != 0 || self.protrusion.get(&font).is_some_and(|font| font.contains_key(&slot)) { + self.protrusion.entry(font).or_default().entry(slot).or_default()[usize::from(right)] = code; + } + } pub fn set_integers(&mut self, id: FontId, integers: FontIntegers) -> Result<(), String> { self.font(id)?; self.fonts[id.0 as usize].integers = integers; diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index e60c186..9934d64 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,8 +8,8 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 31; -const COMPATIBLE_SCHEMAS: [u32; 3] = [27, 28, SCHEMA]; +const SCHEMA: u32 = 32; +const COMPATIBLE_SCHEMAS: [u32; 4] = [27, 28, 31, SCHEMA]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); #[derive(serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index d272d42..08f2fb9 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -4,6 +4,7 @@ use crate::{HorizontalBox, Paragraph, ParagraphFont}; use std::collections::BTreeMap; mod break_cache; +mod protrusion; use break_cache::BreakNode; pub use break_cache::{LineBreakCache, LineBreakWork}; @@ -72,6 +73,7 @@ pub enum TextNode { }, /// Spacing owned by a text accent and protected from leading discard. AccentKern(i32), + MarginKern { width: i32, right: bool, font: FontId, slot: u8 }, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct NativeParagraph { @@ -386,6 +388,7 @@ fn width(n: &TextNode) -> i64 { TextNode::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width), TextNode::Kern { width: n, .. } | TextNode::AccentKern(n) + | TextNode::MarginKern { width: n, .. } | TextNode::MathBoundary { width: n, .. } | TextNode::Indent(n) => *n as i64, _ => 0, @@ -553,6 +556,7 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64) fn break_lines( nodes: &[TextNode], projected: &[BreakNode], + margins: Option<&protrusion::Search>, p: &BTreeMap, shape: &[ParagraphShapeLine], pass: u8, @@ -732,7 +736,14 @@ fn break_lines( if target < 0 && shape.is_empty() { return Err("negative native paragraph measure".into()); } - let delta = target - natural; + let hanging = margins.map_or(0, |margins| { + // The active paragraph still ends in parfillskip. A nonzero + // fill stops the right search at the terminal breakpoint. + let right_visible = !final_break + || p[&Parameter::Parfillskip].glue().canonical_zero; + margins.width(a.start, b.end, a.post_break, b.pre_break, right_visible) + }); + let delta = target - natural + hanging; let infinite = stretch[1..].iter().any(|n| *n != 0); let bad = if delta >= 0 { if infinite { @@ -918,17 +929,32 @@ fn pack( p: &BTreeMap, (indent, target): (i64, i64), last: bool, + terminal_marker: bool, + ends_in_pre_break: bool, state: &State, span: Span, -) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial), String> { +) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial, bool), String> { let left = p[&Parameter::Leftskip].glue(); let mut material = Vec::new(); if left != Glue::default() { material.push(TextNode::NamedGlue(left, Parameter::Leftskip)); } - material.extend_from_slice(nodes); + let enabled = p[&Parameter::Pdfprotrudechars].width() > 0; + if enabled && let Some(kern) = protrusion::margin_kern(state, nodes, false, false) { + material.push(kern); + } + let right_end = nodes.len() - usize::from(terminal_marker); + material.extend_from_slice(&nodes[..right_end]); if last { material.push(TextNode::Penalty(10000)); + } + if enabled + && let Some(kern) = protrusion::margin_kern(state, &nodes[..right_end], true, ends_in_pre_break) + { + material.push(kern); + } + material.extend_from_slice(&nodes[right_end..]); + if last { material.push(TextNode::NamedGlue( p[&Parameter::Parfillskip].glue(), Parameter::Parfillskip, @@ -939,6 +965,7 @@ fn pack( Parameter::Rightskip, )); let (material, adjustments) = super::marks::extract(material); + let shrinking = material.iter().map(width).sum::() > target; let mut b = super::boxes::hpack( material, super::boxes::PackSpec::To( @@ -962,7 +989,7 @@ fn pack( centered: false, right_aligned: false, }; - Ok((paragraph, b, adjustments)) + Ok((paragraph, b, adjustments, shrinking)) } // TeX init_math scans natural widths and visible nodes, independently of // rounded glue-setting coordinates. Stretch/shrink before the last visible @@ -1085,6 +1112,7 @@ pub(super) fn finish( if let Some(path) = break_cache::solve( &b.nodes, ¶meters, + state, shape, pass, &mut work, @@ -1114,13 +1142,6 @@ pub(super) fn finish( let mut packed_shrinking = Vec::new(); let mut pre_display_size = -1073741823; for (i, (point, bad)) in path.iter().enumerate() { - let left = parameters[&Parameter::Leftskip].glue(); - let mut right = parameters[&Parameter::Rightskip].glue(); - if i + 1 == path.len() { - right = right - .add(parameters[&Parameter::Parfillskip].glue()) - .map_err(str::to_owned)?; - } let material = line_material( &b.nodes, start, @@ -1130,23 +1151,26 @@ pub(super) fn finish( true, point.zero_tail, ); - let (natural, stretch, shrink) = metrics(&material, left, right); let dimensions = geometry(¶meters, shape, i + b.previous_lines); - let target = dimensions.1; - let (set, packed_bad, excess) = - super::boxes::setting(target - natural, stretch, [shrink, 0, 0, 0], true); - packed_diagnostic.push(target != natural && set.order == 0); - packed_shrinking.push(target < natural); - packed_badness.push(packed_bad); - packed_excess.push(excess); - let (line, line_box, adjustments) = pack( + let terminal_marker = point.zero_tail.is_some() + || matches!(b.nodes.get(point.end), Some(TextNode::Penalty(_))); + let ends_in_pre_break = point.pre_break.is_some_and(|index| { + matches!(&b.nodes[index], TextNode::Discretionary { pre_break, .. } if !pre_break.is_empty()) + }); + let (line, line_box, adjustments, shrinking) = pack( &material, ¶meters, dimensions, i + 1 == path.len(), + terminal_marker, + ends_in_pre_break, state, b.span, )?; + packed_diagnostic.push(line_box.diagnostic_eligible); + packed_shrinking.push(shrinking); + packed_badness.push(line_box.badness); + packed_excess.push(line_box.excess); if i + 1 == path.len() { let BoxContent::Horizontal(material) = &line_box.content else { unreachable!() 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 e219a0f..d5a860c 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs @@ -47,6 +47,7 @@ type Path = Option>; struct Entry { hash: u64, nodes: Vec, + margins: Option, parameters: BTreeMap, shape: Vec, previous_lines: usize, @@ -57,7 +58,9 @@ struct Entry { impl Entry { fn retained_nodes(&self) -> usize { - self.nodes.len() + self.shape.len() + self.nodes.len() + + self.shape.len() + + self.margins.as_ref().map_or(0, protrusion::Search::len) } } @@ -148,6 +151,7 @@ impl BreakNode { | TextNode::NamedGlue(glue, _) | TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue), TextNode::AccentKern(width) => Self::AccentKern(*width), + TextNode::MarginKern { width, .. } => Self::Content(i64::from(*width)), TextNode::Kern { width, explicit } => Self::Kern { width: *width, explicit: *explicit, @@ -259,6 +263,7 @@ pub(super) fn candidate_widths( pub(super) fn solve( source: &[TextNode], parameters: &BTreeMap, + state: &State, shape: &[ParagraphShapeLine], pass: u8, work: &mut usize, @@ -267,14 +272,16 @@ pub(super) fn solve( cache: Option<&LineBreakCache>, ) -> Result { let nodes: Vec<_> = source.iter().map(BreakNode::project).collect(); - let retained = nodes.len() + shape.len(); + let margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1) + .then(|| protrusion::Search::new(state, source)); + let retained = nodes.len() + shape.len() + margins.as_ref().map_or(0, protrusion::Search::len); let mut hash = None; if let Some(cache) = cache && retained <= RETAINED_NODES && parameters[&Parameter::Tracingparagraphs].width() <= 0 { let mut hasher = DefaultHasher::new(); - (&nodes, parameters, shape, pass, previous_lines).hash(&mut hasher); + (&nodes, &margins, parameters, shape, pass, previous_lines).hash(&mut hasher); let key = hasher.finish(); hash = Some(key); let mut cache = cache @@ -288,6 +295,7 @@ pub(super) fn solve( && entry.parameters == *parameters && entry.shape == shape && entry.nodes == nodes + && entry.margins == margins }) { let entry = cache.entries.remove(index).unwrap(); *work += entry.edges; @@ -306,6 +314,7 @@ pub(super) fn solve( let result = break_lines( source, &nodes, + margins.as_ref(), parameters, shape, pass, @@ -335,6 +344,7 @@ pub(super) fn solve( cache.entries.push_back(Entry { hash, nodes, + margins, parameters: parameters.clone(), shape: shape.to_vec(), previous_lines, diff --git a/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs b/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs new file mode 100644 index 0000000..0c431ed --- /dev/null +++ b/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs @@ -0,0 +1,205 @@ +//! The same font-slot widths drive break search and the owned margin kerns. +use super::*; + +#[derive(Clone, Copy)] +enum Edge { + Skip, + Solid, + Glyph(FontId, u8), +} + +impl Edge { + fn character(node: &TextNode) -> Self { + match node { + TextNode::Glyph { font, slot, .. } => Self::Glyph(*font, *slot), + TextNode::MathChar(glyph) => { + use crate::math_engine_tex::MathItem; + match glyph + .math_geometry + .as_deref() + .map(|geometry| geometry.items.as_slice()) + { + Some([item]) => match &item.item { + MathItem::NativeGlyph { font, slot, .. } => Self::Glyph(font.id, *slot), + _ => Self::Solid, + }, + _ => Self::Solid, + } + } + _ => Self::Solid, + } + } + + fn node(node: &TextNode, right: bool) -> Self { + match node { + TextNode::Box(boxed) => match boxed.native_box.as_deref() { + Some(NativeBox { + content: BoxContent::Horizontal(nodes), + .. + }) if !nodes.is_empty() => Self::list(nodes, right), + Some(NativeBox { + content: BoxContent::Horizontal(_), + .. + }) if boxed.width == 0 && boxed.height == 0 && boxed.depth == 0 => Self::Skip, + _ => Self::Solid, + }, + TextNode::Language(_) + | TextNode::Mark(_) + | TextNode::Adjustment(_) + | TextNode::Insertion(_) + | TextNode::Penalty(_) + | TextNode::Indent(0) + | TextNode::AccentKern(0) + | TextNode::MathBoundary { width: 0, .. } + | TextNode::Kern { + explicit: false, .. + } + | TextNode::Kern { width: 0, .. } => Self::Skip, + TextNode::Output(node) if node.dimensions().is_none() => Self::Skip, + TextNode::Glue(glue) + | TextNode::NamedGlue(glue, _) + | TextNode::Leaders(LeaderGlue { glue, .. }) + if glue.canonical_zero => + { + Self::Skip + } + TextNode::Discretionary { + pre_break, + post_break, + replacement_count: 0, + .. + } if pre_break.is_empty() && post_break.is_empty() => Self::Skip, + _ => Self::character(node), + } + } + + fn list(nodes: &[TextNode], right: bool) -> Self { + let mut nodes = nodes.iter(); + while let Some(node) = if right { + nodes.next_back() + } else { + nodes.next() + } { + let edge = Self::node(node, right); + if !matches!(edge, Self::Skip) { + return edge; + } + } + Self::Skip + } + + fn width(self, state: &State, right: bool) -> i32 { + let Self::Glyph(font, slot) = self else { + return 0; + }; + let code = state.fonts.protrusion_code(font, slot, right); + if code == 0 { + return 0; + } + let quad = state + .fonts + .font(font) + .expect("marginal glyph's font is live") + .quad(); + let scaled = i64::from(quad) * i64::from(code); + // Round to the nearest sp, taking half a unit away from zero. + (scaled.signum() * ((scaled.abs() + 500) / 1000)) as i32 + } +} + +pub(super) fn margin_kern( + state: &State, + nodes: &[TextNode], + right: bool, + direct: bool, +) -> Option { + let edge = if direct { + nodes.last().map_or(Edge::Solid, Edge::character) + } else { + Edge::list(nodes, right) + }; + let Edge::Glyph(font, slot) = edge else { + return None; + }; + let width = -edge.width(state, right); + (width != 0).then_some(TextNode::MarginKern { + width, + right, + font, + slot, + }) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +struct Projected { + left: Option<(usize, i32)>, + right: Option<(usize, i32)>, + pre: Option, + post: Option, +} + +#[derive(Debug, PartialEq, Eq, Hash)] +pub(super) struct Search(Vec); + +impl Search { + pub(super) fn new(state: &State, nodes: &[TextNode]) -> Self { + let mut widths = vec![Projected::default(); nodes.len() + 1]; + for (i, node) in nodes.iter().enumerate() { + let edge = Edge::node(node, true); + widths[i + 1].right = if matches!(edge, Edge::Skip) { + widths[i].right + } else { + Some((i, edge.width(state, true))) + }; + if let TextNode::Discretionary { + pre_break, + post_break, + .. + } = node + { + widths[i].pre = pre_break + .last() + .map(|node| Edge::character(node).width(state, true)); + widths[i].post = post_break + .first() + .map(|node| Edge::character(node).width(state, false)); + } + } + for (i, node) in nodes.iter().enumerate().rev() { + let edge = Edge::node(node, false); + widths[i].left = if matches!(edge, Edge::Skip) { + widths[i + 1].left + } else { + Some((i, edge.width(state, false))) + }; + } + Self(widths) + } + + pub(super) fn len(&self) -> usize { + self.0.len() + } + + pub(super) fn width( + &self, + start: usize, + end: usize, + post: Option, + pre: Option, + right_visible: bool, + ) -> i64 { + let left = post.and_then(|i| self.0[i].post).or_else(|| { + self.0[start] + .left + .filter(|(i, _)| *i < end) + .map(|(_, width)| width) + }); + let right = pre.and_then(|i| self.0[i].pre).or_else(|| { + self.0[end] + .right + .filter(|(i, _)| right_visible && *i >= start) + .map(|(_, width)| width) + }); + i64::from(left.unwrap_or(0)) + i64::from(right.unwrap_or(0)) + } +} diff --git a/crates/texrra-tex-core/src/execution/paragraph_trace.rs b/crates/texrra-tex-core/src/execution/paragraph_trace.rs index b810978..5357c2e 100644 --- a/crates/texrra-tex-core/src/execution/paragraph_trace.rs +++ b/crates/texrra-tex-core/src/execution/paragraph_trace.rs @@ -230,7 +230,8 @@ impl<'a> Tracer<'a> { self.short(post_break, out)?; i += usize::from(*replacement_count); } - TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_) => {} + TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_) + | 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 5c9a688..18b2add 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -111,6 +111,7 @@ pub enum Parameter { Baselineskip, Lineskip, Tabskip, + Pdfprotrudechars, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum ParameterValue { @@ -225,6 +226,7 @@ impl Parameter { Self::Baselineskip, Self::Lineskip, Self::Tabskip, + Self::Pdfprotrudechars, ]; pub fn name(self) -> String { format!("{self:?}").to_ascii_lowercase() diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 60668bb..a52132b 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -315,6 +315,8 @@ pub enum Primitive { Accent, Pdfmatch, Pdflastmatch, + Lpcode, + Rpcode, } impl Primitive { @@ -735,6 +737,8 @@ impl Default for State { ("eqno", Eqno), ("leqno", Leqno), ("hyphenchar", Hyphenchar), + ("lpcode", Lpcode), + ("rpcode", Rpcode), ("fontname", Fontname), ("fontdimen", Fontdimen), ("skewchar", Skewchar), diff --git a/crates/texrra-tex-core/tests/execution_diagnostics.rs b/crates/texrra-tex-core/tests/execution_diagnostics.rs index 317d687..f8459e5 100644 --- a/crates/texrra-tex-core/tests/execution_diagnostics.rs +++ b/crates/texrra-tex-core/tests/execution_diagnostics.rs @@ -357,3 +357,63 @@ fn text_accents_preserve_font_metrics_kerns_and_paint_positions() { assert_eq!(pages[0]["glyphs"].as_u64(), Some(15)); assert!(pages[0]["max_coordinate_error_sp"].as_i64().unwrap() <= 1); } + +#[test] +fn margin_protrusion_uses_font_slots_in_break_search_and_shipout() { + let case = directory("margin-protrusion"); + let source = r"\catcode123=1 \catcode125=2 +\font\roman=cmr10 \roman +\hsize=38pt \baselineskip=12pt \parskip=0pt +\parfillskip=0pt plus 1fil +\rightskip=0pt plus 1fil +\pretolerance=100 \tolerance=200 +\linepenalty=10 +\showboxbreadth=99 \showboxdepth=99 +\begingroup \lpcode\roman65=120 \endgroup +\message{GROUP-CODE:\the\lpcode\roman65} +\lpcode\roman65=100 \rpcode\roman46=500 +\message{LEFT-CODE:\the\lpcode\roman65} +\message{RIGHT-CODE:\the\rpcode\roman46} +\setbox0=\vbox{\pdfprotrudechars=0 \noindent AA. AA.\par} +\setbox1=\vbox{\pdfprotrudechars=1 \noindent AA. AA.\par} +\setbox2=\vbox{\pdfprotrudechars=2 \noindent AA. AA.\par} +\setbox3=\vbox{\pdfprotrudechars=1 \noindent\hbox{A}A.\par} +\lpcode\roman65=-100 \rpcode\roman46=-125 +\setbox4=\vbox{\pdfprotrudechars=1 \noindent AA.\par} +\pdfprotrudechars=1 \lpcode\roman65=100 \rpcode\roman46=500 +\setbox7=\vbox{\noindent AA.\par\global\setbox8=\lastbox} +\setbox5=\hbox{\unhcopy8\unskip\unskip\message{COPIED-TAIL:\the\lastnodetype,\the\lastkern}} +\setbox6=\hbox{\unhbox8\unskip\unskip\message{MOVED-TAIL:\the\lastnodetype,\the\lastkern}} +\showbox0 \showbox1 \showbox2 \showbox3 \showbox4 \showbox5 \showbox6 +\shipout\vbox{\box0\kern3pt\box1\kern3pt\box2\kern3pt\box3\kern3pt\box4\kern3pt\box5\kern3pt\box6} +\end +"; + let log = dvi_shipout::run_reference_with_showboxes(&case, source, 7); + assert!(log.contains("GROUP-CODE:120 LEFT-CODE:100 RIGHT-CODE:500")); + for marker in ["COPIED-TAIL:13,0.0pt", "MOVED-TAIL:13,0.0pt"] { + assert!(log.contains(marker)); + } + let actual = Executor::new(State::initex().with_etex(), Limits::default()) + .with_native_pages() + .run( + SourceFile { + name: "margin-protrusion.tex".into(), + data: source.as_bytes().to_vec(), + }, + &mut Host::default(), + ) + .unwrap_or_else(|error| panic!("{case:?}: {error}")); + let lists = reports(&actual); + assert_eq!(lists.len(), 7); + for (report, line_count) in lists.into_iter().zip([2, 2, 1, 1, 1, 0, 0]) { + assert!(log.contains(&report.text), "{case:?}\nnative:\n{}\nreference:\n{log}", report.text); + assert_eq!( + report.text.lines().filter(|line| line.starts_with(r".\hbox(")).count(), + line_count, + ); + } + let page = dvi_shipout::compare_shipout(&case, actual) + .unwrap_or_else(|error| panic!("{case:?}: {error}")); + assert_eq!(page["glyphs"].as_u64(), Some(30)); + assert!(page["max_coordinate_error_sp"].as_i64().unwrap() <= 1); +} diff --git a/crates/texrra-tex-core/tests/execution_fractions.rs b/crates/texrra-tex-core/tests/execution_fractions.rs index 4ead3c3..6f46a74 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"], 31); + assert_eq!(payload["schema"], 32); 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 1f918b0..9ef159c 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"], 31); + assert_eq!(original["schema"], 32); for (schema, expected) in [ (1, "incompatible native format"), (2, "incompatible native format"), @@ -367,6 +367,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() (29, "incompatible native format"), (30, "incompatible native format"), (31, "glyph_unicode"), + (32, "glyph_unicode"), ] { let mut payload = original.clone(); payload["schema"] = schema.into(); diff --git a/crates/texrra-tex-core/tests/execution_vcenter.rs b/crates/texrra-tex-core/tests/execution_vcenter.rs index a880e37..8df9a3d 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"], 31); + assert_eq!(payload["schema"], 32); let executor = FormatImage::decode(&bytes) .unwrap() .new_job( diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index fa9a45e..a597517 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1126,6 +1126,45 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode [原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿) [pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143) +### 原生段落边缘悬挂 + +`\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平 +列表。模式1在装盒时加入有符号边缘 kern,模式2也在断行搜索时计算 +实际边缘量。使用当前字体 quad、实际边缘字形和嵌套横盒。拆开横盒时 +去掉本层边缘 kern,保留原列表其余节点。模式2的缓存键包括实际边缘 +投影,字体槽或活参数改变后重新选择断点。 +[pdfTeX 的边缘宽度和节点](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L19387-L19430) +[pdfTeX 的断行短缺量](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L23363-L23369) + +定向列表和 DVI 7项、格式3项全部通过。新用例的7个原始盒及30个 +实际字形与 pdfTeX 对齐,最大坐标差为0 sp。冻结的 PDF 文档8个词框 +与实际原生输出坐标完全一致。比对脚本首轮误把正常 showbox 退出 +状态当失败,使用保存的文件和完整输出继续核对。最小格式读取需要 +显式 PDF 模式,从同一个此前保存的格式读回左代码100和右代码−125。 +真实未修改的 pdflatex.ini 生成 schema32,继续读取已发布27/28/31。 + +基于原样 A4 主文件和子文件附加参考段落,实际预览修改左边缘的 +字体代码后,模式2从一行改成两行。该次修改仍复用849626步,发布 +PDF、SVG、来源映射和 aux 与独立零复用全量一致。更早的两个短文档 +对照也得到同样的断行与输出,保留实际复用步数为零的证据。 + +原样 arXiv、ACL 和 NeurIPS 2025 均越过 `\MT@protrudechars`,下一处 +为 `\MT@adjustspacing` 对应的 `\pdfadjustspacing`。已冻结真实 +pdfTeX 字宽伸缩对照,4个盒分别显示0、+50、−50、0千分比,包含 +字形 `\efcode` 为零的情形。实际 PDF 词框同样反映伸展和收缩。 +[下一处上游字体伸缩](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L16327-L16385) + +按20份组合代码和测试的确切指纹合入主线。发布阶段保留原样矩阵, +此次沿用已有参考,只运行受影响的三份样稿及对应定向。 +回执在 `target/p3-pdf-protrusion-native`。 + +- 原始绘制 `paint-receipt.json` 为 `2b54c5ccab28e6cc6699f9c748761962bae04f004a32d0c1428230cc264ef034` +- 原样格式 `format/receipt.json` 为 `2ec1b3861460dad8490f030dac802d53e24e3c43547220146ccadc1f988b4b73` +- 实际 PDF `actual-pdf/receipt.json` 为 `869a6824cc1ff4348613dd802ccf463ad3c5a16f0a35265f3db4b837ab1c7e80` +- 原样样稿 `publisher/receipt.json` 为 `885c1780af905b9d7a5c22cfc0584c67f5edc8393cbbc624692746af0a55eb96` +- A4 编辑 `edited-font-codes-a4/receipt.json` 为 `57464a38938db16e0f02b1138caa7f99760b72b17f61934b6ede2f550af7263f` +- 字宽伸缩参考 `target/p3-pdf-font-expansion-reference/receipt.json` 为 `27a8757e73f54e43b865e01d463b809d60c31962467edb6466250f7b876811a2` + ### 会话内复用实际 Type 1 字体解析 逐版读取并核对真实 PFB 后,以路径、字节数和 SHA-256 复用 Type 1 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index ed80f26..a486921 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -433,6 +433,15 @@ pdfTeX 对照字节一致。两项编译随后在实际 `\pdfprotrudechars` 的 本次主要核对正常部署及编辑取消,复用冻结对照。 [编译与取消证据](P2_M1_PROGRESS.md#正常发布入口的可取消-pdftex-匹配) +### arXiv、ACL 与 NeurIPS 的边缘悬挂 + +schema32 的正常入口继续执行三份已有官方样例。三份均越过 +microtype 的边缘悬挂设置,随后停在字宽伸缩 +`\MT@adjustspacing`。同一版的独立 pdfTeX 对照核对真实断点、 +边缘 kern 和物理 PDF 词框。受影响样稿的源指纹及实际诊断见 +`target/p3-pdf-protrusion-native/publisher/receipt.json`。 +[阶段证据](P2_M1_PROGRESS.md#原生段落边缘悬挂) + ### IEEE 双栏期刊与 CVPR 会议的实时会话对照 使用矩阵中同一原样输入、TeX 格式和已验证的字体资源,验证编辑后