summaryrefslogtreecommitdiff
path: root/Libraries/LibGfx/Font.cpp
blob: 7837c01cdf394121f64ddf010e5d4fc542ecd192 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "Font.h"
#include "Bitmap.h"
#include "Emoji.h"
#include <AK/BufferStream.h>
#include <AK/MappedFile.h>
#include <AK/StdLibExtras.h>
#include <AK/StringBuilder.h>
#include <AK/Utf32View.h>
#include <AK/Utf8View.h>
#include <AK/Vector.h>
#include <AK/kmalloc.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

namespace Gfx {

struct [[gnu::packed]] FontFileHeader
{
    char magic[4];
    u8 glyph_width;
    u8 glyph_height;
    u8 type;
    u8 is_variable_width;
    u8 glyph_spacing;
    u8 baseline;
    u8 unused[4];
    char name[64];
};

Font& Font::default_font()
{
    static Font* s_default_font;
    static const char* default_font_path = "/res/fonts/Katica10.font";
    if (!s_default_font) {
        s_default_font = Font::load_from_file(default_font_path).leak_ref();
        ASSERT(s_default_font);
    }
    return *s_default_font;
}

Font& Font::default_fixed_width_font()
{
    static Font* s_default_fixed_width_font;
    static const char* default_fixed_width_font_path = "/res/fonts/CsillaThin7x10.font";
    if (!s_default_fixed_width_font) {
        s_default_fixed_width_font = Font::load_from_file(default_fixed_width_font_path).leak_ref();
        ASSERT(s_default_fixed_width_font);
    }
    return *s_default_fixed_width_font;
}

Font& Font::default_bold_fixed_width_font()
{
    static Font* font;
    static const char* default_bold_fixed_width_font_path = "/res/fonts/CsillaBold7x10.font";
    if (!font) {
        font = Font::load_from_file(default_bold_fixed_width_font_path).leak_ref();
        ASSERT(font);
    }
    return *font;
}

Font& Font::default_bold_font()
{
    static Font* s_default_bold_font;
    static const char* default_bold_font_path = "/res/fonts/KaticaBold10.font";
    if (!s_default_bold_font) {
        s_default_bold_font = Font::load_from_file(default_bold_font_path).leak_ref();
        ASSERT(s_default_bold_font);
    }
    return *s_default_bold_font;
}

NonnullRefPtr<Font> Font::clone() const
{
    size_t bytes_per_glyph = sizeof(u32) * glyph_height();
    // FIXME: This is leaked!
    auto* new_rows = static_cast<unsigned*>(kmalloc(bytes_per_glyph * m_glyph_count));
    memcpy(new_rows, m_rows, bytes_per_glyph * m_glyph_count);
    auto* new_widths = static_cast<u8*>(kmalloc(m_glyph_count));
    if (m_glyph_widths)
        memcpy(new_widths, m_glyph_widths, m_glyph_count);
    else
        memset(new_widths, m_glyph_width, m_glyph_count);
    return adopt(*new Font(m_name, new_rows, new_widths, m_fixed_width, m_glyph_width, m_glyph_height, m_glyph_spacing, m_type, m_baseline));
}

NonnullRefPtr<Font> Font::create(u8 glyph_height, u8 glyph_width, bool fixed, FontTypes type)
{
    size_t bytes_per_glyph = sizeof(u32) * glyph_height;
    // FIXME: This is leaked!
    size_t count = glyph_count_by_type(type);
    auto* new_rows = static_cast<unsigned*>(malloc(bytes_per_glyph * count));
    memset(new_rows, 0, bytes_per_glyph * count);
    auto* new_widths = static_cast<u8*>(malloc(count));
    memset(new_widths, glyph_width, count);
    return adopt(*new Font("Untitled", new_rows, new_widths, fixed, glyph_width, glyph_height, 1, type, 0));
}

Font::Font(const StringView& name, unsigned* rows, u8* widths, bool is_fixed_width, u8 glyph_width, u8 glyph_height, u8 glyph_spacing, FontTypes type, u8 baseline)
    : m_name(name)
    , m_type(type)
    , 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_fixed_width(is_fixed_width)
{
    // FIXME: This is just a dumb guess. It would be cool to know the actual x-height of the font!
    m_x_height = glyph_height / 2;

    m_glyph_count = glyph_count_by_type(m_type);

    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 = maximum;
    }

    set_family_fonts();
}

Font::~Font()
{
}

RefPtr<Font> Font::load_from_memory(const u8* data)
{
    auto& header = *reinterpret_cast<const FontFileHeader*>(data);
    if (memcmp(header.magic, "!Fnt", 4)) {
        dbgprintf("header.magic != '!Fnt', instead it's '%c%c%c%c'\n", header.magic[0], header.magic[1], header.magic[2], header.magic[3]);
        return nullptr;
    }
    if (header.name[63] != '\0') {
        dbgprintf("Font name not fully null-terminated\n");
        return nullptr;
    }

    FontTypes type;
    if (header.type == 0)
        type = FontTypes::Default;
    else if (header.type == 1)
        type = FontTypes::LatinExtendedA;
    else
        ASSERT_NOT_REACHED();

    size_t count = glyph_count_by_type(type);
    size_t bytes_per_glyph = sizeof(unsigned) * header.glyph_height;

    auto* rows = const_cast<unsigned*>((const unsigned*)(data + sizeof(FontFileHeader)));
    u8* widths = nullptr;
    if (header.is_variable_width)
        widths = (u8*)(rows) + count * bytes_per_glyph;
    return adopt(*new Font(String(header.name), rows, widths, !header.is_variable_width, header.glyph_width, header.glyph_height, header.glyph_spacing, type, header.baseline));
}

size_t Font::glyph_count_by_type(FontTypes type)
{
    if (type == FontTypes::Default)
        return 256;

    if (type == FontTypes::LatinExtendedA)
        return 384;

    dbg() << "Unknown font type:" << type;
    ASSERT_NOT_REACHED();
}

RefPtr<Font> Font::load_from_file(const StringView& path)
{
    MappedFile mapped_file(path);
    if (!mapped_file.is_valid())
        return nullptr;

    auto font = load_from_memory((const u8*)mapped_file.data());
    if (!font)
        return nullptr;

    font->m_mapped_file = move(mapped_file);
    return font;
}

bool Font::write_to_file(const StringView& path)
{
    int fd;
#ifdef __serenity__
    fd = creat_with_path_length(path.characters_without_null_termination(), path.length(), 0644);
#else
    {
        String null_terminated_path = path;
        fd = creat(null_terminated_path.characters(), 0644);
    }
#endif
    if (fd < 0) {
        perror("open");
        return false;
    }

    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.type = m_type;
    header.baseline = m_baseline;
    header.is_variable_width = !m_fixed_width;
    header.glyph_spacing = m_glyph_spacing;
    memcpy(header.name, m_name.characters(), min(m_name.length(), (size_t)63));

    size_t bytes_per_glyph = sizeof(unsigned) * m_glyph_height;
    size_t count = glyph_count_by_type(m_type);

    auto buffer = ByteBuffer::create_uninitialized(sizeof(FontFileHeader) + (count * bytes_per_glyph) + count);
    BufferStream stream(buffer);

    stream << ByteBuffer::wrap(&header, sizeof(FontFileHeader));
    stream << ByteBuffer::wrap(m_rows, (count * bytes_per_glyph));
    stream << ByteBuffer::wrap(m_glyph_widths, count);

    ASSERT(stream.at_end());
    ssize_t nwritten = write(fd, buffer.data(), buffer.size());
    ASSERT(nwritten == (ssize_t)buffer.size());
    int rc = close(fd);
    ASSERT(rc == 0);
    return true;
}

GlyphBitmap Font::glyph_bitmap(u32 code_point) const
{
    return GlyphBitmap(&m_rows[code_point * m_glyph_height], { glyph_width(code_point), m_glyph_height });
}

int Font::glyph_or_emoji_width(u32 code_point) const
{
    if (code_point < m_glyph_count)
        return glyph_width(code_point);

    if (m_fixed_width)
        return m_glyph_width;

    auto* emoji = Emoji::emoji_for_code_point(code_point);
    if (emoji == nullptr)
        return glyph_width('?');
    return emoji->size().width();
}

int Font::width(const StringView& string) const
{
    Utf8View utf8 { string };
    return width(utf8);
}

int Font::width(const Utf8View& utf8) const
{
    bool first = true;
    int width = 0;

    for (u32 code_point : utf8) {
        if (!first)
            width += glyph_spacing();
        first = false;
        width += glyph_or_emoji_width(code_point);
    }

    return width;
}

int Font::width(const Utf32View& view) const
{
    if (view.length() == 0)
        return 0;
    int width = (view.length() - 1) * glyph_spacing();
    for (size_t i = 0; i < view.length(); ++i)
        width += glyph_or_emoji_width(view.code_points()[i]);
    return width;
}

void Font::set_type(FontTypes type)
{
    if (type == m_type)
        return;

    if (type == FontTypes::Default)
        return;

    size_t new_glyph_count = glyph_count_by_type(type);
    if (new_glyph_count <= m_glyph_count) {
        m_glyph_count = new_glyph_count;
        return;
    }

    int item_count_to_copy = min(m_glyph_count, new_glyph_count);

    size_t bytes_per_glyph = sizeof(u32) * glyph_height();

    auto* new_rows = static_cast<unsigned*>(kmalloc(bytes_per_glyph * new_glyph_count));
    memset(new_rows, (unsigned)0, bytes_per_glyph * new_glyph_count);
    memcpy(new_rows, m_rows, bytes_per_glyph * item_count_to_copy);

    auto* new_widths = static_cast<u8*>(kmalloc(new_glyph_count));
    memset(new_widths, (u8)0, new_glyph_count);
    memcpy(new_widths, m_glyph_widths, item_count_to_copy);

    kfree(m_rows);
    kfree(m_glyph_widths);

    m_type = type;
    m_glyph_count = new_glyph_count;
    m_rows = new_rows;
    m_glyph_widths = new_widths;
}

void Font::set_family_fonts()
{
    String typeface;
    String weight;
    StringBuilder size;

    auto parts = this->name().split(' ');
    if (parts.size() < 2) {
        typeface = this->name();
    } else {
        typeface = parts[0];
        weight = parts[1];
    }

    if (this->is_fixed_width()) {
        size.appendf("%d", this->m_max_glyph_width);
        size.append("x");
    }
    size.appendf("%d", this->m_glyph_height);

    StringBuilder path;

    if (weight != "Bold") {
        path.appendf("/res/fonts/%sBold%s.font", &typeface[0], &size.to_string()[0]);
        m_bold_family_font = Font::load_from_file(path.to_string());
        if (m_bold_family_font)
            set_boldface(true);
        path.clear();
    }
}

}