Apply native font protrusion during line breaking and packing

This commit is contained in:
gloamxun committed 2026-11-20 17:18:25 +08:00
1 parent 361e8d070f
commit 4777d66fc8
22 files changed
+441 -32

No files matched your search

@@ -333,6 +333,7 @@ impl NativeBox {
TextNode::Indent(w) TextNode::Indent(w)
| TextNode::MathBoundary { width: w, .. } | TextNode::MathBoundary { width: w, .. }
| TextNode::AccentKern(w) | TextNode::AccentKern(w)
| TextNode::MarginKern { width: w, .. }
| TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox { | TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox {
width: *w as i64, width: *w as i64,
..HorizontalBox::default() ..HorizontalBox::default()
@@ -614,6 +615,7 @@ pub(super) fn hpack(
TextNode::Indent(w) TextNode::Indent(w)
| TextNode::MathBoundary { width: w, .. } | TextNode::MathBoundary { width: w, .. }
| TextNode::AccentKern(w) | TextNode::AccentKern(w)
| TextNode::MarginKern { width: w, .. }
| TextNode::Kern { width: w, .. } => width += *w as i64, | TextNode::Kern { width: w, .. } => width += *w as i64,
TextNode::Glue(g) | TextNode::NamedGlue(g, _) => { TextNode::Glue(g) | TextNode::NamedGlue(g, _) => {
width += g.width as i64; width += g.width as i64;
@@ -51,6 +51,7 @@ pub enum DiagnosticNode {
Output(OutputNode), Output(OutputNode),
Unsupported(String), Unsupported(String),
AccentKern(i32), AccentKern(i32),
MarginKern { width: i32, right: bool },
} }
/// A semantic view, without recursively copying the box's painted contents. /// A semantic view, without recursively copying the box's painted contents.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -211,6 +212,10 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
}, },
TextNode::Leaders(leader) => leader_node(leader), TextNode::Leaders(leader) => leader_node(leader),
TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width), TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width),
TextNode::MarginKern { width, right, .. } => DiagnosticNode::MarginKern {
width: *width,
right: *right,
},
TextNode::Kern { width, explicit } => DiagnosticNode::Kern { TextNode::Kern { width, explicit } => DiagnosticNode::Kern {
width: *width, width: *width,
explicit: *explicit, explicit: *explicit,
@@ -473,6 +478,11 @@ impl Printer<'_> {
&format!("{prefix}."), &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) => { DiagnosticNode::AccentKern(width) => {
self.command("kern"); self.command("kern");
self.literal(" "); self.literal(" ");
@@ -1988,6 +1988,16 @@ impl Executor {
Ok(()) 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( fn internal_integer_from(
&mut self, &mut self,
next: InputToken, next: InputToken,
@@ -2012,6 +2022,10 @@ impl Executor {
} }
Ok(value.width()) 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)) => { Meaning::Primitive(p @ (Primitive::Hyphenchar | Primitive::Skewchar)) => {
let font = self.font_identifier(files)?; let font = self.font_identifier(files)?;
let values = self.state.font_integers(font); let values = self.state.font_integers(font);
@@ -3847,6 +3861,12 @@ impl Executor {
matches!(primitive, Some(Edef | Xdef)), matches!(primitive, Some(Edef | Xdef)),
files, 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) => { Some(Hyphenchar | Skewchar) => {
let font = self.font_identifier(files)?; let font = self.font_identifier(files)?;
self.optional_equals(files)?; self.optional_equals(files)?;
@@ -165,7 +165,9 @@ impl Executor {
.as_mut() .as_mut()
.expect("unhbox starts an actual paragraph") .expect("unhbox starts an actual paragraph")
.nodes .nodes
.extend(nodes), .extend(
nodes.into_iter().filter(|node| !matches!(node, TextNode::MarginKern { .. })),
),
BoxContent::Vertical(nodes) => self.append_unboxed_vertical(nodes), BoxContent::Vertical(nodes) => self.append_unboxed_vertical(nodes),
} }
Ok(()) Ok(())
@@ -407,6 +407,8 @@ impl Executor {
| Font | Font
| Fontdimen | Fontdimen
| Hyphenchar | Hyphenchar
| Lpcode
| Rpcode
| Skewchar | Skewchar
| Textfont | Textfont
| Scriptfont | Scriptfont
@@ -22,6 +22,7 @@ impl Tail {
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false), | TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false),
TextNode::Kern { width, .. } | TextNode::AccentKern(width) => Self::Kern(*width), TextNode::Kern { width, .. } | TextNode::AccentKern(width) => Self::Kern(*width),
TextNode::Penalty(n) => Self::Penalty(*n), TextNode::Penalty(n) => Self::Penalty(*n),
TextNode::MarginKern { .. } => Self::Other(15),
TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }), TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }),
TextNode::MathChar(_) => Self::Other(0), TextNode::MathChar(_) => Self::Other(0),
TextNode::Box(b) => Self::Other(b.native_box.as_ref().map_or(1, |b| { TextNode::Box(b) => Self::Other(b.native_box.as_ref().map_or(1, |b| {
@@ -783,7 +783,7 @@ impl Executor {
| Lccode | Uccode | Lowercase | Uppercase | Hyphenation | Patterns | Mathcode | Lccode | Uccode | Lowercase | Uppercase | Hyphenation | Patterns | Mathcode
| Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip | Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip
| Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline | 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 | Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage | Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage
| Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen | Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen
@@ -223,6 +223,8 @@ impl Executor {
| Primitive::Prevgraf | Primitive::Prevgraf
| Primitive::Spacefactor | Primitive::Spacefactor
| Primitive::Hyphenchar | Primitive::Hyphenchar
| Primitive::Lpcode
| Primitive::Rpcode
| Primitive::Skewchar | Primitive::Skewchar
) )
) )
@@ -6,7 +6,7 @@ use crate::{
tfm::{FontSize, TfmMetrics}, tfm::{FontSize, TfmMetrics},
}; };
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::sync::Arc; use std::{collections::BTreeMap, sync::Arc};
#[derive( #[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
@@ -144,6 +144,8 @@ pub struct FontCatalog {
resources: Vec<FontResource>, resources: Vec<FontResource>,
parameter_words: usize, parameter_words: usize,
limits: FontLimits, limits: FontLimits,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
protrusion: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
} }
impl Default for FontCatalog { impl Default for FontCatalog {
fn default() -> Self { fn default() -> Self {
@@ -173,6 +175,7 @@ impl FontCatalog {
resources: Vec::new(), resources: Vec::new(),
parameter_words: 7, parameter_words: 7,
limits, limits,
protrusion: BTreeMap::new(),
}) })
} }
pub fn fonts(&self) -> &[FontInstance] { pub fn fonts(&self) -> &[FontInstance] {
@@ -316,6 +319,18 @@ impl FontCatalog {
self.fonts[id.0 as usize].parameters[index] = value; self.fonts[id.0 as usize].parameters[index] = value;
Ok(()) 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> { pub fn set_integers(&mut self, id: FontId, integers: FontIntegers) -> Result<(), String> {
self.font(id)?; self.font(id)?;
self.fonts[id.0 as usize].integers = integers; self.fonts[id.0 as usize].integers = integers;
@@ -8,8 +8,8 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak}, sync::{Arc, Mutex, OnceLock, Weak},
}; };
const SCHEMA: u32 = 31; const SCHEMA: u32 = 32;
const COMPATIBLE_SCHEMAS: [u32; 3] = [27, 28, SCHEMA]; const COMPATIBLE_SCHEMAS: [u32; 4] = [27, 28, 31, SCHEMA];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)] #[derive(serde::Serialize, serde::Deserialize)]
@@ -4,6 +4,7 @@ use crate::{HorizontalBox, Paragraph, ParagraphFont};
use std::collections::BTreeMap; use std::collections::BTreeMap;
mod break_cache; mod break_cache;
mod protrusion;
use break_cache::BreakNode; use break_cache::BreakNode;
pub use break_cache::{LineBreakCache, LineBreakWork}; pub use break_cache::{LineBreakCache, LineBreakWork};
@@ -72,6 +73,7 @@ pub enum TextNode {
}, },
/// Spacing owned by a text accent and protected from leading discard. /// Spacing owned by a text accent and protected from leading discard.
AccentKern(i32), AccentKern(i32),
MarginKern { width: i32, right: bool, font: FontId, slot: u8 },
} }
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NativeParagraph { pub struct NativeParagraph {
@@ -386,6 +388,7 @@ fn width(n: &TextNode) -> i64 {
TextNode::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width), TextNode::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width),
TextNode::Kern { width: n, .. } TextNode::Kern { width: n, .. }
| TextNode::AccentKern(n) | TextNode::AccentKern(n)
| TextNode::MarginKern { width: n, .. }
| TextNode::MathBoundary { width: n, .. } | TextNode::MathBoundary { width: n, .. }
| TextNode::Indent(n) => *n as i64, | TextNode::Indent(n) => *n as i64,
_ => 0, _ => 0,
@@ -553,6 +556,7 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64)
fn break_lines( fn break_lines(
nodes: &[TextNode], nodes: &[TextNode],
projected: &[BreakNode], projected: &[BreakNode],
margins: Option<&protrusion::Search>,
p: &BTreeMap<Parameter, ParameterValue>, p: &BTreeMap<Parameter, ParameterValue>,
shape: &[ParagraphShapeLine], shape: &[ParagraphShapeLine],
pass: u8, pass: u8,
@@ -732,7 +736,14 @@ fn break_lines(
if target < 0 && shape.is_empty() { if target < 0 && shape.is_empty() {
return Err("negative native paragraph measure".into()); 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 infinite = stretch[1..].iter().any(|n| *n != 0);
let bad = if delta >= 0 { let bad = if delta >= 0 {
if infinite { if infinite {
@@ -918,17 +929,32 @@ fn pack(
p: &BTreeMap<Parameter, ParameterValue>, p: &BTreeMap<Parameter, ParameterValue>,
(indent, target): (i64, i64), (indent, target): (i64, i64),
last: bool, last: bool,
terminal_marker: bool,
ends_in_pre_break: bool,
state: &State, state: &State,
span: Span, span: Span,
) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial), String> { ) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial, bool), String> {
let left = p[&Parameter::Leftskip].glue(); let left = p[&Parameter::Leftskip].glue();
let mut material = Vec::new(); let mut material = Vec::new();
if left != Glue::default() { if left != Glue::default() {
material.push(TextNode::NamedGlue(left, Parameter::Leftskip)); 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 { if last {
material.push(TextNode::Penalty(10000)); 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( material.push(TextNode::NamedGlue(
p[&Parameter::Parfillskip].glue(), p[&Parameter::Parfillskip].glue(),
Parameter::Parfillskip, Parameter::Parfillskip,
@@ -939,6 +965,7 @@ fn pack(
Parameter::Rightskip, Parameter::Rightskip,
)); ));
let (material, adjustments) = super::marks::extract(material); let (material, adjustments) = super::marks::extract(material);
let shrinking = material.iter().map(width).sum::<i64>() > target;
let mut b = super::boxes::hpack( let mut b = super::boxes::hpack(
material, material,
super::boxes::PackSpec::To( super::boxes::PackSpec::To(
@@ -962,7 +989,7 @@ fn pack(
centered: false, centered: false,
right_aligned: false, right_aligned: false,
}; };
Ok((paragraph, b, adjustments)) Ok((paragraph, b, adjustments, shrinking))
} }
// TeX init_math scans natural widths and visible nodes, independently of // TeX init_math scans natural widths and visible nodes, independently of
// rounded glue-setting coordinates. Stretch/shrink before the last visible // 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( if let Some(path) = break_cache::solve(
&b.nodes, &b.nodes,
&parameters, &parameters,
state,
shape, shape,
pass, pass,
&mut work, &mut work,
@@ -1114,13 +1142,6 @@ pub(super) fn finish(
let mut packed_shrinking = Vec::new(); let mut packed_shrinking = Vec::new();
let mut pre_display_size = -1073741823; let mut pre_display_size = -1073741823;
for (i, (point, bad)) in path.iter().enumerate() { 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( let material = line_material(
&b.nodes, &b.nodes,
start, start,
@@ -1130,23 +1151,26 @@ pub(super) fn finish(
true, true,
point.zero_tail, point.zero_tail,
); );
let (natural, stretch, shrink) = metrics(&material, left, right);
let dimensions = geometry(&parameters, shape, i + b.previous_lines); let dimensions = geometry(&parameters, shape, i + b.previous_lines);
let target = dimensions.1; let terminal_marker = point.zero_tail.is_some()
let (set, packed_bad, excess) = || matches!(b.nodes.get(point.end), Some(TextNode::Penalty(_)));
super::boxes::setting(target - natural, stretch, [shrink, 0, 0, 0], true); let ends_in_pre_break = point.pre_break.is_some_and(|index| {
packed_diagnostic.push(target != natural && set.order == 0); matches!(&b.nodes[index], TextNode::Discretionary { pre_break, .. } if !pre_break.is_empty())
packed_shrinking.push(target < natural); });
packed_badness.push(packed_bad); let (line, line_box, adjustments, shrinking) = pack(
packed_excess.push(excess);
let (line, line_box, adjustments) = pack(
&material, &material,
&parameters, &parameters,
dimensions, dimensions,
i + 1 == path.len(), i + 1 == path.len(),
terminal_marker,
ends_in_pre_break,
state, state,
b.span, 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() { if i + 1 == path.len() {
let BoxContent::Horizontal(material) = &line_box.content else { let BoxContent::Horizontal(material) = &line_box.content else {
unreachable!() unreachable!()
@@ -47,6 +47,7 @@ type Path = Option<Vec<(Break, i32)>>;
struct Entry { struct Entry {
hash: u64, hash: u64,
nodes: Vec<BreakNode>, nodes: Vec<BreakNode>,
margins: Option<protrusion::Search>,
parameters: BTreeMap<Parameter, ParameterValue>, parameters: BTreeMap<Parameter, ParameterValue>,
shape: Vec<ParagraphShapeLine>, shape: Vec<ParagraphShapeLine>,
previous_lines: usize, previous_lines: usize,
@@ -57,7 +58,9 @@ struct Entry {
impl Entry { impl Entry {
fn retained_nodes(&self) -> usize { 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::NamedGlue(glue, _)
| TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue), | TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue),
TextNode::AccentKern(width) => Self::AccentKern(*width), TextNode::AccentKern(width) => Self::AccentKern(*width),
TextNode::MarginKern { width, .. } => Self::Content(i64::from(*width)),
TextNode::Kern { width, explicit } => Self::Kern { TextNode::Kern { width, explicit } => Self::Kern {
width: *width, width: *width,
explicit: *explicit, explicit: *explicit,
@@ -259,6 +263,7 @@ pub(super) fn candidate_widths(
pub(super) fn solve( pub(super) fn solve(
source: &[TextNode], source: &[TextNode],
parameters: &BTreeMap<Parameter, ParameterValue>, parameters: &BTreeMap<Parameter, ParameterValue>,
state: &State,
shape: &[ParagraphShapeLine], shape: &[ParagraphShapeLine],
pass: u8, pass: u8,
work: &mut usize, work: &mut usize,
@@ -267,14 +272,16 @@ pub(super) fn solve(
cache: Option<&LineBreakCache>, cache: Option<&LineBreakCache>,
) -> Result<Path, String> { ) -> Result<Path, String> {
let nodes: Vec<_> = source.iter().map(BreakNode::project).collect(); 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; let mut hash = None;
if let Some(cache) = cache if let Some(cache) = cache
&& retained <= RETAINED_NODES && retained <= RETAINED_NODES
&& parameters[&Parameter::Tracingparagraphs].width() <= 0 && parameters[&Parameter::Tracingparagraphs].width() <= 0
{ {
let mut hasher = DefaultHasher::new(); 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(); let key = hasher.finish();
hash = Some(key); hash = Some(key);
let mut cache = cache let mut cache = cache
@@ -288,6 +295,7 @@ pub(super) fn solve(
&& entry.parameters == *parameters && entry.parameters == *parameters
&& entry.shape == shape && entry.shape == shape
&& entry.nodes == nodes && entry.nodes == nodes
&& entry.margins == margins
}) { }) {
let entry = cache.entries.remove(index).unwrap(); let entry = cache.entries.remove(index).unwrap();
*work += entry.edges; *work += entry.edges;
@@ -306,6 +314,7 @@ pub(super) fn solve(
let result = break_lines( let result = break_lines(
source, source,
&nodes, &nodes,
margins.as_ref(),
parameters, parameters,
shape, shape,
pass, pass,
@@ -335,6 +344,7 @@ pub(super) fn solve(
cache.entries.push_back(Entry { cache.entries.push_back(Entry {
hash, hash,
nodes, nodes,
margins,
parameters: parameters.clone(), parameters: parameters.clone(),
shape: shape.to_vec(), shape: shape.to_vec(),
previous_lines, previous_lines,
@@ -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<TextNode> {
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<i32>,
post: Option<i32>,
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub(super) struct Search(Vec<Projected>);
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<usize>,
pre: Option<usize>,
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))
}
}
@@ -230,7 +230,8 @@ impl<'a> Tracer<'a> {
self.short(post_break, out)?; self.short(post_break, out)?;
i += usize::from(*replacement_count); i += usize::from(*replacement_count);
} }
TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_) => {} TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_)
| TextNode::MarginKern { .. } => {}
} }
i += 1; i += 1;
} }
@@ -111,6 +111,7 @@ pub enum Parameter {
Baselineskip, Baselineskip,
Lineskip, Lineskip,
Tabskip, Tabskip,
Pdfprotrudechars,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue { pub enum ParameterValue {
@@ -225,6 +226,7 @@ impl Parameter {
Self::Baselineskip, Self::Baselineskip,
Self::Lineskip, Self::Lineskip,
Self::Tabskip, Self::Tabskip,
Self::Pdfprotrudechars,
]; ];
pub fn name(self) -> String { pub fn name(self) -> String {
format!("{self:?}").to_ascii_lowercase() format!("{self:?}").to_ascii_lowercase()
@@ -315,6 +315,8 @@ pub enum Primitive {
Accent, Accent,
Pdfmatch, Pdfmatch,
Pdflastmatch, Pdflastmatch,
Lpcode,
Rpcode,
} }
impl Primitive { impl Primitive {
@@ -735,6 +737,8 @@ impl Default for State {
("eqno", Eqno), ("eqno", Eqno),
("leqno", Leqno), ("leqno", Leqno),
("hyphenchar", Hyphenchar), ("hyphenchar", Hyphenchar),
("lpcode", Lpcode),
("rpcode", Rpcode),
("fontname", Fontname), ("fontname", Fontname),
("fontdimen", Fontdimen), ("fontdimen", Fontdimen),
("skewchar", Skewchar), ("skewchar", Skewchar),
@@ -357,3 +357,63 @@ fn text_accents_preserve_font_metrics_kerns_and_paint_positions() {
assert_eq!(pages[0]["glyphs"].as_u64(), Some(15)); assert_eq!(pages[0]["glyphs"].as_u64(), Some(15));
assert!(pages[0]["max_coordinate_error_sp"].as_i64().unwrap() <= 1); 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);
}
@@ -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 envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value = let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); 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 state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes) let loaded = FormatImage::decode(&bytes)
.unwrap() .unwrap()
@@ -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 envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
let original: serde_json::Value = let original: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(original["schema"], 31); assert_eq!(original["schema"], 32);
for (schema, expected) in [ for (schema, expected) in [
(1, "incompatible native format"), (1, "incompatible native format"),
(2, "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"), (29, "incompatible native format"),
(30, "incompatible native format"), (30, "incompatible native format"),
(31, "glyph_unicode"), (31, "glyph_unicode"),
(32, "glyph_unicode"),
] { ] {
let mut payload = original.clone(); let mut payload = original.clone();
payload["schema"] = schema.into(); payload["schema"] = schema.into();
@@ -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 envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value = let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); 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) let executor = FormatImage::decode(&bytes)
.unwrap() .unwrap()
.new_job( .new_job(
+39
View File
@@ -1126,6 +1126,45 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode
[原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿) [原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿)
[pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143) [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 字体解析 ### 会话内复用实际 Type 1 字体解析
逐版读取并核对真实 PFB 后,以路径、字节数和 SHA-256 复用 Type 1 逐版读取并核对真实 PFB 后,以路径、字节数和 SHA-256 复用 Type 1
+9
View File
@@ -433,6 +433,15 @@ pdfTeX 对照字节一致。两项编译随后在实际 `\pdfprotrudechars` 的
本次主要核对正常部署及编辑取消,复用冻结对照。 本次主要核对正常部署及编辑取消,复用冻结对照。
[编译与取消证据](P2_M1_PROGRESS.md#正常发布入口的可取消-pdftex-匹配) [编译与取消证据](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 会议的实时会话对照 ### IEEE 双栏期刊与 CVPR 会议的实时会话对照
使用矩阵中同一原样输入、TeX 格式和已验证的字体资源,验证编辑后 使用矩阵中同一原样输入、TeX 格式和已验证的字体资源,验证编辑后