Truly independent web browser
LibGfx+LibWebView: Open platform fonts by their PostScript names
Aliaksandr Kalenik59f7cc8bce8c
diff --git a/Libraries/LibGfx/Font/Font.cpp b/Libraries/LibGfx/Font/Font.cppindex 9e9cc3954f1..72a48984d3c 100644--- a/Libraries/LibGfx/Font/Font.cpp+++ b/Libraries/LibGfx/Font/Font.cpp@@ -11,6 +11,7 @@#include <AK/TypeCasts.h>#include <AK/Utf16String.h>#include <LibGfx/Font/Font.h>+#include <LibGfx/Font/FontTable.h>#include <LibGfx/TextLayout.h>#include <RustFFI.h>@@ -144,14 +145,6 @@ hb_font_t* Font::create_harfbuzz_font() constreturn font;}-static bool hb_face_has_table(hb_face_t* face, hb_tag_t tag)-{- hb_blob_t* blob = hb_face_reference_table(face, tag);- unsigned len = hb_blob_get_length(blob);- hb_blob_destroy(blob);- return len > 0;-}-bool Font::is_emoji_font() const{if (m_is_emoji_font.load(AK::MemoryOrder::memory_order_relaxed) == TriState::Unknown) {@@ -170,9 +163,9 @@ bool Font::is_emoji_font() constbool has_colr = hb_ot_color_has_layers(face) || hb_ot_color_has_paint(face);bool has_svg = hb_ot_color_has_svg(face);- bool has_sbix = hb_face_has_table(face, HB_TAG('s', 'b', 'i', 'x'));- bool has_cbdt = hb_face_has_table(face, HB_TAG('C', 'B', 'D', 'T'));- bool has_cblc = hb_face_has_table(face, HB_TAG('C', 'B', 'L', 'C'));+ bool has_sbix = face_has_table(face, FourCC { "sbix" });+ bool has_cbdt = face_has_table(face, FourCC { "CBDT" });+ bool has_cblc = face_has_table(face, FourCC { "CBLC" });bool has_any_color = has_colr || has_svg || has_sbix || (has_cbdt && has_cblc);auto looks_like_text = [&]() {diff --git a/Libraries/LibGfx/Font/FontTable.cpp b/Libraries/LibGfx/Font/FontTable.cppindex 39dcaf8c57c..c117c7be876 100644--- a/Libraries/LibGfx/Font/FontTable.cpp+++ b/Libraries/LibGfx/Font/FontTable.cpp@@ -78,6 +78,34 @@ static Optional<TableLocation> find_table(FontDataReader const& data, unsigned freturn {};}+static FontDataReader face_data(hb_blob_t* blob)+{+ unsigned length = 0;+ auto const* data = hb_blob_get_data(blob, &length);+ if (!data || length == 0)+ return {};+ return FontDataReader { { reinterpret_cast<u8 const*>(data), length } };+}++bool face_has_table(hb_face_t* face, FourCC tag)+{+ auto* blob = hb_face_reference_blob(face);+ auto data = face_data(blob);+ bool has_table = false;+ if (!data.is_empty()) {+ has_table = find_table(data, hb_face_get_index(face) & 0xFFFF, tag).has_value();+ } else {+ // A face without data of its own lists its tables without copying them.+ unsigned tag_count = hb_face_get_table_tags(face, 0, nullptr, nullptr);+ Vector<hb_tag_t> tags;+ tags.resize(tag_count);+ hb_face_get_table_tags(face, 0, &tag_count, tags.data());+ has_table = tags.contains_slow(tag.to_u32());+ }+ hb_blob_destroy(blob);+ return has_table;+}+Optional<String> face_name(hb_face_t* face, u16 name_id){unsigned entry_count = 0;@@ -113,10 +141,7 @@ Optional<String> face_name(hb_face_t* face, u16 name_id)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 } };+ if (auto data = face_data(m_blob); !data.is_empty()) {// 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) };diff --git a/Libraries/LibGfx/Font/FontTable.h b/Libraries/LibGfx/Font/FontTable.hindex cbc2e822caa..70ee0e24ddb 100644--- a/Libraries/LibGfx/Font/FontTable.h+++ b/Libraries/LibGfx/Font/FontTable.h@@ -40,6 +40,9 @@ private:ReadonlyBytes m_bytes;};+// Whether a face has a table, by the same rules as FontTable, without reading the table.+bool face_has_table(hb_face_t*, FourCC tag);+// 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);diff --git a/Libraries/LibGfx/Font/SharedFontProvider.cpp b/Libraries/LibGfx/Font/SharedFontProvider.cppindex c45fdfe742a..1894c2ed56f 100644--- a/Libraries/LibGfx/Font/SharedFontProvider.cpp+++ b/Libraries/LibGfx/Font/SharedFontProvider.cpp@@ -8,7 +8,9 @@#include <LibCore/AnonymousBuffer.h>#include <LibGfx/Font/Font.h>#include <LibGfx/Font/SharedFontProvider.h>-#include <LibGfx/Font/TypefaceSkia.h>+#ifdef AK_OS_MACOS+# include <LibGfx/Font/TypefaceCoreText.h>+#endif#include <LibGfx/Font/WOFF/Loader.h>#include <LibIPC/Decoder.h>#include <LibIPC/Encoder.h>@@ -228,24 +230,27 @@ RefPtr<Typeface> SharedFontProvider::load_brokered_font(BrokeredFont brokered_foreturn brokered_font.source.visit([](Empty) -> RefPtr<Typeface> { return nullptr; },[&](BrokeredFontFile& font_file) { return load_font_file(brokered_font.face_id, font_file.ttc_index, font_file.format, move(font_file.file)); },- [&](SystemFontReference const& reference) { return load_font_reference(brokered_font.face_id, reference); });+ [&](PlatformFontName const& name) { return load_platform_font(brokered_font.face_id, name); });}-RefPtr<Typeface> SharedFontProvider::load_font_reference(u64 face_id, SystemFontReference const& reference)+RefPtr<Typeface> SharedFontProvider::load_platform_font(u64 face_id, [[maybe_unused]] PlatformFontName const& name){if (m_failed_face_ids.contains(face_id))return nullptr;- auto typeface_or_error = TypefaceSkia::match_family_style(reference.family, reference.weight, reference.width, reference.slope);- if (typeface_or_error.is_error() || !typeface_or_error.value()) {- m_failed_face_ids.set(face_id);- return nullptr;+#ifdef AK_OS_MACOS+ auto typeface_or_error = TypefaceCoreText::try_load_postscript_name(name.postscript_name);+ if (!typeface_or_error.is_error()) {+ auto typeface = typeface_or_error.release_value();+ typeface->set_system_font_identifier({ m_catalog->generation(), face_id });+ m_typeface_cache.set(face_id, typeface);+ return typeface;}+#endif- auto typeface = typeface_or_error.release_value().release_nonnull();- typeface->set_system_font_identifier({ m_catalog->generation(), face_id });- m_typeface_cache.set(face_id, typeface);- return typeface;+ // Only CoreText gives fonts by name.+ m_failed_face_ids.set(face_id);+ return nullptr;}RefPtr<Typeface> SharedFontProvider::load_font_file(u64 face_id, u32 ttc_index, FontFileFormat format, IPC::File file)@@ -301,23 +306,17 @@ ErrorOr<Gfx::BrokeredFontFile> decode(Decoder& decoder)}template<>-ErrorOr<void> encode(Encoder& encoder, Gfx::SystemFontReference const& reference)+ErrorOr<void> encode(Encoder& encoder, Gfx::PlatformFontName const& name){- TRY(encoder.encode(reference.family));- TRY(encoder.encode(reference.weight));- TRY(encoder.encode(reference.width));- TRY(encoder.encode(reference.slope));+ TRY(encoder.encode(name.postscript_name));return {};}template<>-ErrorOr<Gfx::SystemFontReference> decode(Decoder& decoder)+ErrorOr<Gfx::PlatformFontName> decode(Decoder& decoder){- auto family = TRY(decoder.decode<String>());- auto weight = TRY(decoder.decode<u16>());- auto width = TRY(decoder.decode<u16>());- auto slope = TRY(decoder.decode<u8>());- return Gfx::SystemFontReference { move(family), weight, width, slope };+ auto postscript_name = TRY(decoder.decode<String>());+ return Gfx::PlatformFontName { move(postscript_name) };}template<>@@ -332,7 +331,7 @@ template<>ErrorOr<Gfx::BrokeredFont> decode(Decoder& decoder){auto face_id = TRY(decoder.decode<u64>());- auto source = TRY((decoder.decode<Variant<Empty, Gfx::BrokeredFontFile, Gfx::SystemFontReference>>()));+ auto source = TRY((decoder.decode<Variant<Empty, Gfx::BrokeredFontFile, Gfx::PlatformFontName>>()));return Gfx::BrokeredFont { face_id, move(source) };}diff --git a/Libraries/LibGfx/Font/SharedFontProvider.h b/Libraries/LibGfx/Font/SharedFontProvider.hindex 1adde762626..a5f1192356f 100644--- a/Libraries/LibGfx/Font/SharedFontProvider.h+++ b/Libraries/LibGfx/Font/SharedFontProvider.h@@ -26,17 +26,14 @@ struct BrokeredFontFile {IPC::File file;};-// A system font the client re-matches in its own process, for typefaces whose data does not survive a round trip.-struct SystemFontReference {- String family;- u16 weight { 0 };- u16 width { 0 };- u8 slope { 0 };+// 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, SystemFontReference> source;+ Variant<Empty, BrokeredFontFile, PlatformFontName> source;};// Any thread may ask these. The provider asks one question at a time.@@ -92,7 +89,7 @@ private:RefPtr<Typeface> load_catalog_face(FontCatalogFace const&);RefPtr<Typeface> load_brokered_font(BrokeredFont);RefPtr<Typeface> load_font_file(u64 face_id, u32 ttc_index, FontFileFormat, IPC::File);- RefPtr<Typeface> load_font_reference(u64 face_id, SystemFontReference const&);+ RefPtr<Typeface> load_platform_font(u64 face_id, PlatformFontName const&);NonnullOwnPtr<Core::MappedFile> const m_catalog_mapping;NonnullOwnPtr<FontCatalog> const m_catalog;@@ -119,10 +116,10 @@ template<>ErrorOr<Gfx::BrokeredFontFile> decode(Decoder&);template<>-ErrorOr<void> encode(Encoder&, Gfx::SystemFontReference const&);+ErrorOr<void> encode(Encoder&, Gfx::PlatformFontName const&);template<>-ErrorOr<Gfx::SystemFontReference> decode(Decoder&);+ErrorOr<Gfx::PlatformFontName> decode(Decoder&);template<>ErrorOr<void> encode(Encoder&, Gfx::BrokeredFont const&);diff --git a/Libraries/LibGfx/Font/Typeface.cpp b/Libraries/LibGfx/Font/Typeface.cppindex 967eebcf8d6..9d5eb4f8e1a 100644--- a/Libraries/LibGfx/Font/Typeface.cpp+++ b/Libraries/LibGfx/Font/Typeface.cpp@@ -37,6 +37,11 @@ ErrorOr<Vector<String>> Typeface::local_font_names() constreturn names;}+Optional<String> Typeface::postscript_name() const+{+ return face_name(harfbuzz_typeface(), HB_OT_NAME_ID_POSTSCRIPT_NAME);+}+FlyString const& Typeface::family() const{return description().family();@@ -417,6 +422,15 @@ ErrorOr<NonnullRefPtr<Gfx::Typeface const>> decode(Decoder& decoder)#endifreturn Error::from_string_literal("Typeface IPC data referred to an unavailable system UI font");}+ case Gfx::Typeface::FontDataFormat::PlatformFontName: {+ auto postscript_name = TRY(decoder.decode<String>());+#ifdef AK_OS_MACOS+ return TRY(Gfx::TypefaceCoreText::try_load_postscript_name(postscript_name));+#else+ (void)postscript_name;+ return Error::from_string_literal("Typeface IPC data referred to a platform font, which this platform does not have");+#endif+ }case Gfx::Typeface::FontDataFormat::SystemFontId: {auto generation = TRY(decoder.decode<u64>());auto face_id = TRY(decoder.decode<u64>());diff --git a/Libraries/LibGfx/Font/Typeface.h b/Libraries/LibGfx/Font/Typeface.hindex 487736e1681..9ac2219c381 100644--- a/Libraries/LibGfx/Font/Typeface.h+++ b/Libraries/LibGfx/Font/Typeface.h@@ -130,6 +130,7 @@ public:// The style of a font of this typeface with these variations.FaceStyle style_for_variations(ReadonlySpan<FontVariationAxis>) const;ErrorOr<Vector<String>> local_font_names() const;+ Optional<String> postscript_name() const;// What a rasterizer keeps with this typeface. The first call makes it.template<typename T, typename Callback>@@ -164,6 +165,7 @@ protected:SystemFont,SystemUIFont,SystemFontId,+ PlatformFontName,};Typeface();diff --git a/Libraries/LibGfx/Font/TypefaceCoreText.cpp b/Libraries/LibGfx/Font/TypefaceCoreText.cppindex 7c2aa29493d..3e374e9f31e 100644--- a/Libraries/LibGfx/Font/TypefaceCoreText.cpp+++ b/Libraries/LibGfx/Font/TypefaceCoreText.cpp@@ -10,6 +10,7 @@#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>#include <AK/ScopeGuard.h>+#include <LibGfx/Font/FontTable.h>#include <LibGfx/Font/TypefaceCoreText.h>#include <LibIPC/Encoder.h>@@ -106,10 +107,83 @@ RefPtr<TypefaceCoreText> TypefaceCoreText::system_ui(SystemUIFontStyle style)return typeface;}-TypefaceCoreText::TypefaceCoreText(CTFontRef core_text_font, CGFontRef graphics_font, SystemUIFontStyle style)+ErrorOr<NonnullRefPtr<TypefaceCoreText>> TypefaceCoreText::try_load_postscript_name(String const& postscript_name)+{+ auto name_bytes = postscript_name.bytes();+ auto name = CFStringCreateWithBytes(kCFAllocatorDefault, name_bytes.data(), static_cast<CFIndex>(name_bytes.size()), kCFStringEncodingUTF8, false);+ if (!name)+ return Error::from_string_literal("Invalid PostScript name");+ ScopeGuard release_name = [&] { CFRelease(name); };++ auto core_text_font = CTFontCreateWithName(name, 0, nullptr);+ if (!core_text_font)+ return Error::from_string_literal("CoreText has no font with this PostScript name");+ ScopeGuard release_core_text_font = [&] { CFRelease(core_text_font); };++ // CoreText gives another font for a name that it does not know.+ auto found_name = CTFontCopyPostScriptName(core_text_font);+ ScopeGuard release_found_name = [&] {+ if (found_name)+ CFRelease(found_name);+ };+ if (!found_name || !CFEqual(found_name, name))+ return Error::from_string_literal("CoreText has no font with this PostScript name");++ auto graphics_font = CTFontCopyGraphicsFont(core_text_font, nullptr);+ if (!graphics_font)+ return Error::from_string_literal("Failed to get graphics font from CoreText font");+ ScopeGuard release_graphics_font = [&] { CFRelease(graphics_font); };++ return adopt_ref(*new TypefaceCoreText(core_text_font, graphics_font, postscript_name));+}++CTFontRef create_core_text_font_with_variations(CTFontRef font, CGFloat size, ReadonlySpan<FontVariationAxis> coordinates)+{+ // A variation attribute can reset the axes that it leaves out. So the copy starts from the variation of the font,+ // and a copy without coordinates gets no variation attribute.+ if (coordinates.is_empty())+ return CTFontCreateCopyWithAttributes(font, size, nullptr, nullptr);++ CFMutableDictionaryRef variation = nullptr;+ if (auto font_variation = CTFontCopyVariation(font)) {+ variation = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, font_variation);+ CFRelease(font_variation);+ } else {+ variation = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ }+ if (!variation)+ return nullptr;+ ScopeGuard release_variation = [&] { CFRelease(variation); };+ for (auto const& coordinate : coordinates) {+ i64 tag = coordinate.tag.to_u32();+ double value = coordinate.value;+ 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, size, nullptr, descriptor);+}++TypefaceCoreText::TypefaceCoreText(CTFontRef core_text_font, CGFontRef graphics_font, Identity identity): m_core_text_font(core_text_font), m_graphics_font(graphics_font)- , m_style(style)+ , m_identity(move(identity)){CFRetain(m_core_text_font);CFRetain(m_graphics_font);@@ -121,6 +195,14 @@ TypefaceCoreText::~TypefaceCoreText()CFRelease(m_core_text_font);}+bool TypefaceCoreText::has_outlines_that_only_core_text_draws() const+{+ call_once(m_outline_format_once, [&] {+ m_has_outlines_that_only_core_text_draws = face_has_table(harfbuzz_typeface(), FourCC { "hvgl" });+ });+ return m_has_outlines_that_only_core_text_draws;+}+hb_face_t* TypefaceCoreText::create_harfbuzz_face() const{return hb_coretext_face_create(m_graphics_font);@@ -133,15 +215,24 @@ void TypefaceCoreText::encode_font_data_for_ipc(IPC::Encoder& encoder) constreturn;}- MUST(encoder.encode(FontDataFormat::SystemUIFont));- MUST(encoder.encode(m_style));+ m_identity.visit(+ [&](SystemUIFontStyle const& style) {+ MUST(encoder.encode(FontDataFormat::SystemUIFont));+ MUST(encoder.encode(style));+ },+ [&](String const& postscript_name) {+ MUST(encoder.encode(FontDataFormat::PlatformFontName));+ MUST(encoder.encode(postscript_name));+ });}Optional<FaceStyle> TypefaceCoreText::fixed_style() const{// One variable face of a system UI font serves every style, so the typeface answers with the style that it was// asked for.- return FaceStyle { .weight = m_style.weight, .width = m_style.width, .slope = m_style.slope };+ if (auto const* style = m_identity.get_pointer<SystemUIFontStyle>())+ return FaceStyle { .weight = style->weight, .width = style->width, .slope = style->slope };+ return {};}}diff --git a/Libraries/LibGfx/Font/TypefaceCoreText.h b/Libraries/LibGfx/Font/TypefaceCoreText.hindex 268d8c3df46..7b307492561 100644--- a/Libraries/LibGfx/Font/TypefaceCoreText.h+++ b/Libraries/LibGfx/Font/TypefaceCoreText.h@@ -6,13 +6,16 @@#pragma once+#include <AK/String.h>+#include <AK/Variant.h>#include <LibGfx/Font/Typeface.h>#include <CoreText/CoreText.h>namespace Gfx {-// A system UI font, which CoreText gives without its font data. HarfBuzz reads its tables through CoreText.+// A typeface that CoreText gives without its font data: a system UI font, or an installed font whose data CoreText+// cannot load back. HarfBuzz reads its tables through CoreText.class TypefaceCoreText final : public Typeface {AK_MAKE_NONCOPYABLE(TypefaceCoreText);AK_MAKE_NONMOVABLE(TypefaceCoreText);@@ -22,12 +25,20 @@ public:// same typeface.static RefPtr<TypefaceCoreText> system_ui(SystemUIFontStyle);+ // The installed font that has this PostScript name.+ static ErrorOr<NonnullRefPtr<TypefaceCoreText>> try_load_postscript_name(String const&);+virtual ~TypefaceCoreText() override;CTFontRef core_text_font() const { return m_core_text_font; }+ // HarfBuzz cannot draw the outlines of some fonts that CoreText gives, such as the hvgl outlines of PingFang.+ bool has_outlines_that_only_core_text_draws() const;+private:- TypefaceCoreText(CTFontRef, CGFontRef, SystemUIFontStyle);+ using Identity = Variant<SystemUIFontStyle, String>;++ TypefaceCoreText(CTFontRef, CGFontRef, Identity);virtual ReadonlyBytes buffer() const override { return {}; }virtual u32 ttc_index() const override { return 0; }@@ -38,10 +49,16 @@ private:CTFontRef m_core_text_font { nullptr };CGFontRef m_graphics_font { nullptr };- SystemUIFontStyle m_style;+ Identity m_identity;+ mutable OnceFlag m_outline_format_once;+ mutable bool m_has_outlines_that_only_core_text_draws { false };};template<>inline bool Typeface::fast_is<TypefaceCoreText>() const { return is_core_text(); }+// A copy of a CoreText font at a size, with these coordinates on top of the variation of the font. Without+// 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>);+}diff --git a/Libraries/LibGfx/PathSkia.cpp b/Libraries/LibGfx/PathSkia.cppindex 947428cb6c4..aac57fb0b72 100644--- a/Libraries/LibGfx/PathSkia.cpp+++ b/Libraries/LibGfx/PathSkia.cpp@@ -8,6 +8,8 @@#include <AK/GenericShorthands.h>#include <AK/Math.h>+#include <AK/Noncopyable.h>+#include <AK/ScopeGuard.h>#include <AK/Span.h>#include <AK/TypeCasts.h>#include <LibGfx/Font/Font.h>@@ -23,6 +25,10 @@#include <harfbuzz/hb.h>+#ifdef AK_OS_MACOS+# include <LibGfx/Font/TypefaceCoreText.h>+#endif+template<>constexpr bool AllocatedWithSystemAllocator<SkPath> = true;@@ -128,25 +134,101 @@ hb_draw_funcs_t* glyph_outline_draw_funcs()}-// The outline of a glyph in pixels, with its origin on the baseline.-static SkPath glyph_outline(Font const& font, u32 glyph_id)+#ifdef AK_OS_MACOS+static SkPath core_text_glyph_outline(CTFontRef font, u32 glyph_id){- auto* hb_font = font.harfbuzz_font();- int x_scale = 0;- int y_scale = 0;- hb_font_get_scale(hb_font, &x_scale, &y_scale);- if (x_scale <= 0 || y_scale <= 0)+ auto path = CTFontCreatePathForGlyph(font, static_cast<CGGlyph>(glyph_id), nullptr);+ if (!path)return {};+ ScopeGuard release_path = [&] { CGPathRelease(path); };++ // CoreText gives points in pixels with y up.SkPathBuilder builder;- GlyphOutline outline {- .builder = builder,- .units_to_pixels_x = font.pixel_size() / static_cast<float>(x_scale),- .units_to_pixels_y = font.pixel_size() / static_cast<float>(y_scale),- };- hb_font_draw_glyph(hb_font, glyph_id, glyph_outline_draw_funcs(), &outline);- outline.close_contour();+ CGPathApply(path, &builder, [](void* info, CGPathElement const* element) {+ auto& builder = *static_cast<SkPathBuilder*>(info);+ auto point = [&](size_t index) {+ return SkPoint::Make(static_cast<float>(element->points[index].x), 0.0f - static_cast<float>(element->points[index].y));+ };+ switch (element->type) {+ case kCGPathElementMoveToPoint:+ builder.moveTo(point(0));+ break;+ case kCGPathElementAddLineToPoint:+ builder.lineTo(point(0));+ break;+ case kCGPathElementAddQuadCurveToPoint:+ builder.quadTo(point(0), point(1));+ break;+ case kCGPathElementAddCurveToPoint:+ builder.cubicTo(point(0), point(1), point(2));+ break;+ case kCGPathElementCloseSubpath:+ builder.close();+ break;+ }+ });return builder.detach();}+#endif++namespace {++// Gives the outlines of the glyphs of a font in pixels, with their origin on the baseline.+class GlyphOutliner {+ AK_MAKE_NONCOPYABLE(GlyphOutliner);+ AK_MAKE_NONMOVABLE(GlyphOutliner);++public:+ explicit GlyphOutliner(Font const& font)+ : m_font(font)+ {+#ifdef AK_OS_MACOS+ if (auto const* core_text_typeface = as_if<TypefaceCoreText>(font.typeface()); core_text_typeface && core_text_typeface->has_outlines_that_only_core_text_draws())+ m_core_text_font = create_core_text_font_with_variations(core_text_typeface->core_text_font(), font.pixel_size(), font.variation_settings().to_sorted_list());+#endif+ }++ ~GlyphOutliner()+ {+#ifdef AK_OS_MACOS+ if (m_core_text_font)+ CFRelease(m_core_text_font);+#endif+ }++ SkPath outline(u32 glyph_id) const+ {+#ifdef AK_OS_MACOS+ if (m_core_text_font)+ return core_text_glyph_outline(m_core_text_font, glyph_id);+#endif++ auto* hb_font = m_font.harfbuzz_font();+ int x_scale = 0;+ int y_scale = 0;+ hb_font_get_scale(hb_font, &x_scale, &y_scale);+ if (x_scale <= 0 || y_scale <= 0)+ return {};+ SkPathBuilder builder;+ GlyphOutline outline {+ .builder = builder,+ .units_to_pixels_x = m_font.pixel_size() / static_cast<float>(x_scale),+ .units_to_pixels_y = m_font.pixel_size() / static_cast<float>(y_scale),+ };+ hb_font_draw_glyph(hb_font, glyph_id, glyph_outline_draw_funcs(), &outline);+ outline.close_contour();+ return builder.detach();+ }++private:+ Font const& m_font;+#ifdef AK_OS_MACOS+ // The font at its size and variations, for outlines that only CoreText draws.+ CTFontRef m_core_text_font { nullptr };+#endif+};++}NonnullOwnPtr<Gfx::PathImplSkia> PathImplSkia::create(){@@ -313,8 +395,9 @@ void PathImplSkia::glyph_run(GlyphRun const& glyph_run)auto& path_builder = sk_path_builder();path_builder.setFillType(SkPathFillType::kWinding);auto font_ascent = glyph_run.font().pixel_metrics().ascent;+ GlyphOutliner outliner { glyph_run.font() };for (auto const& glyph : glyph_run.glyphs())- path_builder.addPath(glyph_outline(glyph_run.font(), glyph.glyph_id), glyph.position.x(), glyph.position.y() + font_ascent);+ path_builder.addPath(outliner.outline(glyph.glyph_id), glyph.position.x(), glyph.position.y() + font_ascent);update_state_from_path(sk_path());}@@ -340,6 +423,7 @@ NonnullOwnPtr<PathImpl> PathImplSkia::place_glyph_runs_along(ReadonlySpan<Nonnulfor (auto const& glyph_run : glyph_runs) {if (glyph_run->font().is_invisible())continue;+ GlyphOutliner outliner { glyph_run->font() };for (auto const& glyph : glyph_run->glyphs()) {SkScalar glyph_distance = offset + glyph.position.x();@@ -357,7 +441,7 @@ NonnullOwnPtr<PathImpl> PathImplSkia::place_glyph_runs_along(ReadonlySpan<NonnulSkMatrix matrix;matrix.setTranslate(position.x(), position.y());matrix.preRotate(SkRadiansToDegrees(std::atan2(tangent.y(), tangent.x())));- output_path->sk_path_builder().addPath(glyph_outline(glyph_run->font(), glyph.glyph_id), matrix);+ output_path->sk_path_builder().addPath(outliner.outline(glyph.glyph_id), matrix);}if (reached_end_of_path)break;diff --git a/Libraries/LibWebView/FontService.cpp b/Libraries/LibWebView/FontService.cppindex faeb03ab656..fa5dfccf316 100644--- a/Libraries/LibWebView/FontService.cpp+++ b/Libraries/LibWebView/FontService.cpp@@ -232,8 +232,8 @@ Gfx::BrokeredFont FontService::open_font_without_lock(u64 generation, u64 face_i},};},- [&](Gfx::SystemFontReference const& reference) -> Gfx::BrokeredFont {- return { .face_id = face_id, .source = reference };+ [&](Gfx::PlatformFontName const& name) -> Gfx::BrokeredFont {+ return { .face_id = face_id, .source = name };});}return {};@@ -256,17 +256,18 @@ Gfx::BrokeredFont FontService::materialize_typeface(NonnullRefPtr<Gfx::TypefaceSreturn open_font_without_lock(m_generation, face_id);}- auto face_id = m_next_dynamic_face_id++;-// The platform does not always load a matched typeface's data back (CoreText rejects the hvgl-only data it hands- // out for PingFang), so such fonts are referred to by family and style for the client to re-match itself.+ // out for PingFang), so such fonts are referred to by their PostScript name for the client to open.+ Optional<String> postscript_name;if (Gfx::TypefaceSkia::try_load_from_temporary_memory(typeface->font_data(), ttc_index).is_error()) {- m_memory_font_sources.set(face_id, Gfx::SystemFontReference {- .family = typeface->family().to_string(),- .weight = typeface->weight(),- .width = typeface->width(),- .slope = typeface->slope(),- });+ postscript_name = typeface->postscript_name();+ if (!postscript_name.has_value())+ return {};+ }++ auto face_id = m_next_dynamic_face_id++;+ if (postscript_name.has_value()) {+ m_memory_font_sources.set(face_id, Gfx::PlatformFontName { postscript_name.release_value() });} else {auto file = create_immutable_font_data(typeface->font_data());if (file.is_error())diff --git a/Libraries/LibWebView/FontService.h b/Libraries/LibWebView/FontService.hindex ae18ddbbbf6..e6718fb8818 100644--- a/Libraries/LibWebView/FontService.h+++ b/Libraries/LibWebView/FontService.h@@ -55,7 +55,7 @@ private:Gfx::FontFileFormat format { Gfx::FontFileFormat::OpenType };};- using MemoryFontSource = Variant<Gfx::BrokeredFontFile, Gfx::SystemFontReference>;+ using MemoryFontSource = Variant<Gfx::BrokeredFontFile, Gfx::PlatformFontName>;ErrorOr<void> build_catalog();ErrorOr<void> build_empty_catalog();diff --git a/Tests/LibGfx/TestSharedFontProvider.cpp b/Tests/LibGfx/TestSharedFontProvider.cppindex 96a1eb560de..e42dc855a37 100644--- a/Tests/LibGfx/TestSharedFontProvider.cpp+++ b/Tests/LibGfx/TestSharedFontProvider.cpp@@ -18,7 +18,6 @@#include <LibGfx/Font/FontCatalog.h>#include <LibGfx/Font/PathFontProvider.h>#include <LibGfx/Font/SharedFontProvider.h>-#include <LibGfx/Font/TypefaceSkia.h>#include <LibTest/TestCase.h>namespace {@@ -72,16 +71,11 @@ static Gfx::BrokeredFont open_test_font(u64 face_id)};}-static Gfx::BrokeredFont reference_test_font(u64 face_id, String family)+static Gfx::BrokeredFont platform_test_font(u64 face_id, String postscript_name){return {.face_id = face_id,- .source = Gfx::SystemFontReference {- .family = move(family),- .weight = 400,- .width = Gfx::FontWidth::Normal,- .slope = 0,- },+ .source = Gfx::PlatformFontName { move(postscript_name) },};}@@ -256,26 +250,21 @@ TEST_CASE(caches_code_point_fallback_matches_and_misses)EXPECT_EQ(match_count, 4u);}-TEST_CASE(matches_referenced_system_fonts_in_process)+#ifdef AK_OS_MACOS+TEST_CASE(opens_platform_fonts_by_name_in_process){- // Referenced fonts are re-matched locally, so this needs a family the platform can resolve: whichever one it- // would pick for a plain letter.- auto platform_typeface = Gfx::TypefaceSkia::find_typeface_for_code_point('A', 400, Gfx::FontWidth::Normal, 0, false);- if (platform_typeface.is_error() || !platform_typeface.value())- return;- auto family = platform_typeface.value()->family();-+ // A platform font is opened by its PostScript name in the client, and every Mac has Helvetica.size_t match_count = 0;Gfx::SharedFontProviderCallbacks callbacks;callbacks.match_font_for_code_point = [&](u32, u16, u16, u8, bool) {++match_count;- return reference_test_font(96, family.to_string());+ return platform_test_font(96, "Helvetica"_string);};auto provider = MUST(Gfx::SharedFontProvider::create_empty(9, move(callbacks)));auto font = provider->get_font_for_code_point('A', 12, 400, Gfx::FontWidth::Normal, 0, false);EXPECT(font);- EXPECT_EQ(font->typeface().family(), family);+ EXPECT_EQ(font->typeface().postscript_name(), "Helvetica"_string);auto identifier = font->typeface().system_font_identifier();EXPECT(identifier.has_value());EXPECT_EQ(identifier->face_id, 96u);@@ -284,14 +273,15 @@ TEST_CASE(matches_referenced_system_fonts_in_process)EXPECT(provider->get_typeface_by_id(9, 96));EXPECT_EQ(match_count, 1u);}+#endif-TEST_CASE(negatively_caches_unresolvable_system_font_references)+TEST_CASE(negatively_caches_platform_fonts_that_do_not_open){size_t match_count = 0;Gfx::SharedFontProviderCallbacks callbacks;callbacks.match_font_for_code_point = [&](u32, u16, u16, u8, bool) {++match_count;- return reference_test_font(97, "Ladybird No Such Family"_string);+ return platform_test_font(97, "Ladybird-NoSuchFont"_string);};auto provider = MUST(Gfx::SharedFontProvider::create_empty(9, move(callbacks)));