-
Notifications
You must be signed in to change notification settings - Fork 388
Expand file tree
/
Copy pathFontSupportPango.C
More file actions
610 lines (466 loc) · 14.2 KB
/
FontSupportPango.C
File metadata and controls
610 lines (466 loc) · 14.2 KB
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*
* Copyright (C) 2011 Emweb bv, Herent, Belgium.
*
* See the LICENSE file for terms of use.
*/
#include "Wt/WFont.h"
#include "Wt/WFontMetrics.h"
#include "Wt/WPointF.h"
#include "Wt/WRectF.h"
#include "Wt/WTransform.h"
#include "Wt/FontSupport.h"
#include "WebUtils.h"
#ifdef WT_THREADED
#include <thread>
#include <mutex>
#endif // WT_THREADED
#include <boost/algorithm/string.hpp>
#include <pango/pango.h>
#include <pango/pangoft2.h>
#ifndef DOXYGEN_ONLY
namespace {
const double EPSILON = 1e-4;
bool isEpsilonMore(double x, double limit) {
return x - EPSILON > limit;
}
double pangoUnitsToDouble(const int u)
{
return ((double)u) / PANGO_SCALE;
}
int pangoUnitsFromDouble(const double u)
{
return (int) (u * PANGO_SCALE);
}
static Wt::FontSupport::EnabledFontFormats enabledFontFormats = Wt::FontSupport::AnyFont;
void addTrueTypePattern(FcPattern *pattern, gpointer data)
{
if (enabledFontFormats == Wt::FontSupport::TrueTypeOnly) {
FcChar8 font_format[] = "TrueType";
FcPatternAddString(pattern, "fontformat", font_format);
}
}
/*
* A global font map, since this one leaks as hell, and it cannot stand
* being used in thread local storage since cleanup (with thread exit)
* doesn't work properly.
*
* It is not clear what operations involving the font map are thread-safe,
* so here we serialize everything using a mutex.
*/
PangoFontMap *pangoFontMap = nullptr;
#ifdef WT_THREADED
std::recursive_mutex pangoMutex;
#define PANGO_LOCK std::unique_lock<std::recursive_mutex> lock(pangoMutex);
#else
#define PANGO_LOCK
#endif // WT_THREADED
}
namespace Wt {
FontSupport::Bitmap::Bitmap(int width, int height)
: width_(width),
height_(height),
pitch_((width_ + 3) & -4)
{
buffer_ = new unsigned char[height_ * pitch_];
memset(buffer_, 0, height_ * pitch_);
}
FontSupport::Bitmap::~Bitmap()
{
delete[] buffer_;
}
FontSupport::FontMatch::FontMatch(PangoFont *font, PangoFontDescription *desc)
: font_(font), desc_(desc)
{ }
std::string FontSupport::FontMatch::fileName() const
{
return FontSupport::fontPath(font_);
}
FontSupport::FontSupport(WPaintDevice *paintDevice, EnabledFontFormats enabledFontFormats)
: device_(paintDevice),
enabledFontFormats_(enabledFontFormats),
cache_(10)
{
PANGO_LOCK;
if (!pangoFontMap) {
pangoFontMap = pango_ft2_font_map_new();
pango_ft2_font_map_set_default_substitute(PANGO_FT2_FONT_MAP(pangoFontMap),
addTrueTypePattern, NULL, NULL);
}
#if PANGO_VERSION_MAJOR > 1 || PANGO_VERSION_MINOR > 21
context_ = pango_font_map_create_context(pangoFontMap);
#else
context_ = pango_ft2_font_map_create_context(PANGO_FT2_FONT_MAP(pangoFontMap));
#endif
currentFont_ = nullptr;
}
FontSupport::~FontSupport()
{
PANGO_LOCK;
for (MatchCache::iterator i = cache_.begin(); i != cache_.end(); ++i) {
if (i->match) {
g_object_unref(i->match);
pango_font_description_free(i->desc);
}
}
g_object_unref(context_);
}
bool FontSupport::canRender() const
{
return true;
}
void FontSupport::setDevice(WPaintDevice *paintDevice)
{
device_ = paintDevice;
}
PangoFontDescription *FontSupport::createFontDescription(const WFont& f) const
{
std::string s = f.specificFamilies().toUTF8();
/* Quick fix for Mac OS X (Times is a special font?) */
boost::trim(s);
if (Utils::lowerCase(s) == "times")
s = "Times New Roman";
if (f.genericFamily() != FontFamily::Default) {
if (!s.empty())
s += ',';
switch (f.genericFamily()) {
case FontFamily::Serif: s += "serif"; break;
case FontFamily::SansSerif: s += "sans"; break;
case FontFamily::Cursive: s += "cursive"; break;
case FontFamily::Fantasy: s += "fantasy"; break;
case FontFamily::Monospace: s += "monospace"; break;
default: break;
}
}
if (f.weightValue() < 300)
s += " ultra-light";
else if (f.weightValue() < 400)
s += " light";
else if (f.weightValue() >= 700)
s += " bold";
else if (f.weightValue() >= 800)
s += " ultra-bold";
else if (f.weightValue() >= 900)
s += " heavy";
switch (f.style()) {
case FontStyle::Italic: s += " italic"; break;
case FontStyle::Oblique: s += " oblique"; break;
default: break;
}
switch (f.variant()) {
case FontVariant::SmallCaps: s += " small-caps"; break;
default: break;
}
s += " " + std::to_string((int)(f.sizeLength().toPixels() * 0.75 * 96/72));
return pango_font_description_from_string(s.c_str());
}
FontSupport::FontMatch FontSupport::matchFont(const WFont& f) const
{
for (MatchCache::iterator i = cache_.begin(); i != cache_.end(); ++i) {
if (i->font == f) {
cache_.splice(cache_.begin(), cache_, i); // implement LRU
return FontMatch(i->match, i->desc);
}
}
PANGO_LOCK;
enabledFontFormats = enabledFontFormats_;
PangoFontDescription *desc = createFontDescription(f);
PangoFont *match = pango_font_map_load_font(pangoFontMap, context_, desc);
pango_context_set_font_description(context_, desc); // for layoutText()
if (cache_.back().match) {
g_object_unref(cache_.back().match);
pango_font_description_free(cache_.back().desc);
}
cache_.pop_back();
cache_.push_front(Matched(f, match, desc));
return FontMatch(match, desc);
}
void FontSupport::addFontCollection(const std::string& directory,
bool recursive)
{
}
bool FontSupport::busy() const
{
return currentFont_;
}
std::string FontSupport::drawingFontPath() const
{
return fontPath(currentFont_);
}
std::string FontSupport::fontPath(PangoFont *font)
{
PANGO_LOCK;
PangoFcFont *f = (PangoFcFont *)font;
FT_Face face = pango_fc_font_lock_face(f);
std::string result;
if (face->stream->pathname.pointer)
result = (const char *)face->stream->pathname.pointer;
pango_fc_font_unlock_face(f);
return result;
}
GList *FontSupport::layoutText(const WFont& font,
const std::string& utf8,
std::vector<PangoGlyphString *>& glyphs,
int& width)
{
PANGO_LOCK;
enabledFontFormats = enabledFontFormats_;
FontMatch match = matchFont(font);
PangoAttrList *attrs = pango_attr_list_new();
pango_context_set_font_description(context_, match.pangoFontDescription());
GList *items
= pango_itemize(context_, utf8.c_str(), 0, utf8.length(), attrs, nullptr);
width = 0;
for (GList *elem = items; elem; elem = elem->next) {
PangoItem *item = (PangoItem *)elem->data;
PangoAnalysis *analysis = &item->analysis;
PangoGlyphString *gl = pango_glyph_string_new();
pango_shape(utf8.c_str() + item->offset, item->length, analysis, gl);
glyphs.push_back(gl);
if (device_) {
currentFont_ = analysis->font;
WTextItem textItem
= device_->measureText(WString::fromUTF8(utf8.substr(item->offset,
item->length)),
-1, false);
width += pangoUnitsFromDouble(textItem.width());
currentFont_ = nullptr;
} else
width += pango_glyph_string_get_width(gl);
}
pango_attr_list_unref(attrs);
return items;
}
void FontSupport::drawText(const WFont& font, const WRectF& rect,
WFlags<AlignmentFlag> flags, const WString& text)
{
PANGO_LOCK;
enabledFontFormats = enabledFontFormats_;
std::string utf8 = text.toUTF8();
std::vector<PangoGlyphString *> glyphs;
int width;
GList *items = layoutText(font, utf8, glyphs, width);
AlignmentFlag hAlign = flags & AlignHorizontalMask;
AlignmentFlag vAlign = flags & AlignVerticalMask;
/* FIXME handle bidi ! */
double x;
switch (hAlign) {
case AlignmentFlag::Left:
x = rect.left();
break;
case AlignmentFlag::Right:
x = rect.right() - pangoUnitsToDouble(width);
break;
case AlignmentFlag::Center:
x = rect.center().x() - pangoUnitsToDouble(width/2);
break;
default:
x = 0;
}
unsigned i = 0;
for (GList *elem = items; elem; elem = elem->next) {
PangoItem *item = (PangoItem *)elem->data;
PangoAnalysis *analysis = &item->analysis;
PangoGlyphString *gl = glyphs[i++];
currentFont_ = analysis->font;
/*
* Note, we are actually ignoring the selected glyphs here, which
* is a pitty and possibly wrong if the device does not make the
* same selection !
*/
WString s = WString::fromUTF8(utf8.substr(item->offset,
item->length));
device_->drawText(WRectF(x, rect.y(),
1000, rect.height()),
AlignmentFlag::Left | vAlign, TextFlag::SingleLine,
s, nullptr);
WTextItem textItem = device_->measureText(s, -1, false);
x += textItem.width();
pango_item_free(item);
pango_glyph_string_free(gl);
}
g_list_free(items);
currentFont_ = nullptr;
}
WFontMetrics FontSupport::fontMetrics(const WFont& font)
{
PANGO_LOCK;
enabledFontFormats = enabledFontFormats_;
PangoFont *pangoFont = matchFont(font).pangoFont();
PangoFontMetrics *metrics = pango_font_get_metrics(pangoFont, nullptr);
double ascent
= pangoUnitsToDouble(pango_font_metrics_get_ascent(metrics));
double descent
= pangoUnitsToDouble(pango_font_metrics_get_descent(metrics));
double leading = (ascent + descent) - font.sizeLength(12).toPixels();
// ascent < leading is an odd thing. it happens with a font like
// Cursive.
if (ascent > leading)
ascent -= leading;
else
leading = 0;
WFontMetrics result(font, leading, ascent, descent);
pango_font_metrics_unref(metrics);
return result;
}
WTextItem FontSupport::measureText(const WFont& font, const WString& text,
double maxWidth, bool wordWrap)
{
PANGO_LOCK;
enabledFontFormats = enabledFontFormats_;
/*
* Note: accurate measuring on a bitmap requires that the transformation
* is applied, because hinting may push chars to boundaries e.g. when
* rotated (or scaled too?)
*/
std::string utf8 = text.toUTF8();
const char *s = utf8.c_str();
if (wordWrap) {
int utflen = g_utf8_strlen(s, -1);
PangoLogAttr *attrs = new PangoLogAttr[utflen + 1];
PangoLanguage *language = pango_language_from_string("en-US");
pango_get_log_attrs(s, utf8.length(), -1, language, attrs, utflen + 1);
double w = 0, nextW = -1;
int current = 0;
int measured = 0;
int end = 0;
bool maxWidthReached = false;
for (int i = 0; i < utflen + 1; ++i) {
if (i == utflen || attrs[i].is_line_break) {
int cend = g_utf8_offset_to_pointer(s, end) - s;
WTextItem ti
= measureText(font, WString::fromUTF8(utf8.substr(measured,
cend - measured)),
-1, false);
if (isEpsilonMore(w + ti.width(), maxWidth)) {
nextW = ti.width();
maxWidthReached = true;
break;
} else {
measured = cend;
current = g_utf8_offset_to_pointer(s, i) - s;
w += ti.width();
if (i == utflen) {
w += measureText(font, WString::fromUTF8(utf8.substr(measured)),
-1, false).width();
measured = utf8.length();
}
}
}
if (!attrs[i].is_white)
end = i + 1;
}
delete[] attrs;
if (maxWidthReached) {
return WTextItem(WString::fromUTF8(utf8.substr(0, current)), w, nextW);
} else {
/*
* For some reason, the sum of the individual widths is a bit less
* (for longer stretches of text), so we re-measure it !
*/
w = measureText(font, WString::fromUTF8(utf8.substr(0, measured)),
-1, false).width();
return WTextItem(text, w);
}
} else {
std::vector<PangoGlyphString *> glyphs;
int width;
GList *items = layoutText(font, utf8, glyphs, width);
double w = pangoUnitsToDouble(width);
for (unsigned i = 0; i < glyphs.size(); ++i)
pango_glyph_string_free(glyphs[i]);
g_list_foreach(items, (GFunc) pango_item_free, nullptr);
g_list_free(items);
return WTextItem(text, w);
}
}
void FontSupport::drawText(const WFont& font, const WRectF& rect,
const WTransform& transform, Bitmap& bitmap,
WFlags<AlignmentFlag> flags,
const WString& text)
{
PANGO_LOCK;
enabledFontFormats = enabledFontFormats_;
PangoMatrix matrix;
matrix.xx = transform.m11();
matrix.xy = transform.m21();
matrix.yx = transform.m12();
matrix.yy = transform.m22();
matrix.x0 = transform.dx();
matrix.y0 = transform.dy();
std::string utf8 = text.toUTF8();
std::vector<PangoGlyphString *> glyphs;
int width;
pango_context_set_matrix(context_, &matrix);
/*
* Oh my god, somebody explain me why we need to do this...
*/
WFont f = font;
f.setSize(font.sizeLength().toPixels()
/ pango_matrix_get_font_scale_factor(&matrix));
GList *items = layoutText(f, utf8, glyphs, width);
pango_context_set_matrix(context_, nullptr);
AlignmentFlag hAlign = flags & AlignHorizontalMask;
/* FIXME handle bidi ! */
double x;
switch (hAlign) {
case AlignmentFlag::Left:
x = rect.left();
break;
case AlignmentFlag::Right:
x = rect.right() - pangoUnitsToDouble(width);
break;
case AlignmentFlag::Center:
x = rect.center().x() - pangoUnitsToDouble(width/2);
break;
default:
x = 0;
}
AlignmentFlag vAlign = flags & AlignVerticalMask;
PangoFont *pangoFont = matchFont(font).pangoFont();
PangoFontMetrics *metrics = pango_font_get_metrics(pangoFont, nullptr);
double ascent
= pangoUnitsToDouble(pango_font_metrics_get_ascent(metrics));
double descent
= pangoUnitsToDouble(pango_font_metrics_get_descent(metrics));
pango_font_metrics_unref(metrics);
double baseline = ascent;
double height = ascent + descent;
double y;
switch (vAlign) {
case AlignmentFlag::Top:
y = rect.top() + baseline;
break;
case AlignmentFlag::Middle:
y = rect.center().y() - height / 2 + baseline;
break;
case AlignmentFlag::Bottom:
y = rect.bottom() - height + baseline;
break;
default:
y = 0;
}
FT_Bitmap bmp;
bmp.buffer = bitmap.buffer();
bmp.width = bitmap.width();
bmp.rows = bitmap.height();
bmp.pitch = bitmap.pitch();
bmp.pixel_mode = FT_PIXEL_MODE_GRAY;
bmp.num_grays = 16; // ???
GList *elem;
unsigned i = 0;
for (elem = items; elem; elem = elem->next) {
PangoItem *item = (PangoItem *)elem->data;
PangoAnalysis *analysis = &item->analysis;
PangoGlyphString *gl = glyphs[i++];
pango_ft2_render_transformed(&bmp, &matrix,
analysis->font, gl,
pangoUnitsFromDouble(x),
pangoUnitsFromDouble(y));
x += pangoUnitsToDouble(pango_glyph_string_get_width(gl));
pango_glyph_string_free(gl);
pango_item_free(item);
}
g_list_free(items);
}
}
#endif // DOXYGEN_ONLY