Skip to content

Truly independent web browser

LibGfx+Compositor: Make Skia typefaces from font data in the compositor

Aliaksandr Kalenik8266fc4174b6
diff --git a/Libraries/LibGfx/Font/Typeface.h b/Libraries/LibGfx/Font/Typeface.h
index ba09b53ad12..48d54e67151 100644
--- a/Libraries/LibGfx/Font/Typeface.h
+++ b/Libraries/LibGfx/Font/Typeface.h
@@ -113,6 +113,8 @@ public:
u8 slope() const;
ReadonlyBytes font_data() const LIFETIME_BOUND { return buffer(); }
+ // What keeps the font data alive. Null for a typeface without font data of its own.
+ RefPtr<FontDataBacking> font_data_backing() const { return m_font_data; }
u32 collection_index() const { return ttc_index(); }
[[nodiscard]] NonnullRefPtr<Font> font(float point_size, FontVariationSettings const& variations = {}, Gfx::ShapeFeatures const& shape_features = {}) const;
diff --git a/Libraries/LibGfx/Font/TypefaceCoreText.cpp b/Libraries/LibGfx/Font/TypefaceCoreText.cpp
index 29e54af94b9..befe667b957 100644
--- a/Libraries/LibGfx/Font/TypefaceCoreText.cpp
+++ b/Libraries/LibGfx/Font/TypefaceCoreText.cpp
@@ -9,6 +9,7 @@
#include <AK/HashMap.h>
#include <AK/Mutex.h>
#include <AK/NeverDestroyed.h>
+#include <AK/NumericLimits.h>
#include <AK/ScopeGuard.h>
#include <AK/Vector.h>
#include <LibGfx/Font/FontTable.h>
@@ -222,6 +223,96 @@ Optional<unsigned> named_instance_with_variation(hb_face_t* face, CFDictionaryRe
return {};
}
+// 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;
+
+ Vector<FontVariationAxis> variation;
+ variation.ensure_capacity(axis_count);
+ for (unsigned index = 0; index < axis_count; ++index)
+ variation.unchecked_append({ FourCC::from_u32(axes[index].tag), coordinates[index] });
+ return create_core_text_font_with_variations(font, 0, variation);
+}
+
+CTFontRef create_core_text_font_from_data(NonnullRefPtr<Typeface::FontDataBacking> backing, ReadonlyBytes bytes, u32 ttc_index)
+{
+ if (bytes.size() > static_cast<size_t>(NumericLimits<CFIndex>::max()) || bytes.size() > NumericLimits<unsigned>::max())
+ return nullptr;
+ auto* blob = hb_blob_create(reinterpret_cast<char const*>(bytes.data()), bytes.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 name = face_name(face, HB_OT_NAME_ID_POSTSCRIPT_NAME);
+ if (!name.has_value())
+ return nullptr;
+ auto name_bytes = name->bytes();
+ auto postscript_name = CFStringCreateWithBytes(kCFAllocatorDefault, name_bytes.data(), static_cast<CFIndex>(name_bytes.size()), kCFStringEncodingUTF8, false);
+ if (!postscript_name)
+ return nullptr;
+ ScopeGuard release_name = [&] { CFRelease(postscript_name); };
+
+ CFAllocatorContext allocator_context {};
+ allocator_context.info = backing.ptr();
+ allocator_context.retain = [](void const* info) -> void const* {
+ static_cast<Typeface::FontDataBacking const*>(info)->ref();
+ return info;
+ };
+ allocator_context.release = [](void const* info) { static_cast<Typeface::FontDataBacking const*>(info)->unref(); };
+ allocator_context.deallocate = [](void*, void*) { };
+ auto allocator = CFAllocatorCreate(kCFAllocatorDefault, &allocator_context);
+ if (!allocator)
+ return nullptr;
+ ScopeGuard release_allocator = [&] { CFRelease(allocator); };
+ auto data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, bytes.data(), static_cast<CFIndex>(bytes.size()), allocator);
+ if (!data)
+ return nullptr;
+ ScopeGuard release_data = [&] { CFRelease(data); };
+ auto descriptors = CTFontManagerCreateFontDescriptorsFromData(data);
+ if (!descriptors)
+ return nullptr;
+ ScopeGuard release_descriptors = [&] { CFRelease(descriptors); };
+
+ // CoreText also lists the named instances of the faces, so the PostScript name of the face finds its descriptor,
+ // and the position of a descriptor in the list is not a face index.
+ CTFontDescriptorRef descriptor = nullptr;
+ for (CFIndex index = 0; index < CFArrayGetCount(descriptors); ++index) {
+ auto candidate = static_cast<CTFontDescriptorRef>(CFArrayGetValueAtIndex(descriptors, index));
+ auto candidate_name = CTFontDescriptorCopyAttribute(candidate, kCTFontNameAttribute);
+ if (!candidate_name)
+ continue;
+ ScopeGuard release_candidate_name = [&] { CFRelease(candidate_name); };
+ if (CFEqual(candidate_name, postscript_name)) {
+ descriptor = candidate;
+ break;
+ }
+ }
+ if (!descriptor)
+ return nullptr;
+ auto font = CTFontCreateWithFontDescriptor(descriptor, 0, nullptr);
+ if (!font)
+ return nullptr;
+
+ // 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(font, face, instance_index - 1)) {
+ CFRelease(font);
+ font = instance_font;
+ }
+ }
+ return font;
+}
+
TypefaceCoreText::TypefaceCoreText(CTFontRef core_text_font, CGFontRef graphics_font, Identity identity)
: m_core_text_font(core_text_font)
, m_graphics_font(graphics_font)
diff --git a/Libraries/LibGfx/Font/TypefaceCoreText.h b/Libraries/LibGfx/Font/TypefaceCoreText.h
index 23b8e875c37..607f60ffce9 100644
--- a/Libraries/LibGfx/Font/TypefaceCoreText.h
+++ b/Libraries/LibGfx/Font/TypefaceCoreText.h
@@ -57,6 +57,11 @@ private:
template<>
inline bool Typeface::fast_is<TypefaceCoreText>() const { return is_core_text(); }
+// The CoreText font of a face in font data. The upper 16 bits of the index select a named instance, from 1, whose
+// coordinates the font gets as a variation. CoreText keeps the backing while it uses the data. Null if CoreText does
+// not load the face.
+CTFontRef create_core_text_font_from_data(NonnullRefPtr<Typeface::FontDataBacking>, ReadonlyBytes, u32 ttc_index);
+
// 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/Font/TypefaceSkia.cpp b/Libraries/LibGfx/Font/TypefaceSkia.cpp
index e0287da6463..d3cc2f3f94c 100644
--- a/Libraries/LibGfx/Font/TypefaceSkia.cpp
+++ b/Libraries/LibGfx/Font/TypefaceSkia.cpp
@@ -40,6 +40,7 @@
#ifdef AK_OS_MACOS
# include <CoreText/CoreText.h>
+# include <LibGfx/Font/TypefaceCoreText.h>
# include <ports/SkFontMgr_mac_ct.h>
# include <ports/SkTypeface_mac.h>
# include <src/ports/SkTypeface_mac_ct.h>
@@ -70,52 +71,6 @@ 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))
@@ -129,85 +84,11 @@ ErrorOr<NonnullRefPtr<TypefaceSkia>> TypefaceSkia::load_from_buffer(AK::Readonly
sk_sp<SkTypeface> skia_typeface;
#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.
+ // NB: Skia's CoreText stream loader only supports collection index zero.
if (ttc_index != 0 && !FontDatabase::the().force_freetype_rasterization()) {
- if (buffer.size() > static_cast<size_t>(NumericLimits<CFIndex>::max()))
- return Error::from_string_literal("Font data is too large for CoreText");
- 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); };
- unsigned entry_count = 0;
- auto const* entries = hb_ot_name_list_names(face, &entry_count);
- auto language = HB_LANGUAGE_INVALID;
- for (unsigned index = 0; index < entry_count; ++index) {
- if (entries[index].name_id != HB_OT_NAME_ID_POSTSCRIPT_NAME)
- continue;
- if (language == HB_LANGUAGE_INVALID)
- language = entries[index].language;
- if (entries[index].language == hb_language_from_string("en", -1)) {
- language = entries[index].language;
- break;
- }
- }
- unsigned name_length = hb_ot_name_get_utf8(face, HB_OT_NAME_ID_POSTSCRIPT_NAME, language, nullptr, nullptr);
- if (name_length == 0 || name_length == NumericLimits<unsigned>::max())
- return Error::from_string_literal("Font collection face has no PostScript name");
- auto name = TRY(ByteBuffer::create_uninitialized(static_cast<size_t>(name_length) + 1));
- unsigned capacity = name_length + 1;
- hb_ot_name_get_utf8(face, HB_OT_NAME_ID_POSTSCRIPT_NAME, language, &capacity, reinterpret_cast<char*>(name.data()));
- auto postscript_name = CFStringCreateWithBytes(kCFAllocatorDefault, name.data(), capacity, kCFStringEncodingUTF8, false);
- if (!postscript_name)
- return Error::from_string_literal("Invalid font PostScript name");
- ScopeGuard release_name = [&] { CFRelease(postscript_name); };
- // NB: CoreText must share the same bytes as Skia, retaining their backing for as long as it uses them.
- CFAllocatorContext allocator_context {};
- allocator_context.info = data.get();
- allocator_context.retain = [](void const* info) -> void const* {
- static_cast<SkData const*>(info)->ref();
- return info;
- };
- allocator_context.release = [](void const* info) { static_cast<SkData const*>(info)->unref(); };
- allocator_context.deallocate = [](void*, void*) { };
- auto allocator = CFAllocatorCreate(kCFAllocatorDefault, &allocator_context);
- if (!allocator)
- return Error::from_string_literal("Failed to create CoreText font data allocator");
- ScopeGuard release_allocator = [&] { CFRelease(allocator); };
- auto cf_data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, static_cast<u8 const*>(data->data()), static_cast<CFIndex>(data->size()), allocator);
- if (!cf_data)
- return Error::from_string_literal("Failed to create CoreText font data");
- ScopeGuard release_data = [&] { CFRelease(cf_data); };
- auto descriptors = CTFontManagerCreateFontDescriptorsFromData(cf_data);
- if (!descriptors)
- return Error::from_string_literal("Failed to read CoreText font descriptors");
- ScopeGuard release_descriptors = [&] { CFRelease(descriptors); };
- // NB: CoreText also lists named variation instances. Match the actual TTC face's PostScript name rather
- // than interpreting a descriptor array position as a collection index.
- CTFontDescriptorRef descriptor = nullptr;
- for (CFIndex index = 0; index < CFArrayGetCount(descriptors); ++index) {
- auto candidate = static_cast<CTFontDescriptorRef>(CFArrayGetValueAtIndex(descriptors, index));
- auto candidate_name = CTFontDescriptorCopyAttribute(candidate, kCTFontNameAttribute);
- if (!candidate_name)
- continue;
- ScopeGuard release_candidate_name = [&] { CFRelease(candidate_name); };
- if (CFEqual(candidate_name, postscript_name)) {
- descriptor = candidate;
- break;
- }
- }
- if (!descriptor)
- return Error::from_string_literal("CoreText did not describe the requested collection face");
- auto ct_font = CTFontCreateWithFontDescriptor(descriptor, 0, nullptr);
+ auto ct_font = create_core_text_font_from_data(backing, buffer, ttc_index);
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;
- }
- }
+ return Error::from_string_literal("CoreText did not load the collection face");
ScopeGuard release_font = [&] { CFRelease(ct_font); };
skia_typeface = SkMakeTypefaceFromCTFont(ct_font);
} else
diff --git a/Services/Compositor/FontSkia.cpp b/Services/Compositor/FontSkia.cpp
index 7be337320d7..189d5d773e8 100644
--- a/Services/Compositor/FontSkia.cpp
+++ b/Services/Compositor/FontSkia.cpp
@@ -5,16 +5,22 @@
*/
#include <AK/Atomic.h>
+#include <AK/NeverDestroyed.h>
+#include <AK/ScopeGuard.h>
#include <AK/TypeCasts.h>
#include <Compositor/FontSkia.h>
#include <LibGfx/Font/Font.h>
+#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/RasterizerData.h>
-#include <LibGfx/Font/TypefaceSkia.h>
+#include <core/SkData.h>
#include <core/SkFont.h>
#include <core/SkFontArguments.h>
+#include <core/SkFontMgr.h>
#include <core/SkFontTypes.h>
+#include <core/SkStream.h>
#include <core/SkTypeface.h>
+#include <ports/SkFontMgr_empty.h>
#if defined(USE_FONTCONFIG)
# include <LibGfx/Font/GlobalFontConfig.h>
@@ -23,6 +29,11 @@
#ifdef AK_OS_MACOS
# include <LibGfx/Font/TypefaceCoreText.h>
# include <ports/SkTypeface_mac.h>
+# include <src/ports/SkTypeface_mac_ct.h>
+#endif
+
+#ifdef AK_OS_WINDOWS
+# include <src/ports/SkTypeface_win_dw.h>
#endif
namespace Compositor {
@@ -70,13 +81,53 @@ struct TypefaceData final : public Gfx::RasterizerData {
sk_sp<SkTypeface> typeface;
};
+// The Skia typeface of font data from the font manager of the platform. Null where FreeType is that font manager.
+// The typeface loaders are called directly, because a font manager also finds the system fonts when it is made.
+sk_sp<SkTypeface> make_platform_skia_typeface([[maybe_unused]] sk_sp<SkData> const& data, [[maybe_unused]] Gfx::Typeface const& typeface)
+{
+ if (Gfx::FontDatabase::the().force_freetype_rasterization())
+ return nullptr;
+#if defined(AK_OS_MACOS)
+ // The CoreText typeface loader of Skia loads only the first face of font data.
+ if (typeface.collection_index() != 0) {
+ auto font = Gfx::create_core_text_font_from_data(typeface.font_data_backing().release_nonnull(), typeface.font_data(), typeface.collection_index());
+ if (!font)
+ return nullptr;
+ ScopeGuard release_font = [&] { CFRelease(font); };
+ return SkMakeTypefaceFromCTFont(font);
+ }
+ return SkTypeface_Mac::MakeFromStream(std::make_unique<SkMemoryStream>(data), SkFontArguments {});
+#elif defined(AK_OS_WINDOWS)
+ return DWriteFontTypeface::MakeFromStream(std::make_unique<SkMemoryStream>(data), SkFontArguments {}.setCollectionIndex(static_cast<int>(typeface.collection_index())));
+#else
+ return nullptr;
+#endif
+}
+
sk_sp<SkTypeface> make_skia_typeface(Gfx::Typeface const& typeface)
{
#ifdef AK_OS_MACOS
if (auto const* core_text_typeface = as_if<Gfx::TypefaceCoreText>(typeface))
return SkMakeTypefaceFromCTFont(core_text_typeface->core_text_font());
#endif
- return sk_ref_sp(as<Gfx::TypefaceSkia>(typeface).sk_typeface());
+ auto backing = typeface.font_data_backing();
+ if (!backing)
+ return nullptr;
+
+ // Skia can keep a typeface in text blobs and glyph caches after the typeface is gone, so the data keeps its backing.
+ auto bytes = typeface.font_data();
+ auto data = SkData::MakeWithProc(
+ bytes.data(), bytes.size(), [](void const*, void* context) { static_cast<Gfx::Typeface::FontDataBacking*>(context)->unref(); }, backing.leak_ref());
+ if (auto skia_typeface = make_platform_skia_typeface(data, typeface))
+ return skia_typeface;
+
+ // FreeType also loads some data that the font manager of the platform does not.
+ static NeverDestroyed<sk_sp<SkFontMgr>> font_manager { SkFontMgr_New_Custom_Empty() };
+ if (auto skia_typeface = (*font_manager)->makeFromStream(std::make_unique<SkMemoryStream>(data), SkFontArguments {}.setCollectionIndex(static_cast<int>(typeface.collection_index()))))
+ return skia_typeface;
+
+ dbgln("Compositor: Skia does not load the typeface of family '{}'", typeface.family());
+ return nullptr;
}
// The Skia typeface of a typeface. Null if Skia cannot load it.