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 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
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.
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.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
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 qMemCopy(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 unsigned int uc = str[i].unicode();
273 if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
274 uint low = str[i+1].unicode();
275 if (low >= 0xdc00 && low < 0xe000) {
276 uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
283 bool QFontEngineDirectWrite::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
284 int *nglyphs, QTextEngine::ShaperFlags flags) const
286 if (m_directWriteFontFace != 0) {
287 QVarLengthArray<UINT32> codePoints(len);
288 for (int i=0; i<len; ++i) {
289 codePoints[i] = getChar(str, i, len);
290 if (flags & QTextEngine::RightToLeft)
291 codePoints[i] = QChar::mirroredChar(codePoints[i]);
294 QVarLengthArray<UINT16> glyphIndices(len);
295 HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(codePoints.data(),
297 glyphIndices.data());
300 for (int i=0; i<len; ++i)
301 glyphs->glyphs[i] = glyphIndices[i];
305 if (!(flags & QTextEngine::GlyphIndicesOnly))
306 recalcAdvances(glyphs, 0);
310 qErrnoWarning("QFontEngineDirectWrite::stringToCMap: GetGlyphIndicesW failed");
317 void QFontEngineDirectWrite::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags) const
319 if (m_directWriteFontFace == 0)
322 QVarLengthArray<UINT16> glyphIndices(glyphs->numGlyphs);
325 for(int i=0; i<glyphs->numGlyphs; i++)
326 glyphIndices[i] = UINT16(glyphs->glyphs[i]);
328 QVarLengthArray<DWRITE_GLYPH_METRICS> glyphMetrics(glyphIndices.size());
329 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(glyphIndices.data(),
331 glyphMetrics.data());
333 for (int i=0; i<glyphs->numGlyphs; ++i) {
334 glyphs->advances_x[i] = DESIGN_TO_LOGICAL(glyphMetrics[i].advanceWidth);
335 if (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
336 glyphs->advances_x[i] = glyphs->advances_x[i].round();
337 glyphs->advances_y[i] = 0;
340 qErrnoWarning("QFontEngineDirectWrite::recalcAdvances: GetDesignGlyphMetrics failed");
344 void QFontEngineDirectWrite::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
345 QPainterPath *path, QTextItem::RenderFlags flags)
347 if (m_directWriteFontFace == 0)
350 QVarLengthArray<UINT16> glyphIndices(nglyphs);
351 QVarLengthArray<DWRITE_GLYPH_OFFSET> glyphOffsets(nglyphs);
352 QVarLengthArray<FLOAT> glyphAdvances(nglyphs);
354 for (int i=0; i<nglyphs; ++i) {
355 glyphIndices[i] = glyphs[i];
356 glyphOffsets[i].advanceOffset = positions[i].x.toReal();
357 glyphOffsets[i].ascenderOffset = -positions[i].y.toReal();
358 glyphAdvances[i] = 0.0;
361 GeometrySink geometrySink(path);
362 HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline(
365 glyphAdvances.data(),
369 flags & QTextItem::RightToLeft,
374 qErrnoWarning("QFontEngineDirectWrite::addGlyphsToPath: GetGlyphRunOutline failed");
377 glyph_metrics_t QFontEngineDirectWrite::boundingBox(const QGlyphLayout &glyphs)
379 if (glyphs.numGlyphs == 0)
380 return glyph_metrics_t();
382 bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics;
385 for (int i = 0; i < glyphs.numGlyphs; ++i) {
386 w += round ? glyphs.effectiveAdvance(i).round() : glyphs.effectiveAdvance(i);
390 return glyph_metrics_t(0, -m_ascent, w - lastRightBearing(glyphs), m_ascent + m_descent, w, 0);
393 glyph_metrics_t QFontEngineDirectWrite::boundingBox(glyph_t g)
395 if (m_directWriteFontFace == 0)
396 return glyph_metrics_t();
398 UINT16 glyphIndex = g;
400 DWRITE_GLYPH_METRICS glyphMetrics;
401 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&glyphIndex, 1, &glyphMetrics);
403 QFixed advanceWidth = DESIGN_TO_LOGICAL(glyphMetrics.advanceWidth);
404 QFixed leftSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.leftSideBearing);
405 QFixed rightSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.rightSideBearing);
406 QFixed advanceHeight = DESIGN_TO_LOGICAL(glyphMetrics.advanceHeight);
407 QFixed verticalOriginY = DESIGN_TO_LOGICAL(glyphMetrics.verticalOriginY);
409 if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
410 advanceWidth = advanceWidth.round();
411 advanceHeight = advanceHeight.round();
414 QFixed width = advanceWidth - leftSideBearing - rightSideBearing;
416 return glyph_metrics_t(-leftSideBearing, -verticalOriginY,
417 width, m_ascent + m_descent,
418 advanceWidth, advanceHeight);
420 qErrnoWarning("QFontEngineDirectWrite::boundingBox: GetDesignGlyphMetrics failed");
423 return glyph_metrics_t();
426 QFixed QFontEngineDirectWrite::ascent() const
428 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
433 QFixed QFontEngineDirectWrite::descent() const
435 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
436 ? (m_descent - 1).round()
440 QFixed QFontEngineDirectWrite::leading() const
442 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
447 QFixed QFontEngineDirectWrite::xHeight() const
449 return fontDef.styleStrategy & QFont::ForceIntegerMetrics
454 qreal QFontEngineDirectWrite::maxCharWidth() const
460 extern uint qt_pow_gamma[256];
462 QImage QFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition)
464 QImage im = imageForGlyph(glyph, subPixelPosition, 0, QTransform());
466 QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
467 QVector<QRgb> colors(256);
468 for (int i=0; i<256; ++i)
469 colors[i] = qRgba(0, 0, 0, i);
470 indexed.setColorTable(colors);
472 for (int y=0; y<im.height(); ++y) {
473 uint *src = (uint*) im.scanLine(y);
474 uchar *dst = indexed.scanLine(y);
475 for (int x=0; x<im.width(); ++x) {
476 *dst = 255 - (qt_pow_gamma[qGray(0xffffffff - *src)] * 255. / 2047.);
485 bool QFontEngineDirectWrite::supportsSubPixelPositions() const
490 QImage QFontEngineDirectWrite::imageForGlyph(glyph_t t,
491 QFixed subPixelPosition,
493 const QTransform &xform)
495 glyph_metrics_t metrics = QFontEngine::boundingBox(t, xform);
496 int width = (metrics.width + margin * 2 + 4).ceil().toInt() ;
497 int height = (metrics.height + margin * 2 + 4).ceil().toInt();
499 UINT16 glyphIndex = t;
500 FLOAT glyphAdvance = metrics.xoff.toReal();
502 DWRITE_GLYPH_OFFSET glyphOffset;
503 glyphOffset.advanceOffset = 0;
504 glyphOffset.ascenderOffset = 0;
506 DWRITE_GLYPH_RUN glyphRun;
507 glyphRun.fontFace = m_directWriteFontFace;
508 glyphRun.fontEmSize = fontDef.pixelSize;
509 glyphRun.glyphCount = 1;
510 glyphRun.glyphIndices = &glyphIndex;
511 glyphRun.glyphAdvances = &glyphAdvance;
512 glyphRun.isSideways = false;
513 glyphRun.bidiLevel = 0;
514 glyphRun.glyphOffsets = &glyphOffset;
516 QFixed x = margin - metrics.x.round() + subPixelPosition;
517 QFixed y = margin - metrics.y.floor();
519 DWRITE_MATRIX transform;
520 transform.dx = x.toReal();
521 transform.dy = y.toReal();
522 transform.m11 = xform.m11();
523 transform.m12 = xform.m12();
524 transform.m21 = xform.m21();
525 transform.m22 = xform.m22();
527 IDWriteGlyphRunAnalysis *glyphAnalysis = NULL;
528 HRESULT hr = m_directWriteFactory->CreateGlyphRunAnalysis(
532 DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC,
533 DWRITE_MEASURING_MODE_NATURAL,
543 rect.bottom = height;
545 int size = width * height * 3;
546 BYTE *alphaValues = new BYTE[size];
547 qMemSet(alphaValues, size, 0);
549 hr = glyphAnalysis->CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1,
555 QImage img(width, height, QImage::Format_RGB32);
556 img.fill(0xffffffff);
558 for (int y=0; y<height; ++y) {
559 uint *dest = reinterpret_cast<uint *>(img.scanLine(y));
560 BYTE *src = alphaValues + width * 3 * y;
562 for (int x=0; x<width; ++x) {
563 dest[x] = *(src) << 16
571 delete[] alphaValues;
572 glyphAnalysis->Release();
576 delete[] alphaValues;
577 glyphAnalysis->Release();
579 qErrnoWarning("QFontEngineDirectWrite::imageForGlyph: CreateAlphaTexture failed");
583 qErrnoWarning("QFontEngineDirectWrite::imageForGlyph: CreateGlyphRunAnalysis failed");
589 QImage QFontEngineDirectWrite::alphaRGBMapForGlyph(glyph_t t,
590 QFixed subPixelPosition,
592 const QTransform &xform)
594 QImage mask = imageForGlyph(t, subPixelPosition, margin, xform);
595 return mask.depth() == 32
597 : mask.convertToFormat(QImage::Format_RGB32);
600 const char *QFontEngineDirectWrite::name() const
605 bool QFontEngineDirectWrite::canRender(const QChar *string, int len)
607 QVarLengthArray<UINT32> codePoints(len);
608 int actualLength = 0;
609 for (int i=0; i<len; ++i, actualLength++)
610 codePoints[actualLength] = getChar(string, i, len);
612 QVarLengthArray<UINT16> glyphIndices(actualLength);
613 HRESULT hr = m_directWriteFontFace->GetGlyphIndices(codePoints.data(), actualLength,
614 glyphIndices.data());
616 qErrnoWarning(hr, "QFontEngineDirectWrite::canRender: GetGlyphIndices failed");
619 for (int i=0; i<glyphIndices.size(); ++i) {
620 if (glyphIndices.at(i) == 0)
628 QFontEngine::Type QFontEngineDirectWrite::type() const
630 return QFontEngine::DirectWrite;
633 QFontEngine *QFontEngineDirectWrite::cloneWithSize(qreal pixelSize) const
635 QFontEngine *fontEngine = new QFontEngineDirectWrite(m_directWriteFactory, m_directWriteFontFace,
638 fontEngine->fontDef = fontDef;
639 fontEngine->fontDef.pixelSize = pixelSize;
646 #endif // QT_NO_DIRECTWRITE