1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qfontengine_qpf_p.h"
44 #include "private/qpaintengine_raster_p.h"
45 #include <QtCore/qlibraryinfo.h>
46 #include <QtCore/qfileinfo.h>
48 #include <QtCore/qfile.h>
49 #include <QtCore/qdir.h>
50 #include <QtCore/qbuffer.h>
51 #if !defined(QT_NO_FREETYPE)
52 #include "private/qfontengine_ft_p.h"
54 #include "private/qcore_unix_p.h" // overrides QT_OPEN
59 #include <sys/types.h>
67 #ifndef QT_NO_QWS_QPF2
69 #include "qpfutil.cpp"
71 QT_BEGIN_INCLUDE_NAMESPACE
74 # include "private/qwscommand_qws_p.h"
75 # include "qwsdisplay_qws.h"
76 # include "qabstractfontengine_p.h"
78 #include "qplatformdefs.h"
79 QT_END_INCLUDE_NAMESPACE
81 //#define DEBUG_HEADER
82 //#define DEBUG_FONTENGINE
84 #if defined(DEBUG_HEADER)
85 # define DEBUG_VERIFY qDebug
87 # define DEBUG_VERIFY if (0) qDebug
90 #define READ_VERIFY(type, variable) \
91 if (tagPtr + sizeof(type) > endPtr) { \
92 DEBUG_VERIFY() << "read verify failed in line" << __LINE__; \
95 variable = qFromBigEndian<type>(tagPtr); \
96 DEBUG_VERIFY() << "read value" << variable << "of type " #type; \
97 tagPtr += sizeof(type)
100 T readValue(const uchar *&data)
102 T value = qFromBigEndian<T>(data);
107 #define VERIFY(condition) \
108 if (!(condition)) { \
109 DEBUG_VERIFY() << "condition " #condition " failed in line" << __LINE__; \
113 #define VERIFY_TAG(condition) \
114 if (!(condition)) { \
115 DEBUG_VERIFY() << "verifying tag condition " #condition " failed in line" << __LINE__ << "with tag" << tag; \
119 static inline const uchar *verifyTag(const uchar *tagPtr, const uchar *endPtr)
122 READ_VERIFY(quint16, tag);
123 READ_VERIFY(quint16, length);
124 if (tag == QFontEngineQPF::Tag_EndOfHeader)
126 if (tag < QFontEngineQPF::NumTags) {
127 switch (tagTypes[tag]) {
128 case QFontEngineQPF::BitFieldType:
129 case QFontEngineQPF::StringType:
130 // can't do anything...
132 case QFontEngineQPF::UInt32Type:
133 VERIFY_TAG(length == sizeof(quint32));
135 case QFontEngineQPF::FixedType:
136 VERIFY_TAG(length == sizeof(quint32));
138 case QFontEngineQPF::UInt8Type:
139 VERIFY_TAG(length == sizeof(quint8));
142 #if defined(DEBUG_HEADER)
144 qDebug() << "tag data" << hex << *tagPtr;
145 else if (length == 4)
146 qDebug() << "tag data" << hex << tagPtr[0] << tagPtr[1] << tagPtr[2] << tagPtr[3];
149 return tagPtr + length;
152 const QFontEngineQPF::Glyph *QFontEngineQPF::findGlyph(glyph_t g) const
154 if (!g || g >= glyphMapEntries)
156 const quint32 *gmapPtr = reinterpret_cast<const quint32 *>(fontData + glyphMapOffset);
157 quint32 glyphPos = qFromBigEndian<quint32>(gmapPtr[g]);
158 if (glyphPos > glyphDataSize) {
159 if (glyphPos == 0xffffffff)
161 #if defined(DEBUG_FONTENGINE)
162 qDebug() << "glyph" << g << "outside of glyphData, remapping font file";
164 #if !defined(QT_NO_FREETYPE) && !defined(QT_FONTS_ARE_RESOURCES)
165 const_cast<QFontEngineQPF *>(this)->remapFontData();
167 if (glyphPos > glyphDataSize)
170 return reinterpret_cast<const Glyph *>(fontData + glyphDataOffset + glyphPos);
173 bool QFontEngineQPF::verifyHeader(const uchar *data, int size)
175 VERIFY(size >= int(sizeof(Header)));
176 const Header *header = reinterpret_cast<const Header *>(data);
177 if (header->magic[0] != 'Q'
178 || header->magic[1] != 'P'
179 || header->magic[2] != 'F'
180 || header->magic[3] != '2')
183 VERIFY(header->majorVersion <= CurrentMajorVersion);
184 const quint16 dataSize = qFromBigEndian<quint16>(header->dataSize);
185 VERIFY(size >= int(sizeof(Header)) + dataSize);
187 const uchar *tagPtr = data + sizeof(Header);
188 const uchar *tagEndPtr = tagPtr + dataSize;
189 while (tagPtr < tagEndPtr - 3) {
190 tagPtr = verifyTag(tagPtr, tagEndPtr);
194 VERIFY(tagPtr <= tagEndPtr);
198 QVariant QFontEngineQPF::extractHeaderField(const uchar *data, HeaderTag requestedTag)
200 const Header *header = reinterpret_cast<const Header *>(data);
201 const uchar *tagPtr = data + sizeof(Header);
202 const uchar *endPtr = tagPtr + qFromBigEndian<quint16>(header->dataSize);
203 while (tagPtr < endPtr - 3) {
204 quint16 tag = readValue<quint16>(tagPtr);
205 quint16 length = readValue<quint16>(tagPtr);
206 if (tag == requestedTag) {
207 switch (tagTypes[requestedTag]) {
209 return QVariant(QString::fromUtf8(reinterpret_cast<const char *>(tagPtr), length));
211 return QVariant(readValue<quint32>(tagPtr));
213 return QVariant(uint(*tagPtr));
215 return QVariant(QFixed::fromFixed(readValue<quint32>(tagPtr)).toReal());
217 return QVariant(QByteArray(reinterpret_cast<const char *>(tagPtr), length));
220 } else if (tag == Tag_EndOfHeader) {
229 #endif // QT_NO_QWS_QPF2
231 QString qws_fontCacheDir()
234 #if defined(Q_WS_QWS)
235 extern QString qws_dataDir();
238 dir = QDir::tempPath();
240 dir.append(QLatin1String("/fonts/"));
242 if (!qd.exists() && !qd.mkpath(dir))
243 dir = QDir::tempPath();
247 #ifndef QT_NO_QWS_QPF2
249 #ifndef QT_FONTS_ARE_RESOURCES
250 QList<QByteArray> QFontEngineQPF::cleanUpAfterClientCrash(const QList<int> &crashedClientIds)
252 QList<QByteArray> removedFonts;
253 QDir dir(qws_fontCacheDir(), QLatin1String("*.qsf"));
254 for (int i = 0; i < int(dir.count()); ++i) {
255 const QByteArray fileName = QFile::encodeName(dir.absoluteFilePath(dir[i]));
257 int fd = QT_OPEN(fileName.constData(), O_RDONLY, 0);
259 void *header = ::mmap(0, sizeof(QFontEngineQPF::Header), PROT_READ, MAP_SHARED, fd, 0);
260 if (header && header != MAP_FAILED) {
261 quint32 lockValue = reinterpret_cast<QFontEngineQPF::Header *>(header)->lock;
263 if (lockValue && crashedClientIds.contains(lockValue)) {
264 removedFonts.append(fileName);
265 QFile::remove(QFile::decodeName(fileName));
268 ::munmap(header, sizeof(QFontEngineQPF::Header));
273 if (!removedFonts.isEmpty())
274 qDebug() << "list of corrupted and removed fonts:" << removedFonts;
279 static inline unsigned int getChar(const QChar *str, int &i, const int len)
281 uint ucs4 = str[i].unicode();
282 if (str[i].isHighSurrogate() && i < len-1 && str[i+1].isLowSurrogate()) {
284 ucs4 = QChar::surrogateToUcs4(ucs4, str[i].unicode());
288 #ifdef QT_FONTS_ARE_RESOURCES
289 QFontEngineQPF::QFontEngineQPF(const QFontDef &def, const uchar *bytes, int size)
290 : fd(-1), fontData(bytes), dataSize(size), renderingFontEngine(0)
292 QFontEngineQPF::QFontEngineQPF(const QFontDef &def, int fileDescriptor, QFontEngine *fontEngine)
293 : fd(fileDescriptor), fontData(0), dataSize(0), renderingFontEngine(fontEngine)
306 if (renderingFontEngine)
307 glyphFormat = renderingFontEngine->glyphFormat;
308 kerning_pairs_loaded = false;
311 #if defined(DEBUG_FONTENGINE)
312 qDebug() << "QFontEngineQPF::QFontEngineQPF( fd =" << fd << ", renderingFontEngine =" << renderingFontEngine << ')';
315 #ifndef QT_FONTS_ARE_RESOURCES
317 if (!renderingFontEngine)
320 fileName = fontDef.family.toLower() + QLatin1Char('_')
321 + QString::number(fontDef.pixelSize)
322 + QLatin1Char('_') + QString::number(fontDef.weight)
323 + (fontDef.style != QFont::StyleNormal ?
324 QLatin1String("_italic") : QLatin1String(""))
325 + QLatin1String(".qsf");
326 fileName.replace(QLatin1Char(' '), QLatin1Char('_'));
327 fileName.prepend(qws_fontCacheDir());
329 encodedFileName = QFile::encodeName(fileName);
330 if (::access(encodedFileName, F_OK) == 0) {
331 #if defined(DEBUG_FONTENGINE)
332 qDebug() << "found existing qpf:" << fileName;
334 if (::access(encodedFileName, W_OK | R_OK) == 0) {
335 fd = QT_OPEN(encodedFileName, O_RDWR);
337 // read-write access failed - try read-only access
338 if (fd == -1 && ::access(encodedFileName, R_OK) == 0) {
339 fd = QT_OPEN(encodedFileName, O_RDONLY);
341 #if defined(DEBUG_FONTENGINE)
342 qErrnoWarning("QFontEngineQPF: unable to open %s", encodedName.constData());
348 #if defined(DEBUG_FONTENGINE)
349 qWarning("QFontEngineQPF: insufficient access rights to %s", encodedName.constData());
354 #if defined(DEBUG_FONTENGINE)
355 qDebug() << "creating qpf on the fly:" << fileName;
357 if (::access(QFile::encodeName(qws_fontCacheDir()), W_OK) == 0) {
358 fd = QT_OPEN(encodedFileName, O_RDWR | O_EXCL | O_CREAT, 0644);
360 #if defined(DEBUG_FONTENGINE)
361 qErrnoWarning(errno, "QFontEngineQPF: open() failed for %s", encodedName.constData());
367 buffer.open(QIODevice::ReadWrite);
368 QPFGenerator generator(&buffer, renderingFontEngine);
369 generator.generate();
371 const QByteArray &data = buffer.data();
372 if (QT_WRITE(fd, data.constData(), data.size()) == -1) {
373 #if defined(DEBUG_FONTENGINE)
374 qErrnoWarning(errno, "QFontEngineQPF: write() failed for %s", encodedName.constData());
379 #if defined(DEBUG_FONTENGINE)
380 qErrnoWarning(errno, "QFontEngineQPF: access() failed for %s", qPrintable(qws_fontCacheDir()));
388 if (QT_FSTAT(fd, &st)) {
389 #if defined(DEBUG_FONTENGINE)
390 qErrnoWarning(errno, "QFontEngineQPF: fstat failed!");
394 dataSize = st.st_size;
397 fontData = (const uchar *)::mmap(0, st.st_size, PROT_READ | (renderingFontEngine ? PROT_WRITE : 0), MAP_SHARED, fd, 0);
398 if (!fontData || fontData == (const uchar *)MAP_FAILED) {
399 #if defined(DEBUG_FONTENGINE)
400 perror("mmap failed");
405 #endif //QT_FONTS_ARE_RESOURCES
407 if (!verifyHeader(fontData, dataSize)) {
408 #if defined(DEBUG_FONTENGINE)
409 qDebug() << "verifyHeader failed!";
414 const Header *header = reinterpret_cast<const Header *>(fontData);
416 readOnly = (header->lock == 0xffffffff);
418 const uchar *data = fontData + sizeof(Header) + qFromBigEndian<quint16>(header->dataSize);
419 const uchar *endPtr = fontData + dataSize;
420 while (data <= endPtr - 8) {
421 quint16 blockTag = readValue<quint16>(data);
422 data += 2; // skip padding
423 quint32 blockSize = readValue<quint32>(data);
425 if (blockTag == CMapBlock) {
426 cmapOffset = data - fontData;
427 cmapSize = blockSize;
428 } else if (blockTag == GMapBlock) {
429 glyphMapOffset = data - fontData;
430 glyphMapEntries = blockSize / 4;
431 } else if (blockTag == GlyphBlock) {
432 glyphDataOffset = data - fontData;
433 glyphDataSize = blockSize;
439 face_id.filename = QFile::encodeName(extractHeaderField(fontData, Tag_FileName).toString());
440 face_id.index = extractHeaderField(fontData, Tag_FileIndex).toInt();
441 #if !defined(QT_NO_FREETYPE) && !defined(QT_FONTS_ARE_RESOURCES)
442 freetype = QFreetypeFace::getFace(face_id);
445 #ifndef QT_NO_SETTINGS
446 QLibraryInfo::location(QLibraryInfo::LibrariesPath) +
448 QLatin1String("/fonts/") +
449 QFileInfo(QFile::decodeName(face_id.filename)).fileName();
450 face_id.filename = QFile::encodeName(newPath);
451 freetype = QFreetypeFace::getFace(face_id);
454 const quint32 qpfTtfRevision = extractHeaderField(fontData, Tag_FontRevision).toUInt();
457 bool ok = freetype->getSfntTable(MAKE_TAG('h', 'e', 'a', 'd'), data, &length);
458 if (!ok || length != 4
459 || qFromBigEndian<quint32>(data) != qpfTtfRevision) {
460 freetype->release(face_id);
464 if (!cmapOffset && freetype) {
465 freetypeCMapTable = getSfntTable(MAKE_TAG('c', 'm', 'a', 'p'));
466 externalCMap = reinterpret_cast<const uchar *>(freetypeCMapTable.constData());
467 cmapSize = freetypeCMapTable.size();
473 int tableSize = cmapSize;
474 const uchar *cmapPtr = getCMap(fontData + cmapOffset, tableSize, &symbol, &cmapSize);
476 cmapOffset = cmapPtr - fontData;
479 } else if (externalCMap) {
480 int tableSize = cmapSize;
481 externalCMap = getCMap(externalCMap, tableSize, &symbol, &cmapSize);
484 // verify all the positions in the glyphMap
485 if (glyphMapOffset) {
486 const quint32 *gmapPtr = reinterpret_cast<const quint32 *>(fontData + glyphMapOffset);
487 for (uint i = 0; i < glyphMapEntries; ++i) {
488 quint32 glyphDataPos = qFromBigEndian<quint32>(gmapPtr[i]);
489 if (glyphDataPos == 0xffffffff)
491 if (glyphDataPos >= glyphDataSize) {
500 #if defined(DEBUG_FONTENGINE)
502 qDebug() << "fontData" << fontData << "dataSize" << dataSize
503 << "externalCMap" << externalCMap << "cmapOffset" << cmapOffset
504 << "glyphMapOffset" << glyphMapOffset << "glyphDataOffset" << glyphDataOffset
505 << "fd" << fd << "glyphDataSize" << glyphDataSize;
507 #if defined(Q_WS_QWS)
508 if (isValid() && renderingFontEngine)
509 qt_fbdpy->sendFontCommand(QWSFontCommand::StartedUsingFont, encodedFileName);
513 QFontEngineQPF::~QFontEngineQPF()
515 #if defined(Q_WS_QWS)
516 if (isValid() && renderingFontEngine) {
518 qt_fbdpy->sendFontCommand(QWSFontCommand::StoppedUsingFont, encodedFileName);
520 qDebug("QFontEngineQPF::~QFontEngineQPF: Out of memory");
525 delete renderingFontEngine;
527 if (munmap((void *)fontData, dataSize) == -1) {
528 #if defined(DEBUG_FONTENGINE)
529 qErrnoWarning(errno, "~QFontEngineQPF: Unable to munmap");
535 #if !defined(QT_NO_FREETYPE)
537 freetype->release(face_id);
541 bool QFontEngineQPF::getSfntTableData(uint tag, uchar *buffer, uint *length) const
543 #if !defined(QT_NO_FREETYPE)
545 return freetype->getSfntTable(tag, buffer, length);
553 bool QFontEngineQPF::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
555 if (!externalCMap && !cmapOffset && renderingFontEngine) {
556 if (!renderingFontEngine->stringToCMap(str, len, glyphs, nglyphs, flags))
558 #ifndef QT_NO_FREETYPE
559 const_cast<QFontEngineQPF *>(this)->ensureGlyphsLoaded(*glyphs);
564 if (*nglyphs < len) {
569 #if defined(DEBUG_FONTENGINE)
570 QSet<QChar> seenGlyphs;
573 const uchar *cmap = externalCMap ? externalCMap : (fontData + cmapOffset);
575 bool mirrored = flags & QTextEngine::RightToLeft;
578 for (int i = 0; i < len; ++i) {
579 unsigned int uc = getChar(str, i, len);
580 glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
581 if(!glyphs->glyphs[glyph_pos] && uc < 0x100)
582 glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
586 for (int i = 0; i < len; ++i) {
587 unsigned int uc = getChar(str, i, len);
589 uc = QChar::mirroredChar(uc);
590 glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
591 #if 0 && defined(DEBUG_FONTENGINE)
593 if (!findGlyph(glyphs[glyph_pos].glyph) && !seenGlyphs.contains(c))
594 qDebug() << "glyph for character" << c << '/' << hex << uc << "is" << dec << glyphs[glyph_pos].glyph;
596 seenGlyphs.insert(c);
602 *nglyphs = glyph_pos;
603 glyphs->numGlyphs = glyph_pos;
604 recalcAdvances(glyphs, flags);
608 void QFontEngineQPF::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags) const
610 #ifndef QT_NO_FREETYPE
611 const_cast<QFontEngineQPF *>(this)->ensureGlyphsLoaded(*glyphs);
613 for (int i = 0; i < glyphs->numGlyphs; ++i) {
614 const Glyph *g = findGlyph(glyphs->glyphs[i]);
616 glyphs->glyphs[i] = 0;
619 glyphs->advances_x[i] = g->advance;
620 glyphs->advances_y[i] = 0;
624 QImage QFontEngineQPF::alphaMapForGlyph(glyph_t g)
626 const Glyph *glyph = findGlyph(g);
630 const uchar *bits = ((const uchar *) glyph) + sizeof(Glyph);
632 QImage image(glyph->width, glyph->height, QImage::Format_Indexed8);
633 for (int j=0; j<256; ++j)
634 image.setColor(j, qRgba(0, 0, 0, j));
636 for (int i=0; i<glyph->height; ++i) {
637 memcpy(image.scanLine(i), bits, glyph->bytesPerLine);
638 bits += glyph->bytesPerLine;
643 void QFontEngineQPF::draw(QPaintEngine *p, qreal _x, qreal _y, const QTextItemInt &si)
645 QPaintEngineState *pState = p->state;
646 QRasterPaintEngine *paintEngine = static_cast<QRasterPaintEngine*>(p);
648 QTransform matrix = pState->transform();
649 matrix.translate(_x, _y);
650 QFixed x = QFixed::fromReal(matrix.dx());
651 QFixed y = QFixed::fromReal(matrix.dy());
653 QVarLengthArray<QFixedPoint> positions;
654 QVarLengthArray<glyph_t> glyphs;
655 getGlyphPositions(si.glyphs, matrix, si.flags, glyphs, positions);
656 if (glyphs.size() == 0)
659 for(int i = 0; i < glyphs.size(); i++) {
660 const Glyph *glyph = findGlyph(glyphs[i]);
664 const int depth = 8; //###
666 paintEngine->alphaPenBlt(reinterpret_cast<const uchar *>(glyph) + sizeof(Glyph), glyph->bytesPerLine, depth,
667 qRound(positions[i].x) + glyph->x,
668 qRound(positions[i].y) + glyph->y,
669 glyph->width, glyph->height);
673 void QFontEngineQPF::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags)
675 if (renderingFontEngine &&
676 (renderingFontEngine->type() != QFontEngine::Proxy
677 || static_cast<QProxyFontEngine *>(renderingFontEngine)->capabilities() & QAbstractFontEngine::CanOutlineGlyphs)) {
678 renderingFontEngine->addOutlineToPath(x, y, glyphs, path, flags);
681 addBitmapFontToPath(x, y, glyphs, path, flags);
684 glyph_metrics_t QFontEngineQPF::boundingBox(const QGlyphLayout &glyphs)
686 #ifndef QT_NO_FREETYPE
687 const_cast<QFontEngineQPF *>(this)->ensureGlyphsLoaded(glyphs);
690 glyph_metrics_t overall;
691 // initialize with line height, we get the same behaviour on all platforms
692 overall.y = -ascent();
693 overall.height = ascent() + descent() + 1;
697 for (int i = 0; i < glyphs.numGlyphs; i++) {
698 const Glyph *g = findGlyph(glyphs.glyphs[i]);
702 QFixed x = overall.xoff + glyphs.offsets[i].x + g->x;
703 QFixed y = overall.yoff + glyphs.offsets[i].y + g->y;
704 overall.x = qMin(overall.x, x);
705 overall.y = qMin(overall.y, y);
706 xmax = qMax(xmax, x + g->width);
707 ymax = qMax(ymax, y + g->height);
708 overall.xoff += g->advance;
710 overall.height = qMax(overall.height, ymax - overall.y);
711 overall.width = xmax - overall.x;
716 glyph_metrics_t QFontEngineQPF::boundingBox(glyph_t glyph)
718 #ifndef QT_NO_FREETYPE
720 QGlyphLayoutArray<1> tmp;
721 tmp.glyphs[0] = glyph;
722 const_cast<QFontEngineQPF *>(this)->ensureGlyphsLoaded(tmp);
725 glyph_metrics_t overall;
726 const Glyph *g = findGlyph(glyph);
731 overall.width = g->width;
732 overall.height = g->height;
733 overall.xoff = g->advance;
737 QFixed QFontEngineQPF::ascent() const
739 return QFixed::fromReal(extractHeaderField(fontData, Tag_Ascent).value<qreal>());
742 QFixed QFontEngineQPF::descent() const
744 return QFixed::fromReal(extractHeaderField(fontData, Tag_Descent).value<qreal>());
747 QFixed QFontEngineQPF::leading() const
749 return QFixed::fromReal(extractHeaderField(fontData, Tag_Leading).value<qreal>());
752 qreal QFontEngineQPF::maxCharWidth() const
754 return extractHeaderField(fontData, Tag_MaxCharWidth).value<qreal>();
757 qreal QFontEngineQPF::minLeftBearing() const
759 return extractHeaderField(fontData, Tag_MinLeftBearing).value<qreal>();
762 qreal QFontEngineQPF::minRightBearing() const
764 return extractHeaderField(fontData, Tag_MinRightBearing).value<qreal>();
767 QFixed QFontEngineQPF::underlinePosition() const
769 return QFixed::fromReal(extractHeaderField(fontData, Tag_UnderlinePosition).value<qreal>());
772 QFixed QFontEngineQPF::lineThickness() const
774 return QFixed::fromReal(extractHeaderField(fontData, Tag_LineThickness).value<qreal>());
777 QFontEngine::Type QFontEngineQPF::type() const
779 return QFontEngine::QPF2;
782 bool QFontEngineQPF::canRender(const QChar *string, int len)
784 const uchar *cmap = externalCMap ? externalCMap : (fontData + cmapOffset);
787 for (int i = 0; i < len; ++i) {
788 unsigned int uc = getChar(string, i, len);
789 glyph_t g = getTrueTypeGlyphIndex(cmap, uc);
791 g = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
796 for (int i = 0; i < len; ++i) {
797 unsigned int uc = getChar(string, i, len);
798 if (!getTrueTypeGlyphIndex(cmap, uc))
805 bool QFontEngineQPF::isValid() const
807 return fontData && dataSize && (cmapOffset || externalCMap || renderingFontEngine)
808 && glyphMapOffset && glyphDataOffset && (fd >= 0 || glyphDataSize > 0);
811 #if !defined(QT_NO_FREETYPE)
812 FT_Face QFontEngineQPF::lockFace() const
816 FT_Face face = freetype->face;
819 const int ysize = qRound(fontDef.pixelSize * qreal(64));
820 const int xsize = ysize;
822 if (freetype->xsize != xsize || freetype->ysize != ysize) {
823 FT_Set_Char_Size(face, xsize, ysize, 0, 0);
824 freetype->xsize = xsize;
825 freetype->ysize = ysize;
827 FT_Matrix identityMatrix;
828 identityMatrix.xx = 0x10000;
829 identityMatrix.yy = 0x10000;
830 identityMatrix.xy = 0;
831 identityMatrix.yx = 0;
832 if (freetype->matrix.xx != identityMatrix.xx ||
833 freetype->matrix.yy != identityMatrix.yy ||
834 freetype->matrix.xy != identityMatrix.xy ||
835 freetype->matrix.yx != identityMatrix.yx) {
836 freetype->matrix = identityMatrix;
837 FT_Set_Transform(face, &freetype->matrix, 0);
842 void QFontEngineQPF::unlockFace() const
847 void QFontEngineQPF::doKerning(QGlyphLayout *g, QTextEngine::ShaperFlags flags) const
849 if (!kerning_pairs_loaded) {
850 kerning_pairs_loaded = true;
853 if (freetype->face->size->metrics.x_ppem != 0) {
854 QFixed scalingFactor(freetype->face->units_per_EM/freetype->face->size->metrics.x_ppem);
856 const_cast<QFontEngineQPF *>(this)->loadKerningPairs(scalingFactor);
862 QFontEngine::doKerning(g, flags);
865 HB_Error QFontEngineQPF::getPointInOutline(HB_Glyph glyph, int flags, hb_uint32 point, HB_Fixed *xpos, HB_Fixed *ypos, hb_uint32 *nPoints)
868 return HB_Err_Not_Covered;
870 HB_Error result = freetype->getPointInOutline(glyph, flags, point, xpos, ypos, nPoints);
875 QFixed QFontEngineQPF::emSquareSize() const
878 return QFontEngine::emSquareSize();
879 if (FT_IS_SCALABLE(freetype->face))
880 return freetype->face->units_per_EM;
882 return freetype->face->size->metrics.y_ppem;
885 void QFontEngineQPF::ensureGlyphsLoaded(const QGlyphLayout &glyphs)
890 for (int i = 0; i < glyphs.numGlyphs; ++i) {
891 if (!glyphs.glyphs[i])
893 const Glyph *g = findGlyph(glyphs.glyphs[i]);
900 g = findGlyph(glyphs.glyphs[i]);
904 loadGlyph(glyphs.glyphs[i]);
908 #if defined(DEBUG_FONTENGINE)
909 qDebug() << "Finished rendering glyphs\n";
914 void QFontEngineQPF::loadGlyph(glyph_t glyph)
916 quint32 glyphPos = ~0;
918 if (!renderingFontEngine)
920 QImage img = renderingFontEngine->alphaMapForGlyph(glyph);
921 if (img.format() != QImage::Format_Indexed8) {
922 bool mono = img.depth() == 1;
923 img = img.convertToFormat(QImage::Format_Indexed8);
925 //### we know that 1 is opaque and 0 is transparent
926 uchar *byte = img.bits();
927 int count = img.byteCount();
932 glyph_metrics_t metrics = renderingFontEngine->boundingBox(glyph);
933 renderingFontEngine->removeGlyphFromCache(glyph);
935 off_t oldSize = ::lseek(fd, 0, SEEK_END);
936 if (oldSize == (off_t)-1)
940 g.width = img.width();
941 g.height = img.height();
942 g.bytesPerLine = img.bytesPerLine();
943 g.x = qRound(metrics.x);
944 g.y = qRound(metrics.y);
945 g.advance = qRound(metrics.xoff);
947 QT_WRITE(fd, &g, sizeof(g));
948 QT_WRITE(fd, img.bits(), img.byteCount());
950 glyphPos = oldSize - glyphDataOffset;
951 #if 0 && defined(DEBUG_FONTENGINE)
952 qDebug() << "glyphPos for new glyph" << glyph << "is" << glyphPos << "oldSize" << oldSize << "glyphDataOffset" << glyphDataOffset;
955 quint32 *gmap = (quint32 *)(fontData + glyphMapOffset);
956 gmap[glyph] = qToBigEndian(glyphPos);
958 glyphDataSize = glyphPos + sizeof(g) + img.byteCount();
959 quint32 *blockSizePtr = (quint32 *)(fontData + glyphDataOffset - 4);
960 *blockSizePtr = qToBigEndian(glyphDataSize);
963 bool QFontEngineQPF::lockFile()
965 // #### this does not handle the case when the process holding the
966 // lock hangs for some reason
968 lock.l_type = F_WRLCK;
969 lock.l_whence = SEEK_SET;
971 lock.l_len = 0; // lock the whole file
972 while (fcntl(fd, F_SETLKW, &lock) != 0) {
975 perror("locking qpf");
978 Header *header = (Header *)fontData;
980 lock.l_type = F_UNLCK;
981 if (fcntl(fd, F_SETLK, &lock) != 0)
982 perror("unlocking possibly corrupt qpf");
985 #if defined(Q_WS_QWS)
986 extern int qws_client_id;
987 // qws_client_id == 0 means we're the server. in this case we just
989 header->lock = qws_client_id ? qws_client_id : 1;
996 void QFontEngineQPF::unlockFile()
998 ((Header *)fontData)->lock = 0;
1001 lock.l_type = F_UNLCK;
1002 lock.l_whence = SEEK_SET;
1004 lock.l_len = 0; // lock the whole file
1005 if (fcntl(fd, F_SETLK, &lock) != 0) {
1006 perror("unlocking qpf");
1012 void QFontEngineQPF::remapFontData()
1014 off_t newFileSize = ::lseek(fd, 0, SEEK_END);
1015 if (newFileSize == (off_t)-1) {
1016 #ifdef DEBUG_FONTENGINE
1017 perror("QFontEngineQPF::remapFontData: lseek failed");
1023 #ifndef QT_NO_MREMAP
1024 fontData = static_cast<uchar *>(::mremap(const_cast<uchar *>(fontData), dataSize, newFileSize, MREMAP_MAYMOVE));
1025 if (!fontData || fontData == (const uchar *)MAP_FAILED) {
1026 # if defined(DEBUG_FONTENGINE)
1027 perror("QFontEngineQPF::remapFontData(): mremap failed");
1033 #endif // QT_NO_MREMAP
1035 int status = ::munmap((void *)fontData, dataSize);
1037 qErrnoWarning(status, "QFontEngineQPF::remapFomrData: munmap failed!");
1039 fontData = (const uchar *)::mmap(0, newFileSize, PROT_READ | (renderingFontEngine ? PROT_WRITE : 0),
1041 if (!fontData || fontData == (const uchar *)MAP_FAILED) {
1042 # if defined(DEBUG_FONTENGINE)
1043 perror("mmap failed");
1050 dataSize = newFileSize;
1051 glyphDataSize = newFileSize - glyphDataOffset;
1052 #if defined(DEBUG_FONTENGINE)
1053 qDebug() << "remapped the font file to" << newFileSize << "bytes";
1057 #endif // QT_NO_FREETYPE
1059 void QPFGenerator::generate()
1063 writeBlock(QFontEngineQPF::GlyphBlock, QByteArray());
1065 dev->seek(4); // position of header.lock
1069 void QPFGenerator::writeHeader()
1071 QFontEngineQPF::Header header;
1073 header.magic[0] = 'Q';
1074 header.magic[1] = 'P';
1075 header.magic[2] = 'F';
1076 header.magic[3] = '2';
1078 header.majorVersion = QFontEngineQPF::CurrentMajorVersion;
1079 header.minorVersion = QFontEngineQPF::CurrentMinorVersion;
1080 header.dataSize = 0;
1081 dev->write((const char *)&header, sizeof(header));
1083 writeTaggedString(QFontEngineQPF::Tag_FontName, fe->fontDef.family.toUtf8());
1085 QFontEngine::FaceId face = fe->faceId();
1086 writeTaggedString(QFontEngineQPF::Tag_FileName, face.filename);
1087 writeTaggedUInt32(QFontEngineQPF::Tag_FileIndex, face.index);
1092 bool ok = fe->getSfntTableData(MAKE_TAG('h', 'e', 'a', 'd'), data, &len);
1094 const quint32 revision = qFromBigEndian<quint32>(data);
1095 writeTaggedUInt32(QFontEngineQPF::Tag_FontRevision, revision);
1099 writeTaggedQFixed(QFontEngineQPF::Tag_Ascent, fe->ascent());
1100 writeTaggedQFixed(QFontEngineQPF::Tag_Descent, fe->descent());
1101 writeTaggedQFixed(QFontEngineQPF::Tag_Leading, fe->leading());
1102 writeTaggedQFixed(QFontEngineQPF::Tag_XHeight, fe->xHeight());
1103 writeTaggedQFixed(QFontEngineQPF::Tag_AverageCharWidth, fe->averageCharWidth());
1104 writeTaggedQFixed(QFontEngineQPF::Tag_MaxCharWidth, QFixed::fromReal(fe->maxCharWidth()));
1105 writeTaggedQFixed(QFontEngineQPF::Tag_LineThickness, fe->lineThickness());
1106 writeTaggedQFixed(QFontEngineQPF::Tag_MinLeftBearing, QFixed::fromReal(fe->minLeftBearing()));
1107 writeTaggedQFixed(QFontEngineQPF::Tag_MinRightBearing, QFixed::fromReal(fe->minRightBearing()));
1108 writeTaggedQFixed(QFontEngineQPF::Tag_UnderlinePosition, fe->underlinePosition());
1109 writeTaggedUInt8(QFontEngineQPF::Tag_PixelSize, fe->fontDef.pixelSize);
1110 writeTaggedUInt8(QFontEngineQPF::Tag_Weight, fe->fontDef.weight);
1111 writeTaggedUInt8(QFontEngineQPF::Tag_Style, fe->fontDef.style);
1113 writeTaggedUInt8(QFontEngineQPF::Tag_GlyphFormat, QFontEngineQPF::AlphamapGlyphs);
1115 writeTaggedString(QFontEngineQPF::Tag_EndOfHeader, QByteArray());
1118 const quint64 size = dev->pos();
1119 header.dataSize = qToBigEndian<quint16>(size - sizeof(header));
1121 dev->write((const char *)&header, sizeof(header));
1125 void QPFGenerator::writeGMap()
1127 const quint16 glyphCount = fe->glyphCount();
1129 writeUInt16(QFontEngineQPF::GMapBlock);
1130 writeUInt16(0); // padding
1131 writeUInt32(glyphCount * 4);
1133 QByteArray &buffer = dev->buffer();
1134 const int numBytes = glyphCount * sizeof(quint32);
1135 qint64 pos = buffer.size();
1136 buffer.resize(pos + numBytes);
1137 qMemSet(buffer.data() + pos, 0xff, numBytes);
1138 dev->seek(pos + numBytes);
1141 void QPFGenerator::writeBlock(QFontEngineQPF::BlockTag tag, const QByteArray &data)
1144 writeUInt16(0); // padding
1145 const int padSize = ((data.size() + 3) / 4) * 4 - data.size();
1146 writeUInt32(data.size() + padSize);
1148 for (int i = 0; i < padSize; ++i)
1152 void QPFGenerator::writeTaggedString(QFontEngineQPF::HeaderTag tag, const QByteArray &string)
1155 writeUInt16(string.length());
1159 void QPFGenerator::writeTaggedUInt32(QFontEngineQPF::HeaderTag tag, quint32 value)
1162 writeUInt16(sizeof(value));
1166 void QPFGenerator::writeTaggedUInt8(QFontEngineQPF::HeaderTag tag, quint8 value)
1169 writeUInt16(sizeof(value));
1173 void QPFGenerator::writeTaggedQFixed(QFontEngineQPF::HeaderTag tag, QFixed value)
1176 writeUInt16(sizeof(quint32));
1177 writeUInt32(value.value());
1180 #endif // QT_NO_QWS_QPF2
1183 Creates a new multi qws engine.
1185 This function takes ownership of the QFontEngine, increasing it's refcount.
1187 QFontEngineMultiQWS::QFontEngineMultiQWS(QFontEngine *fe, int _script, const QStringList &fallbacks)
1188 : QFontEngineMulti(fallbacks.size() + 1),
1189 fallbackFamilies(fallbacks), script(_script)
1193 fontDef = engines[0]->fontDef;
1196 void QFontEngineMultiQWS::loadEngine(int at)
1198 Q_ASSERT(at < engines.size());
1199 Q_ASSERT(engines.at(at) == 0);
1201 QFontDef request = fontDef;
1202 request.styleStrategy |= QFont::NoFontMerging;
1203 request.family = fallbackFamilies.at(at-1);
1204 engines[at] = QFontDatabase::findFont(script,
1207 Q_ASSERT(engines[at]);
1208 engines[at]->ref.ref();
1209 engines[at]->fontDef = request;
1212 void QFontEngineMultiQWS::draw(QPaintEngine */*p*/, qreal /*x*/, qreal /*y*/, const QTextItemInt &/*si*/)
1214 qFatal("QFontEngineMultiQWS::draw should never be called!");