/
font.cpp
423 lines (356 loc) · 11.5 KB
/
font.cpp
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/** @file font.cpp Font with metrics.
*
* @authors Copyright (c) 2013-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* LGPL: http://www.gnu.org/licenses/lgpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "de/Font"
#include <de/ConstantRule>
#include <de/Hash>
#include <de/ThreadLocal>
#if (defined(MACOSX) && defined(MACOS_10_7)) || defined(DE_IOS)
# include "coretextnativefont_macx.h"
namespace de { using PlatformFont = CoreTextNativeFont; }
#else
# include "stbttnativefont.h"
namespace de { using PlatformFont = StbTtNativeFont; }
#endif
namespace std {
template<>
struct hash<de::FontParams> {
std::size_t operator()(const de::FontParams &fp) const {
return hash<de::String>()(fp.family)
^ hash<int>()(int(100 * fp.pointSize + 0.5f))
^ hash<int>()(fp.spec.weight)
^ hash<int>()(int(fp.spec.style))
^ hash<int>()(fp.spec.transform);
}
};
} // namespace std
namespace de {
namespace internal {
struct ThreadFonts
{
PlatformFont font;
Hash<FontParams, PlatformFont *> fontMods;
~ThreadFonts() { fontMods.deleteAll(); }
};
} // namespace internal
/**
* Each thread uses its own independent set of native font instances. This allows
* background threads to freely measure and render text using the native font
* instances without any synchronization. Also note that these background threads are
* pooled, so there is only a fixed total number of threads accessing these objects.
*/
static ThreadLocal<Hash<Font *, internal::ThreadFonts>> fontsForThread;
DE_PIMPL(Font)
{
FontParams fontParams;
internal::ThreadFonts *threadFonts = nullptr;
ConstantRule *heightRule;
ConstantRule *ascentRule;
ConstantRule *descentRule;
ConstantRule *lineSpacingRule;
int ascent = 0;
Impl(Public *i) : Base(i)
{
createRules();
}
Impl(Public *i, const FontParams &fp)
: Base(i)
, fontParams(fp)
{
createRules();
updateMetrics();
}
~Impl()
{
fontsForThread.get().remove(thisPublic); // FIXME: not removed by all threads...
releaseRef(heightRule);
releaseRef(ascentRule);
releaseRef(descentRule);
releaseRef(lineSpacingRule);
}
void createRules()
{
heightRule = new ConstantRule(0);
ascentRule = new ConstantRule(0);
descentRule = new ConstantRule(0);
lineSpacingRule = new ConstantRule(0);
}
/**
* Initializes the current thread's platform fonts for this Font.
*/
internal::ThreadFonts &getThreadFonts()
{
auto &hash = fontsForThread.get();
auto found = hash.find(thisPublic);
if (found != hash.end())
{
auto &tf = found->second;
if (fequal(tf.font.pointSize(), fontParams.pointSize))
{
return tf;
}
// Size has changed, re-initialize the font.
tf.fontMods.deleteAll();
tf.fontMods.clear();
}
auto &font = hash[thisPublic].font;
font.setFamily(fontParams.family);
font.setPointSize(fontParams.pointSize);
font.setStyle(fontParams.spec.style);
font.setTransform(fontParams.spec.transform);
font.setWeight(fontParams.spec.weight);
return hash[thisPublic];
}
void updateMetrics()
{
auto &plat = getThreadFonts();
ascent = plat.font.ascent();
if (plat.font.weight() != NativeFont::Normal)
{
// Use the ascent of the normal weight for non-normal weights;
// we need to align content to baseline regardless of weight.
PlatformFont normalized(plat.font);
normalized.setWeight(NativeFont::Normal);
ascent = normalized.ascent();
}
ascentRule ->set(ascent);
descentRule ->set(plat.font.descent());
heightRule ->set(plat.font.height());
lineSpacingRule->set(plat.font.lineSpacing());
}
static PlatformFont makePlatformFont(const FontParams ¶ms)
{
PlatformFont pf;
pf.setFamily(params.family);
pf.setPointSize(params.pointSize);
pf.setStyle(params.spec.style);
pf.setWeight(params.spec.weight);
pf.setTransform(params.spec.transform);
return pf;
}
PlatformFont &getFontMod(FontParams const ¶ms)
{
auto &plat = getThreadFonts();
auto found = plat.fontMods.find(params);
if (found != plat.fontMods.end())
{
return *found->second;
}
PlatformFont *mod = new PlatformFont(makePlatformFont(params));
plat.fontMods.insert(params, mod);
return *mod;
}
/**
* Produces a font based on this one but with the attribute modifications applied
* from a rich format range.
*
* @param rich Rich formatting.
*
* @return Font with applied formatting.
*/
PlatformFont const &alteredFont(RichFormat::Iterator const &rich)
{
auto &plat = getThreadFonts();
if (!rich.isDefault())
{
FontParams modParams(plat.font);
// Size change.
if (!fequal(rich.sizeFactor(), 1.f))
{
modParams.pointSize *= rich.sizeFactor();
}
// Style change (including monospace).
switch (rich.style())
{
case RichFormat::OriginalStyle:
break;
case RichFormat::Regular:
modParams.family = plat.font.family();
modParams.spec.style = NativeFont::Regular;
break;
case RichFormat::Italic:
modParams.family = plat.font.family();
modParams.spec.style = NativeFont::Italic;
break;
case RichFormat::Monospace:
if (rich.format.format().hasStyle())
{
if (Font const *altFont = rich.format.format().style().richStyleFont(rich.style()))
{
modParams = FontParams(altFont->d->getThreadFonts().font);
}
}
break;
}
// Weight change.
if (rich.weight() != RichFormat::OriginalWeight)
{
modParams.spec.weight = (rich.weight() == RichFormat::Normal? NativeFont::Normal :
rich.weight() == RichFormat::Bold? NativeFont::Bold :
NativeFont::Light);
}
return getFontMod(modParams);
}
// No alterations applied.
return plat.font;
}
};
Font::Font()
: d(new Impl(this))
{}
Font::Font(Font const &other)
: d(new Impl(this, other.d->fontParams))
{}
Font::Font(const FontParams ¶ms)
: d(new Impl(this, params))
{}
void Font::initialize(const FontParams ¶ms)
{
d->fontParams = params;
d->updateMetrics();
}
Rectanglei Font::measure(String const &textLine) const
{
return measure(RichFormat::fromPlainText(textLine));
}
Rectanglei Font::measure(RichFormatRef const &format) const
{
Rectanglei bounds;
int advance = 0;
RichFormat::Iterator iter(format);
while (iter.hasNext())
{
iter.next();
if (iter.range().isEmpty()) continue;
const PlatformFont &altFont = d->alteredFont(iter);
const String part = iter.range();
Rectanglei rect = altFont.measure(part);
// Combine to the total bounds.
rect.move(Vec2i(advance, 0));
bounds |= rect;
advance += altFont.advanceWidth(part);
}
return bounds;
}
int Font::advanceWidth(String const &textLine) const
{
return advanceWidth(RichFormat::fromPlainText(textLine));
}
int Font::advanceWidth(RichFormatRef const &format) const
{
int advance = 0;
RichFormat::Iterator iter(format);
while (iter.hasNext())
{
iter.next();
if (!iter.range().isEmpty())
{
advance += d->alteredFont(iter).advanceWidth(iter.range());
}
}
return advance;
}
Image Font::rasterize(String const & textLine,
Image::Color const &foreground,
Image::Color const &background) const
{
if (textLine.isEmpty()) return {};
return rasterize(RichFormat::fromPlainText(textLine), foreground, background);
}
Image Font::rasterize(RichFormatRef const &format,
Image::Color const & foreground,
Image::Color const & background) const
{
auto const &plat = d->getThreadFonts();
const Rectanglei bounds = measure(format);
Image::Color bgColor(background.x, background.y, background.z, background.w);
Image::Color fg = foreground;
Image::Color bg = background;
const Vec2i imgOrigin = -bounds.topLeft;
Image img(bounds.size(), Image::RGBA_8888);
img.fill(bgColor);
img.setOrigin(bounds.topLeft);
// Composite the final image by drawing each rich range first into a separate
// bitmap and then drawing those into the final image.
int advance = 0;
int ascent = 0;
RichFormat::Iterator iter(format);
while (iter.hasNext())
{
iter.next();
if (iter.range().isEmpty()) continue;
const auto *font = &plat.font;
if (iter.isDefault())
{
fg = foreground;
bg = background;
}
else
{
font = &d->alteredFont(iter);
if (iter.colorIndex() != RichFormat::OriginalColor)
{
fg = iter.color();
bg = Vec4ub(fg, 0);
}
else
{
fg = foreground;
bg = background;
}
}
const String part = iter.range();
const Image raster = font->rasterize(part, fg, bg);
ascent = de::max(ascent, font->ascent());
img.draw(raster, imgOrigin + raster.origin() + Vec2i(advance, 0));
advance += font->advanceWidth(part);
}
img.setOrigin(img.origin() + Vec2i(0, ascent));
return img;
}
Rule const &Font::height() const
{
return *d->heightRule;
}
Rule const &Font::ascent() const
{
return *d->ascentRule;
}
Rule const &Font::descent() const
{
return *d->descentRule;
}
Rule const &Font::lineSpacing() const
{
return *d->lineSpacingRule;
}
bool Font::load(const String &name, const Block &data) // static
{
return PlatformFont::load(name, data);
}
//------------------------------------------------------------------------------------------------
FontParams::FontParams()
{}
FontParams::FontParams(const NativeFont &font)
{
family = font.family();
pointSize = font.pointSize();
spec.weight = font.weight();
spec.style = font.style();
spec.transform = font.transform();
}
} // namespace de