Skip to content

Truly independent web browser

LibGfx+LibWebView: Match system fonts with DirectWrite directly

Aliaksandr Kalenik1eb133ea49d3
diff --git a/Libraries/LibGfx/CMakeLists.txt b/Libraries/LibGfx/CMakeLists.txt
index 5badc18e763..5b0b116652e 100644
--- a/Libraries/LibGfx/CMakeLists.txt
+++ b/Libraries/LibGfx/CMakeLists.txt
@@ -77,8 +77,10 @@ if (HAS_FONTCONFIG)
list(APPEND SOURCES Font/GlobalFontConfig.cpp Font/SystemFontMatcherFontconfig.cpp)
elseif (APPLE)
list(APPEND SOURCES Font/SystemFontMatcherCoreText.cpp)
+elseif (WIN32)
+ list(APPEND SOURCES Font/SystemFontMatcherDirectWrite.cpp)
else()
- list(APPEND SOURCES Font/SystemFontMatcherSkia.cpp)
+ list(APPEND SOURCES Font/SystemFontMatcherNone.cpp)
endif()
compile_ipc(Point.ipc PointCodecs.h)
@@ -122,6 +124,10 @@ if (HAS_DIRECTX)
target_link_libraries(LibGfx PRIVATE d3d12 dxgi d3dcompiler)
endif()
+if (WIN32)
+ target_link_libraries(LibGfx PRIVATE dwrite)
+endif()
+
if (HAS_VULKAN)
# Public LibGfx headers include <vulkan/vulkan.h>. Only LibGfx calls the Vulkan loader.
target_link_libraries(LibGfx PUBLIC Vulkan::Headers)
diff --git a/Libraries/LibGfx/Font/SystemFontMatcher.cpp b/Libraries/LibGfx/Font/SystemFontMatcher.cpp
index 38310478c50..dacd8cd3e3d 100644
--- a/Libraries/LibGfx/Font/SystemFontMatcher.cpp
+++ b/Libraries/LibGfx/Font/SystemFontMatcher.cpp
@@ -130,9 +130,6 @@ ErrorOr<NonnullRefPtr<Typeface>> load(SystemFontMatch const& match)
(void)name;
return Error::from_string_literal("Only CoreText opens fonts by name");
#endif
- },
- [](NonnullRefPtr<Typeface> const& typeface) -> ErrorOr<NonnullRefPtr<Typeface>> {
- return typeface;
});
}
diff --git a/Libraries/LibGfx/Font/SystemFontMatcher.h b/Libraries/LibGfx/Font/SystemFontMatcher.h
index edb75593e4b..8578bf9c7db 100644
--- a/Libraries/LibGfx/Font/SystemFontMatcher.h
+++ b/Libraries/LibGfx/Font/SystemFontMatcher.h
@@ -30,8 +30,7 @@ struct PlatformFontName {
String postscript_name;
};
-// A platform whose matcher does not give a file or a name gives the typeface itself.
-using SystemFontMatch = Variant<SystemFontFile, PlatformFontName, NonnullRefPtr<Typeface>>;
+using SystemFontMatch = Variant<SystemFontFile, PlatformFontName>;
// Matches installed fonts by the rules of the platform. Each face that a match gives is one that Typeface loads.
namespace SystemFontMatcher {
diff --git a/Libraries/LibGfx/Font/SystemFontMatcherDirectWrite.cpp b/Libraries/LibGfx/Font/SystemFontMatcherDirectWrite.cpp
new file mode 100644
index 00000000000..74cd3e4acc7
--- /dev/null
+++ b/Libraries/LibGfx/Font/SystemFontMatcherDirectWrite.cpp
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Vector.h>
+#include <AK/Windows.h>
+#include <LibGfx/Font/Font.h>
+#include <LibGfx/Font/SystemFontMatcher.h>
+
+#include <dwrite.h>
+#include <dwrite_2.h>
+// NB: WRL instead of WinRT, because WinRT reports errors with exceptions.
+#include <wrl/client.h>
+
+namespace Gfx::SystemFontMatcher {
+
+using Microsoft::WRL::ComPtr;
+
+namespace {
+
+struct DirectWrite {
+ ComPtr<IDWriteFactory2> factory;
+ ComPtr<IDWriteFontCollection> system_fonts;
+ ComPtr<IDWriteFontFallback> system_fallback;
+ // The locale of the user, which picks among the fonts of a script, ending with a null character.
+ Vector<wchar_t> user_locale;
+};
+
+// The text of one code point, which the font fallback of DirectWrite reads. It lives on the stack for one call, so it
+// does not count references.
+class CodePointText final : public IDWriteTextAnalysisSource {
+public:
+ CodePointText(u32 code_point, wchar_t const* locale)
+ : m_locale(locale)
+ {
+ if (code_point < 0x10000) {
+ m_code_units[0] = static_cast<wchar_t>(code_point);
+ m_length = 1;
+ } else {
+ m_code_units[0] = static_cast<wchar_t>(0xD800 + ((code_point - 0x10000) >> 10));
+ m_code_units[1] = static_cast<wchar_t>(0xDC00 + ((code_point - 0x10000) & 0x3FF));
+ m_length = 2;
+ }
+ }
+
+ UINT32 length() const { return m_length; }
+
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID interface_id, void** object) override
+ {
+ if (interface_id != __uuidof(IUnknown) && interface_id != __uuidof(IDWriteTextAnalysisSource)) {
+ *object = nullptr;
+ return E_NOINTERFACE;
+ }
+ *object = this;
+ return S_OK;
+ }
+
+ ULONG STDMETHODCALLTYPE AddRef() override { return 1; }
+ ULONG STDMETHODCALLTYPE Release() override { return 1; }
+
+ HRESULT STDMETHODCALLTYPE GetTextAtPosition(UINT32 position, WCHAR const** text, UINT32* length) override
+ {
+ *text = position < m_length ? m_code_units + position : nullptr;
+ *length = position < m_length ? m_length - position : 0;
+ return S_OK;
+ }
+
+ HRESULT STDMETHODCALLTYPE GetTextBeforePosition(UINT32 position, WCHAR const** text, UINT32* length) override
+ {
+ *text = position > 0 && position <= m_length ? m_code_units : nullptr;
+ *length = position > 0 && position <= m_length ? position : 0;
+ return S_OK;
+ }
+
+ DWRITE_READING_DIRECTION STDMETHODCALLTYPE GetParagraphReadingDirection() override
+ {
+ return DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
+ }
+
+ HRESULT STDMETHODCALLTYPE GetLocaleName(UINT32 position, UINT32* length, WCHAR const** locale) override
+ {
+ *length = position < m_length ? m_length - position : 0;
+ *locale = m_locale;
+ return S_OK;
+ }
+
+ HRESULT STDMETHODCALLTYPE GetNumberSubstitution(UINT32 position, UINT32* length, IDWriteNumberSubstitution** number_substitution) override
+ {
+ // The text has no digits to substitute.
+ *length = position < m_length ? m_length - position : 0;
+ *number_substitution = nullptr;
+ return S_OK;
+ }
+
+private:
+ wchar_t m_code_units[2] {};
+ UINT32 m_length { 0 };
+ wchar_t const* m_locale { nullptr };
+};
+
+}
+
+static DirectWrite const* direct_write()
+{
+ static DirectWrite const* const instance = []() -> DirectWrite const* {
+ auto* direct_write = new DirectWrite;
+ // IDWriteFactory2 and its system font fallback need Windows 8.1 or later.
+ if (FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory2), reinterpret_cast<IUnknown**>(direct_write->factory.GetAddressOf())))
+ || FAILED(direct_write->factory->GetSystemFontCollection(&direct_write->system_fonts, FALSE))
+ || FAILED(direct_write->factory->GetSystemFontFallback(&direct_write->system_fallback))) {
+ delete direct_write;
+ return nullptr;
+ }
+
+ wchar_t locale[LOCALE_NAME_MAX_LENGTH] {};
+ auto locale_length = GetUserDefaultLocaleName(locale, LOCALE_NAME_MAX_LENGTH);
+ for (int index = 0; index < locale_length && locale[index] != 0; ++index)
+ direct_write->user_locale.append(locale[index]);
+ direct_write->user_locale.append(0);
+ return direct_write;
+ }();
+ return instance;
+}
+
+static Vector<wchar_t> to_wide_string(StringView string)
+{
+ Vector<wchar_t> wide_string;
+ if (!string.is_empty()) {
+ auto length = MultiByteToWideChar(CP_UTF8, 0, string.characters_without_null_termination(), static_cast<int>(string.length()), nullptr, 0);
+ if (length > 0) {
+ wide_string.resize(length);
+ MultiByteToWideChar(CP_UTF8, 0, string.characters_without_null_termination(), static_cast<int>(string.length()), wide_string.data(), length);
+ }
+ }
+ wide_string.append(0);
+ return wide_string;
+}
+
+static Optional<String> from_wide_string(wchar_t const* wide_string, UINT32 length)
+{
+ if (length == 0)
+ return String {};
+ auto size = WideCharToMultiByte(CP_UTF8, 0, wide_string, static_cast<int>(length), nullptr, 0, nullptr, nullptr);
+ if (size <= 0)
+ return {};
+ Vector<char> buffer;
+ buffer.resize(size);
+ WideCharToMultiByte(CP_UTF8, 0, wide_string, static_cast<int>(length), buffer.data(), size, nullptr, nullptr);
+ auto string = String::from_utf8(StringView { buffer.data(), buffer.size() });
+ if (string.is_error())
+ return {};
+ return string.release_value();
+}
+
+// DirectWrite uses the CSS weights and the width classes of the OS/2 table.
+static DWRITE_FONT_WEIGHT direct_write_weight(u16 weight)
+{
+ return static_cast<DWRITE_FONT_WEIGHT>(clamp<u16>(weight, 1, 999));
+}
+
+static DWRITE_FONT_STRETCH direct_write_stretch(u16 width)
+{
+ return static_cast<DWRITE_FONT_STRETCH>(clamp<u16>(width, FontWidth::UltraCondensed, FontWidth::UltraExpanded));
+}
+
+static DWRITE_FONT_STYLE direct_write_style(u8 slope)
+{
+ if (slope == 1)
+ return DWRITE_FONT_STYLE_ITALIC;
+ if (slope == 2)
+ return DWRITE_FONT_STYLE_OBLIQUE;
+ return DWRITE_FONT_STYLE_NORMAL;
+}
+
+// The face of a font that DirectWrite gives, if it is in a local file that Typeface loads. DirectWrite gives a named
+// instance of a variable font as the face at its default coordinates.
+static Optional<SystemFontMatch> match_of(IDWriteFont* font)
+{
+ ComPtr<IDWriteFontFace> face;
+ if (FAILED(font->CreateFontFace(&face)))
+ return {};
+
+ // A face whose data is in several files cannot be loaded from one of them.
+ UINT32 file_count = 0;
+ if (FAILED(face->GetFiles(&file_count, nullptr)) || file_count != 1)
+ return {};
+ ComPtr<IDWriteFontFile> file;
+ if (FAILED(face->GetFiles(&file_count, file.GetAddressOf())))
+ return {};
+
+ void const* reference_key = nullptr;
+ UINT32 reference_key_size = 0;
+ ComPtr<IDWriteFontFileLoader> loader;
+ ComPtr<IDWriteLocalFontFileLoader> local_loader;
+ if (FAILED(file->GetReferenceKey(&reference_key, &reference_key_size)) || FAILED(file->GetLoader(&loader)) || FAILED(loader.As(&local_loader)))
+ return {};
+
+ UINT32 path_length = 0;
+ if (FAILED(local_loader->GetFilePathLengthFromKey(reference_key, reference_key_size, &path_length)))
+ return {};
+ Vector<wchar_t> path;
+ path.resize(path_length + 1);
+ if (FAILED(local_loader->GetFilePathFromKey(reference_key, reference_key_size, path.data(), path_length + 1)))
+ return {};
+ auto utf8_path = from_wide_string(path.data(), path_length);
+ if (!utf8_path.has_value())
+ return {};
+
+ auto loadable = loadable_file(*utf8_path, face->GetIndex());
+ if (!loadable.has_value())
+ return {};
+ return SystemFontMatch { loadable.release_value() };
+}
+
+static ComPtr<IDWriteFont> match_font_for_family(StringView family, u16 weight, u16 width, u8 slope)
+{
+ auto const* direct_write = SystemFontMatcher::direct_write();
+ if (!direct_write)
+ return {};
+
+ auto family_name = to_wide_string(family);
+ UINT32 family_index = 0;
+ BOOL exists = FALSE;
+ ComPtr<IDWriteFontFamily> font_family;
+ if (FAILED(direct_write->system_fonts->FindFamilyName(family_name.data(), &family_index, &exists)) || !exists
+ || FAILED(direct_write->system_fonts->GetFontFamily(family_index, &font_family)))
+ return {};
+
+ ComPtr<IDWriteFont> font;
+ if (FAILED(font_family->GetFirstMatchingFont(direct_write_weight(weight), direct_write_stretch(width), direct_write_style(slope), &font)))
+ return {};
+ return font;
+}
+
+Optional<SystemFontMatch> match_family_style(StringView family, u16 weight, u16 width, u8 slope)
+{
+ auto font = match_font_for_family(family, weight, width, slope);
+ if (!font)
+ return {};
+ return match_of(font.Get());
+}
+
+Optional<SystemFontMatch> match_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji)
+{
+ auto const* direct_write = SystemFontMatcher::direct_write();
+ if (!direct_write || code_point > 0x10FFFF)
+ return {};
+
+ // https://www.unicode.org/reports/tr51/#Emoji_Script
+ // The script subtag Zsye asks for emoji presentation, which DirectWrite gives with a color emoji font.
+ CodePointText text { code_point, prefer_color_emoji ? L"und-Zsye" : direct_write->user_locale.data() };
+ UINT32 mapped_length = 0;
+ ComPtr<IDWriteFont> font;
+ FLOAT scale = 1;
+ if (FAILED(direct_write->system_fallback->MapCharacters(&text, 0, text.length(), direct_write->system_fonts.Get(), nullptr, direct_write_weight(weight), direct_write_style(slope), direct_write_stretch(width), &mapped_length, &font, &scale)))
+ return {};
+ if (!font)
+ return {};
+ return match_of(font.Get());
+}
+
+Optional<FlyString> resolve_generic_family(StringView family, u16 weight, u8 slope)
+{
+ auto font = match_font_for_family(family, weight, FontWidth::Normal, slope);
+ if (!font)
+ return {};
+
+ ComPtr<IDWriteFontFamily> font_family;
+ ComPtr<IDWriteLocalizedStrings> family_names;
+ if (FAILED(font->GetFontFamily(&font_family)) || FAILED(font_family->GetFamilyNames(&family_names)))
+ return {};
+
+ // The US English name, or else the first name.
+ UINT32 name_index = 0;
+ BOOL exists = FALSE;
+ if (FAILED(family_names->FindLocaleName(L"en-us", &name_index, &exists)) || !exists)
+ name_index = 0;
+
+ UINT32 name_length = 0;
+ if (FAILED(family_names->GetStringLength(name_index, &name_length)))
+ return {};
+ Vector<wchar_t> name;
+ name.resize(name_length + 1);
+ if (FAILED(family_names->GetString(name_index, name.data(), name_length + 1)))
+ return {};
+ auto resolved_family = from_wide_string(name.data(), name_length);
+ if (!resolved_family.has_value())
+ return {};
+ return FlyString { resolved_family.release_value() };
+}
+
+}
diff --git a/Libraries/LibGfx/Font/SystemFontMatcherNone.cpp b/Libraries/LibGfx/Font/SystemFontMatcherNone.cpp
new file mode 100644
index 00000000000..b5c18e7036c
--- /dev/null
+++ b/Libraries/LibGfx/Font/SystemFontMatcherNone.cpp
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGfx/Font/SystemFontMatcher.h>
+
+// A platform without a font matcher matches no installed fonts.
+namespace Gfx::SystemFontMatcher {
+
+Optional<SystemFontMatch> match_family_style(StringView, u16, u16, u8)
+{
+ return {};
+}
+
+Optional<SystemFontMatch> match_code_point(u32, u16, u16, u8, bool)
+{
+ return {};
+}
+
+Optional<FlyString> resolve_generic_family(StringView, u16, u8)
+{
+ return {};
+}
+
+}
diff --git a/Libraries/LibGfx/Font/SystemFontMatcherSkia.cpp b/Libraries/LibGfx/Font/SystemFontMatcherSkia.cpp
deleted file mode 100644
index 212f545e6ef..00000000000
--- a/Libraries/LibGfx/Font/SystemFontMatcherSkia.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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/LibGfx/Font/Typeface.cpp b/Libraries/LibGfx/Font/Typeface.cpp
index 9d5eb4f8e1a..98ef4d945c6 100644
--- a/Libraries/LibGfx/Font/Typeface.cpp
+++ b/Libraries/LibGfx/Font/Typeface.cpp
@@ -402,16 +402,6 @@ ErrorOr<NonnullRefPtr<Gfx::Typeface const>> decode(Decoder& decoder)
typeface->set_file_path(move(file_path));
return typeface;
}
- case Gfx::Typeface::FontDataFormat::SystemFont: {
- auto family_name = TRY(decoder.decode<String>());
- auto weight = TRY(decoder.decode<u16>());
- auto width = TRY(decoder.decode<u16>());
- auto slope = TRY(decoder.decode<u8>());
- auto typeface = TRY(Gfx::TypefaceSkia::match_family_style(family_name.bytes_as_string_view(), weight, width, slope));
- if (!typeface)
- return Error::from_string_literal("Typeface IPC data referred to an unavailable system font");
- return typeface.release_nonnull();
- }
case Gfx::Typeface::FontDataFormat::SystemUIFont: {
auto style = TRY(decoder.decode<Gfx::SystemUIFontStyle>());
#ifdef AK_OS_MACOS
diff --git a/Libraries/LibGfx/Font/Typeface.h b/Libraries/LibGfx/Font/Typeface.h
index 9ac2219c381..ba09b53ad12 100644
--- a/Libraries/LibGfx/Font/Typeface.h
+++ b/Libraries/LibGfx/Font/Typeface.h
@@ -162,7 +162,6 @@ protected:
enum class FontDataFormat : u8 {
RawFontData,
MappedFile,
- SystemFont,
SystemUIFont,
SystemFontId,
PlatformFontName,
diff --git a/Libraries/LibGfx/Font/TypefaceSkia.cpp b/Libraries/LibGfx/Font/TypefaceSkia.cpp
index 9441d71a252..e0287da6463 100644
--- a/Libraries/LibGfx/Font/TypefaceSkia.cpp
+++ b/Libraries/LibGfx/Font/TypefaceSkia.cpp
@@ -47,104 +47,17 @@
namespace Gfx {
-static auto& skia_font_manager()
-{
- static NeverDestroyed<sk_sp<SkFontMgr>> font_manager;
- return *font_manager;
-}
-
struct TypefaceSkia::Impl {
AK_ALLOC_WITH_KMALLOC;
- Impl(sk_sp<SkTypeface> skia_typeface, std::unique_ptr<SkStreamAsset> stream = {})
+ explicit Impl(sk_sp<SkTypeface> skia_typeface)
: skia_typeface(move(skia_typeface))
- , stream(move(stream))
{
}
sk_sp<SkTypeface> skia_typeface;
- std::unique_ptr<SkStreamAsset> stream;
};
-static SkFontMgr& font_manager()
-{
- auto& font_manager = skia_font_manager();
- if (!font_manager) {
-#ifdef AK_OS_MACOS
- if (!Gfx::FontDatabase::the().force_freetype_rasterization()) {
- font_manager = SkFontMgr_New_CoreText(nullptr);
- }
-#endif
-#if defined(AK_OS_ANDROID)
- font_manager = SkFontMgr_New_Android(nullptr);
-#elif defined(AK_OS_WINDOWS)
- if (Gfx::FontDatabase::the().force_freetype_rasterization())
- font_manager = SkFontMgr_New_Custom_Empty();
- else
- font_manager = SkFontMgr_New_DirectWrite();
-#else
- if (!font_manager) {
- font_manager = SkFontMgr_New_FontConfig(nullptr, SkFontScanner_Make_FreeType());
- }
-#endif
- }
- VERIFY(font_manager);
- return *font_manager;
-}
-
-static std::unique_ptr<SkMemoryStream> copy_stream_to_memory_stream(SkStreamAsset& stream)
-{
- auto stream_copy = stream.duplicate();
- VERIFY(stream_copy);
-
- auto data = SkData::MakeFromStream(stream_copy.get(), stream_copy->getLength());
- VERIFY(data);
- VERIFY(data->size() == stream.getLength());
-
- return std::make_unique<SkMemoryStream>(move(data));
-}
-
-static SkFontStyle::Slant slope_to_skia_slant(u8 slope)
-{
- switch (slope) {
- case 1:
- return SkFontStyle::kItalic_Slant;
- case 2:
- return SkFontStyle::kOblique_Slant;
- default:
- return SkFontStyle::kUpright_Slant;
- }
-}
-
-ErrorOr<RefPtr<TypefaceSkia>> TypefaceSkia::typeface_from_skia_typeface(sk_sp<SkTypeface> skia_typeface)
-{
- if (!skia_typeface)
- return RefPtr<TypefaceSkia> {};
-
- int skia_ttc_index = 0;
- auto stream = skia_typeface->openStream(&skia_ttc_index);
- auto ttc_index = static_cast<u32>(skia_ttc_index);
-
- if (stream && stream->getMemoryBase()) {
- // NB: Safe to reference without copying because we hold on to the stream.
- ReadonlyBytes bytes { static_cast<u8 const*>(stream->getMemoryBase()), stream->getLength() };
- return adopt_ref(*new TypefaceSkia {
- make<TypefaceSkia::Impl>(skia_typeface, std::move(stream)),
- bytes,
- ttc_index });
- }
-
- if (!stream)
- return Error::from_string_literal("Failed to get font data from typeface");
-
- auto memory_stream = copy_stream_to_memory_stream(*stream);
- auto bytes = ReadonlyBytes { static_cast<u8 const*>(memory_stream->getMemoryBase()), memory_stream->getLength() };
- return adopt_ref(*new TypefaceSkia {
- make<TypefaceSkia::Impl>(skia_typeface, move(memory_stream)),
- bytes,
- ttc_index });
-}
-
// Text is shaped with HarfBuzz, so font data is of no use if HarfBuzz cannot read the face in it, even if Skia can
// draw it. FreeType also reads font formats such as WOFF, which have to be decoded first.
static bool harfbuzz_can_read_face(ReadonlyBytes buffer, u32 ttc_index)
@@ -331,71 +244,11 @@ ErrorOr<NonnullRefPtr<TypefaceSkia>> TypefaceSkia::load_from_buffer(AK::Readonly
return typeface;
}
-void TypefaceSkia::encode_font_data_for_ipc(IPC::Encoder& encoder) const
-{
- if (has_font_data_backing()) {
- Typeface::encode_font_data_for_ipc(encoder);
- return;
- }
-
- auto family_name = family().to_string();
-
- MUST(encoder.encode(FontDataFormat::SystemFont));
- MUST(encoder.encode(family_name));
- MUST(encoder.encode(weight()));
- MUST(encoder.encode(width()));
- MUST(encoder.encode(slope()));
-}
-
-ErrorOr<RefPtr<TypefaceSkia>> TypefaceSkia::match_family_style(StringView family_name, u16 weight, u16 width, u8 slope)
-{
- auto skia_typeface = font_manager().matchFamilyStyle(ByteString(family_name).characters(), SkFontStyle { weight, width, slope_to_skia_slant(slope) });
- return typeface_from_skia_typeface(move(skia_typeface));
-}
-
-ErrorOr<RefPtr<TypefaceSkia>> TypefaceSkia::find_typeface_for_code_point(u32 code_point, u16 weight, u16 width, u8 slope, bool prefer_color_emoji)
-{
- SkFontStyle style(weight, width, slope_to_skia_slant(slope));
-
- // The "und-Zsye" language tag steers the font matcher towards a color emoji font. Without it, a text-presentation
- // font is preferred for emoji-capable code points.
- char const* emoji_locale[] = { "und-Zsye" };
- auto skia_typeface = font_manager().matchFamilyStyleCharacter(
- nullptr, style, prefer_color_emoji ? emoji_locale : nullptr, prefer_color_emoji ? 1 : 0, code_point);
-
- if (!skia_typeface)
- return RefPtr<TypefaceSkia> {};
-
- return typeface_from_skia_typeface(move(skia_typeface));
-}
-
-Optional<FlyString> TypefaceSkia::resolve_generic_family(StringView family_name, u16 weight, u8 slope)
-{
- SkFontStyle style(weight, SkFontStyle::kNormal_Width, slope_to_skia_slant(slope));
- auto skia_typeface = font_manager().matchFamilyStyle(
- ByteString(family_name).characters(), style);
-
- if (!skia_typeface)
- return {};
-
- SkString resolved_family;
- skia_typeface->getFamilyName(&resolved_family);
- auto result_or_error = FlyString::from_utf8(StringView { resolved_family.c_str(), resolved_family.size() });
- if (result_or_error.is_error())
- return {};
- return result_or_error.release_value();
-}
-
SkTypeface const* TypefaceSkia::sk_typeface() const
{
return impl().skia_typeface.get();
}
-u32 TypefaceSkia::platform_typeface_id() const
-{
- return impl().skia_typeface->uniqueID();
-}
-
TypefaceSkia::TypefaceSkia(NonnullOwnPtr<Impl> impl, ReadonlyBytes buffer, u32 ttc_index)
: m_impl(move(impl))
, m_buffer(buffer)
diff --git a/Libraries/LibGfx/Font/TypefaceSkia.h b/Libraries/LibGfx/Font/TypefaceSkia.h
index 59819f45837..0d610b29d17 100644
--- a/Libraries/LibGfx/Font/TypefaceSkia.h
+++ b/Libraries/LibGfx/Font/TypefaceSkia.h
@@ -8,9 +8,6 @@
#include <LibGfx/Font/Typeface.h>
-template<typename T>
-class sk_sp;
-
namespace Gfx {
class TypefaceSkia : public Gfx::Typeface {
@@ -18,26 +15,17 @@ class TypefaceSkia : public Gfx::Typeface {
public:
static ErrorOr<NonnullRefPtr<TypefaceSkia>> load_from_buffer(ReadonlyBytes, u32 ttc_index, NonnullRefPtr<FontDataBacking>);
- static ErrorOr<RefPtr<TypefaceSkia>> match_family_style(StringView family_name, u16 weight, u16 width, u8 slope);
- 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);
virtual ReadonlyBytes buffer() const LIFETIME_BOUND override { return m_buffer; }
virtual u32 ttc_index() const override { return m_ttc_index; }
SkTypeface const* sk_typeface() const;
- u32 platform_typeface_id() const;
-
-protected:
- virtual void encode_font_data_for_ipc(IPC::Encoder&) const override;
private:
struct Impl;
Impl& impl() const { return *m_impl; }
NonnullOwnPtr<Impl> m_impl;
- static ErrorOr<RefPtr<TypefaceSkia>> typeface_from_skia_typeface(sk_sp<SkTypeface>);
-
TypefaceSkia(NonnullOwnPtr<Impl>, ReadonlyBytes, u32 ttc_index = 0);
virtual bool is_skia() const override { return true; }
diff --git a/Libraries/LibWebView/FontService.cpp b/Libraries/LibWebView/FontService.cpp
index 815fa9dee9e..6fed5c7ed32 100644
--- a/Libraries/LibWebView/FontService.cpp
+++ b/Libraries/LibWebView/FontService.cpp
@@ -11,7 +11,6 @@
#include <LibCore/System.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/PathFontProvider.h>
-#include <LibGfx/Font/TypefaceSkia.h>
#include <LibWebView/FontService.h>
#include <fcntl.h>
@@ -216,25 +215,8 @@ Gfx::BrokeredFont FontService::open_font_without_lock(u64 generation, u64 face_i
};
}
- if (auto source = m_memory_font_sources.get(face_id); source.has_value()) {
- return source->visit(
- [&](Gfx::BrokeredFontFile const& font_file) -> Gfx::BrokeredFont {
- auto file = IPC::File::clone_fd(font_file.file.fd());
- if (file.is_error())
- return {};
- return {
- .face_id = face_id,
- .source = Gfx::BrokeredFontFile {
- .ttc_index = font_file.ttc_index,
- .format = font_file.format,
- .file = file.release_value(),
- },
- };
- },
- [&](Gfx::PlatformFontName const& name) -> Gfx::BrokeredFont {
- return { .face_id = face_id, .source = name };
- });
- }
+ if (auto name = m_platform_font_names.get(face_id); name.has_value())
+ return { .face_id = face_id, .source = *name };
return {};
}
@@ -242,8 +224,7 @@ Gfx::BrokeredFont FontService::materialize(Gfx::SystemFontMatch match, String ca
{
return match.visit(
[&](Gfx::SystemFontFile& file) { return materialize_file(move(file), move(cache_key)); },
- [&](Gfx::PlatformFontName& name) { return materialize_platform_font(move(name), move(cache_key)); },
- [&](NonnullRefPtr<Gfx::Typeface>& typeface) { return materialize_typeface(move(typeface), move(cache_key)); });
+ [&](Gfx::PlatformFontName& name) { return materialize_platform_font(move(name), move(cache_key)); });
}
Gfx::BrokeredFont FontService::materialize_file(Gfx::SystemFontFile file, String cache_key)
@@ -264,57 +245,13 @@ Gfx::BrokeredFont FontService::materialize_platform_font(Gfx::PlatformFontName n
{
auto face_id = m_face_id_by_platform_font_name.ensure(name.postscript_name, [&] {
auto new_face_id = m_next_dynamic_face_id++;
- m_memory_font_sources.set(new_face_id, name);
+ m_platform_font_names.set(new_face_id, name);
return new_face_id;
});
m_dynamic_match_cache.set(move(cache_key), face_id);
return open_font_without_lock(m_generation, face_id);
}
-Gfx::BrokeredFont FontService::materialize_typeface(NonnullRefPtr<Gfx::Typeface> generic_typeface, String cache_key)
-{
- auto& typeface = as<Gfx::TypefaceSkia>(*generic_typeface);
-
- // 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()));
- 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;
- m_dynamic_match_cache.set(move(cache_key), face_id);
- return open_font_without_lock(m_generation, 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 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 (!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())
- return {};
- m_memory_font_sources.set(face_id, Gfx::BrokeredFontFile {
- .ttc_index = ttc_index,
- .format = Gfx::FontFileFormat::OpenType,
- .file = file.release_value(),
- });
- }
-
- m_dynamic_match_cache.set(move(face_key), face_id);
- m_dynamic_match_cache.set(move(cache_key), face_id);
- return open_font_without_lock(m_generation, face_id);
-}
-
Gfx::BrokeredFont FontService::match_local_font(String const& name)
{
MutexLocker locker(m_mutex);
diff --git a/Libraries/LibWebView/FontService.h b/Libraries/LibWebView/FontService.h
index 3f68ced2bee..656a837f957 100644
--- a/Libraries/LibWebView/FontService.h
+++ b/Libraries/LibWebView/FontService.h
@@ -64,8 +64,6 @@ private:
}
};
- using MemoryFontSource = Variant<Gfx::BrokeredFontFile, Gfx::PlatformFontName>;
-
ErrorOr<void> build_catalog();
ErrorOr<void> build_empty_catalog();
ErrorOr<void> wait_until_ready();
@@ -73,7 +71,6 @@ private:
Gfx::BrokeredFont materialize(Gfx::SystemFontMatch, String cache_key);
Gfx::BrokeredFont materialize_file(Gfx::SystemFontFile, String cache_key);
Gfx::BrokeredFont materialize_platform_font(Gfx::PlatformFontName, String cache_key);
- Gfx::BrokeredFont materialize_typeface(NonnullRefPtr<Gfx::Typeface>, String cache_key);
Gfx::BrokeredFont open_font_without_lock(u64 generation, u64 face_id);
Vector<String> m_additional_font_directories;
@@ -87,7 +84,7 @@ private:
HashMap<u64, FontSource> m_font_sources;
HashMap<FontSource, u64, FontSourceTraits> m_face_id_by_source;
HashMap<String, u64> m_face_id_by_platform_font_name;
- HashMap<u64, MemoryFontSource> m_memory_font_sources;
+ HashMap<u64, Gfx::PlatformFontName> m_platform_font_names;
HashMap<String, u64> m_dynamic_match_cache;
// Font requests arrive on the UI process's renderer connections and on the dedicated font connections of the
diff --git a/Tests/LibWebView/TestFontService.cpp b/Tests/LibWebView/TestFontService.cpp
index 9175d9971c8..95ccc61392b 100644
--- a/Tests/LibWebView/TestFontService.cpp
+++ b/Tests/LibWebView/TestFontService.cpp
@@ -4,10 +4,8 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#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>
@@ -89,47 +87,3 @@ TEST_CASE(dynamic_matches_of_a_catalog_face_use_its_catalog_id)
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));
- NonnullRefPtr<Gfx::TypefaceSkia> first_face = as<Gfx::TypefaceSkia>(*MUST(Gfx::Typeface::try_load_from_temporary_memory(file->bytes())));
- // Change a glyph advance without changing the family, style, collection index, or byte length.
- auto second_data = MUST(ByteBuffer::copy(file->bytes()));
- auto bytes = second_data.bytes();
- VERIFY(bytes.size() >= 12);
- size_t table_count = (static_cast<u16>(bytes[4]) << 8) | bytes[5];
- bool changed_metric = false;
- for (size_t index = 0; index < table_count; ++index) {
- size_t entry = 12 + 16 * index;
- VERIFY(entry + 16 <= bytes.size());
- if (bytes[entry] != 'h' || bytes[entry + 1] != 'm' || bytes[entry + 2] != 't' || bytes[entry + 3] != 'x')
- continue;
- u32 offset = (static_cast<u32>(bytes[entry + 8]) << 24)
- | (static_cast<u32>(bytes[entry + 9]) << 16)
- | (static_cast<u32>(bytes[entry + 10]) << 8) | bytes[entry + 11];
- VERIFY(static_cast<size_t>(offset) + 2 <= bytes.size());
- bytes[offset + 1] ^= 1;
- changed_metric = true;
- break;
- }
- VERIFY(changed_metric);
- NonnullRefPtr<Gfx::TypefaceSkia> second_face = as<Gfx::TypefaceSkia>(*MUST(Gfx::Typeface::try_load_from_temporary_memory(bytes)));
- EXPECT_NE(first_face->platform_typeface_id(), second_face->platform_typeface_id());
- EXPECT_EQ(first_face->family(), second_face->family());
- EXPECT_EQ(first_face->weight(), second_face->weight());
- EXPECT_EQ(first_face->width(), second_face->width());
- EXPECT_EQ(first_face->slope(), second_face->slope());
- EXPECT_EQ(first_face->collection_index(), second_face->collection_index());
- EXPECT_EQ(first_face->font_data().size(), second_face->font_data().size());
-
- auto service = WebView::FontService::create({});
- 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);
- EXPECT_EQ(first.face_id, repeated.face_id);
- EXPECT_NE(first.face_id, distinct.face_id);
-}