LibWeb: Remove Gfx::BitmapFont

This class supported the binary bitmap font file format in SerenityOS,
and isn't something we need in Ladybird.
This commit is contained in:
Andreas Kling 2024-06-03 17:14:05 +02:00
parent 30a92911fa
commit 04a6e2f83d
Notes: sideshowbarker 2024-07-17 04:34:25 +09:00
16 changed files with 24 additions and 914 deletions

View file

@ -70,7 +70,7 @@ void FontPlugin::update_generic_fonts()
RefPtr<Gfx::Font const> gfx_font;
for (auto& fallback : fallbacks) {
gfx_font = Gfx::FontDatabase::the().get(fallback, 16, 400, Gfx::FontWidth::Normal, 0, Gfx::Font::AllowInexactSizeMatch::Yes);
gfx_font = Gfx::FontDatabase::the().get(fallback, 16, 400, Gfx::FontWidth::Normal, 0);
if (gfx_font)
break;
}

View file

@ -35,7 +35,6 @@ shared_library("LibGfx") {
"Filters/FastBoxBlurFilter.cpp",
"Filters/LumaFilter.cpp",
"Filters/StackBlurFilter.cpp",
"Font/BitmapFont.cpp",
"Font/Emoji.cpp",
"Font/Font.cpp",
"Font/FontDatabase.cpp",

View file

@ -3,7 +3,6 @@ set(TEST_SOURCES
BenchmarkJPEGLoader.cpp
TestColor.cpp
TestDeltaE.cpp
TestFontHandling.cpp
TestGfxBitmap.cpp
TestICCProfile.cpp
TestImageDecoder.cpp

View file

@ -1,196 +0,0 @@
/*
* Copyright (c) 2020, the SerenityOS developers.
* Copyright (c) 2021, Brian Gianforcaro <bgianf@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Utf8View.h>
#include <LibCore/ResourceImplementationFile.h>
#include <LibGfx/Font/BitmapFont.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/OpenType/Glyf.h>
#include <LibTest/TestCase.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void init_font_database()
{
#ifdef AK_OS_SERENITY
auto const test_file_root = "/usr/Tests/LibGfx/test-inputs/"_string;
#else
auto const test_file_root = "test-inputs/"_string;
#endif
Core::ResourceImplementation::install(make<Core::ResourceImplementationFile>(test_file_root));
Gfx::FontDatabase::the().load_all_fonts_from_uri("resource:///"sv);
}
TEST_CASE(test_fontdatabase_get_by_name)
{
init_font_database();
auto& font_database = Gfx::FontDatabase::the();
auto name = "Family 12 400 0"sv;
EXPECT(!font_database.get_by_name(name)->name().is_empty());
}
TEST_CASE(test_fontdatabase_get)
{
init_font_database();
auto& font_database = Gfx::FontDatabase::the();
EXPECT(!font_database.get("Family"_fly_string, 12, 400, Gfx::FontWidth::Normal, 0)->name().is_empty());
}
TEST_CASE(test_fontdatabase_for_each_font)
{
init_font_database();
auto& font_database = Gfx::FontDatabase::the();
font_database.for_each_font([&](Gfx::Font const& font) {
EXPECT(!font.name().is_empty());
EXPECT(!font.qualified_name().is_empty());
EXPECT(!font.family().is_empty());
EXPECT(font.glyph_count() > 0);
});
}
TEST_CASE(test_clone)
{
u8 glyph_height = 1;
u8 glyph_width = 1;
auto font = MUST(Gfx::BitmapFont::create(glyph_height, glyph_width, true, 256));
auto new_font = font->clone();
EXPECT(!new_font->name().is_empty());
EXPECT(!new_font->qualified_name().is_empty());
EXPECT(!new_font->family().is_empty());
EXPECT(new_font->glyph_count() > 0);
}
TEST_CASE(test_set_name)
{
u8 glyph_height = 1;
u8 glyph_width = 1;
auto font = MUST(Gfx::BitmapFont::create(glyph_height, glyph_width, true, 256));
auto name = "my newly created font"_string;
font->set_name(name);
EXPECT(!font->name().is_empty());
EXPECT(font->name().contains(name));
}
TEST_CASE(test_set_family)
{
u8 glyph_height = 1;
u8 glyph_width = 1;
auto font = MUST(Gfx::BitmapFont::create(glyph_height, glyph_width, true, 256));
auto family = "my newly created font family"_string;
font->set_family(family);
EXPECT(!font->family().is_empty());
EXPECT(font->family().contains(family));
}
TEST_CASE(test_set_glyph_width)
{
u8 glyph_height = 1;
u8 glyph_width = 1;
auto font = MUST(Gfx::BitmapFont::create(glyph_height, glyph_width, true, 256));
size_t ch = 123;
font->set_glyph_width(ch, glyph_width);
EXPECT(font->glyph_width(ch) == glyph_width);
}
TEST_CASE(test_set_glyph_spacing)
{
u8 glyph_height = 1;
u8 glyph_width = 1;
auto font = MUST(Gfx::BitmapFont::create(glyph_height, glyph_width, true, 256));
u8 glyph_spacing = 8;
font->set_glyph_spacing(glyph_spacing);
EXPECT(font->glyph_spacing() == glyph_spacing);
}
TEST_CASE(test_width)
{
u8 glyph_height = 1;
u8 glyph_width = 1;
auto font = MUST(Gfx::BitmapFont::create(glyph_height, glyph_width, true, 256));
EXPECT(font->width("A"sv) == glyph_width);
}
TEST_CASE(test_glyph_or_emoji_width)
{
u8 glyph_height = 1;
u8 glyph_width = 1;
auto font = MUST(Gfx::BitmapFont::create(glyph_height, glyph_width, true, 256));
Utf8View view { " "sv };
auto it = view.begin();
EXPECT(font->glyph_or_emoji_width(it));
}
TEST_CASE(test_load_from_uri)
{
init_font_database();
auto font = Gfx::BitmapFont::load_from_uri("resource://TestFont.font"sv);
EXPECT(!font->name().is_empty());
}
TEST_CASE(test_write_to_file)
{
u8 glyph_height = 1;
u8 glyph_width = 1;
auto font = MUST(Gfx::BitmapFont::create(glyph_height, glyph_width, true, 256));
char path[] = "/tmp/new.font.XXXXXX";
EXPECT(mkstemp(path) != -1);
TRY_OR_FAIL(font->write_to_file(path));
unlink(path);
}
TEST_CASE(test_character_set_masking)
{
init_font_database();
auto font = TRY_OR_FAIL(Gfx::BitmapFont::try_load_from_uri("resource://TestFont.font"sv));
auto unmasked_font = TRY_OR_FAIL(font->unmasked_character_set());
EXPECT(unmasked_font->glyph_index(0x0041).value() == 0x0041);
EXPECT(unmasked_font->glyph_index(0x0100).value() == 0x0100);
EXPECT(unmasked_font->glyph_index(0xFFFD).value() == 0xFFFD);
auto masked_font = TRY_OR_FAIL(unmasked_font->masked_character_set());
EXPECT(masked_font->glyph_index(0x0041).value() == 0x0041);
EXPECT(!masked_font->glyph_index(0x0100).has_value());
EXPECT(masked_font->glyph_index(0xFFFD).value() == 0x1FD);
}
TEST_CASE(resolve_glyph_path_containing_single_off_curve_point)
{
Vector<u8> glyph_data {
0, 5, 0, 205, 255, 51, 7, 51, 6, 225, 0, 3, 0, 6, 0, 9, 0, 12, 0, 15, 0, 31, 64, 13, 13, 2, 15, 5, 7, 2, 8, 5, 10, 3, 0,
5, 3, 0, 47, 47, 51, 17, 51, 17, 51, 17, 51, 17, 51, 17, 51, 48, 49, 19, 33, 17, 33, 1, 33, 1, 1, 17, 1, 1, 33, 9, 3,
205, 6, 102, 249, 154, 5, 184, 250, 248, 2, 133, 2, 199, 253, 125, 253, 57, 5, 4, 253, 127, 253, 53, 2, 133, 253,
123, 6, 225, 248, 82, 7, 68, 252, 231, 252, 145, 6, 50, 252, 231, 252, 149, 3, 23, 253, 57, 3, 27, 3, 29, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 177, 2, 81, 43, 48, 49, 48, 0
};
OpenType::Glyf glyf(glyph_data.span());
auto glyph = glyf.glyph(118);
EXPECT(glyph.has_value());
EXPECT_NO_CRASH("resolving the path of glyph containing single off-curve point should not crash", [&] {
Gfx::Path path;
(void)glyph->append_path(path, 0, 0, 1, 1, [&](u16) -> Optional<OpenType::Glyf::Glyph> { VERIFY_NOT_REACHED(); });
return Test::Crash::Failure::DidNotCrash;
});
}

View file

@ -11,7 +11,6 @@ set(SOURCES
Filters/LumaFilter.cpp
Filters/StackBlurFilter.cpp
FontCascadeList.cpp
Font/BitmapFont.cpp
Font/Emoji.cpp
Font/Font.cpp
Font/FontDatabase.cpp

View file

@ -1,444 +0,0 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "BitmapFont.h"
#include "Emoji.h"
#include <AK/BuiltinWrappers.h>
#include <AK/Utf32View.h>
#include <AK/Utf8View.h>
#include <LibCore/File.h>
#include <LibCore/Resource.h>
#include <LibCore/System.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/FontStyleMapping.h>
#include <LibGfx/Painter.h>
#include <string.h>
namespace Gfx {
struct [[gnu::packed]] FontFileHeader {
char magic[4];
u8 glyph_width;
u8 glyph_height;
u16 range_mask_size;
u8 is_variable_width;
u8 glyph_spacing;
u8 baseline;
u8 mean_line;
u8 presentation_size;
u16 weight;
u8 slope;
char name[32];
char family[32];
};
static_assert(AssertSize<FontFileHeader, 80>());
static constexpr size_t s_max_glyph_count = 0x110000;
static constexpr size_t s_max_range_mask_size = s_max_glyph_count / (256 * 8);
}
template<>
class AK::Traits<Gfx::FontFileHeader> : public DefaultTraits<Gfx::FontFileHeader> {
public:
static constexpr bool is_trivially_serializable() { return true; }
};
namespace Gfx {
NonnullRefPtr<Font> BitmapFont::clone() const
{
return MUST(try_clone());
}
ErrorOr<NonnullRefPtr<Font>> BitmapFont::try_clone() const
{
auto new_range_mask = TRY(Core::System::allocate(m_range_mask.size(), 1));
m_range_mask.copy_to(new_range_mask);
size_t bytes_per_glyph = sizeof(u32) * glyph_height();
auto new_rows = TRY(Core::System::allocate(m_glyph_count, bytes_per_glyph));
m_rows.copy_to(new_rows);
auto new_widths = TRY(Core::System::allocate(m_glyph_count, 1));
m_glyph_widths.copy_to(new_widths);
return TRY(adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true)));
}
ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::create(u8 glyph_height, u8 glyph_width, bool fixed, size_t glyph_count)
{
glyph_count += 256 - (glyph_count % 256);
glyph_count = min(glyph_count, s_max_glyph_count);
size_t glyphs_per_range = 8 * 256;
u16 range_mask_size = ceil_div(glyph_count, glyphs_per_range);
auto new_range_mask = TRY(Core::System::allocate(range_mask_size, 1));
for (size_t i = 0; i < glyph_count; i += 256) {
new_range_mask[i / 256 / 8] |= 1 << (i / 256 % 8);
}
size_t bytes_per_glyph = sizeof(u32) * glyph_height;
auto new_rows = TRY(Core::System::allocate(glyph_count, bytes_per_glyph));
auto new_widths = TRY(Core::System::allocate(glyph_count, 1));
return adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont("Untitled"_string, "Untitled"_string, new_rows, new_widths, fixed, glyph_width, glyph_height, 1, new_range_mask, 0, 0, 0, 400, 0, true));
}
ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::unmasked_character_set() const
{
auto new_range_mask = TRY(Core::System::allocate(s_max_range_mask_size, 1));
constexpr u8 max_bits { 0b1111'1111 };
memset(new_range_mask.data(), max_bits, s_max_range_mask_size);
size_t bytes_per_glyph = sizeof(u32) * glyph_height();
auto new_rows = TRY(Core::System::allocate(s_max_glyph_count, bytes_per_glyph));
auto new_widths = TRY(Core::System::allocate(s_max_glyph_count, 1));
for (size_t code_point = 0; code_point < s_max_glyph_count; ++code_point) {
auto index = glyph_index(code_point);
if (index.has_value()) {
new_widths[code_point] = m_glyph_widths[index.value()];
memcpy(&new_rows[code_point * bytes_per_glyph], &m_rows[index.value() * bytes_per_glyph], bytes_per_glyph);
}
}
return adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true));
}
ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::masked_character_set() const
{
auto new_range_mask = TRY(Core::System::allocate(s_max_range_mask_size, 1));
u16 new_range_mask_size { 0 };
for (size_t i = 0; i < m_glyph_count; ++i) {
if (m_glyph_widths[i] > 0) {
new_range_mask[i / 256 / 8] |= 1 << (i / 256 % 8);
if (i / 256 / 8 + 1 > new_range_mask_size)
new_range_mask_size = i / 256 / 8 + 1;
}
}
size_t new_glyph_count { 0 };
for (size_t i = 0; i < new_range_mask_size; ++i) {
new_glyph_count += 256 * popcount(new_range_mask[i]);
}
size_t bytes_per_glyph = sizeof(u32) * m_glyph_height;
auto new_rows = TRY(Core::System::allocate(new_glyph_count, bytes_per_glyph));
auto new_widths = TRY(Core::System::allocate(new_glyph_count, 1));
for (size_t i = 0, j = 0; i < m_glyph_count; ++i) {
if (!(new_range_mask[i / 256 / 8] & 1 << (i / 256 % 8))) {
j++;
i += 255;
continue;
}
new_widths[i - j * 256] = m_glyph_widths[i];
memcpy(&new_rows[(i - j * 256) * bytes_per_glyph], &m_rows[i * bytes_per_glyph], bytes_per_glyph);
}
// Now that we're done working with the range-mask memory, reduce its reported size down to what it should be.
new_range_mask = { new_range_mask.data(), new_range_mask_size };
return adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true));
}
BitmapFont::BitmapFont(String name, String family, Bytes rows, Span<u8> widths, bool is_fixed_width, u8 glyph_width, u8 glyph_height, u8 glyph_spacing, Bytes range_mask, u8 baseline, u8 mean_line, u8 presentation_size, u16 weight, u8 slope, bool owns_arrays)
: m_name(move(name))
, m_family(move(family))
, m_range_mask(range_mask)
, m_rows(rows)
, m_glyph_widths(widths)
, m_glyph_width(glyph_width)
, m_glyph_height(glyph_height)
, m_min_glyph_width(glyph_width)
, m_max_glyph_width(glyph_width)
, m_glyph_spacing(glyph_spacing)
, m_baseline(baseline)
, m_mean_line(mean_line)
, m_presentation_size(presentation_size)
, m_weight(weight)
, m_slope(slope)
, m_fixed_width(is_fixed_width)
, m_owns_arrays(owns_arrays)
{
update_x_height();
for (size_t i = 0, index = 0; i < m_range_mask.size(); ++i) {
for (size_t j = 0; j < 8; ++j) {
if (m_range_mask[i] & (1 << j)) {
m_glyph_count += 256;
m_range_indices.append(index++);
} else {
m_range_indices.append({});
}
}
}
if (!m_fixed_width) {
u8 maximum = 0;
u8 minimum = 255;
for (size_t i = 0; i < m_glyph_count; ++i) {
minimum = min(minimum, m_glyph_widths[i]);
maximum = max(maximum, m_glyph_widths[i]);
}
m_min_glyph_width = minimum;
m_max_glyph_width = max(maximum, m_glyph_width);
}
}
BitmapFont::~BitmapFont()
{
if (m_owns_arrays) {
free(m_glyph_widths.data());
free(m_rows.data());
free(m_range_mask.data());
}
}
ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_stream(FixedMemoryStream& stream)
{
auto& header = *TRY(stream.read_in_place<FontFileHeader const>());
if (memcmp(header.magic, "!Fnt", 4))
return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Incompatible header");
if (header.name[sizeof(header.name) - 1] != '\0')
return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Nonnull-terminated name");
if (header.family[sizeof(header.family) - 1] != '\0')
return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Nonnull-terminated family");
size_t bytes_per_glyph = sizeof(u32) * header.glyph_height;
size_t glyph_count { 0 };
// FIXME: These ReadonlyFoo -> Foo casts are awkward, and only needed because BitmapFont is
// sometimes editable and sometimes not. Splitting it into editable/non-editable classes
// would make this a lot cleaner.
ReadonlyBytes readonly_range_mask = TRY(stream.read_in_place<u8 const>(header.range_mask_size));
Bytes range_mask { const_cast<u8*>(readonly_range_mask.data()), readonly_range_mask.size() };
for (size_t i = 0; i < header.range_mask_size; ++i)
glyph_count += 256 * popcount(range_mask[i]);
ReadonlyBytes readonly_rows = TRY(stream.read_in_place<u8 const>(glyph_count * bytes_per_glyph));
Bytes rows { const_cast<u8*>(readonly_rows.data()), readonly_rows.size() };
ReadonlySpan<u8> readonly_widths = TRY(stream.read_in_place<u8 const>(glyph_count));
Span<u8> widths { const_cast<u8*>(readonly_widths.data()), readonly_widths.size() };
if (!stream.is_eof())
return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Trailing data in file");
auto name = TRY(String::from_utf8(ReadonlyBytes { header.name, strlen(header.name) }));
auto family = TRY(String::from_utf8(ReadonlyBytes { header.family, strlen(header.family) }));
auto font = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(move(name), move(family), rows, widths, !header.is_variable_width, header.glyph_width, header.glyph_height, header.glyph_spacing, range_mask, header.baseline, header.mean_line, header.presentation_size, header.weight, header.slope)));
return font;
}
ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_resource(NonnullRefPtr<Core::Resource> resource)
{
auto stream = resource->stream();
auto font = TRY(try_load_from_stream(stream));
font->m_owned_data = move(resource);
return font;
}
ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_mapped_file(NonnullOwnPtr<Core::MappedFile> mapped_file)
{
auto font = TRY(try_load_from_stream(*mapped_file));
font->m_owned_data = move(mapped_file);
return font;
}
NonnullRefPtr<BitmapFont> BitmapFont::load_from_uri(StringView uri)
{
return MUST(try_load_from_uri(uri));
}
ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_uri(StringView uri)
{
return try_load_from_resource(TRY(Core::Resource::load_from_uri(uri)));
}
ErrorOr<void> BitmapFont::write_to_file(ByteString const& path)
{
auto stream = TRY(Core::File::open(path, Core::File::OpenMode::Write));
TRY(write_to_file(move(stream)));
return {};
}
ErrorOr<void> BitmapFont::write_to_file(NonnullOwnPtr<Core::File> file)
{
FontFileHeader header;
memset(&header, 0, sizeof(FontFileHeader));
memcpy(header.magic, "!Fnt", 4);
header.glyph_width = m_glyph_width;
header.glyph_height = m_glyph_height;
header.range_mask_size = m_range_mask.size();
header.baseline = m_baseline;
header.mean_line = m_mean_line;
header.is_variable_width = !m_fixed_width;
header.glyph_spacing = m_glyph_spacing;
header.presentation_size = m_presentation_size;
header.weight = m_weight;
header.slope = m_slope;
memcpy(header.name, m_name.bytes().data(), min(m_name.bytes().size(), sizeof(header.name) - 1));
memcpy(header.family, m_family.bytes().data(), min(m_family.bytes().size(), sizeof(header.family) - 1));
TRY(file->write_until_depleted({ &header, sizeof(header) }));
TRY(file->write_until_depleted(m_range_mask));
TRY(file->write_until_depleted(m_rows));
TRY(file->write_until_depleted(m_glyph_widths));
return {};
}
Glyph BitmapFont::glyph(u32 code_point) const
{
// Note: Until all fonts support the 0xFFFD replacement
// character, fall back to painting '?' if necessary.
auto index = glyph_index(code_point).value_or('?');
auto width = m_glyph_widths[index];
auto glyph_byte_count = m_glyph_height * GlyphBitmap::bytes_per_row();
return Glyph(
GlyphBitmap(m_rows.slice(index * glyph_byte_count, glyph_byte_count), { width, m_glyph_height }),
0,
width,
m_glyph_height);
}
Glyph BitmapFont::raw_glyph(u32 code_point) const
{
auto width = m_glyph_widths[code_point];
auto glyph_byte_count = m_glyph_height * GlyphBitmap::bytes_per_row();
return Glyph(
GlyphBitmap(m_rows.slice(code_point * glyph_byte_count, glyph_byte_count), { width, m_glyph_height }),
0,
width,
m_glyph_height);
}
Optional<size_t> BitmapFont::glyph_index(u32 code_point) const
{
auto index = code_point / 256;
if (index >= m_range_indices.size())
return {};
if (!m_range_indices[index].has_value())
return {};
return m_range_indices[index].value() * 256 + code_point % 256;
}
bool BitmapFont::contains_glyph(u32 code_point) const
{
auto index = glyph_index(code_point);
return index.has_value() && m_glyph_widths[index.value()] > 0;
}
float BitmapFont::glyph_width(u32 code_point) const
{
if (is_ascii(code_point) && !is_ascii_printable(code_point))
return 0;
auto index = glyph_index(code_point);
return m_fixed_width || !index.has_value() ? m_glyph_width : m_glyph_widths[index.value()];
}
template<typename CodePointIterator>
static float glyph_or_emoji_width_impl(BitmapFont const& font, CodePointIterator& it)
{
if (auto const* emoji = Emoji::emoji_for_code_point_iterator(it))
return font.pixel_size() * emoji->width() / emoji->height();
if (font.is_fixed_width())
return font.glyph_fixed_width();
return font.glyph_width(*it);
}
float BitmapFont::glyph_or_emoji_width(Utf8CodePointIterator& it) const
{
return glyph_or_emoji_width_impl(*this, it);
}
float BitmapFont::glyph_or_emoji_width(Utf32CodePointIterator& it) const
{
return glyph_or_emoji_width_impl(*this, it);
}
int BitmapFont::width_rounded_up(StringView view) const
{
return static_cast<int>(ceilf(width(view)));
}
float BitmapFont::width(StringView view) const { return unicode_view_width(Utf8View(view)); }
float BitmapFont::width(Utf8View const& view) const { return unicode_view_width(view); }
float BitmapFont::width(Utf32View const& view) const { return unicode_view_width(view); }
template<typename T>
ALWAYS_INLINE int BitmapFont::unicode_view_width(T const& view) const
{
if (view.is_empty())
return 0;
bool first = true;
int width = 0;
int longest_width = 0;
for (auto it = view.begin(); it != view.end(); ++it) {
auto code_point = *it;
if (code_point == '\n' || code_point == '\r') {
first = true;
longest_width = max(width, longest_width);
width = 0;
continue;
}
if (!first)
width += glyph_spacing();
first = false;
width += glyph_or_emoji_width(it);
}
longest_width = max(width, longest_width);
return longest_width;
}
String BitmapFont::qualified_name() const
{
return MUST(String::formatted("{} {} {} {}", family(), presentation_size(), weight(), slope()));
}
String BitmapFont::variant() const
{
StringBuilder builder;
builder.append(weight_to_name(weight()));
if (slope() != 0) {
if (builder.string_view() == "Regular"sv)
builder.clear();
else
builder.append(' ');
builder.append(slope_to_name(slope()));
}
return MUST(builder.to_string());
}
NonnullRefPtr<Font> BitmapFont::with_size(float point_size) const
{
auto scaled_font = Gfx::FontDatabase::the().get(family(), point_size, weight(), width(), slope(), AllowInexactSizeMatch::Yes);
VERIFY(scaled_font); // The inexact lookup should, at the very least, return `this` font.
return *scaled_font;
}
Font const& Font::bold_variant() const
{
if (m_bold_variant)
return *m_bold_variant;
m_bold_variant = Gfx::FontDatabase::the().get(family(), presentation_size(), 700, Gfx::FontWidth::Normal, 0);
if (!m_bold_variant)
m_bold_variant = this;
return *m_bold_variant;
}
FontPixelMetrics BitmapFont::pixel_metrics() const
{
return FontPixelMetrics {
.size = (float)pixel_size(),
.x_height = (float)x_height(),
.advance_of_ascii_zero = (float)glyph_width('0'),
.glyph_spacing = (float)glyph_spacing(),
.ascent = (float)m_baseline,
.descent = (float)(m_glyph_height - m_baseline),
.line_gap = Gfx::Painter::LINE_SPACING,
};
}
}

View file

@ -1,175 +0,0 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/ByteString.h>
#include <AK/CharacterTypes.h>
#include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <AK/Types.h>
#include <AK/Vector.h>
#include <LibCore/MappedFile.h>
#include <LibCore/Resource.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Size.h>
namespace Gfx {
class BitmapFont final : public Font {
public:
virtual NonnullRefPtr<Font> clone() const override;
virtual ErrorOr<NonnullRefPtr<Font>> try_clone() const override;
static ErrorOr<NonnullRefPtr<BitmapFont>> create(u8 glyph_height, u8 glyph_width, bool fixed, size_t glyph_count);
virtual FontPixelMetrics pixel_metrics() const override;
ErrorOr<NonnullRefPtr<BitmapFont>> masked_character_set() const;
ErrorOr<NonnullRefPtr<BitmapFont>> unmasked_character_set() const;
static NonnullRefPtr<BitmapFont> load_from_uri(StringView);
static ErrorOr<NonnullRefPtr<BitmapFont>> try_load_from_uri(StringView);
static ErrorOr<NonnullRefPtr<BitmapFont>> try_load_from_resource(NonnullRefPtr<Core::Resource>);
static ErrorOr<NonnullRefPtr<BitmapFont>> try_load_from_mapped_file(NonnullOwnPtr<Core::MappedFile>);
static ErrorOr<NonnullRefPtr<BitmapFont>> try_load_from_stream(FixedMemoryStream&);
ErrorOr<void> write_to_file(ByteString const& path);
ErrorOr<void> write_to_file(NonnullOwnPtr<Core::File> file);
~BitmapFont();
Bytes rows() { return m_rows; }
Span<u8> widths() { return m_glyph_widths; }
virtual float point_size() const override { return m_presentation_size; }
u8 presentation_size() const override { return m_presentation_size; }
void set_presentation_size(u8 size) { m_presentation_size = size; }
virtual float pixel_size() const override { return m_glyph_height; }
virtual int pixel_size_rounded_up() const override { return m_glyph_height; }
u16 width() const override { return FontWidth::Normal; }
u16 weight() const override { return m_weight; }
void set_weight(u16 weight) { m_weight = weight; }
virtual u8 slope() const override { return m_slope; }
void set_slope(u8 slope) { m_slope = slope; }
Glyph glyph(u32 code_point) const override;
Glyph glyph(u32 code_point, GlyphSubpixelOffset) const override { return glyph(code_point); }
float glyph_left_bearing(u32) const override { return 0; }
Glyph raw_glyph(u32 code_point) const;
bool contains_glyph(u32 code_point) const override;
bool contains_raw_glyph(u32 code_point) const { return m_glyph_widths[code_point] > 0; }
virtual float glyph_or_emoji_width(Utf8CodePointIterator&) const override;
virtual float glyph_or_emoji_width(Utf32CodePointIterator&) const override;
float glyphs_horizontal_kerning(u32, u32) const override { return 0.f; }
u8 glyph_height() const { return m_glyph_height; }
int x_height() const override { return m_x_height; }
virtual float preferred_line_height() const override { return glyph_height() + m_line_gap; }
virtual float glyph_width(u32 code_point) const override;
u8 raw_glyph_width(u32 code_point) const { return m_glyph_widths[code_point]; }
u8 min_glyph_width() const override { return m_min_glyph_width; }
u8 max_glyph_width() const override { return m_max_glyph_width; }
u8 glyph_fixed_width() const override { return m_glyph_width; }
u8 baseline() const override { return m_baseline; }
void set_baseline(u8 baseline)
{
m_baseline = baseline;
update_x_height();
}
u8 mean_line() const override { return m_mean_line; }
void set_mean_line(u8 mean_line)
{
m_mean_line = mean_line;
update_x_height();
}
virtual float width(StringView) const override;
virtual float width(Utf8View const&) const override;
virtual float width(Utf32View const&) const override;
virtual int width_rounded_up(StringView) const override;
virtual String name() const override { return m_name; }
void set_name(String name) { m_name = move(name); }
bool is_fixed_width() const override { return m_fixed_width; }
void set_fixed_width(bool b) { m_fixed_width = b; }
u8 glyph_spacing() const override { return m_glyph_spacing; }
void set_glyph_spacing(u8 spacing) { m_glyph_spacing = spacing; }
void set_glyph_width(u32 code_point, u8 width)
{
m_glyph_widths[code_point] = width;
}
size_t glyph_count() const override { return m_glyph_count; }
Optional<size_t> glyph_index(u32 code_point) const;
bool is_range_empty(u32 code_point) const { return !(m_range_mask[code_point / 256 / 8] & 1 << (code_point / 256 % 8)); }
virtual String family() const override { return m_family; }
void set_family(String family) { m_family = move(family); }
virtual String variant() const override;
virtual String qualified_name() const override;
virtual String human_readable_name() const override { return MUST(String::formatted("{} {} {}", family(), variant(), presentation_size())); }
virtual NonnullRefPtr<Font> with_size(float point_size) const override;
private:
BitmapFont(String name, String family, Bytes rows, Span<u8> widths, bool is_fixed_width,
u8 glyph_width, u8 glyph_height, u8 glyph_spacing, Bytes range_mask,
u8 baseline, u8 mean_line, u8 presentation_size, u16 weight, u8 slope, bool owns_arrays = false);
template<typename T>
int unicode_view_width(T const& view) const;
void update_x_height() { m_x_height = m_baseline - m_mean_line; }
virtual bool has_color_bitmaps() const override { return false; }
String m_name;
String m_family;
size_t m_glyph_count { 0 };
Bytes m_range_mask;
Vector<Optional<size_t>> m_range_indices;
Bytes m_rows;
Span<u8> m_glyph_widths;
Variant<Empty, NonnullOwnPtr<Core::MappedFile>, NonnullRefPtr<Core::Resource>> m_owned_data = Empty {};
u8 m_glyph_width { 0 };
u8 m_glyph_height { 0 };
u8 m_x_height { 0 };
u8 m_min_glyph_width { 0 };
u8 m_max_glyph_width { 0 };
u8 m_glyph_spacing { 0 };
u8 m_baseline { 0 };
u8 m_mean_line { 0 };
u8 m_presentation_size { 0 };
u16 m_weight { 0 };
u8 m_slope { 0 };
u8 m_line_gap { 4 };
bool m_fixed_width { false };
bool m_owns_arrays { false };
};
}

View file

@ -5,6 +5,7 @@
*/
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontDatabase.h>
namespace Gfx {
@ -26,4 +27,14 @@ GlyphRasterPosition GlyphRasterPosition::get_nearest_fit_for(FloatPoint position
return GlyphRasterPosition { { blit_x, blit_y }, { subpixel_x, subpixel_y } };
}
Font const& Font::bold_variant() const
{
if (m_bold_variant)
return *m_bold_variant;
m_bold_variant = Gfx::FontDatabase::the().get(family(), point_size(), 700, Gfx::FontWidth::Normal, 0);
if (!m_bold_variant)
m_bold_variant = this;
return *m_bold_variant;
}
}

View file

@ -145,13 +145,6 @@ enum FontWidth {
class Font : public RefCounted<Font> {
public:
enum class AllowInexactSizeMatch {
No,
Yes,
Larger,
Smaller,
};
virtual NonnullRefPtr<Font> clone() const = 0;
virtual ErrorOr<NonnullRefPtr<Font>> try_clone() const = 0;
virtual ~Font() {};

View file

@ -42,14 +42,7 @@ void FontDatabase::load_all_fonts_from_uri(StringView uri)
root->for_each_descendant_file([this](Core::Resource const& resource) -> IterationDecision {
auto uri = resource.uri();
auto path = LexicalPath(uri.bytes_as_string_view());
if (path.has_extension(".font"sv)) {
if (auto font_or_error = Gfx::BitmapFont::try_load_from_resource(resource); !font_or_error.is_error()) {
auto font = font_or_error.release_value();
m_private->full_name_to_font_map.set(font->qualified_name().to_byte_string(), *font);
auto typeface = get_or_create_typeface(font->family(), font->variant());
typeface->add_bitmap_font(font);
}
} else if (path.has_extension(".ttf"sv)) {
if (path.has_extension(".ttf"sv)) {
// FIXME: What about .otf
if (auto font_or_error = OpenType::Font::try_load_from_resource(resource); !font_or_error.is_error()) {
auto font = font_or_error.release_value();
@ -102,26 +95,26 @@ RefPtr<Gfx::Font> FontDatabase::get_by_name(StringView name)
return it->value;
}
RefPtr<Gfx::Font> FontDatabase::get(FlyString const& family, float point_size, unsigned weight, unsigned width, unsigned slope, Font::AllowInexactSizeMatch allow_inexact_size_match)
RefPtr<Gfx::Font> FontDatabase::get(FlyString const& family, float point_size, unsigned weight, unsigned width, unsigned slope)
{
auto it = m_private->typefaces.find(family);
if (it == m_private->typefaces.end())
return nullptr;
for (auto const& typeface : it->value) {
if (typeface->weight() == weight && typeface->width() == width && typeface->slope() == slope)
return typeface->get_font(point_size, allow_inexact_size_match);
return typeface->get_font(point_size);
}
return nullptr;
}
RefPtr<Gfx::Font> FontDatabase::get(FlyString const& family, FlyString const& variant, float point_size, Font::AllowInexactSizeMatch allow_inexact_size_match)
RefPtr<Gfx::Font> FontDatabase::get(FlyString const& family, FlyString const& variant, float point_size)
{
auto it = m_private->typefaces.find(family);
if (it == m_private->typefaces.end())
return nullptr;
for (auto const& typeface : it->value) {
if (typeface->variant() == variant)
return typeface->get_font(point_size, allow_inexact_size_match);
return typeface->get_font(point_size);
}
return nullptr;
}

View file

@ -21,8 +21,8 @@ class FontDatabase {
public:
static FontDatabase& the();
RefPtr<Gfx::Font> get(FlyString const& family, float point_size, unsigned weight, unsigned width, unsigned slope, Font::AllowInexactSizeMatch = Font::AllowInexactSizeMatch::No);
RefPtr<Gfx::Font> get(FlyString const& family, FlyString const& variant, float point_size, Font::AllowInexactSizeMatch = Font::AllowInexactSizeMatch::No);
RefPtr<Gfx::Font> get(FlyString const& family, float point_size, unsigned weight, unsigned width, unsigned slope);
RefPtr<Gfx::Font> get(FlyString const& family, FlyString const& variant, float point_size);
RefPtr<Gfx::Font> get_by_name(StringView);
void for_each_font(Function<void(Gfx::Font const&)>);

View file

@ -11,6 +11,7 @@
#include <AK/OwnPtr.h>
#include <AK/RefCounted.h>
#include <AK/StringView.h>
#include <LibCore/Resource.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/OpenType/Cmap.h>

View file

@ -11,94 +11,33 @@ namespace Gfx {
unsigned Typeface::weight() const
{
VERIFY(m_vector_font || m_bitmap_fonts.size() > 0);
if (is_fixed_size())
return m_bitmap_fonts[0]->weight();
return m_vector_font->weight();
}
unsigned Typeface::width() const
{
VERIFY(m_vector_font || m_bitmap_fonts.size() > 0);
if (is_fixed_size())
return Gfx::FontWidth::Normal;
return m_vector_font->width();
}
u8 Typeface::slope() const
{
VERIFY(m_vector_font || m_bitmap_fonts.size() > 0);
if (is_fixed_size())
return m_bitmap_fonts[0]->slope();
return m_vector_font->slope();
}
bool Typeface::is_fixed_width() const
{
VERIFY(m_vector_font || m_bitmap_fonts.size() > 0);
if (is_fixed_size())
return m_bitmap_fonts[0]->is_fixed_width();
return m_vector_font->is_fixed_width();
}
void Typeface::add_bitmap_font(RefPtr<BitmapFont> font)
{
m_bitmap_fonts.append(font);
}
void Typeface::set_vector_font(RefPtr<VectorFont> font)
{
m_vector_font = move(font);
}
RefPtr<Font> Typeface::get_font(float point_size, Font::AllowInexactSizeMatch allow_inexact_size_match) const
RefPtr<Font> Typeface::get_font(float point_size) const
{
VERIFY(point_size >= 0);
if (m_vector_font)
return m_vector_font->scaled_font(point_size);
RefPtr<BitmapFont> best_match;
int size = roundf(point_size);
int best_delta = NumericLimits<int>::max();
for (auto font : m_bitmap_fonts) {
if (font->presentation_size() == size)
return font;
if (allow_inexact_size_match != Font::AllowInexactSizeMatch::No) {
int delta = static_cast<int>(font->presentation_size()) - static_cast<int>(size);
if (abs(delta) == best_delta) {
if (allow_inexact_size_match == Font::AllowInexactSizeMatch::Larger && delta > 0) {
best_match = font;
} else if (allow_inexact_size_match == Font::AllowInexactSizeMatch::Smaller && delta < 0) {
best_match = font;
}
} else if (abs(delta) < best_delta) {
best_match = font;
best_delta = abs(delta);
}
}
}
if (allow_inexact_size_match != Font::AllowInexactSizeMatch::No && best_match)
return best_match;
return {};
}
void Typeface::for_each_fixed_size_font(Function<void(Font const&)> callback) const
{
for (auto font : m_bitmap_fonts) {
callback(*font);
}
return m_vector_font->scaled_font(point_size);
}
}

View file

@ -11,7 +11,6 @@
#include <AK/Function.h>
#include <AK/RefCounted.h>
#include <AK/Vector.h>
#include <LibGfx/Font/BitmapFont.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/VectorFont.h>
@ -32,19 +31,15 @@ public:
u8 slope() const;
bool is_fixed_width() const;
bool is_fixed_size() const { return !m_bitmap_fonts.is_empty(); }
void for_each_fixed_size_font(Function<void(Font const&)>) const;
void add_bitmap_font(RefPtr<BitmapFont>);
void set_vector_font(RefPtr<VectorFont>);
RefPtr<Font> get_font(float point_size, Font::AllowInexactSizeMatch = Font::AllowInexactSizeMatch::No) const;
RefPtr<Font> get_font(float point_size) const;
private:
FlyString m_family;
FlyString m_variant;
Vector<RefPtr<BitmapFont>> m_bitmap_fonts;
RefPtr<VectorFont> m_vector_font;
};

View file

@ -2086,7 +2086,7 @@ RefPtr<Gfx::FontCascadeList const> StyleComputer::compute_font_for_style_values(
return found_font;
}
if (auto found_font = Gfx::FontDatabase::the().get(family, font_size_in_pt, weight, width, slope, Gfx::Font::AllowInexactSizeMatch::Yes)) {
if (auto found_font = Gfx::FontDatabase::the().get(family, font_size_in_pt, weight, width, slope)) {
result->add(*found_font);
return result;
}

View file

@ -298,15 +298,11 @@ Gfx::Path CanvasRenderingContext2D::text_path(StringView text, float x, float y,
void CanvasRenderingContext2D::fill_text(StringView text, float x, float y, Optional<double> max_width)
{
if (is<Gfx::BitmapFont>(*current_font()))
return bitmap_font_fill_text(text, x, y, max_width);
fill_internal(text_path(text, x, y, max_width), Gfx::Painter::WindingRule::Nonzero);
}
void CanvasRenderingContext2D::stroke_text(StringView text, float x, float y, Optional<double> max_width)
{
if (is<Gfx::BitmapFont>(*current_font()))
return bitmap_font_fill_text(text, x, y, max_width);
stroke_internal(text_path(text, x, y, max_width));
}