Skip to content

Truly independent web browser

LibGfx+LibWebView: Match system fonts with fontconfig directly

Aliaksandr Kalenikc2ea4c0a8d52
diff --git a/Libraries/LibGfx/CMakeLists.txt b/Libraries/LibGfx/CMakeLists.txt
index 9aa923aba8d..0c6395a4cc3 100644
--- a/Libraries/LibGfx/CMakeLists.txt
+++ b/Libraries/LibGfx/CMakeLists.txt
@@ -21,6 +21,7 @@ set(SOURCES
Font/PathFontProvider.cpp
Font/SharedFontProvider.cpp
Font/SystemFallbackFonts.cpp
+ Font/SystemFontMatcher.cpp
Font/Typeface.cpp
Font/TypefaceSkia.cpp
Font/WOFF/Loader.cpp
@@ -73,7 +74,9 @@ if (HAS_VULKAN)
endif()
if (HAS_FONTCONFIG)
- list(APPEND SOURCES Font/GlobalFontConfig.cpp)
+ list(APPEND SOURCES Font/GlobalFontConfig.cpp Font/SystemFontMatcherFontconfig.cpp)
+else()
+ list(APPEND SOURCES Font/SystemFontMatcherSkia.cpp)
endif()
compile_ipc(Point.ipc PointCodecs.h)
diff --git a/Libraries/LibGfx/Font/FontDatabase.cpp b/Libraries/LibGfx/Font/FontDatabase.cpp
index 0758cf73f24..6117455f471 100644
--- a/Libraries/LibGfx/Font/FontDatabase.cpp
+++ b/Libraries/LibGfx/Font/FontDatabase.cpp
@@ -10,7 +10,7 @@
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/SystemFallbackFonts.h>
-#include <LibGfx/Font/TypefaceSkia.h>
+#include <LibGfx/Font/SystemFontMatcher.h>
#if defined(AK_OS_HAIKU)
# include <FindDirectory.h>
@@ -42,15 +42,18 @@ RefPtr<Typeface> SystemFontProvider::get_typeface_by_id(u64, u64)
RefPtr<Gfx::Font> SystemFontProvider::get_font_for_code_point(u32 code_point, float point_size, u16 weight, u16 width, u8 slope, bool prefer_color_emoji)
{
- auto typeface_or_error = TypefaceSkia::find_typeface_for_code_point(code_point, weight, width, slope, prefer_color_emoji);
- if (typeface_or_error.is_error() || !typeface_or_error.value())
+ auto match = SystemFontMatcher::match_code_point(code_point, weight, width, slope, prefer_color_emoji);
+ if (!match.has_value())
return nullptr;
- return typeface_or_error.release_value()->font(point_size, {});
+ auto typeface = SystemFontMatcher::load(*match);
+ if (typeface.is_error())
+ return nullptr;
+ return typeface.value()->font(point_size, {});
}
Optional<FlyString> SystemFontProvider::resolve_generic_family(StringView family_name, u16 weight, u8 slope)
{
- return TypefaceSkia::resolve_generic_family(family_name, weight, slope);
+ return SystemFontMatcher::resolve_generic_family(family_name, weight, slope);
}
FontDatabase& FontDatabase::the()
diff --git a/Libraries/LibGfx/Font/GlobalFontConfig.cpp b/Libraries/LibGfx/Font/GlobalFontConfig.cpp
index cf2315ff7a0..5da1642c6d2 100644
--- a/Libraries/LibGfx/Font/GlobalFontConfig.cpp
+++ b/Libraries/LibGfx/Font/GlobalFontConfig.cpp
@@ -12,6 +12,15 @@
namespace Gfx {
+int fontconfig_slant(u8 slope)
+{
+ if (slope == 1)
+ return FC_SLANT_ITALIC;
+ if (slope == 2)
+ return FC_SLANT_OBLIQUE;
+ return FC_SLANT_ROMAN;
+}
+
GlobalFontConfig::GlobalFontConfig()
{
FcBool inited = FcInit();
@@ -34,12 +43,7 @@ FontHintingOptions GlobalFontConfig::hinting_for_font(FlyString const& family, f
FcPatternAddDouble(pattern, FC_PIXEL_SIZE, pixel_size);
FcPatternAddInteger(pattern, FC_WEIGHT, FcWeightFromOpenType(weight));
- int slant = FC_SLANT_ROMAN;
- if (slope == 1)
- slant = FC_SLANT_ITALIC;
- else if (slope == 2)
- slant = FC_SLANT_OBLIQUE;
- FcPatternAddInteger(pattern, FC_SLANT, slant);
+ FcPatternAddInteger(pattern, FC_SLANT, fontconfig_slant(slope));
FcConfigSubstitute(m_config, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
diff --git a/Libraries/LibGfx/Font/GlobalFontConfig.h b/Libraries/LibGfx/Font/GlobalFontConfig.h
index 5279ec466e4..34a4f9bf85a 100644
--- a/Libraries/LibGfx/Font/GlobalFontConfig.h
+++ b/Libraries/LibGfx/Font/GlobalFontConfig.h
@@ -30,6 +30,9 @@ struct FontHintingOptions {
bool force_autohinting { false };
};
+// The FC_SLANT value for a slope of 0 for upright, 1 for italic or 2 for oblique.
+int fontconfig_slant(u8 slope);
+
class GlobalFontConfig {
public:
static GlobalFontConfig& the();
diff --git a/Libraries/LibGfx/Font/SystemFontMatcher.cpp b/Libraries/LibGfx/Font/SystemFontMatcher.cpp
new file mode 100644
index 00000000000..f1326661f03
--- /dev/null
+++ b/Libraries/LibGfx/Font/SystemFontMatcher.cpp
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/ByteString.h>
+#include <AK/HashMap.h>
+#include <AK/Mutex.h>
+#include <AK/NeverDestroyed.h>
+#include <LibCore/MappedFile.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibGfx/Font/SystemFontMatcher.h>
+#include <LibGfx/Font/WOFF/Loader.h>
+
+namespace Gfx::SystemFontMatcher {
+
+namespace {
+
+struct FileFace {
+ ByteString path;
+ u32 ttc_index { 0 };
+
+ bool operator==(FileFace const&) const = default;
+};
+
+struct FileFaceTraits : public DefaultTraits<FileFace> {
+ static unsigned hash(FileFace const& face) { return pair_int_hash(face.path.hash(), face.ttc_index); }
+};
+
+struct SystemFontFileTraits : public DefaultTraits<SystemFontFile> {
+ static unsigned hash(SystemFontFile const& file) { return pair_int_hash(pair_int_hash(file.path.hash(), file.ttc_index), to_underlying(file.format)); }
+};
+
+// A fallback font covers many code points, and each code point that a page asks for matches the same face again. So
+// each face is checked and loaded only once.
+struct MatchCaches {
+ Mutex mutex;
+ HashMap<FileFace, Optional<SystemFontFile>, FileFaceTraits> loadable_files;
+ HashMap<SystemFontFile, NonnullRefPtr<Typeface>, SystemFontFileTraits> typefaces;
+};
+
+MatchCaches& match_caches()
+{
+ static NeverDestroyed<MatchCaches> caches;
+ return *caches;
+}
+
+}
+
+static FontFileFormat format_of(ReadonlyBytes bytes)
+{
+ // https://www.w3.org/TR/WOFF/#WOFFHeader
+ if (bytes.size() >= 4 && bytes[0] == 'w' && bytes[1] == 'O' && bytes[2] == 'F' && bytes[3] == 'F')
+ return FontFileFormat::WOFF;
+ return FontFileFormat::OpenType;
+}
+
+static ErrorOr<NonnullRefPtr<Typeface>> load_mapped_file(NonnullOwnPtr<Core::MappedFile> mapped_file, u32 ttc_index, FontFileFormat format)
+{
+ if (format == FontFileFormat::WOFF)
+ return WOFF::try_load_from_bytes(mapped_file->bytes(), ttc_index);
+ return Typeface::try_load_from_mapped_file(move(mapped_file), ttc_index);
+}
+
+static Optional<SystemFontFile> find_loadable_file(StringView path, u32 ttc_index)
+{
+ auto canonical_path = FileSystem::real_path(path);
+ if (canonical_path.is_error())
+ return {};
+ auto mapped_file = Core::MappedFile::map(canonical_path.value());
+ if (mapped_file.is_error())
+ return {};
+ auto format = format_of(mapped_file.value()->bytes());
+ if (load_mapped_file(mapped_file.release_value(), ttc_index, format).is_error())
+ return {};
+ auto string_path = String::from_byte_string(canonical_path.release_value());
+ if (string_path.is_error())
+ return {};
+ return SystemFontFile { .path = string_path.release_value(), .ttc_index = ttc_index, .format = format };
+}
+
+Optional<SystemFontFile> loadable_file(StringView path, u32 ttc_index)
+{
+ auto& caches = match_caches();
+ FileFace face { path, ttc_index };
+ {
+ MutexLocker locker { caches.mutex };
+ if (auto it = caches.loadable_files.find(face); it != caches.loadable_files.end())
+ return it->value;
+ }
+ auto file = find_loadable_file(path, ttc_index);
+ MutexLocker locker { caches.mutex };
+ caches.loadable_files.set(move(face), file);
+ return file;
+}
+
+ErrorOr<NonnullRefPtr<Typeface>> load(SystemFontMatch const& match)
+{
+ auto& caches = match_caches();
+ return match.visit(
+ [&](SystemFontFile const& file) -> ErrorOr<NonnullRefPtr<Typeface>> {
+ {
+ MutexLocker locker { caches.mutex };
+ if (auto it = caches.typefaces.find(file); it != caches.typefaces.end())
+ return it->value;
+ }
+ auto typeface = TRY(load_mapped_file(TRY(Core::MappedFile::map(file.path)), file.ttc_index, file.format));
+ if (file.format == FontFileFormat::OpenType)
+ typeface->set_file_path(file.path);
+ MutexLocker locker { caches.mutex };
+ return caches.typefaces.ensure(file, [&] { return move(typeface); });
+ },
+ [](NonnullRefPtr<Typeface> const& typeface) -> ErrorOr<NonnullRefPtr<Typeface>> {
+ return typeface;
+ });
+}
+
+}
diff --git a/Libraries/LibGfx/Font/SystemFontMatcher.h b/Libraries/LibGfx/Font/SystemFontMatcher.h
new file mode 100644
index 00000000000..50f7a6d57eb
--- /dev/null
+++ b/Libraries/LibGfx/Font/SystemFontMatcher.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/FlyString.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Variant.h>
+#include <LibGfx/Font/FontCatalog.h>
+#include <LibGfx/Font/Typeface.h>
+
+namespace Gfx {
+
+// A face of an installed font file.
+struct SystemFontFile {
+ String path;
+ u32 ttc_index { 0 };
+ FontFileFormat format { FontFileFormat::OpenType };
+
+ 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>>;
+
+// Matches installed fonts by the rules of the platform. Each face that a match gives is one that Typeface loads.
+namespace SystemFontMatcher {
+
+// The face for a family and a style, if the family is installed.
+Optional<SystemFontMatch> match_family_style(StringView family, u16 weight, u16 width, u8 slope);
+
+// The face for a code point that the fonts of a page do not have.
+Optional<SystemFontMatch> match_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji);
+
+// The installed family for a generic family, such as 'sans-serif'.
+Optional<FlyString> resolve_generic_family(StringView family, u16 weight, u8 slope);
+
+ErrorOr<NonnullRefPtr<Typeface>> load(SystemFontMatch const&);
+
+// The face of an installed font file at its canonical path, if Typeface loads it.
+Optional<SystemFontFile> loadable_file(StringView path, u32 ttc_index);
+
+}
+
+}
diff --git a/Libraries/LibGfx/Font/SystemFontMatcherFontconfig.cpp b/Libraries/LibGfx/Font/SystemFontMatcherFontconfig.cpp
new file mode 100644
index 00000000000..63f946f4524
--- /dev/null
+++ b/Libraries/LibGfx/Font/SystemFontMatcherFontconfig.cpp
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Array.h>
+#include <AK/ByteString.h>
+#include <AK/Mutex.h>
+#include <AK/NeverDestroyed.h>
+#include <AK/Vector.h>
+#include <LibGfx/Font/Font.h>
+#include <LibGfx/Font/GlobalFontConfig.h>
+#include <LibGfx/Font/SystemFontMatcher.h>
+
+#include <fontconfig/fontconfig.h>
+
+namespace Gfx::SystemFontMatcher {
+
+namespace {
+
+// Destroys a fontconfig object at the end of its scope.
+template<typename T, void (*destroy)(T*)>
+class Owned {
+ AK_MAKE_NONCOPYABLE(Owned);
+
+public:
+ explicit Owned(T* object)
+ : m_object(object)
+ {
+ }
+
+ Owned(Owned&& other)
+ : m_object(exchange(other.m_object, nullptr))
+ {
+ }
+
+ ~Owned()
+ {
+ if (m_object)
+ destroy(m_object);
+ }
+
+ T* get() const { return m_object; }
+
+private:
+ T* m_object { nullptr };
+};
+
+using OwnedPattern = Owned<FcPattern, FcPatternDestroy>;
+using OwnedCharSet = Owned<FcCharSet, FcCharSetDestroy>;
+using OwnedLangSet = Owned<FcLangSet, FcLangSetDestroy>;
+
+// The file and the face index of a matched font. The face is loaded after the lock is released.
+struct MatchedFile {
+ ByteString path;
+ u32 ttc_index { 0 };
+};
+
+}
+
+// The configuration is shared by all threads, so one match runs at a time.
+static Mutex& fontconfig_mutex()
+{
+ static NeverDestroyed<Mutex> mutex;
+ return *mutex;
+}
+
+static FcChar8 const* fontconfig_string(char const* string)
+{
+ return reinterpret_cast<FcChar8 const*>(string);
+}
+
+// Calls the callback with each string value of an object of a pattern.
+template<typename Callback>
+static void for_each_string(FcPattern* pattern, char const* object, Callback callback)
+{
+ FcChar8* value = nullptr;
+ for (int id = 0; FcPatternGetString(pattern, object, id, &value) == FcResultMatch; ++id)
+ callback(value, id);
+}
+
+static void add_style(FcPattern* pattern, u16 weight, u16 width, u8 slope)
+{
+ // https://learn.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass
+ // Fontconfig gives a width in percent of the normal width, as the width classes of the OS/2 table do.
+ static constexpr Array<int, 9> widths {
+ FC_WIDTH_ULTRACONDENSED,
+ FC_WIDTH_EXTRACONDENSED,
+ FC_WIDTH_CONDENSED,
+ FC_WIDTH_SEMICONDENSED,
+ FC_WIDTH_NORMAL,
+ FC_WIDTH_SEMIEXPANDED,
+ FC_WIDTH_EXPANDED,
+ FC_WIDTH_EXTRAEXPANDED,
+ FC_WIDTH_ULTRAEXPANDED,
+ };
+ FcPatternAddInteger(pattern, FC_WEIGHT, FcWeightFromOpenType(clamp<int>(weight, 1, 1000)));
+ FcPatternAddInteger(pattern, FC_WIDTH, widths[clamp<u16>(width, FontWidth::UltraCondensed, FontWidth::UltraExpanded) - 1]);
+ FcPatternAddInteger(pattern, FC_SLANT, fontconfig_slant(slope));
+}
+
+// A family name that no font has. Put after the requested family, it splits the families of a pattern after
+// substitution: the configuration puts the families that it substitutes for the requested family, such as the fonts
+// that an alias stands for, before it, and the families that it adds to every pattern as defaults after it.
+static constexpr char const* end_of_substitutes = "ladybird-end-of-family-substitutes";
+
+static Optional<MatchedFile> matched_file(FcPattern* font)
+{
+ FcChar8* path = nullptr;
+ if (FcPatternGetString(font, FC_FILE, 0, &path) != FcResultMatch)
+ return {};
+ // The upper 16 bits of the index select a named instance of a variable face.
+ int index = 0;
+ FcPatternGetInteger(font, FC_INDEX, 0, &index);
+ return MatchedFile { reinterpret_cast<char const*>(path), static_cast<u32>(index) };
+}
+
+// The font for a family and a style, if it has the family or one that the configuration substitutes for it.
+static OwnedPattern match_font_for_family(StringView family, u16 weight, u16 width, u8 slope)
+{
+ auto* config = GlobalFontConfig::the().get();
+
+ OwnedPattern pattern { FcPatternCreate() };
+ auto family_name = family.to_byte_string();
+ FcPatternAddString(pattern.get(), FC_FAMILY, fontconfig_string(family_name.characters()));
+ FcPatternAddString(pattern.get(), FC_FAMILY, fontconfig_string(end_of_substitutes));
+ add_style(pattern.get(), weight, width, slope);
+ FcConfigSubstitute(config, pattern.get(), FcMatchPattern);
+
+ // A rule can replace the requested family itself, so it is accepted whatever the configuration does with it.
+ Vector<ByteString> accepted_families { family_name };
+ Optional<int> end_id;
+ for_each_string(pattern.get(), FC_FAMILY, [&](FcChar8 const* name, int id) {
+ if (end_id.has_value())
+ return;
+ if (FcStrCmp(name, fontconfig_string(end_of_substitutes)) == 0)
+ end_id = id;
+ else
+ accepted_families.append(reinterpret_cast<char const*>(name));
+ });
+ if (end_id.has_value())
+ FcPatternRemove(pattern.get(), FC_FAMILY, *end_id);
+
+ FcDefaultSubstitute(pattern.get());
+ FcResult result;
+ OwnedPattern font { FcFontMatch(config, pattern.get(), &result) };
+ if (!font.get())
+ return font;
+
+ bool has_accepted_family = false;
+ for_each_string(font.get(), FC_FAMILY, [&](FcChar8 const* name, int) {
+ for (auto const& accepted_family : accepted_families) {
+ if (FcStrCmpIgnoreCase(name, fontconfig_string(accepted_family.characters())) == 0)
+ has_accepted_family = true;
+ }
+ });
+ if (!has_accepted_family)
+ return OwnedPattern { nullptr };
+ return font;
+}
+
+// The font for a code point and a style, if it has the code point.
+static Optional<MatchedFile> match_file_for_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji)
+{
+ auto* config = GlobalFontConfig::the().get();
+
+ OwnedPattern pattern { FcPatternCreate() };
+ add_style(pattern.get(), weight, width, slope);
+ OwnedCharSet char_set { FcCharSetCreate() };
+ FcCharSetAddChar(char_set.get(), code_point);
+ FcPatternAddCharSet(pattern.get(), FC_CHARSET, char_set.get());
+
+ // https://www.unicode.org/reports/tr51/#Emoji_Script
+ // The script subtag Zsye asks for emoji presentation, which fontconfig gives to the color emoji fonts.
+ if (prefer_color_emoji) {
+ OwnedLangSet lang_set { FcLangSetCreate() };
+ FcLangSetAdd(lang_set.get(), fontconfig_string("und-zsye"));
+ FcPatternAddLangSet(pattern.get(), FC_LANG, lang_set.get());
+ }
+
+ FcConfigSubstitute(config, pattern.get(), FcMatchPattern);
+ FcDefaultSubstitute(pattern.get());
+ FcResult result;
+ OwnedPattern font { FcFontMatch(config, pattern.get(), &result) };
+ if (!font.get())
+ return {};
+
+ FcCharSet* font_char_set = nullptr;
+ if (FcPatternGetCharSet(font.get(), FC_CHARSET, 0, &font_char_set) != FcResultMatch || !FcCharSetHasChar(font_char_set, code_point))
+ return {};
+ return matched_file(font.get());
+}
+
+static Optional<SystemFontMatch> loadable_match(Optional<MatchedFile> const& file)
+{
+ if (!file.has_value())
+ return {};
+ auto loadable = loadable_file(file->path, file->ttc_index);
+ if (!loadable.has_value())
+ return {};
+ return SystemFontMatch { loadable.release_value() };
+}
+
+Optional<SystemFontMatch> match_family_style(StringView family, u16 weight, u16 width, u8 slope)
+{
+ Optional<MatchedFile> file;
+ {
+ MutexLocker locker(fontconfig_mutex());
+ if (auto font = match_font_for_family(family, weight, width, slope); font.get())
+ file = matched_file(font.get());
+ }
+ return loadable_match(file);
+}
+
+Optional<SystemFontMatch> match_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji)
+{
+ Optional<MatchedFile> file;
+ {
+ MutexLocker locker(fontconfig_mutex());
+ file = match_file_for_code_point(code_point, weight, width, slope, prefer_color_emoji);
+ }
+ return loadable_match(file);
+}
+
+Optional<FlyString> resolve_generic_family(StringView family, u16 weight, u8 slope)
+{
+ ByteString family_name;
+ {
+ MutexLocker locker(fontconfig_mutex());
+ auto font = match_font_for_family(family, weight, FontWidth::Normal, slope);
+ if (!font.get())
+ return {};
+ FcChar8* name = nullptr;
+ if (FcPatternGetString(font.get(), FC_FAMILY, 0, &name) != FcResultMatch)
+ return {};
+ family_name = reinterpret_cast<char const*>(name);
+ }
+ auto resolved_family = FlyString::from_utf8(family_name.view());
+ if (resolved_family.is_error())
+ return {};
+ return resolved_family.release_value();
+}
+
+}
diff --git a/Libraries/LibGfx/Font/SystemFontMatcherSkia.cpp b/Libraries/LibGfx/Font/SystemFontMatcherSkia.cpp
new file mode 100644
index 00000000000..212f545e6ef
--- /dev/null
+++ b/Libraries/LibGfx/Font/SystemFontMatcherSkia.cpp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGfx/Font/SystemFontMatcher.h>
+#include <LibGfx/Font/TypefaceSkia.h>
+
+namespace Gfx::SystemFontMatcher {
+
+static Optional<SystemFontMatch> match_of(ErrorOr<RefPtr<TypefaceSkia>> typeface)
+{
+ if (typeface.is_error() || !typeface.value())
+ return {};
+ return SystemFontMatch { NonnullRefPtr<Typeface> { typeface.release_value().release_nonnull() } };
+}
+
+Optional<SystemFontMatch> match_family_style(StringView family, u16 weight, u16 width, u8 slope)
+{
+ return match_of(TypefaceSkia::match_family_style(family, weight, width, slope));
+}
+
+Optional<SystemFontMatch> match_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji)
+{
+ return match_of(TypefaceSkia::find_typeface_for_code_point(code_point, weight, width, slope, prefer_color_emoji));
+}
+
+Optional<FlyString> resolve_generic_family(StringView family, u16 weight, u8 slope)
+{
+ return TypefaceSkia::resolve_generic_family(family, weight, slope);
+}
+
+}
diff --git a/Libraries/LibWebView/FontService.cpp b/Libraries/LibWebView/FontService.cpp
index fa5dfccf316..0fb5ebf32e7 100644
--- a/Libraries/LibWebView/FontService.cpp
+++ b/Libraries/LibWebView/FontService.cpp
@@ -34,6 +34,7 @@ FontService::FontService(Vector<String> additional_font_directories)
if (auto result = build_catalog(); result.is_error()) {
dbgln("Unable to discover system fonts: {}. Using an empty catalog.", result.error());
m_font_sources.clear();
+ m_face_id_by_source.clear();
m_local_font_names.clear();
if (auto fallback_result = build_empty_catalog(); fallback_result.is_error())
m_build_error = MUST(String::formatted("{}", fallback_result.error()));
@@ -117,11 +118,9 @@ ErrorOr<void> FontService::build_catalog()
callback_error = result.release_error();
return;
}
- m_font_sources.set(face_id, FontSource {
- .path = path,
- .ttc_index = ttc_index,
- .format = format,
- });
+ FontSource source { .path = path, .ttc_index = ttc_index, .format = format };
+ m_face_id_by_source.set(source, face_id);
+ m_font_sources.set(face_id, move(source));
};
Gfx::PathFontProvider::for_each_typeface_in_uri(uri, loaded_paths, move(collect_typeface));
if (callback_error.has_value())
@@ -239,16 +238,36 @@ Gfx::BrokeredFont FontService::open_font_without_lock(u64 generation, u64 face_i
return {};
}
-Gfx::BrokeredFont FontService::materialize_typeface(NonnullRefPtr<Gfx::TypefaceSkia> typeface, String cache_key)
+Gfx::BrokeredFont FontService::materialize(Gfx::SystemFontMatch match, String cache_key)
{
- if (auto face_id = m_dynamic_match_cache.get(cache_key); face_id.has_value())
- return open_font_without_lock(m_generation, *face_id);
+ return match.visit(
+ [&](Gfx::SystemFontFile& file) { return materialize_file(move(file), move(cache_key)); },
+ [&](NonnullRefPtr<Gfx::Typeface>& typeface) { return materialize_typeface(move(typeface), move(cache_key)); });
+}
+
+Gfx::BrokeredFont FontService::materialize_file(Gfx::SystemFontFile file, String cache_key)
+{
+ // Every code point that a fallback font covers matches it under a key of its own, but the face is one face for all
+ // of them. A face of the catalog keeps its catalog id.
+ FontSource source { .path = move(file.path), .ttc_index = file.ttc_index, .format = file.format };
+ auto face_id = m_face_id_by_source.ensure(source, [&] {
+ auto new_face_id = m_next_dynamic_face_id++;
+ m_font_sources.set(new_face_id, source);
+ 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);
// Every code point a fallback font covers matches it under a key of its own. The face is one
// face however many keys reach it: a copy of its data per key would copy a CJK font once for
// each character a page uses, and a renderer would load each copy as a typeface of its own.
- auto ttc_index = typeface->collection_index();
- auto face_key = MUST(String::formatted("face:{}", typeface->platform_typeface_id()));
+ auto ttc_index = typeface.collection_index();
+ auto face_key = MUST(String::formatted("face:{}", typeface.platform_typeface_id()));
if (auto cached_face_id = m_dynamic_match_cache.get(face_key); cached_face_id.has_value()) {
// Copy the id out first: adding a key may grow the cache and free the entry it points at.
auto face_id = *cached_face_id;
@@ -259,8 +278,8 @@ Gfx::BrokeredFont FontService::materialize_typeface(NonnullRefPtr<Gfx::TypefaceS
// 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 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()) {
- postscript_name = typeface->postscript_name();
+ if (Gfx::TypefaceSkia::try_load_from_temporary_memory(typeface.font_data(), ttc_index).is_error()) {
+ postscript_name = typeface.postscript_name();
if (!postscript_name.has_value())
return {};
}
@@ -269,7 +288,7 @@ Gfx::BrokeredFont FontService::materialize_typeface(NonnullRefPtr<Gfx::TypefaceS
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());
+ auto file = create_immutable_font_data(typeface.font_data());
if (file.is_error())
return {};
m_memory_font_sources.set(face_id, Gfx::BrokeredFontFile {
@@ -309,10 +328,10 @@ Gfx::BrokeredFont FontService::match_font(String const& family, u16 weight, u16
if (auto face_id = m_dynamic_match_cache.get(cache_key); face_id.has_value())
return open_font_without_lock(m_generation, *face_id);
- auto typeface = Gfx::TypefaceSkia::match_family_style(family.bytes_as_string_view(), weight, width, slope);
- if (typeface.is_error() || !typeface.value())
+ auto match = Gfx::SystemFontMatcher::match_family_style(family, weight, width, slope);
+ if (!match.has_value())
return {};
- return materialize_typeface(typeface.release_value().release_nonnull(), move(cache_key));
+ return materialize(match.release_value(), move(cache_key));
}
Gfx::BrokeredFont FontService::match_font_for_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji)
@@ -324,10 +343,10 @@ Gfx::BrokeredFont FontService::match_font_for_code_point(u32 code_point, u16 wei
if (auto face_id = m_dynamic_match_cache.get(cache_key); face_id.has_value())
return open_font_without_lock(m_generation, *face_id);
- auto typeface = Gfx::TypefaceSkia::find_typeface_for_code_point(code_point, weight, width, slope, prefer_color_emoji);
- if (typeface.is_error() || !typeface.value())
+ auto match = Gfx::SystemFontMatcher::match_code_point(code_point, weight, width, slope, prefer_color_emoji);
+ if (!match.has_value())
return {};
- return materialize_typeface(typeface.release_value().release_nonnull(), move(cache_key));
+ return materialize(match.release_value(), move(cache_key));
}
Optional<FlyString> FontService::resolve_generic_family(String const& family, u16 weight, u8 slope)
@@ -335,7 +354,7 @@ Optional<FlyString> FontService::resolve_generic_family(String const& family, u1
MutexLocker locker(m_mutex);
if (wait_until_ready().is_error())
return {};
- return Gfx::TypefaceSkia::resolve_generic_family(family.bytes_as_string_view(), weight, slope);
+ return Gfx::SystemFontMatcher::resolve_generic_family(family, weight, slope);
}
}
diff --git a/Libraries/LibWebView/FontService.h b/Libraries/LibWebView/FontService.h
index e6718fb8818..590576e0264 100644
--- a/Libraries/LibWebView/FontService.h
+++ b/Libraries/LibWebView/FontService.h
@@ -13,7 +13,7 @@
#include <AK/String.h>
#include <LibGfx/Font/FontCatalog.h>
#include <LibGfx/Font/SharedFontProvider.h>
-#include <LibGfx/Font/TypefaceSkia.h>
+#include <LibGfx/Font/SystemFontMatcher.h>
#include <LibThreading/Thread.h>
#include <LibWebView/Export.h>
@@ -53,6 +53,15 @@ private:
String path;
u32 ttc_index { 0 };
Gfx::FontFileFormat format { Gfx::FontFileFormat::OpenType };
+
+ bool operator==(FontSource const&) const = default;
+ };
+
+ struct FontSourceTraits : public DefaultTraits<FontSource> {
+ static unsigned hash(FontSource const& source)
+ {
+ return pair_int_hash(pair_int_hash(source.path.hash(), source.ttc_index), to_underlying(source.format));
+ }
};
using MemoryFontSource = Variant<Gfx::BrokeredFontFile, Gfx::PlatformFontName>;
@@ -61,7 +70,9 @@ private:
ErrorOr<void> build_empty_catalog();
ErrorOr<void> wait_until_ready();
ErrorOr<IPC::File> create_immutable_font_data(ReadonlyBytes);
- Gfx::BrokeredFont materialize_typeface(NonnullRefPtr<Gfx::TypefaceSkia>, String cache_key);
+ Gfx::BrokeredFont materialize(Gfx::SystemFontMatch, String cache_key);
+ Gfx::BrokeredFont materialize_file(Gfx::SystemFontFile, String cache_key);
+ Gfx::BrokeredFont materialize_typeface(NonnullRefPtr<Gfx::Typeface>, String cache_key);
Gfx::BrokeredFont open_font_without_lock(u64 generation, u64 face_id);
Vector<String> m_additional_font_directories;
@@ -73,6 +84,7 @@ private:
u64 m_generation { 1 };
u64 m_next_dynamic_face_id { 1ull << 63 };
HashMap<u64, FontSource> m_font_sources;
+ HashMap<FontSource, u64, FontSourceTraits> m_face_id_by_source;
HashMap<u64, MemoryFontSource> m_memory_font_sources;
HashMap<String, u64> m_dynamic_match_cache;
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index c7ec1b3aeeb..75bc0a349cd 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -56,7 +56,7 @@ foreach(source IN LISTS TEST_SOURCES)
list(APPEND test_libraries LibHTTP)
endif()
if (source STREQUAL "TestFontService.cpp")
- list(APPEND test_libraries LibIPC LibGfx)
+ list(APPEND test_libraries LibFileSystem LibIPC LibGfx)
endif()
if (source STREQUAL "TestRendererFontService.cpp")
list(APPEND test_libraries LibCompositing LibGfx LibIPC LibThreading)
diff --git a/Tests/LibWebView/TestFontService.cpp b/Tests/LibWebView/TestFontService.cpp
index 1816134fe79..20c4053c426 100644
--- a/Tests/LibWebView/TestFontService.cpp
+++ b/Tests/LibWebView/TestFontService.cpp
@@ -6,6 +6,8 @@
#include <AK/ByteBuffer.h>
#include <LibCore/MappedFile.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibGfx/Font/TypefaceSkia.h>
#include <LibTest/TestCase.h>
#include <LibWebView/FontService.h>
#include <sys/mman.h>
@@ -28,16 +30,58 @@ TEST_CASE(font_catalog_is_shared_read_only)
namespace WebView {
struct FontServiceTestAccess {
- static Gfx::BrokeredFont materialize(FontService& service, NonnullRefPtr<Gfx::TypefaceSkia> typeface, String key)
+ static Gfx::BrokeredFont materialize(FontService& service, Gfx::SystemFontMatch match, String key)
{
MutexLocker locker(service.m_mutex);
MUST(service.wait_until_ready());
- return service.materialize_typeface(move(typeface), move(key));
+ return service.materialize(move(match), move(key));
}
};
}
+static Gfx::SystemFontFile test_font_file(StringView name, u32 ttc_index = 0)
+{
+ auto path = MUST(FileSystem::real_path(ByteString::formatted("../LibGfx/test-inputs/fonts/{}", name)));
+ return { .path = MUST(String::from_byte_string(path)), .ttc_index = ttc_index };
+}
+
+TEST_CASE(dynamic_matches_of_one_face_share_its_id)
+{
+ auto service = WebView::FontService::create({});
+ auto first = WebView::FontServiceTestAccess::materialize(*service, test_font_file("text.ttf"sv), "first-match"_string);
+ auto repeated = WebView::FontServiceTestAccess::materialize(*service, test_font_file("text.ttf"sv), "second-match"_string);
+ auto other_file = WebView::FontServiceTestAccess::materialize(*service, test_font_file("mono-emoji.ttf"sv), "other-file"_string);
+ auto other_face = WebView::FontServiceTestAccess::materialize(*service, test_font_file("styles.ttc"sv, 1), "other-face"_string);
+ auto first_face = WebView::FontServiceTestAccess::materialize(*service, test_font_file("styles.ttc"sv, 0), "first-face"_string);
+ EXPECT_NE(first.face_id, 0u);
+ EXPECT_EQ(first.face_id, repeated.face_id);
+ EXPECT_NE(first.face_id, other_file.face_id);
+ EXPECT_NE(other_face.face_id, first_face.face_id);
+
+ // The renderer gets the file itself, not a copy of its data.
+ auto* font_file = first.source.get_pointer<Gfx::BrokeredFontFile>();
+ EXPECT(font_file);
+ auto mapped_file = MUST(Core::MappedFile::map_from_fd_and_close(font_file->file.take_fd(), "brokered font"sv));
+ auto original_file = MUST(Core::MappedFile::map("../LibGfx/test-inputs/fonts/text.ttf"sv));
+ EXPECT_EQ(mapped_file->bytes(), original_file->bytes());
+}
+
+TEST_CASE(dynamic_matches_of_a_catalog_face_use_its_catalog_id)
+{
+ auto directory = MUST(FileSystem::real_path("../LibGfx/test-inputs/fonts"sv));
+ auto service = WebView::FontService::create({ MUST(String::from_byte_string(directory)) });
+
+ auto file = MUST(Core::MappedFile::map("../LibGfx/test-inputs/fonts/text.ttf"sv));
+ auto postscript_name = MUST(Gfx::Typeface::try_load_from_temporary_memory(file->bytes()))->postscript_name();
+ EXPECT(postscript_name.has_value());
+ auto catalog_face = service->match_local_font(*postscript_name);
+ EXPECT_NE(catalog_face.face_id, 0u);
+
+ auto match = WebView::FontServiceTestAccess::materialize(*service, test_font_file("text.ttf"sv), "catalog-face"_string);
+ EXPECT_EQ(match.face_id, catalog_face.face_id);
+}
+
TEST_CASE(dynamic_matches_reuse_platform_faces_without_merging_equal_metadata)
{
auto file = MUST(Core::MappedFile::map("../LibGfx/test-inputs/fonts/text.ttf"sv));
@@ -72,9 +116,9 @@ TEST_CASE(dynamic_matches_reuse_platform_faces_without_merging_equal_metadata)
EXPECT_EQ(first_face->font_data().size(), second_face->font_data().size());
auto service = WebView::FontService::create({});
- auto first = WebView::FontServiceTestAccess::materialize(*service, first_face, "first-match"_string);
- auto repeated = WebView::FontServiceTestAccess::materialize(*service, first_face, "second-match"_string);
- auto distinct = WebView::FontServiceTestAccess::materialize(*service, second_face, "distinct-face"_string);
+ auto first = WebView::FontServiceTestAccess::materialize(*service, NonnullRefPtr<Gfx::Typeface> { first_face }, "first-match"_string);
+ auto repeated = WebView::FontServiceTestAccess::materialize(*service, NonnullRefPtr<Gfx::Typeface> { first_face }, "second-match"_string);
+ auto distinct = WebView::FontServiceTestAccess::materialize(*service, NonnullRefPtr<Gfx::Typeface> { second_face }, "distinct-face"_string);
EXPECT_NE(first.face_id, 0u);
EXPECT_NE(repeated.face_id, 0u);
EXPECT_NE(distinct.face_id, 0u);