From 7a1cd362aa150045371cc85578ef50bef2951be2 Mon Sep 17 00:00:00 2001 From: damaxwell Date: Mon, 17 Jul 2023 08:19:46 -0800 Subject: Support for bounding box text edges (#1626) --- crates/typst-library/src/math/ctx.rs | 24 +++++- crates/typst-library/src/math/mod.rs | 4 +- crates/typst-library/src/text/mod.rs | 136 +++++++++++++++++++++++++++---- crates/typst-library/src/text/shaping.rs | 16 ++-- 4 files changed, 155 insertions(+), 25 deletions(-) (limited to 'crates/typst-library') diff --git a/crates/typst-library/src/math/ctx.rs b/crates/typst-library/src/math/ctx.rs index 999a5ccb..e6a84674 100644 --- a/crates/typst-library/src/math/ctx.rs +++ b/crates/typst-library/src/math/ctx.rs @@ -5,7 +5,7 @@ use typst::model::realize; use unicode_segmentation::UnicodeSegmentation; use super::*; -use crate::text::tags; +use crate::text::{tags, BottomEdge, BottomEdgeMetric, TopEdge, TopEdgeMetric}; macro_rules! scaled { ($ctx:expr, text: $text:ident, display: $display:ident $(,)?) => { @@ -203,7 +203,27 @@ impl<'a, 'b, 'v> MathContext<'a, 'b, 'v> { style = style.with_italic(false); } let text: EcoString = text.chars().map(|c| style.styled_char(c)).collect(); - let frame = self.layout_content(&TextElem::packed(text).spanned(span))?; + let text = TextElem::packed(text) + .styled(TextElem::set_top_edge(TopEdge::Metric(TopEdgeMetric::Bounds))) + .styled(TextElem::set_bottom_edge(BottomEdge::Metric( + BottomEdgeMetric::Bounds, + ))) + .spanned(span); + let par = ParElem::new(vec![text]); + + // There isn't a natural width for a paragraph in a math environment; + // because it will be placed somewhere probably not at the left margin + // it will overflow. So emulate an `hbox` instead and allow the paragraph + // to extend as far as needed. + let frame = par + .layout( + self.vt, + self.outer.chain(&self.local), + false, + Size::splat(Abs::inf()), + false, + )? + .into_frame(); FrameFragment::new(self, frame) .with_class(MathClass::Alphabetic) .with_spaced(spaced) diff --git a/crates/typst-library/src/math/mod.rs b/crates/typst-library/src/math/mod.rs index b5410a03..c29ad29b 100644 --- a/crates/typst-library/src/math/mod.rs +++ b/crates/typst-library/src/math/mod.rs @@ -292,9 +292,9 @@ impl Layout for EquationElem { } } else { let slack = ParElem::leading_in(styles) * 0.7; - let top_edge = TextElem::top_edge_in(styles).resolve(styles, font.metrics()); + let top_edge = TextElem::top_edge_in(styles).resolve(styles, &font, None); let bottom_edge = - -TextElem::bottom_edge_in(styles).resolve(styles, font.metrics()); + -TextElem::bottom_edge_in(styles).resolve(styles, &font, None); let ascent = top_edge.max(frame.ascent() - slack); let descent = bottom_edge.max(frame.descent() - slack); diff --git a/crates/typst-library/src/text/mod.rs b/crates/typst-library/src/text/mod.rs index 3c3ccdef..f7c15c29 100644 --- a/crates/typst-library/src/text/mod.rs +++ b/crates/typst-library/src/text/mod.rs @@ -15,7 +15,8 @@ pub use self::shaping::*; pub use self::shift::*; use rustybuzz::Tag; -use typst::font::{FontMetrics, FontStretch, FontStyle, FontWeight, VerticalFontMetric}; +use ttf_parser::Rect; +use typst::font::{Font, FontStretch, FontStyle, FontWeight, VerticalFontMetric}; use crate::layout::ParElem; use crate::prelude::*; @@ -245,8 +246,8 @@ pub struct TextElem { /// #set text(top-edge: "cap-height") /// #rect(fill: aqua)[Typst] /// ``` - #[default(TextEdge::Metric(VerticalFontMetric::CapHeight))] - pub top_edge: TextEdge, + #[default(TopEdge::Metric(TopEdgeMetric::CapHeight))] + pub top_edge: TopEdge, /// The bottom end of the conceptual frame around the text used for layout /// and positioning. This affects the size of containers that hold text. @@ -261,8 +262,8 @@ pub struct TextElem { /// #set text(bottom-edge: "descender") /// #rect(fill: aqua)[Typst] /// ``` - #[default(TextEdge::Metric(VerticalFontMetric::Baseline))] - pub bottom_edge: TextEdge, + #[default(BottomEdge::Metric(BottomEdgeMetric::Baseline))] + pub bottom_edge: BottomEdge, /// An [ISO 639-1/2/3 language code.](https://en.wikipedia.org/wiki/ISO_639) /// @@ -606,35 +607,140 @@ cast! { v: Length => Self(v), } -/// Specifies the bottom or top edge of text. +/// Specifies the top edge of text. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] -pub enum TextEdge { - /// An edge specified using one of the well-known font metrics. - Metric(VerticalFontMetric), +pub enum TopEdge { + /// An edge specified via font metrics or bounding box. + Metric(TopEdgeMetric), /// An edge specified as a length. Length(Length), } -impl TextEdge { +impl TopEdge { + /// Determine if the edge is specified from bounding box info. + pub fn is_bounds(&self) -> bool { + matches!(self, Self::Metric(TopEdgeMetric::Bounds)) + } + /// Resolve the value of the text edge given a font's metrics. - pub fn resolve(self, styles: StyleChain, metrics: &FontMetrics) -> Abs { + pub fn resolve(self, styles: StyleChain, font: &Font, bbox: Option) -> Abs { match self { - Self::Metric(metric) => metrics.vertical(metric).resolve(styles), - Self::Length(length) => length.resolve(styles), + TopEdge::Metric(metric) => { + if let Ok(metric) = metric.try_into() { + font.metrics().vertical(metric).resolve(styles) + } else { + bbox.map(|bbox| (font.to_em(bbox.y_max)).resolve(styles)) + .unwrap_or_default() + } + } + TopEdge::Length(length) => length.resolve(styles), } } } cast! { - TextEdge, + TopEdge, self => match self { Self::Metric(metric) => metric.into_value(), Self::Length(length) => length.into_value(), }, - v: VerticalFontMetric => Self::Metric(v), + v: TopEdgeMetric => Self::Metric(v), v: Length => Self::Length(v), } +/// Metrics that describe the top edge of text. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)] +pub enum TopEdgeMetric { + /// The font's ascender, which typically exceeds the height of all glyphs. + Ascender, + /// The approximate height of uppercase letters. + CapHeight, + /// The approximate height of non-ascending lowercase letters. + XHeight, + /// The baseline on which the letters rest. + Baseline, + /// The top edge of the glyph's bounding box. + Bounds, +} + +impl TryInto for TopEdgeMetric { + type Error = (); + + fn try_into(self) -> Result { + match self { + Self::Ascender => Ok(VerticalFontMetric::Ascender), + Self::CapHeight => Ok(VerticalFontMetric::CapHeight), + Self::XHeight => Ok(VerticalFontMetric::XHeight), + Self::Baseline => Ok(VerticalFontMetric::Baseline), + _ => Err(()), + } + } +} + +/// Specifies the top edge of text. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub enum BottomEdge { + /// An edge specified via font metrics or bounding box. + Metric(BottomEdgeMetric), + /// An edge specified as a length. + Length(Length), +} + +impl BottomEdge { + /// Determine if the edge is specified from bounding box info. + pub fn is_bounds(&self) -> bool { + matches!(self, Self::Metric(BottomEdgeMetric::Bounds)) + } + + /// Resolve the value of the text edge given a font's metrics. + pub fn resolve(self, styles: StyleChain, font: &Font, bbox: Option) -> Abs { + match self { + BottomEdge::Metric(metric) => { + if let Ok(metric) = metric.try_into() { + font.metrics().vertical(metric).resolve(styles) + } else { + bbox.map(|bbox| (font.to_em(bbox.y_min)).resolve(styles)) + .unwrap_or_default() + } + } + BottomEdge::Length(length) => length.resolve(styles), + } + } +} + +cast! { + BottomEdge, + self => match self { + Self::Metric(metric) => metric.into_value(), + Self::Length(length) => length.into_value(), + }, + v: BottomEdgeMetric => Self::Metric(v), + v: Length => Self::Length(v), +} + +/// Metrics that describe the bottom edge of text. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)] +pub enum BottomEdgeMetric { + /// The baseline on which the letters rest. + Baseline, + /// The font's descender, which typically exceeds the depth of all glyphs. + Descender, + /// The bottom edge of the glyph's bounding box. + Bounds, +} + +impl TryInto for BottomEdgeMetric { + type Error = (); + + fn try_into(self) -> Result { + match self { + Self::Baseline => Ok(VerticalFontMetric::Baseline), + Self::Descender => Ok(VerticalFontMetric::Descender), + _ => Err(()), + } + } +} + /// The direction of text and inline objects in their line. #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)] pub struct TextDir(pub Smart); diff --git a/crates/typst-library/src/text/shaping.rs b/crates/typst-library/src/text/shaping.rs index 5be22390..3ccac635 100644 --- a/crates/typst-library/src/text/shaping.rs +++ b/crates/typst-library/src/text/shaping.rs @@ -320,10 +320,9 @@ impl<'a> ShapedText<'a> { 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| { - let metrics = font.metrics(); - top.set_max(top_edge.resolve(self.styles, metrics)); - bottom.set_max(-bottom_edge.resolve(self.styles, metrics)); + let mut expand = |font: &Font, bbox: Option| { + top.set_max(top_edge.resolve(self.styles, font, bbox)); + bottom.set_max(-bottom_edge.resolve(self.styles, font, bbox)); }; if self.glyphs.is_empty() { @@ -336,13 +335,18 @@ impl<'a> ShapedText<'a> { .select(family.as_str(), self.variant) .and_then(|id| world.font(id)) { - expand(&font); + expand(&font, None); break; } } } else { for g in self.glyphs.iter() { - expand(&g.font); + let bbox = if top_edge.is_bounds() || bottom_edge.is_bounds() { + g.font.ttf().glyph_bounding_box(ttf_parser::GlyphId(g.glyph_id)) + } else { + None + }; + expand(&g.font, bbox); } } -- cgit v1.2.3