Truly independent web browser
LibWeb: Implement TextMetrics in Rust
Andreas Klingb6d05280ec0e
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex df1d7bfad9f..8459d015719 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -16,6 +16,7 @@ use libcompositing_rust::display_list::commands::Canvas2DPaintKind;use libjs_rust::api::Vm;use super::canvas_gradient::CanvasGradient;+use super::text_metrics::{TextMeasurements, TextMetrics};use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi};/// # Safety@@ -160,3 +161,13 @@ pub unsafe extern "C" fn web_canvas_gradient_lend_paint<'a>(// SAFETY: The caller adds no stop while the paint is in use.lend_paint(unsafe { gradient.paint_unguarded() }, out_paint);}++/// # Safety+///+/// `vm` must be the live VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_metrics_create(vm: *mut c_void, measurements: &TextMeasurements) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ cell_into_abi(TextMetrics::create(vm, *measurements))+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex 4d694d15361..e8b12848d10 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -14,3 +14,5 @@ pub(crate) mod color_stops;pub(crate) mod canvas_gradient;#[cfg(not(test))]pub(crate) mod exports;+#[cfg(not(test))]+pub(crate) mod text_metrics;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/text_metrics.rs b/Libraries/LibWeb/Bindings/Rust/src/html/text_metrics.rsnew file mode 100644index 00000000000..519a7cf44f1--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/text_metrics.rs@@ -0,0 +1,96 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://html.spec.whatwg.org/multipage/canvas.html#textmetrics++use libjs_rust::api::{Trace, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};++/// The measurements of a text, in CSS pixels, which measureText() takes, as the members of TextMetrics describe them.+#[derive(Clone, Copy, Debug, Default)]+#[repr(C)]+pub(crate) struct TextMeasurements {+ // x-direction+ pub(crate) width: f64,+ pub(crate) actual_bounding_box_left: f64,+ pub(crate) actual_bounding_box_right: f64,++ // y-direction+ pub(crate) font_bounding_box_ascent: f64,+ pub(crate) font_bounding_box_descent: f64,+ pub(crate) actual_bounding_box_ascent: f64,+ pub(crate) actual_bounding_box_descent: f64,+ pub(crate) em_height_ascent: f64,+ pub(crate) em_height_descent: f64,+ pub(crate) hanging_baseline: f64,+ pub(crate) alphabetic_baseline: f64,+ pub(crate) ideographic_baseline: f64,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct TextMetrics {+ #[gc(untraced)]+ measurements: TextMeasurements,+}++impl Wrappable for TextMetrics {}++impl TextMetrics {+ pub(crate) fn create(vm: &Vm, measurements: TextMeasurements) -> Ref<Self> {+ allocate(vm, Self { measurements })+ }++ pub(crate) fn width(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.width)+ }++ pub(crate) fn actual_bounding_box_left(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.actual_bounding_box_left)+ }++ pub(crate) fn actual_bounding_box_right(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.actual_bounding_box_right)+ }++ pub(crate) fn font_bounding_box_ascent(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.font_bounding_box_ascent)+ }++ pub(crate) fn font_bounding_box_descent(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.font_bounding_box_descent)+ }++ pub(crate) fn actual_bounding_box_ascent(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.actual_bounding_box_ascent)+ }++ pub(crate) fn actual_bounding_box_descent(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.actual_bounding_box_descent)+ }++ pub(crate) fn em_height_ascent(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.em_height_ascent)+ }++ pub(crate) fn em_height_descent(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.em_height_descent)+ }++ pub(crate) fn hanging_baseline(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.hanging_baseline)+ }++ pub(crate) fn alphabetic_baseline(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.alphabetic_baseline)+ }++ pub(crate) fn ideographic_baseline(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.measurements.ideographic_baseline)+ }+}diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cppindex 5cafa02f379..73c9fafd06a 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp@@ -948,7 +948,7 @@ GC::Ref<TextMetrics> Canvas2DContextBase::measure_text(Utf16View text)// TextMetrics object with members behaving as described in the following// list:auto prepared_text = prepare_text(text);- auto metrics = TextMetrics::create();+ TextMeasurements metrics;// FIXME: Use the font that was used to create the glyphs in prepared_text.auto const& font = font_cascade_list()->first();auto const& font_pixel_metrics = font.pixel_metrics();@@ -977,31 +977,31 @@ GC::Ref<TextMetrics> Canvas2DContextBase::measure_text(Utf16View text)}// width attribute: The width of that inline box, in CSS pixels. (The text's advance width.)- metrics->set_width(prepared_text.bounding_box.width());+ metrics.width = prepared_text.bounding_box.width();// actualBoundingBoxLeft attribute: The distance parallel to the baseline from the alignment point given by the textAlign attribute to the left side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going left from the given alignment point.- metrics->set_actual_bounding_box_left(-prepared_text.bounding_box.left());+ metrics.actual_bounding_box_left = -prepared_text.bounding_box.left();// actualBoundingBoxRight attribute: The distance parallel to the baseline from the alignment point given by the textAlign attribute to the right side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going right from the given alignment point.- metrics->set_actual_bounding_box_right(prepared_text.bounding_box.right());+ metrics.actual_bounding_box_right = prepared_text.bounding_box.right();// fontBoundingBoxAscent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the ascent metric of the first available font, in CSS pixels; positive numbers indicating a distance going up from the given baseline.- metrics->set_font_bounding_box_ascent(ascent - baseline_offset);+ metrics.font_bounding_box_ascent = ascent - baseline_offset;// fontBoundingBoxDescent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the descent metric of the first available font, in CSS pixels; positive numbers indicating a distance going down from the given baseline.- metrics->set_font_bounding_box_descent(descent + baseline_offset);+ metrics.font_bounding_box_descent = descent + baseline_offset;// actualBoundingBoxAscent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the top of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going up from the given baseline.- metrics->set_actual_bounding_box_ascent(ascent - baseline_offset);+ metrics.actual_bounding_box_ascent = ascent - baseline_offset;// actualBoundingBoxDescent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the bottom of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going down from the given baseline.- metrics->set_actual_bounding_box_descent(descent + baseline_offset);+ metrics.actual_bounding_box_descent = descent + baseline_offset;// emHeightAscent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the highest top of the em squares in the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the top of that em square (so this value will usually be positive). Zero if the given baseline is the top of that em square; half the font size if the given baseline is the middle of that em square.- metrics->set_em_height_ascent(ascent - baseline_offset);+ metrics.em_height_ascent = ascent - baseline_offset;// emHeightDescent attribute: The distance from the horizontal line indicated by the textBaseline attribute to the lowest bottom of the em squares in the inline box, in CSS pixels; positive numbers indicating that the given baseline is above the bottom of that em square. (Zero if the given baseline is the bottom of that em square.)- metrics->set_em_height_descent(descent + baseline_offset);+ metrics.em_height_descent = descent + baseline_offset;// hangingBaseline attribute: The distance from the horizontal line indicated by the textBaseline attribute to the hanging baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the hanging baseline. (Zero if the given baseline is the hanging baseline.)- metrics->set_hanging_baseline(hanging_baseline - baseline_offset);+ metrics.hanging_baseline = hanging_baseline - baseline_offset;// alphabeticBaseline attribute: The distance from the horizontal line indicated by the textBaseline attribute to the alphabetic baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the alphabetic baseline. (Zero if the given baseline is the alphabetic baseline.)- metrics->set_alphabetic_baseline(-baseline_offset);+ metrics.alphabetic_baseline = -baseline_offset;// ideographicBaseline attribute: The distance from the horizontal line indicated by the textBaseline attribute to the ideographic-under baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the ideographic-under baseline. (Zero if the given baseline is the ideographic-under baseline.)- metrics->set_ideographic_baseline(-descent - baseline_offset);+ metrics.ideographic_baseline = -descent - baseline_offset;- return metrics;+ return TextMetrics::create(metrics);}RefPtr<Gfx::FontCascadeList const> Canvas2DContextBase::font_cascade_list()diff --git a/Libraries/LibWeb/HTML/TextMetrics.cpp b/Libraries/LibWeb/HTML/TextMetrics.cppindex f1921a71c47..59a8c5a8847 100644--- a/Libraries/LibWeb/HTML/TextMetrics.cpp+++ b/Libraries/LibWeb/HTML/TextMetrics.cpp@@ -4,23 +4,23 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/HTML/TextMetrics.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::HTML {-GC_DEFINE_ALLOCATOR(TextMetrics);+// NB: `TextMeasurements` of Bindings/Rust/src/html/text_metrics.rs is twelve doubles in this order.+static_assert(sizeof(TextMeasurements) == 12 * sizeof(double));+static_assert(offsetof(TextMeasurements, actual_bounding_box_right) == 2 * sizeof(double));+static_assert(offsetof(TextMeasurements, ideographic_baseline) == 11 * sizeof(double));-GC::Ref<TextMetrics> TextMetrics::create()-{- return GC::Heap::the().allocate<TextMetrics>();-}+// Defined in Bindings/Rust/src/html/exports.rs.+extern "C" void* web_text_metrics_create(JSVM*, TextMeasurements const*);-TextMetrics::TextMetrics()+GC::Ref<TextMetrics> TextMetrics::create(TextMeasurements const& measurements){+ return *static_cast<TextMetrics*>(web_text_metrics_create(JS::HostABI::vm_to_abi(JS::VM::the()), &measurements));}-TextMetrics::~TextMetrics() = default;-}diff --git a/Libraries/LibWeb/HTML/TextMetrics.h b/Libraries/LibWeb/HTML/TextMetrics.hindex 0526222169f..32442286a5e 100644--- a/Libraries/LibWeb/HTML/TextMetrics.h+++ b/Libraries/LibWeb/HTML/TextMetrics.h@@ -6,61 +6,40 @@#pragma once-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Bindings/TextMetrics.h>+#include <LibWeb/Export.h>namespace Web::HTML {-class TextMetrics : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(TextMetrics, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(TextMetrics);--public:- [[nodiscard]] static GC::Ref<TextMetrics> create();-- virtual ~TextMetrics() override;-- double width() const { return m_width; }- double actual_bounding_box_left() const { return m_actual_bounding_box_left; }- double actual_bounding_box_right() const { return m_actual_bounding_box_right; }- double font_bounding_box_ascent() const { return m_font_bounding_box_ascent; }- double font_bounding_box_descent() const { return m_font_bounding_box_descent; }- double actual_bounding_box_ascent() const { return m_actual_bounding_box_ascent; }- double actual_bounding_box_descent() const { return m_actual_bounding_box_descent; }- double em_height_ascent() const { return m_em_height_ascent; }- double em_height_descent() const { return m_em_height_descent; }- double hanging_baseline() const { return m_hanging_baseline; }- double alphabetic_baseline() const { return m_alphabetic_baseline; }- double ideographic_baseline() const { return m_ideographic_baseline; }-- void set_width(double width) { m_width = width; }- void set_actual_bounding_box_left(double left) { m_actual_bounding_box_left = left; }- void set_actual_bounding_box_right(double right) { m_actual_bounding_box_right = right; }- void set_font_bounding_box_ascent(double ascent) { m_font_bounding_box_ascent = ascent; }- void set_font_bounding_box_descent(double descent) { m_font_bounding_box_descent = descent; }- void set_actual_bounding_box_ascent(double ascent) { m_actual_bounding_box_ascent = ascent; }- void set_actual_bounding_box_descent(double descent) { m_actual_bounding_box_descent = descent; }- void set_em_height_ascent(double ascent) { m_em_height_ascent = ascent; }- void set_em_height_descent(double descent) { m_em_height_descent = descent; }- void set_hanging_baseline(double baseline) { m_hanging_baseline = baseline; }- void set_alphabetic_baseline(double baseline) { m_alphabetic_baseline = baseline; }- void set_ideographic_baseline(double baseline) { m_ideographic_baseline = baseline; }--private:- explicit TextMetrics();+// The measurements of a text, in CSS pixels, as the members of TextMetrics describe them. `TextMeasurements` of+// Bindings/Rust/src/html/text_metrics.rs mirrors it.+struct TextMeasurements {+ // x-direction+ double width { 0 };+ double actual_bounding_box_left { 0 };+ double actual_bounding_box_right { 0 };++ // y-direction+ double font_bounding_box_ascent { 0 };+ double font_bounding_box_descent { 0 };+ double actual_bounding_box_ascent { 0 };+ double actual_bounding_box_descent { 0 };+ double em_height_ascent { 0 };+ double em_height_descent { 0 };+ double hanging_baseline { 0 };+ double alphabetic_baseline { 0 };+ double ideographic_baseline { 0 };+};- double m_width { 0 };- double m_actual_bounding_box_left { 0 };- double m_actual_bounding_box_right { 0 };+// https://html.spec.whatwg.org/multipage/canvas.html#textmetrics+// The C++ side of a TextMetrics, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what+// measureText() returns.+class WEB_API TextMetrics final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(TextMetrics, text_metrics)- double m_font_bounding_box_ascent { 0 };- double m_font_bounding_box_descent { 0 };- double m_actual_bounding_box_ascent { 0 };- double m_actual_bounding_box_descent { 0 };- double m_em_height_ascent { 0 };- double m_em_height_descent { 0 };- double m_hanging_baseline { 0 };- double m_alphabetic_baseline { 0 };- double m_ideographic_baseline { 0 };+public:+ [[nodiscard]] static GC::Ref<TextMetrics> create(TextMeasurements const&);};}diff --git a/Libraries/LibWeb/HTML/TextMetrics.idl b/Libraries/LibWeb/HTML/TextMetrics.idlindex 4b3ebe5e4f7..6461c24bc78 100644--- a/Libraries/LibWeb/HTML/TextMetrics.idl+++ b/Libraries/LibWeb/HTML/TextMetrics.idl@@ -1,5 +1,5 @@// https://html.spec.whatwg.org/multipage/canvas.html#textmetrics-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface TextMetrics {// x-directionreadonly attribute double width; // advance widthdiff --git a/Tests/LibWeb/Text/expected/canvas/textmetrics-attributes.txt b/Tests/LibWeb/Text/expected/canvas/textmetrics-attributes.txtnew file mode 100644index 00000000000..d4bd222ade2--- /dev/null+++ b/Tests/LibWeb/Text/expected/canvas/textmetrics-attributes.txt@@ -0,0 +1,19 @@+metrics is a TextMetrics: true+toString tag: [object TextMetrics]+width: number, finite true+actualBoundingBoxLeft: number, finite true+actualBoundingBoxRight: number, finite true+fontBoundingBoxAscent: number, finite true+fontBoundingBoxDescent: number, finite true+actualBoundingBoxAscent: number, finite true+actualBoundingBoxDescent: number, finite true+emHeightAscent: number, finite true+emHeightDescent: number, finite true+hangingBaseline: number, finite true+alphabeticBaseline: number, finite true+ideographicBaseline: number, finite true+width is positive: true+empty text has zero width: true+each call returns a new object: true+width getter on a plain object: TypeError+new TextMetrics(): TypeErrordiff --git a/Tests/LibWeb/Text/input/canvas/textmetrics-attributes.html b/Tests/LibWeb/Text/input/canvas/textmetrics-attributes.htmlnew file mode 100644index 00000000000..b940633576c--- /dev/null+++ b/Tests/LibWeb/Text/input/canvas/textmetrics-attributes.html@@ -0,0 +1,29 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ const context = document.createElement("canvas").getContext("2d");+ const metrics = context.measureText("Hello");+ println(`metrics is a TextMetrics: ${metrics instanceof TextMetrics}`);+ println(`toString tag: ${Object.prototype.toString.call(metrics)}`);+ for (const name of Object.getOwnPropertyNames(TextMetrics.prototype)) {+ if (name === "constructor")+ continue;+ const value = metrics[name];+ println(`${name}: ${typeof value}, finite ${Number.isFinite(value)}`);+ }+ println(`width is positive: ${metrics.width > 0}`);+ println(`empty text has zero width: ${context.measureText("").width === 0}`);+ println(`each call returns a new object: ${context.measureText("a") !== context.measureText("a")}`);+ try {+ Object.getOwnPropertyDescriptor(TextMetrics.prototype, "width").get.call({});+ } catch (e) {+ println(`width getter on a plain object: ${e.constructor.name}`);+ }+ try {+ new TextMetrics();+ } catch (e) {+ println(`new TextMetrics(): ${e.constructor.name}`);+ }+ });+</script>