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::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;
@@ -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<DiagnosticNode> {
},
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(" ");
@@ -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)?;
@@ -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(())
@@ -407,6 +407,8 @@ impl Executor {
| Font
| Fontdimen
| Hyphenchar
| Lpcode
| Rpcode
| Skewchar
| Textfont
| Scriptfont
@@ -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| {
@@ -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
@@ -223,6 +223,8 @@ impl Executor {
| Primitive::Prevgraf
| Primitive::Spacefactor
| Primitive::Hyphenchar
| Primitive::Lpcode
| Primitive::Rpcode
| Primitive::Skewchar
)
)
@@ -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<FontResource>,
parameter_words: usize,
limits: FontLimits,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
protrusion: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
}
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;
@@ -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)]
@@ -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<Parameter, ParameterValue>,
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<Parameter, ParameterValue>,
(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::<i64>() > 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,
&parameters,
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(&parameters, 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,
&parameters,
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!()
@@ -47,6 +47,7 @@ type Path = Option<Vec<(Break, i32)>>;
struct Entry {
hash: u64,
nodes: Vec<BreakNode>,
margins: Option<protrusion::Search>,
parameters: BTreeMap<Parameter, ParameterValue>,
shape: Vec<ParagraphShapeLine>,
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<Parameter, ParameterValue>,
state: &State,
shape: &[ParagraphShapeLine],
pass: u8,
work: &mut usize,
@@ -267,14 +272,16 @@ pub(super) fn solve(
cache: Option<&LineBreakCache>,
) -> Result<Path, String> {
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,
@@ -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)?;
i += usize::from(*replacement_count);
}
TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_) => {}
TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_)
| TextNode::MarginKern { .. } => {}
}
i += 1;
}
@@ -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()
@@ -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),