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
228 if (m_directWriteFontFace) {
229 DWORD t = qbswap<quint32>(tag);
231 const void *tableData = 0;
232 void *tableContext = 0;
235 HRESULT hr = m_directWriteFontFace->TryGetFontTable(
236 t, &tableData, &tableSize, &tableContext, &exists
246 } else if (*length < tableSize) {
250 memcpy(buffer, tableData, tableSize);
251 m_directWriteFontFace->ReleaseFontTable(tableContext);
255 qErrnoWarning("QFontEngineDirectWrite::getSfntTableData: TryGetFontTable failed");
262 QFixed QFontEngineDirectWrite::emSquareSize() const
264 if (m_unitsPerEm > 0)
267 return QFontEngine::emSquareSize();
270 inline unsigned int getChar(const QChar *str, int &i, const int len)
272 uint ucs4 = str[i].unicode();
273 if (str[i].isHighSurrogate() && i < len-1 && str[i+1].isLowSurrogate()) {
275 ucs4 = QChar::surrogateToUcs4( ucs4, str[i].unicode());
280 bool QFontEngineDirectWrite::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
281 int *nglyphs, QTextEngine::ShaperFlags flags) const
283 if (m_directWriteFontFace != 0) {
284 QVarLengthArray<UINT32> codePoints(len);
285 for (int i=0; i<len; ++i) {
286 codePoints[i] = getChar(str, i, len);
287 if (flags & QTextEngine::RightToLeft)
288 codePoints[i] = QChar::mirroredChar(codePoints[i]);
291 QVarLengthArray<UINT16> glyphIndices(len);
292 HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(codePoints.data(),
294 glyphIndices.data());
297 for (int i=0; i<len; ++i)
298 glyphs->glyphs[i] = glyphIndices[i];
302 if (!(flags & QTextEngine::GlyphIndicesOnly))
303 recalcAdvances(glyphs, 0);
307 qErrnoWarning("QFontEngineDirectWrite::stringToCMap: GetGlyphIndicesW failed");
314 void QFontEngineDirectWrite::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags) const
316 if (m_directWriteFontFace == 0)
319 QVarLengthArray<UINT16> glyphIndices(glyphs->numGlyphs);
322 for(int i=0; i<glyphs->numGlyphs; i++)
323 glyphIndices[i] = UINT16(glyphs->glyphs[i]);
325 QVarLengthArray<DWRITE_GLYPH_METRICS> glyphMetrics(glyphIndices.size());
326 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(glyphIndices.data(),
328 glyphMetrics.data());
330 for (int i=0; i<glyphs->numGlyphs; ++i) {
331 glyphs->advances_x[i] = DESIGN_TO_LOGICAL(glyphMetrics[i].advanceWidth);
332 if (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
333 glyphs->advances_x[i] = glyphs->advances_x[i].round();
334 glyphs->advances_y[i] = 0;
337 qErrnoWarning("QFontEngineDirectWrite::recalcAdvances: GetDesignGlyphMetrics failed");
341 void QFontEngineDirectWrite::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
342 QPainterPath *path, QTextItem::RenderFlags flags)
344 if (m_directWriteFontFace == 0)
347 QVarLengthArray<UINT16> glyphIndices(nglyphs);
348 QVarLengthArray<DWRITE_GLYPH_OFFSET> glyphOffsets(nglyphs);
349 QVarLengthArray<FLOAT> glyphAdvances(nglyphs);
351 for (int i=0; i<nglyphs; ++i) {
352 glyphIndices[i] = glyphs[i];
353 glyphOffsets[i].advanceOffset = positions[i].x.toReal();
354 glyphOffsets[i].ascenderOffset = -positions[i].y.toReal();
355 glyphAdvances[i] = 0.0;
358 GeometrySink geometrySink(path);
359 HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline(
362 glyphAdvances.data(),
366 flags & QTextItem::RightToLeft,
371 qErrnoWarning("QFontEngineDirectWrite::addGlyphsToPath: GetGlyphRunOutline failed");
374 glyph_metrics_t QFontEngineDirectWrite::boundingBox(const QGlyphLayout &glyphs)
376 if (glyphs.numGlyphs == 0)
377 return glyph_metrics_t();
379 bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics;
382 for (int i = 0; i < glyphs.numGlyphs; ++i) {
383 w += round ? glyphs.effectiveAdvance(i).round() : glyphs.effectiveAdvance(i);
387 return glyph_metrics_t(0, -m_ascent, w - lastRightBearing(glyphs), m_ascent + m_descent, w, 0);
390 glyph_metrics_t QFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph, QFixed subPixelPosition,
391 const QTransform &matrix,
392 GlyphFormat /*format*/)
394 glyph_metrics_t bbox = QFontEngine::boundingBox(glyph, matrix); // To get transformed advance
396 UINT16 glyphIndex = glyph;
397 FLOAT glyphAdvance = 0;
399 DWRITE_GLYPH_OFFSET glyphOffset;
400 glyphOffset.advanceOffset = 0;
401 glyphOffset.ascenderOffset = 0;
403 DWRITE_GLYPH_RUN glyphRun;
404 glyphRun.fontFace = m_directWriteFontFace;
405 glyphRun.fontEmSize = fontDef.pixelSize;
406 glyphRun.glyphCount = 1;
407 glyphRun.glyphIndices = &glyphIndex;
408 glyphRun.glyphAdvances = &glyphAdvance;
409 glyphRun.isSideways = false;
410 glyphRun.bidiLevel = 0;
411 glyphRun.glyphOffsets = &glyphOffset;
413 DWRITE_MATRIX transform;
414 transform.dx = subPixelPosition.toReal();
416 transform.m11 = matrix.m11();
417 transform.m12 = matrix.m12();
418 transform.m21 = matrix.m21();
419 transform.m22 = matrix.m22();
421 IDWriteGlyphRunAnalysis *glyphAnalysis = NULL;
422 HRESULT hr = m_directWriteFactory->CreateGlyphRunAnalysis(
426 DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC,
427 DWRITE_MEASURING_MODE_NATURAL,
434 glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect);
435 glyphAnalysis->Release();
437 return glyph_metrics_t(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
438 bbox.xoff, bbox.yoff);
440 return glyph_metrics_t();
444 glyph_metrics_t QFontEngineDirectWrite::boundingBox(glyph_t g)
446 if (m_directWriteFontFace == 0)
447 return glyph_metrics_t();
449 UINT16 glyphIndex = g;
451 DWRITE_GLYPH_METRICS glyphMetrics;
452 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&glyphIndex, 1, &glyphMetrics);
454 QFixed advanceWidth = DESIGN_TO_LOGICAL(glyphMetrics.advanceWidth);
455 QFixed leftSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.leftSideBearing);
456 QFixed rightSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.rightSideBearing);
457 QFixed advanceHeight = DESIGN_TO_LOGICAL(glyphMetrics.advanceHeight);
458 QFixed verticalOriginY = DESIGN_TO_LOGICAL(glyphMetrics.verticalOriginY);
460 if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
461 advanceWidth = advanceWidth.round();
462 advanceHeight = advanceHeight.round();
465 QFixed width = advanceWidth - leftSideBearing - rightSideBearing;
467 return glyph_metrics_t(-leftSideBearing, -verticalOriginY,
468 width, m_ascent + m_descent,
469 advanceWidth, advanceHeight);
471 qErrnoWarning("QFontEngineDirectWrite::boundingBox: GetDesignGlyphMetrics failed");
474 return glyph_metrics_t();
477 QFixed QFontEngineDirectWrite::ascent() const
479 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
484 QFixed QFontEngineDirectWrite::descent() const
486 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
487 ? (m_descent).round()
491 QFixed QFontEngineDirectWrite::leading() const
493 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
498 QFixed QFontEngineDirectWrite::xHeight() const
500 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
505 qreal QFontEngineDirectWrite::maxCharWidth() const
511 extern const uint *qt_pow_gamma();
513 QImage QFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition,
514 const QTransform &xform)
516 QImage im = imageForGlyph(glyph, subPixelPosition, 0, xform);
518 QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
519 QVector<QRgb> colors(256);
520 for (int i=0; i<256; ++i)
521 colors[i] = qRgba(0, 0, 0, i);
522 indexed.setColorTable(colors);
524 uint *gamma = qt_pow_gamma();
525 for (int y=0; y<im.height(); ++y) {
526 uint *src = (uint*) im.scanLine(y);
527 uchar *dst = indexed.scanLine(y);
528 for (int x=0; x<im.width(); ++x) {
529 uint gray = qGray(0xffffffff - *src);
530 *dst = 255 - (gamma ? gamma[gray] * 255. / 2047. : gray);
539 bool QFontEngineDirectWrite::supportsSubPixelPositions() const
544 QImage QFontEngineDirectWrite::imageForGlyph(glyph_t t,
545 QFixed subPixelPosition,
547 const QTransform &xform)
549 UINT16 glyphIndex = t;
550 FLOAT glyphAdvance = 0;
552 DWRITE_GLYPH_OFFSET glyphOffset;
553 glyphOffset.advanceOffset = 0;
554 glyphOffset.ascenderOffset = 0;
556 DWRITE_GLYPH_RUN glyphRun;
557 glyphRun.fontFace = m_directWriteFontFace;
558 glyphRun.fontEmSize = fontDef.pixelSize;
559 glyphRun.glyphCount = 1;
560 glyphRun.glyphIndices = &glyphIndex;
561 glyphRun.glyphAdvances = &glyphAdvance;
562 glyphRun.isSideways = false;
563 glyphRun.bidiLevel = 0;
564 glyphRun.glyphOffsets = &glyphOffset;
566 DWRITE_MATRIX transform;
567 transform.dx = subPixelPosition.toReal();
569 transform.m11 = xform.m11();
570 transform.m12 = xform.m12();
571 transform.m21 = xform.m21();
572 transform.m22 = xform.m22();
574 IDWriteGlyphRunAnalysis *glyphAnalysis = NULL;
575 HRESULT hr = m_directWriteFactory->CreateGlyphRunAnalysis(
579 DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC,
580 DWRITE_MEASURING_MODE_NATURAL,
587 glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect);
591 rect.right += margin;
592 rect.bottom += margin;
594 int width = rect.right - rect.left;
595 int height = rect.bottom - rect.top;
597 int size = width * height * 3;
599 BYTE *alphaValues = new BYTE[size];
600 memset(alphaValues, size, 0);
602 hr = glyphAnalysis->CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1,
608 QImage img(width, height, QImage::Format_RGB32);
609 img.fill(0xffffffff);
611 for (int y=0; y<height; ++y) {
612 uint *dest = reinterpret_cast<uint *>(img.scanLine(y));
613 BYTE *src = alphaValues + width * 3 * y;
615 for (int x=0; x<width; ++x) {
616 dest[x] = *(src) << 16
624 delete[] alphaValues;
625 glyphAnalysis->Release();
629 delete[] alphaValues;
630 glyphAnalysis->Release();
632 qErrnoWarning("QFontEngineDirectWrite::imageForGlyph: CreateAlphaTexture failed");
636 qErrnoWarning("QFontEngineDirectWrite::imageForGlyph: CreateGlyphRunAnalysis failed");
642 QImage QFontEngineDirectWrite::alphaRGBMapForGlyph(glyph_t t,
643 QFixed subPixelPosition,
644 const QTransform &xform)
646 QImage mask = imageForGlyph(t, subPixelPosition,
647 glyphMargin(QFontEngineGlyphCache::Raster_RGBMask),
649 return mask.depth() == 32
651 : mask.convertToFormat(QImage::Format_RGB32);
654 const char *QFontEngineDirectWrite::name() const
659 bool QFontEngineDirectWrite::canRender(const QChar *string, int len)
661 QVarLengthArray<UINT32> codePoints(len);
662 int actualLength = 0;
663 for (int i=0; i<len; ++i, actualLength++)
664 codePoints[actualLength] = getChar(string, i, len);
666 QVarLengthArray<UINT16> glyphIndices(actualLength);
667 HRESULT hr = m_directWriteFontFace->GetGlyphIndices(codePoints.data(), actualLength,
668 glyphIndices.data());
670 qErrnoWarning(hr, "QFontEngineDirectWrite::canRender: GetGlyphIndices failed");
673 for (int i=0; i<glyphIndices.size(); ++i) {
674 if (glyphIndices.at(i) == 0)
682 QFontEngine::Type QFontEngineDirectWrite::type() const
684 return QFontEngine::DirectWrite;
687 QFontEngine *QFontEngineDirectWrite::cloneWithSize(qreal pixelSize) const
689 QFontEngine *fontEngine = new QFontEngineDirectWrite(m_directWriteFactory, m_directWriteFontFace,
692 fontEngine->fontDef = fontDef;
693 fontEngine->fontDef.pixelSize = pixelSize;
700 #endif // QT_NO_DIRECTWRITE