1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 08:57:47 +00:00

LibGfx: Move other font-related files to LibGfx/Font/

This commit is contained in:
Simon Wanner 2022-04-09 09:28:38 +02:00 committed by Andreas Kling
parent 6f8fd91f22
commit 206d6ece55
131 changed files with 177 additions and 176 deletions

View file

@ -0,0 +1,388 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@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/FileStream.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/FontStyleMapping.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);
NonnullRefPtr<Font> BitmapFont::clone() const
{
auto* new_range_mask = static_cast<u8*>(malloc(m_range_mask_size));
memcpy(new_range_mask, m_range_mask, m_range_mask_size);
size_t bytes_per_glyph = sizeof(u32) * glyph_height();
auto* new_rows = static_cast<u8*>(kmalloc_array(m_glyph_count, bytes_per_glyph));
memcpy(new_rows, m_rows, bytes_per_glyph * m_glyph_count);
auto* new_widths = static_cast<u8*>(malloc(m_glyph_count));
memcpy(new_widths, m_glyph_widths, m_glyph_count);
return adopt_ref(*new BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, m_range_mask_size, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true));
}
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 = static_cast<u8*>(calloc(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 = static_cast<u8*>(calloc(glyph_count, bytes_per_glyph));
auto* new_widths = static_cast<u8*>(calloc(glyph_count, 1));
return adopt_ref(*new BitmapFont("Untitled", "Untitled", new_rows, new_widths, fixed, glyph_width, glyph_height, 1, range_mask_size, new_range_mask, 0, 0, 0, 400, 0, true));
}
NonnullRefPtr<BitmapFont> BitmapFont::unmasked_character_set() const
{
auto* new_range_mask = static_cast<u8*>(malloc(s_max_range_mask_size));
constexpr u8 max_bits { 0b1111'1111 };
memset(new_range_mask, max_bits, s_max_range_mask_size);
size_t bytes_per_glyph = sizeof(u32) * glyph_height();
auto* new_rows = static_cast<u8*>(kmalloc_array(s_max_glyph_count, bytes_per_glyph));
auto* new_widths = static_cast<u8*>(calloc(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()) {
memcpy(&new_widths[code_point], &m_glyph_widths[index.value()], 1);
memcpy(&new_rows[code_point * bytes_per_glyph], &m_rows[index.value() * bytes_per_glyph], bytes_per_glyph);
}
}
return adopt_ref(*new BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, s_max_range_mask_size, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true));
}
NonnullRefPtr<BitmapFont> BitmapFont::masked_character_set() const
{
auto* new_range_mask = static_cast<u8*>(calloc(s_max_range_mask_size, 1));
u16 new_range_mask_size { 0 };
for (size_t i = 0; i < s_max_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 = static_cast<u8*>(calloc(new_glyph_count, bytes_per_glyph));
auto* new_widths = static_cast<u8*>(calloc(new_glyph_count, 1));
for (size_t i = 0, j = 0; i < s_max_glyph_count; ++i) {
if (!(new_range_mask[i / 256 / 8] & 1 << (i / 256 % 8))) {
j++;
i += 255;
continue;
}
memcpy(&new_widths[i - j * 256], &m_glyph_widths[i], 1);
memcpy(&new_rows[(i - j * 256) * bytes_per_glyph], &m_rows[i * bytes_per_glyph], bytes_per_glyph);
}
return adopt_ref(*new BitmapFont(m_name, m_family, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, new_range_mask_size, new_range_mask, m_baseline, m_mean_line, m_presentation_size, m_weight, m_slope, true));
}
BitmapFont::BitmapFont(String name, String family, u8* rows, u8* widths, bool is_fixed_width, u8 glyph_width, u8 glyph_height, u8 glyph_spacing, u16 range_mask_size, u8* 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_size(range_mask_size)
, 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)
{
VERIFY(m_range_mask);
VERIFY(m_rows);
VERIFY(m_glyph_widths);
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);
free(m_rows);
free(m_range_mask);
}
}
RefPtr<BitmapFont> BitmapFont::load_from_memory(u8 const* data)
{
auto const& header = *reinterpret_cast<FontFileHeader const*>(data);
if (memcmp(header.magic, "!Fnt", 4)) {
dbgln("header.magic != '!Fnt', instead it's '{:c}{:c}{:c}{:c}'", header.magic[0], header.magic[1], header.magic[2], header.magic[3]);
return nullptr;
}
if (header.name[sizeof(header.name) - 1] != '\0') {
dbgln("Font name not fully null-terminated");
return nullptr;
}
if (header.family[sizeof(header.family) - 1] != '\0') {
dbgln("Font family not fully null-terminated");
return nullptr;
}
size_t bytes_per_glyph = sizeof(u32) * header.glyph_height;
size_t glyph_count { 0 };
u8* range_mask = const_cast<u8*>(data + sizeof(FontFileHeader));
for (size_t i = 0; i < header.range_mask_size; ++i)
glyph_count += 256 * popcount(range_mask[i]);
u8* rows = range_mask + header.range_mask_size;
u8* widths = (u8*)(rows) + glyph_count * bytes_per_glyph;
return adopt_ref(*new BitmapFont(String(header.name), String(header.family), rows, widths, !header.is_variable_width, header.glyph_width, header.glyph_height, header.glyph_spacing, header.range_mask_size, range_mask, header.baseline, header.mean_line, header.presentation_size, header.weight, header.slope));
}
RefPtr<BitmapFont> BitmapFont::load_from_file(String const& path)
{
if (Core::File::is_device(path))
return nullptr;
auto file_or_error = Core::MappedFile::map(path);
if (file_or_error.is_error())
return nullptr;
auto font = load_from_memory((u8 const*)file_or_error.value()->data());
if (!font)
return nullptr;
font->m_mapped_file = file_or_error.release_value();
return font;
}
bool BitmapFont::write_to_file(String const& path)
{
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.characters(), min(m_name.length(), sizeof(header.name) - 1));
memcpy(header.family, m_family.characters(), min(m_family.length(), sizeof(header.family) - 1));
auto stream_result = Core::OutputFileStream::open_buffered(path);
if (stream_result.is_error())
return false;
auto& stream = stream_result.value();
size_t bytes_per_glyph = sizeof(u32) * m_glyph_height;
stream << ReadonlyBytes { &header, sizeof(header) };
stream << ReadonlyBytes { m_range_mask, m_range_mask_size };
stream << ReadonlyBytes { m_rows, m_glyph_count * bytes_per_glyph };
stream << ReadonlyBytes { m_glyph_widths, m_glyph_count };
stream.flush();
return !stream.handle_any_error();
}
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];
return Glyph(
GlyphBitmap(m_rows, index * m_glyph_height, { width, m_glyph_height }),
0,
width,
m_glyph_height);
}
Glyph BitmapFont::raw_glyph(u32 code_point) const
{
auto width = m_glyph_widths[code_point];
return Glyph(
GlyphBitmap(m_rows, code_point * m_glyph_height, { 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;
}
u8 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()];
}
int BitmapFont::glyph_or_emoji_width_for_variable_width_font(u32 code_point) const
{
// FIXME: This is a hack in lieu of proper code point identification.
// 0xFFFF is arbitrary but also the end of the Basic Multilingual Plane.
if (code_point < 0xFFFF) {
auto index = glyph_index(code_point);
if (!index.has_value())
return glyph_width(0xFFFD);
if (m_glyph_widths[index.value()] > 0)
return glyph_width(code_point);
return glyph_width(0xFFFD);
}
auto const* emoji = Emoji::emoji_for_code_point(code_point);
if (emoji == nullptr)
return glyph_width(0xFFFD);
return glyph_height() * emoji->width() / emoji->height();
}
int BitmapFont::width(StringView view) const { return unicode_view_width(Utf8View(view)); }
int BitmapFont::width(Utf8View const& view) const { return unicode_view_width(view); }
int 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 (u32 code_point : view) {
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(code_point);
}
longest_width = max(width, longest_width);
return longest_width;
}
String BitmapFont::qualified_name() const
{
return 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 builder.to_string();
}
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, 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 = (float)pixel_size() * 0.4f, // FIXME: Do something nicer here.
};
}
}

View file

@ -0,0 +1,162 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/CharacterTypes.h>
#include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <AK/String.h>
#include <AK/Types.h>
#include <AK/Vector.h>
#include <LibCore/MappedFile.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Size.h>
namespace Gfx {
class BitmapFont final : public Font {
public:
NonnullRefPtr<Font> clone() const override;
static NonnullRefPtr<BitmapFont> create(u8 glyph_height, u8 glyph_width, bool fixed, size_t glyph_count);
virtual FontPixelMetrics pixel_metrics() const override;
NonnullRefPtr<BitmapFont> masked_character_set() const;
NonnullRefPtr<BitmapFont> unmasked_character_set() const;
static RefPtr<BitmapFont> load_from_file(String const& path);
bool write_to_file(String const& path);
~BitmapFont();
u8* rows() { return m_rows; }
u8* widths() { return m_glyph_widths; }
u8 presentation_size() const override { return m_presentation_size; }
void set_presentation_size(u8 size) { m_presentation_size = size; }
virtual int pixel_size() const override { return m_glyph_height; }
virtual float point_size() const override { return static_cast<float>(m_glyph_height) * 0.75f; }
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 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; }
ALWAYS_INLINE int glyph_or_emoji_width(u32 code_point) const override
{
if (m_fixed_width)
return m_glyph_width;
return glyph_or_emoji_width_for_variable_width_font(code_point);
}
float glyphs_horizontal_kerning(u32, u32) const override { return 0.f; }
u8 glyph_height() const override { return m_glyph_height; }
int x_height() const override { return m_x_height; }
int preferred_line_height() const override { return glyph_height() + m_line_gap; }
u8 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();
}
int width(StringView) const override;
int width(Utf8View const&) const override;
int width(Utf32View const&) const override;
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)
{
VERIFY(m_glyph_widths);
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;
u16 range_size() const { return m_range_mask_size; }
bool is_range_empty(u32 code_point) const { return !(m_range_mask[code_point / 256 / 8] & 1 << (code_point / 256 % 8)); }
String family() const override { return m_family; }
void set_family(String family) { m_family = move(family); }
String variant() const override;
String qualified_name() const override;
String human_readable_name() const override { return String::formatted("{} {} {}", family(), variant(), presentation_size()); }
private:
BitmapFont(String name, String family, u8* rows, u8* widths, bool is_fixed_width,
u8 glyph_width, u8 glyph_height, u8 glyph_spacing, u16 range_mask_size, u8* range_mask,
u8 baseline, u8 mean_line, u8 presentation_size, u16 weight, u8 slope, bool owns_arrays = false);
static RefPtr<BitmapFont> load_from_memory(u8 const*);
template<typename T>
int unicode_view_width(T const& view) const;
void update_x_height() { m_x_height = m_baseline - m_mean_line; };
int glyph_or_emoji_width_for_variable_width_font(u32 code_point) const;
String m_name;
String m_family;
size_t m_glyph_count { 0 };
u16 m_range_mask_size { 0 };
u8* m_range_mask { nullptr };
Vector<Optional<size_t>> m_range_indices;
u8* m_rows { nullptr };
u8* m_glyph_widths { nullptr };
RefPtr<Core::MappedFile> m_mapped_file;
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

@ -0,0 +1,89 @@
/*
* Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
* Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/HashMap.h>
#include <AK/Span.h>
#include <AK/String.h>
#include <AK/Utf8View.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Font/Emoji.h>
namespace Gfx {
// https://unicode.org/reports/tr51/
// https://unicode.org/emoji/charts/emoji-list.html
// https://unicode.org/emoji/charts/emoji-zwj-sequences.html
static HashMap<Span<u32>, RefPtr<Gfx::Bitmap>> s_emojis;
Bitmap const* Emoji::emoji_for_code_point(u32 code_point)
{
return emoji_for_code_points(Array { code_point });
}
Bitmap const* Emoji::emoji_for_code_points(Span<u32> const& code_points)
{
auto it = s_emojis.find(code_points);
if (it != s_emojis.end())
return (*it).value.ptr();
auto basename = String::join('_', code_points, "U+{:X}");
auto bitmap_or_error = Bitmap::try_load_from_file(String::formatted("/res/emoji/{}.png", basename));
if (bitmap_or_error.is_error()) {
s_emojis.set(code_points, nullptr);
return nullptr;
}
auto bitmap = bitmap_or_error.release_value();
s_emojis.set(code_points, bitmap);
return bitmap.ptr();
}
Bitmap const* Emoji::emoji_for_code_point_iterator(Utf8CodePointIterator& it)
{
// NOTE: I'm sure this could be more efficient, e.g. by checking if each code point falls
// into a certain range in the loop below (emojis, modifiers, variation selectors, ZWJ),
// and bailing out early if not. Current worst case is 10 file lookups for any sequence of
// code points (if the first glyph isn't part of the font in regular text rendering).
constexpr size_t max_emoji_code_point_sequence_length = 10;
Vector<u32, max_emoji_code_point_sequence_length> code_points;
struct EmojiAndCodePoints {
Bitmap const* emoji;
Span<u32> code_points;
};
Vector<EmojiAndCodePoints, max_emoji_code_point_sequence_length> possible_emojis;
// Determine all existing emojis for the longest possible ZWJ emoji sequence,
// or until we run out of code points in the iterator.
for (size_t i = 0; i < max_emoji_code_point_sequence_length; ++i) {
auto code_point = it.peek(i);
if (!code_point.has_value())
break;
code_points.append(*code_point);
if (auto const* emoji = emoji_for_code_points(code_points))
possible_emojis.empend(emoji, code_points);
}
if (possible_emojis.is_empty())
return nullptr;
// If we found one or more matches, return the longest, i.e. last. For example:
// U+1F3F3 - white flag
// U+1F3F3 U+FE0F U+200D U+1F308 - rainbow flag
auto& [emoji, emoji_code_points] = possible_emojis.last();
// Advance the iterator, so it's on the last code point of our found emoji and
// whoever is iterating will advance to the next new code point.
for (size_t i = 0; i < emoji_code_points.size() - 1; ++i)
++it;
return emoji;
}
}

View file

@ -0,0 +1,24 @@
/*
* Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
* Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Forward.h>
#include <AK/Types.h>
namespace Gfx {
class Bitmap;
class Emoji {
public:
static Gfx::Bitmap const* emoji_for_code_point(u32 code_point);
static Gfx::Bitmap const* emoji_for_code_points(Span<u32> const&);
static Gfx::Bitmap const* emoji_for_code_point_iterator(Utf8CodePointIterator&);
};
}

View file

@ -0,0 +1,166 @@
/*
* Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Bitmap.h>
#include <AK/ByteReader.h>
#include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <AK/String.h>
#include <AK/Types.h>
#include <LibCore/MappedFile.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Size.h>
namespace Gfx {
// FIXME: Make a MutableGlyphBitmap buddy class for FontEditor instead?
class GlyphBitmap {
public:
GlyphBitmap() = default;
GlyphBitmap(u8 const* rows, size_t start_index, IntSize size)
: m_rows(rows)
, m_start_index(start_index)
, m_size(size)
{
}
unsigned row(unsigned index) const { return ByteReader::load32(bitmap(index).data()); }
bool bit_at(int x, int y) const { return bitmap(y).get(x); }
void set_bit_at(int x, int y, bool b) { bitmap(y).set(x, b); }
IntSize size() const { return m_size; }
int width() const { return m_size.width(); }
int height() const { return m_size.height(); }
static constexpr size_t bytes_per_row() { return sizeof(u32); }
static constexpr int max_width() { return bytes_per_row() * 8; }
static constexpr int max_height() { return max_width() + bytes_per_row(); }
private:
AK::Bitmap bitmap(size_t y) const
{
return { const_cast<u8*>(m_rows) + bytes_per_row() * (m_start_index + y), bytes_per_row() * 8 };
}
u8 const* m_rows { nullptr };
size_t m_start_index { 0 };
IntSize m_size { 0, 0 };
};
class Glyph {
public:
Glyph(GlyphBitmap const& glyph_bitmap, int left_bearing, int advance, int ascent)
: m_glyph_bitmap(glyph_bitmap)
, m_left_bearing(left_bearing)
, m_advance(advance)
, m_ascent(ascent)
{
}
Glyph(RefPtr<Bitmap> bitmap, int left_bearing, int advance, int ascent)
: m_bitmap(bitmap)
, m_left_bearing(left_bearing)
, m_advance(advance)
, m_ascent(ascent)
{
}
bool is_glyph_bitmap() const { return !m_bitmap; }
GlyphBitmap glyph_bitmap() const { return m_glyph_bitmap; }
RefPtr<Bitmap> bitmap() const { return m_bitmap; }
int left_bearing() const { return m_left_bearing; }
int advance() const { return m_advance; }
int ascent() const { return m_ascent; }
private:
GlyphBitmap m_glyph_bitmap;
RefPtr<Bitmap> m_bitmap;
int m_left_bearing;
int m_advance;
int m_ascent;
};
struct FontPixelMetrics {
float size { 0 };
float x_height { 0 };
float advance_of_ascii_zero { 0 };
float glyph_spacing { 0 };
// Number of pixels the font extends above the baseline.
float ascent { 0 };
// Number of pixels the font descends below the baseline.
float descent { 0 };
// Line gap specified by font.
float line_gap { 0 };
float line_spacing() const { return roundf(ascent) + roundf(descent) + roundf(line_gap); }
};
class Font : public RefCounted<Font> {
public:
enum class AllowInexactSizeMatch {
No,
Yes,
};
virtual NonnullRefPtr<Font> clone() const = 0;
virtual ~Font() {};
virtual FontPixelMetrics pixel_metrics() const = 0;
virtual u8 presentation_size() const = 0;
virtual int pixel_size() const = 0;
virtual float point_size() const = 0;
virtual u8 slope() const = 0;
virtual u16 weight() const = 0;
virtual Glyph glyph(u32 code_point) const = 0;
virtual bool contains_glyph(u32 code_point) const = 0;
virtual u8 glyph_width(u32 code_point) const = 0;
virtual int glyph_or_emoji_width(u32 code_point) const = 0;
virtual float glyphs_horizontal_kerning(u32 left_code_point, u32 right_code_point) const = 0;
virtual u8 glyph_height() const = 0;
virtual int x_height() const = 0;
virtual int preferred_line_height() const = 0;
virtual u8 min_glyph_width() const = 0;
virtual u8 max_glyph_width() const = 0;
virtual u8 glyph_fixed_width() const = 0;
virtual u8 baseline() const = 0;
virtual u8 mean_line() const = 0;
virtual int width(StringView) const = 0;
virtual int width(Utf8View const&) const = 0;
virtual int width(Utf32View const&) const = 0;
virtual String name() const = 0;
virtual bool is_fixed_width() const = 0;
virtual u8 glyph_spacing() const = 0;
virtual size_t glyph_count() const = 0;
virtual String family() const = 0;
virtual String variant() const = 0;
virtual String qualified_name() const = 0;
virtual String human_readable_name() const = 0;
Font const& bold_variant() const;
private:
mutable RefPtr<Gfx::Font> m_bold_variant;
};
}

View file

@ -0,0 +1,200 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/FlyString.h>
#include <AK/NonnullRefPtrVector.h>
#include <AK/QuickSort.h>
#include <LibCore/DirIterator.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibGfx/Font/TrueType/Font.h>
#include <LibGfx/Font/Typeface.h>
#include <stdlib.h>
namespace Gfx {
FontDatabase& FontDatabase::the()
{
static FontDatabase s_the;
return s_the;
}
static RefPtr<Font> s_default_font;
static String s_default_font_query;
static RefPtr<Font> s_fixed_width_font;
static String s_fixed_width_font_query;
static String s_default_fonts_lookup_path = "/res/fonts";
void FontDatabase::set_default_font_query(String query)
{
if (s_default_font_query == query)
return;
s_default_font_query = move(query);
s_default_font = nullptr;
}
String FontDatabase::default_font_query()
{
return s_default_font_query;
}
void FontDatabase::set_default_fonts_lookup_path(String path)
{
if (s_default_fonts_lookup_path == path)
return;
s_default_fonts_lookup_path = move(path);
}
String FontDatabase::default_fonts_lookup_path()
{
return s_default_fonts_lookup_path;
}
Font& FontDatabase::default_font()
{
if (!s_default_font) {
VERIFY(!s_default_font_query.is_empty());
s_default_font = FontDatabase::the().get_by_name(s_default_font_query);
VERIFY(s_default_font);
}
return *s_default_font;
}
void FontDatabase::set_fixed_width_font_query(String query)
{
if (s_fixed_width_font_query == query)
return;
s_fixed_width_font_query = move(query);
s_fixed_width_font = nullptr;
}
String FontDatabase::fixed_width_font_query()
{
return s_fixed_width_font_query;
}
Font& FontDatabase::default_fixed_width_font()
{
if (!s_fixed_width_font) {
VERIFY(!s_fixed_width_font_query.is_empty());
s_fixed_width_font = FontDatabase::the().get_by_name(s_fixed_width_font_query);
VERIFY(s_fixed_width_font);
}
return *s_fixed_width_font;
}
struct FontDatabase::Private {
HashMap<String, NonnullRefPtr<Gfx::Font>> full_name_to_font_map;
Vector<RefPtr<Typeface>> typefaces;
};
FontDatabase::FontDatabase()
: m_private(make<Private>())
{
Core::DirIterator dir_iterator(s_default_fonts_lookup_path, Core::DirIterator::SkipDots);
if (dir_iterator.has_error()) {
warnln("DirIterator: {}", dir_iterator.error_string());
exit(1);
}
while (dir_iterator.has_next()) {
auto path = dir_iterator.next_full_path();
if (path.ends_with(".font"sv)) {
if (auto font = Gfx::BitmapFont::load_from_file(path)) {
m_private->full_name_to_font_map.set(font->qualified_name(), *font);
auto typeface = get_or_create_typeface(font->family(), font->variant());
typeface->add_bitmap_font(font);
}
} else if (path.ends_with(".ttf"sv)) {
// FIXME: What about .otf and .woff
if (auto font_or_error = TTF::Font::try_load_from_file(path); !font_or_error.is_error()) {
auto font = font_or_error.release_value();
auto typeface = get_or_create_typeface(font->family(), font->variant());
typeface->set_ttf_font(move(font));
}
}
}
}
void FontDatabase::for_each_font(Function<void(Gfx::Font const&)> callback)
{
Vector<RefPtr<Gfx::Font>> fonts;
fonts.ensure_capacity(m_private->full_name_to_font_map.size());
for (auto& it : m_private->full_name_to_font_map)
fonts.append(it.value);
quick_sort(fonts, [](auto& a, auto& b) { return a->qualified_name() < b->qualified_name(); });
for (auto& font : fonts)
callback(*font);
}
void FontDatabase::for_each_fixed_width_font(Function<void(Gfx::Font const&)> callback)
{
Vector<RefPtr<Gfx::Font>> fonts;
fonts.ensure_capacity(m_private->full_name_to_font_map.size());
for (auto& it : m_private->full_name_to_font_map) {
if (it.value->is_fixed_width())
fonts.append(it.value);
}
quick_sort(fonts, [](auto& a, auto& b) { return a->qualified_name() < b->qualified_name(); });
for (auto& font : fonts)
callback(*font);
}
RefPtr<Gfx::Font> FontDatabase::get_by_name(StringView name)
{
auto it = m_private->full_name_to_font_map.find(name);
if (it == m_private->full_name_to_font_map.end()) {
auto parts = name.split_view(" "sv);
if (parts.size() >= 4) {
auto slope = parts.take_last().to_int().value_or(0);
auto weight = parts.take_last().to_int().value_or(0);
auto size = parts.take_last().to_int().value_or(0);
auto family = String::join(' ', parts);
return get(family, size, weight, slope);
}
dbgln("Font lookup failed: '{}'", name);
return nullptr;
}
return it->value;
}
RefPtr<Gfx::Font> FontDatabase::get(FlyString const& family, float point_size, unsigned weight, unsigned slope, Font::AllowInexactSizeMatch allow_inexact_size_match)
{
for (auto typeface : m_private->typefaces) {
if (typeface->family() == family && typeface->weight() == weight && typeface->slope() == slope)
return typeface->get_font(point_size, allow_inexact_size_match);
}
return nullptr;
}
RefPtr<Gfx::Font> FontDatabase::get(FlyString const& family, FlyString const& variant, float point_size, Font::AllowInexactSizeMatch allow_inexact_size_match)
{
for (auto typeface : m_private->typefaces) {
if (typeface->family() == family && typeface->variant() == variant)
return typeface->get_font(point_size, allow_inexact_size_match);
}
return nullptr;
}
RefPtr<Typeface> FontDatabase::get_or_create_typeface(String const& family, String const& variant)
{
for (auto typeface : m_private->typefaces) {
if (typeface->family() == family && typeface->variant() == variant)
return typeface;
}
auto typeface = adopt_ref(*new Typeface(family, variant));
m_private->typefaces.append(typeface);
return typeface;
}
void FontDatabase::for_each_typeface(Function<void(Typeface const&)> callback)
{
for (auto typeface : m_private->typefaces) {
callback(*typeface);
}
}
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Function.h>
#include <AK/HashMap.h>
#include <AK/OwnPtr.h>
#include <AK/String.h>
#include <LibGfx/Font/Typeface.h>
#include <LibGfx/Forward.h>
namespace Gfx {
namespace FontWeight {
enum {
Thin = 100,
ExtraLight = 200,
Light = 300,
Regular = 400,
Medium = 500,
SemiBold = 600,
Bold = 700,
ExtraBold = 800,
Black = 900,
ExtraBlack = 950
};
}
class FontDatabase {
public:
static FontDatabase& the();
static Font& default_font();
static Font& default_fixed_width_font();
static String default_font_query();
static String fixed_width_font_query();
static String default_fonts_lookup_path();
static void set_default_font_query(String);
static void set_fixed_width_font_query(String);
static void set_default_fonts_lookup_path(String);
RefPtr<Gfx::Font> get(FlyString const& family, float point_size, unsigned weight, 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_by_name(StringView);
void for_each_font(Function<void(Gfx::Font const&)>);
void for_each_fixed_width_font(Function<void(Gfx::Font const&)>);
void for_each_typeface(Function<void(Typeface const&)>);
private:
FontDatabase();
~FontDatabase() = default;
RefPtr<Typeface> get_or_create_typeface(String const& family, String const& variant);
struct Private;
OwnPtr<Private> m_private;
};
}

View file

@ -0,0 +1,80 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2021, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/StringView.h>
namespace Gfx {
struct FontStyleMapping {
constexpr FontStyleMapping(int s, char const* n)
: style(s)
, name(n)
{
}
int style { 0 };
StringView name;
};
static constexpr FontStyleMapping font_weight_names[] = {
{ 100, "Thin" },
{ 200, "Extra Light" },
{ 300, "Light" },
{ 400, "Regular" },
{ 500, "Medium" },
{ 600, "Semi Bold" },
{ 700, "Bold" },
{ 800, "Extra Bold" },
{ 900, "Black" },
{ 950, "Extra Black" },
};
static constexpr FontStyleMapping font_slope_names[] = {
{ 0, "Regular" },
{ 1, "Italic" },
{ 2, "Oblique" },
{ 3, "Reclined" }
};
static constexpr StringView weight_to_name(int weight)
{
for (auto& it : font_weight_names) {
if (it.style == weight)
return it.name;
}
return {};
}
static constexpr int name_to_weight(StringView name)
{
for (auto& it : font_weight_names) {
if (it.name == name)
return it.style;
}
return {};
}
static constexpr StringView slope_to_name(int slope)
{
for (auto& it : font_slope_names) {
if (it.style == slope)
return it.name;
}
return {};
}
static constexpr int name_to_slope(StringView name)
{
for (auto& it : font_slope_names) {
if (it.name == name)
return it.style;
}
return {};
}
}

View file

@ -11,11 +11,11 @@
#include <AK/RefCounted.h>
#include <AK/StringView.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Font.h>
#include <LibGfx/Size.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/TrueType/Cmap.h>
#include <LibGfx/Font/TrueType/Glyf.h>
#include <LibGfx/Font/TrueType/Tables.h>
#include <LibGfx/Size.h>
#define POINTS_PER_INCH 72.0f
#define DEFAULT_DPI 96

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibGfx/Font/Typeface.h>
namespace Gfx {
unsigned Typeface::weight() const
{
VERIFY(m_ttf_font || m_bitmap_fonts.size() > 0);
if (is_fixed_size())
return m_bitmap_fonts[0]->weight();
return m_ttf_font->weight();
}
u8 Typeface::slope() const
{
VERIFY(m_ttf_font || m_bitmap_fonts.size() > 0);
if (is_fixed_size())
return m_bitmap_fonts[0]->slope();
return m_ttf_font->slope();
}
bool Typeface::is_fixed_width() const
{
VERIFY(m_ttf_font || m_bitmap_fonts.size() > 0);
if (is_fixed_size())
return m_bitmap_fonts[0]->is_fixed_width();
return m_ttf_font->is_fixed_width();
}
void Typeface::add_bitmap_font(RefPtr<BitmapFont> font)
{
m_bitmap_fonts.append(font);
}
void Typeface::set_ttf_font(RefPtr<TTF::Font> font)
{
m_ttf_font = move(font);
}
RefPtr<Font> Typeface::get_font(float point_size, Font::AllowInexactSizeMatch allow_inexact_size_match) const
{
VERIFY(point_size > 0);
if (m_ttf_font)
return adopt_ref(*new TTF::ScaledFont(*m_ttf_font, point_size, 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::Yes) {
int delta = static_cast<int>(font->presentation_size()) - static_cast<int>(size);
if (abs(delta) < best_delta) {
best_match = font;
best_delta = abs(delta);
}
}
}
if (allow_inexact_size_match == Font::AllowInexactSizeMatch::Yes && 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);
}
}
}

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/FlyString.h>
#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/TrueType/Font.h>
namespace Gfx {
class Typeface : public RefCounted<Typeface> {
public:
Typeface(String const& family, String const& variant)
: m_family(family)
, m_variant(variant)
{
}
FlyString const& family() const { return m_family; }
FlyString const& variant() const { return m_variant; }
unsigned weight() const;
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_ttf_font(RefPtr<TTF::Font>);
RefPtr<Font> get_font(float point_size, Font::AllowInexactSizeMatch = Font::AllowInexactSizeMatch::No) const;
private:
FlyString m_family;
FlyString m_variant;
Vector<RefPtr<BitmapFont>> m_bitmap_fonts;
RefPtr<TTF::Font> m_ttf_font;
};
}