Skip to content

Truly independent web browser

LibGfx+LibCompositing+Compositor: Share typefaces between variations

Aliaksandr Kalenikf295b0fd6bda
diff --git a/Libraries/LibCompositing/DisplayList/DisplayListResourceTransaction.cpp b/Libraries/LibCompositing/DisplayList/DisplayListResourceTransaction.cpp
index 0181091f3c7..9d899fabc52 100644
--- a/Libraries/LibCompositing/DisplayList/DisplayListResourceTransaction.cpp
+++ b/Libraries/LibCompositing/DisplayList/DisplayListResourceTransaction.cpp
@@ -56,9 +56,7 @@ ErrorOr<Compositing::DisplayListFontResource> decode(Decoder& decoder)
auto variations = TRY(decoder.decode<Gfx::FontVariationSettings>());
auto features = TRY(decoder.decode<Gfx::ShapeFeatures>());
auto invisible = TRY(decoder.decode<bool>());
- auto font = typeface->font(point_size, move(variations), move(features));
- if (invisible)
- font = font->invisible_variant();
+ auto font = invisible ? typeface->invisible_font(point_size, variations, features) : typeface->font(point_size, variations, features);
return Compositing::DisplayListFontResource {
.id = id,
diff --git a/Libraries/LibGfx/Font/Font.cpp b/Libraries/LibGfx/Font/Font.cpp
index 1a3e727501a..9e9cc3954f1 100644
--- a/Libraries/LibGfx/Font/Font.cpp
+++ b/Libraries/LibGfx/Font/Font.cpp
@@ -85,9 +85,7 @@ float Font::width(Utf16View const& view) const { return measure_text_width(view,
NonnullRefPtr<Font> Font::invisible_variant() const
{
- auto font = adopt_ref(*new Font(m_typeface, m_point_width, m_point_height, m_font_variation_settings, m_shape_features));
- font->m_is_invisible = true;
- return font;
+ return m_typeface->invisible_font(m_point_height, m_font_variation_settings, m_shape_features);
}
float Font::pixel_size() const
@@ -100,6 +98,11 @@ float Font::point_size() const
return m_point_height;
}
+void Font::will_be_destroyed() const
+{
+ m_typeface->forget_font(*this);
+}
+
Font::~Font()
{
if (m_harfbuzz_font)
diff --git a/Libraries/LibGfx/Font/Font.h b/Libraries/LibGfx/Font/Font.h
index 2992d911059..e1c4e06734c 100644
--- a/Libraries/LibGfx/Font/Font.h
+++ b/Libraries/LibGfx/Font/Font.h
@@ -81,6 +81,9 @@ public:
bool is_emoji_font() const;
+ // Called by AtomicRefCounted when the last reference goes away.
+ void will_be_destroyed() const;
+
// What a rasterizer keeps with this font. The first call makes it.
template<typename T, typename Callback>
T& rasterizer_data(Callback make) const
@@ -90,6 +93,8 @@ public:
}
private:
+ friend class Typeface;
+
bool m_is_invisible { false };
u64 m_id { 0 };
diff --git a/Libraries/LibGfx/Font/SharedFontProvider.cpp b/Libraries/LibGfx/Font/SharedFontProvider.cpp
index 29a2fafa626..c45fdfe742a 100644
--- a/Libraries/LibGfx/Font/SharedFontProvider.cpp
+++ b/Libraries/LibGfx/Font/SharedFontProvider.cpp
@@ -69,11 +69,7 @@ SharedFontProvider::SharedFontProvider(NonnullOwnPtr<Core::MappedFile> mapping,
m_resource_fonts.load_all_fonts_from_uri("resource://fonts"sv);
}
-SharedFontProvider::~SharedFontProvider()
-{
- for (auto const& entry : m_typeface_cache)
- entry.value->clear_font_cache();
-}
+SharedFontProvider::~SharedFontProvider() = default;
static FontVariationSettings default_variations(float point_size, unsigned weight, unsigned width)
{
diff --git a/Libraries/LibGfx/Font/SystemFallbackFonts.cpp b/Libraries/LibGfx/Font/SystemFallbackFonts.cpp
index 635d24a6d4d..f1afb2fa009 100644
--- a/Libraries/LibGfx/Font/SystemFallbackFonts.cpp
+++ b/Libraries/LibGfx/Font/SystemFallbackFonts.cpp
@@ -29,8 +29,8 @@ struct SystemFallbackFontCache {
Mutex mutex;
// A miss is an answer too: without it every code point no family covers asks the provider again
// on every lookup, and for the shared provider that is an IPC round trip.
- // NB: The memo holds typefaces, not fonts, so the sizes a page asks for stay bounded by the typeface's
- // own font cache instead of each one being kept here until the font set changes.
+ // NB: The memo holds typefaces, not fonts, so a font of each size that a page asks for lives only while it is
+ // in use or among the fonts made last, instead of until the font set changes.
HashMap<SystemFallbackFontKey, RefPtr<Typeface const>, SystemFallbackFontKeyTraits> typefaces;
};
diff --git a/Libraries/LibGfx/Font/Typeface.cpp b/Libraries/LibGfx/Font/Typeface.cpp
index 739ba89e866..91a051038ee 100644
--- a/Libraries/LibGfx/Font/Typeface.cpp
+++ b/Libraries/LibGfx/Font/Typeface.cpp
@@ -7,8 +7,10 @@
#include <harfbuzz/hb-ot.h>
#include <harfbuzz/hb.h>
+#include <AK/Array.h>
#include <AK/Atomic.h>
#include <AK/Diagnostics.h>
+#include <AK/NeverDestroyed.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/FontTable.h>
@@ -70,38 +72,66 @@ Typeface::~Typeface()
hb_blob_destroy(m_harfbuzz_blob);
}
-void Typeface::clear_font_cache() const
+namespace {
+
+// The fonts that were made last. Text asks for the same fonts again and again, so a font stays alive for a while after
+// its last holder drops it, and keeps its id and the data of its rasterizer when it comes back.
+struct RecentFonts {
+ static constexpr size_t capacity = 256;
+
+ Mutex mutex;
+ Array<RefPtr<Font const>, capacity> fonts;
+ size_t next_index { 0 };
+};
+
+void keep_recent_font(NonnullRefPtr<Font const> font)
{
- MutexLocker locker { m_fonts_mutex };
- m_fonts.clear();
+ static NeverDestroyed<RecentFonts> recent_fonts;
+ RefPtr<Font const> oldest_font;
+ {
+ MutexLocker locker { recent_fonts->mutex };
+ oldest_font = exchange(recent_fonts->fonts[recent_fonts->next_index], move(font));
+ recent_fonts->next_index = (recent_fonts->next_index + 1) % RecentFonts::capacity;
+ }
+ // NB: The oldest font is released after the lock, because releasing it can destroy the font and its typeface.
+}
+
}
NonnullRefPtr<Font> Typeface::font(float point_size, FontVariationSettings const& variations, Gfx::ShapeFeatures const& shape_features) const
{
- MutexLocker locker { m_fonts_mutex };
- FontCacheKey key { point_size, variations.to_sorted_list(), shape_features };
+ RefPtr<Font> font;
+ {
+ MutexLocker locker { m_fonts_mutex };
+ FontCacheKey key { point_size, variations.to_sorted_list(), shape_features };
- if (auto it = m_fonts.find(key); it != m_fonts.end())
- return *it->value;
+ // A font that another thread is destroying cannot be referenced any more, and a new font replaces it.
+ if (auto it = m_fonts.find(key); it != m_fonts.end() && it->value->try_ref())
+ return adopt_ref(*it->value);
- // FIXME: It might be nice to have a global cap on the number of fonts we cache
- // instead of doing it at the per-Typeface level like this.
- constexpr size_t max_cached_font_size_count = 128;
- if (m_fonts.size() > max_cached_font_size_count)
- m_fonts.remove(m_fonts.begin());
-
- RefPtr<Typeface const> used_typeface = const_cast<Typeface*>(this);
- if (!variations.is_empty()) {
- if (auto const* skia_typeface = as_if<TypefaceSkia const>(this))
- if (auto derived = skia_typeface->clone_with_variations(variations.to_sorted_list()))
- used_typeface = move(derived);
+ font = adopt_ref(*new Font(*this, point_size, point_size, variations, shape_features));
+ m_fonts.set(move(key), font.ptr());
}
+ keep_recent_font(*font);
+ return font.release_nonnull();
+}
- auto font = adopt_ref(*new Font(*used_typeface, point_size, point_size, variations, shape_features));
- m_fonts.set(key, font);
+NonnullRefPtr<Font> Typeface::invisible_font(float point_size, FontVariationSettings const& variations, Gfx::ShapeFeatures const& shape_features) const
+{
+ auto font = adopt_ref(*new Font(*this, point_size, point_size, variations, shape_features));
+ font->m_is_invisible = true;
return font;
}
+void Typeface::forget_font(Font const& font) const
+{
+ MutexLocker locker { m_fonts_mutex };
+ FontCacheKey key { font.point_size(), font.variation_settings().to_sorted_list(), font.features() };
+ // Invisible variants are not in the cache, and a newer font may have replaced this one.
+ if (auto it = m_fonts.find(key); it != m_fonts.end() && it->value == &font)
+ m_fonts.remove(it);
+}
+
hb_face_t* Typeface::harfbuzz_typeface() const
{
call_once(m_harfbuzz_face_once, [&] {
@@ -307,13 +337,6 @@ void Typeface::encode_font_data_for_ipc(IPC::Encoder& encoder) const
});
}
-void Typeface::copy_font_data_from(Typeface const& other)
-{
- m_font_data = other.m_font_data;
- m_system_font_identifier = other.m_system_font_identifier;
- m_file_path = other.m_file_path;
-}
-
}
namespace IPC {
diff --git a/Libraries/LibGfx/Font/Typeface.h b/Libraries/LibGfx/Font/Typeface.h
index 54bd064ffcd..67d170d8c64 100644
--- a/Libraries/LibGfx/Font/Typeface.h
+++ b/Libraries/LibGfx/Font/Typeface.h
@@ -47,9 +47,16 @@ struct FontCacheKey {
Vector<FontVariationAxis> axes;
Gfx::ShapeFeatures shape_features;
+ // Sizes and values compare by their bits, as the hash reads them, so that a key with NaN finds itself.
bool operator==(FontCacheKey const& other) const
{
- return point_size == other.point_size && axes == other.axes && shape_features == other.shape_features;
+ if (bit_cast<u32>(point_size) != bit_cast<u32>(other.point_size) || axes.size() != other.axes.size() || shape_features != other.shape_features)
+ return false;
+ for (size_t index = 0; index < axes.size(); ++index) {
+ if (axes[index].tag != other.axes[index].tag || bit_cast<u32>(axes[index].value) != bit_cast<u32>(other.axes[index].value))
+ return false;
+ }
+ return true;
}
unsigned hash() const
@@ -93,6 +100,8 @@ public:
u32 collection_index() const { return ttc_index(); }
[[nodiscard]] NonnullRefPtr<Font> font(float point_size, FontVariationSettings const& variations = {}, Gfx::ShapeFeatures const& shape_features = {}) const;
+ // A font that measures and shapes text like font() but draws nothing. Each call makes a new font.
+ [[nodiscard]] NonnullRefPtr<Font> invisible_font(float point_size, FontVariationSettings const& variations = {}, Gfx::ShapeFeatures const& shape_features = {}) const;
void set_system_font_identifier(SystemFontIdentifier identifier) { m_system_font_identifier = identifier; }
Optional<SystemFontIdentifier> system_font_identifier() const { return m_system_font_identifier; }
@@ -144,11 +153,10 @@ protected:
virtual hb_face_t* create_harfbuzz_face() const;
void set_font_data(NonnullRefPtr<FontDataBacking> backing) { m_font_data = move(backing); }
- void copy_font_data_from(Typeface const&);
bool has_font_data_backing() const { return !m_font_data.is_null(); }
private:
- friend class SharedFontProvider;
+ friend class Font;
template<typename T>
friend ErrorOr<void> IPC::encode(IPC::Encoder&, T const&);
@@ -160,7 +168,8 @@ private:
Optional<SystemFontIdentifier> m_system_font_identifier;
Optional<String> m_file_path;
- void clear_font_cache() const;
+ // A font that is being destroyed leaves the cache of its typeface.
+ void forget_font(Font const&) const;
// This cache stores information per code point.
// It's segmented into pages with data about 256 code points each.
@@ -179,7 +188,8 @@ private:
u64 m_glyph_cache_id { 0 };
mutable Mutex m_fonts_mutex;
- mutable HashMap<FontCacheKey, NonnullRefPtr<Font>> m_fonts;
+ // The fonts that are alive. A font does not keep itself here, so it holds its typeface without a reference cycle.
+ mutable HashMap<FontCacheKey, Font*> m_fonts;
mutable OnceFlag m_harfbuzz_face_once;
mutable hb_blob_t* m_harfbuzz_blob { nullptr };
mutable hb_face_t* m_harfbuzz_face { nullptr };
diff --git a/Libraries/LibGfx/Font/TypefaceSkia.cpp b/Libraries/LibGfx/Font/TypefaceSkia.cpp
index eb30720d532..cc9f58f8b99 100644
--- a/Libraries/LibGfx/Font/TypefaceSkia.cpp
+++ b/Libraries/LibGfx/Font/TypefaceSkia.cpp
@@ -473,53 +473,6 @@ Optional<FlyString> TypefaceSkia::resolve_generic_family(StringView family_name,
return result_or_error.release_value();
}
-RefPtr<TypefaceSkia const> TypefaceSkia::clone_with_variations(Vector<FontVariationAxis> const& axes) const
-{
- if (axes.is_empty())
- return this;
-
- SkFontArguments font_args;
-
- Vector<SkFontArguments::VariationPosition::Coordinate> coords;
- coords.ensure_capacity(axes.size());
- for (size_t i = 0; i < axes.size(); ++i) {
- coords.unchecked_append({ axes[i].tag.to_u32(), axes[i].value });
- }
- SkFontArguments::VariationPosition variation_pos;
- variation_pos.coordinates = coords.data();
- variation_pos.coordinateCount = static_cast<int>(coords.size());
- font_args.setVariationDesignPosition(variation_pos);
-
- font_args.setCollectionIndex(static_cast<int>(m_ttc_index));
-
- auto skia_typeface = impl().skia_typeface->makeClone(font_args);
- if (!skia_typeface)
- return {};
-
- 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);
- return typeface;
- }
-
-#ifdef AK_OS_MACOS
- if (impl().cg_font) {
- return adopt_ref(*new TypefaceSkia {
- make<TypefaceSkia::Impl>(move(skia_typeface), std::unique_ptr<SkStreamAsset> {}, impl().system_ui_font_style, impl().cg_font),
- {},
- m_ttc_index });
- }
-#endif
-
- auto typeface_or_error = typeface_from_skia_typeface(move(skia_typeface), impl().system_ui_font_style);
- if (typeface_or_error.is_error())
- return {};
- return typeface_or_error.release_value();
-}
-
SkTypeface const* TypefaceSkia::sk_typeface() const
{
return impl().skia_typeface.get();
diff --git a/Libraries/LibGfx/Font/TypefaceSkia.h b/Libraries/LibGfx/Font/TypefaceSkia.h
index 549f78e574a..42c5eda3d3f 100644
--- a/Libraries/LibGfx/Font/TypefaceSkia.h
+++ b/Libraries/LibGfx/Font/TypefaceSkia.h
@@ -41,8 +41,6 @@ public:
static ErrorOr<RefPtr<TypefaceSkia>> find_typeface_for_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji);
static Optional<FlyString> resolve_generic_family(StringView family_name, u16 weight, u8 slope);
- RefPtr<TypefaceSkia const> clone_with_variations(Vector<FontVariationAxis> const& axes) const;
-
virtual FlyString const& family() const override;
virtual u16 weight() const override;
virtual u16 width() const override;
diff --git a/Services/Compositor/FontSkia.cpp b/Services/Compositor/FontSkia.cpp
index d83741a7c61..83ba48d9487 100644
--- a/Services/Compositor/FontSkia.cpp
+++ b/Services/Compositor/FontSkia.cpp
@@ -12,6 +12,7 @@
#include <LibGfx/Font/TypefaceSkia.h>
#include <core/SkFont.h>
+#include <core/SkFontArguments.h>
#include <core/SkFontTypes.h>
#include <core/SkTypeface.h>
@@ -54,8 +55,36 @@ static u64 encode_hinting_memo(float scale, Gfx::FontHintingOptions options)
namespace {
+// The typeface of the font's variations. Without variations, or if Skia cannot apply them, it is the typeface itself.
+sk_sp<SkTypeface> typeface_with_variations(Gfx::Font const& font)
+{
+ auto const* typeface = as<Gfx::TypefaceSkia>(font.typeface()).sk_typeface();
+ if (!typeface)
+ return nullptr;
+ auto axes = font.variation_settings().to_sorted_list();
+ if (axes.is_empty())
+ return sk_ref_sp(typeface);
+
+ Vector<SkFontArguments::VariationPosition::Coordinate> coordinates;
+ coordinates.ensure_capacity(axes.size());
+ for (auto const& axis : axes)
+ coordinates.unchecked_append({ axis.tag.to_u32(), axis.value });
+ SkFontArguments arguments;
+ arguments.setVariationDesignPosition({ coordinates.data(), static_cast<int>(coordinates.size()) });
+ arguments.setCollectionIndex(static_cast<int>(font.typeface().collection_index()));
+ if (auto clone = typeface->makeClone(arguments))
+ return clone;
+ return sk_ref_sp(typeface);
+}
+
// What the compositor keeps with each font.
struct FontData final : public Gfx::RasterizerData {
+ explicit FontData(Gfx::Font const& font)
+ : typeface(typeface_with_variations(font))
+ {
+ }
+
+ sk_sp<SkTypeface> typeface;
#if defined(USE_FONTCONFIG)
// A font is drawn at one scale most of the time, and fontconfig's answer is a pure function of the family, the
// scaled pixel size, the weight and the slope, so one answer is kept.
@@ -65,7 +94,7 @@ struct FontData final : public Gfx::RasterizerData {
FontData& font_data(Gfx::Font const& font)
{
- return font.rasterizer_data<FontData>([] { return make<FontData>(); });
+ return font.rasterizer_data<FontData>([&] { return make<FontData>(font); });
}
#if defined(USE_FONTCONFIG)
@@ -97,11 +126,11 @@ void force_font_hinting_for_testing()
Optional<SkFont> skia_font(Gfx::Font const& font, float scale)
{
- auto const* typeface = as<Gfx::TypefaceSkia>(font.typeface()).sk_typeface();
- if (!typeface)
+ auto& data = font_data(font);
+ if (!data.typeface)
return {};
- SkFont sk_font { sk_ref_sp(typeface), font.pixel_size() * scale };
+ SkFont sk_font { data.typeface, font.pixel_size() * scale };
sk_font.setSubpixel(true);
#if defined(USE_FONTCONFIG)
diff --git a/Tests/LibGfx/TestFont.cpp b/Tests/LibGfx/TestFont.cpp
index f5465ceb8ac..97eebe4d586 100644
--- a/Tests/LibGfx/TestFont.cpp
+++ b/Tests/LibGfx/TestFont.cpp
@@ -58,10 +58,7 @@ private:
static bool font_is_emoji(StringView path)
{
auto typeface = MUST(Gfx::Typeface::try_load_from_mapped_file(MUST(Core::MappedFile::map(path)), 0));
- // Construct the Font directly rather than via Typeface::font() — which would cache it on the
- // Typeface and form a Typeface<->Font reference cycle that leaks once both leave this scope.
- auto font = adopt_ref(*new Gfx::Font(typeface, 12, 12, {}, {}));
- return font->is_emoji_font();
+ return typeface->font(12)->is_emoji_font();
}
// A COLRv1 color font is recognized.
@@ -606,11 +603,11 @@ TEST_CASE(system_fallback_fonts_can_be_matched_on_several_threads)
};
// NB: A machine without a font covering this code point answers null, and null is an answer the
// memo keeps like any other, so this test does not depend on what is installed.
- IGNORE_USE_IN_ESCAPING_LAMBDA Array<Gfx::Font const*, 8> matched {};
+ IGNORE_USE_IN_ESCAPING_LAMBDA Array<RefPtr<Gfx::Font const>, 8> matched {};
Vector<NonnullRefPtr<Threading::Thread>> threads;
for (size_t thread_index = 0; thread_index < matched.size(); ++thread_index) {
auto thread = Threading::Thread::construct("SystemFallbackFont"sv, [&key, &matched, thread_index]() {
- matched[thread_index] = Gfx::system_fallback_font(key, 12).ptr();
+ matched[thread_index] = Gfx::system_fallback_font(key, 12);
return 0;
});
thread->start();
@@ -620,10 +617,10 @@ TEST_CASE(system_fallback_fonts_can_be_matched_on_several_threads)
(void)thread->join();
// One key is matched once, so every thread names the same font object, not eight equivalent ones.
- for (auto const* font : matched)
- EXPECT_EQ(font, matched[0]);
+ for (auto const& font : matched)
+ EXPECT_EQ(font.ptr(), matched[0].ptr());
EXPECT_EQ(Gfx::system_fallback_font_cache_size(), 1u);
- EXPECT_EQ(Gfx::system_fallback_font(key, 12).ptr(), matched[0]);
+ EXPECT_EQ(Gfx::system_fallback_font(key, 12).ptr(), matched[0].ptr());
// Another size picks another font from the same typeface, so it does not grow the memo.
(void)Gfx::system_fallback_font(key, 13);