diff options
| author | Malo <57839069+MDLC01@users.noreply.github.com> | 2025-07-02 09:00:45 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-07-02 08:00:45 +0000 |
| commit | 09c831d3b32935fe162f198e3512e1e7cd6647db (patch) | |
| tree | a80a3e60381c2ac162034c45661d4070443563a7 /crates/typst-layout/src/inline | |
| parent | 30ddc4a7ca38ea41d9184cec6eee732307c80b33 (diff) | |
Use "subs" and "sups" font features for typographic scripts (#5777)
Diffstat (limited to 'crates/typst-layout/src/inline')
| -rw-r--r-- | crates/typst-layout/src/inline/collect.rs | 4 | ||||
| -rw-r--r-- | crates/typst-layout/src/inline/line.rs | 43 | ||||
| -rw-r--r-- | crates/typst-layout/src/inline/linebreak.rs | 6 | ||||
| -rw-r--r-- | crates/typst-layout/src/inline/mod.rs | 2 | ||||
| -rw-r--r-- | crates/typst-layout/src/inline/prepare.rs | 4 | ||||
| -rw-r--r-- | crates/typst-layout/src/inline/shaping.rs | 143 |
6 files changed, 155 insertions, 47 deletions
diff --git a/crates/typst-layout/src/inline/collect.rs b/crates/typst-layout/src/inline/collect.rs index 5a1b7b4f..829f64b6 100644 --- a/crates/typst-layout/src/inline/collect.rs +++ b/crates/typst-layout/src/inline/collect.rs @@ -206,7 +206,7 @@ pub fn collect<'a>( } InlineItem::Frame(mut frame) => { frame.modify(&FrameModifiers::get_in(styles)); - apply_baseline_shift(&mut frame, styles); + apply_shift(&engine.world, &mut frame, styles); collector.push_item(Item::Frame(frame)); } } @@ -221,7 +221,7 @@ pub fn collect<'a>( let mut frame = layout_and_modify(styles, |styles| { layout_box(elem, engine, loc, styles, region) })?; - apply_baseline_shift(&mut frame, styles); + apply_shift(&engine.world, &mut frame, styles); collector.push_item(Item::Frame(frame)); } } else if let Some(elem) = child.to_packed::<TagElem>() { diff --git a/crates/typst-layout/src/inline/line.rs b/crates/typst-layout/src/inline/line.rs index 7bf4d4c7..b850e50e 100644 --- a/crates/typst-layout/src/inline/line.rs +++ b/crates/typst-layout/src/inline/line.rs @@ -5,7 +5,7 @@ use typst_library::engine::Engine; use typst_library::introspection::{SplitLocator, Tag}; use typst_library::layout::{Abs, Dir, Em, Fr, Frame, FrameItem, Point}; use typst_library::model::ParLineMarker; -use typst_library::text::{Lang, TextElem}; +use typst_library::text::{variant, Lang, TextElem}; use typst_utils::Numeric; use super::*; @@ -330,7 +330,7 @@ fn adjust_cj_at_line_start(p: &Preparation, items: &mut Items) { let glyph = shaped.glyphs.to_mut().first_mut().unwrap(); let shrink = glyph.shrinkability().0; glyph.shrink_left(shrink); - shaped.width -= shrink.at(shaped.size); + shaped.width -= shrink.at(glyph.size); } else if p.config.cjk_latin_spacing && glyph.is_cj_script() && glyph.x_offset > Em::zero() @@ -342,7 +342,7 @@ fn adjust_cj_at_line_start(p: &Preparation, items: &mut Items) { glyph.x_advance -= shrink; glyph.x_offset = Em::zero(); glyph.adjustability.shrinkability.0 = Em::zero(); - shaped.width -= shrink.at(shaped.size); + shaped.width -= shrink.at(glyph.size); } } @@ -360,7 +360,7 @@ fn adjust_cj_at_line_end(p: &Preparation, items: &mut Items) { let shrink = glyph.shrinkability().1; let punct = shaped.glyphs.to_mut().last_mut().unwrap(); punct.shrink_right(shrink); - shaped.width -= shrink.at(shaped.size); + shaped.width -= shrink.at(punct.size); } else if p.config.cjk_latin_spacing && glyph.is_cj_script() && (glyph.x_advance - glyph.x_offset) > Em::one() @@ -371,7 +371,7 @@ fn adjust_cj_at_line_end(p: &Preparation, items: &mut Items) { let glyph = shaped.glyphs.to_mut().last_mut().unwrap(); glyph.x_advance -= shrink; glyph.adjustability.shrinkability.1 = Em::zero(); - shaped.width -= shrink.at(shaped.size); + shaped.width -= shrink.at(glyph.size); } } @@ -412,9 +412,30 @@ fn should_repeat_hyphen(pred_line: &Line, text: &str) -> bool { } } -/// Apply the current baseline shift to a frame. -pub fn apply_baseline_shift(frame: &mut Frame, styles: StyleChain) { - frame.translate(Point::with_y(TextElem::baseline_in(styles))); +/// Apply the current baseline shift and italic compensation to a frame. +pub fn apply_shift<'a>( + world: &Tracked<'a, dyn World + 'a>, + frame: &mut Frame, + styles: StyleChain, +) { + let mut baseline = TextElem::baseline_in(styles); + let mut compensation = Abs::zero(); + if let Some(scripts) = TextElem::shift_settings_in(styles) { + let font_metrics = TextElem::font_in(styles) + .into_iter() + .find_map(|family| { + world + .book() + .select(family.as_str(), variant(styles)) + .and_then(|id| world.font(id)) + }) + .map_or(*scripts.kind.default_metrics(), |f| { + *scripts.kind.read_metrics(f.metrics()) + }); + baseline -= scripts.shift.unwrap_or(font_metrics.vertical_offset).resolve(styles); + compensation += font_metrics.horizontal_offset.resolve(styles); + } + frame.translate(Point::new(compensation, baseline)); } /// Commit to a line and build its frame. @@ -444,7 +465,7 @@ pub fn commit( && TextElem::overhang_in(text.styles) && (line.items.len() > 1 || text.glyphs.len() > 1) { - let amount = overhang(glyph.c) * glyph.x_advance.at(text.size); + let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size); offset -= amount; remaining += amount; } @@ -458,7 +479,7 @@ pub fn commit( && TextElem::overhang_in(text.styles) && (line.items.len() > 1 || text.glyphs.len() > 1) { - let amount = overhang(glyph.c) * glyph.x_advance.at(text.size); + let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size); remaining += amount; } } @@ -519,7 +540,7 @@ pub fn commit( let mut frame = layout_and_modify(*styles, |styles| { layout_box(elem, engine, loc.relayout(), styles, region) })?; - apply_baseline_shift(&mut frame, *styles); + apply_shift(&engine.world, &mut frame, *styles); push(&mut offset, frame, idx); } else { offset += amount; diff --git a/crates/typst-layout/src/inline/linebreak.rs b/crates/typst-layout/src/inline/linebreak.rs index ada048c7..709745ed 100644 --- a/crates/typst-layout/src/inline/linebreak.rs +++ b/crates/typst-layout/src/inline/linebreak.rs @@ -927,9 +927,9 @@ impl Estimates { let byte_len = g.range.len(); let stretch = g.stretchability().0 + g.stretchability().1; let shrink = g.shrinkability().0 + g.shrinkability().1; - widths.push(byte_len, g.x_advance.at(shaped.size)); - stretchability.push(byte_len, stretch.at(shaped.size)); - shrinkability.push(byte_len, shrink.at(shaped.size)); + widths.push(byte_len, g.x_advance.at(g.size)); + stretchability.push(byte_len, stretch.at(g.size)); + shrinkability.push(byte_len, shrink.at(g.size)); justifiables.push(byte_len, g.is_justifiable() as usize); } } else { diff --git a/crates/typst-layout/src/inline/mod.rs b/crates/typst-layout/src/inline/mod.rs index 6cafb9b0..506fa5ea 100644 --- a/crates/typst-layout/src/inline/mod.rs +++ b/crates/typst-layout/src/inline/mod.rs @@ -29,7 +29,7 @@ use typst_utils::{Numeric, SliceExt}; use self::collect::{collect, Item, Segment, SpanMapper}; use self::deco::decorate; use self::finalize::finalize; -use self::line::{apply_baseline_shift, commit, line, Line}; +use self::line::{apply_shift, commit, line, Line}; use self::linebreak::{linebreak, Breakpoint}; use self::prepare::{prepare, Preparation}; use self::shaping::{ diff --git a/crates/typst-layout/src/inline/prepare.rs b/crates/typst-layout/src/inline/prepare.rs index 5d7fcd7c..ab39bdb1 100644 --- a/crates/typst-layout/src/inline/prepare.rs +++ b/crates/typst-layout/src/inline/prepare.rs @@ -144,7 +144,7 @@ fn add_cjk_latin_spacing(items: &mut [(Range, Item)]) { // The spacing is default to 1/4 em, and can be shrunk to 1/8 em. glyph.x_advance += Em::new(0.25); glyph.adjustability.shrinkability.1 += Em::new(0.125); - text.width += Em::new(0.25).at(text.size); + text.width += Em::new(0.25).at(glyph.size); } // Case 2: Latin followed by a CJ character @@ -152,7 +152,7 @@ fn add_cjk_latin_spacing(items: &mut [(Range, Item)]) { glyph.x_advance += Em::new(0.25); glyph.x_offset += Em::new(0.25); glyph.adjustability.shrinkability.0 += Em::new(0.125); - text.width += Em::new(0.25).at(text.size); + text.width += Em::new(0.25).at(glyph.size); } prev = Some(glyph); diff --git a/crates/typst-layout/src/inline/shaping.rs b/crates/typst-layout/src/inline/shaping.rs index 935a86b3..48747cd5 100644 --- a/crates/typst-layout/src/inline/shaping.rs +++ b/crates/typst-layout/src/inline/shaping.rs @@ -3,14 +3,15 @@ use std::fmt::{self, Debug, Formatter}; use std::sync::Arc; use az::SaturatingAs; -use rustybuzz::{BufferFlags, ShapePlan, UnicodeBuffer}; +use rustybuzz::{BufferFlags, Feature, ShapePlan, UnicodeBuffer}; +use ttf_parser::gsub::SubstitutionSubtable; use ttf_parser::Tag; use typst_library::engine::Engine; use typst_library::foundations::{Smart, StyleChain}; use typst_library::layout::{Abs, Dir, Em, Frame, FrameItem, Point, Size}; use typst_library::text::{ families, features, is_default_ignorable, language, variant, Font, FontFamily, - FontVariant, Glyph, Lang, Region, TextEdgeBounds, TextElem, TextItem, + FontVariant, Glyph, Lang, Region, ShiftSettings, TextEdgeBounds, TextElem, TextItem, }; use typst_library::World; use typst_utils::SliceExt; @@ -41,8 +42,6 @@ pub struct ShapedText<'a> { pub styles: StyleChain<'a>, /// The font variant. pub variant: FontVariant, - /// The font size. - pub size: Abs, /// The width of the text's bounding box. pub width: Abs, /// The shaped glyphs. @@ -62,6 +61,8 @@ pub struct ShapedGlyph { pub x_offset: Em, /// The vertical offset of the glyph. pub y_offset: Em, + /// The font size for the glyph. + pub size: Abs, /// The adjustability of the glyph. pub adjustability: Adjustability, /// The byte range of this glyph's cluster in the full inline layout. A @@ -222,14 +223,17 @@ impl<'a> ShapedText<'a> { let mut frame = Frame::soft(size); frame.set_baseline(top); + let size = TextElem::size_in(self.styles); let shift = TextElem::baseline_in(self.styles); let decos = TextElem::deco_in(self.styles); let fill = TextElem::fill_in(self.styles); let stroke = TextElem::stroke_in(self.styles); let span_offset = TextElem::span_offset_in(self.styles); - for ((font, y_offset), group) in - self.glyphs.as_ref().group_by_key(|g| (g.font.clone(), g.y_offset)) + for ((font, y_offset, glyph_size), group) in self + .glyphs + .as_ref() + .group_by_key(|g| (g.font.clone(), g.y_offset, g.size)) { let mut range = group[0].range.clone(); for glyph in group { @@ -237,7 +241,7 @@ impl<'a> ShapedText<'a> { range.end = range.end.max(glyph.range.end); } - let pos = Point::new(offset, top + shift - y_offset.at(self.size)); + let pos = Point::new(offset, top + shift - y_offset.at(size)); let glyphs: Vec<Glyph> = group .iter() .map(|shaped: &ShapedGlyph| { @@ -257,11 +261,11 @@ impl<'a> ShapedText<'a> { adjustability_right * justification_ratio; if shaped.is_justifiable() { justification_right += - Em::from_length(extra_justification, self.size) + Em::from_abs(extra_justification, glyph_size) } - frame.size_mut().x += justification_left.at(self.size) - + justification_right.at(self.size); + frame.size_mut().x += justification_left.at(glyph_size) + + justification_right.at(glyph_size); // We may not be able to reach the offset completely if // it exceeds u16, but better to have a roughly correct @@ -304,7 +308,7 @@ impl<'a> ShapedText<'a> { let item = TextItem { font, - size: self.size, + size: glyph_size, lang: self.lang, region: self.region, fill: fill.clone(), @@ -336,12 +340,13 @@ impl<'a> ShapedText<'a> { let mut top = Abs::zero(); let mut bottom = Abs::zero(); + let size = TextElem::size_in(self.styles); let top_edge = TextElem::top_edge_in(self.styles); let bottom_edge = TextElem::bottom_edge_in(self.styles); // Expand top and bottom by reading the font's vertical metrics. let mut expand = |font: &Font, bounds: TextEdgeBounds| { - let (t, b) = font.edges(top_edge, bottom_edge, self.size, bounds); + let (t, b) = font.edges(top_edge, bottom_edge, size, bounds); top.set_max(t); bottom.set_max(b); }; @@ -388,18 +393,16 @@ impl<'a> ShapedText<'a> { pub fn stretchability(&self) -> Abs { self.glyphs .iter() - .map(|g| g.stretchability().0 + g.stretchability().1) - .sum::<Em>() - .at(self.size) + .map(|g| (g.stretchability().0 + g.stretchability().1).at(g.size)) + .sum() } /// The shrinkability of the text pub fn shrinkability(&self) -> Abs { self.glyphs .iter() - .map(|g| g.shrinkability().0 + g.shrinkability().1) - .sum::<Em>() - .at(self.size) + .map(|g| (g.shrinkability().0 + g.shrinkability().1).at(g.size)) + .sum() } /// Reshape a range of the shaped text, reusing information from this @@ -418,9 +421,8 @@ impl<'a> ShapedText<'a> { lang: self.lang, region: self.region, styles: self.styles, - size: self.size, variant: self.variant, - width: glyphs.iter().map(|g| g.x_advance).sum::<Em>().at(self.size), + width: glyphs_width(glyphs), glyphs: Cow::Borrowed(glyphs), } } else { @@ -484,13 +486,15 @@ impl<'a> ShapedText<'a> { // that subtracting either of the endpoints by self.base doesn't // underflow. See <https://github.com/typst/typst/issues/2283>. .unwrap_or_else(|| self.base..self.base); - self.width += x_advance.at(self.size); + let size = TextElem::size_in(self.styles); + self.width += x_advance.at(size); let glyph = ShapedGlyph { font, glyph_id: glyph_id.0, x_advance, x_offset: Em::zero(), y_offset: Em::zero(), + size, adjustability: Adjustability::default(), range, safe_to_break: true, @@ -666,6 +670,7 @@ fn shape<'a>( region: Option<Region>, ) -> ShapedText<'a> { let size = TextElem::size_in(styles); + let shift_settings = TextElem::shift_settings_in(styles); let mut ctx = ShapingContext { engine, size, @@ -676,6 +681,7 @@ fn shape<'a>( features: features(styles), fallback: TextElem::fallback_in(styles), dir, + shift_settings, }; if !text.is_empty() { @@ -698,12 +704,17 @@ fn shape<'a>( region, styles, variant: ctx.variant, - size, - width: ctx.glyphs.iter().map(|g| g.x_advance).sum::<Em>().at(size), + width: glyphs_width(&ctx.glyphs), glyphs: Cow::Owned(ctx.glyphs), } } +/// Computes the width of a run of glyphs relative to the font size, accounting +/// for their individual scaling factors and other font metrics. +fn glyphs_width(glyphs: &[ShapedGlyph]) -> Abs { + glyphs.iter().map(|g| g.x_advance.at(g.size)).sum() +} + /// Holds shaping results and metadata common to all shaped segments. struct ShapingContext<'a, 'v> { engine: &'a Engine<'v>, @@ -715,6 +726,7 @@ struct ShapingContext<'a, 'v> { features: Vec<rustybuzz::Feature>, fallback: bool, dir: Dir, + shift_settings: Option<ShiftSettings>, } /// Shape text with font fallback using the `families` iterator. @@ -789,6 +801,18 @@ fn shape_segment<'a>( // text extraction. buffer.set_flags(BufferFlags::REMOVE_DEFAULT_IGNORABLES); + let (script_shift, script_compensation, scale, shift_feature) = ctx + .shift_settings + .map_or((Em::zero(), Em::zero(), Em::one(), None), |settings| { + determine_shift(text, &font, settings) + }); + + let has_shift_feature = shift_feature.is_some(); + if let Some(feat) = shift_feature { + // Temporarily push the feature. + ctx.features.push(feat) + } + // Prepare the shape plan. This plan depends on direction, script, language, // and features, but is independent from the text and can thus be memoized. let plan = create_shape_plan( @@ -799,6 +823,10 @@ fn shape_segment<'a>( &ctx.features, ); + if has_shift_feature { + ctx.features.pop(); + } + // Shape! let buffer = rustybuzz::shape_with_plan(font.rusty(), &plan, buffer); let infos = buffer.glyph_infos(); @@ -869,8 +897,9 @@ fn shape_segment<'a>( glyph_id: info.glyph_id as u16, // TODO: Don't ignore y_advance. x_advance, - x_offset: font.to_em(pos[i].x_offset), - y_offset: font.to_em(pos[i].y_offset), + x_offset: font.to_em(pos[i].x_offset) + script_compensation, + y_offset: font.to_em(pos[i].y_offset) + script_shift, + size: scale.at(ctx.size), adjustability: Adjustability::default(), range: start..end, safe_to_break: !info.unsafe_to_break(), @@ -932,6 +961,64 @@ fn shape_segment<'a>( ctx.used.pop(); } +/// Returns a `(script_shift, script_compensation, scale, feature)` quadruplet +/// describing how to produce scripts. +/// +/// Those values determine how the rendered text should be transformed to +/// display sub-/super-scripts. If the OpenType feature can be used, the +/// rendered text should not be transformed in any way, and so those values are +/// neutral (`(0, 0, 1, None)`). If scripts should be synthesized, those values +/// determine how to transform the rendered text to display scripts as expected. +fn determine_shift( + text: &str, + font: &Font, + settings: ShiftSettings, +) -> (Em, Em, Em, Option<Feature>) { + settings + .typographic + .then(|| { + // If typographic scripts are enabled (i.e., we want to use the + // OpenType feature instead of synthesizing if possible), we add + // "subs"/"sups" to the feature list if supported by the font. + // In case of a problem, we just early exit + let gsub = font.rusty().tables().gsub?; + let subtable_index = + gsub.features.find(settings.kind.feature())?.lookup_indices.get(0)?; + let coverage = gsub + .lookups + .get(subtable_index)? + .subtables + .get::<SubstitutionSubtable>(0)? + .coverage(); + text.chars() + .all(|c| { + font.rusty().glyph_index(c).is_some_and(|i| coverage.contains(i)) + }) + .then(|| { + // If we can use the OpenType feature, we can keep the text + // as is. + ( + Em::zero(), + Em::zero(), + Em::one(), + Some(Feature::new(settings.kind.feature(), 1, ..)), + ) + }) + }) + // Reunite the cases where `typographic` is `false` or where using the + // OpenType feature would not work. + .flatten() + .unwrap_or_else(|| { + let script_metrics = settings.kind.read_metrics(font.metrics()); + ( + settings.shift.unwrap_or(script_metrics.vertical_offset), + script_metrics.horizontal_offset, + settings.size.unwrap_or(script_metrics.height), + None, + ) + }) +} + /// Create a shape plan. #[comemo::memoize] pub fn create_shape_plan( @@ -963,6 +1050,7 @@ fn shape_tofus(ctx: &mut ShapingContext, base: usize, text: &str, font: Font) { x_advance, x_offset: Em::zero(), y_offset: Em::zero(), + size: ctx.size, adjustability: Adjustability::default(), range: start..end, safe_to_break: true, @@ -985,9 +1073,8 @@ fn shape_tofus(ctx: &mut ShapingContext, base: usize, text: &str, font: Font) { /// Apply tracking and spacing to the shaped glyphs. fn track_and_space(ctx: &mut ShapingContext) { - let tracking = Em::from_length(TextElem::tracking_in(ctx.styles), ctx.size); - let spacing = - TextElem::spacing_in(ctx.styles).map(|abs| Em::from_length(abs, ctx.size)); + let tracking = Em::from_abs(TextElem::tracking_in(ctx.styles), ctx.size); + let spacing = TextElem::spacing_in(ctx.styles).map(|abs| Em::from_abs(abs, ctx.size)); let mut glyphs = ctx.glyphs.iter_mut().peekable(); while let Some(glyph) = glyphs.next() { |
