Measure external font expansion at paragraph break margins
This commit is contained in:
1 parent
91b3e6a8fe
commit
1e4c113b27
6 files changed
+242
-91
No files matched your search
@@ -267,21 +267,24 @@ pub(super) fn candidate_widths(
|
||||
pub(super) fn solve(
|
||||
source: &[TextNode],
|
||||
parameters: &BTreeMap<Parameter, ParameterValue>,
|
||||
state: &State,
|
||||
state: &mut State,
|
||||
files: &mut impl SourceProvider,
|
||||
shape: &[ParagraphShapeLine],
|
||||
pass: u8,
|
||||
work: &mut usize,
|
||||
previous_lines: usize,
|
||||
trace: &mut super::super::paragraph_trace::Tracer<'_>,
|
||||
trace: &mut super::super::paragraph_trace::Tracer,
|
||||
cache: Option<&LineBreakCache>,
|
||||
) -> Result<Path, String> {
|
||||
let nodes: Vec<_> = source.iter().map(BreakNode::project).collect();
|
||||
let margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1)
|
||||
.then(|| protrusion::Search::new(state, source));
|
||||
let expansion = (parameters[&Parameter::Pdfadjustspacing].width() > 1
|
||||
&& state.fonts.has_expansion())
|
||||
.then(|| expansion::Search::new(state, source))
|
||||
.transpose()?;
|
||||
let expand_margins = expansion.is_some() && state.fonts.has_external_expansions();
|
||||
let mut margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1)
|
||||
.then(|| protrusion::Search::new(state, source, expand_margins))
|
||||
.transpose()?;
|
||||
let retained = nodes.len()
|
||||
+ shape.len()
|
||||
+ margins.as_ref().map_or(0, protrusion::Search::len)
|
||||
@@ -289,6 +292,9 @@ pub(super) fn solve(
|
||||
let mut hash = None;
|
||||
if let Some(cache) = cache
|
||||
&& retained <= RETAINED_NODES
|
||||
// A pass that can assign a font has job effects. Only reuse search
|
||||
// once all projected variations come from the live font table.
|
||||
&& !margins.as_ref().is_some_and(protrusion::Search::needs_fonts)
|
||||
&& parameters[&Parameter::Tracingparagraphs].width() <= 0
|
||||
{
|
||||
let mut hasher = DefaultHasher::new();
|
||||
@@ -326,8 +332,10 @@ pub(super) fn solve(
|
||||
let result = break_lines(
|
||||
source,
|
||||
&nodes,
|
||||
margins.as_ref(),
|
||||
margins.as_mut(),
|
||||
expansion.as_ref(),
|
||||
state,
|
||||
files,
|
||||
parameters,
|
||||
shape,
|
||||
pass,
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::{math_engine_tex::MathItem, native_font::NativeFont, pdf_device};
|
||||
use std::{collections::BTreeMap, ops::AddAssign, sync::Arc};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
struct Capacity {
|
||||
pub(super) struct Capacity {
|
||||
stretch: i64,
|
||||
shrink: i64,
|
||||
}
|
||||
@@ -43,20 +43,25 @@ impl Limits {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn residual(self, shortfall: i64, capacity: Capacity) -> i64 {
|
||||
fn residual(self, shortfall: i64, capacity: Capacity) -> Result<i64, String> {
|
||||
let (direction, limit, available) = if shortfall < 0 {
|
||||
(-1, self.shrink, capacity.shrink)
|
||||
} else {
|
||||
(1, self.stretch, capacity.stretch)
|
||||
};
|
||||
if available <= 0 || shortfall == 0 {
|
||||
return shortfall;
|
||||
return Ok(shortfall);
|
||||
}
|
||||
if available > shortfall.abs() {
|
||||
direction * (available / i64::from(limit / self.step)) / 2
|
||||
} else {
|
||||
shortfall - direction * available
|
||||
if available <= shortfall.abs() {
|
||||
return Ok(shortfall - direction * available);
|
||||
}
|
||||
// A nested margin glyph can contribute before an outer character
|
||||
// establishes the step. pdfTeX's initial limit and step are both -1.
|
||||
let steps = if self.step == 0 { 1 } else { limit / self.step };
|
||||
if steps == 0 {
|
||||
return Err("paragraph margin expansion has no limit in this direction".into());
|
||||
}
|
||||
Ok(direction * (available / i64::from(steps)) / 2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,8 +216,9 @@ impl Search {
|
||||
end: usize,
|
||||
post: Option<usize>,
|
||||
pre: Option<usize>,
|
||||
) -> i64 {
|
||||
let mut total = Capacity {
|
||||
mut total: Capacity,
|
||||
) -> Result<i64, String> {
|
||||
total += Capacity {
|
||||
stretch: self.prefix[end].stretch - self.prefix[start].stretch,
|
||||
shrink: self.prefix[end].shrink - self.prefix[start].shrink,
|
||||
};
|
||||
@@ -244,6 +250,80 @@ fn slot_ratio(state: &State, font: &NativeFont, slot: u8, line_ratio: i32) -> i3
|
||||
(magnitude + step / 2).div_euclid(step) as i32 * config.step * line_ratio.signum()
|
||||
}
|
||||
|
||||
/// Variation of a candidate's protrusion at its quantized font limits.
|
||||
/// pdfTeX uses the left protrusion code for this variation on both sides.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(super) enum MarginVariation {
|
||||
Measured(Capacity),
|
||||
Pending {
|
||||
amounts: [i32; 2],
|
||||
code: i32,
|
||||
original: i64,
|
||||
},
|
||||
}
|
||||
|
||||
impl MarginVariation {
|
||||
pub(super) fn project(state: &State, font: FontId, slot: u8) -> Result<Option<Self>, String> {
|
||||
if !state.fonts.has_external_expansion(font) {
|
||||
return Ok(None);
|
||||
}
|
||||
let face = state.fonts.glyph_font(font)?;
|
||||
let amounts = [slot_ratio(state, face, slot, 1000), slot_ratio(state, face, slot, -1000)];
|
||||
if amounts == [0, 0] {
|
||||
return Ok(None);
|
||||
}
|
||||
let quad = i64::from(state.fonts.font(font)?.quad());
|
||||
let code = state.fonts.protrusion_code(font, slot, false);
|
||||
let original = pdf_device::magnify(quad, code);
|
||||
let selected = |amount| -> Result<Option<i64>, String> {
|
||||
if amount == 0 {
|
||||
return Ok(Some(original));
|
||||
}
|
||||
let Some(variant) = state.fonts.external_variant(font, amount) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let quad = i64::from(state.fonts.font(variant)?.quad());
|
||||
Ok(Some(pdf_device::magnify(quad, code)))
|
||||
};
|
||||
Ok(Some(match (selected(amounts[0])?, selected(amounts[1])?) {
|
||||
(Some(wide), Some(narrow)) => Self::Measured(Capacity {
|
||||
stretch: original - wide,
|
||||
shrink: narrow - original,
|
||||
}),
|
||||
_ => Self::Pending { amounts, code, original },
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn resolve(
|
||||
&mut self,
|
||||
state: &mut State,
|
||||
font: FontId,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Capacity, String> {
|
||||
match *self {
|
||||
Self::Measured(capacity) => Ok(capacity),
|
||||
Self::Pending { amounts, code, original } => {
|
||||
let base = state.fonts.glyph_font(font)?.clone();
|
||||
let defaults = state.font_defaults();
|
||||
let mut selected = |amount| -> Result<i64, String> {
|
||||
if amount == 0 {
|
||||
return Ok(original);
|
||||
}
|
||||
let face = state.fonts.expansion_face(&base, amount, defaults, files)?;
|
||||
let quad = i64::from(state.fonts.font(face.id)?.quad());
|
||||
Ok(pdf_device::magnify(quad, code))
|
||||
};
|
||||
let capacity = Capacity {
|
||||
stretch: original - selected(amounts[0])?,
|
||||
shrink: selected(amounts[1])? - original,
|
||||
};
|
||||
*self = Self::Measured(capacity);
|
||||
Ok(capacity)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PackingFonts(BTreeMap<(FontId, i32), Arc<NativeFont>>);
|
||||
|
||||
@@ -298,21 +378,26 @@ pub(super) fn pack(
|
||||
) -> Result<(), String> {
|
||||
let (natural, stretch, _) = metrics(material, Default::default(), Default::default());
|
||||
let shortfall = target - natural;
|
||||
if shortfall == 0 || (shortfall > 0 && stretch[1..].iter().any(|width| *width != 0)) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut fonts = PackingFonts::default();
|
||||
let mut capacity = sum(state, material, None)?;
|
||||
for node in material.iter() {
|
||||
let TextNode::MarginKern { width, right, font, slot } = *node else {
|
||||
continue;
|
||||
};
|
||||
for (ratio, limit) in [(1000, &mut capacity.stretch), (-1000, &mut capacity.shrink)] {
|
||||
if let Some((expanded, _)) = fonts.external_margin(state, font, slot, right, ratio, files)? {
|
||||
*limit += i64::from(expanded) - i64::from(width);
|
||||
let mut capacity = Capacity::default();
|
||||
if state.fonts.has_external_expansions() {
|
||||
// Measuring the actual margin assigns its extreme variants before
|
||||
// glue setting decides whether to perform any substitution.
|
||||
for node in material.iter() {
|
||||
let TextNode::MarginKern { width, right, font, slot } = *node else {
|
||||
continue;
|
||||
};
|
||||
for (ratio, limit) in [(1000, &mut capacity.stretch), (-1000, &mut capacity.shrink)] {
|
||||
if let Some((expanded, _)) = fonts.external_margin(state, font, slot, right, ratio, files)? {
|
||||
*limit += i64::from(expanded) - i64::from(width);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if shortfall == 0 || (shortfall > 0 && stretch[1..].iter().any(|width| *width != 0)) {
|
||||
return Ok(());
|
||||
}
|
||||
capacity += sum(state, material, None)?;
|
||||
let available = if shortfall < 0 {
|
||||
capacity.shrink
|
||||
} else {
|
||||
|
||||
@@ -158,39 +158,60 @@ pub(super) fn margin_kern(
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub(super) struct EdgeMeasure {
|
||||
pub(super) width: i32,
|
||||
expanding: Option<(FontId, u8)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
struct Projected {
|
||||
left: Option<(usize, i32)>,
|
||||
right: Option<(usize, i32)>,
|
||||
pre: Option<i32>,
|
||||
post: Option<i32>,
|
||||
left: Option<(usize, EdgeMeasure)>,
|
||||
right: Option<(usize, EdgeMeasure)>,
|
||||
pre: Option<EdgeMeasure>,
|
||||
post: Option<EdgeMeasure>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
pub(super) struct Search(Vec<Projected>);
|
||||
pub(super) struct Search {
|
||||
widths: Vec<Projected>,
|
||||
variations: BTreeMap<(FontId, u8), expansion::MarginVariation>,
|
||||
}
|
||||
|
||||
impl Search {
|
||||
pub(super) fn new(state: &State, nodes: &[TextNode]) -> Self {
|
||||
pub(super) fn new(state: &State, nodes: &[TextNode], expand: bool) -> Result<Self, String> {
|
||||
let mut widths = vec![Projected::default(); nodes.len() + 1];
|
||||
let mut variations = BTreeMap::new();
|
||||
let mut project = |edge: Edge, right| -> Result<EdgeMeasure, String> {
|
||||
use std::collections::btree_map::Entry;
|
||||
let width = edge.width(state, right);
|
||||
let mut expanding = None;
|
||||
if expand && let Edge::Glyph(font, slot) = edge {
|
||||
let key = (font, slot);
|
||||
match variations.entry(key) {
|
||||
Entry::Occupied(_) => expanding = Some(key),
|
||||
Entry::Vacant(entry) => {
|
||||
if let Some(variation) = expansion::MarginVariation::project(state, font, slot)? {
|
||||
entry.insert(variation);
|
||||
expanding = Some(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(EdgeMeasure { width, expanding })
|
||||
};
|
||||
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)))
|
||||
Some((i, project(edge, 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));
|
||||
if let TextNode::Discretionary { pre_break, post_break, .. } = node {
|
||||
widths[i].pre = pre_break.last()
|
||||
.map(|node| project(Edge::character(node), true)).transpose()?;
|
||||
widths[i].post = post_break.first()
|
||||
.map(|node| project(Edge::character(node), false)).transpose()?;
|
||||
}
|
||||
}
|
||||
for (i, node) in nodes.iter().enumerate().rev() {
|
||||
@@ -198,36 +219,54 @@ impl Search {
|
||||
widths[i].left = if matches!(edge, Edge::Skip) {
|
||||
widths[i + 1].left
|
||||
} else {
|
||||
Some((i, edge.width(state, false)))
|
||||
Some((i, project(edge, false)?))
|
||||
};
|
||||
}
|
||||
Self(widths)
|
||||
Ok(Self { widths, variations })
|
||||
}
|
||||
|
||||
pub(super) fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
self.widths.len() + self.variations.len()
|
||||
}
|
||||
|
||||
pub(super) fn width(
|
||||
pub(super) fn needs_fonts(&self) -> bool {
|
||||
self.variations.values().any(|v| matches!(v, expansion::MarginVariation::Pending { .. }))
|
||||
}
|
||||
|
||||
pub(super) fn edges(
|
||||
&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
|
||||
) -> [EdgeMeasure; 2] {
|
||||
let left = post.and_then(|i| self.widths[i].post).or_else(|| {
|
||||
self.widths[start].left
|
||||
.filter(|(i, _)| *i < end)
|
||||
.map(|(_, width)| width)
|
||||
.map(|(_, edge)| edge)
|
||||
});
|
||||
let right = pre.and_then(|i| self.0[i].pre).or_else(|| {
|
||||
self.0[end]
|
||||
.right
|
||||
let right = pre.and_then(|i| self.widths[i].pre).or_else(|| {
|
||||
self.widths[end].right
|
||||
.filter(|(i, _)| right_visible && *i >= start)
|
||||
.map(|(_, width)| width)
|
||||
.map(|(_, edge)| edge)
|
||||
});
|
||||
i64::from(left.unwrap_or(0)) + i64::from(right.unwrap_or(0))
|
||||
[left.unwrap_or_default(), right.unwrap_or_default()]
|
||||
}
|
||||
|
||||
pub(super) fn variation(
|
||||
&mut self,
|
||||
edges: [EdgeMeasure; 2],
|
||||
state: &mut State,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<expansion::Capacity, String> {
|
||||
let mut total = expansion::Capacity::default();
|
||||
for edge in edges {
|
||||
if let Some(key) = edge.expanding {
|
||||
total += self.variations.get_mut(&key).expect("projected margin glyph")
|
||||
.resolve(state, key.0, files)?;
|
||||
}
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user