Measure native XeTeX glyphs and break after mapped dashes
This commit is contained in:
1 parent
c548ca8e9f
commit
facecbf790
9 files changed
+332
-35
No files matched your search
@@ -608,8 +608,9 @@ pub(super) fn hpack(
|
||||
}
|
||||
TextNode::OpenType(run) => {
|
||||
width += run.width;
|
||||
height = height.max(run.font.ascent);
|
||||
depth = depth.max(run.font.descent);
|
||||
let [run_height, run_depth] = run.height_depth();
|
||||
height = height.max(run_height);
|
||||
depth = depth.max(run_depth);
|
||||
}
|
||||
TextNode::Rule(r) => {
|
||||
let (w, h, d) = r.dimensions();
|
||||
|
||||
@@ -387,6 +387,12 @@ impl Executor {
|
||||
self.reads.insert(Dependency::FontResources);
|
||||
self.reads.insert(Dependency::TextFont);
|
||||
if let Some(font) = opentype {
|
||||
if self.state.input_profile() == InputProfile::XeTeX {
|
||||
self.reads.insert(Dependency::Parameter(Parameter::XeTeXuseglyphmetrics));
|
||||
if !self.restricted() {
|
||||
self.reads.insert(Dependency::Parameter(Parameter::XeTeXdashbreakstate));
|
||||
}
|
||||
}
|
||||
return self.paragraph.as_mut().unwrap()
|
||||
.opentype_character(c, TokenOrigin::from(token), &self.state, font)
|
||||
.map_err(|e| self.error(e, token.invocation.unwrap_or(token.span)));
|
||||
|
||||
@@ -8,9 +8,9 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 61;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 30] = [
|
||||
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, SCHEMA,
|
||||
const SCHEMA: u32 = 62;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 31] = [
|
||||
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, SCHEMA,
|
||||
];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Native horizontal material and paragraph breaking. No command/string parser.
|
||||
use super::*;
|
||||
use crate::{HorizontalBox, Paragraph, ParagraphFont};
|
||||
use crate::{HorizontalBox, Paragraph, ParagraphFont, provenance::PaintSource};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use crate::opentype::{OpenTypeFont, OpenTypeRun};
|
||||
|
||||
@@ -209,14 +209,7 @@ impl Builder {
|
||||
});
|
||||
if explicit_hyphen && !self.restricted {
|
||||
hyphen_break = Some(self.nodes.len());
|
||||
self.nodes.push(TextNode::Discretionary {
|
||||
font: run.font.id,
|
||||
automatic: false,
|
||||
hyphen_char: None,
|
||||
pre_break: Vec::new(),
|
||||
post_break: Vec::new(),
|
||||
replacement_count: 0,
|
||||
});
|
||||
self.push_explicit_hyphen_break(run.font.id);
|
||||
}
|
||||
}
|
||||
Output::Kern(width) => self.nodes.push(TextNode::Kern {
|
||||
@@ -238,11 +231,7 @@ impl Builder {
|
||||
}
|
||||
pub fn finish_text(&mut self, right_boundary: bool, state: &State) -> Result<(), String> {
|
||||
if let Some(run) = self.opentype.take() {
|
||||
let shaped = run.font.shape(run.text, run.sources)?;
|
||||
self.font_steps = self.font_steps.checked_add(shaped.glyphs.len())
|
||||
.filter(|steps| *steps <= self.font_step_limit)
|
||||
.ok_or("native OpenType shaping step limit exceeded")?;
|
||||
self.nodes.push(TextNode::OpenType(Arc::new(shaped)));
|
||||
self.finish_opentype(run, state)?;
|
||||
}
|
||||
if let Some(mut run) = self.run.take() {
|
||||
run.machine
|
||||
@@ -262,6 +251,83 @@ impl Builder {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn push_explicit_hyphen_break(&mut self, font: FontId) {
|
||||
self.nodes.push(TextNode::Discretionary {
|
||||
font,
|
||||
automatic: false,
|
||||
hyphen_char: None,
|
||||
pre_break: Vec::new(),
|
||||
post_break: Vec::new(),
|
||||
replacement_count: 0,
|
||||
});
|
||||
}
|
||||
|
||||
fn finish_opentype(&mut self, run: PendingOpenType, state: &State) -> Result<(), String> {
|
||||
let xetex = state.input_profile() == InputProfile::XeTeX;
|
||||
let use_glyph_metrics =
|
||||
xetex && state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0;
|
||||
let original_end = run.text.chars().next_back();
|
||||
let (text, sources) = run.font.map_text(run.text, run.sources)?;
|
||||
if self.restricted || !xetex {
|
||||
return self.push_opentype(&run.font, text, sources, use_glyph_metrics);
|
||||
}
|
||||
|
||||
let dash_breaks = state.parameter(Parameter::XeTeXdashbreakstate).width() > 0;
|
||||
let hyphen = u32::try_from(state.font_integers(run.font.id).hyphen)
|
||||
.ok()
|
||||
.and_then(char::from_u32);
|
||||
let is_hyphen = |c| Some(c) == hyphen || (dash_breaks && matches!(c, '–' | '—'));
|
||||
// XeTeX tests the end of the original word for the final discretionary,
|
||||
// and the characters of the mapped word for interior breakpoints.
|
||||
let trailing_break = original_end.is_some_and(is_hyphen);
|
||||
let ends = text.char_indices().filter_map(|(at, c)| {
|
||||
let end = at + c.len_utf8();
|
||||
(end < text.len() && is_hyphen(c)).then_some(end)
|
||||
});
|
||||
let mut ends = ends.peekable();
|
||||
if ends.peek().is_none() {
|
||||
self.push_opentype(&run.font, text, sources, use_glyph_metrics)?;
|
||||
} else {
|
||||
let mut sources = sources.into_iter().peekable();
|
||||
let mut start = 0;
|
||||
for end in ends.chain(std::iter::once(text.len())) {
|
||||
let mut fragment_sources = Vec::new();
|
||||
while let Some((offset, origin)) = sources.next_if(|(at, _)| *at < end) {
|
||||
fragment_sources.push((offset - start, origin));
|
||||
}
|
||||
self.push_opentype(
|
||||
&run.font,
|
||||
text[start..end].to_owned(),
|
||||
fragment_sources,
|
||||
use_glyph_metrics,
|
||||
)?;
|
||||
if end != text.len() {
|
||||
self.push_explicit_hyphen_break(run.font.id);
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
if trailing_break {
|
||||
self.push_explicit_hyphen_break(run.font.id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn push_opentype(
|
||||
&mut self,
|
||||
font: &Arc<OpenTypeFont>,
|
||||
text: String,
|
||||
sources: Vec<(usize, PaintSource)>,
|
||||
use_glyph_metrics: bool,
|
||||
) -> Result<(), String> {
|
||||
let shaped = font.shape_mapped(text, sources, use_glyph_metrics)?;
|
||||
self.font_steps = self.font_steps.checked_add(shaped.glyphs.len())
|
||||
.filter(|steps| *steps <= self.font_step_limit)
|
||||
.ok_or("native OpenType shaping step limit exceeded")?;
|
||||
self.nodes.push(TextNode::OpenType(Arc::new(shaped)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn opentype_character(
|
||||
&mut self, c: char, origin: TokenOrigin, state: &State, font: Arc<OpenTypeFont>,
|
||||
) -> Result<(), String> {
|
||||
|
||||
@@ -119,6 +119,8 @@ pub enum Parameter {
|
||||
Pdfappendkern,
|
||||
Pdfadjustspacing,
|
||||
Partokencontext,
|
||||
XeTeXuseglyphmetrics,
|
||||
XeTeXdashbreakstate,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ParameterValue {
|
||||
@@ -151,6 +153,8 @@ impl Parameter {
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) const XETEX: [Self; 2] = [Self::XeTeXuseglyphmetrics, Self::XeTeXdashbreakstate];
|
||||
|
||||
pub const ALL: &'static [Self] = &[
|
||||
Self::Pdfoutput,
|
||||
Self::Pdfmajorversion,
|
||||
@@ -266,9 +270,15 @@ impl Parameter {
|
||||
Self::Pdfappendkern,
|
||||
Self::Pdfadjustspacing,
|
||||
Self::Partokencontext,
|
||||
Self::XeTeXuseglyphmetrics,
|
||||
Self::XeTeXdashbreakstate,
|
||||
];
|
||||
pub fn name(self) -> String {
|
||||
format!("{self:?}").to_ascii_lowercase()
|
||||
match self {
|
||||
Self::XeTeXuseglyphmetrics => "XeTeXuseglyphmetrics".into(),
|
||||
Self::XeTeXdashbreakstate => "XeTeXdashbreakstate".into(),
|
||||
_ => format!("{self:?}").to_ascii_lowercase(),
|
||||
}
|
||||
}
|
||||
pub fn kind(self) -> Option<RegisterKind> {
|
||||
match self {
|
||||
|
||||
@@ -1144,7 +1144,7 @@ impl Default for State {
|
||||
| Parameter::Tracingnesting
|
||||
| Parameter::Tracingassigns
|
||||
| Parameter::Savingvdiscards
|
||||
) {
|
||||
) || Parameter::XETEX.contains(p) {
|
||||
continue;
|
||||
}
|
||||
state
|
||||
@@ -1637,6 +1637,13 @@ impl State {
|
||||
] {
|
||||
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
|
||||
}
|
||||
for parameter in Parameter::XETEX {
|
||||
self.update_profile_command(
|
||||
¶meter.name(),
|
||||
Meaning::Parameter(parameter),
|
||||
enabled,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn profile_primitive_name(&self, primitive: Primitive) -> Option<&'static str> {
|
||||
|
||||
@@ -277,16 +277,24 @@ impl OpenTypeFont {
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn shape(
|
||||
pub(crate) fn map_text(
|
||||
&self,
|
||||
text: String,
|
||||
sources: Vec<(usize, PaintSource)>,
|
||||
) -> Result<(String, Vec<(usize, PaintSource)>), String> {
|
||||
if let Some(mapping) = &self.mapping {
|
||||
mapping.apply(&text, &sources)
|
||||
} else {
|
||||
Ok((text, sources))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn shape_mapped(
|
||||
self: &Arc<Self>,
|
||||
text: String,
|
||||
sources: Vec<(usize, PaintSource)>,
|
||||
use_glyph_metrics: bool,
|
||||
) -> Result<OpenTypeRun, String> {
|
||||
let (text, sources) = if let Some(mapping) = &self.mapping {
|
||||
mapping.apply(&text, &sources)?
|
||||
} else {
|
||||
(text, sources)
|
||||
};
|
||||
let face = Face::from_slice(&self.resource.data, self.request.index)
|
||||
.ok_or("invalid OpenType shaping face")?;
|
||||
let features: Vec<_> = self
|
||||
@@ -357,20 +365,76 @@ impl OpenTypeFont {
|
||||
x_origin += scale(x);
|
||||
}
|
||||
}
|
||||
let glyph_extents = (use_glyph_metrics && !glyphs.is_empty())
|
||||
.then(|| glyph_extents(&face, self.size, &glyphs));
|
||||
Ok(OpenTypeRun {
|
||||
font: self.clone(),
|
||||
text,
|
||||
glyphs,
|
||||
width: x_origin,
|
||||
sources,
|
||||
glyph_extents,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// FreeType's unscaled control box includes off-curve points. In particular
|
||||
// it can be larger than the tight bounds of a CFF cubic outline.
|
||||
#[derive(Default)]
|
||||
struct VerticalControlBox(Option<[f32; 2]>);
|
||||
impl VerticalControlBox {
|
||||
fn point(&mut self, y: f32) {
|
||||
let y = y.round();
|
||||
let bounds = self.0.get_or_insert([y, y]);
|
||||
bounds[0] = bounds[0].min(y);
|
||||
bounds[1] = bounds[1].max(y);
|
||||
}
|
||||
}
|
||||
impl ttf_parser::OutlineBuilder for VerticalControlBox {
|
||||
fn move_to(&mut self, _: f32, y: f32) {
|
||||
self.point(y);
|
||||
}
|
||||
fn line_to(&mut self, _: f32, y: f32) {
|
||||
self.point(y);
|
||||
}
|
||||
fn quad_to(&mut self, _: f32, control: f32, _: f32, y: f32) {
|
||||
self.point(control);
|
||||
self.point(y);
|
||||
}
|
||||
fn curve_to(&mut self, _: f32, first: f32, _: f32, second: f32, _: f32, y: f32) {
|
||||
self.point(first);
|
||||
self.point(second);
|
||||
self.point(y);
|
||||
}
|
||||
fn close(&mut self) {}
|
||||
}
|
||||
|
||||
fn glyph_extents(face: &Face<'_>, size: i64, glyphs: &[OpenTypeGlyph]) -> [i64; 2] {
|
||||
let mut minimum = f32::INFINITY;
|
||||
let mut maximum = f32::NEG_INFINITY;
|
||||
let points = |units| units * (size as f32 / 65536.) / f32::from(face.tables().head.units_per_em);
|
||||
for glyph in glyphs {
|
||||
let mut outline = VerticalControlBox::default();
|
||||
let [bottom, top] = if face.outline_glyph(GlyphId(glyph.id), &mut outline).is_some() {
|
||||
outline.0.unwrap_or_default()
|
||||
} else {
|
||||
[0., 0.]
|
||||
};
|
||||
let baseline = -(glyph.y as f32 / 65536.);
|
||||
minimum = minimum.min(baseline + points(bottom));
|
||||
maximum = maximum.max(baseline + points(top));
|
||||
}
|
||||
[points_to_sp(maximum), -points_to_sp(minimum)]
|
||||
}
|
||||
|
||||
fn points_to_sp(points: f32) -> i64 {
|
||||
(f64::from(points) * 65536. + 0.5) as i64
|
||||
}
|
||||
|
||||
pub(crate) fn scale_units(value: i64, size: i64, units: u16) -> i64 {
|
||||
let points = (value as f32 * (size as f32 / 65536.)) / f32::from(units);
|
||||
// XeTeX converts the float point position by adding 0.5 and truncating.
|
||||
(f64::from(points) * 65536. + 0.5) as i64
|
||||
points_to_sp(points)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -390,6 +454,14 @@ pub struct OpenTypeRun {
|
||||
pub glyphs: Vec<OpenTypeGlyph>,
|
||||
pub width: i64,
|
||||
pub sources: Vec<(usize, PaintSource)>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
glyph_extents: Option<[i64; 2]>,
|
||||
}
|
||||
|
||||
impl OpenTypeRun {
|
||||
pub(crate) fn height_depth(&self) -> [i64; 2] {
|
||||
self.glyph_extents.unwrap_or([self.font.ascent, self.font.descent])
|
||||
}
|
||||
}
|
||||
|
||||
/// Materialize a single native math glyph using the final selected glyph,
|
||||
@@ -403,7 +475,8 @@ pub(crate) fn math_glyph(
|
||||
math::MathBox,
|
||||
math_engine_tex::{MathGeometry, MathItem, PositionedItem},
|
||||
};
|
||||
let mut run = font.shape(character.to_string(), vec![(0, source.clone())])?;
|
||||
let (text, sources) = font.map_text(character.to_string(), vec![(0, source.clone())])?;
|
||||
let mut run = font.shape_mapped(text, sources, false)?;
|
||||
let [glyph] = run.glyphs.as_mut_slice() else {
|
||||
return Err("OpenType math character did not select one glyph".into());
|
||||
};
|
||||
@@ -444,11 +517,8 @@ pub(crate) fn horizontal_box(run: &Arc<OpenTypeRun>) -> crate::HorizontalBox {
|
||||
math::MathBox,
|
||||
math_engine_tex::{MathGeometry, MathItem, PositionedItem},
|
||||
};
|
||||
let metrics = MathBox {
|
||||
width: run.width,
|
||||
height: run.font.ascent,
|
||||
depth: run.font.descent,
|
||||
};
|
||||
let [height, depth] = run.height_depth();
|
||||
let metrics = MathBox { width: run.width, height, depth };
|
||||
crate::HorizontalBox {
|
||||
width: metrics.width,
|
||||
height: metrics.height,
|
||||
|
||||
Reference in new issue
Block a user