8#include <QtCore/QtEndian>
9#include <QtCore/QVarLengthArray>
10#include <QtCore/QFile>
11#include <private/qstringiterator_p.h>
12#include <QtCore/private/qsystemlibrary_p.h>
13#include <QtCore/private/qwinregistry_p.h>
14#include <QtCore/private/qcomptr_p.h>
15#include <QtGui/private/qguiapplication_p.h>
16#include <qpa/qplatformintegration.h>
17#include <QtGui/qpainterpath.h>
19#include <private/qcolrpaintgraphrenderer_p.h>
21#if QT_CONFIG(directwrite3)
22# include "qwindowsdirectwritefontdatabase_p.h"
31QT_WARNING_DISABLE_CLANG(
"-Wmicrosoft-exception-spec")
34#define DESIGN_TO_LOGICAL(DESIGN_UNIT_VALUE)
35 QFixed::fromReal((qreal(DESIGN_UNIT_VALUE) / qreal(m_unitsPerEm)) * fontDef.pixelSize)
39 class GeometrySink:
public IDWriteGeometrySink
41 Q_DISABLE_COPY_MOVE(GeometrySink)
43 GeometrySink(QPainterPath *path)
44 : m_refCount(0), m_path(path)
46 Q_ASSERT(m_path != 0);
48 virtual ~GeometrySink() =
default;
50 IFACEMETHOD_(
void, AddBeziers)(
const D2D1_BEZIER_SEGMENT *beziers, UINT bezierCount)
override;
51 IFACEMETHOD_(
void, AddLines)(
const D2D1_POINT_2F *points, UINT pointCount)
override;
52 IFACEMETHOD_(
void, BeginFigure)(D2D1_POINT_2F startPoint, D2D1_FIGURE_BEGIN figureBegin)
override;
53 IFACEMETHOD(Close)()
override;
54 IFACEMETHOD_(
void, EndFigure)(D2D1_FIGURE_END figureEnd)
override;
55 IFACEMETHOD_(
void, SetFillMode)(D2D1_FILL_MODE fillMode)
override;
56 IFACEMETHOD_(
void, SetSegmentFlags)(D2D1_PATH_SEGMENT vertexFlags)
override;
58 IFACEMETHOD_(
unsigned long, AddRef)()
override;
59 IFACEMETHOD_(
unsigned long, Release)()
override;
60 IFACEMETHOD(QueryInterface)(IID
const &riid,
void **ppvObject)
override;
63 inline static QPointF fromD2D1_POINT_2F(
const D2D1_POINT_2F &inp)
65 return QPointF(inp.x, inp.y);
68 unsigned long m_refCount;
73 void GeometrySink::AddBeziers(
const D2D1_BEZIER_SEGMENT *beziers,
74 UINT bezierCount)
noexcept
76 for (uint i=0; i<bezierCount; ++i) {
77 QPointF c1 = fromD2D1_POINT_2F(beziers[i].point1);
78 QPointF c2 = fromD2D1_POINT_2F(beziers[i].point2);
79 QPointF p2 = fromD2D1_POINT_2F(beziers[i].point3);
81 m_path->cubicTo(c1, c2, p2);
85 void GeometrySink::AddLines(
const D2D1_POINT_2F *points, UINT pointsCount)
noexcept
87 for (uint i=0; i<pointsCount; ++i)
88 m_path->lineTo(fromD2D1_POINT_2F(points[i]));
91 void GeometrySink::BeginFigure(D2D1_POINT_2F startPoint,
92 D2D1_FIGURE_BEGIN )
noexcept
94 m_startPoint = fromD2D1_POINT_2F(startPoint);
95 m_path->moveTo(m_startPoint);
98 IFACEMETHODIMP GeometrySink::Close()
noexcept
103 void GeometrySink::EndFigure(D2D1_FIGURE_END figureEnd)
noexcept
105 if (figureEnd == D2D1_FIGURE_END_CLOSED)
106 m_path->closeSubpath();
109 void GeometrySink::SetFillMode(D2D1_FILL_MODE fillMode)
noexcept
111 m_path->setFillRule(fillMode == D2D1_FILL_MODE_ALTERNATE
116 void GeometrySink::SetSegmentFlags(D2D1_PATH_SEGMENT )
noexcept
121 IFACEMETHODIMP_(
unsigned long) GeometrySink::AddRef()
noexcept
123 return InterlockedIncrement(&m_refCount);
126 IFACEMETHODIMP_(
unsigned long) GeometrySink::Release()
noexcept
128 unsigned long newCount = InterlockedDecrement(&m_refCount);
138 IFACEMETHODIMP GeometrySink::QueryInterface(IID
const &riid,
void **ppvObject)
noexcept
140 if (__uuidof(IDWriteGeometrySink) == riid) {
142 }
else if (__uuidof(IUnknown) == riid) {
157 switch (renderMode) {
158 case DWRITE_RENDERING_MODE_GDI_CLASSIC:
159 return DWRITE_MEASURING_MODE_GDI_CLASSIC;
160 case DWRITE_RENDERING_MODE_GDI_NATURAL:
161 return DWRITE_MEASURING_MODE_GDI_NATURAL;
163 return DWRITE_MEASURING_MODE_NATURAL;
169 QFont::HintingPreference hintingPreference = QFont::HintingPreference(fontDef.hintingPreference);
170 if (hintingPreference == QFont::PreferDefaultHinting) {
171 if (!qFuzzyCompare(qApp->devicePixelRatio(), 1.0))
172 hintingPreference = QFont::PreferVerticalHinting;
174 hintingPreference = QFont::PreferFullHinting;
177 return hintingPreference;
180bool QWindowsFontEngineDirectWrite::useSymmetricAntialiasing()
const
182 if (m_useSymmetricAntialiasing < 0) {
183 qCDebug(lcQpaFonts) <<
"Checking antialiasing strategy for:"
191 const qreal effectivePixelSize = fontDef.pixelSize * qApp->devicePixelRatio();
192 m_useSymmetricAntialiasing = effectivePixelSize > 16.0 || !hasHinting();
194 qCDebug(lcQpaFonts) <<
" After checking pixel size and hinting, defaulting to:"
195 <<
bool(m_useSymmetricAntialiasing);
198 const QByteArray gasp = getSfntTable(QFont::Tag(
"gasp").value());
199 if (gasp.size() > 4) {
200 qCDebug(lcQpaFonts) <<
" Checking GASP table, size=" << gasp.size();
202 const uchar *start =
reinterpret_cast<
const uchar *>(gasp.constBegin());
204 const quint16 numRanges = qFromBigEndian<quint16>(start + 2);
205 if (gasp.size() >= 4 + numRanges * 4) {
206 qCDebug(lcQpaFonts) <<
" GASP ranges:" << numRanges;
207 for (
int i = 0; i < numRanges; ++i) {
208 const quint16 rangeMaxPPEM = qFromBigEndian<quint16>(start + 4 + i * 4);
209 qCDebug(lcQpaFonts) <<
" GASP range " << i <<
"upper limit == " << rangeMaxPPEM;
211 if (rangeMaxPPEM >= effectivePixelSize) {
212 const quint16 rangeGaspBehavior = qFromBigEndian<quint16>(start + 4 + i * 4 + 2);
213 qCDebug(lcQpaFonts) <<
" GASP behavior " << i <<
"==" << rangeGaspBehavior;
216 m_useSymmetricAntialiasing = !!(rangeGaspBehavior & 0x8);
217 qCDebug(lcQpaFonts) <<
" Symmetric antialiasing override: "
218 <<
bool(m_useSymmetricAntialiasing);
227 return m_useSymmetricAntialiasing;
230DWRITE_RENDERING_MODE QWindowsFontEngineDirectWrite::hintingPreferenceToRenderingMode(
const QFontDef &fontDef)
const
232 if ((fontDef.styleStrategy & QFont::NoAntialias) && glyphFormat != QFontEngine::Format_ARGB)
233 return DWRITE_RENDERING_MODE_ALIASED;
235 QFont::HintingPreference hintingPreference = determineHinting(fontDef);
236 switch (hintingPreference) {
237 case QFont::PreferNoHinting:
238 return DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC;
239 case QFont::PreferVerticalHinting:
240 if (useSymmetricAntialiasing())
241 return DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC;
243 return DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL;
245 if (useSymmetricAntialiasing())
246 return DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC;
248 return DWRITE_RENDERING_MODE_GDI_CLASSIC;
253
254
255
256
257
258
259
260
261
262
264QWindowsFontEngineDirectWrite::QWindowsFontEngineDirectWrite(IDWriteFontFace *directWriteFontFace,
266 const QSharedPointer<QWindowsFontEngineData> &d)
267 : QFontEngine(DirectWrite)
268 , m_fontEngineData(d)
269 , m_directWriteFontFace(directWriteFontFace)
270 , m_directWriteBitmapRenderTarget(0)
271 , m_lineThickness(-1)
276 qCDebug(lcQpaFonts) <<
__FUNCTION__ << pixelSize;
278 Q_ASSERT(m_directWriteFontFace);
280 m_fontEngineData->directWriteFactory->AddRef();
281 m_directWriteFontFace->AddRef();
283 IDWriteRenderingParams *renderingParams =
nullptr;
284 if (SUCCEEDED(m_fontEngineData->directWriteFactory->CreateRenderingParams(&renderingParams))) {
285 m_pixelGeometry = renderingParams->GetPixelGeometry();
286 renderingParams->Release();
289 fontDef.pixelSize = pixelSize;
291 cache_cost = m_xHeight.toInt() * m_xHeight.toInt() * 2000;
294QWindowsFontEngineDirectWrite::~QWindowsFontEngineDirectWrite()
296 qCDebug(lcQpaFonts) <<
__FUNCTION__;
298 m_fontEngineData->directWriteFactory->Release();
299 m_directWriteFontFace->Release();
301 if (m_directWriteBitmapRenderTarget != 0)
302 m_directWriteBitmapRenderTarget->Release();
304 if (!m_uniqueFamilyName.isEmpty()) {
305 QPlatformFontDatabase *pfdb = QGuiApplicationPrivate::platformIntegration()->fontDatabase();
306 static_cast<QWindowsFontDatabase *>(pfdb)->derefUniqueFont(m_uniqueFamilyName);
315 return __uuidof(IDWriteLocalFontFileLoader);
318DECLARE_INTERFACE_(QIdWriteLocalFontFileLoader, IDWriteFontFileLoader)
320 STDMETHOD(GetFilePathLengthFromKey)(THIS_
void const *, UINT32, UINT32*) PURE;
321 STDMETHOD(GetFilePathFromKey)(THIS_
void const *, UINT32, WCHAR *, UINT32) PURE;
322 STDMETHOD(GetLastWriteTimeFromKey)(THIS_
void const *, UINT32, FILETIME *) PURE;
325static UUID uuidIdWriteLocalFontFileLoader()
327 static const UUID result = { 0xb2d9f3ec, 0xc9fe, 0x4a11, {0xa2, 0xec, 0xd8, 0x62, 0x8, 0xf7, 0xc0, 0xa2}};
332QString QWindowsFontEngineDirectWrite::filenameFromFontFile(IDWriteFontFile *fontFile)
334 IDWriteFontFileLoader *loader =
nullptr;
336 HRESULT hr = fontFile->GetLoader(&loader);
338 qErrnoWarning(
"%s: GetLoader failed",
__FUNCTION__);
342 QIdWriteLocalFontFileLoader *localLoader =
nullptr;
343 hr = loader->QueryInterface(uuidIdWriteLocalFontFileLoader(),
344 reinterpret_cast<
void **>(&localLoader));
346 const void *fontFileReferenceKey =
nullptr;
347 UINT32 fontFileReferenceKeySize = 0;
349 hr = fontFile->GetReferenceKey(&fontFileReferenceKey,
350 &fontFileReferenceKeySize);
352 qErrnoWarning(hr,
"%s: GetReferenceKey failed",
__FUNCTION__);
355 UINT32 filePathLength = 0;
357 hr = localLoader->GetFilePathLengthFromKey(fontFileReferenceKey,
358 fontFileReferenceKeySize,
361 qErrnoWarning(hr,
"GetFilePathLength failed",
__FUNCTION__);
365 if (SUCCEEDED(hr) && filePathLength > 0) {
366 QVarLengthArray<
wchar_t> filePath(filePathLength + 1);
368 hr = localLoader->GetFilePathFromKey(fontFileReferenceKey,
369 fontFileReferenceKeySize,
373 qErrnoWarning(hr,
"%s: GetFilePathFromKey failed",
__FUNCTION__);
375 ret = QString::fromWCharArray(filePath.data());
378 if (localLoader !=
nullptr)
379 localLoader->Release();
381 if (loader !=
nullptr)
386HFONT QWindowsFontEngineDirectWrite::createHFONT()
const
388 if (m_fontEngineData ==
nullptr || m_directWriteFontFace ==
nullptr)
392 HRESULT hr = m_fontEngineData->directWriteGdiInterop->ConvertFontFaceToLOGFONT(m_directWriteFontFace,
395 lf.lfHeight = -qRound(fontDef.pixelSize);
396 return CreateFontIndirect(&lf);
402void QWindowsFontEngineDirectWrite::initializeHeightMetrics()
const
404 DWRITE_FONT_METRICS metrics;
405 m_directWriteFontFace->GetMetrics(&metrics);
411 QFontEngine::initializeHeightMetrics();
414void QWindowsFontEngineDirectWrite::collectMetrics()
416 DWRITE_FONT_METRICS metrics;
418 m_directWriteFontFace->GetMetrics(&metrics);
419 m_unitsPerEm = metrics.designUnitsPerEm;
423 if (m_unitsPerEm == 0) {
424 qCWarning(lcQpaFonts) <<
"Font" << fontDef.families <<
"reports an em square size of 0."
425 <<
"Clamping to minimum value.";
434 IDWriteFontFile *fontFile =
nullptr;
435 UINT32 numberOfFiles = 1;
436 if (SUCCEEDED(m_directWriteFontFace->GetFiles(&numberOfFiles, &fontFile))) {
437 m_faceId.filename = QFile::encodeName(filenameFromFontFile(fontFile));
441 QByteArray table = getSfntTable(QFont::Tag(
"hhea").value());
442 const int advanceWidthMaxLocation = 10;
443 if (table.size() >= advanceWidthMaxLocation +
int(
sizeof(quint16))) {
444 quint16 advanceWidthMax = qFromBigEndian<quint16>(table.constBegin() + advanceWidthMaxLocation);
448 loadKerningPairs(emSquareSize() / QFixed::fromReal(fontDef.pixelSize));
450#if QT_CONFIG(directwrite3)
451 IDWriteFontFace5 *face5;
452 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace5),
453 reinterpret_cast<
void **>(&face5)))) {
455 IDWriteFontResource *fontResource;
456 if (SUCCEEDED(face5->GetFontResource(&fontResource))) {
457 const UINT32 fontAxisCount = fontResource->GetFontAxisCount();
458 if (fontAxisCount > 0) {
459 QVarLengthArray<DWRITE_FONT_AXIS_VALUE, 8> axisValues(fontAxisCount);
460 HRESULT hres = fontResource->GetDefaultFontAxisValues(axisValues.data(), fontAxisCount);
462 QVarLengthArray<DWRITE_FONT_AXIS_RANGE, 8> axisRanges(fontAxisCount);
464 hres = fontResource->GetFontAxisRanges(axisRanges.data(), fontAxisCount);
466 if (SUCCEEDED(hres)) {
467 for (UINT32 i = 0; i < fontAxisCount; ++i) {
468 const DWRITE_FONT_AXIS_VALUE &value = axisValues.at(i);
469 const DWRITE_FONT_AXIS_RANGE &range = axisRanges.at(i);
471 if (range.minValue < range.maxValue) {
472 QFontVariableAxis axis;
473 if (
auto maybeTag = QFont::Tag::fromValue(qToBigEndian<UINT32>(value.axisTag))) {
474 axis.setTag(*maybeTag);
476 qWarning() <<
"QWindowsFontEngineDirectWrite::collectMetrics: Invalid tag" << value.axisTag;
479 axis.setDefaultValue(value.value);
480 axis.setMaximumValue(range.maxValue);
481 axis.setMinimumValue(range.minValue);
483 IDWriteLocalizedStrings *names;
484 if (SUCCEEDED(fontResource->GetAxisNames(i, &names))) {
485 wchar_t defaultLocale[LOCALE_NAME_MAX_LENGTH];
486 bool hasDefaultLocale = GetUserDefaultLocaleName(defaultLocale, LOCALE_NAME_MAX_LENGTH) != 0;
488 QString name = hasDefaultLocale
489 ? QWindowsDirectWriteFontDatabase::localeString(names, defaultLocale)
491 if (name.isEmpty()) {
492 wchar_t englishLocale[] = L"en-us";
493 name = QWindowsDirectWriteFontDatabase::localeString(names, englishLocale);
500 m_variableAxes.append(axis);
505 fontResource->Release();
512QFixed QWindowsFontEngineDirectWrite::underlinePosition()
const
514 if (m_underlinePosition > 0)
515 return m_underlinePosition;
517 return QFontEngine::underlinePosition();
520QFixed QWindowsFontEngineDirectWrite::lineThickness()
const
522 if (m_lineThickness > 0)
523 return m_lineThickness;
525 return QFontEngine::lineThickness();
528bool QWindowsFontEngineDirectWrite::getSfntTableData(uint tag, uchar *buffer, uint *length)
const
532 const void *tableData = 0;
534 void *tableContext = 0;
536 HRESULT hr = m_directWriteFontFace->TryGetFontTable(qbswap<quint32>(tag),
537 &tableData, &tableSize,
538 &tableContext, &exists);
541 if (buffer && *length >= tableSize)
542 memcpy(buffer, tableData, tableSize);
546 m_directWriteFontFace->ReleaseFontTable(tableContext);
548 qErrnoWarning(
"%s: TryGetFontTable failed",
__FUNCTION__);
554QFixed QWindowsFontEngineDirectWrite::emSquareSize()
const
559glyph_t QWindowsFontEngineDirectWrite::glyphIndex(uint ucs4)
const
563 HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(&ucs4, 1, &glyphIndex);
565 qErrnoWarning(
"%s: glyphIndex failed",
__FUNCTION__);
572int QWindowsFontEngineDirectWrite::stringToCMap(
const QChar *str,
int len, QGlyphLayout *glyphs,
573 int *nglyphs, QFontEngine::ShaperFlags flags)
const
575 Q_ASSERT(glyphs->numGlyphs >= *nglyphs);
576 if (*nglyphs < len) {
581 QVarLengthArray<UINT32> codePoints(len);
582 int actualLength = 0;
583 QStringIterator it(str, str + len);
585 codePoints[actualLength++] = it.next();
587 QVarLengthArray<UINT16> glyphIndices(actualLength);
588 HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(codePoints.data(), actualLength,
589 glyphIndices.data());
591 qErrnoWarning(
"%s: GetGlyphIndicesW failed",
__FUNCTION__);
595 int mappedGlyphs = 0;
596 for (
int i = 0; i < actualLength; ++i) {
597 glyphs->glyphs[i] = glyphIndices.at(i);
598 if (glyphs->glyphs[i] != 0 || isIgnorableChar(codePoints.at(i)))
602 *nglyphs = actualLength;
603 glyphs->numGlyphs = actualLength;
605 if (!(flags & GlyphIndicesOnly))
606 recalcAdvances(glyphs, {});
611QFontEngine::FaceId QWindowsFontEngineDirectWrite::faceId()
const
616void QWindowsFontEngineDirectWrite::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags shaperFlags)
const
618 QVarLengthArray<UINT16> glyphIndices(glyphs->numGlyphs);
621 for(
int i=0; i<glyphs->numGlyphs; i++)
622 glyphIndices[i] = UINT16(glyphs->glyphs[i]);
624 QVarLengthArray<DWRITE_GLYPH_METRICS> glyphMetrics(glyphIndices.size());
627 QFont::HintingPreference hint = determineHinting(fontDef);
628 bool needsDesignMetrics = shaperFlags & QFontEngine::DesignMetrics;
629 if (!needsDesignMetrics && hint == QFont::PreferFullHinting) {
630 const DWRITE_RENDERING_MODE renderMode = hintingPreferenceToRenderingMode(fontDef);
631 const bool needsNaturalMetrics = renderMode == DWRITE_RENDERING_MODE_NATURAL
632 || renderMode == DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC;
634 hr = m_directWriteFontFace->GetGdiCompatibleGlyphMetrics(
float(fontDef.pixelSize),
640 glyphMetrics.data());
642 hr = m_directWriteFontFace->GetDesignGlyphMetrics(glyphIndices.data(),
644 glyphMetrics.data());
647 qreal stretch = fontDef.stretch != QFont::AnyStretch ? fontDef.stretch / 100.0 : 1.0;
648 for (
int i = 0; i < glyphs->numGlyphs; ++i)
651 qErrnoWarning(
"%s: GetDesignGlyphMetrics failed",
__FUNCTION__);
655QPainterPath QWindowsFontEngineDirectWrite::unscaledGlyph(glyph_t glyph)
const
657 float advance = 0.0f;
659 DWRITE_GLYPH_OFFSET offset;
660 offset.advanceOffset = 0;
661 offset.ascenderOffset = 0;
664 GeometrySink geometrySink(&ret);
665 HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline(m_unitsPerEm,
674 qErrnoWarning(
"%s: GetGlyphRunOutline failed",
__FUNCTION__);
679void QWindowsFontEngineDirectWrite::getUnscaledGlyph(glyph_t glyph,
681 glyph_metrics_t *metric)
683 *path = unscaledGlyph(glyph);
686 DWRITE_GLYPH_METRICS glyphMetrics;
687 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&g, 1, &glyphMetrics);
689 qErrnoWarning(
"%s: GetDesignGlyphMetrics failed",
__FUNCTION__);
693 QFixed advanceWidth = QFixed(
int(glyphMetrics.advanceWidth));
694 QFixed leftSideBearing = QFixed(glyphMetrics.leftSideBearing);
695 QFixed rightSideBearing = QFixed(glyphMetrics.rightSideBearing);
696 QFixed advanceHeight = QFixed(
int(glyphMetrics.advanceHeight));
697 QFixed verticalOriginY = QFixed(glyphMetrics.verticalOriginY);
698 QFixed topSideBearing = QFixed(glyphMetrics.topSideBearing);
699 QFixed bottomSideBearing = QFixed(glyphMetrics.bottomSideBearing);
700 QFixed width = advanceWidth - leftSideBearing - rightSideBearing;
701 QFixed height = advanceHeight - topSideBearing - bottomSideBearing;
702 *metric = glyph_metrics_t(leftSideBearing,
703 -verticalOriginY + topSideBearing,
710void QWindowsFontEngineDirectWrite::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions,
int nglyphs,
711 QPainterPath *path, QTextItem::RenderFlags flags)
714 QVarLengthArray<UINT16> glyphIndices(nglyphs);
715 QVarLengthArray<DWRITE_GLYPH_OFFSET> glyphOffsets(nglyphs);
716 QVarLengthArray<FLOAT> glyphAdvances(nglyphs);
718 for (
int i=0; i<nglyphs; ++i) {
719 glyphIndices[i] = glyphs[i];
720 glyphOffsets[i].advanceOffset = positions[i].x.toReal();
721 glyphOffsets[i].ascenderOffset = -positions[i].y.toReal();
722 glyphAdvances[i] = 0.0;
725 GeometrySink geometrySink(path);
726 HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline(
729 glyphAdvances.data(),
738 qErrnoWarning(
"%s: GetGlyphRunOutline failed",
__FUNCTION__);
741glyph_metrics_t QWindowsFontEngineDirectWrite::boundingBox(
const QGlyphLayout &glyphs)
743 if (glyphs.numGlyphs == 0)
744 return glyph_metrics_t();
746 for (
int i = 0; i < glyphs.numGlyphs; ++i)
747 w += glyphs.effectiveAdvance(i);
749 const QFixed leftBearing = firstLeftBearing(glyphs);
750 return glyph_metrics_t(leftBearing, -ascent(), w - leftBearing - lastRightBearing(glyphs),
751 ascent() + descent(), w, 0);
754glyph_metrics_t QWindowsFontEngineDirectWrite::boundingBox(glyph_t g)
756 UINT16 glyphIndex = g;
758 DWRITE_GLYPH_METRICS glyphMetrics;
759 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&glyphIndex, 1, &glyphMetrics);
768 QFixed width = advanceWidth - leftSideBearing - rightSideBearing;
769 QFixed height = advanceHeight - topSideBearing - bottomSideBearing;
770 return glyph_metrics_t(leftSideBearing,
771 -verticalOriginY + topSideBearing,
777 qErrnoWarning(
"%s: GetDesignGlyphMetrics failed",
__FUNCTION__);
780 return glyph_metrics_t();
783QFixed QWindowsFontEngineDirectWrite::capHeight()
const
785 if (m_capHeight <= 0)
786 return calculatedCapHeight();
791QFixed QWindowsFontEngineDirectWrite::xHeight()
const
796qreal QWindowsFontEngineDirectWrite::maxCharWidth()
const
798 return m_maxAdvanceWidth.toReal();
801QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph,
802 const QFixedPoint &subPixelPosition,
805 QImage im = imageForGlyph(glyph, subPixelPosition, glyphMargin(Format_A8), t);
808 QImage alphaMap(im.width(), im.height(), QImage::Format_Alpha8);
810 for (
int y=0; y<im.height(); ++y) {
811 const uint *src =
reinterpret_cast<
const uint *>(im.constScanLine(y));
812 uchar *dst = alphaMap.scanLine(y);
813 for (
int x=0; x<im.width(); ++x) {
822 return QFontEngine::alphaMapForGlyph(glyph, t);
826QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph,
827 const QFixedPoint &subPixelPosition)
829 return alphaMapForGlyph(glyph, subPixelPosition, QTransform());
832bool QWindowsFontEngineDirectWrite::supportsHorizontalSubPixelPositions()
const
834 QFont::HintingPreference hinting = determineHinting(fontDef);
835 return (hinting != QFont::PreferFullHinting && !(fontDef.styleStrategy & QFont::NoAntialias));
838QFontEngine::Properties QWindowsFontEngineDirectWrite::properties()
const
840 IDWriteFontFace2 *directWriteFontFace2;
841 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace2),
842 reinterpret_cast<
void **>(&directWriteFontFace2)))) {
843 DWRITE_FONT_METRICS1 metrics;
844 directWriteFontFace2->GetMetrics(&metrics);
846 Properties p = QFontEngine::properties();
847 p.emSquare = metrics.designUnitsPerEm;
848 p.boundingBox = QRectF(metrics.glyphBoxLeft,
849 -metrics.glyphBoxTop,
850 metrics.glyphBoxRight - metrics.glyphBoxLeft,
851 metrics.glyphBoxTop - metrics.glyphBoxBottom);
852 p.ascent = metrics.ascent;
853 p.descent = metrics.descent;
854 p.leading = metrics.lineGap;
855 p.capHeight = metrics.capHeight;
856 p.lineWidth = metrics.underlineThickness;
858 directWriteFontFace2->Release();
861 return QFontEngine::properties();
865bool QWindowsFontEngineDirectWrite::renderColr0GlyphRun(QImage *image,
866 const DWRITE_COLOR_GLYPH_RUN *colorGlyphRun,
867 const DWRITE_MATRIX &transform,
868 DWRITE_RENDERING_MODE renderMode,
869 DWRITE_MEASURING_MODE measureMode,
870 DWRITE_GRID_FIT_MODE gridFitMode,
872 QRect boundingRect)
const
874 ComPtr<IDWriteFactory2> factory2;
875 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
880 ComPtr<IDWriteGlyphRunAnalysis> colorGlyphsAnalysis;
881 hr = factory2->CreateGlyphRunAnalysis(
882 &colorGlyphRun->glyphRun,
887 DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
893 qErrnoWarning(hr,
"%s: CreateGlyphRunAnalysis failed for color run",
__FUNCTION__);
898 if (colorGlyphRun->paletteIndex == 0xFFFF) {
899 r =
float(color.redF());
900 g =
float(color.greenF());
901 b =
float(color.blueF());
904 r = qBound(0.0f, colorGlyphRun->runColor.r, 1.0f);
905 g = qBound(0.0f, colorGlyphRun->runColor.g, 1.0f);
906 b = qBound(0.0f, colorGlyphRun->runColor.b, 1.0f);
907 a = qBound(0.0f, colorGlyphRun->runColor.a, 1.0f);
910 if (!qFuzzyIsNull(a))
911 renderGlyphRun(image, r, g, b, a, colorGlyphsAnalysis.Get(), boundingRect, renderMode);
916#if QT_CONFIG(directwritecolrv1)
917static inline QTransform matrixToTransform(
const DWRITE_MATRIX &matrix,
920 return QTransform(matrix.m11, matrix.m12,
921 matrix.m21, matrix.m22,
922 matrix.dx * unitsPerEm, matrix.dy * unitsPerEm);
925static inline QColor colorToColor(
const DWRITE_COLOR_F &color,
float alphaMultiplier = 1.0)
927 return QColor::fromRgbF(color.r, color.g, color.b, color.a * alphaMultiplier);
930static inline QGradient::Spread extendToSpread(UINT32 extendMode)
932 switch (extendMode) {
933 case D2D1_EXTEND_MODE_WRAP:
return QGradient::RepeatSpread;
934 case D2D1_EXTEND_MODE_MIRROR:
return QGradient::ReflectSpread;
935 default:
return QGradient::PadSpread;
939static inline QPainter::CompositionMode compositeToCompositionMode(DWRITE_COLOR_COMPOSITE_MODE mode)
942 case DWRITE_COLOR_COMPOSITE_CLEAR:
943 return QPainter::CompositionMode_Clear;
945 case DWRITE_COLOR_COMPOSITE_SRC:
946 return QPainter::CompositionMode_Source;
948 case DWRITE_COLOR_COMPOSITE_DEST:
949 return QPainter::CompositionMode_Destination;
951 case DWRITE_COLOR_COMPOSITE_SRC_OVER:
952 return QPainter::CompositionMode_SourceOver;
954 case DWRITE_COLOR_COMPOSITE_DEST_OVER:
955 return QPainter::CompositionMode_DestinationOver;
957 case DWRITE_COLOR_COMPOSITE_SRC_IN:
958 return QPainter::CompositionMode_SourceIn;
960 case DWRITE_COLOR_COMPOSITE_DEST_IN:
961 return QPainter::CompositionMode_DestinationIn;
963 case DWRITE_COLOR_COMPOSITE_SRC_OUT:
964 return QPainter::CompositionMode_SourceOut;
966 case DWRITE_COLOR_COMPOSITE_DEST_OUT:
967 return QPainter::CompositionMode_DestinationOut;
969 case DWRITE_COLOR_COMPOSITE_SRC_ATOP:
970 return QPainter::CompositionMode_SourceAtop;
972 case DWRITE_COLOR_COMPOSITE_DEST_ATOP:
973 return QPainter::CompositionMode_DestinationAtop;
975 case DWRITE_COLOR_COMPOSITE_XOR:
976 return QPainter::CompositionMode_Xor;
978 case DWRITE_COLOR_COMPOSITE_PLUS:
979 return QPainter::CompositionMode_Plus;
981 case DWRITE_COLOR_COMPOSITE_SCREEN:
982 return QPainter::CompositionMode_Screen;
984 case DWRITE_COLOR_COMPOSITE_OVERLAY:
985 return QPainter::CompositionMode_Overlay;
987 case DWRITE_COLOR_COMPOSITE_DARKEN:
988 return QPainter::CompositionMode_Darken;
990 case DWRITE_COLOR_COMPOSITE_LIGHTEN:
991 return QPainter::CompositionMode_Lighten;
993 case DWRITE_COLOR_COMPOSITE_COLOR_DODGE:
994 return QPainter::CompositionMode_ColorDodge;
996 case DWRITE_COLOR_COMPOSITE_COLOR_BURN:
997 return QPainter::CompositionMode_ColorBurn;
999 case DWRITE_COLOR_COMPOSITE_HARD_LIGHT:
1000 return QPainter::CompositionMode_HardLight;
1002 case DWRITE_COLOR_COMPOSITE_SOFT_LIGHT:
1003 return QPainter::CompositionMode_SoftLight;
1005 case DWRITE_COLOR_COMPOSITE_DIFFERENCE:
1006 return QPainter::CompositionMode_Difference;
1008 case DWRITE_COLOR_COMPOSITE_EXCLUSION:
1009 return QPainter::CompositionMode_Exclusion;
1011 case DWRITE_COLOR_COMPOSITE_MULTIPLY:
1012 return QPainter::CompositionMode_Multiply;
1015 qCWarning(lcColrv1) <<
"Unhandled color composite mode:" << mode;
1016 return QPainter::CompositionMode_SourceOver;
1021QRect QWindowsFontEngineDirectWrite::paintGraphBounds(glyph_t glyph,
1022 const DWRITE_MATRIX &matrix)
const
1024#if QT_CONFIG(directwritecolrv1)
1025 ComPtr<IDWriteFontFace7> face7;
1026 HRESULT hr = m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace7),
1028 if (SUCCEEDED(hr)) {
1029 DWRITE_PAINT_FEATURE_LEVEL featureLevel = face7->GetPaintFeatureLevel(DWRITE_GLYPH_IMAGE_FORMATS_COLR_PAINT_TREE);
1030 if (featureLevel != DWRITE_PAINT_FEATURE_LEVEL_COLR_V1)
1033 ComPtr<IDWritePaintReader> paintReader;
1034 hr = face7->CreatePaintReader(DWRITE_GLYPH_IMAGE_FORMATS_COLR_PAINT_TREE,
1038 qErrnoWarning(hr,
"%s: CreatePaintReader failed",
__FUNCTION__);
1042 DWRITE_PAINT_ELEMENT paintElement;
1044 hr = paintReader->SetCurrentGlyph(glyph,
1046 sizeof(paintElement),
1051 qErrnoWarning(hr,
"%s: SetCurrentGlyph failed",
__FUNCTION__);
1055 if (paintElement.paintType == DWRITE_PAINT_TYPE_NONE)
1058 QRectF boundingRect = QRectF(QPointF(clipBox.left, clipBox.top),
1059 QPointF(clipBox.right, clipBox.bottom));
1060 if (boundingRect.isNull()) {
1061 QColrPaintGraphRenderer boundingRectCalculator;
1062 boundingRectCalculator.beginCalculateBoundingBox();
1063 if (traverseColr1(paintReader.Get(), face7.Get(), &paintElement, &boundingRectCalculator, 0))
1064 boundingRect = boundingRectCalculator.boundingRect();
1067 QTransform initialTransform;
1068 initialTransform.scale(fontDef.pixelSize, fontDef.pixelSize);
1069 boundingRect = initialTransform.mapRect(boundingRect);
1071 QTransform originalXform = matrixToTransform(matrix);
1072 boundingRect = originalXform.mapRect(boundingRect);
1074 return boundingRect.toAlignedRect();
1076 qCDebug(lcColrv1) <<
"Font face does not support IDWriteFontFace7 interface";
1086#if QT_CONFIG(directwritecolrv1)
1087bool QWindowsFontEngineDirectWrite::traverseColr1(IDWritePaintReader *paintReader,
1088 IDWriteFontFace7 *face7,
1089 const DWRITE_PAINT_ELEMENT *paintElement,
1090 QColrPaintGraphRenderer *paintGraphRenderer,
1093 if (maxColrv1NestingDepth() > 0 && depth > maxColrv1NestingDepth()) {
1094 qCWarning(lcColrv1) <<
"COLRv1 graph nested deeper than" << maxColrv1NestingDepth()
1095 <<
"levels; aborting traversal";
1099 paintGraphRenderer->save();
1100 auto cleanup = qScopeGuard([&paintGraphRenderer]() {
1101 paintGraphRenderer->restore();
1104 auto traverseChildren = [&](quint32 childCount) {
1105 DWRITE_PAINT_ELEMENT childPaintElement;
1106 if (FAILED(paintReader->MoveToFirstChild(&childPaintElement,
sizeof(DWRITE_PAINT_ELEMENT))))
1109 while (childCount-- > 0) {
1110 traverseColr1(paintReader, face7, &childPaintElement, paintGraphRenderer, depth + 1);
1111 if (childCount > 0) {
1112 if (FAILED(paintReader->MoveToNextSibling(&childPaintElement,
sizeof(DWRITE_PAINT_ELEMENT)))) {
1118 return SUCCEEDED(paintReader->MoveToParent());
1121 auto collectStops = [&paintReader](
int stopCount) {
1124 QVarLengthArray<D2D1_GRADIENT_STOP> stops(stopCount);
1125 HRESULT hr = paintReader->GetGradientStops(0, stopCount, stops.data());
1129 for (
int i = 0; i < stopCount; ++i) {
1130 const D2D1_GRADIENT_STOP &stop = stops[i];
1131 QColor color = QColor::fromRgbF(stop.color.r, stop.color.g, stop.color.b, stop.color.a);
1132 ret.append({stop.position, color});
1138 switch (paintElement->paintType) {
1139 case DWRITE_PAINT_TYPE_LAYERS:
1141 if (!traverseChildren(paintElement->paint.layers.childCount))
1147 case DWRITE_PAINT_TYPE_SOLID_GLYPH:
1149 QPainterPath glyphPath = unscaledGlyph(paintElement->paint.solidGlyph.glyphIndex);
1151 QColor color = colorToColor(paintElement->paint.solidGlyph.color.value);
1152 paintGraphRenderer->setPath(glyphPath);
1153 paintGraphRenderer->setSolidColor(color);
1154 paintGraphRenderer->drawCurrentPath();
1159 case DWRITE_PAINT_TYPE_SOLID:
1161 QColor color = colorToColor(paintElement->paint.solid.value,
1162 paintElement->paint.solid.alphaMultiplier);
1163 paintGraphRenderer->setSolidColor(color);
1164 paintGraphRenderer->drawCurrentPath();
1168 case DWRITE_PAINT_TYPE_COMPOSITE:
1170 if (!paintGraphRenderer->isRendering()) {
1171 traverseChildren(2);
1173 DWRITE_PAINT_ELEMENT childElement;
1175 HRESULT hr = paintReader->MoveToFirstChild(&childElement,
sizeof(DWRITE_PAINT_ELEMENT));
1177 qErrnoWarning(hr,
"%s: Cannot move to first child of composite node",
1183 hr = paintReader->MoveToNextSibling(&childElement,
sizeof(DWRITE_PAINT_ELEMENT));
1185 qErrnoWarning(hr,
"%s: Cannot move to second child of composite node",
1190 DWRITE_COLOR_COMPOSITE_MODE compositeMode = paintElement->paint.composite.mode;
1192 QColrPaintGraphRenderer compositeRenderer;
1193 compositeRenderer.setBoundingRect(paintGraphRenderer->boundingRect());
1194 compositeRenderer.beginRender(fontDef.pixelSize / m_unitsPerEm,
1195 paintGraphRenderer->currentTransform());
1196 if (!traverseColr1(paintReader, face7, &childElement, &compositeRenderer, depth + 1))
1200 hr = paintReader->MoveToParent();
1202 qErrnoWarning(hr,
"%s: Cannot move back to parent composite node",
1207 hr = paintReader->MoveToFirstChild(&childElement,
sizeof(DWRITE_PAINT_ELEMENT));
1209 qErrnoWarning(hr,
"%s: Cannot move to first child of composite node",
1214 compositeRenderer.setCompositionMode(compositeToCompositionMode(compositeMode));
1215 if (!traverseColr1(paintReader, face7, &childElement, &compositeRenderer, depth + 1))
1218 hr = paintReader->MoveToParent();
1220 qErrnoWarning(hr,
"%s: Cannot move back to parent composite node",
1225 paintGraphRenderer->drawImage(compositeRenderer.endRender());
1231 case DWRITE_PAINT_TYPE_RADIAL_GRADIENT:
1233 const QPointF c0(paintElement->paint.radialGradient.x0 * m_unitsPerEm,
1234 paintElement->paint.radialGradient.y0 * m_unitsPerEm);
1235 const QPointF c1(paintElement->paint.radialGradient.x1 * m_unitsPerEm,
1236 paintElement->paint.radialGradient.y1 * m_unitsPerEm);
1237 const qreal r0 = paintElement->paint.radialGradient.radius0 * m_unitsPerEm;
1238 const qreal r1 = paintElement->paint.radialGradient.radius1 * m_unitsPerEm;
1240 const QGradient::Spread spread
1241 = extendToSpread(paintElement->paint.radialGradient.extendMode);
1243 const QGradientStops gradientStops
1244 = collectStops(paintElement->paint.radialGradient.gradientStopCount);
1246 paintGraphRenderer->setRadialGradient(c0, r0, c1, r1, spread, gradientStops);
1247 paintGraphRenderer->drawCurrentPath();
1251 case DWRITE_PAINT_TYPE_SWEEP_GRADIENT:
1253 const QPointF center(paintElement->paint.sweepGradient.centerX * m_unitsPerEm,
1254 paintElement->paint.sweepGradient.centerY * m_unitsPerEm);
1255 const qreal startAngle = paintElement->paint.sweepGradient.startAngle;
1256 const qreal endAngle = paintElement->paint.sweepGradient.endAngle;
1258 const QGradient::Spread spread
1259 = extendToSpread(paintElement->paint.radialGradient.extendMode);
1260 const QGradientStops gradientStops
1261 = collectStops(paintElement->paint.radialGradient.gradientStopCount);
1263 paintGraphRenderer->setConicalGradient(center,
1268 paintGraphRenderer->drawCurrentPath();
1272 case DWRITE_PAINT_TYPE_LINEAR_GRADIENT:
1274 const QPointF p0(paintElement->paint.linearGradient.x0 * m_unitsPerEm,
1275 paintElement->paint.linearGradient.y0 * m_unitsPerEm);
1276 const QPointF p1(paintElement->paint.linearGradient.x1 * m_unitsPerEm,
1277 paintElement->paint.linearGradient.y1 * m_unitsPerEm);
1278 const QPointF p2(paintElement->paint.linearGradient.x2 * m_unitsPerEm,
1279 paintElement->paint.linearGradient.y2 * m_unitsPerEm);
1281 const QGradient::Spread spread
1282 = extendToSpread(paintElement->paint.linearGradient.extendMode);
1283 const QGradientStops gradientStops
1284 = collectStops(paintElement->paint.linearGradient.gradientStopCount);
1286 paintGraphRenderer->setLinearGradient(p0, p1, p2, spread, gradientStops);
1287 paintGraphRenderer->drawCurrentPath();
1291 case DWRITE_PAINT_TYPE_GLYPH:
1293 QPainterPath glyphPath = unscaledGlyph(paintElement->paint.glyph.glyphIndex);
1294 paintGraphRenderer->appendPath(glyphPath);
1295 if (!traverseChildren(1))
1300 case DWRITE_PAINT_TYPE_COLOR_GLYPH:
1302 D2D_RECT_F rect = paintElement->paint.colorGlyph.clipBox;
1303 QRect clipBox = QRectF(QPointF(rect.left, rect.top),
1304 QPointF(rect.right, rect.bottom)).toAlignedRect();
1305 if (!clipBox.isEmpty()) {
1306 QTransform coordinatesTransform;
1307 coordinatesTransform.scale(m_unitsPerEm, m_unitsPerEm);
1308 clipBox = coordinatesTransform.mapRect(clipBox);
1310 paintGraphRenderer->setClip(clipBox);
1313 DWRITE_PAINT_ELEMENT childElement;
1314 if (FAILED(paintReader->MoveToFirstChild(&childElement,
sizeof(DWRITE_PAINT_ELEMENT))))
1317 if (!traverseColr1(paintReader, face7, &childElement, paintGraphRenderer, depth + 1))
1320 if (FAILED(paintReader->MoveToParent()))
1326 case DWRITE_PAINT_TYPE_TRANSFORM:
1328 QTransform transform = matrixToTransform(paintElement->paint.transform, m_unitsPerEm);
1329 paintGraphRenderer->prependTransform(transform);
1330 if (!traverseChildren(1))
1337 qCDebug(lcColrv1) <<
"Unhandled paint graph node type" << paintElement->paintType;
1344bool QWindowsFontEngineDirectWrite::renderColr1GlyphRun(QImage *image,
1345 const DWRITE_GLYPH_RUN *glyphRun,
1346 const DWRITE_MATRIX &matrix,
1349 qCDebug(lcColrv1) <<
"renderColr1GlyphRun,"
1350 <<
"families:" << fontDef.families;
1351 ComPtr<IDWriteFontFace7> face7;
1352 HRESULT hr = m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace7),
1354 if (SUCCEEDED(hr)) {
1355 DWRITE_PAINT_FEATURE_LEVEL featureLevel =
1356 face7->GetPaintFeatureLevel(DWRITE_GLYPH_IMAGE_FORMATS_COLR_PAINT_TREE);
1357 if (featureLevel != DWRITE_PAINT_FEATURE_LEVEL_COLR_V1) {
1358 qCDebug(lcColrv1) <<
"Unsupported feature level:" << featureLevel;
1362 ComPtr<IDWritePaintReader> paintReader;
1363 hr = face7->CreatePaintReader(DWRITE_GLYPH_IMAGE_FORMATS_COLR_PAINT_TREE,
1367 qErrnoWarning(hr,
"%s: CreatePaintReader failed",
__FUNCTION__);
1371 Q_ASSERT(glyphRun->glyphCount == 1);
1372 DWRITE_PAINT_ELEMENT paintElement;
1374 hr = paintReader->SetCurrentGlyph(glyphRun->glyphIndices[0],
1376 sizeof(DWRITE_PAINT_ELEMENT),
1380 qErrnoWarning(hr,
"%s: SetCurrentGlyph failed",
__FUNCTION__);
1384 if (paintElement.paintType == DWRITE_PAINT_TYPE_NONE) {
1385 qCDebug(lcColrv1) <<
"Glyph" << glyphRun->glyphIndices[0]
1386 <<
"does not have a paint graph";
1390 DWRITE_COLOR_F dwColor;
1391 dwColor.r = color.redF();
1392 dwColor.g = color.greenF();
1393 dwColor.b = color.blueF();
1394 dwColor.a = color.alphaF();
1395 paintReader->SetTextColor(dwColor);
1397 QRectF boundingRect = QRectF(QPointF(clipBox.left, clipBox.top),
1398 QPointF(clipBox.right, clipBox.bottom));
1399 if (boundingRect.isNull()) {
1400 QColrPaintGraphRenderer boundingRectCalculator;
1401 boundingRectCalculator.beginCalculateBoundingBox();
1402 if (traverseColr1(paintReader.Get(), face7.Get(), &paintElement, &boundingRectCalculator, 0))
1403 boundingRect = boundingRectCalculator.boundingRect();
1406 QTransform initialTransform;
1407 initialTransform.scale(fontDef.pixelSize, fontDef.pixelSize);
1408 boundingRect = initialTransform.mapRect(boundingRect);
1410 QTransform originalXform = matrixToTransform(matrix);
1411 boundingRect = originalXform.mapRect(boundingRect);
1413 qCDebug(lcColrv1).noquote() <<
"Bounds of"
1414 << glyphRun->glyphIndices[0]
1415 <<
" in device coordinates:"
1418 QColrPaintGraphRenderer graphRenderer;
1419 graphRenderer.setBoundingRect(boundingRect);
1420 graphRenderer.beginRender(fontDef.pixelSize / m_unitsPerEm, matrixToTransform(matrix));
1421 if (!traverseColr1(paintReader.Get(), face7.Get(), &paintElement, &graphRenderer, 0))
1424 *image = graphRenderer.endRender();
1426 qCDebug(lcColrv1) <<
"Font face does not support IDWriteFontFace7 interface";
1433QImage QWindowsFontEngineDirectWrite::renderColorGlyph(DWRITE_GLYPH_RUN *glyphRun,
1434 const DWRITE_MATRIX &transform,
1435 DWRITE_RENDERING_MODE renderMode,
1436 DWRITE_MEASURING_MODE measureMode,
1437 DWRITE_GRID_FIT_MODE gridFitMode,
1439 QRect boundingRect)
const
1443#if QT_CONFIG(directwritecolrv1)
1446 renderColr1GlyphRun(&ret, glyphRun, transform, color);
1449#if QT_CONFIG(directwrite3)
1453 ComPtr<IDWriteFactory4> factory4;
1454 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory4),
1456 if (SUCCEEDED(hr)) {
1457 const DWRITE_GLYPH_IMAGE_FORMATS supportedBitmapFormats =
1458 DWRITE_GLYPH_IMAGE_FORMATS(DWRITE_GLYPH_IMAGE_FORMATS_PNG
1459 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1460 | DWRITE_GLYPH_IMAGE_FORMATS_TIFF);
1462 const DWRITE_GLYPH_IMAGE_FORMATS glyphFormats =
1463 DWRITE_GLYPH_IMAGE_FORMATS(DWRITE_GLYPH_IMAGE_FORMATS_COLR
1464 | supportedBitmapFormats
1465 | DWRITE_GLYPH_IMAGE_FORMATS_TRUETYPE
1466 | DWRITE_GLYPH_IMAGE_FORMATS_CFF);
1468 ComPtr<IDWriteColorGlyphRunEnumerator1> enumerator;
1469 hr = factory4->TranslateColorGlyphRun(D2D1::Point2F(0.0f, 0.0f),
1478 while (SUCCEEDED(hr) && ok) {
1479 hr = enumerator->MoveNext(&ok);
1483 const DWRITE_COLOR_GLYPH_RUN1 *colorGlyphRun =
nullptr;
1484 hr = enumerator->GetCurrentRun(&colorGlyphRun);
1486 qErrnoWarning(hr,
"%s: IDWriteColorGlyphRunEnumerator::GetCurrentRun failed",
__FUNCTION__);
1490 if (colorGlyphRun->glyphImageFormat == DWRITE_GLYPH_IMAGE_FORMATS_NONE) {
1494 }
else if (colorGlyphRun->glyphImageFormat == DWRITE_GLYPH_IMAGE_FORMATS_COLR) {
1496 ret = QImage(boundingRect.size(), QImage::Format_ARGB32_Premultiplied);
1500 if (renderColr0GlyphRun(&ret,
1501 reinterpret_cast<
const DWRITE_COLOR_GLYPH_RUN *>(colorGlyphRun),
1510 }
else if (colorGlyphRun->glyphImageFormat & supportedBitmapFormats) {
1511 ComPtr<IDWriteFontFace4> face4;
1512 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace4),
1514 DWRITE_GLYPH_IMAGE_DATA data;
1516 Q_ASSERT(glyphRun->glyphCount == 1);
1517 HRESULT hr = face4->GetGlyphImageData(glyphRun->glyphIndices[0],
1519 DWRITE_GLYPH_IMAGE_FORMATS(colorGlyphRun->glyphImageFormat & supportedBitmapFormats),
1523 qErrnoWarning(
"%s: GetGlyphImageData failed",
__FUNCTION__);
1527 auto fnc = qScopeGuard([&]() {
1528 if (data.imageData !=
nullptr)
1529 face4->ReleaseGlyphImageData(ctx);
1532 if (data.pixelsPerEm == 0 || data.imageData ==
nullptr || data.imageDataSize == 0) {
1533 qCWarning(lcQpaFonts) <<
__FUNCTION__
1534 <<
"Failed to retrieve image data for glyph"
1535 << glyphRun->glyphIndices[0]
1539 << colorGlyphRun->glyphImageFormat;
1542 switch (colorGlyphRun->glyphImageFormat) {
1543 case DWRITE_GLYPH_IMAGE_FORMATS_JPEG:
1546 case DWRITE_GLYPH_IMAGE_FORMATS_TIFF:
1554 ret = QImage::fromData(
reinterpret_cast<
const uchar *>(data.imageData),
1557 ret.convertTo(QImage::Format_ARGB32_Premultiplied);
1559 QTransform matrix(transform.m11, transform.m12,
1560 transform.m21, transform.m22,
1561 transform.dx, transform.dy);
1563 const qreal scale = fontDef.pixelSize / data.pixelsPerEm;
1564 matrix.scale(scale, scale);
1566 if (!matrix.isIdentity())
1567 ret = ret.transformed(matrix, Qt::SmoothTransformation);
1574 qCDebug(lcQpaFonts) <<
"Found glyph run with unsupported format"
1575 << colorGlyphRun->glyphImageFormat;
1584 ComPtr<IDWriteFactory2> factory2;
1585 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
1590 ComPtr<IDWriteColorGlyphRunEnumerator> enumerator;
1591 hr = factory2->TranslateColorGlyphRun(0.0f,
1599 if (SUCCEEDED(hr)) {
1600 ret = QImage(boundingRect.size(), QImage::Format_ARGB32_Premultiplied);
1604 while (SUCCEEDED(hr) && ok) {
1605 hr = enumerator->MoveNext(&ok);
1607 qErrnoWarning(hr,
"%s: IDWriteColorGlyphRunEnumerator::MoveNext failed",
__FUNCTION__);
1612 const DWRITE_COLOR_GLYPH_RUN *colorGlyphRun =
nullptr;
1613 hr = enumerator->GetCurrentRun(&colorGlyphRun);
1615 qErrnoWarning(hr,
"%s: IDWriteColorGlyphRunEnumerator::GetCurrentRun failed",
__FUNCTION__);
1619 if (!renderColr0GlyphRun(&ret,
1637QImage QWindowsFontEngineDirectWrite::imageForGlyph(glyph_t t,
1638 const QFixedPoint &subPixelPosition,
1640 const QTransform &originalTransform,
1641 const QColor &color)
1643 UINT16 glyphIndex = t;
1644 FLOAT glyphAdvance = 0;
1646 DWRITE_GLYPH_OFFSET glyphOffset;
1647 glyphOffset.advanceOffset = 0;
1648 glyphOffset.ascenderOffset = 0;
1650 DWRITE_GLYPH_RUN glyphRun;
1651 glyphRun.fontFace = m_directWriteFontFace;
1652 glyphRun.fontEmSize = fontDef.pixelSize;
1653 glyphRun.glyphCount = 1;
1654 glyphRun.glyphIndices = &glyphIndex;
1655 glyphRun.glyphAdvances = &glyphAdvance;
1656 glyphRun.isSideways =
false;
1657 glyphRun.bidiLevel = 0;
1658 glyphRun.glyphOffsets = &glyphOffset;
1660 QTransform xform = originalTransform;
1661 if (fontDef.stretch != 100 && fontDef.stretch != QFont::AnyStretch)
1662 xform.scale(fontDef.stretch / 100.0, 1.0);
1664 DWRITE_MATRIX transform;
1665 transform.dx = subPixelPosition.x.toReal();
1667 transform.m11 = xform.m11();
1668 transform.m12 = xform.m12();
1669 transform.m21 = xform.m21();
1670 transform.m22 = xform.m22();
1672 DWRITE_RENDERING_MODE renderMode = hintingPreferenceToRenderingMode(fontDef);
1673 DWRITE_MEASURING_MODE measureMode = renderModeToMeasureMode(renderMode);
1674 DWRITE_GRID_FIT_MODE gridFitMode = fontDef.hintingPreference == QFont::PreferNoHinting
1675 ? DWRITE_GRID_FIT_MODE_DISABLED
1676 : DWRITE_GRID_FIT_MODE_DEFAULT;
1678 ComPtr<IDWriteFactory2> factory2;
1679 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
1681 ComPtr<IDWriteGlyphRunAnalysis> glyphAnalysis;
1682 if (!SUCCEEDED(hr)) {
1683 qErrnoWarning(hr,
"%s: Failed to query IDWriteFactory2 interface.",
__FUNCTION__);
1684 hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis(
1694 hr = factory2->CreateGlyphRunAnalysis(
1700 DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
1706 if (SUCCEEDED(hr)) {
1707 QRect rect = paintGraphBounds(t, transform);
1709 rect = alphaTextureBounds(t, transform);
1711 rect = colorBitmapBounds(t, transform);
1713 if (rect.isEmpty()) {
1714 qCDebug(lcQpaFonts) <<
__FUNCTION__ <<
"Cannot get alpha texture bounds. Falling back to slower rendering path.";
1718 if (glyphBoundingBoxExceedsLimit(rect.width(),
1720 effectivePixelSizeSquared(xform))) {
1724 QRect boundingRect = rect.adjusted(-margin, -margin, margin, margin);
1727 if (glyphFormat == QFontEngine::Format_ARGB) {
1728 image = renderColorGlyph(&glyphRun,
1738 if (image.isNull()) {
1739 image = QImage(boundingRect.size(),
1740 glyphFormat == QFontEngine::Format_ARGB
1741 ? QImage::Format_ARGB32_Premultiplied
1742 : QImage::Format_RGB32);
1743 image.fill(image.format() == QImage::Format_ARGB32_Premultiplied ? 0x0 : 0xffffffff);
1746 if (glyphFormat == QFontEngine::Format_ARGB) {
1747 r =
float(color.redF());
1748 g =
float(color.greenF());
1749 b =
float(color.blueF());
1750 a =
float(color.alphaF());
1752 r = g = b = a = 0.0;
1755 renderGlyphRun(&image,
1760 glyphAnalysis.Get(),
1767 qErrnoWarning(hr,
"%s: CreateGlyphRunAnalysis failed",
__FUNCTION__);
1772void QWindowsFontEngineDirectWrite::renderGlyphRun(QImage *destination,
1777 IDWriteGlyphRunAnalysis *glyphAnalysis,
1778 const QRect &boundingRect,
1779 DWRITE_RENDERING_MODE renderMode)
const
1781 const int width = destination->width();
1782 const int height = destination->height();
1788 const int size = width * height * 3;
1791 rect.left = boundingRect.left();
1792 rect.top = boundingRect.top();
1793 rect.right = boundingRect.left() + boundingRect.width();
1794 rect.bottom = boundingRect.top() + boundingRect.height();
1796 QVarLengthArray<BYTE, 1024> alphaValueArray(size);
1797 BYTE *alphaValues = alphaValueArray.data();
1798 memset(alphaValues, 0, size);
1800 HRESULT hr = glyphAnalysis->CreateAlphaTexture(renderMode == DWRITE_RENDERING_MODE_ALIASED
1801 ? DWRITE_TEXTURE_ALIASED_1x1
1802 : DWRITE_TEXTURE_CLEARTYPE_3x1,
1806 if (SUCCEEDED(hr)) {
1807 if (destination->hasAlphaChannel()) {
1808 for (
int y = 0; y < height; ++y) {
1809 uint *dest =
reinterpret_cast<uint *>(destination->scanLine(y));
1810 BYTE *src = alphaValues + width * 3 * y;
1812 for (
int x = 0; x < width; ++x) {
1813 float redAlpha = a * *src++ / 255.0;
1814 float greenAlpha = a * *src++ / 255.0;
1815 float blueAlpha = a * *src++ / 255.0;
1816 float averageAlpha = (redAlpha + greenAlpha + blueAlpha) / 3.0;
1818 if (m_pixelGeometry == DWRITE_PIXEL_GEOMETRY_BGR)
1819 qSwap(redAlpha, blueAlpha);
1821 QRgb currentRgb = dest[x];
1822 dest[x] = qRgba(qRound(qRed(currentRgb) * (1.0 - averageAlpha) + averageAlpha * r),
1823 qRound(qGreen(currentRgb) * (1.0 - averageAlpha) + averageAlpha * g),
1824 qRound(qBlue(currentRgb) * (1.0 - averageAlpha) + averageAlpha * b),
1825 qRound(qAlpha(currentRgb) * (1.0 - averageAlpha) + averageAlpha * 255));
1828 }
else if (renderMode == DWRITE_RENDERING_MODE_ALIASED) {
1829 for (
int y = 0; y < height; ++y) {
1830 uint *dest =
reinterpret_cast<uint *>(destination->scanLine(y));
1831 BYTE *src = alphaValues + width * y;
1833 for (
int x = 0; x < width; ++x) {
1834 int alpha = *(src++);
1835 dest[x] = (alpha << 16) + (alpha << 8) + alpha;
1839 for (
int y = 0; y < height; ++y) {
1840 uint *dest =
reinterpret_cast<uint *>(destination->scanLine(y));
1841 BYTE *src = alphaValues + width * 3 * y;
1843 for (
int x = 0; x < width; ++x) {
1844 BYTE redAlpha = *(src + 0);
1845 BYTE greenAlpha = *(src + 1);
1846 BYTE blueAlpha = *(src + 2);
1848 if (m_pixelGeometry == DWRITE_PIXEL_GEOMETRY_BGR)
1849 qSwap(redAlpha, blueAlpha);
1851 dest[x] = qRgb(redAlpha, greenAlpha, blueAlpha);
1857 qErrnoWarning(
"%s: CreateAlphaTexture failed",
__FUNCTION__);
1862QImage QWindowsFontEngineDirectWrite::alphaRGBMapForGlyph(glyph_t t,
1863 const QFixedPoint &subPixelPosition,
1864 const QTransform &xform)
1866 QImage mask = imageForGlyph(t,
1868 glyphMargin(QFontEngine::Format_A32),
1871 if (mask.isNull()) {
1872 if (xform.type() > QTransform::TxTranslate && glyphTransformExceedsLimit(t, xform))
1875 mask = QFontEngine::renderedPathForGlyph(t, Qt::white);
1876 if (!xform.isIdentity())
1877 mask = mask.transformed(xform);
1880 return mask.depth() == 32
1882 : mask.convertToFormat(QImage::Format_RGB32);
1885QFontEngine *QWindowsFontEngineDirectWrite::cloneWithSize(qreal pixelSize)
const
1887 QWindowsFontEngineDirectWrite *fontEngine =
new QWindowsFontEngineDirectWrite(m_directWriteFontFace,
1891 fontEngine->fontDef = fontDef;
1892 fontEngine->fontDef.pixelSize = pixelSize;
1893 if (!m_uniqueFamilyName.isEmpty()) {
1894 fontEngine->setUniqueFamilyName(m_uniqueFamilyName);
1895 QPlatformFontDatabase *pfdb = QGuiApplicationPrivate::platformIntegration()->fontDatabase();
1896 static_cast<QWindowsFontDatabase *>(pfdb)->refUniqueFont(m_uniqueFamilyName);
1902Qt::HANDLE QWindowsFontEngineDirectWrite::handle()
const
1904 return m_directWriteFontFace;
1907void QWindowsFontEngineDirectWrite::initFontInfo(
const QFontDef &request,
1912 if (fontDef.pointSize < 0)
1913 fontDef.pointSize = fontDef.pixelSize * 72. / dpi;
1914 else if (fontDef.pixelSize == -1)
1915 fontDef.pixelSize = qRound(fontDef.pointSize * dpi / 72.);
1917 m_faceId.variableAxes = request.variableAxisValues;
1919#if QT_CONFIG(directwrite3)
1920 IDWriteFontFace3 *face3 =
nullptr;
1921 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace3),
1922 reinterpret_cast<
void **>(&face3)))) {
1924 fontDef.weight = QWindowsDirectWriteFontDatabase::fromDirectWriteWeight(face3->GetWeight());
1925 fontDef.style = QWindowsDirectWriteFontDatabase::fromDirectWriteStyle(face3->GetStyle());
1927 IDWriteLocalizedStrings *names;
1928 if (SUCCEEDED(face3->GetFaceNames(&names))) {
1929 wchar_t englishLocale[] = L"en-us";
1930 fontDef.styleName = QWindowsDirectWriteFontDatabase::localeString(names, englishLocale);
1935 if (face3->IsColorFont())
1936 glyphFormat = QFontEngine::Format_ARGB;
1943QString QWindowsFontEngineDirectWrite::fontNameSubstitute(
const QString &familyName)
1945 const QString substitute =
1946 QWinRegistryKey(HKEY_LOCAL_MACHINE,
1947 LR"(Software\Microsoft\Windows NT\CurrentVersion\FontSubstitutes)")
1948 .stringValue(familyName);
1949 return substitute.isEmpty() ? familyName : substitute;
1952QRect QWindowsFontEngineDirectWrite::alphaTextureBounds(glyph_t glyph,
1953 const DWRITE_MATRIX &transform)
1955 UINT16 glyphIndex = glyph;
1956 FLOAT glyphAdvance = 0;
1958 DWRITE_GLYPH_OFFSET glyphOffset;
1959 glyphOffset.advanceOffset = 0;
1960 glyphOffset.ascenderOffset = 0;
1962 DWRITE_GLYPH_RUN glyphRun;
1963 glyphRun.fontFace = m_directWriteFontFace;
1964 glyphRun.fontEmSize = fontDef.pixelSize;
1965 glyphRun.glyphCount = 1;
1966 glyphRun.glyphIndices = &glyphIndex;
1967 glyphRun.glyphAdvances = &glyphAdvance;
1968 glyphRun.isSideways =
false;
1969 glyphRun.bidiLevel = 0;
1970 glyphRun.glyphOffsets = &glyphOffset;
1972 DWRITE_RENDERING_MODE renderMode = hintingPreferenceToRenderingMode(fontDef);
1973 DWRITE_MEASURING_MODE measureMode = renderModeToMeasureMode(renderMode);
1974 DWRITE_GRID_FIT_MODE gridFitMode = fontDef.hintingPreference == QFont::PreferNoHinting
1975 ? DWRITE_GRID_FIT_MODE_DISABLED
1976 : DWRITE_GRID_FIT_MODE_DEFAULT;
1978 ComPtr<IDWriteFactory2> factory2 =
nullptr;
1979 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
1982 ComPtr<IDWriteGlyphRunAnalysis> glyphAnalysis;
1983 if (SUCCEEDED(hr)) {
1984 hr = factory2->CreateGlyphRunAnalysis(
1990 DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
1995 hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis(
2006 if (SUCCEEDED(hr)) {
2008 hr = glyphAnalysis->GetAlphaTextureBounds(renderMode == DWRITE_RENDERING_MODE_ALIASED
2009 ? DWRITE_TEXTURE_ALIASED_1x1
2010 : DWRITE_TEXTURE_CLEARTYPE_3x1,
2012 if (FAILED(hr) || rect.left == rect.right || rect.top == rect.bottom)
2015 return QRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
2021QRect QWindowsFontEngineDirectWrite::colorBitmapBounds(glyph_t glyph,
const DWRITE_MATRIX &transform)
2023#if QT_CONFIG(directwrite3)
2024 ComPtr<IDWriteFontFace4> face4;
2025 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace4),
2027 DWRITE_GLYPH_IMAGE_FORMATS formats = face4->GetGlyphImageFormats();
2029 const DWRITE_GLYPH_IMAGE_FORMATS supportedBitmapFormats =
2030 DWRITE_GLYPH_IMAGE_FORMATS(DWRITE_GLYPH_IMAGE_FORMATS_PNG
2031 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
2032 | DWRITE_GLYPH_IMAGE_FORMATS_TIFF);
2034 if (formats & supportedBitmapFormats) {
2035 DWRITE_GLYPH_IMAGE_DATA data;
2037 HRESULT hr = face4->GetGlyphImageData(glyph,
2039 DWRITE_GLYPH_IMAGE_FORMATS(formats & supportedBitmapFormats),
2043 qErrnoWarning(
"%s: GetGlyphImageData failed",
__FUNCTION__);
2047 auto fnc = qScopeGuard([&]() {
2048 if (data.imageData !=
nullptr)
2049 face4->ReleaseGlyphImageData(ctx);
2052 if (data.pixelsPerEm == 0 || data.imageData ==
nullptr || data.imageDataSize == 0)
2055 QRect rect(-data.horizontalLeftOrigin.x,
2056 -data.horizontalLeftOrigin.y,
2057 data.pixelSize.width,
2058 data.pixelSize.height);
2060 QTransform matrix(transform.m11, transform.m12,
2061 transform.m21, transform.m22,
2062 transform.dx, transform.dy);
2065 const qreal scale = fontDef.pixelSize / data.pixelsPerEm;
2066 matrix.scale(scale, scale);
2067 rect = matrix.mapRect(rect);
2076 Q_UNUSED(transform);
2081glyph_metrics_t QWindowsFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph,
2082 const QFixedPoint &subPixelPosition,
2083 const QTransform &originalTransform,
2086 QTransform matrix = originalTransform;
2087 if (fontDef.stretch != 100 && fontDef.stretch != QFont::AnyStretch)
2088 matrix.scale(fontDef.stretch / 100.0, 1.0);
2090 glyph_metrics_t bbox = QFontEngine::boundingBox(glyph, matrix);
2092 DWRITE_MATRIX transform;
2093 transform.dx = subPixelPosition.x.toReal();
2095 transform.m11 = matrix.m11();
2096 transform.m12 = matrix.m12();
2097 transform.m21 = matrix.m21();
2098 transform.m22 = matrix.m22();
2101 QRect rect = paintGraphBounds(glyph, transform);
2105 rect = alphaTextureBounds(glyph, transform);
2109 rect = colorBitmapBounds(glyph, transform);
2115 int margin = glyphMargin(format);
2116 return glyph_metrics_t(rect.left(),
2118 rect.width() + margin * 2,
2119 rect.height() + margin * 2,
2120 bbox.xoff, bbox.yoff);
2123QImage QWindowsFontEngineDirectWrite::bitmapForGlyph(glyph_t glyph,
2124 const QFixedPoint &subPixelPosition,
2125 const QTransform &t,
2126 const QColor &color)
2128 return imageForGlyph(glyph, subPixelPosition, glyphMargin(QFontEngine::Format_ARGB), t, color);
2131QList<QFontVariableAxis> QWindowsFontEngineDirectWrite::variableAxes()
const
2133 return m_variableAxes;
2136bool QWindowsFontEngineDirectWrite::expectsGammaCorrectedBlending(QFontEngine::GlyphFormat format)
const
2138 return format == QFontEngine::Format_A32;
Combined button and popup list for selecting options.
static UUID uuidIdWriteLocalFontFileLoader()
IDWriteLocalFontFileLoader QIdWriteLocalFontFileLoader
static QFont::HintingPreference determineHinting(const QFontDef &fontDef)
#define DESIGN_TO_LOGICAL(DESIGN_UNIT_VALUE)
static DWRITE_MEASURING_MODE renderModeToMeasureMode(DWRITE_RENDERING_MODE renderMode)