source: trunk/src/gui/text/qfontengine.cpp@ 890

Last change on this file since 890 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 51.2 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtGui module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <qdebug.h>
43#include <private/qfontengine_p.h>
44
45#include "qbitmap.h"
46#include "qpainter.h"
47#include "qpainterpath.h"
48#include "qvarlengtharray.h"
49#include <qmath.h>
50#include <qendian.h>
51#include <private/qharfbuzz_p.h>
52
53QT_BEGIN_NAMESPACE
54
55static inline bool qtransform_equals_no_translate(const QTransform &a, const QTransform &b)
56{
57 if (a.type() <= QTransform::TxTranslate && b.type() <= QTransform::TxTranslate) {
58 return true;
59 } else {
60 // We always use paths for perspective text anyway, so no
61 // point in checking the full matrix...
62 Q_ASSERT(a.type() < QTransform::TxProject);
63 Q_ASSERT(b.type() < QTransform::TxProject);
64
65 return a.m11() == b.m11()
66 && a.m12() == b.m12()
67 && a.m21() == b.m21()
68 && a.m22() == b.m22();
69 }
70}
71
72// Harfbuzz helper functions
73
74static HB_Bool hb_stringToGlyphs(HB_Font font, const HB_UChar16 *string, hb_uint32 length, HB_Glyph *glyphs, hb_uint32 *numGlyphs, HB_Bool rightToLeft)
75{
76 QFontEngine *fe = (QFontEngine *)font->userData;
77
78 QVarLengthGlyphLayoutArray qglyphs(*numGlyphs);
79
80 QTextEngine::ShaperFlags shaperFlags(QTextEngine::GlyphIndicesOnly);
81 if (rightToLeft)
82 shaperFlags |= QTextEngine::RightToLeft;
83
84 int nGlyphs = *numGlyphs;
85 bool result = fe->stringToCMap(reinterpret_cast<const QChar *>(string), length, &qglyphs, &nGlyphs, shaperFlags);
86 *numGlyphs = nGlyphs;
87 if (!result)
88 return false;
89
90 for (hb_uint32 i = 0; i < *numGlyphs; ++i)
91 glyphs[i] = qglyphs.glyphs[i];
92
93 return true;
94}
95
96static void hb_getAdvances(HB_Font font, const HB_Glyph *glyphs, hb_uint32 numGlyphs, HB_Fixed *advances, int flags)
97{
98 QFontEngine *fe = (QFontEngine *)font->userData;
99
100 QVarLengthGlyphLayoutArray qglyphs(numGlyphs);
101
102 for (hb_uint32 i = 0; i < numGlyphs; ++i)
103 qglyphs.glyphs[i] = glyphs[i];
104
105 fe->recalcAdvances(&qglyphs, flags & HB_ShaperFlag_UseDesignMetrics ? QFlags<QTextEngine::ShaperFlag>(QTextEngine::DesignMetrics) : QFlags<QTextEngine::ShaperFlag>(0));
106
107 for (hb_uint32 i = 0; i < numGlyphs; ++i)
108 advances[i] = qglyphs.advances_x[i].value();
109}
110
111static HB_Bool hb_canRender(HB_Font font, const HB_UChar16 *string, hb_uint32 length)
112{
113 QFontEngine *fe = (QFontEngine *)font->userData;
114 return fe->canRender(reinterpret_cast<const QChar *>(string), length);
115}
116
117static void hb_getGlyphMetrics(HB_Font font, HB_Glyph glyph, HB_GlyphMetrics *metrics)
118{
119 QFontEngine *fe = (QFontEngine *)font->userData;
120 glyph_metrics_t m = fe->boundingBox(glyph);
121 metrics->x = m.x.value();
122 metrics->y = m.y.value();
123 metrics->width = m.width.value();
124 metrics->height = m.height.value();
125 metrics->xOffset = m.xoff.value();
126 metrics->yOffset = m.yoff.value();
127}
128
129static HB_Fixed hb_getFontMetric(HB_Font font, HB_FontMetric metric)
130{
131 if (metric == HB_FontAscent) {
132 QFontEngine *fe = (QFontEngine *)font->userData;
133 return fe->ascent().value();
134 }
135 return 0;
136}
137
138HB_Error QFontEngine::getPointInOutline(HB_Glyph glyph, int flags, hb_uint32 point, HB_Fixed *xpos, HB_Fixed *ypos, hb_uint32 *nPoints)
139{
140 Q_UNUSED(glyph)
141 Q_UNUSED(flags)
142 Q_UNUSED(point)
143 Q_UNUSED(xpos)
144 Q_UNUSED(ypos)
145 Q_UNUSED(nPoints)
146 return HB_Err_Not_Covered;
147}
148
149static HB_Error hb_getPointInOutline(HB_Font font, HB_Glyph glyph, int flags, hb_uint32 point, HB_Fixed *xpos, HB_Fixed *ypos, hb_uint32 *nPoints)
150{
151 QFontEngine *fe = (QFontEngine *)font->userData;
152 return fe->getPointInOutline(glyph, flags, point, xpos, ypos, nPoints);
153}
154
155static const HB_FontClass hb_fontClass = {
156 hb_stringToGlyphs, hb_getAdvances, hb_canRender, hb_getPointInOutline,
157 hb_getGlyphMetrics, hb_getFontMetric
158};
159
160static HB_Error hb_getSFntTable(void *font, HB_Tag tableTag, HB_Byte *buffer, HB_UInt *length)
161{
162 QFontEngine *fe = (QFontEngine *)font;
163 if (!fe->getSfntTableData(tableTag, buffer, length))
164 return HB_Err_Invalid_Argument;
165 return HB_Err_Ok;
166}
167
168// QFontEngine
169
170QFontEngine::QFontEngine()
171 : QObject()
172{
173 ref = 0;
174 cache_count = 0;
175 fsType = 0;
176 symbol = false;
177 memset(&hbFont, 0, sizeof(hbFont));
178 hbFont.klass = &hb_fontClass;
179 hbFont.userData = this;
180
181 hbFace = 0;
182 glyphFormat = -1;
183}
184
185QFontEngine::~QFontEngine()
186{
187 for (QLinkedList<GlyphCacheEntry>::const_iterator it = m_glyphCaches.constBegin(),
188 end = m_glyphCaches.constEnd(); it != end; ++it) {
189 delete it->cache;
190 }
191 m_glyphCaches.clear();
192 qHBFreeFace(hbFace);
193}
194
195QFixed QFontEngine::lineThickness() const
196{
197 // ad hoc algorithm
198 int score = fontDef.weight * fontDef.pixelSize;
199 int lw = score / 700;
200
201 // looks better with thicker line for small pointsizes
202 if (lw < 2 && score >= 1050) lw = 2;
203 if (lw == 0) lw = 1;
204
205 return lw;
206}
207
208QFixed QFontEngine::underlinePosition() const
209{
210 return ((lineThickness() * 2) + 3) / 6;
211}
212
213HB_Font QFontEngine::harfbuzzFont() const
214{
215 if (!hbFont.x_ppem) {
216 QFixed emSquare = emSquareSize();
217 hbFont.x_ppem = fontDef.pixelSize;
218 hbFont.y_ppem = fontDef.pixelSize * fontDef.stretch / 100;
219 hbFont.x_scale = (QFixed(hbFont.x_ppem * (1 << 16)) / emSquare).value();
220 hbFont.y_scale = (QFixed(hbFont.y_ppem * (1 << 16)) / emSquare).value();
221 }
222 return &hbFont;
223}
224
225HB_Face QFontEngine::harfbuzzFace() const
226{
227 if (!hbFace) {
228 hbFace = qHBNewFace(const_cast<QFontEngine *>(this), hb_getSFntTable);
229 Q_CHECK_PTR(hbFace);
230 }
231 return hbFace;
232}
233
234glyph_metrics_t QFontEngine::boundingBox(glyph_t glyph, const QTransform &matrix)
235{
236 glyph_metrics_t metrics = boundingBox(glyph);
237
238 if (matrix.type() > QTransform::TxTranslate) {
239 return metrics.transformed(matrix);
240 }
241 return metrics;
242}
243
244QFixed QFontEngine::xHeight() const
245{
246 QGlyphLayoutArray<8> glyphs;
247 int nglyphs = 7;
248 QChar x((ushort)'x');
249 stringToCMap(&x, 1, &glyphs, &nglyphs, QTextEngine::GlyphIndicesOnly);
250
251 glyph_metrics_t bb = const_cast<QFontEngine *>(this)->boundingBox(glyphs.glyphs[0]);
252 return bb.height;
253}
254
255QFixed QFontEngine::averageCharWidth() const
256{
257 QGlyphLayoutArray<8> glyphs;
258 int nglyphs = 7;
259 QChar x((ushort)'x');
260 stringToCMap(&x, 1, &glyphs, &nglyphs, QTextEngine::GlyphIndicesOnly);
261
262 glyph_metrics_t bb = const_cast<QFontEngine *>(this)->boundingBox(glyphs.glyphs[0]);
263 return bb.xoff;
264}
265
266
267void QFontEngine::getGlyphPositions(const QGlyphLayout &glyphs, const QTransform &matrix, QTextItem::RenderFlags flags,
268 QVarLengthArray<glyph_t> &glyphs_out, QVarLengthArray<QFixedPoint> &positions)
269{
270 QFixed xpos;
271 QFixed ypos;
272
273 const bool transform = matrix.m11() != 1.
274 || matrix.m12() != 0.
275 || matrix.m21() != 0.
276 || matrix.m22() != 1.;
277 if (!transform) {
278 xpos = QFixed::fromReal(matrix.dx());
279 ypos = QFixed::fromReal(matrix.dy());
280 }
281
282 int current = 0;
283 if (flags & QTextItem::RightToLeft) {
284 int i = glyphs.numGlyphs;
285 int totalKashidas = 0;
286 while(i--) {
287 xpos += glyphs.advances_x[i] + QFixed::fromFixed(glyphs.justifications[i].space_18d6);
288 ypos += glyphs.advances_y[i];
289 totalKashidas += glyphs.justifications[i].nKashidas;
290 }
291 positions.resize(glyphs.numGlyphs+totalKashidas);
292 glyphs_out.resize(glyphs.numGlyphs+totalKashidas);
293
294 i = 0;
295 while(i < glyphs.numGlyphs) {
296 if (glyphs.attributes[i].dontPrint) {
297 ++i;
298 continue;
299 }
300 xpos -= glyphs.advances_x[i];
301 ypos -= glyphs.advances_y[i];
302
303 QFixed gpos_x = xpos + glyphs.offsets[i].x;
304 QFixed gpos_y = ypos + glyphs.offsets[i].y;
305 if (transform) {
306 QPointF gpos(gpos_x.toReal(), gpos_y.toReal());
307 gpos = gpos * matrix;
308 gpos_x = QFixed::fromReal(gpos.x());
309 gpos_y = QFixed::fromReal(gpos.y());
310 }
311 positions[current].x = gpos_x;
312 positions[current].y = gpos_y;
313 glyphs_out[current] = glyphs.glyphs[i];
314 ++current;
315 if (glyphs.justifications[i].nKashidas) {
316 QChar ch(0x640); // Kashida character
317 QGlyphLayoutArray<8> g;
318 int nglyphs = 7;
319 stringToCMap(&ch, 1, &g, &nglyphs, 0);
320 for (uint k = 0; k < glyphs.justifications[i].nKashidas; ++k) {
321 xpos -= g.advances_x[0];
322 ypos -= g.advances_y[0];
323
324 QFixed gpos_x = xpos + glyphs.offsets[i].x;
325 QFixed gpos_y = ypos + glyphs.offsets[i].y;
326 if (transform) {
327 QPointF gpos(gpos_x.toReal(), gpos_y.toReal());
328 gpos = gpos * matrix;
329 gpos_x = QFixed::fromReal(gpos.x());
330 gpos_y = QFixed::fromReal(gpos.y());
331 }
332 positions[current].x = gpos_x;
333 positions[current].y = gpos_y;
334 glyphs_out[current] = g.glyphs[0];
335 ++current;
336 }
337 } else {
338 xpos -= QFixed::fromFixed(glyphs.justifications[i].space_18d6);
339 }
340 ++i;
341 }
342 } else {
343 positions.resize(glyphs.numGlyphs);
344 glyphs_out.resize(glyphs.numGlyphs);
345 int i = 0;
346 if (!transform) {
347 while (i < glyphs.numGlyphs) {
348 if (!glyphs.attributes[i].dontPrint) {
349 positions[current].x = xpos + glyphs.offsets[i].x;
350 positions[current].y = ypos + glyphs.offsets[i].y;
351 glyphs_out[current] = glyphs.glyphs[i];
352 xpos += glyphs.advances_x[i] + QFixed::fromFixed(glyphs.justifications[i].space_18d6);
353 ypos += glyphs.advances_y[i];
354 ++current;
355 }
356 ++i;
357 }
358 } else {
359 while (i < glyphs.numGlyphs) {
360 if (!glyphs.attributes[i].dontPrint) {
361 QFixed gpos_x = xpos + glyphs.offsets[i].x;
362 QFixed gpos_y = ypos + glyphs.offsets[i].y;
363 QPointF gpos(gpos_x.toReal(), gpos_y.toReal());
364 gpos = gpos * matrix;
365 positions[current].x = QFixed::fromReal(gpos.x());
366 positions[current].y = QFixed::fromReal(gpos.y());
367 glyphs_out[current] = glyphs.glyphs[i];
368 xpos += glyphs.advances_x[i] + QFixed::fromFixed(glyphs.justifications[i].space_18d6);
369 ypos += glyphs.advances_y[i];
370 ++current;
371 }
372 ++i;
373 }
374 }
375 }
376 positions.resize(current);
377 glyphs_out.resize(current);
378 Q_ASSERT(positions.size() == glyphs_out.size());
379}
380
381void QFontEngine::getGlyphBearings(glyph_t glyph, qreal *leftBearing, qreal *rightBearing)
382{
383 glyph_metrics_t gi = boundingBox(glyph);
384 bool isValid = gi.isValid();
385 if (leftBearing != 0)
386 *leftBearing = isValid ? gi.x.toReal() : 0.0;
387 if (rightBearing != 0)
388 *rightBearing = isValid ? (gi.xoff - gi.x - gi.width).toReal() : 0.0;
389}
390
391glyph_metrics_t QFontEngine::tightBoundingBox(const QGlyphLayout &glyphs)
392{
393 glyph_metrics_t overall;
394
395 QFixed ymax = 0;
396 QFixed xmax = 0;
397 for (int i = 0; i < glyphs.numGlyphs; i++) {
398 glyph_metrics_t bb = boundingBox(glyphs.glyphs[i]);
399 QFixed x = overall.xoff + glyphs.offsets[i].x + bb.x;
400 QFixed y = overall.yoff + glyphs.offsets[i].y + bb.y;
401 overall.x = qMin(overall.x, x);
402 overall.y = qMin(overall.y, y);
403 xmax = qMax(xmax, x + bb.width);
404 ymax = qMax(ymax, y + bb.height);
405 overall.xoff += bb.xoff;
406 overall.yoff += bb.yoff;
407 }
408 overall.height = qMax(overall.height, ymax - overall.y);
409 overall.width = xmax - overall.x;
410
411 return overall;
412}
413
414
415void QFontEngine::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path,
416 QTextItem::RenderFlags flags)
417{
418 if (!glyphs.numGlyphs)
419 return;
420
421 QVarLengthArray<QFixedPoint> positions;
422 QVarLengthArray<glyph_t> positioned_glyphs;
423 QTransform matrix = QTransform::fromTranslate(x, y);
424 getGlyphPositions(glyphs, matrix, flags, positioned_glyphs, positions);
425 addGlyphsToPath(positioned_glyphs.data(), positions.data(), positioned_glyphs.size(), path, flags);
426}
427
428#define GRID(x, y) grid[(y)*(w+1) + (x)]
429#define SET(x, y) (*(image_data + (y)*bpl + ((x) >> 3)) & (0x80 >> ((x) & 7)))
430
431enum { EdgeRight = 0x1,
432 EdgeDown = 0x2,
433 EdgeLeft = 0x4,
434 EdgeUp = 0x8
435};
436
437static void collectSingleContour(qreal x0, qreal y0, uint *grid, int x, int y, int w, int h, QPainterPath *path)
438{
439 Q_UNUSED(h);
440
441 path->moveTo(x + x0, y + y0);
442 while (GRID(x, y)) {
443 if (GRID(x, y) & EdgeRight) {
444 while (GRID(x, y) & EdgeRight) {
445 GRID(x, y) &= ~EdgeRight;
446 ++x;
447 }
448 Q_ASSERT(x <= w);
449 path->lineTo(x + x0, y + y0);
450 continue;
451 }
452 if (GRID(x, y) & EdgeDown) {
453 while (GRID(x, y) & EdgeDown) {
454 GRID(x, y) &= ~EdgeDown;
455 ++y;
456 }
457 Q_ASSERT(y <= h);
458 path->lineTo(x + x0, y + y0);
459 continue;
460 }
461 if (GRID(x, y) & EdgeLeft) {
462 while (GRID(x, y) & EdgeLeft) {
463 GRID(x, y) &= ~EdgeLeft;
464 --x;
465 }
466 Q_ASSERT(x >= 0);
467 path->lineTo(x + x0, y + y0);
468 continue;
469 }
470 if (GRID(x, y) & EdgeUp) {
471 while (GRID(x, y) & EdgeUp) {
472 GRID(x, y) &= ~EdgeUp;
473 --y;
474 }
475 Q_ASSERT(y >= 0);
476 path->lineTo(x + x0, y + y0);
477 continue;
478 }
479 }
480 path->closeSubpath();
481}
482
483void qt_addBitmapToPath(qreal x0, qreal y0, const uchar *image_data, int bpl, int w, int h, QPainterPath *path)
484{
485 uint *grid = new uint[(w+1)*(h+1)];
486 // set up edges
487 for (int y = 0; y <= h; ++y) {
488 for (int x = 0; x <= w; ++x) {
489 bool topLeft = (x == 0)|(y == 0) ? false : SET(x - 1, y - 1);
490 bool topRight = (x == w)|(y == 0) ? false : SET(x, y - 1);
491 bool bottomLeft = (x == 0)|(y == h) ? false : SET(x - 1, y);
492 bool bottomRight = (x == w)|(y == h) ? false : SET(x, y);
493
494 GRID(x, y) = 0;
495 if ((!topRight) & bottomRight)
496 GRID(x, y) |= EdgeRight;
497 if ((!bottomRight) & bottomLeft)
498 GRID(x, y) |= EdgeDown;
499 if ((!bottomLeft) & topLeft)
500 GRID(x, y) |= EdgeLeft;
501 if ((!topLeft) & topRight)
502 GRID(x, y) |= EdgeUp;
503 }
504 }
505
506 // collect edges
507 for (int y = 0; y < h; ++y) {
508 for (int x = 0; x < w; ++x) {
509 if (!GRID(x, y))
510 continue;
511 // found start of a contour, follow it
512 collectSingleContour(x0, y0, grid, x, y, w, h, path);
513 }
514 }
515 delete [] grid;
516}
517
518#undef GRID
519#undef SET
520
521
522void QFontEngine::addBitmapFontToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
523 QPainterPath *path, QTextItem::RenderFlags flags)
524{
525// TODO what to do with 'flags' ??
526 Q_UNUSED(flags);
527 QFixed advanceX = QFixed::fromReal(x);
528 QFixed advanceY = QFixed::fromReal(y);
529 for (int i=0; i < glyphs.numGlyphs; ++i) {
530 glyph_metrics_t metrics = boundingBox(glyphs.glyphs[i]);
531 if (metrics.width.value() == 0 || metrics.height.value() == 0) {
532 advanceX += glyphs.advances_x[i];
533 advanceY += glyphs.advances_y[i];
534 continue;
535 }
536 const QImage alphaMask = alphaMapForGlyph(glyphs.glyphs[i]);
537
538 const int w = alphaMask.width();
539 const int h = alphaMask.height();
540 const int srcBpl = alphaMask.bytesPerLine();
541 QImage bitmap;
542 if (alphaMask.depth() == 1) {
543 bitmap = alphaMask;
544 } else {
545 bitmap = QImage(w, h, QImage::Format_Mono);
546 const uchar *imageData = alphaMask.bits();
547 const int destBpl = bitmap.bytesPerLine();
548 uchar *bitmapData = bitmap.bits();
549
550 for (int yi = 0; yi < h; ++yi) {
551 const uchar *src = imageData + yi*srcBpl;
552 uchar *dst = bitmapData + yi*destBpl;
553 for (int xi = 0; xi < w; ++xi) {
554 const int byte = xi / 8;
555 const int bit = xi % 8;
556 if (bit == 0)
557 dst[byte] = 0;
558 if (src[xi])
559 dst[byte] |= 128 >> bit;
560 }
561 }
562 }
563 const uchar *bitmap_data = bitmap.bits();
564 QFixedPoint offset = glyphs.offsets[i];
565 advanceX += offset.x;
566 advanceY += offset.y;
567 qt_addBitmapToPath((advanceX + metrics.x).toReal(), (advanceY + metrics.y).toReal(), bitmap_data, bitmap.bytesPerLine(), w, h, path);
568 advanceX += glyphs.advances_x[i];
569 advanceY += glyphs.advances_y[i];
570 }
571}
572
573void QFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nGlyphs,
574 QPainterPath *path, QTextItem::RenderFlags flags)
575{
576 qreal x = positions[0].x.toReal();
577 qreal y = positions[0].y.toReal();
578 QVarLengthGlyphLayoutArray g(nGlyphs);
579
580 for (int i = 0; i < nGlyphs; ++i) {
581 g.glyphs[i] = glyphs[i];
582 if (i < nGlyphs - 1) {
583 g.advances_x[i] = positions[i+1].x - positions[i].x;
584 g.advances_y[i] = positions[i+1].y - positions[i].y;
585 } else {
586 g.advances_x[i] = QFixed::fromReal(maxCharWidth());
587 g.advances_y[i] = 0;
588 }
589 }
590
591 addBitmapFontToPath(x, y, g, path, flags);
592}
593
594QImage QFontEngine::alphaMapForGlyph(glyph_t glyph, const QTransform &t)
595{
596 QImage i = alphaMapForGlyph(glyph);
597 if (t.type() > QTransform::TxTranslate)
598 i = i.transformed(t).convertToFormat(QImage::Format_Indexed8);
599 Q_ASSERT(i.depth() <= 8); // To verify that transformed didn't change the format...
600
601 return i;
602}
603
604QImage QFontEngine::alphaRGBMapForGlyph(glyph_t glyph, int /* margin */, const QTransform &t)
605{
606 QImage alphaMask = alphaMapForGlyph(glyph, t);
607 QImage rgbMask(alphaMask.width(), alphaMask.height(), QImage::Format_RGB32);
608
609 QVector<QRgb> colorTable = alphaMask.colorTable();
610 for (int y=0; y<alphaMask.height(); ++y) {
611 uint *dst = (uint *) rgbMask.scanLine(y);
612 uchar *src = (uchar *) alphaMask.scanLine(y);
613 for (int x=0; x<alphaMask.width(); ++x) {
614 int val = qAlpha(colorTable.at(src[x]));
615 dst[x] = qRgb(val, val, val);
616 }
617 }
618
619 return rgbMask;
620}
621
622QImage QFontEngine::alphaMapForGlyph(glyph_t glyph)
623{
624 glyph_metrics_t gm = boundingBox(glyph);
625 int glyph_x = qFloor(gm.x.toReal());
626 int glyph_y = qFloor(gm.y.toReal());
627 int glyph_width = qCeil((gm.x + gm.width).toReal()) - glyph_x;
628 int glyph_height = qCeil((gm.y + gm.height).toReal()) - glyph_y;
629
630 if (glyph_width <= 0 || glyph_height <= 0)
631 return QImage();
632 QFixedPoint pt;
633 pt.x = -glyph_x;
634 pt.y = -glyph_y; // the baseline
635 QPainterPath path;
636 QImage im(glyph_width + 4, glyph_height, QImage::Format_ARGB32_Premultiplied);
637 im.fill(Qt::transparent);
638 QPainter p(&im);
639 p.setRenderHint(QPainter::Antialiasing);
640 addGlyphsToPath(&glyph, &pt, 1, &path, 0);
641 p.setPen(Qt::NoPen);
642 p.setBrush(Qt::black);
643 p.drawPath(path);
644 p.end();
645
646 QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
647 QVector<QRgb> colors(256);
648 for (int i=0; i<256; ++i)
649 colors[i] = qRgba(0, 0, 0, i);
650 indexed.setColorTable(colors);
651
652 for (int y=0; y<im.height(); ++y) {
653 uchar *dst = (uchar *) indexed.scanLine(y);
654 uint *src = (uint *) im.scanLine(y);
655 for (int x=0; x<im.width(); ++x)
656 dst[x] = qAlpha(src[x]);
657 }
658
659 return indexed;
660}
661
662void QFontEngine::removeGlyphFromCache(glyph_t)
663{
664}
665
666QFontEngine::Properties QFontEngine::properties() const
667{
668 Properties p;
669 QByteArray psname = QFontEngine::convertToPostscriptFontFamilyName(fontDef.family.toUtf8());
670 psname += '-';
671 psname += QByteArray::number(fontDef.style);
672 psname += '-';
673 psname += QByteArray::number(fontDef.weight);
674
675 p.postscriptName = psname;
676 p.ascent = ascent();
677 p.descent = descent();
678 p.leading = leading();
679 p.emSquare = p.ascent;
680 p.boundingBox = QRectF(0, -p.ascent.toReal(), maxCharWidth(), (p.ascent + p.descent).toReal());
681 p.italicAngle = 0;
682 p.capHeight = p.ascent;
683 p.lineWidth = lineThickness();
684 return p;
685}
686
687void QFontEngine::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
688{
689 *metrics = boundingBox(glyph);
690 QFixedPoint p;
691 p.x = 0;
692 p.y = 0;
693 addGlyphsToPath(&glyph, &p, 1, path, QFlag(0));
694}
695
696QByteArray QFontEngine::getSfntTable(uint tag) const
697{
698 QByteArray table;
699 uint len = 0;
700 if (!getSfntTableData(tag, 0, &len))
701 return table;
702 if (!len)
703 return table;
704 table.resize(len);
705 if (!getSfntTableData(tag, reinterpret_cast<uchar *>(table.data()), &len))
706 return QByteArray();
707 return table;
708}
709
710void QFontEngine::setGlyphCache(void *key, QFontEngineGlyphCache *data)
711{
712 Q_ASSERT(data);
713
714 GlyphCacheEntry entry = { key, data };
715 if (m_glyphCaches.contains(entry))
716 return;
717
718 // Limit the glyph caches to 4. This covers all 90 degree rotations and limits
719 // memory use when there is continuous or random rotation
720 if (m_glyphCaches.size() == 4)
721 delete m_glyphCaches.takeLast().cache;
722
723 m_glyphCaches.push_front(entry);
724
725}
726
727QFontEngineGlyphCache *QFontEngine::glyphCache(void *key, QFontEngineGlyphCache::Type type, const QTransform &transform) const
728{
729 for (QLinkedList<GlyphCacheEntry>::const_iterator it = m_glyphCaches.constBegin(), end = m_glyphCaches.constEnd(); it != end; ++it) {
730 QFontEngineGlyphCache *c = it->cache;
731 if (key == it->context
732 && type == c->cacheType()
733 && qtransform_equals_no_translate(c->m_transform, transform)) {
734 return c;
735 }
736 }
737 return 0;
738}
739
740#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN) || defined(Q_WS_PM) || defined(Q_WS_PM)
741static inline QFixed kerning(int left, int right, const QFontEngine::KernPair *pairs, int numPairs)
742{
743 uint left_right = (left << 16) + right;
744
745 left = 0, right = numPairs - 1;
746 while (left <= right) {
747 int middle = left + ( ( right - left ) >> 1 );
748
749 if(pairs[middle].left_right == left_right)
750 return pairs[middle].adjust;
751
752 if (pairs[middle].left_right < left_right)
753 left = middle + 1;
754 else
755 right = middle - 1;
756 }
757 return 0;
758}
759
760void QFontEngine::doKerning(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
761{
762 int numPairs = kerning_pairs.size();
763 if(!numPairs)
764 return;
765
766 const KernPair *pairs = kerning_pairs.constData();
767
768 if(flags & QTextEngine::DesignMetrics) {
769 for(int i = 0; i < glyphs->numGlyphs - 1; ++i)
770 glyphs->advances_x[i] += kerning(glyphs->glyphs[i], glyphs->glyphs[i+1] , pairs, numPairs);
771 } else {
772 for(int i = 0; i < glyphs->numGlyphs - 1; ++i)
773 glyphs->advances_x[i] += qRound(kerning(glyphs->glyphs[i], glyphs->glyphs[i+1] , pairs, numPairs));
774 }
775}
776
777void QFontEngine::loadKerningPairs(QFixed scalingFactor)
778{
779 kerning_pairs.clear();
780
781 QByteArray tab = getSfntTable(MAKE_TAG('k', 'e', 'r', 'n'));
782 if (tab.isEmpty())
783 return;
784
785 const uchar *table = reinterpret_cast<const uchar *>(tab.constData());
786
787 unsigned short version = qFromBigEndian<quint16>(table);
788 if (version != 0) {
789// qDebug("wrong version");
790 return;
791 }
792
793 unsigned short numTables = qFromBigEndian<quint16>(table + 2);
794 {
795 int offset = 4;
796 for(int i = 0; i < numTables; ++i) {
797 if (offset + 6 > tab.size()) {
798// qDebug("offset out of bounds");
799 goto end;
800 }
801 const uchar *header = table + offset;
802
803 ushort version = qFromBigEndian<quint16>(header);
804 ushort length = qFromBigEndian<quint16>(header+2);
805 ushort coverage = qFromBigEndian<quint16>(header+4);
806// qDebug("subtable: version=%d, coverage=%x",version, coverage);
807 if(version == 0 && coverage == 0x0001) {
808 if (offset + length > tab.size()) {
809// qDebug("length ouf ot bounds");
810 goto end;
811 }
812 const uchar *data = table + offset + 6;
813
814 ushort nPairs = qFromBigEndian<quint16>(data);
815 if(nPairs * 6 + 8 > length - 6) {
816// qDebug("corrupt table!");
817 // corrupt table
818 goto end;
819 }
820
821 int off = 8;
822 for(int i = 0; i < nPairs; ++i) {
823 QFontEngine::KernPair p;
824 p.left_right = (((uint)qFromBigEndian<quint16>(data+off)) << 16) + qFromBigEndian<quint16>(data+off+2);
825 p.adjust = QFixed(((int)(short)qFromBigEndian<quint16>(data+off+4))) / scalingFactor;
826 kerning_pairs.append(p);
827 off += 6;
828 }
829 }
830 offset += length;
831 }
832 }
833end:
834 qSort(kerning_pairs);
835// for (int i = 0; i < kerning_pairs.count(); ++i)
836// qDebug() << 'i' << i << "left_right" << hex << kerning_pairs.at(i).left_right;
837}
838
839#else
840void QFontEngine::doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const
841{
842}
843#endif
844
845int QFontEngine::glyphCount() const
846{
847 QByteArray maxpTable = getSfntTable(MAKE_TAG('m', 'a', 'x', 'p'));
848 if (maxpTable.size() < 6)
849 return 0;
850 return qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(maxpTable.constData() + 4));
851}
852
853const uchar *QFontEngine::getCMap(const uchar *table, uint tableSize, bool *isSymbolFont, int *cmapSize)
854{
855 const uchar *header = table;
856 if (tableSize < 4)
857 return 0;
858
859 const uchar *endPtr = table + tableSize;
860
861 // version check
862 if (qFromBigEndian<quint16>(header) != 0)
863 return 0;
864
865 unsigned short numTables = qFromBigEndian<quint16>(header + 2);
866 const uchar *maps = table + 4;
867 if (maps + 8 * numTables > endPtr)
868 return 0;
869
870 enum {
871 Invalid,
872 AppleRoman,
873 Symbol,
874 Unicode11,
875 Unicode,
876 MicrosoftUnicode,
877 MicrosoftUnicodeExtended
878 };
879
880 int symbolTable = -1;
881 int tableToUse = -1;
882 int score = Invalid;
883 for (int n = 0; n < numTables; ++n) {
884 const quint16 platformId = qFromBigEndian<quint16>(maps + 8 * n);
885 const quint16 platformSpecificId = qFromBigEndian<quint16>(maps + 8 * n + 2);
886 switch (platformId) {
887 case 0: // Unicode
888 if (score < Unicode &&
889 (platformSpecificId == 0 ||
890 platformSpecificId == 2 ||
891 platformSpecificId == 3)) {
892 tableToUse = n;
893 score = Unicode;
894 } else if (score < Unicode11 && platformSpecificId == 1) {
895 tableToUse = n;
896 score = Unicode11;
897 }
898 break;
899 case 1: // Apple
900 if (score < AppleRoman && platformSpecificId == 0) { // Apple Roman
901 tableToUse = n;
902 score = AppleRoman;
903 }
904 break;
905 case 3: // Microsoft
906 switch (platformSpecificId) {
907 case 0:
908 symbolTable = n;
909 if (score < Symbol) {
910 tableToUse = n;
911 score = Symbol;
912 }
913 break;
914 case 1:
915 if (score < MicrosoftUnicode) {
916 tableToUse = n;
917 score = MicrosoftUnicode;
918 }
919 break;
920 case 0xa:
921 if (score < MicrosoftUnicodeExtended) {
922 tableToUse = n;
923 score = MicrosoftUnicodeExtended;
924 }
925 break;
926 default:
927 break;
928 }
929 default:
930 break;
931 }
932 }
933 if(tableToUse < 0)
934 return 0;
935
936resolveTable:
937 *isSymbolFont = (symbolTable > -1);
938
939 unsigned int unicode_table = qFromBigEndian<quint32>(maps + 8*tableToUse + 4);
940
941 if (!unicode_table || unicode_table + 8 > tableSize)
942 return 0;
943
944 // get the header of the unicode table
945 header = table + unicode_table;
946
947 unsigned short format = qFromBigEndian<quint16>(header);
948 unsigned int length;
949 if(format < 8)
950 length = qFromBigEndian<quint16>(header + 2);
951 else
952 length = qFromBigEndian<quint32>(header + 4);
953
954 if (table + unicode_table + length > endPtr)
955 return 0;
956 *cmapSize = length;
957
958 // To support symbol fonts that contain a unicode table for the symbol area
959 // we check the cmap tables and fall back to symbol font unless that would
960 // involve losing information from the unicode table
961 if (symbolTable > -1 && ((score == Unicode) || (score == Unicode11))) {
962 const uchar *selectedTable = table + unicode_table;
963
964 // Check that none of the latin1 range are in the unicode table
965 bool unicodeTableHasLatin1 = false;
966 for (int uc=0x00; uc<0x100; ++uc) {
967 if (getTrueTypeGlyphIndex(selectedTable, uc) != 0) {
968 unicodeTableHasLatin1 = true;
969 break;
970 }
971 }
972
973 // Check that at least one symbol char is in the unicode table
974 bool unicodeTableHasSymbols = false;
975 if (!unicodeTableHasLatin1) {
976 for (int uc=0xf000; uc<0xf100; ++uc) {
977 if (getTrueTypeGlyphIndex(selectedTable, uc) != 0) {
978 unicodeTableHasSymbols = true;
979 break;
980 }
981 }
982 }
983
984 // Fall back to symbol table
985 if (!unicodeTableHasLatin1 && unicodeTableHasSymbols) {
986 tableToUse = symbolTable;
987 score = Symbol;
988 goto resolveTable;
989 }
990 }
991
992 return table + unicode_table;
993}
994
995quint32 QFontEngine::getTrueTypeGlyphIndex(const uchar *cmap, uint unicode)
996{
997 unsigned short format = qFromBigEndian<quint16>(cmap);
998 if (format == 0) {
999 if (unicode < 256)
1000 return (int) *(cmap+6+unicode);
1001 } else if (format == 4) {
1002 /* some fonts come with invalid cmap tables, where the last segment
1003 specified end = start = rangeoffset = 0xffff, delta = 0x0001
1004 Since 0xffff is never a valid Unicode char anyway, we just get rid of the issue
1005 by returning 0 for 0xffff
1006 */
1007 if(unicode >= 0xffff)
1008 return 0;
1009 quint16 segCountX2 = qFromBigEndian<quint16>(cmap + 6);
1010 const unsigned char *ends = cmap + 14;
1011 int i = 0;
1012 for (; i < segCountX2/2 && qFromBigEndian<quint16>(ends + 2*i) < unicode; i++) {}
1013
1014 const unsigned char *idx = ends + segCountX2 + 2 + 2*i;
1015 quint16 startIndex = qFromBigEndian<quint16>(idx);
1016
1017 if (startIndex > unicode)
1018 return 0;
1019
1020 idx += segCountX2;
1021 qint16 idDelta = (qint16)qFromBigEndian<quint16>(idx);
1022 idx += segCountX2;
1023 quint16 idRangeoffset_t = (quint16)qFromBigEndian<quint16>(idx);
1024
1025 quint16 glyphIndex;
1026 if (idRangeoffset_t) {
1027 quint16 id = qFromBigEndian<quint16>(idRangeoffset_t + 2*(unicode - startIndex) + idx);
1028 if (id)
1029 glyphIndex = (idDelta + id) % 0x10000;
1030 else
1031 glyphIndex = 0;
1032 } else {
1033 glyphIndex = (idDelta + unicode) % 0x10000;
1034 }
1035 return glyphIndex;
1036 } else if (format == 6) {
1037 quint16 tableSize = qFromBigEndian<quint16>(cmap + 2);
1038
1039 quint16 firstCode6 = qFromBigEndian<quint16>(cmap + 6);
1040 if (unicode < firstCode6)
1041 return 0;
1042
1043 quint16 entryCount6 = qFromBigEndian<quint16>(cmap + 8);
1044 if (entryCount6 * 2 + 10 > tableSize)
1045 return 0;
1046
1047 quint16 sentinel6 = firstCode6 + entryCount6;
1048 if (unicode >= sentinel6)
1049 return 0;
1050
1051 quint16 entryIndex6 = unicode - firstCode6;
1052 return qFromBigEndian<quint16>(cmap + 10 + (entryIndex6 * 2));
1053 } else if (format == 12) {
1054 quint32 nGroups = qFromBigEndian<quint32>(cmap + 12);
1055
1056 cmap += 16; // move to start of groups
1057
1058 int left = 0, right = nGroups - 1;
1059 while (left <= right) {
1060 int middle = left + ( ( right - left ) >> 1 );
1061
1062 quint32 startCharCode = qFromBigEndian<quint32>(cmap + 12*middle);
1063 if(unicode < startCharCode)
1064 right = middle - 1;
1065 else {
1066 quint32 endCharCode = qFromBigEndian<quint32>(cmap + 12*middle + 4);
1067 if(unicode <= endCharCode)
1068 return qFromBigEndian<quint32>(cmap + 12*middle + 8) + unicode - startCharCode;
1069 left = middle + 1;
1070 }
1071 }
1072 } else {
1073 qDebug("cmap table of format %d not implemented", format);
1074 }
1075
1076 return 0;
1077}
1078
1079QByteArray QFontEngine::convertToPostscriptFontFamilyName(const QByteArray &family)
1080{
1081 QByteArray f = family;
1082 f.replace(' ', "");
1083 f.replace('(', "");
1084 f.replace(')', "");
1085 f.replace('<', "");
1086 f.replace('>', "");
1087 f.replace('[', "");
1088 f.replace(']', "");
1089 f.replace('{', "");
1090 f.replace('}', "");
1091 f.replace('/', "");
1092 f.replace('%', "");
1093 return f;
1094}
1095
1096Q_GLOBAL_STATIC_WITH_INITIALIZER(QVector<QRgb>, qt_grayPalette, {
1097 x->resize(256);
1098 QRgb *it = x->data();
1099 for (int i = 0; i < x->size(); ++i, ++it)
1100 *it = 0xff000000 | i | (i<<8) | (i<<16);
1101})
1102
1103const QVector<QRgb> &QFontEngine::grayPalette()
1104{
1105 return *qt_grayPalette();
1106}
1107
1108QFixed QFontEngine::lastRightBearing(const QGlyphLayout &glyphs, bool round)
1109{
1110 if (glyphs.numGlyphs >= 1) {
1111 glyph_t glyph = glyphs.glyphs[glyphs.numGlyphs - 1];
1112 glyph_metrics_t gi = boundingBox(glyph);
1113 if (gi.isValid())
1114 return round ? QFixed(qRound(gi.xoff - gi.x - gi.width))
1115 : QFixed(gi.xoff - gi.x - gi.width);
1116 }
1117 return 0;
1118}
1119
1120// ------------------------------------------------------------------
1121// The box font engine
1122// ------------------------------------------------------------------
1123
1124QFontEngineBox::QFontEngineBox(int size)
1125 : _size(size)
1126{
1127 cache_cost = sizeof(QFontEngineBox);
1128}
1129
1130QFontEngineBox::~QFontEngineBox()
1131{
1132}
1133
1134bool QFontEngineBox::stringToCMap(const QChar *, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags) const
1135{
1136 if (*nglyphs < len) {
1137 *nglyphs = len;
1138 return false;
1139 }
1140
1141 for (int i = 0; i < len; i++) {
1142 glyphs->glyphs[i] = 0;
1143 glyphs->advances_x[i] = _size;
1144 glyphs->advances_y[i] = 0;
1145 }
1146
1147 *nglyphs = len;
1148 glyphs->numGlyphs = len;
1149 return true;
1150}
1151
1152void QFontEngineBox::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags) const
1153{
1154 for (int i = 0; i < glyphs->numGlyphs; i++) {
1155 glyphs->advances_x[i] = _size;
1156 glyphs->advances_y[i] = 0;
1157 }
1158}
1159
1160void QFontEngineBox::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags)
1161{
1162 if (!glyphs.numGlyphs)
1163 return;
1164
1165 QVarLengthArray<QFixedPoint> positions;
1166 QVarLengthArray<glyph_t> positioned_glyphs;
1167 QTransform matrix = QTransform::fromTranslate(x, y - _size);
1168 getGlyphPositions(glyphs, matrix, flags, positioned_glyphs, positions);
1169
1170 QSize s(_size - 3, _size - 3);
1171 for (int k = 0; k < positions.size(); k++)
1172 path->addRect(QRectF(positions[k].toPointF(), s));
1173}
1174
1175glyph_metrics_t QFontEngineBox::boundingBox(const QGlyphLayout &glyphs)
1176{
1177 glyph_metrics_t overall;
1178 overall.width = _size*glyphs.numGlyphs;
1179 overall.height = _size;
1180 overall.xoff = overall.width;
1181 return overall;
1182}
1183
1184#if defined(Q_WS_QWS)
1185void QFontEngineBox::draw(QPaintEngine *p, qreal x, qreal y, const QTextItemInt &ti)
1186{
1187 if (!ti.glyphs.numGlyphs)
1188 return;
1189
1190 // any fixes here should probably also be done in QPaintEnginePrivate::drawBoxTextItem
1191 QSize s(_size - 3, _size - 3);
1192
1193 QVarLengthArray<QFixedPoint> positions;
1194 QVarLengthArray<glyph_t> glyphs;
1195 QTransform matrix = QTransform::fromTranslate(x, y - _size);
1196 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
1197 if (glyphs.size() == 0)
1198 return;
1199
1200
1201 QPainter *painter = p->painter();
1202 painter->save();
1203 painter->setBrush(Qt::NoBrush);
1204 QPen pen = painter->pen();
1205 pen.setWidthF(lineThickness().toReal());
1206 painter->setPen(pen);
1207 for (int k = 0; k < positions.size(); k++)
1208 painter->drawRect(QRectF(positions[k].toPointF(), s));
1209 painter->restore();
1210}
1211#endif
1212
1213glyph_metrics_t QFontEngineBox::boundingBox(glyph_t)
1214{
1215 return glyph_metrics_t(0, -_size, _size, _size, _size, 0);
1216}
1217
1218
1219
1220QFixed QFontEngineBox::ascent() const
1221{
1222 return _size;
1223}
1224
1225QFixed QFontEngineBox::descent() const
1226{
1227 return 0;
1228}
1229
1230QFixed QFontEngineBox::leading() const
1231{
1232 QFixed l = _size * QFixed::fromReal(qreal(0.15));
1233 return l.ceil();
1234}
1235
1236qreal QFontEngineBox::maxCharWidth() const
1237{
1238 return _size;
1239}
1240
1241#ifdef Q_WS_X11
1242int QFontEngineBox::cmap() const
1243{
1244 return -1;
1245}
1246#endif
1247
1248const char *QFontEngineBox::name() const
1249{
1250 return "null";
1251}
1252
1253bool QFontEngineBox::canRender(const QChar *, int)
1254{
1255 return true;
1256}
1257
1258QFontEngine::Type QFontEngineBox::type() const
1259{
1260 return Box;
1261}
1262
1263QImage QFontEngineBox::alphaMapForGlyph(glyph_t)
1264{
1265 QImage image(_size, _size, QImage::Format_Indexed8);
1266 QVector<QRgb> colors(256);
1267 for (int i=0; i<256; ++i)
1268 colors[i] = qRgba(0, 0, 0, i);
1269 image.setColorTable(colors);
1270 image.fill(0);
1271
1272 // can't use qpainter for index8; so use setPixel to draw our rectangle.
1273 for (int i=2; i <= _size-3; ++i) {
1274 image.setPixel(i, 2, 255);
1275 image.setPixel(i, _size-3, 255);
1276 image.setPixel(2, i, 255);
1277 image.setPixel(_size-3, i, 255);
1278 }
1279 return image;
1280}
1281
1282// ------------------------------------------------------------------
1283// Multi engine
1284// ------------------------------------------------------------------
1285
1286static inline uchar highByte(glyph_t glyph)
1287{ return glyph >> 24; }
1288
1289// strip high byte from glyph
1290static inline glyph_t stripped(glyph_t glyph)
1291{ return glyph & 0x00ffffff; }
1292
1293QFontEngineMulti::QFontEngineMulti(int engineCount)
1294{
1295 engines.fill(0, engineCount);
1296 cache_cost = 0;
1297}
1298
1299QFontEngineMulti::~QFontEngineMulti()
1300{
1301 for (int i = 0; i < engines.size(); ++i) {
1302 QFontEngine *fontEngine = engines.at(i);
1303 if (fontEngine) {
1304 fontEngine->ref.deref();
1305 if (fontEngine->cache_count == 0 && fontEngine->ref == 0)
1306 delete fontEngine;
1307 }
1308 }
1309}
1310
1311bool QFontEngineMulti::stringToCMap(const QChar *str, int len,
1312 QGlyphLayout *glyphs, int *nglyphs,
1313 QTextEngine::ShaperFlags flags) const
1314{
1315 int ng = *nglyphs;
1316 if (!engine(0)->stringToCMap(str, len, glyphs, &ng, flags))
1317 return false;
1318
1319 int glyph_pos = 0;
1320 for (int i = 0; i < len; ++i) {
1321 bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
1322 && str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
1323
1324 if (glyphs->glyphs[glyph_pos] == 0 && str[i].category() != QChar::Separator_Line) {
1325 QGlyphLayoutInstance tmp = glyphs->instance(glyph_pos);
1326 for (int x = 1; x < engines.size(); ++x) {
1327 QFontEngine *engine = engines.at(x);
1328 if (!engine) {
1329 const_cast<QFontEngineMulti *>(this)->loadEngine(x);
1330 engine = engines.at(x);
1331 }
1332 Q_ASSERT(engine != 0);
1333 if (engine->type() == Box)
1334 continue;
1335 glyphs->advances_x[glyph_pos] = glyphs->advances_y[glyph_pos] = 0;
1336 glyphs->offsets[glyph_pos] = QFixedPoint();
1337 int num = 2;
1338 QGlyphLayout offs = glyphs->mid(glyph_pos, num);
1339 engine->stringToCMap(str + i, surrogate ? 2 : 1, &offs, &num, flags);
1340 Q_ASSERT(num == 1); // surrogates only give 1 glyph
1341 if (glyphs->glyphs[glyph_pos]) {
1342 // set the high byte to indicate which engine the glyph came from
1343 glyphs->glyphs[glyph_pos] |= (x << 24);
1344 break;
1345 }
1346 }
1347 // ensure we use metrics from the 1st font when we use the fallback image.
1348 if (!glyphs->glyphs[glyph_pos]) {
1349 glyphs->setInstance(glyph_pos, tmp);
1350 }
1351 }
1352 if (surrogate)
1353 ++i;
1354 ++glyph_pos;
1355 }
1356
1357 *nglyphs = ng;
1358 glyphs->numGlyphs = ng;
1359 return true;
1360}
1361
1362glyph_metrics_t QFontEngineMulti::boundingBox(const QGlyphLayout &glyphs)
1363{
1364 if (glyphs.numGlyphs <= 0)
1365 return glyph_metrics_t();
1366
1367 glyph_metrics_t overall;
1368
1369 int which = highByte(glyphs.glyphs[0]);
1370 int start = 0;
1371 int end, i;
1372 for (end = 0; end < glyphs.numGlyphs; ++end) {
1373 const int e = highByte(glyphs.glyphs[end]);
1374 if (e == which)
1375 continue;
1376
1377 // set the high byte to zero
1378 for (i = start; i < end; ++i)
1379 glyphs.glyphs[i] = stripped(glyphs.glyphs[i]);
1380
1381 // merge the bounding box for this run
1382 const glyph_metrics_t gm = engine(which)->boundingBox(glyphs.mid(start, end - start));
1383
1384 overall.x = qMin(overall.x, gm.x);
1385 overall.y = qMin(overall.y, gm.y);
1386 overall.width = overall.xoff + gm.width;
1387 overall.height = qMax(overall.height + overall.y, gm.height + gm.y) -
1388 qMin(overall.y, gm.y);
1389 overall.xoff += gm.xoff;
1390 overall.yoff += gm.yoff;
1391
1392 // reset the high byte for all glyphs
1393 const int hi = which << 24;
1394 for (i = start; i < end; ++i)
1395 glyphs.glyphs[i] = hi | glyphs.glyphs[i];
1396
1397 // change engine
1398 start = end;
1399 which = e;
1400 }
1401
1402 // set the high byte to zero
1403 for (i = start; i < end; ++i)
1404 glyphs.glyphs[i] = stripped(glyphs.glyphs[i]);
1405
1406 // merge the bounding box for this run
1407 const glyph_metrics_t gm = engine(which)->boundingBox(glyphs.mid(start, end - start));
1408
1409 overall.x = qMin(overall.x, gm.x);
1410 overall.y = qMin(overall.y, gm.y);
1411 overall.width = overall.xoff + gm.width;
1412 overall.height = qMax(overall.height + overall.y, gm.height + gm.y) -
1413 qMin(overall.y, gm.y);
1414 overall.xoff += gm.xoff;
1415 overall.yoff += gm.yoff;
1416
1417 // reset the high byte for all glyphs
1418 const int hi = which << 24;
1419 for (i = start; i < end; ++i)
1420 glyphs.glyphs[i] = hi | glyphs.glyphs[i];
1421
1422 return overall;
1423}
1424
1425void QFontEngineMulti::getGlyphBearings(glyph_t glyph, qreal *leftBearing, qreal *rightBearing)
1426{
1427 int which = highByte(glyph);
1428 engine(which)->getGlyphBearings(stripped(glyph), leftBearing, rightBearing);
1429}
1430
1431void QFontEngineMulti::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
1432 QPainterPath *path, QTextItem::RenderFlags flags)
1433{
1434 if (glyphs.numGlyphs <= 0)
1435 return;
1436
1437 int which = highByte(glyphs.glyphs[0]);
1438 int start = 0;
1439 int end, i;
1440 if (flags & QTextItem::RightToLeft) {
1441 for (int gl = 0; gl < glyphs.numGlyphs; gl++) {
1442 x += glyphs.advances_x[gl].toReal();
1443 y += glyphs.advances_y[gl].toReal();
1444 }
1445 }
1446 for (end = 0; end < glyphs.numGlyphs; ++end) {
1447 const int e = highByte(glyphs.glyphs[end]);
1448 if (e == which)
1449 continue;
1450
1451 if (flags & QTextItem::RightToLeft) {
1452 for (i = start; i < end; ++i) {
1453 x -= glyphs.advances_x[i].toReal();
1454 y -= glyphs.advances_y[i].toReal();
1455 }
1456 }
1457
1458 // set the high byte to zero
1459 for (i = start; i < end; ++i)
1460 glyphs.glyphs[i] = stripped(glyphs.glyphs[i]);
1461 engine(which)->addOutlineToPath(x, y, glyphs.mid(start, end - start), path, flags);
1462 // reset the high byte for all glyphs and update x and y
1463 const int hi = which << 24;
1464 for (i = start; i < end; ++i)
1465 glyphs.glyphs[i] = hi | glyphs.glyphs[i];
1466
1467 if (!(flags & QTextItem::RightToLeft)) {
1468 for (i = start; i < end; ++i) {
1469 x += glyphs.advances_x[i].toReal();
1470 y += glyphs.advances_y[i].toReal();
1471 }
1472 }
1473
1474 // change engine
1475 start = end;
1476 which = e;
1477 }
1478
1479 if (flags & QTextItem::RightToLeft) {
1480 for (i = start; i < end; ++i) {
1481 x -= glyphs.advances_x[i].toReal();
1482 y -= glyphs.advances_y[i].toReal();
1483 }
1484 }
1485
1486 // set the high byte to zero
1487 for (i = start; i < end; ++i)
1488 glyphs.glyphs[i] = stripped(glyphs.glyphs[i]);
1489
1490 engine(which)->addOutlineToPath(x, y, glyphs.mid(start, end - start), path, flags);
1491
1492 // reset the high byte for all glyphs
1493 const int hi = which << 24;
1494 for (i = start; i < end; ++i)
1495 glyphs.glyphs[i] = hi | glyphs.glyphs[i];
1496}
1497
1498void QFontEngineMulti::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
1499{
1500 if (glyphs->numGlyphs <= 0)
1501 return;
1502
1503 int which = highByte(glyphs->glyphs[0]);
1504 int start = 0;
1505 int end, i;
1506 for (end = 0; end < glyphs->numGlyphs; ++end) {
1507 const int e = highByte(glyphs->glyphs[end]);
1508 if (e == which)
1509 continue;
1510
1511 // set the high byte to zero
1512 for (i = start; i < end; ++i)
1513 glyphs->glyphs[i] = stripped(glyphs->glyphs[i]);
1514
1515 QGlyphLayout offs = glyphs->mid(start, end - start);
1516 engine(which)->recalcAdvances(&offs, flags);
1517
1518 // reset the high byte for all glyphs and update x and y
1519 const int hi = which << 24;
1520 for (i = start; i < end; ++i)
1521 glyphs->glyphs[i] = hi | glyphs->glyphs[i];
1522
1523 // change engine
1524 start = end;
1525 which = e;
1526 }
1527
1528 // set the high byte to zero
1529 for (i = start; i < end; ++i)
1530 glyphs->glyphs[i] = stripped(glyphs->glyphs[i]);
1531
1532 QGlyphLayout offs = glyphs->mid(start, end - start);
1533 engine(which)->recalcAdvances(&offs, flags);
1534
1535 // reset the high byte for all glyphs
1536 const int hi = which << 24;
1537 for (i = start; i < end; ++i)
1538 glyphs->glyphs[i] = hi | glyphs->glyphs[i];
1539}
1540
1541void QFontEngineMulti::doKerning(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
1542{
1543 if (glyphs->numGlyphs <= 0)
1544 return;
1545
1546 int which = highByte(glyphs->glyphs[0]);
1547 int start = 0;
1548 int end, i;
1549 for (end = 0; end < glyphs->numGlyphs; ++end) {
1550 const int e = highByte(glyphs->glyphs[end]);
1551 if (e == which)
1552 continue;
1553
1554 // set the high byte to zero
1555 for (i = start; i < end; ++i)
1556 glyphs->glyphs[i] = stripped(glyphs->glyphs[i]);
1557
1558 QGlyphLayout offs = glyphs->mid(start, end - start);
1559 engine(which)->doKerning(&offs, flags);
1560
1561 // reset the high byte for all glyphs and update x and y
1562 const int hi = which << 24;
1563 for (i = start; i < end; ++i)
1564 glyphs->glyphs[i] = hi | glyphs->glyphs[i];
1565
1566 // change engine
1567 start = end;
1568 which = e;
1569 }
1570
1571 // set the high byte to zero
1572 for (i = start; i < end; ++i)
1573 glyphs->glyphs[i] = stripped(glyphs->glyphs[i]);
1574
1575 QGlyphLayout offs = glyphs->mid(start, end - start);
1576 engine(which)->doKerning(&offs, flags);
1577
1578 // reset the high byte for all glyphs
1579 const int hi = which << 24;
1580 for (i = start; i < end; ++i)
1581 glyphs->glyphs[i] = hi | glyphs->glyphs[i];
1582}
1583
1584glyph_metrics_t QFontEngineMulti::boundingBox(glyph_t glyph)
1585{
1586 const int which = highByte(glyph);
1587 Q_ASSERT(which < engines.size());
1588 return engine(which)->boundingBox(stripped(glyph));
1589}
1590
1591QFixed QFontEngineMulti::ascent() const
1592{ return engine(0)->ascent(); }
1593
1594QFixed QFontEngineMulti::descent() const
1595{ return engine(0)->descent(); }
1596
1597QFixed QFontEngineMulti::leading() const
1598{
1599 return engine(0)->leading();
1600}
1601
1602QFixed QFontEngineMulti::xHeight() const
1603{
1604 return engine(0)->xHeight();
1605}
1606
1607QFixed QFontEngineMulti::averageCharWidth() const
1608{
1609 return engine(0)->averageCharWidth();
1610}
1611
1612QFixed QFontEngineMulti::lineThickness() const
1613{
1614 return engine(0)->lineThickness();
1615}
1616
1617QFixed QFontEngineMulti::underlinePosition() const
1618{
1619 return engine(0)->underlinePosition();
1620}
1621
1622qreal QFontEngineMulti::maxCharWidth() const
1623{
1624 return engine(0)->maxCharWidth();
1625}
1626
1627qreal QFontEngineMulti::minLeftBearing() const
1628{
1629 return engine(0)->minLeftBearing();
1630}
1631
1632qreal QFontEngineMulti::minRightBearing() const
1633{
1634 return engine(0)->minRightBearing();
1635}
1636
1637bool QFontEngineMulti::canRender(const QChar *string, int len)
1638{
1639 if (engine(0)->canRender(string, len))
1640 return true;
1641
1642 QVarLengthGlyphLayoutArray glyphs(len);
1643 int nglyphs = len;
1644 if (stringToCMap(string, len, &glyphs, &nglyphs, QTextEngine::GlyphIndicesOnly) == false) {
1645 glyphs.resize(nglyphs);
1646 stringToCMap(string, len, &glyphs, &nglyphs, QTextEngine::GlyphIndicesOnly);
1647 }
1648
1649 bool allExist = true;
1650 for (int i = 0; i < nglyphs; i++) {
1651 if (!glyphs.glyphs[i]) {
1652 allExist = false;
1653 break;
1654 }
1655 }
1656
1657 return allExist;
1658}
1659
1660QImage QFontEngineMulti::alphaMapForGlyph(glyph_t)
1661{
1662 Q_ASSERT(false);
1663 return QImage();
1664}
1665
1666
1667QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.