Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qfontengine.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5#include <qdebug.h>
6#include <private/qfontengine_p.h>
7#include <private/qfontengineglyphcache_p.h>
8#include <private/qguiapplication_p.h>
9
10#include <qpa/qplatformfontdatabase.h>
11#include <qpa/qplatformintegration.h>
12
13#include "qbitmap.h"
14#include "qpainter.h"
15#include "qpainterpath.h"
17#include "qtextengine_p.h"
18#include <qmath.h>
19#include <qendian.h>
20#include <private/qstringiterator_p.h>
21
22#if QT_CONFIG(harfbuzz)
23# include "qharfbuzzng_p.h"
24# include <hb-ot.h>
25#endif
26
27#include <algorithm>
28#include <limits.h>
29
30#if !defined(QT_MAX_CACHED_GLYPH_SIZE)
31# define QT_MAX_CACHED_GLYPH_SIZE 64
32#endif
33
35
36Q_LOGGING_CATEGORY(lcColrv1, "qt.text.font.colrv1")
37Q_LOGGING_CATEGORY(lcTextFontCmap, "qt.text.font.cmap")
38
39using namespace Qt::StringLiterals;
40
41static inline bool qtransform_equals_no_translate(const QTransform &a, const QTransform &b)
42{
43 if (a.type() <= QTransform::TxTranslate && b.type() <= QTransform::TxTranslate) {
44 return true;
45 } else {
46 // We always use paths for perspective text anyway, so no
47 // point in checking the full matrix...
48 Q_ASSERT(a.type() < QTransform::TxProject);
49 Q_ASSERT(b.type() < QTransform::TxProject);
50
51 return a.m11() == b.m11()
52 && a.m12() == b.m12()
53 && a.m21() == b.m21()
54 && a.m22() == b.m22();
55 }
56}
57
58template<typename T>
59static inline bool qSafeFromBigEndian(const uchar *source, const uchar *end, T *output)
60{
61 if (source + sizeof(T) > end)
62 return false;
63
64 *output = qFromBigEndian<T>(source);
65 return true;
66}
67
68int QFontEngine::getPointInOutline(glyph_t glyph, int flags, quint32 point, QFixed *xpos, QFixed *ypos, quint32 *nPoints)
69{
70 Q_UNUSED(glyph);
71 Q_UNUSED(flags);
72 Q_UNUSED(point);
73 Q_UNUSED(xpos);
74 Q_UNUSED(ypos);
75 Q_UNUSED(nPoints);
76 return Err_Not_Covered;
77}
78
79static bool qt_get_font_table_default(void *user_data, uint tag, uchar *buffer, uint *length)
80{
81 QFontEngine *fe = (QFontEngine *)user_data;
82 return fe->getSfntTableData(tag, buffer, length);
83}
84
85
86#ifdef QT_BUILD_INTERNAL
87// for testing purpose only, not thread-safe!
88static QList<QFontEngine *> *enginesCollector = nullptr;
89
90Q_AUTOTEST_EXPORT void QFontEngine_startCollectingEngines()
91{
92 delete enginesCollector;
93 enginesCollector = new QList<QFontEngine *>();
94}
95
96Q_AUTOTEST_EXPORT QList<QFontEngine *> QFontEngine_stopCollectingEngines()
97{
98 Q_ASSERT(enginesCollector);
99 QList<QFontEngine *> ret = *enginesCollector;
100 delete enginesCollector;
101 enginesCollector = nullptr;
102 return ret;
103}
104#endif // QT_BUILD_INTERNAL
105
106
107// QFontEngine
108
109#define kBearingNotInitialized std::numeric_limits<qreal>::max()
110
111QFontEngine::QFontEngine(Type type)
112 : m_type(type), ref(0),
113 font_(),
114 face_(),
115 m_heightMetricsQueried(false),
116 m_minLeftBearing(kBearingNotInitialized),
117 m_minRightBearing(kBearingNotInitialized)
118{
119 faceData.user_data = this;
120 faceData.get_font_table = qt_get_font_table_default;
121
122 cache_cost = 0;
123 fsType = 0;
124 symbol = false;
125 isSmoothlyScalable = false;
126
127 glyphFormat = Format_None;
128 m_subPixelPositionCount = 0;
129
130#ifdef QT_BUILD_INTERNAL
131 if (enginesCollector)
132 enginesCollector->append(this);
133#endif
134}
135
136QFontEngine::~QFontEngine()
137{
138#ifdef QT_BUILD_INTERNAL
139 if (enginesCollector)
140 enginesCollector->removeOne(this);
141#endif
142}
143
144QFixed QFontEngine::lineThickness() const
145{
146 // ad hoc algorithm
147 int score = fontDef.weight * fontDef.pixelSize / 10;
148 int lw = score / 700;
149
150 // looks better with thicker line for small pointsizes
151 if (lw < 2 && score >= 1050) lw = 2;
152 if (lw == 0) lw = 1;
153
154 return lw;
155}
156
157QFixed QFontEngine::underlinePosition() const
158{
159 return ((lineThickness() * 2) + 3) / 6;
160}
161
162void *QFontEngine::harfbuzzFont() const
163{
164 Q_ASSERT(type() != QFontEngine::Multi);
165#if QT_CONFIG(harfbuzz)
166 return hb_qt_font_get_for_engine(const_cast<QFontEngine *>(this));
167#else
168 return nullptr;
169#endif
170}
171
172void *QFontEngine::harfbuzzFace() const
173{
174 Q_ASSERT(type() != QFontEngine::Multi);
175#if QT_CONFIG(harfbuzz)
176 return hb_qt_face_get_for_engine(const_cast<QFontEngine *>(this));
177#else
178 return nullptr;
179#endif
180}
181
182bool QFontEngine::supportsScript(QChar::Script script) const
183{
184 if (type() <= QFontEngine::Multi)
185 return true;
186
187 // ### TODO: This only works for scripts that require OpenType. More generally
188 // for scripts that do not require OpenType we should just look at the list of
189 // supported writing systems in the font's OS/2 table.
190 if (!scriptRequiresOpenType(script))
191 return true;
192
193#if QT_CONFIG(harfbuzz)
194 // in AAT fonts, 'gsub' table is effectively replaced by 'mort'/'morx' table
195 uint lenMort = 0, lenMorx = 0;
196 if (getSfntTableData(QFont::Tag("mort").value(), nullptr, &lenMort)
197 || getSfntTableData(QFont::Tag("morx").value(), nullptr, &lenMorx)) {
198 return true;
199 }
200
201 if (hb_face_t *face = hb_qt_face_get_for_engine(const_cast<QFontEngine *>(this))) {
202 unsigned int script_count = HB_OT_MAX_TAGS_PER_SCRIPT;
203 hb_tag_t script_tags[HB_OT_MAX_TAGS_PER_SCRIPT];
204
205 hb_ot_tags_from_script_and_language(hb_qt_script_to_script(script), HB_LANGUAGE_INVALID,
206 &script_count, script_tags,
207 nullptr, nullptr);
208
209 if (hb_ot_layout_table_select_script(face, HB_OT_TAG_GSUB, script_count, script_tags, nullptr, nullptr))
210 return true;
211 }
212#endif
213 return false;
214}
215
216bool QFontEngine::canRender(const QChar *str, int len) const
217{
218 QStringIterator it(str, str + len);
219 while (it.hasNext()) {
220 if (glyphIndex(it.next()) == 0)
221 return false;
222 }
223
224 return true;
225}
226
227glyph_metrics_t QFontEngine::boundingBox(glyph_t glyph, const QTransform &matrix)
228{
229 glyph_metrics_t metrics = boundingBox(glyph);
230
231 if (matrix.type() > QTransform::TxTranslate) {
232 return metrics.transformed(matrix);
233 }
234 return metrics;
235}
236
237QFixed QFontEngine::calculatedCapHeight() const
238{
239 const glyph_t glyph = glyphIndex('H');
240 glyph_metrics_t bb = const_cast<QFontEngine *>(this)->boundingBox(glyph);
241 return bb.height;
242}
243
244QFixed QFontEngine::xHeight() const
245{
246 const glyph_t glyph = glyphIndex('x');
247 glyph_metrics_t bb = const_cast<QFontEngine *>(this)->boundingBox(glyph);
248 return bb.height;
249}
250
251QFixed QFontEngine::averageCharWidth() const
252{
253 const glyph_t glyph = glyphIndex('x');
254 glyph_metrics_t bb = const_cast<QFontEngine *>(this)->boundingBox(glyph);
255 return bb.xoff;
256}
257
258bool QFontEngine::supportsTransformation(const QTransform &transform) const
259{
260 return transform.type() < QTransform::TxProject;
261}
262
263bool QFontEngine::expectsGammaCorrectedBlending(QFontEngine::GlyphFormat format) const
264{
265 Q_UNUSED(format);
266 return true;
267}
268
269void QFontEngine::getGlyphPositions(const QGlyphLayout &glyphs, const QTransform &matrix, QTextItem::RenderFlags flags,
270 QVarLengthArray<glyph_t> &glyphs_out, QVarLengthArray<QFixedPoint> &positions)
271{
272 QFixed xpos;
273 QFixed ypos;
274
275 const bool transform = matrix.m11() != 1.
276 || matrix.m12() != 0.
277 || matrix.m21() != 0.
278 || matrix.m22() != 1.;
279 if (!transform) {
280 xpos = QFixed::fromReal(matrix.dx());
281 ypos = QFixed::fromReal(matrix.dy());
282 }
283
284 int current = 0;
285 if (flags & QTextItem::RightToLeft) {
286 int i = glyphs.numGlyphs;
287 int totalKashidas = 0;
288 while(i--) {
289 if (glyphs.attributes[i].dontPrint)
290 continue;
291 xpos += glyphs.advances[i] + QFixed::fromFixed(glyphs.justifications[i].space_18d6);
292 totalKashidas += glyphs.justifications[i].nKashidas;
293 }
294 positions.resize(glyphs.numGlyphs+totalKashidas);
295 glyphs_out.resize(glyphs.numGlyphs+totalKashidas);
296
297 i = 0;
298 while(i < glyphs.numGlyphs) {
299 if (glyphs.attributes[i].dontPrint) {
300 ++i;
301 continue;
302 }
303 xpos -= glyphs.advances[i];
304
305 QFixed gpos_x = xpos + glyphs.offsets[i].x;
306 QFixed gpos_y = ypos + glyphs.offsets[i].y;
307 if (transform) {
308 QPointF gpos(gpos_x.toReal(), gpos_y.toReal());
309 gpos = gpos * matrix;
310 gpos_x = QFixed::fromReal(gpos.x());
311 gpos_y = QFixed::fromReal(gpos.y());
312 }
313 positions[current].x = gpos_x;
314 positions[current].y = gpos_y;
315 glyphs_out[current] = glyphs.glyphs[i];
316 ++current;
317 if (glyphs.justifications[i].nKashidas) {
318 QChar ch = u'\x640'; // Kashida character
319
320 glyph_t kashidaGlyph = glyphIndex(ch.unicode());
321 QFixed kashidaWidth;
322
323 QGlyphLayout g;
324 g.numGlyphs = 1;
325 g.glyphs = &kashidaGlyph;
326 g.advances = &kashidaWidth;
327 recalcAdvances(&g, { });
328
329 for (uint k = 0; k < glyphs.justifications[i].nKashidas; ++k) {
330 xpos -= kashidaWidth;
331
332 QFixed gpos_x = xpos + glyphs.offsets[i].x;
333 QFixed gpos_y = ypos + glyphs.offsets[i].y;
334 if (transform) {
335 QPointF gpos(gpos_x.toReal(), gpos_y.toReal());
336 gpos = gpos * matrix;
337 gpos_x = QFixed::fromReal(gpos.x());
338 gpos_y = QFixed::fromReal(gpos.y());
339 }
340 positions[current].x = gpos_x;
341 positions[current].y = gpos_y;
342 glyphs_out[current] = kashidaGlyph;
343 ++current;
344 }
345 } else {
346 xpos -= QFixed::fromFixed(glyphs.justifications[i].space_18d6);
347 }
348 ++i;
349 }
350 } else {
351 positions.resize(glyphs.numGlyphs);
352 glyphs_out.resize(glyphs.numGlyphs);
353 int i = 0;
354 if (!transform) {
355 while (i < glyphs.numGlyphs) {
356 if (!glyphs.attributes[i].dontPrint) {
357 positions[current].x = xpos + glyphs.offsets[i].x;
358 positions[current].y = ypos + glyphs.offsets[i].y;
359 glyphs_out[current] = glyphs.glyphs[i];
360 xpos += glyphs.advances[i] + QFixed::fromFixed(glyphs.justifications[i].space_18d6);
361 ++current;
362 }
363 ++i;
364 }
365 } else {
366 while (i < glyphs.numGlyphs) {
367 if (!glyphs.attributes[i].dontPrint) {
368 QFixed gpos_x = xpos + glyphs.offsets[i].x;
369 QFixed gpos_y = ypos + glyphs.offsets[i].y;
370 QPointF gpos(gpos_x.toReal(), gpos_y.toReal());
371 gpos = gpos * matrix;
372 positions[current].x = QFixed::fromReal(gpos.x());
373 positions[current].y = QFixed::fromReal(gpos.y());
374 glyphs_out[current] = glyphs.glyphs[i];
375 xpos += glyphs.advances[i] + QFixed::fromFixed(glyphs.justifications[i].space_18d6);
376 ++current;
377 }
378 ++i;
379 }
380 }
381 }
382 positions.resize(current);
383 glyphs_out.resize(current);
384 Q_ASSERT(positions.size() == glyphs_out.size());
385}
386
387void QFontEngine::getGlyphBearings(glyph_t glyph, qreal *leftBearing, qreal *rightBearing)
388{
389 glyph_metrics_t gi = boundingBox(glyph);
390 if (leftBearing != nullptr)
391 *leftBearing = gi.leftBearing().toReal();
392 if (rightBearing != nullptr)
393 *rightBearing = gi.rightBearing().toReal();
394}
395
396bool QFontEngine::processHheaTable() const
397{
398 QByteArray hhea = getSfntTable(QFont::Tag("hhea").value());
399 if (hhea.size() >= 10) {
400 auto ptr = hhea.constData();
401 qint16 ascent = qFromBigEndian<qint16>(ptr + 4);
402 qint16 descent = qFromBigEndian<qint16>(ptr + 6);
403 qint16 leading = qFromBigEndian<qint16>(ptr + 8);
404
405 // Some fonts may have invalid HHEA data. We detect this and bail out.
406 if (ascent == 0 && descent == 0)
407 return false;
408
409 const qreal unitsPerEm = emSquareSize().toReal();
410 // Bail out if values are too large for QFixed
411 const auto limitForQFixed = qreal(std::numeric_limits<int>::max() >> 6) / fontDef.pixelSize;
412 if (ascent > limitForQFixed || descent > limitForQFixed || leading > limitForQFixed)
413 return false;
414 m_ascent = QFixed::fromReal(ascent * fontDef.pixelSize / unitsPerEm);
415 m_descent = -QFixed::fromReal(descent * fontDef.pixelSize / unitsPerEm);
416 m_leading = QFixed::fromReal(leading * fontDef.pixelSize / unitsPerEm);
417
418 return true;
419 }
420
421 return false;
422}
423
424void QFontEngine::initializeHeightMetrics() const
425{
426 bool hasEmbeddedBitmaps =
427 !getSfntTable(QFont::Tag("EBLC").value()).isEmpty()
428 || !getSfntTable(QFont::Tag("CBLC").value()).isEmpty()
429 || !getSfntTable(QFont::Tag("bdat").value()).isEmpty();
430
431 // When porting applications from Qt 5 to Qt 6, users have noticed differences in line
432 // metrics due to the effort to consolidate these across platforms instead of using the
433 // system values directly. This environment variable gives a "last resort" for those users
434 // to tell Qt to prefer the metrics we get from the system, despite the fact these being
435 // inconsistent across platforms.
436 static bool useSystemLineMetrics = qEnvironmentVariableIntValue("QT_USE_SYSTEM_LINE_METRICS") > 0;
437 if (!hasEmbeddedBitmaps && !useSystemLineMetrics) {
438 // Get HHEA table values if available
439 processHheaTable();
440
441 // Allow OS/2 metrics to override if present
442 processOS2Table();
443
444 if (!supportsSubPixelPositions()) {
445 const QFixed actualHeight = m_ascent + m_descent + m_leading;
446 m_ascent = m_ascent.round();
447 m_descent = m_descent.round();
448 m_leading = actualHeight.round() - m_ascent - m_descent;
449 }
450 }
451
452 m_heightMetricsQueried = true;
453}
454
455bool QFontEngine::preferTypoLineMetrics() const
456{
457 return (fontDef.styleStrategy & QFont::PreferTypoLineMetrics) != 0;
458}
459
460bool QFontEngine::processOS2Table() const
461{
462 QByteArray os2 = getSfntTable(QFont::Tag("OS/2").value());
463 if (os2.size() >= 78) {
464 auto ptr = os2.constData();
465 quint16 fsSelection = qFromBigEndian<quint16>(ptr + 62);
466 qint16 typoAscent = qFromBigEndian<qint16>(ptr + 68);
467 qint16 typoDescent = qFromBigEndian<qint16>(ptr + 70);
468 qint16 typoLineGap = qFromBigEndian<qint16>(ptr + 72);
469 quint16 winAscent = qFromBigEndian<quint16>(ptr + 74);
470 quint16 winDescent = qFromBigEndian<quint16>(ptr + 76);
471
472 enum { USE_TYPO_METRICS = 0x80 };
473 const qreal unitsPerEm = emSquareSize().toReal();
474 if (preferTypoLineMetrics() || fsSelection & USE_TYPO_METRICS) {
475 // Some fonts may have invalid OS/2 data. We detect this and bail out.
476 if (typoAscent == 0 && typoDescent == 0)
477 return false;
478 // Bail out if values are too large for QFixed
479 const auto limitForQFixed = qreal(std::numeric_limits<int>::max() >> 6) / fontDef.pixelSize;
480 if (typoAscent > limitForQFixed || typoDescent > limitForQFixed
481 || typoLineGap > limitForQFixed)
482 return false;
483 m_ascent = QFixed::fromReal(typoAscent * fontDef.pixelSize / unitsPerEm);
484 m_descent = -QFixed::fromReal(typoDescent * fontDef.pixelSize / unitsPerEm);
485 m_leading = QFixed::fromReal(typoLineGap * fontDef.pixelSize / unitsPerEm);
486 } else {
487 // Some fonts may have invalid OS/2 data. We detect this and bail out.
488 if (winAscent == 0 && winDescent == 0)
489 return false;
490 const auto limitForQFixed = qreal(std::numeric_limits<int>::max() >> 6) / fontDef.pixelSize;
491 if (winAscent > limitForQFixed || winDescent > limitForQFixed)
492 return false;
493 m_ascent = QFixed::fromReal(winAscent * fontDef.pixelSize / unitsPerEm);
494 m_descent = QFixed::fromReal(winDescent * fontDef.pixelSize / unitsPerEm);
495 m_leading = QFixed{};
496 }
497
498 return true;
499 }
500
501 return false;
502}
503
504QFixed QFontEngine::leading() const
505{
506 if (!m_heightMetricsQueried)
507 initializeHeightMetrics();
508
509 return m_leading;
510}
511
512
513QFixed QFontEngine::emSquareSize() const
514{
515 qCWarning(lcQpaFonts) << "Font engine does not reimplement emSquareSize(). Returning minimum value.";
516 return 16;
517}
518
519QFixed QFontEngine::ascent() const
520{
521 if (!m_heightMetricsQueried)
522 initializeHeightMetrics();
523
524 return m_ascent;
525}
526
527QFixed QFontEngine::descent() const
528{
529 if (!m_heightMetricsQueried)
530 initializeHeightMetrics();
531
532 return m_descent;
533}
534
535qreal QFontEngine::minLeftBearing() const
536{
537 if (m_minLeftBearing == kBearingNotInitialized)
538 minRightBearing(); // Initializes both (see below)
539
540 return m_minLeftBearing;
541}
542
543#define kMinLeftSideBearingOffset 12
544#define kMinRightSideBearingOffset 14
545
546qreal QFontEngine::minRightBearing() const
547{
548 if (m_minRightBearing == kBearingNotInitialized) {
549
550 // Try the 'hhea' font table first, which covers the entire font
551 QByteArray hheaTable = getSfntTable(QFont::Tag("hhea").value());
552 if (hheaTable.size() >= int(kMinRightSideBearingOffset + sizeof(qint16))) {
553 const uchar *tableData = reinterpret_cast<const uchar *>(hheaTable.constData());
554
555 const quint32 tableVersion = qFromBigEndian<quint32>(tableData);
556 if (tableVersion == 0x00010000) {
557 const qint16 minLeftSideBearing = qFromBigEndian<qint16>(tableData + kMinLeftSideBearingOffset);
558 const qint16 minRightSideBearing = qFromBigEndian<qint16>(tableData + kMinRightSideBearingOffset);
559
560 // The table data is expressed as FUnits, meaning we have to take the number
561 // of units per em into account. Since pixelSize already has taken DPI into
562 // account we can use that directly instead of the point size.
563 const int unitsPerEm = emSquareSize().toInt();
564 if (unitsPerEm > 0) {
565 const qreal funitToPixelFactor = fontDef.pixelSize / unitsPerEm;
566
567 // Some fonts on OS X (such as Gurmukhi Sangam MN, Khmer MN, Lao Sangam MN, etc.), have
568 // invalid values for their NBSPACE left bearing, causing the 'hhea' minimum bearings to
569 // be way off. We detect this by assuming that the minimum bearings are within a certain
570 // range of the em square size.
571 const int largestValidBearing = 4 * unitsPerEm;
572
573 if (qAbs(int(minLeftSideBearing)) < largestValidBearing)
574 m_minLeftBearing = minLeftSideBearing * funitToPixelFactor;
575 if (qAbs(int(minRightSideBearing)) < largestValidBearing)
576 m_minRightBearing = minRightSideBearing * funitToPixelFactor;
577 }
578 }
579 }
580
581 // Fallback in case of missing 'hhea' table (bitmap fonts e.g.) or broken 'hhea' values
582 if (m_minLeftBearing == kBearingNotInitialized || m_minRightBearing == kBearingNotInitialized) {
583
584 // To balance performance and correctness we only look at a subset of the
585 // possible glyphs in the font, based on which characters are more likely
586 // to have a left or right bearing.
587 static const ushort characterSubset[] = {
588 '(', 'C', 'F', 'K', 'V', 'X', 'Y', ']', '_', 'f', 'r', '|',
589 127, 205, 645, 884, 922, 1070, 12386
590 };
591
592 // The font may have minimum bearings larger than 0, so we have to start at the max
593 m_minLeftBearing = m_minRightBearing = std::numeric_limits<qreal>::max();
594
595 for (uint i = 0; i < (sizeof(characterSubset) / sizeof(ushort)); ++i) {
596 const glyph_t glyph = glyphIndex(characterSubset[i]);
597 if (!glyph)
598 continue;
599
600 glyph_metrics_t glyphMetrics = const_cast<QFontEngine *>(this)->boundingBox(glyph);
601
602 // Glyphs with no contours shouldn't contribute to bearings
603 if (!glyphMetrics.width || !glyphMetrics.height)
604 continue;
605
606 m_minLeftBearing = qMin(m_minLeftBearing, glyphMetrics.leftBearing().toReal());
607 m_minRightBearing = qMin(m_minRightBearing, glyphMetrics.rightBearing().toReal());
608 }
609 }
610
611 if (m_minLeftBearing == kBearingNotInitialized || m_minRightBearing == kBearingNotInitialized) {
612 qWarning() << "Failed to compute left/right minimum bearings for"
613 << fontDef.family();
614
615 // Return an arbitrarily large value, but make it smaller than DBL_MAX to avoid
616 // redoing the check over and over.
617 m_minRightBearing = qreal(QFIXED_MAX);
618 m_minLeftBearing = qreal(QFIXED_MAX);
619 }
620 }
621
622 return m_minRightBearing;
623}
624
625glyph_metrics_t QFontEngine::boundingBox(const QGlyphLayout &glyphs)
626{
627 QFixed w;
628 for (int i = 0; i < glyphs.numGlyphs; ++i)
629 w += glyphs.effectiveAdvance(i);
630 const QFixed leftBearing = firstLeftBearing(glyphs);
631 const QFixed rightBearing = lastRightBearing(glyphs);
632 return glyph_metrics_t(leftBearing, -(ascent()), w - leftBearing - rightBearing, ascent() + descent(), w, 0);
633}
634
635glyph_metrics_t QFontEngine::tightBoundingBox(const QGlyphLayout &glyphs, QTextItem::RenderFlags flags)
636{
637 glyph_metrics_t overall;
638
639 const bool isRtl = flags & QTextItem::RightToLeft;
640 if (isRtl) {
641 for (int i = 0; i < glyphs.numGlyphs; i++) {
642 // If shaping has found this should be ignored, ignore it.
643 if (glyphs.attributes[i].dontPrint)
644 continue;
645
646 overall.xoff += glyphs.effectiveAdvance(i);
647 }
648 }
649
650 QFixed ymax = 0;
651 QFixed xmax = 0;
652 for (int i = 0; i < glyphs.numGlyphs; i++) {
653 // If shaping has found this should be ignored, ignore it.
654 if (glyphs.attributes[i].dontPrint)
655 continue;
656
657 glyph_metrics_t bb = boundingBox(glyphs.glyphs[i]);
658
659 if (isRtl)
660 overall.xoff -= glyphs.effectiveAdvance(i);
661
662 QFixed x = overall.xoff + glyphs.offsets[i].x + bb.x;
663 QFixed y = overall.yoff + glyphs.offsets[i].y + bb.y;
664
665 overall.x = qMin(overall.x, x);
666 overall.y = qMin(overall.y, y);
667 xmax = qMax(xmax, x.ceil() + bb.width);
668 ymax = qMax(ymax, y.ceil() + bb.height);
669
670 if (!isRtl)
671 overall.xoff += glyphs.effectiveAdvance(i);
672 overall.yoff += bb.yoff;
673 }
674 overall.height = qMax(overall.height, ymax - overall.y);
675 overall.width = xmax - overall.x;
676
677 return overall;
678}
679
680
681void QFontEngine::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path,
682 QTextItem::RenderFlags flags)
683{
684 if (!glyphs.numGlyphs)
685 return;
686
687 QVarLengthArray<QFixedPoint> positions;
688 QVarLengthArray<glyph_t> positioned_glyphs;
689 QTransform matrix = QTransform::fromTranslate(x, y);
690 getGlyphPositions(glyphs, matrix, flags, positioned_glyphs, positions);
691 addGlyphsToPath(positioned_glyphs.data(), positions.data(), positioned_glyphs.size(), path, flags);
692}
693
694#define GRID(x, y) grid[(y)*(w+1) + (x)]
695#define SET(x, y) (*(image_data + (y)*bpl + ((x) >> 3)) & (0x80 >> ((x) & 7)))
696
697enum { EdgeRight = 0x1,
698 EdgeDown = 0x2,
699 EdgeLeft = 0x4,
700 EdgeUp = 0x8
701};
702
703static void collectSingleContour(qreal x0, qreal y0, uint *grid, int x, int y, int w, int h, QPainterPath *path)
704{
705 Q_UNUSED(h);
706
707 path->moveTo(x + x0, y + y0);
708 while (GRID(x, y)) {
709 if (GRID(x, y) & EdgeRight) {
710 while (GRID(x, y) & EdgeRight) {
711 GRID(x, y) &= ~EdgeRight;
712 ++x;
713 }
714 Q_ASSERT(x <= w);
715 path->lineTo(x + x0, y + y0);
716 continue;
717 }
718 if (GRID(x, y) & EdgeDown) {
719 while (GRID(x, y) & EdgeDown) {
720 GRID(x, y) &= ~EdgeDown;
721 ++y;
722 }
723 Q_ASSERT(y <= h);
724 path->lineTo(x + x0, y + y0);
725 continue;
726 }
727 if (GRID(x, y) & EdgeLeft) {
728 while (GRID(x, y) & EdgeLeft) {
729 GRID(x, y) &= ~EdgeLeft;
730 --x;
731 }
732 Q_ASSERT(x >= 0);
733 path->lineTo(x + x0, y + y0);
734 continue;
735 }
736 if (GRID(x, y) & EdgeUp) {
737 while (GRID(x, y) & EdgeUp) {
738 GRID(x, y) &= ~EdgeUp;
739 --y;
740 }
741 Q_ASSERT(y >= 0);
742 path->lineTo(x + x0, y + y0);
743 continue;
744 }
745 }
746 path->closeSubpath();
747}
748
749Q_GUI_EXPORT void qt_addBitmapToPath(qreal x0, qreal y0, const uchar *image_data, int bpl, int w, int h, QPainterPath *path)
750{
751 uint *grid = new uint[(w+1)*(h+1)];
752 // set up edges
753 for (int y = 0; y <= h; ++y) {
754 for (int x = 0; x <= w; ++x) {
755 bool topLeft = (x == 0 || y == 0) ? false : SET(x - 1, y - 1);
756 bool topRight = (x == w || y == 0) ? false : SET(x, y - 1);
757 bool bottomLeft = (x == 0 || y == h) ? false : SET(x - 1, y);
758 bool bottomRight = (x == w || y == h) ? false : SET(x, y);
759
760 GRID(x, y) = 0;
761 if ((!topRight) & bottomRight)
762 GRID(x, y) |= EdgeRight;
763 if ((!bottomRight) & bottomLeft)
764 GRID(x, y) |= EdgeDown;
765 if ((!bottomLeft) & topLeft)
766 GRID(x, y) |= EdgeLeft;
767 if ((!topLeft) & topRight)
768 GRID(x, y) |= EdgeUp;
769 }
770 }
771
772 // collect edges
773 for (int y = 0; y < h; ++y) {
774 for (int x = 0; x < w; ++x) {
775 if (!GRID(x, y))
776 continue;
777 // found start of a contour, follow it
778 collectSingleContour(x0, y0, grid, x, y, w, h, path);
779 }
780 }
781 delete [] grid;
782}
783
784#undef GRID
785#undef SET
786
787
788void QFontEngine::addBitmapFontToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
789 QPainterPath *path, QTextItem::RenderFlags flags)
790{
791// TODO what to do with 'flags' ??
792 Q_UNUSED(flags);
793 QFixed advanceX = QFixed::fromReal(x);
794 QFixed advanceY = QFixed::fromReal(y);
795 for (int i=0; i < glyphs.numGlyphs; ++i) {
796 glyph_metrics_t metrics = boundingBox(glyphs.glyphs[i]);
797 if (metrics.width.value() == 0 || metrics.height.value() == 0) {
798 advanceX += glyphs.advances[i];
799 continue;
800 }
801 const QImage alphaMask = alphaMapForGlyph(glyphs.glyphs[i]);
802
803 const int w = alphaMask.width();
804 const int h = alphaMask.height();
805 const qsizetype srcBpl = alphaMask.bytesPerLine();
806 QImage bitmap;
807 if (alphaMask.depth() == 1) {
808 bitmap = alphaMask;
809 } else {
810 bitmap = QImage(w, h, QImage::Format_Mono);
811 const uchar *imageData = alphaMask.bits();
812 const qsizetype destBpl = bitmap.bytesPerLine();
813 uchar *bitmapData = bitmap.bits();
814
815 for (int yi = 0; yi < h; ++yi) {
816 const uchar *src = imageData + yi*srcBpl;
817 uchar *dst = bitmapData + yi*destBpl;
818 for (int xi = 0; xi < w; ++xi) {
819 const int byte = xi / 8;
820 const int bit = xi % 8;
821 if (bit == 0)
822 dst[byte] = 0;
823 if (src[xi])
824 dst[byte] |= 128 >> bit;
825 }
826 }
827 }
828 const uchar *bitmap_data = bitmap.constBits();
829 QFixedPoint offset = glyphs.offsets[i];
830 advanceX += offset.x;
831 advanceY += offset.y;
832 qt_addBitmapToPath((advanceX + metrics.x).toReal(), (advanceY + metrics.y).toReal(), bitmap_data, bitmap.bytesPerLine(), w, h, path);
833 advanceX += glyphs.advances[i];
834 }
835}
836
837void QFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nGlyphs,
838 QPainterPath *path, QTextItem::RenderFlags flags)
839{
840 qreal x = positions[0].x.toReal();
841 qreal y = positions[0].y.toReal();
842 QVarLengthGlyphLayoutArray g(nGlyphs);
843
844 for (int i = 0; i < nGlyphs - 1; ++i) {
845 g.glyphs[i] = glyphs[i];
846 g.advances[i] = positions[i + 1].x - positions[i].x;
847 }
848 g.glyphs[nGlyphs - 1] = glyphs[nGlyphs - 1];
849 g.advances[nGlyphs - 1] = QFixed::fromReal(maxCharWidth());
850
851 addBitmapFontToPath(x, y, g, path, flags);
852}
853
854QImage QFontEngine::alphaMapForGlyph(glyph_t glyph, const QFixedPoint &/*subPixelPosition*/)
855{
856 // For font engines don't support subpixel positioning
857 return alphaMapForGlyph(glyph);
858}
859
860QImage QFontEngine::alphaMapForGlyph(glyph_t glyph, const QTransform &t)
861{
862 if (t.type() > QTransform::TxTranslate && glyphTransformExceedsLimit(glyph, t))
863 return QImage();
864
865 QImage i = alphaMapForGlyph(glyph);
866 if (t.type() > QTransform::TxTranslate)
867 i = i.transformed(t).convertToFormat(QImage::Format_Alpha8);
868 Q_ASSERT(i.depth() <= 8); // To verify that transformed didn't change the format...
869
870 return i;
871}
872
873QImage QFontEngine::alphaMapForGlyph(glyph_t glyph, const QFixedPoint &subPixelPosition, const QTransform &t)
874{
875 if (!supportsHorizontalSubPixelPositions() && !supportsVerticalSubPixelPositions())
876 return alphaMapForGlyph(glyph, t);
877
878 if (t.type() > QTransform::TxTranslate && glyphTransformExceedsLimit(glyph, t))
879 return QImage();
880
881 QImage i = alphaMapForGlyph(glyph, subPixelPosition);
882 if (t.type() > QTransform::TxTranslate)
883 i = i.transformed(t).convertToFormat(QImage::Format_Alpha8);
884 Q_ASSERT(i.depth() <= 8); // To verify that transformed didn't change the format...
885
886 return i;
887}
888
889QImage QFontEngine::alphaRGBMapForGlyph(glyph_t glyph, const QFixedPoint &/*subPixelPosition*/, const QTransform &t)
890{
891 const QImage alphaMask = alphaMapForGlyph(glyph, t);
892 QImage rgbMask(alphaMask.width(), alphaMask.height(), QImage::Format_RGB32);
893
894 for (int y=0; y<alphaMask.height(); ++y) {
895 uint *dst = (uint *) rgbMask.scanLine(y);
896 const uchar *src = alphaMask.constScanLine(y);
897 for (int x=0; x<alphaMask.width(); ++x) {
898 int val = src[x];
899 dst[x] = qRgb(val, val, val);
900 }
901 }
902
903 return rgbMask;
904}
905
906QImage QFontEngine::bitmapForGlyph(glyph_t, const QFixedPoint &subPixelPosition, const QTransform&, const QColor &)
907{
908 Q_UNUSED(subPixelPosition);
909
910 return QImage();
911}
912
913QFixedPoint QFontEngine::subPixelPositionFor(const QFixedPoint &position) const
914{
915 if (m_subPixelPositionCount <= 1
916 || (!supportsHorizontalSubPixelPositions()
917 && !supportsVerticalSubPixelPositions())) {
918 return QFixedPoint();
919 }
920
921 auto f = [&](QFixed v) {
922 if (v != 0) {
923 v = v - v.floor() + QFixed::fromFixed(1);
924 QFixed fraction = (v * m_subPixelPositionCount).floor();
925 v = fraction / QFixed(m_subPixelPositionCount);
926 }
927 return v;
928 };
929
930 return QFixedPoint(f(position.x), f(position.y));
931}
932
933QFontEngine::Glyph *QFontEngine::glyphData(glyph_t,
934 const QFixedPoint &,
935 QFontEngine::GlyphFormat,
936 const QTransform &)
937{
938 return nullptr;
939}
940
941#if QT_CONFIG(harfbuzz)
942template <typename Functor>
943auto queryHarfbuzz(const QFontEngine *engine, Functor &&func)
944{
945 decltype(func(nullptr)) result = {};
946
947 hb_face_t *hbFace = hb_qt_face_get_for_engine(const_cast<QFontEngine *>(engine));
948 if (hb_font_t *hbFont = hb_font_create(hbFace)) {
949 // explicitly use OpenType handlers for this font
950 hb_ot_font_set_funcs(hbFont);
951
952 result = func(hbFont);
953
954 hb_font_destroy(hbFont);
955 }
956
957 return result;
958}
959#endif
960
961QString QFontEngine::glyphName(glyph_t index) const
962{
963 QString result;
964 if (index >= glyph_t(glyphCount()))
965 return result;
966
967#if QT_CONFIG(harfbuzz)
968 result = queryHarfbuzz(this, [index](hb_font_t *hbFont){
969 QString result;
970 // According to the OpenType specification, glyph names are limited to 63
971 // characters and can only contain (a subset of) ASCII.
972 char name[64];
973 if (hb_font_get_glyph_name(hbFont, index, name, sizeof(name)))
974 result = QString::fromLatin1(name);
975 return result;
976 });
977#endif
978
979 if (result.isEmpty())
980 result = index ? u"gid%1"_s.arg(index) : u".notdef"_s;
981 return result;
982}
983
984glyph_t QFontEngine::findGlyph(QLatin1StringView name) const
985{
986 glyph_t result = 0;
987
988#if QT_CONFIG(harfbuzz)
989 result = queryHarfbuzz(this, [name](hb_font_t *hbFont){
990 // glyph names are all ASCII, so latin1 is fine here.
991 hb_codepoint_t glyph;
992 if (hb_font_get_glyph_from_name(hbFont, name.constData(), name.size(), &glyph))
993 return glyph_t(glyph);
994 return glyph_t(0);
995 });
996#else // if we are here, no point in trying again if we already tried harfbuzz
997 if (!result) {
998 for (glyph_t index = 0; index < uint(glyphCount()); ++index) {
999 if (name == glyphName(index))
1000 return index;
1001 }
1002 }
1003#endif
1004
1005 if (!result) {
1006 constexpr auto gid = "gid"_L1;
1007 constexpr auto uni = "uni"_L1;
1008 if (name.startsWith(gid)) {
1009 bool ok;
1010 result = name.slice(gid.size()).toUInt(&ok);
1011 if (ok && result < glyph_t(glyphCount()))
1012 return result;
1013 } else if (name.startsWith(uni)) {
1014 bool ok;
1015 const uint ucs4 = name.slice(uni.size()).toUInt(&ok, 16);
1016 if (ok) {
1017 result = glyphIndex(ucs4);
1018 if (result > 0 && result < glyph_t(glyphCount()))
1019 return result;
1020 }
1021 }
1022 }
1023
1024 return result;
1025}
1026
1027// Maximum glyph size (in pixels per side) we are willing to rasterize. Defaults
1028// to 4096; overridable via QT_MAX_GLYPH_SIZE, where a value <= 0 disables the check.
1029static int maxGlyphSize()
1030{
1031 static const int size = []() {
1032 bool ok = false;
1033 const int value = qEnvironmentVariableIntValue("QT_MAX_GLYPH_SIZE", &ok);
1034 return ok ? value : 4096;
1035 }();
1036 return size;
1037}
1038
1039qreal QFontEngine::effectivePixelSizeSquared(const QTransform &transform) const
1040{
1041 return fontDef.pixelSize * fontDef.pixelSize * qAbs(transform.determinant());
1042}
1043
1044bool QFontEngine::glyphBoundingBoxExceedsLimit(qreal glyphWidth,
1045 qreal glyphHeight,
1046 qreal effectivePixelSizeSquared)
1047{
1048 const int limit = maxGlyphSize();
1049 if (limit <= 0) // the check is disabled
1050 return false;
1051
1052 const qreal limitSquared = qreal(limit) * limit;
1053
1054 // The font size itself is beyond what we are willing to rasterize.
1055 bool hasExceeded = (effectivePixelSizeSquared > limitSquared);
1056
1057 if (!hasExceeded) {
1058 // Otherwise a glyph may extend up to 16x the effective pixel size. We never reject sizes less
1059 // than 256 pixels on this basis (to leave room for oversized glyphs at small sizes). This
1060 // leaves space for glyphs that stretch outside the em square while still protecting against
1061 // dramatically malformed glyphs.
1062 constexpr qreal glyphSizeFactorSquared = 16 * 16;
1063 constexpr qreal glyphSizeFloorSquared = 256 * 256;
1064 const qreal maxDimensionSquared =
1065 qMin(limitSquared,
1066 qMax(glyphSizeFloorSquared, glyphSizeFactorSquared * effectivePixelSizeSquared));
1067
1068 hasExceeded = glyphWidth * glyphWidth > maxDimensionSquared
1069 || glyphHeight * glyphHeight > maxDimensionSquared;
1070 }
1071
1072 if (hasExceeded) {
1073 static bool warned = false;
1074 if (!warned) {
1075 warned = true;
1076 qCWarning(lcFontMatch,
1077 "Glyph with bounding box (%.0fx%.0f pixels) and requested effective pixel "
1078 "size of %.0f is too large for rasterizer. Set QT_MAX_GLYPH_SIZE=0 to "
1079 "disable the limit.",
1080 glyphWidth, glyphHeight, sqrt(effectivePixelSizeSquared));
1081 }
1082 }
1083
1084 return hasExceeded;
1085}
1086
1087bool QFontEngine::glyphTransformExceedsLimit(glyph_t glyph, const QTransform &transform)
1088{
1089 const glyph_metrics_t gm = boundingBox(glyph, transform);
1090 return glyphBoundingBoxExceedsLimit(gm.width.toReal(), gm.height.toReal(),
1091 effectivePixelSizeSquared(transform));
1092}
1093
1094QImage QFontEngine::renderedPathForGlyph(glyph_t glyph, const QColor &color)
1095{
1096 glyph_metrics_t gm = boundingBox(glyph);
1097 int glyph_x = qFloor(gm.x.toReal());
1098 int glyph_y = qFloor(gm.y.toReal());
1099 int glyph_width = qCeil((gm.x + gm.width).toReal()) - glyph_x;
1100 int glyph_height = qCeil((gm.y + gm.height).toReal()) - glyph_y;
1101
1102 if (glyph_width <= 0
1103 || glyph_height <= 0
1104 || glyphBoundingBoxExceedsLimit(glyph_width,
1105 glyph_height,
1106 fontDef.pixelSize * fontDef.pixelSize)) {
1107 return QImage();
1108 }
1109
1110 QFixedPoint pt;
1111 pt.x = -glyph_x;
1112 pt.y = -glyph_y; // the baseline
1113 QPainterPath path;
1114 path.setFillRule(Qt::WindingFill);
1115 QImage im(glyph_width, glyph_height, QImage::Format_ARGB32_Premultiplied);
1116 im.fill(Qt::transparent);
1117 QPainter p(&im);
1118 p.setRenderHint(QPainter::Antialiasing);
1119 addGlyphsToPath(&glyph, &pt, 1, &path, { });
1120 p.setPen(Qt::NoPen);
1121 p.setBrush(color);
1122 p.drawPath(path);
1123 p.end();
1124
1125 return im;
1126}
1127
1128QImage QFontEngine::alphaMapForGlyph(glyph_t glyph)
1129{
1130 QImage im = renderedPathForGlyph(glyph, Qt::black);
1131 QImage alphaMap(im.width(), im.height(), QImage::Format_Alpha8);
1132
1133 for (int y=0; y<im.height(); ++y) {
1134 uchar *dst = (uchar *) alphaMap.scanLine(y);
1135 const uint *src = reinterpret_cast<const uint *>(im.constScanLine(y));
1136 for (int x=0; x<im.width(); ++x)
1137 dst[x] = qAlpha(src[x]);
1138 }
1139
1140 return alphaMap;
1141}
1142
1143void QFontEngine::removeGlyphFromCache(glyph_t)
1144{
1145}
1146
1147QFontEngine::Properties QFontEngine::properties() const
1148{
1149 Properties p;
1150 p.postscriptName =
1151 QFontEngine::convertToPostscriptFontFamilyName(fontDef.family().toUtf8()) + '-'
1152 + QByteArray::number(fontDef.style) + '-' + QByteArray::number(fontDef.weight);
1153 p.ascent = ascent();
1154 p.descent = descent();
1155 p.leading = leading();
1156 p.emSquare = p.ascent;
1157 p.boundingBox = QRectF(0, -p.ascent.toReal(), maxCharWidth(), (p.ascent + p.descent).toReal());
1158 p.italicAngle = 0;
1159 p.capHeight = p.ascent;
1160 p.lineWidth = lineThickness();
1161 return p;
1162}
1163
1164void QFontEngine::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
1165{
1166 *metrics = boundingBox(glyph);
1167 QFixedPoint p;
1168 p.x = 0;
1169 p.y = 0;
1170 addGlyphsToPath(&glyph, &p, 1, path, QFlag(0));
1171}
1172
1173/*!
1174 \internal
1175 Returns \c true if the font table idetified by \a tag exists in the font;
1176 returns \c false otherwise.
1177
1178 If \a buffer is \nullptr, stores the size of the buffer required for the font table data,
1179 in bytes, in \a length. If \a buffer is not \nullptr and the capacity
1180 of the buffer, passed in \a length, is sufficient to store the font table data,
1181 also copies the font table data to \a buffer.
1182
1183 Note: returning \c false when the font table exists could lead to an undefined behavior.
1184*/
1185bool QFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const
1186{
1187 Q_UNUSED(tag);
1188 Q_UNUSED(buffer);
1189 Q_UNUSED(length);
1190 return false;
1191}
1192
1193QByteArray QFontEngine::getSfntTable(uint tag) const
1194{
1195 QByteArray table;
1196 uint len = 0;
1197 if (!getSfntTableData(tag, nullptr, &len))
1198 return table;
1199 table.resize(len);
1200 if (!getSfntTableData(tag, reinterpret_cast<uchar *>(table.data()), &len))
1201 return QByteArray();
1202 return table;
1203}
1204
1205void QFontEngine::clearGlyphCache(const void *context)
1206{
1207 m_glyphCaches.remove(context);
1208}
1209
1210void QFontEngine::setGlyphCache(const void *context, QFontEngineGlyphCache *cache)
1211{
1212 Q_ASSERT(cache);
1213
1214 GlyphCaches &caches = m_glyphCaches[context];
1215 for (auto & e : caches) {
1216 if (cache == e.cache.data())
1217 return;
1218 }
1219
1220 // Limit the glyph caches to 4 per context. This covers all 90 degree rotations,
1221 // and limits memory use when there is continuous or random rotation
1222 if (caches.size() == 4)
1223 caches.pop_back();
1224
1225 GlyphCacheEntry entry;
1226 entry.cache = cache;
1227 caches.push_front(entry);
1228
1229}
1230
1231QFontEngineGlyphCache *QFontEngine::glyphCache(const void *context,
1232 GlyphFormat format,
1233 const QTransform &transform,
1234 const QColor &color) const
1235{
1236 const QHash<const void*, GlyphCaches>::const_iterator caches = m_glyphCaches.constFind(context);
1237 if (caches == m_glyphCaches.cend())
1238 return nullptr;
1239
1240 for (auto &e : *caches) {
1241 QFontEngineGlyphCache *cache = e.cache.data();
1242 if (format == cache->glyphFormat()
1243 && (format != Format_ARGB || color == cache->color())
1244 && qtransform_equals_no_translate(cache->m_transform, transform)) {
1245 return cache;
1246 }
1247 }
1248
1249 return nullptr;
1250}
1251
1252static inline QFixed kerning(int left, int right, const QFontEngine::KernPair *pairs, int numPairs)
1253{
1254 uint left_right = (left << 16) + right;
1255
1256 left = 0, right = numPairs - 1;
1257 while (left <= right) {
1258 int middle = left + ( ( right - left ) >> 1 );
1259
1260 if (pairs[middle].left_right == left_right)
1261 return pairs[middle].adjust;
1262
1263 if (pairs[middle].left_right < left_right)
1264 left = middle + 1;
1265 else
1266 right = middle - 1;
1267 }
1268 return 0;
1269}
1270
1271void QFontEngine::doKerning(QGlyphLayout *glyphs, QFontEngine::ShaperFlags flags) const
1272{
1273 int numPairs = kerning_pairs.size();
1274 if (!numPairs)
1275 return;
1276
1277 const KernPair *pairs = kerning_pairs.constData();
1278
1279 if (flags & DesignMetrics) {
1280 for(int i = 0; i < glyphs->numGlyphs - 1; ++i)
1281 glyphs->advances[i] += kerning(glyphs->glyphs[i], glyphs->glyphs[i+1] , pairs, numPairs);
1282 } else {
1283 for(int i = 0; i < glyphs->numGlyphs - 1; ++i)
1284 glyphs->advances[i] += qRound(kerning(glyphs->glyphs[i], glyphs->glyphs[i+1] , pairs, numPairs));
1285 }
1286}
1287
1288void QFontEngine::loadKerningPairs(QFixed scalingFactor)
1289{
1290 kerning_pairs.clear();
1291
1292 QByteArray tab = getSfntTable(QFont::Tag("kern").value());
1293 if (tab.isEmpty())
1294 return;
1295
1296 const uchar *table = reinterpret_cast<const uchar *>(tab.constData());
1297 const uchar *end = table + tab.size();
1298
1299 quint16 version;
1300 if (!qSafeFromBigEndian(table, end, &version))
1301 return;
1302
1303 if (version != 0) {
1304// qDebug("wrong version");
1305 return;
1306 }
1307
1308 quint16 numTables;
1309 if (!qSafeFromBigEndian(table + 2, end, &numTables))
1310 return;
1311
1312 {
1313 int offset = 4;
1314 for(int i = 0; i < numTables; ++i) {
1315 const uchar *header = table + offset;
1316
1317 quint16 version;
1318 if (!qSafeFromBigEndian(header, end, &version))
1319 goto end;
1320
1321 quint16 length;
1322 if (!qSafeFromBigEndian(header + 2, end, &length))
1323 goto end;
1324
1325 quint16 coverage;
1326 if (!qSafeFromBigEndian(header + 4, end, &coverage))
1327 goto end;
1328
1329// qDebug("subtable: version=%d, coverage=%x",version, coverage);
1330 if (version == 0 && coverage == 0x0001) {
1331 if (offset + length > tab.size()) {
1332// qDebug("length ouf ot bounds");
1333 goto end;
1334 }
1335 const uchar *data = table + offset + 6;
1336
1337 quint16 nPairs;
1338 if (!qSafeFromBigEndian(data, end, &nPairs))
1339 goto end;
1340
1341 if (nPairs * 6 + 8 > length - 6) {
1342// qDebug("corrupt table!");
1343 // corrupt table
1344 goto end;
1345 }
1346
1347 int off = 8;
1348 for(int i = 0; i < nPairs; ++i) {
1349 QFontEngine::KernPair p;
1350
1351 quint16 tmp;
1352 if (!qSafeFromBigEndian(data + off, end, &tmp))
1353 goto end;
1354
1355 p.left_right = uint(tmp) << 16;
1356 if (!qSafeFromBigEndian(data + off + 2, end, &tmp))
1357 goto end;
1358
1359 p.left_right |= tmp;
1360
1361 if (!qSafeFromBigEndian(data + off + 4, end, &tmp))
1362 goto end;
1363
1364 p.adjust = QFixed(int(short(tmp))) / scalingFactor;
1365 kerning_pairs.append(p);
1366 off += 6;
1367 }
1368 }
1369 offset += length;
1370 }
1371 }
1372end:
1373 std::sort(kerning_pairs.begin(), kerning_pairs.end());
1374// for (int i = 0; i < kerning_pairs.count(); ++i)
1375// qDebug() << 'i' << i << "left_right" << Qt::hex << kerning_pairs.at(i).left_right;
1376}
1377
1378bool QFontEngine::hasHinting() const
1379{
1380 if (m_hasHinting < 0) {
1381 m_hasHinting = false;
1382
1383 const QByteArray maxpTable = getSfntTable(QFont::Tag("maxp").value());
1384 if (maxpTable.size() >= 28) {
1385 const uchar *start = reinterpret_cast<const uchar *>(maxpTable.constData());
1386 const quint32 version = qFromBigEndian<quint32>(start);
1387
1388 if (version == 0x00010000) {
1389 const quint16 maxSizeOfInstructions = qFromBigEndian<quint16>(start + 26);
1390 m_hasHinting = maxSizeOfInstructions > 0;
1391 } else {
1392 // If unrecognized maxp table, assume we might have hinting
1393 qDebug("maxp table of format %d not implemented. Assuming hinting exists.",
1394 version);
1395 m_hasHinting = true;
1396 }
1397 }
1398 }
1399
1400 return m_hasHinting;
1401}
1402
1403int QFontEngine::glyphCount() const
1404{
1405 QByteArray maxpTable = getSfntTable(QFont::Tag("maxp").value());
1406 if (maxpTable.size() < 6)
1407 return 0;
1408
1409 const uchar *start = reinterpret_cast<const uchar *>(maxpTable.constData());
1410 const uchar *end = start + maxpTable.size();
1411 const uchar *source = reinterpret_cast<const uchar *>(start + 4);
1412
1413 quint16 count = 0;
1414 qSafeFromBigEndian(source, end, &count);
1415 return count;
1416}
1417
1418Qt::HANDLE QFontEngine::handle() const
1419{
1420 return nullptr;
1421}
1422
1423const uchar *QFontEngine::getCMap(const uchar *table, uint tableSize, bool *isSymbolFont, int *cmapSize)
1424{
1425 const uchar *header = table;
1426 const uchar *endPtr = table + tableSize;
1427
1428 // version check
1429 quint16 version;
1430 if (!qSafeFromBigEndian(header, endPtr, &version) || version != 0)
1431 return nullptr;
1432
1433 quint16 numTables;
1434 if (!qSafeFromBigEndian(header + 2, endPtr, &numTables))
1435 return nullptr;
1436
1437 const uchar *maps = table + 4;
1438
1439 enum {
1440 Invalid,
1441 AppleRoman,
1442 Symbol,
1443 Unicode11,
1444 Unicode,
1445 MicrosoftUnicode,
1446 MicrosoftUnicodeExtended
1447 };
1448
1449 int symbolTable = -1;
1450 int tableToUse = -1;
1451 int score = Invalid;
1452 for (int n = 0; n < numTables; ++n) {
1453 quint16 platformId = 0;
1454 if (!qSafeFromBigEndian(maps + 8 * n, endPtr, &platformId))
1455 return nullptr;
1456
1457 quint16 platformSpecificId = 0;
1458 if (!qSafeFromBigEndian(maps + 8 * n + 2, endPtr, &platformSpecificId))
1459 return nullptr;
1460
1461 switch (platformId) {
1462 case 0: // Unicode
1463 if (score < Unicode &&
1464 (platformSpecificId == 0 ||
1465 platformSpecificId == 2 ||
1466 platformSpecificId == 3)) {
1467 tableToUse = n;
1468 score = Unicode;
1469 } else if (score < Unicode11 && platformSpecificId == 1) {
1470 tableToUse = n;
1471 score = Unicode11;
1472 }
1473 break;
1474 case 1: // Apple
1475 if (score < AppleRoman && platformSpecificId == 0) { // Apple Roman
1476 tableToUse = n;
1477 score = AppleRoman;
1478 }
1479 break;
1480 case 3: // Microsoft
1481 switch (platformSpecificId) {
1482 case 0:
1483 symbolTable = n;
1484 if (score < Symbol) {
1485 tableToUse = n;
1486 score = Symbol;
1487 }
1488 break;
1489 case 1:
1490 if (score < MicrosoftUnicode) {
1491 tableToUse = n;
1492 score = MicrosoftUnicode;
1493 }
1494 break;
1495 case 0xa:
1496 if (score < MicrosoftUnicodeExtended) {
1497 tableToUse = n;
1498 score = MicrosoftUnicodeExtended;
1499 }
1500 break;
1501 default:
1502 break;
1503 }
1504 break;
1505 default:
1506 break;
1507 }
1508 }
1509 if (tableToUse < 0)
1510 return nullptr;
1511
1512resolveTable:
1513 *isSymbolFont = (symbolTable > -1);
1514
1515 quint32 unicode_table = 0;
1516 if (!qSafeFromBigEndian(maps + 8 * tableToUse + 4, endPtr, &unicode_table))
1517 return nullptr;
1518
1519 if (!unicode_table)
1520 return nullptr;
1521
1522 // get the header of the unicode table
1523 header = table + unicode_table;
1524
1525 quint16 format;
1526 if (!qSafeFromBigEndian(header, endPtr, &format))
1527 return nullptr;
1528
1529 quint32 length;
1530 if (format < 8) {
1531 quint16 tmp;
1532 if (!qSafeFromBigEndian(header + 2, endPtr, &tmp))
1533 return nullptr;
1534 length = tmp;
1535 } else {
1536 if (!qSafeFromBigEndian(header + 4, endPtr, &length))
1537 return nullptr;
1538 }
1539
1540 if (table + unicode_table + length > endPtr)
1541 return nullptr;
1542 *cmapSize = length;
1543
1544 // To support symbol fonts that contain a unicode table for the symbol area
1545 // we check the cmap tables and fall back to symbol font unless that would
1546 // involve losing information from the unicode table
1547 if (symbolTable > -1 && ((score == Unicode) || (score == Unicode11))) {
1548 const uchar *selectedTable = table + unicode_table;
1549
1550 // Check that none of the latin1 range are in the unicode table
1551 bool unicodeTableHasLatin1 = false;
1552 for (int uc=0x00; uc<0x100; ++uc) {
1553 if (getTrueTypeGlyphIndex(selectedTable, length, uc) != 0) {
1554 unicodeTableHasLatin1 = true;
1555 break;
1556 }
1557 }
1558
1559 // Check that at least one symbol char is in the unicode table
1560 bool unicodeTableHasSymbols = false;
1561 if (!unicodeTableHasLatin1) {
1562 for (int uc=0xf000; uc<0xf100; ++uc) {
1563 if (getTrueTypeGlyphIndex(selectedTable, length, uc) != 0) {
1564 unicodeTableHasSymbols = true;
1565 break;
1566 }
1567 }
1568 }
1569
1570 // Fall back to symbol table
1571 if (!unicodeTableHasLatin1 && unicodeTableHasSymbols) {
1572 tableToUse = symbolTable;
1573 score = Symbol;
1574 goto resolveTable;
1575 }
1576 }
1577
1578 return table + unicode_table;
1579}
1580
1581quint32 QFontEngine::getTrueTypeGlyphIndex(const uchar *cmap, int cmapSize, uint unicode)
1582{
1583 const uchar *end = cmap + cmapSize;
1584 quint16 format = 0;
1585 if (!qSafeFromBigEndian(cmap, end, &format))
1586 return 0;
1587
1588 if (format == 0) {
1589 const uchar *ptr = cmap + 6 + unicode;
1590 if (unicode < 256 && ptr < end)
1591 return quint32(*ptr);
1592 } else if (format == 4) {
1593 /* some fonts come with invalid cmap tables, where the last segment
1594 specified end = start = rangeoffset = 0xffff, delta = 0x0001
1595 Since 0xffff is never a valid Unicode char anyway, we just get rid of the issue
1596 by returning 0 for 0xffff
1597 */
1598 if (unicode >= 0xffff)
1599 return 0;
1600
1601 quint16 segCountX2 = 0;
1602 if (!qSafeFromBigEndian(cmap + 6, end, &segCountX2))
1603 return 0;
1604
1605 const unsigned char *ends = cmap + 14;
1606
1607 int i = 0;
1608 for (; i < segCountX2/2; ++i) {
1609 quint16 codePoint = 0;
1610 if (!qSafeFromBigEndian(ends + 2 * i, end, &codePoint))
1611 return 0;
1612 if (codePoint >= unicode)
1613 break;
1614 }
1615
1616 const unsigned char *idx = ends + segCountX2 + 2 + 2*i;
1617
1618 quint16 startIndex = 0;
1619 if (!qSafeFromBigEndian(idx, end, &startIndex))
1620 return 0;
1621 if (startIndex > unicode)
1622 return 0;
1623
1624 idx += segCountX2;
1625
1626 quint16 tmp = 0;
1627 if (!qSafeFromBigEndian(idx, end, &tmp))
1628 return 0;
1629 qint16 idDelta = qint16(tmp);
1630
1631 idx += segCountX2;
1632
1633 quint16 idRangeoffset_t = 0;
1634 if (!qSafeFromBigEndian(idx, end, &idRangeoffset_t))
1635 return 0;
1636
1637 quint16 glyphIndex = 0;
1638 if (idRangeoffset_t) {
1639 quint16 id = 0;
1640 if (!qSafeFromBigEndian(idRangeoffset_t + 2 * (unicode - startIndex) + idx, end, &id))
1641 return 0;
1642
1643 if (id)
1644 glyphIndex = (idDelta + id) % 0x10000;
1645 else
1646 glyphIndex = 0;
1647 } else {
1648 glyphIndex = (idDelta + unicode) % 0x10000;
1649 }
1650 return glyphIndex;
1651 } else if (format == 6) {
1652 quint16 tableSize = 0;
1653 if (!qSafeFromBigEndian(cmap + 2, end, &tableSize))
1654 return 0;
1655
1656 quint16 firstCode6 = 0;
1657 if (!qSafeFromBigEndian(cmap + 6, end, &firstCode6))
1658 return 0;
1659 if (unicode < firstCode6)
1660 return 0;
1661
1662 quint16 entryCount6 = 0;
1663 if (!qSafeFromBigEndian(cmap + 8, end, &entryCount6))
1664 return 0;
1665 if (entryCount6 * 2 + 10 > tableSize)
1666 return 0;
1667
1668 quint16 sentinel6 = firstCode6 + entryCount6;
1669 if (unicode >= sentinel6)
1670 return 0;
1671
1672 quint16 entryIndex6 = unicode - firstCode6;
1673
1674 quint16 index = 0;
1675 qSafeFromBigEndian(cmap + 10 + (entryIndex6 * 2), end, &index);
1676 return index;
1677 } else if (format == 12) {
1678 quint32 nGroups = 0;
1679 if (!qSafeFromBigEndian(cmap + 12, end, &nGroups))
1680 return 0;
1681
1682 cmap += 16; // move to start of groups
1683
1684 int left = 0, right = nGroups - 1;
1685 while (left <= right) {
1686 int middle = left + ( ( right - left ) >> 1 );
1687
1688 quint32 startCharCode = 0;
1689 if (!qSafeFromBigEndian(cmap + 12 * middle, end, &startCharCode))
1690 return 0;
1691
1692 if (unicode < startCharCode)
1693 right = middle - 1;
1694 else {
1695 quint32 endCharCode = 0;
1696 if (!qSafeFromBigEndian(cmap + 12 * middle + 4, end, &endCharCode))
1697 return 0;
1698
1699 if (unicode <= endCharCode) {
1700 quint32 index = 0;
1701 if (!qSafeFromBigEndian(cmap + 12 * middle + 8, end, &index))
1702 return 0;
1703
1704 // Sanity check: No truetype glyph index is >= 0xffff currently, so any value
1705 // above this could result in undefined behavior later.
1706 return std::clamp(index + unicode - startCharCode, quint32(0), quint32(0xffff));
1707 }
1708 left = middle + 1;
1709 }
1710 }
1711 } else {
1712 qDebug("cmap table of format %d not implemented", format);
1713 }
1714
1715 return 0;
1716}
1717
1718QByteArray QFontEngine::convertToPostscriptFontFamilyName(const QByteArray &family)
1719{
1720 QByteArray f = family;
1721 f.replace(' ', "");
1722 f.replace('(', "");
1723 f.replace(')', "");
1724 f.replace('<', "");
1725 f.replace('>', "");
1726 f.replace('[', "");
1727 f.replace(']', "");
1728 f.replace('{', "");
1729 f.replace('}', "");
1730 f.replace('/', "");
1731 f.replace('%', "");
1732 return f;
1733}
1734
1735// Allow font engines (e.g. Windows) that can not reliably create
1736// outline paths for distance-field rendering to switch the scene
1737// graph over to native text rendering.
1738bool QFontEngine::hasUnreliableGlyphOutline() const
1739{
1740 // Color glyphs (Emoji) are generally not suited for outlining
1741 return glyphFormat == QFontEngine::Format_ARGB;
1742}
1743
1744QFixed QFontEngine::firstLeftBearing(const QGlyphLayout &glyphs)
1745{
1746 for (int i = 0; i < glyphs.numGlyphs; ++i) {
1747 glyph_t glyph = glyphs.glyphs[i];
1748 glyph_metrics_t gi = boundingBox(glyph);
1749 if (gi.isValid() && gi.width > 0)
1750 return gi.leftBearing();
1751 }
1752 return 0;
1753}
1754
1755QFixed QFontEngine::lastRightBearing(const QGlyphLayout &glyphs)
1756{
1757 if (glyphs.numGlyphs >= 1) {
1758 glyph_t glyph = glyphs.glyphs[glyphs.numGlyphs - 1];
1759 glyph_metrics_t gi = boundingBox(glyph);
1760 if (gi.isValid())
1761 return gi.rightBearing();
1762 }
1763 return 0;
1764}
1765
1766QList<QFontVariableAxis> QFontEngine::variableAxes() const
1767{
1768 return QList<QFontVariableAxis>{};
1769}
1770
1771QFontEngine::GlyphCacheEntry::GlyphCacheEntry()
1772{
1773}
1774
1775QFontEngine::GlyphCacheEntry::GlyphCacheEntry(const GlyphCacheEntry &o)
1776 : cache(o.cache)
1777{
1778}
1779
1780QFontEngine::GlyphCacheEntry::~GlyphCacheEntry()
1781{
1782}
1783
1784QFontEngine::GlyphCacheEntry &QFontEngine::GlyphCacheEntry::operator=(const GlyphCacheEntry &o)
1785{
1786 cache = o.cache;
1787 return *this;
1788}
1789
1790bool QFontEngine::disableEmojiSegmenter()
1791{
1792#if defined(QT_NO_EMOJISEGMENTER)
1793 return true;
1794#else
1795 static const bool sDisableEmojiSegmenter = qEnvironmentVariableIntValue("QT_DISABLE_EMOJI_SEGMENTER") > 0;
1796 return sDisableEmojiSegmenter;
1797#endif
1798}
1799
1800int QFontEngine::maxCachedGlyphSize()
1801{
1802 static const int maxCachedSize = []{
1803 if (int env = qEnvironmentVariableIntValue("QT_MAX_CACHED_GLYPH_SIZE"))
1804 return env;
1806 }();
1807
1808 return maxCachedSize;
1809}
1810
1811// ------------------------------------------------------------------
1812// The box font engine
1813// ------------------------------------------------------------------
1814
1815QFontEngineBox::QFontEngineBox(int size)
1816 : QFontEngine(Box),
1817 _size(size)
1818{
1819 cache_cost = sizeof(QFontEngineBox);
1820}
1821
1822QFontEngineBox::QFontEngineBox(Type type, int size)
1823 : QFontEngine(type),
1824 _size(size)
1825{
1826 cache_cost = sizeof(QFontEngineBox);
1827}
1828
1829QFontEngineBox::~QFontEngineBox()
1830{
1831}
1832
1833glyph_t QFontEngineBox::glyphIndex(uint ucs4) const
1834{
1835 Q_UNUSED(ucs4);
1836 return 1;
1837}
1838
1839int QFontEngineBox::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QFontEngine::ShaperFlags flags) const
1840{
1841 Q_ASSERT(glyphs->numGlyphs >= *nglyphs);
1842 if (*nglyphs < len) {
1843 *nglyphs = len;
1844 return -1;
1845 }
1846
1847 int ucs4Length = 0;
1848 QStringIterator it(str, str + len);
1849 while (it.hasNext()) {
1850 it.advance();
1851 glyphs->glyphs[ucs4Length++] = 1;
1852 }
1853
1854 *nglyphs = ucs4Length;
1855 glyphs->numGlyphs = ucs4Length;
1856
1857 if (!(flags & GlyphIndicesOnly))
1858 recalcAdvances(glyphs, flags);
1859
1860 return *nglyphs;
1861}
1862
1863void QFontEngineBox::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags) const
1864{
1865 for (int i = 0; i < glyphs->numGlyphs; i++)
1866 glyphs->advances[i] = _size;
1867}
1868
1869void QFontEngineBox::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags)
1870{
1871 if (!glyphs.numGlyphs)
1872 return;
1873
1874 QVarLengthArray<QFixedPoint> positions;
1875 QVarLengthArray<glyph_t> positioned_glyphs;
1876 QTransform matrix = QTransform::fromTranslate(x, y - _size);
1877 getGlyphPositions(glyphs, matrix, flags, positioned_glyphs, positions);
1878
1879 QSize s(_size - 3, _size - 3);
1880 for (int k = 0; k < positions.size(); k++)
1881 path->addRect(QRectF(positions[k].toPointF(), s));
1882}
1883
1884glyph_metrics_t QFontEngineBox::boundingBox(const QGlyphLayout &glyphs)
1885{
1886 glyph_metrics_t overall;
1887 overall.width = _size*glyphs.numGlyphs;
1888 overall.height = _size;
1889 overall.xoff = overall.width;
1890 return overall;
1891}
1892
1893void QFontEngineBox::draw(QPaintEngine *p, qreal x, qreal y, const QTextItemInt &ti)
1894{
1895 if (!ti.glyphs.numGlyphs)
1896 return;
1897
1898 // any fixes here should probably also be done in QPaintEnginePrivate::drawBoxTextItem
1899 QSize s(_size - 3, _size - 3);
1900
1901 QVarLengthArray<QFixedPoint> positions;
1902 QVarLengthArray<glyph_t> glyphs;
1903 QTransform matrix = QTransform::fromTranslate(x, y - _size);
1904 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1905 if (glyphs.size() == 0)
1906 return;
1907
1908
1909 QPainter *painter = p->painter();
1910 painter->save();
1911 painter->setBrush(Qt::NoBrush);
1912 QPen pen = painter->pen();
1913 pen.setWidthF(lineThickness().toReal());
1914 painter->setPen(pen);
1915 for (int k = 0; k < positions.size(); k++)
1916 painter->drawRect(QRectF(positions[k].toPointF(), s));
1917 painter->restore();
1918}
1919
1920glyph_metrics_t QFontEngineBox::boundingBox(glyph_t)
1921{
1922 return glyph_metrics_t(0, -_size, _size, _size, _size, 0);
1923}
1924
1925QFontEngine *QFontEngineBox::cloneWithSize(qreal pixelSize) const
1926{
1927 QFontEngineBox *fe = new QFontEngineBox(pixelSize);
1928 return fe;
1929}
1930
1931QFixed QFontEngineBox::ascent() const
1932{
1933 return _size;
1934}
1935
1936QFixed QFontEngineBox::capHeight() const
1937{
1938 return _size;
1939}
1940
1941QFixed QFontEngineBox::descent() const
1942{
1943 return 0;
1944}
1945
1946QFixed QFontEngineBox::leading() const
1947{
1948 QFixed l = _size * QFixed::fromReal(qreal(0.15));
1949 return l.ceil();
1950}
1951
1952qreal QFontEngineBox::maxCharWidth() const
1953{
1954 return _size;
1955}
1956
1957bool QFontEngineBox::canRender(const QChar *, int) const
1958{
1959 return true;
1960}
1961
1962QImage QFontEngineBox::alphaMapForGlyph(glyph_t)
1963{
1964 QImage image(_size, _size, QImage::Format_Alpha8);
1965 image.fill(0);
1966
1967 uchar *bits = image.bits();
1968 for (int i=2; i <= _size-3; ++i) {
1969 bits[i + 2 * image.bytesPerLine()] = 255;
1970 bits[i + (_size - 3) * image.bytesPerLine()] = 255;
1971 bits[2 + i * image.bytesPerLine()] = 255;
1972 bits[_size - 3 + i * image.bytesPerLine()] = 255;
1973 }
1974 return image;
1975}
1976
1977// ------------------------------------------------------------------
1978// Multi engine
1979// ------------------------------------------------------------------
1980
1981uchar QFontEngineMulti::highByte(glyph_t glyph)
1982{ return glyph >> 24; }
1983
1984// strip high byte from glyph
1985static inline glyph_t stripped(glyph_t glyph)
1986{ return glyph & 0x00ffffff; }
1987
1988QFontEngineMulti::QFontEngineMulti(QFontEngine *engine, int script, const QStringList &fallbackFamilies)
1989 : QFontEngine(Multi),
1990 m_fallbackFamilies(fallbackFamilies),
1991 m_script(script),
1992 m_fallbackFamiliesQueried(!m_fallbackFamilies.isEmpty())
1993{
1994 Q_ASSERT(engine && engine->type() != QFontEngine::Multi);
1995
1996 if (m_fallbackFamilies.isEmpty()) {
1997 // defer obtaining the fallback families until loadEngine(1)
1998 m_fallbackFamilies << QString();
1999 }
2000
2001 m_engines.resize(m_fallbackFamilies.size() + 1);
2002
2003 engine->ref.ref();
2004 m_engines[0] = engine;
2005
2006 fontDef = engine->fontDef;
2007 cache_cost = engine->cache_cost;
2008}
2009
2010QFontEngineMulti::~QFontEngineMulti()
2011{
2012 for (int i = 0; i < m_engines.size(); ++i) {
2013 QFontEngine *fontEngine = m_engines.at(i);
2014 if (fontEngine && !fontEngine->ref.deref())
2015 delete fontEngine;
2016 }
2017}
2018
2019QStringList qt_fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QFontDatabasePrivate::ExtendedScript script);
2020
2021void QFontEngineMulti::ensureFallbackFamiliesQueried()
2022{
2023 QFont::StyleHint styleHint = QFont::StyleHint(fontDef.styleHint);
2024 if (styleHint == QFont::AnyStyle && fontDef.fixedPitch)
2025 styleHint = QFont::TypeWriter;
2026
2027 setFallbackFamiliesList(qt_fallbacksForFamily(fontDef.family(),
2028 QFont::Style(fontDef.style), styleHint,
2029 QFontDatabasePrivate::ExtendedScript(m_script)));
2030}
2031
2032void QFontEngineMulti::setFallbackFamiliesList(const QStringList &fallbackFamilies)
2033{
2034 Q_ASSERT(!m_fallbackFamiliesQueried);
2035
2036 m_fallbackFamilies = fallbackFamilies;
2037 if (m_fallbackFamilies.isEmpty()) {
2038 // turns out we lied about having any fallback at all
2039 Q_ASSERT(m_engines.size() == 2); // see c-tor for details
2040 QFontEngine *engine = m_engines.at(0);
2041 engine->ref.ref();
2042 m_engines[1] = engine;
2043 m_fallbackFamilies << fontDef.family();
2044 } else {
2045 m_engines.resize(m_fallbackFamilies.size() + 1);
2046 }
2047
2048 m_fallbackFamiliesQueried = true;
2049}
2050
2051void QFontEngineMulti::ensureEngineAt(int at)
2052{
2053 if (!m_fallbackFamiliesQueried && at > 0)
2054 ensureFallbackFamiliesQueried();
2055 Q_ASSERT(at < m_engines.size());
2056 if (at < 0 || at >= m_engines.size())
2057 return;
2058 if (!m_engines.at(at)) {
2059 QFontEngine *engine = loadEngine(at);
2060 if (!engine)
2061 engine = new QFontEngineBox(fontDef.pixelSize);
2062 Q_ASSERT(engine && engine->type() != QFontEngine::Multi);
2063 engine->ref.ref();
2064 m_engines[at] = engine;
2065 }
2066}
2067
2068QFontEngine *QFontEngineMulti::loadEngine(int at)
2069{
2070 QFontDef request(fontDef);
2071 request.styleStrategy |= QFont::NoFontMerging;
2072 request.families = QStringList(fallbackFamilyAt(at - 1));
2073
2074 // At this point, the main script of the text has already been considered
2075 // when fetching the list of fallback families from the database, and the
2076 // info about the actual script of the characters may have been discarded,
2077 // so we do not check for writing system support, but instead just load
2078 // the family indiscriminately.
2079 if (QFontEngine *engine = QFontDatabasePrivate::findFont(request, QFontDatabasePrivate::Script_Common)) {
2080 engine->fontDef.weight = request.weight;
2081 if (request.style > QFont::StyleNormal)
2082 engine->fontDef.style = request.style;
2083 return engine;
2084 }
2085
2086 return nullptr;
2087}
2088
2089int QFontEngineMulti::glyphCount() const
2090{
2091 return engine(0)->glyphCount();
2092}
2093
2094glyph_t QFontEngineMulti::glyphIndex(uint ucs4) const
2095{
2096 glyph_t glyph = engine(0)->glyphIndex(ucs4);
2097 if (glyph == 0 && !isIgnorableChar(ucs4)) {
2098 if (!m_fallbackFamiliesQueried)
2099 const_cast<QFontEngineMulti *>(this)->ensureFallbackFamiliesQueried();
2100 for (int x = 1, n = qMin(m_engines.size(), maximumEngineCount()); x < n; ++x) {
2101 QFontEngine *engine = m_engines.at(x);
2102 if (!engine) {
2103 if (!shouldLoadFontEngineForCharacter(x, ucs4))
2104 continue;
2105 const_cast<QFontEngineMulti *>(this)->ensureEngineAt(x);
2106 engine = m_engines.at(x);
2107 }
2108 Q_ASSERT(engine != nullptr);
2109 if (engine->type() == Box)
2110 continue;
2111
2112 glyph = engine->glyphIndex(ucs4);
2113 if (glyph != 0) {
2114 // set the high byte to indicate which engine the glyph came from
2115 glyph |= (x << 24);
2116 break;
2117 }
2118 }
2119 }
2120
2121 return glyph;
2122}
2123
2124QString QFontEngineMulti::glyphName(glyph_t glyph) const
2125{
2126 const int which = highByte(glyph);
2127 const_cast<QFontEngineMulti *>(this)->ensureEngineAt(which);
2128 return engine(which)->glyphName(stripped(glyph));
2129}
2130
2131glyph_t QFontEngineMulti::findGlyph(QLatin1StringView name) const
2132{
2133 return engine(0)->findGlyph(name);
2134}
2135
2136int QFontEngineMulti::stringToCMap(const QChar *str, int len,
2137 QGlyphLayout *glyphs, int *nglyphs,
2138 QFontEngine::ShaperFlags flags) const
2139{
2140 qCDebug(lcTextFontCmap) << "Mapping characters in"
2141 << QString(str, len)
2142 << "; Shaper flags:" << flags;
2143
2144 const int originalNumGlyphs = glyphs->numGlyphs;
2145 int mappedGlyphCount = engine(0)->stringToCMap(str, len, glyphs, nglyphs, flags);
2146 qCDebug(lcTextFontCmap) << " Main font mapped"
2147 << mappedGlyphCount
2148 << "of"
2149 << (nglyphs != nullptr ? *nglyphs : 0)
2150 << "characters";
2151
2152 if (mappedGlyphCount < 0)
2153 return -1;
2154
2155 // If ContextFontMerging is set and the match for the string was incomplete, we try all
2156 // fallbacks on the full string until we find the best match.
2157 bool contextFontMerging = mappedGlyphCount < *nglyphs && (fontDef.styleStrategy & QFont::ContextFontMerging);
2158 if (contextFontMerging) {
2159 qCDebug(lcTextFontCmap) << " Context font merging, first pass";
2160
2161 QVarLengthGlyphLayoutArray tempLayout(len);
2162 if (!m_fallbackFamiliesQueried)
2163 const_cast<QFontEngineMulti *>(this)->ensureFallbackFamiliesQueried();
2164
2165 int maxGlyphCount = 0;
2166 uchar engineIndex = 0;
2167 for (int x = 1, n = qMin(m_engines.size(), maximumEngineCount()); x < n; ++x) {
2168 int numGlyphs = len;
2169 const_cast<QFontEngineMulti *>(this)->ensureEngineAt(x);
2170 maxGlyphCount = engine(x)->stringToCMap(str, len, &tempLayout, &numGlyphs, flags);
2171 qCDebug(lcTextFontCmap) << " Fallback" << x << "mapped" << maxGlyphCount;
2172
2173 // If we found a better match, we copy data into the main QGlyphLayout
2174 if (maxGlyphCount > mappedGlyphCount) {
2175 qCDebug(lcTextFontCmap) << " Better match!";
2176 *nglyphs = numGlyphs;
2177 glyphs->numGlyphs = originalNumGlyphs;
2178 glyphs->copy(&tempLayout);
2179 engineIndex = x;
2180 if (maxGlyphCount == numGlyphs)
2181 break;
2182 } else {
2183 qCDebug(lcTextFontCmap) << " No improvement";
2184 }
2185 }
2186
2187 if (engineIndex > 0) {
2188 for (int y = 0; y < glyphs->numGlyphs; ++y) {
2189 if (glyphs->glyphs[y] != 0)
2190 glyphs->glyphs[y] |= (engineIndex << 24);
2191 }
2192 } else {
2193 contextFontMerging = false;
2194 }
2195
2196 mappedGlyphCount = maxGlyphCount;
2197 }
2198
2199 // Fill in missing glyphs by going through string one character at the time and finding
2200 // the first viable fallback.
2201 int glyph_pos = 0;
2202 QStringIterator it(str, str + len);
2203
2204 const bool enableVariationSelectorHack = disableEmojiSegmenter();
2205 char32_t previousUcs4 = 0;
2206
2207 int lastFallback = -1;
2208 while (it.hasNext()) {
2209 const char32_t ucs4 = it.peekNext();
2210
2211 // If we applied a fallback font to previous glyph, and the current is either
2212 // ZWJ or ZWNJ, we should also try applying the same fallback font to that, in order
2213 // to get the correct shaping rules applied.
2214 if (lastFallback >= 0 && (ucs4 == 0x200d || ucs4 == 0x200c)) {
2215 QFontEngine *engine = m_engines.at(lastFallback);
2216 glyph_t glyph = engine->glyphIndex(ucs4);
2217 if (glyph != 0) {
2218 qCDebug(lcTextFontCmap) << " Applying ZWJ/ZWNJ special case for"
2219 << QString::number(ucs4, 16)
2220 << ", lastFallback:" << lastFallback;
2221
2222 glyphs->glyphs[glyph_pos] = glyph;
2223 if (!(flags & GlyphIndicesOnly)) {
2224 QGlyphLayout g = glyphs->mid(glyph_pos, 1);
2225 engine->recalcAdvances(&g, flags);
2226 }
2227
2228 // set the high byte to indicate which engine the glyph came from
2229 glyphs->glyphs[glyph_pos] |= (lastFallback << 24);
2230 } else {
2231 lastFallback = -1;
2232 }
2233 } else {
2234 lastFallback = -1;
2235 }
2236
2237 if (glyphs->glyphs[glyph_pos] == 0 && !isIgnorableChar(ucs4)) {
2238 qCDebug(lcTextFontCmap) << " Unmapped character"
2239 << QString::number(ucs4, 16);
2240
2241 if (!m_fallbackFamiliesQueried)
2242 const_cast<QFontEngineMulti *>(this)->ensureFallbackFamiliesQueried();
2243 for (int x = contextFontMerging ? 0 : 1, n = qMin(m_engines.size(), maximumEngineCount()); x < n; ++x) {
2244 QFontEngine *engine = m_engines.at(x);
2245 if (!engine) {
2246 if (!shouldLoadFontEngineForCharacter(x, ucs4)) {
2247 qCDebug(lcTextFontCmap) << " Skipping fallback #" << x;
2248 continue;
2249 }
2250 const_cast<QFontEngineMulti *>(this)->ensureEngineAt(x);
2251 engine = m_engines.at(x);
2252 if (!engine)
2253 continue;
2254 }
2255 Q_ASSERT(engine != nullptr);
2256 if (engine->type() == Box)
2257 continue;
2258
2259 glyph_t glyph = engine->glyphIndex(ucs4);
2260 qCDebug(lcTextFontCmap) << " Fallback #" << x
2261 << ", family:" << engine->fontDef.families
2262 << ", styleName:" << engine->fontDef.styleName
2263 << ", style:" << engine->fontDef.style
2264 << ", weight:" << engine->fontDef.weight
2265 << ", glyph mapping:" << glyph;
2266 if (glyph != 0) {
2267 glyphs->glyphs[glyph_pos] = glyph;
2268 if (!(flags & GlyphIndicesOnly)) {
2269 QGlyphLayout g = glyphs->mid(glyph_pos, 1);
2270 engine->recalcAdvances(&g, flags);
2271 }
2272
2273 lastFallback = x;
2274
2275 // set the high byte to indicate which engine the glyph came from
2276 glyphs->glyphs[glyph_pos] |= (x << 24);
2277 break;
2278 }
2279 }
2280
2281 // For variant-selectors, they are modifiers to the previous character. If we
2282 // end up with different font selections for the selector and the character it
2283 // modifies, we try applying the selector font to the preceding character as well
2284 const int variantSelectorBlock = 0xFE00;
2285 if (enableVariationSelectorHack && (ucs4 & 0xFFF0) == variantSelectorBlock && glyph_pos > 0) {
2286 int selectorFontEngine = glyphs->glyphs[glyph_pos] >> 24;
2287 int precedingCharacterFontEngine = glyphs->glyphs[glyph_pos - 1] >> 24;
2288
2289 if (selectorFontEngine != precedingCharacterFontEngine) {
2290 // Emoji variant selectors are specially handled and should affect font
2291 // selection. If VS-16 is used, then this means we want to select a color
2292 // font. If the selected font is already a color font, we do not need search
2293 // again. If the VS-15 is used, then this means we want to select a non-color
2294 // font. If the selected font is not a color font, we don't do anything.
2295 const QFontEngine *selectedEngine = m_engines.at(precedingCharacterFontEngine);
2296 const bool colorFont = selectedEngine->isColorFont();
2297 const char32_t vs15 = 0xFE0E;
2298 const char32_t vs16 = 0xFE0F;
2299 bool adaptVariantSelector = ucs4 < vs15
2300 || (ucs4 == vs15 && colorFont)
2301 || (ucs4 == vs16 && !colorFont);
2302
2303 if (adaptVariantSelector) {
2304 QFontEngine *engine = m_engines.at(selectorFontEngine);
2305 glyph_t glyph = engine->glyphIndex(previousUcs4);
2306 if (glyph != 0) {
2307 glyphs->glyphs[glyph_pos - 1] = glyph;
2308 if (!(flags & GlyphIndicesOnly)) {
2309 QGlyphLayout g = glyphs->mid(glyph_pos - 1, 1);
2310 engine->recalcAdvances(&g, flags);
2311 }
2312
2313 // set the high byte to indicate which engine the glyph came from
2314 glyphs->glyphs[glyph_pos - 1] |= (selectorFontEngine << 24);
2315 }
2316 }
2317 }
2318 }
2319 }
2320
2321 it.advance();
2322 ++glyph_pos;
2323
2324 previousUcs4 = ucs4;
2325 }
2326
2327 *nglyphs = glyph_pos;
2328 glyphs->numGlyphs = glyph_pos;
2329 return mappedGlyphCount;
2330}
2331
2332bool QFontEngineMulti::shouldLoadFontEngineForCharacter(int at, uint ucs4) const
2333{
2334 Q_UNUSED(at);
2335 Q_UNUSED(ucs4);
2336 return true;
2337}
2338
2339glyph_metrics_t QFontEngineMulti::boundingBox(const QGlyphLayout &glyphs)
2340{
2341 if (glyphs.numGlyphs <= 0)
2342 return glyph_metrics_t();
2343
2344 glyph_metrics_t overall;
2345
2346 int which = highByte(glyphs.glyphs[0]);
2347 int start = 0;
2348 int end, i;
2349 for (end = 0; end < glyphs.numGlyphs; ++end) {
2350 const int e = highByte(glyphs.glyphs[end]);
2351 if (e == which)
2352 continue;
2353
2354 // set the high byte to zero
2355 for (i = start; i < end; ++i)
2356 glyphs.glyphs[i] = stripped(glyphs.glyphs[i]);
2357
2358 // merge the bounding box for this run
2359 const glyph_metrics_t gm = engine(which)->boundingBox(glyphs.mid(start, end - start));
2360
2361 overall.x = qMin(overall.x, gm.x);
2362 overall.y = qMin(overall.y, gm.y);
2363 overall.width = overall.xoff + gm.width;
2364 overall.height = qMax(overall.height + overall.y, gm.height + gm.y) -
2365 qMin(overall.y, gm.y);
2366 overall.xoff += gm.xoff;
2367 overall.yoff += gm.yoff;
2368
2369 // reset the high byte for all glyphs
2370 const int hi = which << 24;
2371 for (i = start; i < end; ++i)
2372 glyphs.glyphs[i] = hi | glyphs.glyphs[i];
2373
2374 // change engine
2375 start = end;
2376 which = e;
2377 }
2378
2379 // set the high byte to zero
2380 for (i = start; i < end; ++i)
2381 glyphs.glyphs[i] = stripped(glyphs.glyphs[i]);
2382
2383 // merge the bounding box for this run
2384 const glyph_metrics_t gm = engine(which)->boundingBox(glyphs.mid(start, end - start));
2385
2386 overall.x = qMin(overall.x, gm.x);
2387 overall.y = qMin(overall.y, gm.y);
2388 overall.width = overall.xoff + gm.width;
2389 overall.height = qMax(overall.height + overall.y, gm.height + gm.y) -
2390 qMin(overall.y, gm.y);
2391 overall.xoff += gm.xoff;
2392 overall.yoff += gm.yoff;
2393
2394 // reset the high byte for all glyphs
2395 const int hi = which << 24;
2396 for (i = start; i < end; ++i)
2397 glyphs.glyphs[i] = hi | glyphs.glyphs[i];
2398
2399 return overall;
2400}
2401
2402void QFontEngineMulti::getGlyphBearings(glyph_t glyph, qreal *leftBearing, qreal *rightBearing)
2403{
2404 int which = highByte(glyph);
2405 ensureEngineAt(which);
2406 engine(which)->getGlyphBearings(stripped(glyph), leftBearing, rightBearing);
2407}
2408
2409void QFontEngineMulti::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
2410 QPainterPath *path, QTextItem::RenderFlags flags)
2411{
2412 if (glyphs.numGlyphs <= 0)
2413 return;
2414
2415 int which = highByte(glyphs.glyphs[0]);
2416 int start = 0;
2417 int end, i;
2418 if (flags & QTextItem::RightToLeft) {
2419 for (int gl = 0; gl < glyphs.numGlyphs; gl++)
2420 x += glyphs.advances[gl].toReal();
2421 }
2422 for (end = 0; end < glyphs.numGlyphs; ++end) {
2423 const int e = highByte(glyphs.glyphs[end]);
2424 if (e == which)
2425 continue;
2426
2427 if (flags & QTextItem::RightToLeft) {
2428 for (i = start; i < end; ++i)
2429 x -= glyphs.advances[i].toReal();
2430 }
2431
2432 // set the high byte to zero
2433 for (i = start; i < end; ++i)
2434 glyphs.glyphs[i] = stripped(glyphs.glyphs[i]);
2435 engine(which)->addOutlineToPath(x, y, glyphs.mid(start, end - start), path, flags);
2436 // reset the high byte for all glyphs and update x and y
2437 const int hi = which << 24;
2438 for (i = start; i < end; ++i)
2439 glyphs.glyphs[i] = hi | glyphs.glyphs[i];
2440
2441 if (!(flags & QTextItem::RightToLeft)) {
2442 for (i = start; i < end; ++i)
2443 x += glyphs.advances[i].toReal();
2444 }
2445
2446 // change engine
2447 start = end;
2448 which = e;
2449 }
2450
2451 if (flags & QTextItem::RightToLeft) {
2452 for (i = start; i < end; ++i)
2453 x -= glyphs.advances[i].toReal();
2454 }
2455
2456 // set the high byte to zero
2457 for (i = start; i < end; ++i)
2458 glyphs.glyphs[i] = stripped(glyphs.glyphs[i]);
2459
2460 engine(which)->addOutlineToPath(x, y, glyphs.mid(start, end - start), path, flags);
2461
2462 // reset the high byte for all glyphs
2463 const int hi = which << 24;
2464 for (i = start; i < end; ++i)
2465 glyphs.glyphs[i] = hi | glyphs.glyphs[i];
2466}
2467
2468void QFontEngineMulti::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags flags) const
2469{
2470 if (glyphs->numGlyphs <= 0)
2471 return;
2472
2473 int which = highByte(glyphs->glyphs[0]);
2474 int start = 0;
2475 int end, i;
2476 for (end = 0; end < glyphs->numGlyphs; ++end) {
2477 const int e = highByte(glyphs->glyphs[end]);
2478 if (e == which)
2479 continue;
2480
2481 // set the high byte to zero
2482 for (i = start; i < end; ++i)
2483 glyphs->glyphs[i] = stripped(glyphs->glyphs[i]);
2484
2485 QGlyphLayout offs = glyphs->mid(start, end - start);
2486 engine(which)->recalcAdvances(&offs, flags);
2487
2488 // reset the high byte for all glyphs and update x and y
2489 const int hi = which << 24;
2490 for (i = start; i < end; ++i)
2491 glyphs->glyphs[i] = hi | glyphs->glyphs[i];
2492
2493 // change engine
2494 start = end;
2495 which = e;
2496 }
2497
2498 // set the high byte to zero
2499 for (i = start; i < end; ++i)
2500 glyphs->glyphs[i] = stripped(glyphs->glyphs[i]);
2501
2502 QGlyphLayout offs = glyphs->mid(start, end - start);
2503 engine(which)->recalcAdvances(&offs, flags);
2504
2505 // reset the high byte for all glyphs
2506 const int hi = which << 24;
2507 for (i = start; i < end; ++i)
2508 glyphs->glyphs[i] = hi | glyphs->glyphs[i];
2509}
2510
2511void QFontEngineMulti::doKerning(QGlyphLayout *glyphs, QFontEngine::ShaperFlags flags) const
2512{
2513 if (glyphs->numGlyphs <= 0)
2514 return;
2515
2516 int which = highByte(glyphs->glyphs[0]);
2517 int start = 0;
2518 int end, i;
2519 for (end = 0; end < glyphs->numGlyphs; ++end) {
2520 const int e = highByte(glyphs->glyphs[end]);
2521 if (e == which)
2522 continue;
2523
2524 // set the high byte to zero
2525 for (i = start; i < end; ++i)
2526 glyphs->glyphs[i] = stripped(glyphs->glyphs[i]);
2527
2528 QGlyphLayout offs = glyphs->mid(start, end - start);
2529 engine(which)->doKerning(&offs, flags);
2530
2531 // reset the high byte for all glyphs and update x and y
2532 const int hi = which << 24;
2533 for (i = start; i < end; ++i)
2534 glyphs->glyphs[i] = hi | glyphs->glyphs[i];
2535
2536 // change engine
2537 start = end;
2538 which = e;
2539 }
2540
2541 // set the high byte to zero
2542 for (i = start; i < end; ++i)
2543 glyphs->glyphs[i] = stripped(glyphs->glyphs[i]);
2544
2545 QGlyphLayout offs = glyphs->mid(start, end - start);
2546 engine(which)->doKerning(&offs, flags);
2547
2548 // reset the high byte for all glyphs
2549 const int hi = which << 24;
2550 for (i = start; i < end; ++i)
2551 glyphs->glyphs[i] = hi | glyphs->glyphs[i];
2552}
2553
2554glyph_metrics_t QFontEngineMulti::boundingBox(glyph_t glyph)
2555{
2556 const int which = highByte(glyph);
2557 return engine(which)->boundingBox(stripped(glyph));
2558}
2559
2560QFixed QFontEngineMulti::emSquareSize() const
2561{ return engine(0)->emSquareSize(); }
2562
2563QFixed QFontEngineMulti::ascent() const
2564{ return engine(0)->ascent(); }
2565
2566QFixed QFontEngineMulti::capHeight() const
2567{ return engine(0)->capHeight(); }
2568
2569QFixed QFontEngineMulti::descent() const
2570{ return engine(0)->descent(); }
2571
2572QFixed QFontEngineMulti::leading() const
2573{
2574 return engine(0)->leading();
2575}
2576
2577QFixed QFontEngineMulti::xHeight() const
2578{
2579 return engine(0)->xHeight();
2580}
2581
2582QFixed QFontEngineMulti::averageCharWidth() const
2583{
2584 return engine(0)->averageCharWidth();
2585}
2586
2587QFixed QFontEngineMulti::lineThickness() const
2588{
2589 return engine(0)->lineThickness();
2590}
2591
2592QFixed QFontEngineMulti::underlinePosition() const
2593{
2594 return engine(0)->underlinePosition();
2595}
2596
2597qreal QFontEngineMulti::maxCharWidth() const
2598{
2599 return engine(0)->maxCharWidth();
2600}
2601
2602qreal QFontEngineMulti::minLeftBearing() const
2603{
2604 return engine(0)->minLeftBearing();
2605}
2606
2607qreal QFontEngineMulti::minRightBearing() const
2608{
2609 return engine(0)->minRightBearing();
2610}
2611
2612bool QFontEngineMulti::canRender(const QChar *string, int len) const
2613{
2614 if (engine(0)->canRender(string, len))
2615 return true;
2616
2617 int nglyphs = len;
2618
2619 QVarLengthArray<glyph_t> glyphs(nglyphs);
2620
2621 QGlyphLayout g;
2622 g.numGlyphs = nglyphs;
2623 g.glyphs = glyphs.data();
2624 if (stringToCMap(string, len, &g, &nglyphs, GlyphIndicesOnly) < 0)
2625 Q_UNREACHABLE();
2626
2627 for (int i = 0; i < nglyphs; i++) {
2628 if (glyphs[i] == 0)
2629 return false;
2630 }
2631
2632 return true;
2633}
2634
2635/* Implement alphaMapForGlyph() which is called by QPA Windows code.
2636 * Ideally, that code should be fixed to correctly handle QFontEngineMulti. */
2637
2638QImage QFontEngineMulti::alphaMapForGlyph(glyph_t glyph)
2639{
2640 const int which = highByte(glyph);
2641 return engine(which)->alphaMapForGlyph(stripped(glyph));
2642}
2643
2644QImage QFontEngineMulti::alphaMapForGlyph(glyph_t glyph, const QFixedPoint &subPixelPosition)
2645{
2646 const int which = highByte(glyph);
2647 return engine(which)->alphaMapForGlyph(stripped(glyph), subPixelPosition);
2648}
2649
2650QImage QFontEngineMulti::alphaMapForGlyph(glyph_t glyph, const QTransform &t)
2651{
2652 const int which = highByte(glyph);
2653 return engine(which)->alphaMapForGlyph(stripped(glyph), t);
2654}
2655
2656QImage QFontEngineMulti::alphaMapForGlyph(glyph_t glyph,
2657 const QFixedPoint &subPixelPosition,
2658 const QTransform &t)
2659{
2660 const int which = highByte(glyph);
2661 return engine(which)->alphaMapForGlyph(stripped(glyph), subPixelPosition, t);
2662}
2663
2664QImage QFontEngineMulti::alphaRGBMapForGlyph(glyph_t glyph,
2665 const QFixedPoint &subPixelPosition,
2666 const QTransform &t)
2667{
2668 const int which = highByte(glyph);
2669 return engine(which)->alphaRGBMapForGlyph(stripped(glyph), subPixelPosition, t);
2670}
2671
2672QList<QFontVariableAxis> QFontEngineMulti::variableAxes() const
2673{
2674 return engine(0)->variableAxes();
2675}
2676
2677/*
2678 This is used indirectly by Qt WebKit when using QTextLayout::setRawFont
2679
2680 The purpose of this is to provide the necessary font fallbacks when drawing complex
2681 text. Since Qt WebKit ends up repeatedly creating QTextLayout instances and passing them
2682 the same raw font over and over again, we want to cache the corresponding multi font engine
2683 as it may contain fallback font engines already.
2684*/
2685QFontEngine *QFontEngineMulti::createMultiFontEngine(QFontEngine *fe, int script)
2686{
2687 QFontEngine *engine = nullptr;
2688 QFontCache::Key key(fe->fontDef, script, /*multi = */true);
2689 QFontCache *fc = QFontCache::instance();
2690 // We can't rely on the fontDef (and hence the cache Key)
2691 // alone to distinguish webfonts, since these should not be
2692 // accidentally shared, even if the resulting fontcache key
2693 // is strictly identical. See:
2694 // http://www.w3.org/TR/css3-fonts/#font-face-rule
2695 const bool faceIsLocal = !fe->faceId().filename.isEmpty();
2696 QFontCache::EngineCache::Iterator it = fc->engineCache.find(key),
2697 end = fc->engineCache.end();
2698 while (it != end && it.key() == key) {
2699 Q_ASSERT(it.value().data->type() == QFontEngine::Multi);
2700 QFontEngineMulti *cachedEngine = static_cast<QFontEngineMulti *>(it.value().data);
2701 if (fe == cachedEngine->engine(0) || (faceIsLocal && fe->faceId().filename == cachedEngine->engine(0)->faceId().filename)) {
2702 engine = cachedEngine;
2703 fc->updateHitCountAndTimeStamp(it.value());
2704 break;
2705 }
2706 ++it;
2707 }
2708 if (!engine) {
2709 engine = QGuiApplicationPrivate::instance()->platformIntegration()->fontDatabase()->fontEngineMulti(fe, QFontDatabasePrivate::ExtendedScript(script));
2710 fc->insertEngine(key, engine, /* insertMulti */ !faceIsLocal);
2711 }
2712 Q_ASSERT(engine);
2713 return engine;
2714}
2715
2716QTestFontEngine::QTestFontEngine(int size)
2717 : QFontEngineBox(TestFontEngine, size)
2718{}
2719
2720QT_END_NAMESPACE
friend class QFontEngine
Definition qpainter.h:433
Combined button and popup list for selecting options.
QStringList qt_fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QFontDatabasePrivate::ExtendedScript script)
static int maxGlyphSize()
static bool qt_get_font_table_default(void *user_data, uint tag, uchar *buffer, uint *length)
static bool qSafeFromBigEndian(const uchar *source, const uchar *end, T *output)
static QFixed kerning(int left, int right, const QFontEngine::KernPair *pairs, int numPairs)
#define SET(x, y)
static void collectSingleContour(qreal x0, qreal y0, uint *grid, int x, int y, int w, int h, QPainterPath *path)
static glyph_t stripped(glyph_t glyph)
Q_GUI_EXPORT void qt_addBitmapToPath(qreal x0, qreal y0, const uchar *image_data, int bpl, int w, int h, QPainterPath *path)
#define kBearingNotInitialized
#define QT_MAX_CACHED_GLYPH_SIZE
#define GRID(x, y)
static bool qtransform_equals_no_translate(const QTransform &a, const QTransform &b)
#define kMinLeftSideBearingOffset
@ EdgeUp
@ EdgeRight
@ EdgeDown
@ EdgeLeft
#define kMinRightSideBearingOffset