1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #ifndef QT_NO_DIRECTWRITE
44 #include "qfontenginedirectwrite_p.h"
48 #include <private/qnativeimage_p.h>
54 // Convert from design units to logical pixels
55 #define DESIGN_TO_LOGICAL(DESIGN_UNIT_VALUE) \
56 QFixed::fromReal((qreal(DESIGN_UNIT_VALUE) / qreal(m_unitsPerEm)) * fontDef.pixelSize)
60 class GeometrySink: public IDWriteGeometrySink
63 GeometrySink(QPainterPath *path) : m_path(path), m_refCount(0)
65 Q_ASSERT(m_path != 0);
68 IFACEMETHOD_(void, AddBeziers)(const D2D1_BEZIER_SEGMENT *beziers, UINT bezierCount);
69 IFACEMETHOD_(void, AddLines)(const D2D1_POINT_2F *points, UINT pointCount);
70 IFACEMETHOD_(void, BeginFigure)(D2D1_POINT_2F startPoint, D2D1_FIGURE_BEGIN figureBegin);
72 IFACEMETHOD_(void, EndFigure)(D2D1_FIGURE_END figureEnd);
73 IFACEMETHOD_(void, SetFillMode)(D2D1_FILL_MODE fillMode);
74 IFACEMETHOD_(void, SetSegmentFlags)(D2D1_PATH_SEGMENT vertexFlags);
76 IFACEMETHOD_(unsigned long, AddRef)();
77 IFACEMETHOD_(unsigned long, Release)();
78 IFACEMETHOD(QueryInterface)(IID const &riid, void **ppvObject);
81 inline static QPointF fromD2D1_POINT_2F(const D2D1_POINT_2F &inp)
83 return QPointF(inp.x, inp.y);
86 unsigned long m_refCount;
91 void GeometrySink::AddBeziers(const D2D1_BEZIER_SEGMENT *beziers,
94 for (uint i=0; i<bezierCount; ++i) {
95 QPointF c1 = fromD2D1_POINT_2F(beziers[i].point1);
96 QPointF c2 = fromD2D1_POINT_2F(beziers[i].point2);
97 QPointF p2 = fromD2D1_POINT_2F(beziers[i].point3);
99 m_path->cubicTo(c1, c2, p2);
103 void GeometrySink::AddLines(const D2D1_POINT_2F *points, UINT pointsCount)
105 for (uint i=0; i<pointsCount; ++i)
106 m_path->lineTo(fromD2D1_POINT_2F(points[i]));
109 void GeometrySink::BeginFigure(D2D1_POINT_2F startPoint,
110 D2D1_FIGURE_BEGIN /*figureBegin*/)
112 m_startPoint = fromD2D1_POINT_2F(startPoint);
113 m_path->moveTo(m_startPoint);
116 IFACEMETHODIMP GeometrySink::Close()
121 void GeometrySink::EndFigure(D2D1_FIGURE_END figureEnd)
123 if (figureEnd == D2D1_FIGURE_END_CLOSED)
124 m_path->closeSubpath();
127 void GeometrySink::SetFillMode(D2D1_FILL_MODE fillMode)
129 m_path->setFillRule(fillMode == D2D1_FILL_MODE_ALTERNATE
134 void GeometrySink::SetSegmentFlags(D2D1_PATH_SEGMENT /*vertexFlags*/)
136 /* Not implemented */
139 IFACEMETHODIMP_(unsigned long) GeometrySink::AddRef()
141 return InterlockedIncrement(&m_refCount);
144 IFACEMETHODIMP_(unsigned long) GeometrySink::Release()
146 unsigned long newCount = InterlockedDecrement(&m_refCount);
156 IFACEMETHODIMP GeometrySink::QueryInterface(IID const &riid, void **ppvObject)
158 if (__uuidof(IDWriteGeometrySink) == riid) {
160 } else if (__uuidof(IUnknown) == riid) {
173 QFontEngineDirectWrite::QFontEngineDirectWrite(IDWriteFactory *directWriteFactory,
174 IDWriteFontFace *directWriteFontFace,
176 : m_directWriteFontFace(directWriteFontFace)
177 , m_directWriteFactory(directWriteFactory)
178 , m_directWriteBitmapRenderTarget(0)
179 , m_lineThickness(-1)
186 m_directWriteFactory->AddRef();
187 m_directWriteFontFace->AddRef();
189 fontDef.pixelSize = pixelSize;
193 QFontEngineDirectWrite::~QFontEngineDirectWrite()
195 m_directWriteFactory->Release();
196 m_directWriteFontFace->Release();
198 if (m_directWriteBitmapRenderTarget != 0)
199 m_directWriteBitmapRenderTarget->Release();
202 void QFontEngineDirectWrite::collectMetrics()
204 if (m_directWriteFontFace != 0) {
205 DWRITE_FONT_METRICS metrics;
207 m_directWriteFontFace->GetMetrics(&metrics);
208 m_unitsPerEm = metrics.designUnitsPerEm;
210 m_lineThickness = DESIGN_TO_LOGICAL(metrics.underlineThickness);
211 m_ascent = DESIGN_TO_LOGICAL(metrics.ascent);
212 m_descent = DESIGN_TO_LOGICAL(metrics.descent);
213 m_xHeight = DESIGN_TO_LOGICAL(metrics.xHeight);
214 m_lineGap = DESIGN_TO_LOGICAL(metrics.lineGap);
218 QFixed QFontEngineDirectWrite::lineThickness() const
220 if (m_lineThickness > 0)
221 return m_lineThickness;
223 return QFontEngine::lineThickness();
226 bool QFontEngineDirectWrite::getSfntTableData(uint tag, uchar *buffer, uint *length) const
230 if (m_directWriteFontFace) {
231 DWORD t = qbswap<quint32>(tag);
233 const void *tableData = 0;
234 void *tableContext = 0;
237 HRESULT hr = m_directWriteFontFace->TryGetFontTable(
238 t, &tableData, &tableSize, &tableContext, &exists
246 } else if (*length >= tableSize) {
247 memcpy(buffer, tableData, tableSize);
251 m_directWriteFontFace->ReleaseFontTable(tableContext);
253 qErrnoWarning("QFontEngineDirectWrite::getSfntTableData: TryGetFontTable failed");
260 QFixed QFontEngineDirectWrite::emSquareSize() const
262 if (m_unitsPerEm > 0)
265 return QFontEngine::emSquareSize();
268 inline unsigned int getChar(const QChar *str, int &i, const int len)
270 uint ucs4 = str[i].unicode();
271 if (str[i].isHighSurrogate() && i < len-1 && str[i+1].isLowSurrogate()) {
273 ucs4 = QChar::surrogateToUcs4( ucs4, str[i].unicode());
278 bool QFontEngineDirectWrite::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
279 int *nglyphs, QTextEngine::ShaperFlags flags) const
281 if (m_directWriteFontFace != 0) {
282 QVarLengthArray<UINT32> codePoints(len);
283 for (int i=0; i<len; ++i) {
284 codePoints[i] = getChar(str, i, len);
285 if (flags & QTextEngine::RightToLeft)
286 codePoints[i] = QChar::mirroredChar(codePoints[i]);
289 QVarLengthArray<UINT16> glyphIndices(len);
290 HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(codePoints.data(),
292 glyphIndices.data());
295 for (int i=0; i<len; ++i)
296 glyphs->glyphs[i] = glyphIndices[i];
300 if (!(flags & QTextEngine::GlyphIndicesOnly))
301 recalcAdvances(glyphs, 0);
305 qErrnoWarning("QFontEngineDirectWrite::stringToCMap: GetGlyphIndicesW failed");
312 void QFontEngineDirectWrite::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags) const
314 if (m_directWriteFontFace == 0)
317 QVarLengthArray<UINT16> glyphIndices(glyphs->numGlyphs);
320 for(int i=0; i<glyphs->numGlyphs; i++)
321 glyphIndices[i] = UINT16(glyphs->glyphs[i]);
323 QVarLengthArray<DWRITE_GLYPH_METRICS> glyphMetrics(glyphIndices.size());
324 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(glyphIndices.data(),
326 glyphMetrics.data());
328 for (int i=0; i<glyphs->numGlyphs; ++i) {
329 glyphs->advances_x[i] = DESIGN_TO_LOGICAL(glyphMetrics[i].advanceWidth);
330 if (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
331 glyphs->advances_x[i] = glyphs->advances_x[i].round();
332 glyphs->advances_y[i] = 0;
335 qErrnoWarning("QFontEngineDirectWrite::recalcAdvances: GetDesignGlyphMetrics failed");
339 void QFontEngineDirectWrite::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
340 QPainterPath *path, QTextItem::RenderFlags flags)
342 if (m_directWriteFontFace == 0)
345 QVarLengthArray<UINT16> glyphIndices(nglyphs);
346 QVarLengthArray<DWRITE_GLYPH_OFFSET> glyphOffsets(nglyphs);
347 QVarLengthArray<FLOAT> glyphAdvances(nglyphs);
349 for (int i=0; i<nglyphs; ++i) {
350 glyphIndices[i] = glyphs[i];
351 glyphOffsets[i].advanceOffset = positions[i].x.toReal();
352 glyphOffsets[i].ascenderOffset = -positions[i].y.toReal();
353 glyphAdvances[i] = 0.0;
356 GeometrySink geometrySink(path);
357 HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline(
360 glyphAdvances.data(),
364 flags & QTextItem::RightToLeft,
369 qErrnoWarning("QFontEngineDirectWrite::addGlyphsToPath: GetGlyphRunOutline failed");
372 glyph_metrics_t QFontEngineDirectWrite::boundingBox(const QGlyphLayout &glyphs)
374 if (glyphs.numGlyphs == 0)
375 return glyph_metrics_t();
377 bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics;
380 for (int i = 0; i < glyphs.numGlyphs; ++i) {
381 w += round ? glyphs.effectiveAdvance(i).round() : glyphs.effectiveAdvance(i);
385 return glyph_metrics_t(0, -m_ascent, w - lastRightBearing(glyphs), m_ascent + m_descent, w, 0);
388 glyph_metrics_t QFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph, QFixed subPixelPosition,
389 const QTransform &matrix,
390 GlyphFormat /*format*/)
392 glyph_metrics_t bbox = QFontEngine::boundingBox(glyph, matrix); // To get transformed advance
394 UINT16 glyphIndex = glyph;
395 FLOAT glyphAdvance = 0;
397 DWRITE_GLYPH_OFFSET glyphOffset;
398 glyphOffset.advanceOffset = 0;
399 glyphOffset.ascenderOffset = 0;
401 DWRITE_GLYPH_RUN glyphRun;
402 glyphRun.fontFace = m_directWriteFontFace;
403 glyphRun.fontEmSize = fontDef.pixelSize;
404 glyphRun.glyphCount = 1;
405 glyphRun.glyphIndices = &glyphIndex;
406 glyphRun.glyphAdvances = &glyphAdvance;
407 glyphRun.isSideways = false;
408 glyphRun.bidiLevel = 0;
409 glyphRun.glyphOffsets = &glyphOffset;
411 DWRITE_MATRIX transform;
412 transform.dx = subPixelPosition.toReal();
414 transform.m11 = matrix.m11();
415 transform.m12 = matrix.m12();
416 transform.m21 = matrix.m21();
417 transform.m22 = matrix.m22();
419 IDWriteGlyphRunAnalysis *glyphAnalysis = NULL;
420 HRESULT hr = m_directWriteFactory->CreateGlyphRunAnalysis(
424 DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC,
425 DWRITE_MEASURING_MODE_NATURAL,
432 glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect);
433 glyphAnalysis->Release();
435 return glyph_metrics_t(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
436 bbox.xoff, bbox.yoff);
438 return glyph_metrics_t();
442 glyph_metrics_t QFontEngineDirectWrite::boundingBox(glyph_t g)
444 if (m_directWriteFontFace == 0)
445 return glyph_metrics_t();
447 UINT16 glyphIndex = g;
449 DWRITE_GLYPH_METRICS glyphMetrics;
450 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&glyphIndex, 1, &glyphMetrics);
452 QFixed advanceWidth = DESIGN_TO_LOGICAL(glyphMetrics.advanceWidth);
453 QFixed leftSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.leftSideBearing);
454 QFixed rightSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.rightSideBearing);
455 QFixed advanceHeight = DESIGN_TO_LOGICAL(glyphMetrics.advanceHeight);
456 QFixed verticalOriginY = DESIGN_TO_LOGICAL(glyphMetrics.verticalOriginY);
458 if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
459 advanceWidth = advanceWidth.round();
460 advanceHeight = advanceHeight.round();
463 QFixed width = advanceWidth - leftSideBearing - rightSideBearing;
465 return glyph_metrics_t(-leftSideBearing, -verticalOriginY,
466 width, m_ascent + m_descent,
467 advanceWidth, advanceHeight);
469 qErrnoWarning("QFontEngineDirectWrite::boundingBox: GetDesignGlyphMetrics failed");
472 return glyph_metrics_t();
475 QFixed QFontEngineDirectWrite::ascent() const
477 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
482 QFixed QFontEngineDirectWrite::descent() const
484 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
485 ? (m_descent).round()
489 QFixed QFontEngineDirectWrite::leading() const
491 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
496 QFixed QFontEngineDirectWrite::xHeight() const
498 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
503 qreal QFontEngineDirectWrite::maxCharWidth() const
509 extern const uint *qt_pow_gamma();
511 QImage QFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition,
512 const QTransform &xform)
514 QImage im = imageForGlyph(glyph, subPixelPosition, 0, xform);
516 QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
517 QVector<QRgb> colors(256);
518 for (int i=0; i<256; ++i)
519 colors[i] = qRgba(0, 0, 0, i);
520 indexed.setColorTable(colors);
522 uint *gamma = qt_pow_gamma();
523 for (int y=0; y<im.height(); ++y) {
524 uint *src = (uint*) im.scanLine(y);
525 uchar *dst = indexed.scanLine(y);
526 for (int x=0; x<im.width(); ++x) {
527 uint gray = qGray(0xffffffff - *src);
528 *dst = 255 - (gamma ? gamma[gray] * 255. / 2047. : gray);
537 bool QFontEngineDirectWrite::supportsSubPixelPositions() const
542 QImage QFontEngineDirectWrite::imageForGlyph(glyph_t t,
543 QFixed subPixelPosition,
545 const QTransform &xform)
547 UINT16 glyphIndex = t;
548 FLOAT glyphAdvance = 0;
550 DWRITE_GLYPH_OFFSET glyphOffset;
551 glyphOffset.advanceOffset = 0;
552 glyphOffset.ascenderOffset = 0;
554 DWRITE_GLYPH_RUN glyphRun;
555 glyphRun.fontFace = m_directWriteFontFace;
556 glyphRun.fontEmSize = fontDef.pixelSize;
557 glyphRun.glyphCount = 1;
558 glyphRun.glyphIndices = &glyphIndex;
559 glyphRun.glyphAdvances = &glyphAdvance;
560 glyphRun.isSideways = false;
561 glyphRun.bidiLevel = 0;
562 glyphRun.glyphOffsets = &glyphOffset;
564 DWRITE_MATRIX transform;
565 transform.dx = subPixelPosition.toReal();
567 transform.m11 = xform.m11();
568 transform.m12 = xform.m12();
569 transform.m21 = xform.m21();
570 transform.m22 = xform.m22();
572 IDWriteGlyphRunAnalysis *glyphAnalysis = NULL;
573 HRESULT hr = m_directWriteFactory->CreateGlyphRunAnalysis(
577 DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC,
578 DWRITE_MEASURING_MODE_NATURAL,
585 glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect);
589 rect.right += margin;
590 rect.bottom += margin;
592 int width = rect.right - rect.left;
593 int height = rect.bottom - rect.top;
595 int size = width * height * 3;
597 BYTE *alphaValues = new BYTE[size];
598 memset(alphaValues, size, 0);
600 hr = glyphAnalysis->CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1,
606 QImage img(width, height, QImage::Format_RGB32);
607 img.fill(0xffffffff);
609 for (int y=0; y<height; ++y) {
610 uint *dest = reinterpret_cast<uint *>(img.scanLine(y));
611 BYTE *src = alphaValues + width * 3 * y;
613 for (int x=0; x<width; ++x) {
614 dest[x] = *(src) << 16
622 delete[] alphaValues;
623 glyphAnalysis->Release();
627 delete[] alphaValues;
628 glyphAnalysis->Release();
630 qErrnoWarning("QFontEngineDirectWrite::imageForGlyph: CreateAlphaTexture failed");
634 qErrnoWarning("QFontEngineDirectWrite::imageForGlyph: CreateGlyphRunAnalysis failed");
640 QImage QFontEngineDirectWrite::alphaRGBMapForGlyph(glyph_t t,
641 QFixed subPixelPosition,
642 const QTransform &xform)
644 QImage mask = imageForGlyph(t, subPixelPosition,
645 glyphMargin(QFontEngineGlyphCache::Raster_RGBMask),
647 return mask.depth() == 32
649 : mask.convertToFormat(QImage::Format_RGB32);
652 const char *QFontEngineDirectWrite::name() const
657 bool QFontEngineDirectWrite::canRender(const QChar *string, int len)
659 QVarLengthArray<UINT32> codePoints(len);
660 int actualLength = 0;
661 for (int i=0; i<len; ++i, actualLength++)
662 codePoints[actualLength] = getChar(string, i, len);
664 QVarLengthArray<UINT16> glyphIndices(actualLength);
665 HRESULT hr = m_directWriteFontFace->GetGlyphIndices(codePoints.data(), actualLength,
666 glyphIndices.data());
668 qErrnoWarning(hr, "QFontEngineDirectWrite::canRender: GetGlyphIndices failed");
671 for (int i=0; i<glyphIndices.size(); ++i) {
672 if (glyphIndices.at(i) == 0)
680 QFontEngine::Type QFontEngineDirectWrite::type() const
682 return QFontEngine::DirectWrite;
685 QFontEngine *QFontEngineDirectWrite::cloneWithSize(qreal pixelSize) const
687 QFontEngine *fontEngine = new QFontEngineDirectWrite(m_directWriteFactory, m_directWriteFontFace,
690 fontEngine->fontDef = fontDef;
691 fontEngine->fontDef.pixelSize = pixelSize;
698 #endif // QT_NO_DIRECTWRITE