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

@@ -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))
}
}