/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfontengine_coretext_p.h" #include #include #include #if !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) QT_BEGIN_NAMESPACE static float SYNTHETIC_ITALIC_SKEW = tanf(14 * acosf(0) / 90); static void loadAdvancesForGlyphs(CTFontRef ctfont, QVarLengthArray &cgGlyphs, QGlyphLayout *glyphs, int len, QTextEngine::ShaperFlags flags, const QFontDef &fontDef) { Q_UNUSED(flags); QVarLengthArray advances(len); CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, cgGlyphs.data(), advances.data(), len); for (int i = 0; i < len; ++i) { if (glyphs->glyphs[i] & 0xff000000) continue; glyphs->advances_x[i] = QFixed::fromReal(advances[i].width); glyphs->advances_y[i] = QFixed::fromReal(advances[i].height); } if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) { for (int i = 0; i < len; ++i) { glyphs->advances_x[i] = glyphs->advances_x[i].round(); glyphs->advances_y[i] = glyphs->advances_y[i].round(); } } } extern int qt_antialiasing_threshold, qt_enable_font_smoothing; CGAffineTransform qt_transform_from_fontdef(const QFontDef &fontDef) { CGAffineTransform transform = CGAffineTransformIdentity; if (fontDef.stretch != 100) transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1); return transform; } QCoreTextFontEngine::QCoreTextFontEngine(CTFontRef font, const QFontDef &def) { fontDef = def; transform = qt_transform_from_fontdef(fontDef); ctfont = font; CFRetain(ctfont); cgFont = CTFontCopyGraphicsFont(font, NULL); init(); } QCoreTextFontEngine::QCoreTextFontEngine(CGFontRef font, const QFontDef &def) { fontDef = def; transform = qt_transform_from_fontdef(fontDef); cgFont = font; // Keep reference count balanced CFRetain(cgFont); ctfont = CTFontCreateWithGraphicsFont(font, fontDef.pixelSize, &transform, NULL); init(); } QCoreTextFontEngine::~QCoreTextFontEngine() { CFRelease(cgFont); CFRelease(ctfont); } static QFont::Weight weightFromInteger(int weight) { if (weight < 400) return QFont::Light; else if (weight < 600) return QFont::Normal; else if (weight < 700) return QFont::DemiBold; else if (weight < 800) return QFont::Bold; else return QFont::Black; } int getTraitValue(CFDictionaryRef allTraits, CFStringRef trait) { if (CFDictionaryContainsKey(allTraits, trait)) { CFNumberRef traitNum = (CFNumberRef) CFDictionaryGetValue(allTraits, trait); float v = 0; CFNumberGetValue(traitNum, kCFNumberFloatType, &v); // the value we get from CFNumberRef is from -1.0 to 1.0 int value = v * 500 + 500; return value; } return 0; } void QCoreTextFontEngine::init() { Q_ASSERT(ctfont != NULL); Q_ASSERT(cgFont != NULL); glyphFormat = qt_enable_font_smoothing ? QFontEngineGlyphCache::Raster_RGBMask : QFontEngineGlyphCache::Raster_A8; QCFString family = CTFontCopyFamilyName(ctfont); fontDef.family = family; QCFString styleName = (CFStringRef) CTFontCopyAttribute(ctfont, kCTFontStyleNameAttribute); fontDef.styleName = styleName; synthesisFlags = 0; CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(ctfont); if (traits & kCTFontItalicTrait) fontDef.style = QFont::StyleItalic; CFDictionaryRef allTraits = CTFontCopyTraits(ctfont); fontDef.weight = weightFromInteger(getTraitValue(allTraits, kCTFontWeightTrait)); int slant = getTraitValue(allTraits, kCTFontSlantTrait); if (slant > 500 && !(traits & kCTFontItalicTrait)) fontDef.style = QFont::StyleOblique; CFRelease(allTraits); if (fontDef.weight >= QFont::Bold && !(traits & kCTFontBoldTrait)) synthesisFlags |= SynthesizedBold; // XXX: we probably don't need to synthesis italic for oblique font if (fontDef.style != QFont::StyleNormal && !(traits & kCTFontItalicTrait)) synthesisFlags |= SynthesizedItalic; avgCharWidth = 0; QByteArray os2Table = getSfntTable(MAKE_TAG('O', 'S', '/', '2')); unsigned emSize = CTFontGetUnitsPerEm(ctfont); if (os2Table.size() >= 10) { fsType = qFromBigEndian(reinterpret_cast(os2Table.constData() + 8)); // qAbs is a workaround for weird fonts like Lucida Grande qint16 width = qAbs(qFromBigEndian(reinterpret_cast(os2Table.constData() + 2))); avgCharWidth = QFixed::fromReal(width * fontDef.pixelSize / emSize); } else avgCharWidth = QFontEngine::averageCharWidth(); } bool QCoreTextFontEngine::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const { *nglyphs = len; QCFType cfstring; QVarLengthArray cgGlyphs(len); CTFontGetGlyphsForCharacters(ctfont, (const UniChar*)str, cgGlyphs.data(), len); for (int i = 0; i < len; ++i) if (cgGlyphs[i]) glyphs->glyphs[i] = cgGlyphs[i]; if (flags & QTextEngine::GlyphIndicesOnly) return true; loadAdvancesForGlyphs(ctfont, cgGlyphs, glyphs, len, flags, fontDef); return true; } glyph_metrics_t QCoreTextFontEngine::boundingBox(const QGlyphLayout &glyphs) { QFixed w; bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics; for (int i = 0; i < glyphs.numGlyphs; ++i) { w += round ? glyphs.effectiveAdvance(i).round() : glyphs.effectiveAdvance(i); } return glyph_metrics_t(0, -(ascent()), w - lastRightBearing(glyphs, round), ascent()+descent(), w, 0); } glyph_metrics_t QCoreTextFontEngine::boundingBox(glyph_t glyph) { glyph_metrics_t ret; CGGlyph g = glyph; CGRect rect = CTFontGetBoundingRectsForGlyphs(ctfont, kCTFontHorizontalOrientation, &g, 0, 1); if (synthesisFlags & QFontEngine::SynthesizedItalic) { rect.size.width += rect.size.height * SYNTHETIC_ITALIC_SKEW; } ret.width = QFixed::fromReal(rect.size.width); ret.height = QFixed::fromReal(rect.size.height); ret.x = QFixed::fromReal(rect.origin.x); ret.y = -QFixed::fromReal(rect.origin.y) - ret.height; CGSize advances[1]; CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, &g, advances, 1); ret.xoff = QFixed::fromReal(advances[0].width); ret.yoff = QFixed::fromReal(advances[0].height); if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) { ret.xoff = ret.xoff.round(); ret.yoff = ret.yoff.round(); } return ret; } QFixed QCoreTextFontEngine::ascent() const { return (fontDef.styleStrategy & QFont::ForceIntegerMetrics) ? QFixed::fromReal(CTFontGetAscent(ctfont)).round() : QFixed::fromReal(CTFontGetAscent(ctfont)); } QFixed QCoreTextFontEngine::descent() const { QFixed d = QFixed::fromReal(CTFontGetDescent(ctfont)); if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) d = d.round(); // subtract a pixel to even out the historical +1 in QFontMetrics::height(). // Fix in Qt 5. return d - 1; } QFixed QCoreTextFontEngine::leading() const { return (fontDef.styleStrategy & QFont::ForceIntegerMetrics) ? QFixed::fromReal(CTFontGetLeading(ctfont)).round() : QFixed::fromReal(CTFontGetLeading(ctfont)); } QFixed QCoreTextFontEngine::xHeight() const { return (fontDef.styleStrategy & QFont::ForceIntegerMetrics) ? QFixed::fromReal(CTFontGetXHeight(ctfont)).round() : QFixed::fromReal(CTFontGetXHeight(ctfont)); } QFixed QCoreTextFontEngine::averageCharWidth() const { return (fontDef.styleStrategy & QFont::ForceIntegerMetrics) ? avgCharWidth.round() : avgCharWidth; } qreal QCoreTextFontEngine::maxCharWidth() const { return 0; } qreal QCoreTextFontEngine::minLeftBearing() const { return 0; } qreal QCoreTextFontEngine::minRightBearing() const { return 0; } void QCoreTextFontEngine::draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight) { QVarLengthArray positions; QVarLengthArray glyphs; QTransform matrix; matrix.translate(x, y); getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions); if (glyphs.size() == 0) return; CGContextSetFontSize(ctx, fontDef.pixelSize); CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx); CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, -1, 0, -paintDeviceHeight); CGAffineTransformConcat(cgMatrix, oldTextMatrix); if (synthesisFlags & QFontEngine::SynthesizedItalic) cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0)); cgMatrix = CGAffineTransformConcat(cgMatrix, transform); CGContextSetTextMatrix(ctx, cgMatrix); CGContextSetTextDrawingMode(ctx, kCGTextFill); QVarLengthArray advances(glyphs.size()); QVarLengthArray cgGlyphs(glyphs.size()); for (int i = 0; i < glyphs.size() - 1; ++i) { advances[i].width = (positions[i + 1].x - positions[i].x).toReal(); advances[i].height = (positions[i + 1].y - positions[i].y).toReal(); cgGlyphs[i] = glyphs[i]; } advances[glyphs.size() - 1].width = 0; advances[glyphs.size() - 1].height = 0; cgGlyphs[glyphs.size() - 1] = glyphs[glyphs.size() - 1]; CGContextSetFont(ctx, cgFont); //NSLog(@"Font inDraw %@ ctfont %@", CGFontCopyFullName(cgFont), CTFontCopyFamilyName(ctfont)); CGContextSetTextPosition(ctx, positions[0].x.toReal(), positions[0].y.toReal()); CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size()); if (synthesisFlags & QFontEngine::SynthesizedBold) { CGContextSetTextPosition(ctx, positions[0].x.toReal() + 0.5 * lineThickness().toReal(), positions[0].y.toReal()); CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size()); } CGContextSetTextMatrix(ctx, oldTextMatrix); } struct ConvertPathInfo { ConvertPathInfo(QPainterPath *newPath, const QPointF &newPos) : path(newPath), pos(newPos) {} QPainterPath *path; QPointF pos; }; static void convertCGPathToQPainterPath(void *info, const CGPathElement *element) { ConvertPathInfo *myInfo = static_cast(info); switch(element->type) { case kCGPathElementMoveToPoint: myInfo->path->moveTo(element->points[0].x + myInfo->pos.x(), element->points[0].y + myInfo->pos.y()); break; case kCGPathElementAddLineToPoint: myInfo->path->lineTo(element->points[0].x + myInfo->pos.x(), element->points[0].y + myInfo->pos.y()); break; case kCGPathElementAddQuadCurveToPoint: myInfo->path->quadTo(element->points[0].x + myInfo->pos.x(), element->points[0].y + myInfo->pos.y(), element->points[1].x + myInfo->pos.x(), element->points[1].y + myInfo->pos.y()); break; case kCGPathElementAddCurveToPoint: myInfo->path->cubicTo(element->points[0].x + myInfo->pos.x(), element->points[0].y + myInfo->pos.y(), element->points[1].x + myInfo->pos.x(), element->points[1].y + myInfo->pos.y(), element->points[2].x + myInfo->pos.x(), element->points[2].y + myInfo->pos.y()); break; case kCGPathElementCloseSubpath: myInfo->path->closeSubpath(); break; default: qDebug() << "Unhandled path transform type: " << element->type; } } void QCoreTextFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nGlyphs, QPainterPath *path, QTextItem::RenderFlags) { CGAffineTransform cgMatrix = CGAffineTransformIdentity; cgMatrix = CGAffineTransformScale(cgMatrix, 1, -1); if (synthesisFlags & QFontEngine::SynthesizedItalic) cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0)); for (int i = 0; i < nGlyphs; ++i) { QCFType cgpath = CTFontCreatePathForGlyph(ctfont, glyphs[i], &cgMatrix); ConvertPathInfo info(path, positions[i].toPointF()); CGPathApply(cgpath, &info, convertCGPathToQPainterPath); } } QImage QCoreTextFontEngine::imageForGlyph(glyph_t glyph, QFixed subPixelPosition, int /*margin*/, bool aa) { const glyph_metrics_t br = boundingBox(glyph); QImage im(qRound(br.width)+2, qRound(br.height)+2, QImage::Format_RGB32); im.fill(0); CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); uint cgflags = kCGImageAlphaNoneSkipFirst; #ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version cgflags |= kCGBitmapByteOrder32Host; #endif CGContextRef ctx = CGBitmapContextCreate(im.bits(), im.width(), im.height(), 8, im.bytesPerLine(), colorspace, cgflags); CGContextSetFontSize(ctx, fontDef.pixelSize); CGContextSetShouldAntialias(ctx, (aa || fontDef.pointSize > qt_antialiasing_threshold) && !(fontDef.styleStrategy & QFont::NoAntialias)); CGContextSetShouldSmoothFonts(ctx, aa); CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx); CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, 1, 0, 0); CGAffineTransformConcat(cgMatrix, oldTextMatrix); if (synthesisFlags & QFontEngine::SynthesizedItalic) cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, SYNTHETIC_ITALIC_SKEW, 1, 0, 0)); cgMatrix = CGAffineTransformConcat(cgMatrix, transform); CGContextSetTextMatrix(ctx, cgMatrix); CGContextSetRGBFillColor(ctx, 1, 1, 1, 1); CGContextSetTextDrawingMode(ctx, kCGTextFill); CGContextSetFont(ctx, cgFont); qreal pos_x = -br.x.truncate() + subPixelPosition.toReal(); qreal pos_y = im.height() + br.y.toReal(); CGContextSetTextPosition(ctx, pos_x, pos_y); CGSize advance; advance.width = 0; advance.height = 0; CGGlyph cgGlyph = glyph; CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1); if (synthesisFlags & QFontEngine::SynthesizedBold) { CGContextSetTextPosition(ctx, pos_x + 0.5 * lineThickness().toReal(), pos_y); CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1); } CGContextRelease(ctx); return im; } QImage QCoreTextFontEngine::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition) { QImage im = imageForGlyph(glyph, subPixelPosition, 0, false); QImage indexed(im.width(), im.height(), QImage::Format_Indexed8); QVector colors(256); for (int i=0; i<256; ++i) colors[i] = qRgba(0, 0, 0, i); indexed.setColorTable(colors); for (int y=0; y= QTransform::TxScale) return QFontEngine::alphaRGBMapForGlyph(glyph, subPixelPosition, margin, x); QImage im = imageForGlyph(glyph, subPixelPosition, margin, true); qGamma_correct_back_to_linear_cs(&im); return im; } void QCoreTextFontEngine::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const { int i, numGlyphs = glyphs->numGlyphs; QVarLengthArray cgGlyphs(numGlyphs); for (i = 0; i < numGlyphs; ++i) { if (glyphs->glyphs[i] & 0xff000000) cgGlyphs[i] = 0; else cgGlyphs[i] = glyphs->glyphs[i]; } loadAdvancesForGlyphs(ctfont, cgGlyphs, glyphs, numGlyphs, flags, fontDef); } QFontEngine::FaceId QCoreTextFontEngine::faceId() const { return QFontEngine::FaceId(); } bool QCoreTextFontEngine::canRender(const QChar *string, int len) { QVarLengthArray cgGlyphs(len); return CTFontGetGlyphsForCharacters(ctfont, (const UniChar *) string, cgGlyphs.data(), len); } bool QCoreTextFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const { QCFType table = CTFontCopyTable(ctfont, tag, 0); if (!table || !length) return false; CFIndex tableLength = CFDataGetLength(table); int availableLength = *length; *length = tableLength; if (buffer) { if (tableLength > availableLength) return false; CFDataGetBytes(table, CFRangeMake(0, tableLength), buffer); } return true; } void QCoreTextFontEngine::getUnscaledGlyph(glyph_t, QPainterPath *, glyph_metrics_t *) { // ### } QFixed QCoreTextFontEngine::emSquareSize() const { return QFixed::QFixed(int(CTFontGetUnitsPerEm(ctfont))); } QFontEngine *QCoreTextFontEngine::cloneWithSize(qreal pixelSize) const { QFontDef newFontDef = fontDef; newFontDef.pixelSize = pixelSize; newFontDef.pointSize = pixelSize * 72.0 / qt_defaultDpi(); return new QCoreTextFontEngine(cgFont, newFontDef); } QT_END_NAMESPACE #endif// !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)