Skip to content

Truly independent web browser

LibGfx: Read typeface family and style from the font tables

Aliaksandr Kalenik8ecb07c4a724
diff --git a/Libraries/LibGfx/CMakeLists.txt b/Libraries/LibGfx/CMakeLists.txt
index 10e27efce3c..70e775b32ca 100644
--- a/Libraries/LibGfx/CMakeLists.txt
+++ b/Libraries/LibGfx/CMakeLists.txt
@@ -11,10 +11,12 @@ set(SOURCES
CornerRadii.cpp
Cursor.cpp
Filter.cpp
+ Font/FaceDescription.cpp
Font/Font.cpp
Font/FontCatalog.cpp
Font/FontDatabase.cpp
Font/FontSupport.cpp
+ Font/FontTable.cpp
Font/FontVariationSettings.cpp
Font/PathFontProvider.cpp
Font/SharedFontProvider.cpp
diff --git a/Libraries/LibGfx/Font/FaceDescription.cpp b/Libraries/LibGfx/Font/FaceDescription.cpp
new file mode 100644
index 00000000000..76cac3a5c56
--- /dev/null
+++ b/Libraries/LibGfx/Font/FaceDescription.cpp
@@ -0,0 +1,195 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Array.h>
+#include <AK/Utf16View.h>
+#include <LibGfx/Font/FaceDescription.h>
+#include <LibGfx/Font/FontTable.h>
+
+#include <harfbuzz/hb-ot.h>
+#include <math.h>
+
+namespace Gfx {
+
+static constexpr u8 upright_slope = 0;
+static constexpr u8 italic_slope = 1;
+static constexpr u8 oblique_slope = 2;
+
+// https://learn.microsoft.com/en-us/typography/opentype/spec/name#platform-ids
+// HarfBuzz looks names up by their language, and a record of the Unicode platform has no language, so read such a
+// record here. Its string is UTF-16BE.
+static Optional<String> unicode_platform_name(hb_face_t* face, u16 name_id)
+{
+ FontTable table { face, FourCC { "name" } };
+ if (!table.contains(0, 6))
+ return {};
+ size_t record_count = table.u16_at(2);
+ size_t storage_offset = table.u16_at(4);
+ for (size_t index = 0; index < record_count && table.contains(6 + 12 * index, 12); ++index) {
+ auto record = 6 + 12 * index;
+ if (table.u16_at(record) != 0 || table.u16_at(record + 6) != name_id)
+ continue;
+ size_t length = table.u16_at(record + 8);
+ size_t offset = storage_offset + table.u16_at(record + 10);
+ if (length == 0 || !table.contains(offset, length))
+ continue;
+ Vector<char16_t> code_units;
+ code_units.ensure_capacity(length / 2);
+ // Some fonts end a name with U+0000.
+ for (size_t unit = 0; unit + 1 < length && table.u16_at(offset + unit) != 0; unit += 2)
+ code_units.unchecked_append(static_cast<char16_t>(table.u16_at(offset + unit)));
+ auto name = String::from_utf16_with_replacement_character(Utf16View { code_units.data(), code_units.size() });
+ if (!name.is_error())
+ return name.release_value();
+ }
+ return {};
+}
+
+// https://learn.microsoft.com/en-us/typography/opentype/spec/name#name-ids
+static Optional<String> read_family(hb_face_t* face)
+{
+ // A face has a WWS family name only if its typographic family also differs in styles other than weight, width and
+ // slope, such as optical size. CSS tells the faces of a family apart only by weight, width and slope, so such a
+ // face is in a family of its own.
+ for (auto name_id : { HB_OT_NAME_ID_WWS_FAMILY, HB_OT_NAME_ID_TYPOGRAPHIC_FAMILY, HB_OT_NAME_ID_FONT_FAMILY }) {
+ auto name = face_name(face, name_id);
+ if (!name.has_value())
+ name = unicode_platform_name(face, name_id);
+ if (name.has_value() && !name->is_empty())
+ return name;
+ }
+ return {};
+}
+
+// https://learn.microsoft.com/en-us/typography/opentype/spec/os2#fsselection
+static constexpr u16 italic_selection_bit = 1 << 0;
+static constexpr u16 oblique_selection_bit = 1 << 9;
+
+// https://learn.microsoft.com/en-us/typography/opentype/spec/head
+static constexpr u16 bold_mac_style_bit = 1 << 0;
+static constexpr u16 italic_mac_style_bit = 1 << 1;
+
+static FaceStyle read_declared_style(hb_face_t* face)
+{
+ FaceStyle style;
+
+ u16 mac_style = 0;
+ if (FontTable head { face, FourCC { "head" } }; head.contains(44, 2))
+ mac_style = head.u16_at(44);
+
+ // https://learn.microsoft.com/en-us/typography/opentype/spec/os2
+ FontTable os2 { face, FourCC { "OS/2" } };
+ if (os2.contains(0, 64)) {
+ style.weight = os2.u16_at(4);
+ style.width = os2.u16_at(6);
+ auto selection = os2.u16_at(62);
+ if (selection & oblique_selection_bit)
+ style.slope = oblique_slope;
+ else if (selection & italic_selection_bit)
+ style.slope = italic_slope;
+ } else if (mac_style & bold_mac_style_bit) {
+ style.weight = 700;
+ }
+ if (style.slope == upright_slope && (mac_style & italic_mac_style_bit))
+ style.slope = italic_slope;
+ return style;
+}
+
+FaceDescription FaceDescription::read(hb_face_t* face)
+{
+ FaceDescription description;
+ if (auto family = read_family(face); family.has_value())
+ description.m_family = FlyString { family.release_value() };
+ description.m_declared_style = read_declared_style(face);
+
+ // https://learn.microsoft.com/en-us/typography/opentype/spec/fvar
+ auto axis_count = hb_ot_var_get_axis_count(face);
+ if (axis_count > 0) {
+ Vector<hb_ot_var_axis_info_t> axes;
+ axes.resize(axis_count);
+ hb_ot_var_get_axis_infos(face, 0, &axis_count, axes.data());
+
+ // The upper 16 bits of the face index select a named instance, counting from 1, and the face starts at its
+ // coordinates. An index that no instance has selects the default coordinates.
+ Vector<float> instance_coordinates;
+ if (auto instance = hb_face_get_index(face) >> 16; instance > 0) {
+ instance_coordinates.resize(axis_count);
+ auto coordinate_count = axis_count;
+ if (hb_ot_var_named_instance_get_design_coords(face, instance - 1, &coordinate_count, instance_coordinates.data()) != axis_count)
+ instance_coordinates.clear();
+ }
+
+ for (size_t index = 0; index < axis_count; ++index) {
+ auto const& axis = axes[index];
+ auto face_value = instance_coordinates.is_empty() ? axis.default_value : instance_coordinates[index];
+ description.m_axes.append({
+ .tag = axis.tag,
+ .minimum = axis.min_value,
+ .face_value = clamp(face_value, axis.min_value, axis.max_value),
+ .maximum = axis.max_value,
+ });
+ }
+ }
+
+ description.m_style = description.style_for_variations({});
+ return description;
+}
+
+// https://learn.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass
+static u16 width_class_for_percentage(float percentage)
+{
+ static constexpr Array<float, 9> class_percentages { 50, 62.5f, 75, 87.5f, 100, 112.5f, 125, 150, 200 };
+ size_t nearest = 0;
+ for (size_t index = 1; index < class_percentages.size(); ++index) {
+ if (fabsf(class_percentages[index] - percentage) < fabsf(class_percentages[nearest] - percentage))
+ nearest = index;
+ }
+ return nearest + 1;
+}
+
+FaceStyle FaceDescription::style_for_variations(ReadonlySpan<FontVariationAxis> variations) const
+{
+ int weight = m_declared_style.weight;
+ int width = m_declared_style.width;
+ Optional<float> italic;
+ Optional<float> slant;
+ for (auto const& axis : m_axes) {
+ // The last variation of an axis applies.
+ auto value = axis.face_value;
+ for (size_t index = variations.size(); index-- > 0;) {
+ if (variations[index].tag.to_u32() == axis.tag) {
+ value = clamp(variations[index].value, axis.minimum, axis.maximum);
+ break;
+ }
+ }
+
+ if (axis.tag == HB_OT_TAG_VAR_AXIS_WEIGHT)
+ weight = static_cast<int>(roundf(value));
+ else if (axis.tag == HB_OT_TAG_VAR_AXIS_WIDTH)
+ width = width_class_for_percentage(value);
+ else if (axis.tag == HB_OT_TAG_VAR_AXIS_ITALIC)
+ italic = value;
+ else if (axis.tag == HB_OT_TAG_VAR_AXIS_SLANT)
+ slant = value;
+ }
+
+ // https://learn.microsoft.com/en-us/typography/opentype/spec/dvaraxisreg
+ // An ital or slnt axis decides whether the face is italic or oblique, in place of the tables.
+ u8 slope = upright_slope;
+ if (italic.has_value() ? *italic >= 0.5f : m_declared_style.slope == italic_slope)
+ slope = italic_slope;
+ else if (slant.has_value() ? *slant != 0 : m_declared_style.slope == oblique_slope)
+ slope = oblique_slope;
+
+ return {
+ // CSS font weights start at 1, but some fonts give 0.
+ .weight = static_cast<u16>(clamp(weight, 1, 1000)),
+ .width = static_cast<u16>(clamp(width, 1, 9)),
+ .slope = slope,
+ };
+}
+
+}
diff --git a/Libraries/LibGfx/Font/FaceDescription.h b/Libraries/LibGfx/Font/FaceDescription.h
new file mode 100644
index 00000000000..a64d07da25a
--- /dev/null
+++ b/Libraries/LibGfx/Font/FaceDescription.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/FlyString.h>
+#include <AK/Span.h>
+#include <AK/Vector.h>
+#include <LibGfx/Font/FontVariationSettings.h>
+
+struct hb_face_t;
+
+namespace Gfx {
+
+// The weight and the width use the scales of the OS/2 table. The slope is 0 for upright, 1 for italic and 2 for oblique.
+struct FaceStyle {
+ u16 weight { 400 };
+ u16 width { 5 };
+ u8 slope { 0 };
+
+ bool operator==(FaceStyle const&) const = default;
+};
+
+// The family and the style of a face, read from its tables.
+class FaceDescription {
+public:
+ static FaceDescription read(hb_face_t*);
+
+ FlyString const& family() const { return m_family; }
+ FaceStyle style() const { return m_style; }
+
+ // The style of the face with these variations applied.
+ FaceStyle style_for_variations(ReadonlySpan<FontVariationAxis>) const;
+
+private:
+ struct VariationAxis {
+ u32 tag { 0 };
+ float minimum { 0 };
+ // The default value, or the value of the named instance that the face index selects.
+ float face_value { 0 };
+ float maximum { 0 };
+ };
+
+ FlyString m_family;
+ // The style that the OS/2 and head tables give, which the axes of a variable face can change.
+ FaceStyle m_declared_style;
+ FaceStyle m_style;
+ Vector<VariationAxis> m_axes;
+};
+
+}
diff --git a/Libraries/LibGfx/Font/Font.cpp b/Libraries/LibGfx/Font/Font.cpp
index 08f4a4016b7..2c04e1c7ae4 100644
--- a/Libraries/LibGfx/Font/Font.cpp
+++ b/Libraries/LibGfx/Font/Font.cpp
@@ -49,6 +49,7 @@ Font::Font(NonnullRefPtr<Typeface const> typeface, float point_width, float poin
, m_shape_features(features)
{
m_pixel_size = m_point_height * (DEFAULT_DPI / POINTS_PER_INCH);
+ m_style = m_typeface->style_for_variations(m_font_variation_settings.to_sorted_list());
auto const* sk_typeface = as<TypefaceSkia>(*m_typeface).sk_typeface();
SkFont const font { sk_ref_sp(sk_typeface), m_pixel_size };
diff --git a/Libraries/LibGfx/Font/Font.h b/Libraries/LibGfx/Font/Font.h
index 3897f3292f1..3243e789ce1 100644
--- a/Libraries/LibGfx/Font/Font.h
+++ b/Libraries/LibGfx/Font/Font.h
@@ -75,8 +75,9 @@ public:
float point_size() const;
float pixel_size() const;
FontPixelMetrics const& pixel_metrics() const { return m_pixel_metrics; }
- u8 slope() const { return m_typeface->slope(); }
- u16 weight() const { return m_typeface->weight(); }
+ u8 slope() const { return m_style.slope; }
+ u16 weight() const { return m_style.weight; }
+ u16 width() const { return m_style.width; }
bool contains_glyph(u32 code_point) const { return m_typeface->glyph_id_for_code_point(code_point) > 0; }
u32 glyph_id_for_code_point(u32 code_point) const { return m_typeface->glyph_id_for_code_point(code_point); }
int x_height() const { return m_point_height; } // FIXME: Read from font
@@ -124,6 +125,7 @@ private:
FontVariationSettings const m_font_variation_settings;
ShapeFeatures m_shape_features;
FontPixelMetrics m_pixel_metrics;
+ FaceStyle m_style;
float m_pixel_size { 0.0f };
};
diff --git a/Libraries/LibGfx/Font/FontTable.cpp b/Libraries/LibGfx/Font/FontTable.cpp
new file mode 100644
index 00000000000..39dcaf8c57c
--- /dev/null
+++ b/Libraries/LibGfx/Font/FontTable.cpp
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Assertions.h>
+#include <AK/NumericLimits.h>
+#include <AK/Optional.h>
+#include <AK/Vector.h>
+#include <LibGfx/Font/FontTable.h>
+
+#include <harfbuzz/hb-ot.h>
+#include <harfbuzz/hb.h>
+
+namespace Gfx {
+
+u8 FontDataReader::u8_at(size_t offset) const
+{
+ VERIFY(contains(offset, 1));
+ return m_bytes[offset];
+}
+
+u16 FontDataReader::u16_at(size_t offset) const
+{
+ VERIFY(contains(offset, 2));
+ return static_cast<u16>((m_bytes[offset] << 8) | m_bytes[offset + 1]);
+}
+
+u32 FontDataReader::u32_at(size_t offset) const
+{
+ VERIFY(contains(offset, 4));
+ return (static_cast<u32>(m_bytes[offset]) << 24)
+ | (static_cast<u32>(m_bytes[offset + 1]) << 16)
+ | (static_cast<u32>(m_bytes[offset + 2]) << 8)
+ | static_cast<u32>(m_bytes[offset + 3]);
+}
+
+struct TableLocation {
+ size_t offset { 0 };
+ size_t length { 0 };
+};
+
+// https://learn.microsoft.com/en-us/typography/opentype/spec/otff#table-directory
+static Optional<TableLocation> find_table(FontDataReader const& data, unsigned face_index, FourCC tag)
+{
+ size_t directory_offset = 0;
+ // https://learn.microsoft.com/en-us/typography/opentype/spec/otff#ttc-header
+ if (data.contains(0, 4) && data.u32_at(0) == FourCC { "ttcf" }.to_u32()) {
+ if (!data.contains(8, 4) || face_index >= data.u32_at(8) || !data.contains(12 + 4 * static_cast<size_t>(face_index), 4))
+ return {};
+ directory_offset = data.u32_at(12 + 4 * face_index);
+ }
+ if (!data.contains(directory_offset, 12))
+ return {};
+
+ auto table_count = data.u16_at(directory_offset + 4);
+ for (size_t index = 0; index < table_count; ++index) {
+ auto record_offset = directory_offset + 12 + 16 * index;
+ if (!data.contains(record_offset, 16))
+ return {};
+ if (data.u32_at(record_offset) != tag.to_u32())
+ continue;
+ size_t offset = data.u32_at(record_offset + 8);
+ size_t length = data.u32_at(record_offset + 12);
+ if (offset > data.bytes().size())
+ continue;
+ if (length > data.bytes().size() - offset) {
+ // Metrics tables are simple enough to cut off at the end of the data.
+ if (tag != FourCC { "hmtx" } && tag != FourCC { "vmtx" })
+ continue;
+ length = (data.bytes().size() - offset) & ~static_cast<size_t>(3);
+ }
+ if (length == 0)
+ return {};
+ return TableLocation { offset, length };
+ }
+ return {};
+}
+
+Optional<String> face_name(hb_face_t* face, u16 name_id)
+{
+ unsigned entry_count = 0;
+ auto const* entries = hb_ot_name_list_names(face, &entry_count);
+ hb_language_t language = HB_LANGUAGE_INVALID;
+ for (unsigned index = 0; index < entry_count; ++index) {
+ auto const& entry = entries[index];
+ if (entry.name_id != name_id)
+ continue;
+ if (language == HB_LANGUAGE_INVALID)
+ language = entry.language;
+ if (entry.language == hb_language_from_string("en", -1) || entry.language == hb_language_from_string("en-us", -1)) {
+ language = entry.language;
+ break;
+ }
+ }
+ if (language == HB_LANGUAGE_INVALID)
+ return {};
+ auto length = hb_ot_name_get_utf8(face, name_id, language, nullptr, nullptr);
+ if (length == 0 || length == NumericLimits<unsigned>::max())
+ return {};
+ Vector<char> name;
+ if (name.try_resize(length + 1).is_error())
+ return {};
+ auto capacity = length + 1;
+ hb_ot_name_get_utf8(face, name_id, language, &capacity, name.data());
+ auto result = String::from_utf8({ name.data(), capacity });
+ if (result.is_error())
+ return {};
+ return result.release_value();
+}
+
+FontTable::FontTable(hb_face_t* face, FourCC tag)
+{
+ m_blob = hb_face_reference_blob(face);
+ unsigned data_length = 0;
+ auto const* data_pointer = hb_blob_get_data(m_blob, &data_length);
+ if (data_pointer && data_length > 0) {
+ FontDataReader data { { reinterpret_cast<u8 const*>(data_pointer), data_length } };
+ // The upper 16 bits of the index select a named instance, not a face.
+ if (auto location = find_table(data, hb_face_get_index(face) & 0xFFFF, tag); location.has_value()) {
+ static_cast<FontDataReader&>(*this) = FontDataReader { data.bytes().slice(location->offset, location->length) };
+ }
+ return;
+ }
+
+ // A face without data of its own, such as one that CoreText gives, has only its tables.
+ hb_blob_destroy(m_blob);
+ m_blob = hb_face_reference_table(face, tag.to_u32());
+ unsigned length = 0;
+ auto const* table_pointer = hb_blob_get_data(m_blob, &length);
+ if (table_pointer && length > 0) {
+ FontDataReader table { { reinterpret_cast<u8 const*>(table_pointer), length } };
+ static_cast<FontDataReader&>(*this) = table;
+ }
+}
+
+FontTable::~FontTable()
+{
+ hb_blob_destroy(m_blob);
+}
+
+}
diff --git a/Libraries/LibGfx/Font/FontTable.h b/Libraries/LibGfx/Font/FontTable.h
new file mode 100644
index 00000000000..cbc2e822caa
--- /dev/null
+++ b/Libraries/LibGfx/Font/FontTable.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Noncopyable.h>
+#include <AK/Optional.h>
+#include <AK/Span.h>
+#include <AK/String.h>
+#include <LibGfx/FourCC.h>
+
+struct hb_blob_t;
+struct hb_face_t;
+
+namespace Gfx {
+
+// Reads big-endian values, as font data stores them.
+class FontDataReader {
+public:
+ FontDataReader() = default;
+ explicit FontDataReader(ReadonlyBytes bytes)
+ : m_bytes(bytes)
+ {
+ }
+
+ ReadonlyBytes bytes() const { return m_bytes; }
+ bool is_empty() const { return m_bytes.is_empty(); }
+ bool contains(size_t offset, size_t length) const { return offset <= m_bytes.size() && length <= m_bytes.size() - offset; }
+
+ u8 u8_at(size_t offset) const;
+ u16 u16_at(size_t offset) const;
+ i16 i16_at(size_t offset) const { return static_cast<i16>(u16_at(offset)); }
+ u32 u32_at(size_t offset) const;
+ i32 i32_at(size_t offset) const { return static_cast<i32>(u32_at(offset)); }
+
+private:
+ ReadonlyBytes m_bytes;
+};
+
+// A name of a face from its name table, in US English, or else in the first language that the face has it in.
+Optional<String> face_name(hb_face_t*, u16 name_id);
+
+// One table of a face, kept while it is read. Like FreeType, it counts a table as missing if its length is 0 or if
+// it ends after the end of the font data, and it uses the first entry of the table directory with the tag.
+class FontTable : public FontDataReader {
+ AK_MAKE_NONCOPYABLE(FontTable);
+ AK_MAKE_NONMOVABLE(FontTable);
+
+public:
+ FontTable(hb_face_t*, FourCC tag);
+ ~FontTable();
+
+private:
+ hb_blob_t* m_blob { nullptr };
+};
+
+}
diff --git a/Libraries/LibGfx/Font/Typeface.cpp b/Libraries/LibGfx/Font/Typeface.cpp
index cf48a7290c5..4053b456040 100644
--- a/Libraries/LibGfx/Font/Typeface.cpp
+++ b/Libraries/LibGfx/Font/Typeface.cpp
@@ -9,6 +9,7 @@
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontDatabase.h>
+#include <LibGfx/Font/FontTable.h>
#include <LibGfx/Font/FontVariationSettings.h>
#include <LibGfx/Font/Typeface.h>
#include <LibGfx/Font/TypefaceSkia.h>
@@ -21,33 +22,10 @@ ErrorOr<Vector<String>> Typeface::local_font_names() const
{
// https://drafts.csswg.org/css-fonts-4/#local-font-fallback
// NB: local() identifies a face by its full name or PostScript name, never by its family.
- // Prefer US English names, or the first available localization if English is absent.
- auto* face = harfbuzz_typeface();
- unsigned entry_count = 0;
- auto const* entries = hb_ot_name_list_names(face, &entry_count);
Vector<String> names;
for (auto name_id : { HB_OT_NAME_ID_FULL_NAME, HB_OT_NAME_ID_POSTSCRIPT_NAME }) {
- hb_language_t language = HB_LANGUAGE_INVALID;
- for (unsigned index = 0; index < entry_count; ++index) {
- auto const& entry = entries[index];
- if (entry.name_id != name_id)
- continue;
- if (language == HB_LANGUAGE_INVALID)
- language = entry.language;
- if (entry.language == hb_language_from_string("en", -1) || entry.language == hb_language_from_string("en-us", -1)) {
- language = entry.language;
- break;
- }
- }
- if (language == HB_LANGUAGE_INVALID)
- continue;
- auto length = hb_ot_name_get_utf8(face, name_id, language, nullptr, nullptr);
- if (length == 0 || length == NumericLimits<unsigned>::max())
- continue;
- auto bytes = TRY(ByteBuffer::create_uninitialized(static_cast<size_t>(length) + 1));
- auto capacity = length + 1;
- hb_ot_name_get_utf8(face, name_id, language, &capacity, reinterpret_cast<char*>(bytes.data()));
- names.append(TRY(String::from_utf8({ reinterpret_cast<char const*>(bytes.data()), capacity })));
+ if (auto name = face_name(harfbuzz_typeface(), name_id); name.has_value())
+ TRY(names.try_append(name.release_value()));
}
return names;
}
@@ -123,6 +101,19 @@ hb_face_t* Typeface::harfbuzz_typeface() const
return m_harfbuzz_face;
}
+FaceDescription const& Typeface::description() const
+{
+ call_once(m_description_once, [&] {
+ m_description = FaceDescription::read(harfbuzz_typeface());
+ });
+ return *m_description;
+}
+
+FaceStyle Typeface::style_for_variations(ReadonlySpan<FontVariationAxis> variations) const
+{
+ return description().style_for_variations(variations);
+}
+
// Recording asks for this while the document thread may ask the same typeface for it, so the
// read of a half-written memo has to be impossible. The same `call_once` the HarfBuzz face uses
// above publishes it.
diff --git a/Libraries/LibGfx/Font/Typeface.h b/Libraries/LibGfx/Font/Typeface.h
index be86bbc8d97..5ba05d1ef31 100644
--- a/Libraries/LibGfx/Font/Typeface.h
+++ b/Libraries/LibGfx/Font/Typeface.h
@@ -17,6 +17,7 @@
#include <AK/Variant.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibCore/MappedFile.h>
+#include <LibGfx/Font/FaceDescription.h>
#include <LibGfx/Font/FontVariationSettings.h>
#include <LibGfx/Forward.h>
#include <LibGfx/ShapeFeature.h>
@@ -98,6 +99,10 @@ public:
void set_file_path(String file_path) { m_file_path = move(file_path); }
hb_face_t* harfbuzz_typeface() const;
+ FaceDescription const& description() const;
+
+ // The style of a font of this typeface with these variations.
+ virtual FaceStyle style_for_variations(ReadonlySpan<FontVariationAxis>) const;
ErrorOr<Vector<String>> local_font_names() const;
// Union of all glyph bounding boxes as recorded in the `head` table, in font units with y pointing up.
@@ -158,6 +163,8 @@ private:
mutable OnceFlag m_harfbuzz_face_once;
mutable hb_blob_t* m_harfbuzz_blob { nullptr };
mutable hb_face_t* m_harfbuzz_face { nullptr };
+ mutable OnceFlag m_description_once;
+ mutable Optional<FaceDescription> m_description;
mutable OnceFlag m_bounding_box_once;
mutable BoundingBoxInFontUnits m_bounding_box_in_font_units;
};
diff --git a/Libraries/LibGfx/Font/TypefaceSkia.cpp b/Libraries/LibGfx/Font/TypefaceSkia.cpp
index 4d5d76b19cb..c6042929c83 100644
--- a/Libraries/LibGfx/Font/TypefaceSkia.cpp
+++ b/Libraries/LibGfx/Font/TypefaceSkia.cpp
@@ -90,7 +90,6 @@ struct TypefaceSkia::Impl {
// Skia reads a CoreText UI font as upright and regular because its descriptor carries no numeric style traits,
// so a system UI typeface answers style queries from the style it was matched for instead.
Optional<SystemUIFontStyle> system_ui_font_style;
- Optional<u16> data_font_weight;
#ifdef AK_OS_MACOS
CGFontRef cg_font { nullptr };
#endif
@@ -196,21 +195,6 @@ ErrorOr<RefPtr<TypefaceSkia>> TypefaceSkia::typeface_from_skia_typeface(sk_sp<Sk
ttc_index });
}
-static u16 font_weight_from_data(ReadonlyBytes buffer, u32 ttc_index, Vector<FontVariationAxis> const& axes = {})
-{
- auto* blob = hb_blob_create(reinterpret_cast<char const*>(buffer.data()), buffer.size(), HB_MEMORY_MODE_READONLY, nullptr, nullptr);
- ScopeGuard destroy_blob = [&] { hb_blob_destroy(blob); };
- auto* face = hb_face_create(blob, ttc_index);
- ScopeGuard destroy_face = [&] { hb_face_destroy(face); };
- auto* font = hb_font_create(face);
- ScopeGuard destroy_font = [&] { hb_font_destroy(font); };
- Vector<hb_variation_t> variations;
- for (auto const& axis : axes)
- variations.append({ axis.tag.to_u32(), axis.value });
- hb_font_set_variations(font, variations.data(), variations.size());
- return round_to<u16>(clamp(hb_style_get_value(font, HB_STYLE_TAG_WEIGHT), 0.0f, 1000.0f));
-}
-
ErrorOr<NonnullRefPtr<TypefaceSkia>> TypefaceSkia::load_from_buffer(AK::ReadonlyBytes buffer, u32 ttc_index, NonnullRefPtr<FontDataBacking> backing)
{
// NB: Skia can retain the typeface in text blobs and glyph caches after our Typeface is destroyed.
@@ -220,7 +204,6 @@ ErrorOr<NonnullRefPtr<TypefaceSkia>> TypefaceSkia::load_from_buffer(AK::Readonly
sk_sp<SkData> data = SkData::MakeWithProc(buffer.data(), buffer.size(), [](void const*, void* context) { static_cast<FontDataBacking*>(context)->unref(); }, backing.ptr());
sk_sp<SkTypeface> skia_typeface;
- Optional<u16> data_font_weight;
#ifdef AK_OS_MACOS
// NB: Skia's CoreText stream loader only supports collection index zero. Ask CoreText for the collection's
// descriptors directly, then wrap the selected face in Skia, as we do for system UI fonts.
@@ -300,9 +283,6 @@ ErrorOr<NonnullRefPtr<TypefaceSkia>> TypefaceSkia::load_from_buffer(AK::Readonly
return Error::from_string_literal("Failed to create CoreText font");
ScopeGuard release_font = [&] { CFRelease(ct_font); };
skia_typeface = SkMakeTypefaceFromCTFont(ct_font);
- // NB: SkMakeTypefaceFromCTFont applies native system-font weight conversion even for data-created fonts.
- // Use the supplied face's weight, as we would when loading it through Skia's stream loader.
- data_font_weight = font_weight_from_data(buffer, ttc_index);
} else
#endif
{
@@ -333,7 +313,6 @@ ErrorOr<NonnullRefPtr<TypefaceSkia>> TypefaceSkia::load_from_buffer(AK::Readonly
}
auto typeface = adopt_ref(*new TypefaceSkia { make<TypefaceSkia::Impl>(skia_typeface), buffer, ttc_index });
- typeface->impl().data_font_weight = data_font_weight;
typeface->set_font_data(move(backing));
return typeface;
}
@@ -508,14 +487,12 @@ RefPtr<TypefaceSkia const> TypefaceSkia::clone_with_variations(Vector<FontVariat
if (!skia_typeface)
return {};
- if (has_font_data_backing() || impl().data_font_weight.has_value()) {
+ if (has_font_data_backing()) {
auto typeface = adopt_ref(*new TypefaceSkia {
make<TypefaceSkia::Impl>(skia_typeface, std::unique_ptr<SkStreamAsset> {}, impl().system_ui_font_style),
m_buffer,
m_ttc_index });
typeface->copy_font_data_from(*this);
- if (impl().data_font_weight.has_value())
- typeface->impl().data_font_weight = font_weight_from_data(m_buffer, m_ttc_index, axes);
return typeface;
}
@@ -664,46 +641,35 @@ void TypefaceSkia::populate_glyph_page(GlyphPage& glyph_page, size_t page_index)
FlyString const& TypefaceSkia::family() const
{
- call_once(m_family_once, [&] {
- SkString family_name;
- impl().skia_typeface->getFamilyName(&family_name);
- m_family = FlyString::from_utf8_without_validation(ReadonlyBytes { family_name.c_str(), family_name.size() });
- });
- return *m_family;
+ return description().family();
}
u16 TypefaceSkia::weight() const
{
if (auto const& style = impl().system_ui_font_style; style.has_value())
return style->weight;
- if (impl().data_font_weight.has_value())
- return impl().data_font_weight.value();
- return impl().skia_typeface->fontStyle().weight();
+ return description().style().weight;
}
u16 TypefaceSkia::width() const
{
if (auto const& style = impl().system_ui_font_style; style.has_value())
return style->width;
- return impl().skia_typeface->fontStyle().width();
+ return description().style().width;
}
u8 TypefaceSkia::slope() const
{
if (auto const& style = impl().system_ui_font_style; style.has_value())
return style->slope;
+ return description().style().slope;
+}
- auto slant = impl().skia_typeface->fontStyle().slant();
- switch (slant) {
- case SkFontStyle::kUpright_Slant:
- return 0;
- case SkFontStyle::kItalic_Slant:
- return 1;
- case SkFontStyle::kOblique_Slant:
- return 2;
- default:
- return 0;
- }
+FaceStyle TypefaceSkia::style_for_variations(ReadonlySpan<FontVariationAxis> variations) const
+{
+ if (auto const& style = impl().system_ui_font_style; style.has_value())
+ return { .weight = style->weight, .width = style->width, .slope = style->slope };
+ return Typeface::style_for_variations(variations);
}
}
diff --git a/Libraries/LibGfx/Font/TypefaceSkia.h b/Libraries/LibGfx/Font/TypefaceSkia.h
index 32abbdcd384..d2c518560dd 100644
--- a/Libraries/LibGfx/Font/TypefaceSkia.h
+++ b/Libraries/LibGfx/Font/TypefaceSkia.h
@@ -50,6 +50,7 @@ public:
virtual u16 weight() const override;
virtual u16 width() const override;
virtual u8 slope() const override;
+ virtual FaceStyle style_for_variations(ReadonlySpan<FontVariationAxis>) const override;
virtual ReadonlyBytes buffer() const LIFETIME_BOUND override { return m_buffer; }
virtual u32 ttc_index() const override { return m_ttc_index; }
@@ -81,9 +82,6 @@ private:
ReadonlyBytes m_buffer;
u32 m_ttc_index { 0 };
- mutable OnceFlag m_family_once;
- mutable Optional<FlyString> m_family;
-
// This cache stores information per code point.
// It's segmented into pages with data about 256 code points each.
struct GlyphPage {
diff --git a/Libraries/LibGfx/FontCascadeList.cpp b/Libraries/LibGfx/FontCascadeList.cpp
index 5223514cb88..f8a755b748c 100644
--- a/Libraries/LibGfx/FontCascadeList.cpp
+++ b/Libraries/LibGfx/FontCascadeList.cpp
@@ -545,7 +545,7 @@ extern "C" void const* ladybird_gfx_cascade_snapshot_begin(void const* list)
auto const& reference_font = cascade_list.first();
snapshot->system_fallback_point_size = reference_font.point_size();
snapshot->system_fallback_weight = static_cast<u16>(reference_font.weight());
- snapshot->system_fallback_width = reference_font.typeface().width();
+ snapshot->system_fallback_width = reference_font.width();
snapshot->system_fallback_slope = static_cast<u8>(reference_font.slope());
}
return snapshot;
diff --git a/Libraries/LibWeb/CSS/FontResolution.cpp b/Libraries/LibWeb/CSS/FontResolution.cpp
index ee46b3b3616..d42fe8cf746 100644
--- a/Libraries/LibWeb/CSS/FontResolution.cpp
+++ b/Libraries/LibWeb/CSS/FontResolution.cpp
@@ -394,7 +394,7 @@ NonnullRefPtr<Gfx::FontCascadeList const> resolve_font_cascade(FontFaceSnapshot
Gfx::SystemFallbackFontKey key {
.code_point = code_point,
.weight = static_cast<u16>(reference_font.weight()),
- .width = reference_font.typeface().width(),
+ .width = reference_font.width(),
.slope = static_cast<u8>(reference_font.slope()),
.prefer_color_emoji = presentation == Gfx::EmojiPresentation::Emoji,
};
diff --git a/Libraries/LibWebView/FontService.cpp b/Libraries/LibWebView/FontService.cpp
index 304a6c51d8f..faeb03ab656 100644
--- a/Libraries/LibWebView/FontService.cpp
+++ b/Libraries/LibWebView/FontService.cpp
@@ -87,6 +87,9 @@ ErrorOr<void> FontService::build_catalog()
auto collect_typeface = [&](String const& path, u32 ttc_index, Gfx::FontFileFormat format, NonnullRefPtr<Gfx::Typeface> typeface) {
if (callback_error.has_value())
return;
+ // A face without a family name cannot be matched.
+ if (typeface->family().is_empty())
+ return;
auto face_id = next_face_id++;
auto names = typeface->local_font_names();
if (names.is_error()) {