Truly independent web browser
LibGfx: Read the OpenType MATH table through HarfBuzz
Andreas Klinga40513443647
diff --git a/Libraries/LibGfx/Font/Font.cpp b/Libraries/LibGfx/Font/Font.cppindex 7afb0b219c8..05ed53a500f 100644--- a/Libraries/LibGfx/Font/Font.cpp+++ b/Libraries/LibGfx/Font/Font.cpp@@ -24,6 +24,10 @@ u32 ladybird_gfx_font_glyph_id(void const*, u32);bool ladybird_gfx_font_contains_glyph(void const*, u32);bool ladybird_gfx_font_is_emoji_font(void const*);bool ladybird_gfx_font_is_invisible(void const*);+Gfx::FFI::FfiMathData const* ladybird_gfx_font_math_data(void const*);+void ladybird_gfx_font_glyph_metrics(void const*, u32, Gfx::FFI::FfiGlyphMetrics*);+size_t ladybird_gfx_font_math_glyph_variants(void const*, u32, bool, Gfx::FFI::FfiMathGlyphVariant*, size_t);+size_t ladybird_gfx_font_math_glyph_assembly(void const*, u32, bool, Gfx::FFI::FfiMathGlyphPart*, size_t, float*);void ladybird_gfx_font_ref(void const*);void ladybird_gfx_font_unref(void const*);}@@ -32,6 +36,13 @@ namespace Gfx {static Atomic<u64> s_next_id { 1 };+struct Font::MathData {+ AK_ALLOC_WITH_KMALLOC;++public:+ FFI::FfiMathData data {};+};+Font::Font(NonnullRefPtr<Typeface const> typeface, float point_width, float point_height, FontVariationSettings const variations, ShapeFeatures const& features): m_id(s_next_id.fetch_add(1, AK::MemoryOrder::memory_order_relaxed)), m_typeface(move(typeface))@@ -212,6 +223,42 @@ bool Font::is_emoji_font() constreturn m_is_emoji_font.load(AK::MemoryOrder::memory_order_relaxed) == TriState::True;}+static float harfbuzz_position_to_pixels(hb_position_t position)+{+ return static_cast<float>(position) / text_shaping_resolution;+}++// https://learn.microsoft.com/en-us/typography/opentype/spec/math#mathconstants-table+Font::MathData const& Font::math_data() const+{+ call_once(m_math_data_once, [&] {+ auto math_data = make<MathData>();+ auto* data = &math_data->data;+ data->has_math_table = hb_ot_math_has_data(hb_font_get_face(m_harfbuzz_font));+ if (data->has_math_table) {+ static_assert(HB_OT_MATH_CONSTANT_RADICAL_DEGREE_BOTTOM_RAISE_PERCENT + 1 == sizeof(FFI::FfiMathData::constants) / sizeof(float));+ for (size_t index = 0; index <= HB_OT_MATH_CONSTANT_RADICAL_DEGREE_BOTTOM_RAISE_PERCENT; ++index) {+ auto constant = static_cast<hb_ot_math_constant_t>(index);+ auto value = hb_ot_math_get_constant(m_harfbuzz_font, constant);+ // NB: HarfBuzz scales every constant to the font size, except for the three percentages.+ bool is_percentage = constant == HB_OT_MATH_CONSTANT_SCRIPT_PERCENT_SCALE_DOWN+ || constant == HB_OT_MATH_CONSTANT_SCRIPT_SCRIPT_PERCENT_SCALE_DOWN+ || constant == HB_OT_MATH_CONSTANT_RADICAL_DEGREE_BOTTOM_RAISE_PERCENT;+ data->constants[index] = is_percentage ? static_cast<float>(value) : harfbuzz_position_to_pixels(value);+ }+ data->horizontal_min_connector_overlap = harfbuzz_position_to_pixels(hb_ot_math_get_min_connector_overlap(m_harfbuzz_font, HB_DIRECTION_LTR));+ data->vertical_min_connector_overlap = harfbuzz_position_to_pixels(hb_ot_math_get_min_connector_overlap(m_harfbuzz_font, HB_DIRECTION_BTT));+ }++ hb_position_t position = 0;+ data->has_underline_thickness = hb_ot_metrics_get_position(m_harfbuzz_font, HB_OT_METRICS_TAG_UNDERLINE_SIZE, &position);+ data->underline_thickness = harfbuzz_position_to_pixels(position);++ m_math_data = move(math_data);+ });+ return *m_math_data;+}+}extern "C" void ladybird_gfx_font_snapshot(void const* font, Gfx::FFI::FfiFontSnapshot* out_snapshot)@@ -255,6 +302,74 @@ extern "C" bool ladybird_gfx_font_is_invisible(void const* font)return static_cast<Gfx::Font const*>(font)->is_invisible();}+extern "C" Gfx::FFI::FfiMathData const* ladybird_gfx_font_math_data(void const* font)+{+ VERIFY(font);+ return &static_cast<Gfx::Font const*>(font)->math_data().data;+}++extern "C" void ladybird_gfx_font_glyph_metrics(void const* font, u32 glyph_id, Gfx::FFI::FfiGlyphMetrics* out_metrics)+{+ VERIFY(font);+ VERIFY(out_metrics);+ auto* harfbuzz_font = static_cast<Gfx::Font const*>(font)->harfbuzz_font();+ hb_glyph_extents_t extents {};+ if (!hb_font_get_glyph_extents(harfbuzz_font, glyph_id, &extents))+ extents = {};+ *out_metrics = {+ .advance = Gfx::harfbuzz_position_to_pixels(hb_font_get_glyph_h_advance(harfbuzz_font, glyph_id)),+ .ascent = Gfx::harfbuzz_position_to_pixels(extents.y_bearing),+ .descent = -Gfx::harfbuzz_position_to_pixels(extents.y_bearing + extents.height),+ };+}++static hb_direction_t math_stretch_direction(bool horizontal)+{+ return horizontal ? HB_DIRECTION_LTR : HB_DIRECTION_BTT;+}++extern "C" size_t ladybird_gfx_font_math_glyph_variants(void const* font, u32 glyph_id, bool horizontal, Gfx::FFI::FfiMathGlyphVariant* out_variants, size_t capacity)+{+ VERIFY(font);+ VERIFY(out_variants || capacity == 0);+ auto* harfbuzz_font = static_cast<Gfx::Font const*>(font)->harfbuzz_font();+ Vector<hb_ot_math_glyph_variant_t, 8> variants;+ variants.resize(capacity);+ unsigned count = capacity;+ auto total = hb_ot_math_get_glyph_variants(harfbuzz_font, glyph_id, math_stretch_direction(horizontal), 0, &count, variants.data());+ for (size_t index = 0; index < count; ++index) {+ out_variants[index] = {+ .glyph_id = variants[index].glyph,+ .advance_measurement = Gfx::harfbuzz_position_to_pixels(variants[index].advance),+ };+ }+ return total;+}++extern "C" size_t ladybird_gfx_font_math_glyph_assembly(void const* font, u32 glyph_id, bool horizontal, Gfx::FFI::FfiMathGlyphPart* out_parts, size_t capacity, float* out_italics_correction)+{+ VERIFY(font);+ VERIFY(out_parts || capacity == 0);+ VERIFY(out_italics_correction);+ auto* harfbuzz_font = static_cast<Gfx::Font const*>(font)->harfbuzz_font();+ Vector<hb_ot_math_glyph_part_t, 8> parts;+ parts.resize(capacity);+ unsigned count = capacity;+ hb_position_t italics_correction = 0;+ auto total = hb_ot_math_get_glyph_assembly(harfbuzz_font, glyph_id, math_stretch_direction(horizontal), 0, &count, parts.data(), &italics_correction);+ for (size_t index = 0; index < count; ++index) {+ out_parts[index] = {+ .glyph_id = parts[index].glyph,+ .start_connector_length = Gfx::harfbuzz_position_to_pixels(parts[index].start_connector_length),+ .end_connector_length = Gfx::harfbuzz_position_to_pixels(parts[index].end_connector_length),+ .full_advance = Gfx::harfbuzz_position_to_pixels(parts[index].full_advance),+ .is_extender = (parts[index].flags & HB_OT_MATH_GLYPH_PART_FLAG_EXTENDER) != 0,+ };+ }+ *out_italics_correction = Gfx::harfbuzz_position_to_pixels(italics_correction);+ return total;+}+extern "C" void ladybird_gfx_font_ref(void const* font){VERIFY(font);diff --git a/Libraries/LibGfx/Font/Font.h b/Libraries/LibGfx/Font/Font.hindex fa3accd111a..6c231ee2780 100644--- a/Libraries/LibGfx/Font/Font.h+++ b/Libraries/LibGfx/Font/Font.h@@ -14,6 +14,7 @@#include <AK/FlyString.h>#include <AK/Once.h>#include <AK/Optional.h>+#include <AK/OwnPtr.h>#include <AK/RefPtr.h>#include <AK/Utf16String.h>#include <LibGfx/Font/RasterizerData.h>@@ -84,6 +85,10 @@ public:bool is_emoji_font() const;+ // The constants of the OpenType MATH table and the underline thickness of the post table, read on first use.+ struct MathData;+ MathData const& math_data() const;+// Called by AtomicRefCounted when the last reference goes away.void will_be_destroyed() const;@@ -109,6 +114,9 @@ private:// reads only the face's immutable tables.mutable Atomic<TriState> m_is_emoji_font { TriState::Unknown };+ mutable OnceFlag m_math_data_once;+ mutable OwnPtr<MathData> m_math_data;+NonnullRefPtr<Typeface const> m_typeface;float m_point_width { 0.0f };float m_point_height { 0.0f };diff --git a/Libraries/LibGfx/Rust/cbindgen.toml b/Libraries/LibGfx/Rust/cbindgen.tomlindex 2e530d803ea..b5edb172ac0 100644--- a/Libraries/LibGfx/Rust/cbindgen.toml+++ b/Libraries/LibGfx/Rust/cbindgen.toml@@ -14,9 +14,19 @@ usize_is_size_t = truenamespaces = ["Gfx", "FFI"]# The byte layout the filter codec writes is defined by these enums, and the C++ reader that-# builds Skia filters from it decodes them from the same definitions.+# builds Skia filters from it decodes them from the same definitions. The OpenType MATH table+# structs are filled in by LibGfx for its Rust callers.[export]-include = ["FilterOperationType", "ChannelSelector", "TurbulenceType", "PathVerb"]+include = [+ "FilterOperationType",+ "ChannelSelector",+ "TurbulenceType",+ "PathVerb",+ "FfiMathData",+ "FfiGlyphMetrics",+ "FfiMathGlyphVariant",+ "FfiMathGlyphPart",+][parse]parse_deps = falsediff --git a/Libraries/LibGfx/Rust/src/lib.rs b/Libraries/LibGfx/Rust/src/lib.rsindex d2cf581cccf..53ac490cdca 100644--- a/Libraries/LibGfx/Rust/src/lib.rs+++ b/Libraries/LibGfx/Rust/src/lib.rs@@ -21,6 +21,7 @@ pub mod font;pub mod font_catalog;pub mod geometry;pub mod image_frame;+pub mod math_table;pub mod matrix;pub mod paint_enums;pub mod path;diff --git a/Libraries/LibGfx/Rust/src/math_table.rs b/Libraries/LibGfx/Rust/src/math_table.rsnew file mode 100644index 00000000000..b55777d145f--- /dev/null+++ b/Libraries/LibGfx/Rust/src/math_table.rs@@ -0,0 +1,256 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The OpenType MATH table of a font, as HarfBuzz reads it.+//! https://learn.microsoft.com/en-us/typography/opentype/spec/math++use crate::font::FontHandle;+use std::ffi::c_void;++unsafe extern "C" {+ fn ladybird_gfx_font_math_data(font: *const c_void) -> *const FfiMathData;+ fn ladybird_gfx_font_glyph_metrics(font: *const c_void, glyph_id: u32, out_metrics: *mut FfiGlyphMetrics);+ fn ladybird_gfx_font_math_glyph_variants(+ font: *const c_void,+ glyph_id: u32,+ horizontal: bool,+ out_variants: *mut FfiMathGlyphVariant,+ capacity: usize,+ ) -> usize;+ fn ladybird_gfx_font_math_glyph_assembly(+ font: *const c_void,+ glyph_id: u32,+ horizontal: bool,+ out_parts: *mut FfiMathGlyphPart,+ capacity: usize,+ out_italics_correction: *mut f32,+ ) -> usize;+}++/// What LibGfx reads once per font from its OpenType MATH and post tables. Lengths are in pixels.+#[repr(C)]+#[derive(Clone, Copy, Debug)]+pub struct FfiMathData {+ pub has_math_table: bool,+ /// The MathConstants table, indexed by `MathConstant`. Percentages are in percent, every other constant is a+ /// length.+ pub constants: [f32; 56],+ pub horizontal_min_connector_overlap: f32,+ pub vertical_min_connector_overlap: f32,+ pub has_underline_thickness: bool,+ /// post.underlineThickness.+ pub underline_thickness: f32,+}++/// The ink extents of a glyph and its advance, in pixels.+#[repr(C)]+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct FfiGlyphMetrics {+ pub advance: f32,+ /// How far the ink of the glyph extends above the baseline.+ pub ascent: f32,+ /// How far the ink of the glyph extends below the baseline.+ pub descent: f32,+}++#[repr(C)]+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct FfiMathGlyphVariant {+ pub glyph_id: u32,+ pub advance_measurement: f32,+}++#[repr(C)]+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct FfiMathGlyphPart {+ pub glyph_id: u32,+ pub start_connector_length: f32,+ pub end_connector_length: f32,+ pub full_advance: f32,+ pub is_extender: bool,+}++/// The constants of the MathConstants table, numbered as HarfBuzz numbers them.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum MathConstant {+ ScriptPercentScaleDown = 0,+ ScriptScriptPercentScaleDown = 1,+ DelimitedSubFormulaMinHeight = 2,+ DisplayOperatorMinHeight = 3,+ MathLeading = 4,+ AxisHeight = 5,+ AccentBaseHeight = 6,+ FlattenedAccentBaseHeight = 7,+ SubscriptShiftDown = 8,+ SubscriptTopMax = 9,+ SubscriptBaselineDropMin = 10,+ SuperscriptShiftUp = 11,+ SuperscriptShiftUpCramped = 12,+ SuperscriptBottomMin = 13,+ SuperscriptBaselineDropMax = 14,+ SubSuperscriptGapMin = 15,+ SuperscriptBottomMaxWithSubscript = 16,+ SpaceAfterScript = 17,+ UpperLimitGapMin = 18,+ UpperLimitBaselineRiseMin = 19,+ LowerLimitGapMin = 20,+ LowerLimitBaselineDropMin = 21,+ StackTopShiftUp = 22,+ StackTopDisplayStyleShiftUp = 23,+ StackBottomShiftDown = 24,+ StackBottomDisplayStyleShiftDown = 25,+ StackGapMin = 26,+ StackDisplayStyleGapMin = 27,+ StretchStackTopShiftUp = 28,+ StretchStackBottomShiftDown = 29,+ StretchStackGapAboveMin = 30,+ StretchStackGapBelowMin = 31,+ FractionNumeratorShiftUp = 32,+ FractionNumeratorDisplayStyleShiftUp = 33,+ FractionDenominatorShiftDown = 34,+ FractionDenominatorDisplayStyleShiftDown = 35,+ FractionNumeratorGapMin = 36,+ FractionNumDisplayStyleGapMin = 37,+ FractionRuleThickness = 38,+ FractionDenominatorGapMin = 39,+ FractionDenomDisplayStyleGapMin = 40,+ SkewedFractionHorizontalGap = 41,+ SkewedFractionVerticalGap = 42,+ OverbarVerticalGap = 43,+ OverbarRuleThickness = 44,+ OverbarExtraAscender = 45,+ UnderbarVerticalGap = 46,+ UnderbarRuleThickness = 47,+ UnderbarExtraDescender = 48,+ RadicalVerticalGap = 49,+ RadicalDisplayStyleVerticalGap = 50,+ RadicalRuleThickness = 51,+ RadicalExtraAscender = 52,+ RadicalKernBeforeDegree = 53,+ RadicalKernAfterDegree = 54,+ RadicalDegreeBottomRaisePercent = 55,+}++impl FfiMathData {+ /// The value of a constant of the MathConstants table, or `None` if the font has no MATH table.+ pub fn constant(&self, constant: MathConstant) -> Option<f32> {+ self.has_math_table.then(|| self.constants[constant as usize])+ }++ pub fn underline_thickness(&self) -> Option<f32> {+ self.has_underline_thickness.then_some(self.underline_thickness)+ }++ pub fn min_connector_overlap(&self, axis: StretchAxis) -> f32 {+ match axis {+ StretchAxis::Inline => self.horizontal_min_connector_overlap,+ StretchAxis::Block => self.vertical_min_connector_overlap,+ }+ }+}++/// The direction a glyph is stretched along, in a horizontal writing mode.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StretchAxis {+ Inline,+ Block,+}++/// A GlyphAssembly table, with the italics correction it gives.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct MathGlyphAssembly {+ pub parts: Vec<FfiMathGlyphPart>,+ pub italics_correction: f32,+}++impl FontHandle {+ /// The MATH table constants and related metrics of the font, read once for the font's lifetime.+ pub fn math_data(&self) -> &FfiMathData {+ // SAFETY: The handle's retained reference keeps the font live, and the font keeps the data it read for as long+ // as it lives, never changing it.+ unsafe { &*ladybird_gfx_font_math_data(self.as_raw()) }+ }++ pub fn glyph_metrics(&self, glyph_id: u32) -> FfiGlyphMetrics {+ let mut metrics = FfiGlyphMetrics::default();+ // SAFETY: The handle's retained reference keeps the font live, and the out-pointer addresses a local.+ unsafe { ladybird_gfx_font_glyph_metrics(self.as_raw(), glyph_id, &raw mut metrics) };+ metrics+ }++ /// The MathGlyphVariantRecords of the MathGlyphConstruction table of the glyph along the axis.+ pub fn math_glyph_variants(&self, glyph_id: u32, axis: StretchAxis) -> Vec<FfiMathGlyphVariant> {+ let horizontal = axis == StretchAxis::Inline;+ let mut variants = vec![FfiMathGlyphVariant::default(); 8];+ // SAFETY: The handle's retained reference keeps the font live, and the buffer holds `capacity` entries.+ let count = unsafe {+ ladybird_gfx_font_math_glyph_variants(+ self.as_raw(),+ glyph_id,+ horizontal,+ variants.as_mut_ptr(),+ variants.len(),+ )+ };+ if count > variants.len() {+ variants.resize(count, FfiMathGlyphVariant::default());+ // SAFETY: As above.+ unsafe {+ ladybird_gfx_font_math_glyph_variants(+ self.as_raw(),+ glyph_id,+ horizontal,+ variants.as_mut_ptr(),+ variants.len(),+ )+ };+ }+ variants.truncate(count);+ variants+ }++ /// The GlyphAssembly table of the MathGlyphConstruction table of the glyph along the axis, if it has one.+ pub fn math_glyph_assembly(&self, glyph_id: u32, axis: StretchAxis) -> Option<MathGlyphAssembly> {+ let horizontal = axis == StretchAxis::Inline;+ let mut parts = vec![FfiMathGlyphPart::default(); 8];+ let mut italics_correction = 0.0;+ // SAFETY: The handle's retained reference keeps the font live, the buffer holds `capacity` entries, and the+ // out-pointer addresses a local.+ let count = unsafe {+ ladybird_gfx_font_math_glyph_assembly(+ self.as_raw(),+ glyph_id,+ horizontal,+ parts.as_mut_ptr(),+ parts.len(),+ &raw mut italics_correction,+ )+ };+ if count == 0 {+ return None;+ }+ if count > parts.len() {+ parts.resize(count, FfiMathGlyphPart::default());+ // SAFETY: As above.+ unsafe {+ ladybird_gfx_font_math_glyph_assembly(+ self.as_raw(),+ glyph_id,+ horizontal,+ parts.as_mut_ptr(),+ parts.len(),+ &raw mut italics_correction,+ )+ };+ }+ parts.truncate(count);+ Some(MathGlyphAssembly {+ parts,+ italics_correction,+ })+ }+}