Truly independent web browser
LibGfx+LibWebView: Match system fonts with CoreText directly
Aliaksandr Kalenik2ee46ea547a3
diff --git a/Libraries/LibGfx/CMakeLists.txt b/Libraries/LibGfx/CMakeLists.txtindex 0c6395a4cc3..5badc18e763 100644--- a/Libraries/LibGfx/CMakeLists.txt+++ b/Libraries/LibGfx/CMakeLists.txt@@ -75,6 +75,8 @@ endif()if (HAS_FONTCONFIG)list(APPEND SOURCES Font/GlobalFontConfig.cpp Font/SystemFontMatcherFontconfig.cpp)+elseif (APPLE)+ list(APPEND SOURCES Font/SystemFontMatcherCoreText.cpp)else()list(APPEND SOURCES Font/SystemFontMatcherSkia.cpp)endif()diff --git a/Libraries/LibGfx/Font/SharedFontProvider.h b/Libraries/LibGfx/Font/SharedFontProvider.hindex a5f1192356f..322feaa6991 100644--- a/Libraries/LibGfx/Font/SharedFontProvider.h+++ b/Libraries/LibGfx/Font/SharedFontProvider.h@@ -16,6 +16,7 @@#include <LibGfx/Font/FontCatalog.h>#include <LibGfx/Font/FontDatabase.h>#include <LibGfx/Font/PathFontProvider.h>+#include <LibGfx/Font/SystemFontMatcher.h>#include <LibIPC/File.h>namespace Gfx {@@ -26,11 +27,6 @@ struct BrokeredFontFile {IPC::File file;};-// An installed font that the client opens by its PostScript name, for faces whose data the platform does not load back.-struct PlatformFontName {- String postscript_name;-};-struct BrokeredFont {u64 face_id { 0 };Variant<Empty, BrokeredFontFile, PlatformFontName> source;diff --git a/Libraries/LibGfx/Font/SystemFontMatcher.cpp b/Libraries/LibGfx/Font/SystemFontMatcher.cppindex f1326661f03..38310478c50 100644--- a/Libraries/LibGfx/Font/SystemFontMatcher.cpp+++ b/Libraries/LibGfx/Font/SystemFontMatcher.cpp@@ -13,6 +13,10 @@#include <LibGfx/Font/SystemFontMatcher.h>#include <LibGfx/Font/WOFF/Loader.h>+#ifdef AK_OS_MACOS+# include <LibGfx/Font/TypefaceCoreText.h>+#endif+namespace Gfx::SystemFontMatcher {namespace {@@ -38,6 +42,7 @@ struct MatchCaches {Mutex mutex;HashMap<FileFace, Optional<SystemFontFile>, FileFaceTraits> loadable_files;HashMap<SystemFontFile, NonnullRefPtr<Typeface>, SystemFontFileTraits> typefaces;+ HashMap<String, NonnullRefPtr<Typeface>> platform_typefaces;};MatchCaches& match_caches()@@ -111,6 +116,21 @@ ErrorOr<NonnullRefPtr<Typeface>> load(SystemFontMatch const& match)MutexLocker locker { caches.mutex };return caches.typefaces.ensure(file, [&] { return move(typeface); });},+ [&](PlatformFontName const& name) -> ErrorOr<NonnullRefPtr<Typeface>> {+#ifdef AK_OS_MACOS+ {+ MutexLocker locker { caches.mutex };+ if (auto it = caches.platform_typefaces.find(name.postscript_name); it != caches.platform_typefaces.end())+ return it->value;+ }+ NonnullRefPtr<Typeface> typeface = TRY(TypefaceCoreText::try_load_postscript_name(name.postscript_name));+ MutexLocker locker { caches.mutex };+ return caches.platform_typefaces.ensure(name.postscript_name, [&] { return move(typeface); });+#else+ (void)name;+ return Error::from_string_literal("Only CoreText opens fonts by name");+#endif+ },[](NonnullRefPtr<Typeface> const& typeface) -> ErrorOr<NonnullRefPtr<Typeface>> {return typeface;});diff --git a/Libraries/LibGfx/Font/SystemFontMatcher.h b/Libraries/LibGfx/Font/SystemFontMatcher.hindex 50f7a6d57eb..edb75593e4b 100644--- a/Libraries/LibGfx/Font/SystemFontMatcher.h+++ b/Libraries/LibGfx/Font/SystemFontMatcher.h@@ -25,8 +25,13 @@ struct SystemFontFile {bool operator==(SystemFontFile const&) const = default;};-// A platform whose matcher does not give a file gives the typeface itself.-using SystemFontMatch = Variant<SystemFontFile, NonnullRefPtr<Typeface>>;+// An installed font that the client opens by its PostScript name, for faces whose data the platform does not load back.+struct PlatformFontName {+ String postscript_name;+};++// A platform whose matcher does not give a file or a name gives the typeface itself.+using SystemFontMatch = Variant<SystemFontFile, PlatformFontName, NonnullRefPtr<Typeface>>;// Matches installed fonts by the rules of the platform. Each face that a match gives is one that Typeface loads.namespace SystemFontMatcher {diff --git a/Libraries/LibGfx/Font/SystemFontMatcherCoreText.cpp b/Libraries/LibGfx/Font/SystemFontMatcherCoreText.cppnew file mode 100644index 00000000000..36894c07c46--- /dev/null+++ b/Libraries/LibGfx/Font/SystemFontMatcherCoreText.cpp@@ -0,0 +1,343 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Array.h>+#include <AK/ByteString.h>+#include <AK/HashMap.h>+#include <AK/Mutex.h>+#include <AK/NeverDestroyed.h>+#include <AK/Noncopyable.h>+#include <AK/QuickSort.h>+#include <AK/StdLibExtras.h>+#include <AK/StringBuilder.h>+#include <LibCore/MappedFile.h>+#include <LibGfx/Font/Font.h>+#include <LibGfx/Font/FontTable.h>+#include <LibGfx/Font/SystemFontMatcher.h>+#include <LibGfx/Font/TypefaceCoreText.h>++#include <CoreText/CoreText.h>+#include <harfbuzz/hb-ot.h>+#include <harfbuzz/hb.h>+#include <sys/param.h>++namespace Gfx::SystemFontMatcher {++namespace {++// Releases a CoreFoundation object at the end of its scope.+template<typename T>+class CFOwned {+ AK_MAKE_NONCOPYABLE(CFOwned);++public:+ CFOwned() = default;++ explicit CFOwned(T object)+ : m_object(object)+ {+ }++ CFOwned(CFOwned&& other)+ : m_object(exchange(other.m_object, nullptr))+ {+ }++ CFOwned& operator=(CFOwned&& other)+ {+ if (this != &other) {+ release();+ m_object = exchange(other.m_object, nullptr);+ }+ return *this;+ }++ ~CFOwned() { release(); }++ T get() const { return m_object; }++private:+ void release()+ {+ if (m_object)+ CFRelease(m_object);+ m_object = nullptr;+ }++ T m_object { nullptr };+};++}++// https://developer.apple.com/documentation/appkit/nsfont/weight+// CoreText gives weights from -1 to 1. These are the weights of the AppKit constants from ultraLight to black, which+// stand for the CSS weights from 100 to 900.+static CGFloat core_text_weight(u16 css_weight)+{+ static constexpr Array<CGFloat, 9> weights { -0.8, -0.6, -0.4, 0, 0.23, 0.3, 0.4, 0.56, 0.62 };+ auto position = (clamp<CGFloat>(css_weight, 100, 900) - 100) / 100;+ auto index = min(static_cast<size_t>(position), weights.size() - 2);+ return weights[index] + (weights[index + 1] - weights[index]) * (position - index);+}++// https://learn.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass+// CoreText gives widths from -1 to 1, with 0 for the normal width. Use the change from the normal width, which the+// width classes give in percent.+static CGFloat core_text_width(u16 width_class)+{+ static constexpr Array<CGFloat, 9> percentages { 50, 62.5, 75, 87.5, 100, 112.5, 125, 150, 200 };+ return (percentages[clamp<u16>(width_class, 1, 9) - 1] - 100) / 100;+}++// https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle+// CoreText gives slants from -1 to 1, where 1 is 30 degrees. An italic or oblique style asks for the default angle of+// an oblique style, 14 degrees.+static constexpr CGFloat core_text_slant_of_slanted_styles = 14.0 / 30.0;++static CFOwned<CFStringRef> make_string(StringView string)+{+ return CFOwned<CFStringRef> { CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<UInt8 const*>(string.characters_without_null_termination()), static_cast<CFIndex>(string.length()), kCFStringEncodingUTF8, false) };+}++static Optional<String> string_from(CFStringRef string)+{+ if (!string)+ return {};+ auto capacity = CFStringGetMaximumSizeForEncoding(CFStringGetLength(string), kCFStringEncodingUTF8) + 1;+ Vector<char> buffer;+ buffer.resize(capacity);+ if (!CFStringGetCString(string, buffer.data(), capacity, kCFStringEncodingUTF8))+ return {};+ auto result = String::from_utf8(StringView { buffer.data(), strlen(buffer.data()) });+ if (result.is_error())+ return {};+ return result.release_value();+}++static void set_number(CFMutableDictionaryRef dictionary, CFStringRef key, CGFloat value)+{+ CFOwned<CFNumberRef> number { CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &value) };+ if (number.get())+ CFDictionarySetValue(dictionary, key, number.get());+}++static CFOwned<CTFontDescriptorRef> create_descriptor(CFStringRef family, u16 weight, u16 width, u8 slope)+{+ CFOwned<CFMutableDictionaryRef> traits { CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) };+ CFOwned<CFMutableDictionaryRef> attributes { CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) };+ if (!traits.get() || !attributes.get())+ return {};++ set_number(traits.get(), kCTFontWeightTrait, core_text_weight(weight));+ set_number(traits.get(), kCTFontWidthTrait, core_text_width(width));+ set_number(traits.get(), kCTFontSlantTrait, slope == 0 ? 0 : core_text_slant_of_slanted_styles);+ CFDictionarySetValue(attributes.get(), kCTFontTraitsAttribute, traits.get());+ CFDictionarySetValue(attributes.get(), kCTFontFamilyNameAttribute, family);+ return CFOwned<CTFontDescriptorRef> { CTFontDescriptorCreateWithAttributes(attributes.get()) };+}++// The face of a family that has the style closest to the requested one, if the family is installed.+static CFOwned<CTFontRef> match_font_for_family(CFStringRef family, u16 weight, u16 width, u8 slope)+{+ auto descriptor = create_descriptor(family, weight, width, slope);+ if (!descriptor.get())+ return {};+ CFTypeRef required_attribute_values[] = { kCTFontFamilyNameAttribute };+ CFOwned<CFSetRef> required_attributes { CFSetCreate(kCFAllocatorDefault, required_attribute_values, 1, &kCFTypeSetCallBacks) };+ if (!required_attributes.get())+ return {};+ CFOwned<CTFontDescriptorRef> matched_descriptor { CTFontDescriptorCreateMatchingFontDescriptor(descriptor.get(), required_attributes.get()) };+ if (!matched_descriptor.get())+ return {};+ return CFOwned<CTFontRef> { CTFontCreateWithFontDescriptor(matched_descriptor.get(), 0, nullptr) };+}++static bool has_code_point(CTFontRef font, u32 code_point)+{+ UniChar code_units[2] = {};+ CGGlyph glyphs[2] = {};+ CFIndex length = 1;+ if (code_point < 0x10000) {+ code_units[0] = static_cast<UniChar>(code_point);+ } else {+ code_units[0] = static_cast<UniChar>(0xD800 + ((code_point - 0x10000) >> 10));+ code_units[1] = static_cast<UniChar>(0xDC00 + ((code_point - 0x10000) & 0x3FF));+ length = 2;+ }+ return CTFontGetGlyphsForCharacters(font, code_units, glyphs, length);+}++// The face index in a font file for a font that CoreText gives. This is the face with the same PostScript name, or+// else a face of the same family with a named instance at the variation of the font, or that face by itself if no+// named instance is at the variation. The upper 16 bits of the index select the named instance.+static Optional<u32> face_index_of(ReadonlyBytes bytes, CTFontRef font, String const& postscript_name, CFDictionaryRef variation)+{+ CFOwned<CFStringRef> core_text_family { CTFontCopyFamilyName(font) };+ auto family = string_from(core_text_family.get());++ auto* blob = hb_blob_create(reinterpret_cast<char const*>(bytes.data()), bytes.size(), HB_MEMORY_MODE_READONLY, nullptr, nullptr);+ auto face_count = hb_face_count(blob);+ Optional<u32> match;+ Optional<u32> instance_match;+ Optional<u32> family_match;+ for (u32 index = 0; index < face_count && !match.has_value(); ++index) {+ auto* face = hb_face_create(blob, index);+ if (face_name(face, HB_OT_NAME_ID_POSTSCRIPT_NAME) == postscript_name) {+ match = index;+ } else if (variation && CFDictionaryGetCount(variation) > 0 && family.has_value() && !instance_match.has_value()) {+ auto face_family = face_name(face, HB_OT_NAME_ID_TYPOGRAPHIC_FAMILY);+ if (!face_family.has_value())+ face_family = face_name(face, HB_OT_NAME_ID_FONT_FAMILY);+ if (face_family == family) {+ if (!family_match.has_value())+ family_match = index;+ if (auto instance = named_instance_with_variation(face, variation); instance.has_value())+ instance_match = index | ((*instance + 1) << 16);+ }+ }+ hb_face_destroy(face);+ }+ hb_blob_destroy(blob);+ if (match.has_value())+ return match;+ if (instance_match.has_value())+ return instance_match;+ return family_match;+}++// The face index of a font depends on its file, its PostScript name and its variation.+static ByteString file_face_key(StringView path, String const& postscript_name, CFDictionaryRef variation)+{+ struct Coordinate {+ i64 tag { 0 };+ double value { 0 };+ };+ Vector<Coordinate> coordinates;+ if (variation) {+ CFDictionaryApplyFunction(+ variation, [](void const* key, void const* value, void* context) {+ Coordinate coordinate;+ CFNumberGetValue(static_cast<CFNumberRef>(key), kCFNumberSInt64Type, &coordinate.tag);+ CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberDoubleType, &coordinate.value);+ static_cast<Vector<Coordinate>*>(context)->append(coordinate);+ },+ &coordinates);+ quick_sort(coordinates, [](auto const& a, auto const& b) { return a.tag < b.tag; });+ }++ StringBuilder builder;+ builder.append(path);+ builder.append('\0');+ builder.append(postscript_name);+ for (auto const& coordinate : coordinates) {+ builder.append('\0');+ builder.appendff("{}={:x}", coordinate.tag, bit_cast<u64>(coordinate.value));+ }+ return builder.to_byte_string();+}++// The face of a font file that a CoreText font has, if Typeface loads it. A fallback font covers many code points, and+// each code point that a page asks for gives the same font again, so the answer is kept.+static Optional<SystemFontFile> file_face_of(CTFontRef font, StringView path, String const& postscript_name)+{+ static NeverDestroyed<Mutex> mutex;+ static NeverDestroyed<HashMap<ByteString, Optional<SystemFontFile>>> file_faces;++ CFOwned<CFDictionaryRef> variation { CTFontCopyVariation(font) };+ auto key = file_face_key(path, postscript_name, variation.get());+ {+ MutexLocker locker { *mutex };+ if (auto it = file_faces->find(key); it != file_faces->end())+ return it->value;+ }++ Optional<SystemFontFile> file;+ if (auto mapped_file = Core::MappedFile::map(path); !mapped_file.is_error()) {+ if (auto ttc_index = face_index_of(mapped_file.value()->bytes(), font, postscript_name, variation.get()); ttc_index.has_value())+ file = loadable_file(path, *ttc_index);+ }+ MutexLocker locker { *mutex };+ file_faces->set(move(key), file);+ return file;+}++// The file of a font that CoreText gives, if Typeface loads its face, or else the PostScript name to open it by.+static Optional<SystemFontMatch> match_of(CTFontRef font)+{+ CFOwned<CFStringRef> core_text_postscript_name { CTFontCopyPostScriptName(font) };+ auto postscript_name = string_from(core_text_postscript_name.get());+ if (!postscript_name.has_value())+ return {};++ CFOwned<CFURLRef> url { static_cast<CFURLRef>(CTFontCopyAttribute(font, kCTFontURLAttribute)) };+ char path[MAXPATHLEN];+ if (url.get() && CFURLGetFileSystemRepresentation(url.get(), true, reinterpret_cast<UInt8*>(path), sizeof(path))) {+ if (auto file = file_face_of(font, { path, strlen(path) }, *postscript_name); file.has_value())+ return SystemFontMatch { file.release_value() };+ }++ return SystemFontMatch { PlatformFontName { postscript_name.release_value() } };+}++Optional<SystemFontMatch> match_family_style(StringView family, u16 weight, u16 width, u8 slope)+{+ auto family_name = make_string(family);+ if (!family_name.get())+ return {};+ auto font = match_font_for_family(family_name.get(), weight, width, slope);+ if (!font.get())+ return {};+ return match_of(font.get());+}++Optional<SystemFontMatch> match_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji)+{+ // A code point that is a surrogate or that is past the last code point gives no string, and no font has it.+ CFOwned<CFStringRef> string { CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<UInt8 const*>(&code_point), sizeof(code_point), kCFStringEncodingUTF32LE, false) };+ if (!string.get())+ return {};++ // The cascade list of the font that the user reads documents in gives the font for the code point.+ CFOwned<CTFontRef> document_font { CTFontCreateUIFontForLanguage(kCTFontUIFontUser, 0, nullptr) };+ if (!document_font.get())+ return {};++ // https://www.unicode.org/reports/tr51/#Emoji_Script+ // The script subtag Zsye asks for emoji presentation, which CoreText gives with a color emoji font.+ CFOwned<CFStringRef> language;+ if (prefer_color_emoji)+ language = make_string("und-Zsye"sv);+ CFOwned<CTFontRef> fallback_font { CTFontCreateForStringWithLanguage(document_font.get(), string.get(), CFRangeMake(0, CFStringGetLength(string.get())), language.get()) };+ if (!fallback_font.get() || !has_code_point(fallback_font.get(), code_point))+ return {};++ // The fallback font has the style of the document font, so look for a face of its family with the requested style+ // that also has the code point. A family whose name starts with '.' is hidden, and no name matches it.+ CFOwned<CFStringRef> fallback_family { CTFontCopyFamilyName(fallback_font.get()) };+ if (fallback_family.get() && CFStringGetLength(fallback_family.get()) > 0 && CFStringGetCharacterAtIndex(fallback_family.get(), 0) != '.') {+ if (auto styled_font = match_font_for_family(fallback_family.get(), weight, width, slope); styled_font.get() && has_code_point(styled_font.get(), code_point))+ fallback_font = move(styled_font);+ }++ return match_of(fallback_font.get());+}++Optional<FlyString> resolve_generic_family(StringView family, u16 weight, u8 slope)+{+ auto family_name = make_string(family);+ if (!family_name.get())+ return {};+ auto font = match_font_for_family(family_name.get(), weight, FontWidth::Normal, slope);+ if (!font.get())+ return {};+ CFOwned<CFStringRef> resolved_family { CTFontCopyFamilyName(font.get()) };+ auto name = string_from(resolved_family.get());+ if (!name.has_value())+ return {};+ return FlyString { name.release_value() };+}++}diff --git a/Libraries/LibGfx/Font/TypefaceCoreText.cpp b/Libraries/LibGfx/Font/TypefaceCoreText.cppindex 3e374e9f31e..29e54af94b9 100644--- a/Libraries/LibGfx/Font/TypefaceCoreText.cpp+++ b/Libraries/LibGfx/Font/TypefaceCoreText.cpp@@ -10,11 +10,14 @@#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>#include <AK/ScopeGuard.h>+#include <AK/Vector.h>#include <LibGfx/Font/FontTable.h>#include <LibGfx/Font/TypefaceCoreText.h>#include <LibIPC/Encoder.h>#include <harfbuzz/hb-coretext.h>+#include <harfbuzz/hb-ot.h>+#include <math.h>namespace Gfx {@@ -180,6 +183,45 @@ CTFontRef create_core_text_font_with_variations(CTFontRef font, CGFloat size, Rereturn CTFontCreateCopyWithAttributes(font, size, nullptr, descriptor);}+Optional<unsigned> named_instance_with_variation(hb_face_t* face, CFDictionaryRef variation)+{+ auto axis_count = hb_ot_var_get_axis_count(face);+ auto instance_count = hb_ot_var_get_named_instance_count(face);+ if (axis_count == 0 || instance_count == 0)+ return {};+ Vector<hb_ot_var_axis_info_t> axes;+ axes.resize(axis_count);+ hb_ot_var_get_axis_infos(face, 0, &axis_count, axes.data());++ Vector<double> values;+ values.ensure_capacity(axis_count);+ for (auto const& axis : axes) {+ double value = axis.default_value;+ i64 tag = axis.tag;+ if (auto tag_number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &tag)) {+ if (auto number = static_cast<CFNumberRef>(CFDictionaryGetValue(variation, tag_number)))+ CFNumberGetValue(number, kCFNumberDoubleType, &value);+ CFRelease(tag_number);+ }+ values.unchecked_append(value);+ }++ Vector<float> coordinates;+ coordinates.resize(axis_count);+ for (unsigned instance = 0; instance < instance_count; ++instance) {+ unsigned coordinate_count = axis_count;+ if (hb_ot_var_named_instance_get_design_coords(face, instance, &coordinate_count, coordinates.data()) != axis_count)+ continue;+ // CoreText rounds some coordinates that the font gives in 16.16 fixed point.+ bool matches = true;+ for (unsigned index = 0; matches && index < axis_count; ++index)+ matches = fabs(coordinates[index] - values[index]) <= 0.001;+ if (matches)+ return instance;+ }+ return {};+}+TypefaceCoreText::TypefaceCoreText(CTFontRef core_text_font, CGFontRef graphics_font, Identity identity): m_core_text_font(core_text_font), m_graphics_font(graphics_font)@@ -205,7 +247,18 @@ bool TypefaceCoreText::has_outlines_that_only_core_text_draws() consthb_face_t* TypefaceCoreText::create_harfbuzz_face() const{- return hb_coretext_face_create(m_graphics_font);+ auto* face = hb_coretext_face_create(m_graphics_font);+ // A font that CoreText opens by the PostScript name of a named instance has the coordinates of that instance. The+ // upper 16 bits of the face index select the instance, so the fonts and the description of the face start from+ // the same coordinates as CoreText.+ if (m_identity.has<String>()) {+ if (auto variation = CTFontCopyVariation(m_core_text_font)) {+ if (auto instance = named_instance_with_variation(face, variation); instance.has_value())+ hb_face_set_index(face, (*instance + 1) << 16);+ CFRelease(variation);+ }+ }+ return face;}void TypefaceCoreText::encode_font_data_for_ipc(IPC::Encoder& encoder) constdiff --git a/Libraries/LibGfx/Font/TypefaceCoreText.h b/Libraries/LibGfx/Font/TypefaceCoreText.hindex 7b307492561..23b8e875c37 100644--- a/Libraries/LibGfx/Font/TypefaceCoreText.h+++ b/Libraries/LibGfx/Font/TypefaceCoreText.h@@ -61,4 +61,8 @@ inline bool Typeface::fast_is<TypefaceCoreText>() const { return is_core_text();// coordinates, the copy keeps the variation of the font. Null if CoreText does not make the copy.CTFontRef create_core_text_font_with_variations(CTFontRef, CGFloat size, ReadonlySpan<FontVariationAxis>);+// The first named instance of a face, counted from 0, whose coordinates are the variation of a CoreText font.+// CoreText leaves the axes at their default values out of the variation.+Optional<unsigned> named_instance_with_variation(hb_face_t*, CFDictionaryRef variation);+}diff --git a/Libraries/LibGfx/Font/TypefaceSkia.cpp b/Libraries/LibGfx/Font/TypefaceSkia.cppindex c475fb8ed52..9441d71a252 100644--- a/Libraries/LibGfx/Font/TypefaceSkia.cpp+++ b/Libraries/LibGfx/Font/TypefaceSkia.cpp@@ -13,6 +13,7 @@#include <AK/NeverDestroyed.h>#include <AK/NumericLimits.h>#include <AK/ScopeGuard.h>+#include <AK/Vector.h>#include <LibGfx/Font/FontDatabase.h>#include <LibGfx/Font/TypefaceSkia.h>#include <LibIPC/Decoder.h>@@ -156,6 +157,52 @@ static bool harfbuzz_can_read_face(ReadonlyBytes buffer, u32 ttc_index)return (ttc_index & 0xFFFF) < hb_face_count(blob);}+#ifdef AK_OS_MACOS+// A copy of a CoreText font of a face at the coordinates of a named instance of the face. A face does not have to list+// its default instance, and then the index after the last instance selects it, which needs no copy.+static CTFontRef create_core_text_named_instance(CTFontRef font, hb_face_t* face, unsigned instance_index)+{+ unsigned axis_count = hb_ot_var_get_axis_count(face);+ Vector<hb_ot_var_axis_info_t> axes;+ axes.resize(axis_count);+ hb_ot_var_get_axis_infos(face, 0, &axis_count, axes.data());+ Vector<float> coordinates;+ coordinates.resize(axis_count);+ unsigned coordinate_count = axis_count;+ if (axis_count == 0 || hb_ot_var_named_instance_get_design_coords(face, instance_index, &coordinate_count, coordinates.data()) != axis_count)+ return nullptr;++ auto variation = CFDictionaryCreateMutable(kCFAllocatorDefault, axis_count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ if (!variation)+ return nullptr;+ ScopeGuard release_variation = [&] { CFRelease(variation); };+ for (unsigned index = 0; index < axis_count; ++index) {+ i64 tag = axes[index].tag;+ double value = coordinates[index];+ auto tag_number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &tag);+ auto value_number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value);+ if (tag_number && value_number)+ CFDictionarySetValue(variation, tag_number, value_number);+ if (tag_number)+ CFRelease(tag_number);+ if (value_number)+ CFRelease(value_number);+ }++ CFTypeRef attribute_keys[] = { kCTFontVariationAttribute };+ CFTypeRef attribute_values[] = { variation };+ auto attributes = CFDictionaryCreate(kCFAllocatorDefault, attribute_keys, attribute_values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ if (!attributes)+ return nullptr;+ ScopeGuard release_attributes = [&] { CFRelease(attributes); };+ auto descriptor = CTFontDescriptorCreateWithAttributes(attributes);+ if (!descriptor)+ return nullptr;+ ScopeGuard release_descriptor = [&] { CFRelease(descriptor); };+ return CTFontCreateCopyWithAttributes(font, 0, nullptr, descriptor);+}+#endif+ErrorOr<NonnullRefPtr<TypefaceSkia>> TypefaceSkia::load_from_buffer(AK::ReadonlyBytes buffer, u32 ttc_index, NonnullRefPtr<FontDataBacking> backing){if (!harfbuzz_can_read_face(buffer, ttc_index))@@ -241,6 +288,13 @@ ErrorOr<NonnullRefPtr<TypefaceSkia>> TypefaceSkia::load_from_buffer(AK::Readonlyauto ct_font = CTFontCreateWithFontDescriptor(descriptor, 0, nullptr);if (!ct_font)return Error::from_string_literal("Failed to create CoreText font");+ // The upper 16 bits of the index select a named instance, from 1. CoreText gets its coordinates as a variation.+ if (auto instance_index = ttc_index >> 16; instance_index > 0) {+ if (auto instance_font = create_core_text_named_instance(ct_font, face, instance_index - 1)) {+ CFRelease(ct_font);+ ct_font = instance_font;+ }+ }ScopeGuard release_font = [&] { CFRelease(ct_font); };skia_typeface = SkMakeTypefaceFromCTFont(ct_font);} elsediff --git a/Libraries/LibWebView/FontService.cpp b/Libraries/LibWebView/FontService.cppindex 0fb5ebf32e7..815fa9dee9e 100644--- a/Libraries/LibWebView/FontService.cpp+++ b/Libraries/LibWebView/FontService.cpp@@ -242,6 +242,7 @@ Gfx::BrokeredFont FontService::materialize(Gfx::SystemFontMatch match, String ca{return match.visit([&](Gfx::SystemFontFile& file) { return materialize_file(move(file), move(cache_key)); },+ [&](Gfx::PlatformFontName& name) { return materialize_platform_font(move(name), move(cache_key)); },[&](NonnullRefPtr<Gfx::Typeface>& typeface) { return materialize_typeface(move(typeface), move(cache_key)); });}@@ -259,6 +260,17 @@ Gfx::BrokeredFont FontService::materialize_file(Gfx::SystemFontFile file, Stringreturn open_font_without_lock(m_generation, face_id);}+Gfx::BrokeredFont FontService::materialize_platform_font(Gfx::PlatformFontName name, String cache_key)+{+ auto face_id = m_face_id_by_platform_font_name.ensure(name.postscript_name, [&] {+ auto new_face_id = m_next_dynamic_face_id++;+ m_memory_font_sources.set(new_face_id, name);+ return new_face_id;+ });+ m_dynamic_match_cache.set(move(cache_key), face_id);+ return open_font_without_lock(m_generation, face_id);+}+Gfx::BrokeredFont FontService::materialize_typeface(NonnullRefPtr<Gfx::Typeface> generic_typeface, String cache_key){auto& typeface = as<Gfx::TypefaceSkia>(*generic_typeface);diff --git a/Libraries/LibWebView/FontService.h b/Libraries/LibWebView/FontService.hindex 590576e0264..3f68ced2bee 100644--- a/Libraries/LibWebView/FontService.h+++ b/Libraries/LibWebView/FontService.h@@ -72,6 +72,7 @@ private:ErrorOr<IPC::File> create_immutable_font_data(ReadonlyBytes);Gfx::BrokeredFont materialize(Gfx::SystemFontMatch, String cache_key);Gfx::BrokeredFont materialize_file(Gfx::SystemFontFile, String cache_key);+ Gfx::BrokeredFont materialize_platform_font(Gfx::PlatformFontName, String cache_key);Gfx::BrokeredFont materialize_typeface(NonnullRefPtr<Gfx::Typeface>, String cache_key);Gfx::BrokeredFont open_font_without_lock(u64 generation, u64 face_id);@@ -85,6 +86,7 @@ private:u64 m_next_dynamic_face_id { 1ull << 63 };HashMap<u64, FontSource> m_font_sources;HashMap<FontSource, u64, FontSourceTraits> m_face_id_by_source;+ HashMap<String, u64> m_face_id_by_platform_font_name;HashMap<u64, MemoryFontSource> m_memory_font_sources;HashMap<String, u64> m_dynamic_match_cache;diff --git a/Tests/LibWebView/TestFontService.cpp b/Tests/LibWebView/TestFontService.cppindex 20c4053c426..9175d9971c8 100644--- a/Tests/LibWebView/TestFontService.cpp+++ b/Tests/LibWebView/TestFontService.cpp@@ -59,6 +59,14 @@ TEST_CASE(dynamic_matches_of_one_face_share_its_id)EXPECT_NE(first.face_id, other_file.face_id);EXPECT_NE(other_face.face_id, first_face.face_id);+ // A platform font is one face by its PostScript name.+ auto platform_font = WebView::FontServiceTestAccess::materialize(*service, Gfx::PlatformFontName { "Ladybird-Test"_string }, "platform-font"_string);+ auto repeated_platform_font = WebView::FontServiceTestAccess::materialize(*service, Gfx::PlatformFontName { "Ladybird-Test"_string }, "repeated-platform-font"_string);+ EXPECT_NE(platform_font.face_id, 0u);+ EXPECT_EQ(platform_font.face_id, repeated_platform_font.face_id);+ EXPECT_NE(platform_font.face_id, first.face_id);+ EXPECT(platform_font.source.has<Gfx::PlatformFontName>());+// The renderer gets the file itself, not a copy of its data.auto* font_file = first.source.get_pointer<Gfx::BrokeredFontFile>();EXPECT(font_file);