Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwindowsfontenginedirectwrite.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
7
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>
18
19#include <private/qcolrpaintgraphrenderer_p.h>
20
21#if QT_CONFIG(directwrite3)
22# include "qwindowsdirectwritefontdatabase_p.h"
23# include <dwrite_3.h>
24#endif
25
26#include <d2d1.h>
27
29
30// Clang does not consider __declspec(nothrow) as nothrow
31QT_WARNING_DISABLE_CLANG("-Wmicrosoft-exception-spec")
32
33// Convert from design units to logical pixels
34#define DESIGN_TO_LOGICAL(DESIGN_UNIT_VALUE)
35 QFixed::fromReal((qreal(DESIGN_UNIT_VALUE) / qreal(m_unitsPerEm)) * fontDef.pixelSize)
36
37namespace {
38
39 class GeometrySink: public IDWriteGeometrySink
40 {
41 Q_DISABLE_COPY_MOVE(GeometrySink)
42 public:
43 GeometrySink(QPainterPath *path)
44 : m_refCount(0), m_path(path)
45 {
46 Q_ASSERT(m_path != 0);
47 }
48 virtual ~GeometrySink() = default;
49
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;
57
58 IFACEMETHOD_(unsigned long, AddRef)() override;
59 IFACEMETHOD_(unsigned long, Release)() override;
60 IFACEMETHOD(QueryInterface)(IID const &riid, void **ppvObject) override;
61
62 private:
63 inline static QPointF fromD2D1_POINT_2F(const D2D1_POINT_2F &inp)
64 {
65 return QPointF(inp.x, inp.y);
66 }
67
68 unsigned long m_refCount;
69 QPointF m_startPoint;
70 QPainterPath *m_path;
71 };
72
73 void GeometrySink::AddBeziers(const D2D1_BEZIER_SEGMENT *beziers,
74 UINT bezierCount) noexcept
75 {
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);
80
81 m_path->cubicTo(c1, c2, p2);
82 }
83 }
84
85 void GeometrySink::AddLines(const D2D1_POINT_2F *points, UINT pointsCount) noexcept
86 {
87 for (uint i=0; i<pointsCount; ++i)
88 m_path->lineTo(fromD2D1_POINT_2F(points[i]));
89 }
90
91 void GeometrySink::BeginFigure(D2D1_POINT_2F startPoint,
92 D2D1_FIGURE_BEGIN /*figureBegin*/) noexcept
93 {
94 m_startPoint = fromD2D1_POINT_2F(startPoint);
95 m_path->moveTo(m_startPoint);
96 }
97
98 IFACEMETHODIMP GeometrySink::Close() noexcept
99 {
100 return E_NOTIMPL;
101 }
102
103 void GeometrySink::EndFigure(D2D1_FIGURE_END figureEnd) noexcept
104 {
105 if (figureEnd == D2D1_FIGURE_END_CLOSED)
106 m_path->closeSubpath();
107 }
108
109 void GeometrySink::SetFillMode(D2D1_FILL_MODE fillMode) noexcept
110 {
111 m_path->setFillRule(fillMode == D2D1_FILL_MODE_ALTERNATE
112 ? Qt::OddEvenFill
113 : Qt::WindingFill);
114 }
115
116 void GeometrySink::SetSegmentFlags(D2D1_PATH_SEGMENT /*vertexFlags*/) noexcept
117 {
118 /* Not implemented */
119 }
120
121 IFACEMETHODIMP_(unsigned long) GeometrySink::AddRef() noexcept
122 {
123 return InterlockedIncrement(&m_refCount);
124 }
125
126 IFACEMETHODIMP_(unsigned long) GeometrySink::Release() noexcept
127 {
128 unsigned long newCount = InterlockedDecrement(&m_refCount);
129 if (newCount == 0)
130 {
131 delete this;
132 return 0;
133 }
134
135 return newCount;
136 }
137
138 IFACEMETHODIMP GeometrySink::QueryInterface(IID const &riid, void **ppvObject) noexcept
139 {
140 if (__uuidof(IDWriteGeometrySink) == riid) {
141 *ppvObject = this;
142 } else if (__uuidof(IUnknown) == riid) {
143 *ppvObject = this;
144 } else {
145 *ppvObject = NULL;
146 return E_FAIL;
147 }
148
149 AddRef();
150 return S_OK;
151 }
152
153}
154
155static DWRITE_MEASURING_MODE renderModeToMeasureMode(DWRITE_RENDERING_MODE renderMode)
156{
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;
162 default:
163 return DWRITE_MEASURING_MODE_NATURAL;
164 }
165}
166
167static QFont::HintingPreference determineHinting(const QFontDef &fontDef)
168{
169 QFont::HintingPreference hintingPreference = QFont::HintingPreference(fontDef.hintingPreference);
170 if (hintingPreference == QFont::PreferDefaultHinting) {
171 if (!qFuzzyCompare(qApp->devicePixelRatio(), 1.0))
172 hintingPreference = QFont::PreferVerticalHinting;
173 else
174 hintingPreference = QFont::PreferFullHinting;
175 }
176
177 return hintingPreference;
178}
179
180bool QWindowsFontEngineDirectWrite::useSymmetricAntialiasing() const
181{
182 if (m_useSymmetricAntialiasing < 0) {
183 qCDebug(lcQpaFonts) << "Checking antialiasing strategy for:"
184 << fontDef.families;
185
186 // We default to symmetric antialiasing for fonts without hinting and for pixel sizes
187 // over 16 as recommended by Microsoft documentation. We use the maximum DPR for this,
188 // which means text on multi-screen setups may get symmetric rendering when it strictly
189 // speaking should not, but this looks better than using asymmetric rendering on scaled
190 // fonts.
191 const qreal effectivePixelSize = fontDef.pixelSize * qApp->devicePixelRatio();
192 m_useSymmetricAntialiasing = effectivePixelSize > 16.0 || !hasHinting();
193
194 qCDebug(lcQpaFonts) << " After checking pixel size and hinting, defaulting to:"
195 << bool(m_useSymmetricAntialiasing);
196
197 // Then we check if there is a GASP table and consult this if it is available
198 const QByteArray gasp = getSfntTable(QFont::Tag("gasp").value());
199 if (gasp.size() > 4) {
200 qCDebug(lcQpaFonts) << " Checking GASP table, size=" << gasp.size();
201
202 const uchar *start = reinterpret_cast<const uchar *>(gasp.constBegin());
203
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;
210
211 if (rangeMaxPPEM >= effectivePixelSize) {
212 const quint16 rangeGaspBehavior = qFromBigEndian<quint16>(start + 4 + i * 4 + 2);
213 qCDebug(lcQpaFonts) << " GASP behavior " << i << "==" << rangeGaspBehavior;
214
215 // GASP_SYMMETRIC_SMOOTHING = 0x8
216 m_useSymmetricAntialiasing = !!(rangeGaspBehavior & 0x8);
217 qCDebug(lcQpaFonts) << " Symmetric antialiasing override: "
218 << bool(m_useSymmetricAntialiasing);
219
220 break;
221 }
222 }
223 }
224 }
225 }
226
227 return m_useSymmetricAntialiasing;
228}
229
230DWRITE_RENDERING_MODE QWindowsFontEngineDirectWrite::hintingPreferenceToRenderingMode(const QFontDef &fontDef) const
231{
232 if ((fontDef.styleStrategy & QFont::NoAntialias) && glyphFormat != QFontEngine::Format_ARGB)
233 return DWRITE_RENDERING_MODE_ALIASED;
234
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;
242 else
243 return DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL;
244 default:
245 if (useSymmetricAntialiasing())
246 return DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC;
247 else
248 return DWRITE_RENDERING_MODE_GDI_CLASSIC;
249 }
250}
251
252/*!
253 \class QWindowsFontEngineDirectWrite
254 \brief Windows font engine using Direct Write.
255 \internal
256
257 Font engine for subpixel positioned text on Windows Vista
258 (with platform update) and later. If selected during
259 configuration, the engine will be selected only when the hinting
260 preference of a font is set to None or Vertical hinting, or
261 when fontengine=directwrite is selected as platform option.
262*/
263
264QWindowsFontEngineDirectWrite::QWindowsFontEngineDirectWrite(IDWriteFontFace *directWriteFontFace,
265 qreal pixelSize,
266 const QSharedPointer<QWindowsFontEngineData> &d)
267 : QFontEngine(DirectWrite)
268 , m_fontEngineData(d)
269 , m_directWriteFontFace(directWriteFontFace)
270 , m_directWriteBitmapRenderTarget(0)
271 , m_lineThickness(-1)
272 , m_unitsPerEm(-1)
273 , m_capHeight(-1)
274 , m_xHeight(-1)
275{
276 qCDebug(lcQpaFonts) << __FUNCTION__ << pixelSize;
277
278 Q_ASSERT(m_directWriteFontFace);
279
280 m_fontEngineData->directWriteFactory->AddRef();
281 m_directWriteFontFace->AddRef();
282
283 IDWriteRenderingParams *renderingParams = nullptr;
284 if (SUCCEEDED(m_fontEngineData->directWriteFactory->CreateRenderingParams(&renderingParams))) {
285 m_pixelGeometry = renderingParams->GetPixelGeometry();
286 renderingParams->Release();
287 }
288
289 fontDef.pixelSize = pixelSize;
290 collectMetrics();
291 cache_cost = m_xHeight.toInt() * m_xHeight.toInt() * 2000;
292}
293
294QWindowsFontEngineDirectWrite::~QWindowsFontEngineDirectWrite()
295{
296 qCDebug(lcQpaFonts) << __FUNCTION__;
297
298 m_fontEngineData->directWriteFactory->Release();
299 m_directWriteFontFace->Release();
300
301 if (m_directWriteBitmapRenderTarget != 0)
302 m_directWriteBitmapRenderTarget->Release();
303
304 if (!m_uniqueFamilyName.isEmpty()) {
305 QPlatformFontDatabase *pfdb = QGuiApplicationPrivate::platformIntegration()->fontDatabase();
306 static_cast<QWindowsFontDatabase *>(pfdb)->derefUniqueFont(m_uniqueFamilyName);
307 }
308}
309
310#ifndef Q_CC_MINGW
312
314{
315 return __uuidof(IDWriteLocalFontFileLoader);
316}
317#else // !Q_CC_MINGW
318DECLARE_INTERFACE_(QIdWriteLocalFontFileLoader, IDWriteFontFileLoader)
319{
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;
323};
324
325static UUID uuidIdWriteLocalFontFileLoader()
326{
327 static const UUID result = { 0xb2d9f3ec, 0xc9fe, 0x4a11, {0xa2, 0xec, 0xd8, 0x62, 0x8, 0xf7, 0xc0, 0xa2}};
328 return result;
329}
330#endif // Q_CC_MINGW
331
332QString QWindowsFontEngineDirectWrite::filenameFromFontFile(IDWriteFontFile *fontFile)
333{
334 IDWriteFontFileLoader *loader = nullptr;
335
336 HRESULT hr = fontFile->GetLoader(&loader);
337 if (FAILED(hr)) {
338 qErrnoWarning("%s: GetLoader failed", __FUNCTION__);
339 return QString();
340 }
341
342 QIdWriteLocalFontFileLoader *localLoader = nullptr;
343 hr = loader->QueryInterface(uuidIdWriteLocalFontFileLoader(),
344 reinterpret_cast<void **>(&localLoader));
345
346 const void *fontFileReferenceKey = nullptr;
347 UINT32 fontFileReferenceKeySize = 0;
348 if (SUCCEEDED(hr)) {
349 hr = fontFile->GetReferenceKey(&fontFileReferenceKey,
350 &fontFileReferenceKeySize);
351 if (FAILED(hr))
352 qErrnoWarning(hr, "%s: GetReferenceKey failed", __FUNCTION__);
353 }
354
355 UINT32 filePathLength = 0;
356 if (SUCCEEDED(hr)) {
357 hr = localLoader->GetFilePathLengthFromKey(fontFileReferenceKey,
358 fontFileReferenceKeySize,
359 &filePathLength);
360 if (FAILED(hr))
361 qErrnoWarning(hr, "GetFilePathLength failed", __FUNCTION__);
362 }
363
364 QString ret;
365 if (SUCCEEDED(hr) && filePathLength > 0) {
366 QVarLengthArray<wchar_t> filePath(filePathLength + 1);
367
368 hr = localLoader->GetFilePathFromKey(fontFileReferenceKey,
369 fontFileReferenceKeySize,
370 filePath.data(),
371 filePathLength + 1);
372 if (FAILED(hr))
373 qErrnoWarning(hr, "%s: GetFilePathFromKey failed", __FUNCTION__);
374 else
375 ret = QString::fromWCharArray(filePath.data());
376 }
377
378 if (localLoader != nullptr)
379 localLoader->Release();
380
381 if (loader != nullptr)
382 loader->Release();
383 return ret;
384}
385
386HFONT QWindowsFontEngineDirectWrite::createHFONT() const
387{
388 if (m_fontEngineData == nullptr || m_directWriteFontFace == nullptr)
389 return NULL;
390
391 LOGFONT lf;
392 HRESULT hr = m_fontEngineData->directWriteGdiInterop->ConvertFontFaceToLOGFONT(m_directWriteFontFace,
393 &lf);
394 if (SUCCEEDED(hr)) {
395 lf.lfHeight = -qRound(fontDef.pixelSize);
396 return CreateFontIndirect(&lf);
397 } else {
398 return NULL;
399 }
400}
401
402void QWindowsFontEngineDirectWrite::initializeHeightMetrics() const
403{
404 DWRITE_FONT_METRICS metrics;
405 m_directWriteFontFace->GetMetrics(&metrics);
406
407 m_ascent = DESIGN_TO_LOGICAL(metrics.ascent);
408 m_descent = DESIGN_TO_LOGICAL(metrics.descent);
409 m_leading = DESIGN_TO_LOGICAL(metrics.lineGap);
410
411 QFontEngine::initializeHeightMetrics();
412}
413
414void QWindowsFontEngineDirectWrite::collectMetrics()
415{
416 DWRITE_FONT_METRICS metrics;
417
418 m_directWriteFontFace->GetMetrics(&metrics);
419 m_unitsPerEm = metrics.designUnitsPerEm;
420
421 // Something is wrong with this font. Set the em square size to the minimum value in
422 // the spec.
423 if (m_unitsPerEm == 0) {
424 qCWarning(lcQpaFonts) << "Font" << fontDef.families << "reports an em square size of 0."
425 << "Clamping to minimum value.";
426 m_unitsPerEm = 16;
427 }
428
429 m_lineThickness = DESIGN_TO_LOGICAL(metrics.underlineThickness);
430 m_capHeight = DESIGN_TO_LOGICAL(metrics.capHeight);
431 m_xHeight = DESIGN_TO_LOGICAL(metrics.xHeight);
432 m_underlinePosition = DESIGN_TO_LOGICAL(metrics.underlinePosition);
433
434 IDWriteFontFile *fontFile = nullptr;
435 UINT32 numberOfFiles = 1;
436 if (SUCCEEDED(m_directWriteFontFace->GetFiles(&numberOfFiles, &fontFile))) {
437 m_faceId.filename = QFile::encodeName(filenameFromFontFile(fontFile));
438 fontFile->Release();
439 }
440
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);
445 m_maxAdvanceWidth = DESIGN_TO_LOGICAL(advanceWidthMax);
446 }
447
448 loadKerningPairs(emSquareSize() / QFixed::fromReal(fontDef.pixelSize));
449
450#if QT_CONFIG(directwrite3)
451 IDWriteFontFace5 *face5;
452 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace5),
453 reinterpret_cast<void **>(&face5)))) {
454
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);
461
462 QVarLengthArray<DWRITE_FONT_AXIS_RANGE, 8> axisRanges(fontAxisCount);
463 if (SUCCEEDED(hres))
464 hres = fontResource->GetFontAxisRanges(axisRanges.data(), fontAxisCount);
465
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);
470
471 if (range.minValue < range.maxValue) {
472 QFontVariableAxis axis;
473 if (auto maybeTag = QFont::Tag::fromValue(qToBigEndian<UINT32>(value.axisTag))) {
474 axis.setTag(*maybeTag);
475 } else {
476 qWarning() << "QWindowsFontEngineDirectWrite::collectMetrics: Invalid tag" << value.axisTag;
477 }
478
479 axis.setDefaultValue(value.value);
480 axis.setMaximumValue(range.maxValue);
481 axis.setMinimumValue(range.minValue);
482
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;
487
488 QString name = hasDefaultLocale
489 ? QWindowsDirectWriteFontDatabase::localeString(names, defaultLocale)
490 : QString();
491 if (name.isEmpty()) {
492 wchar_t englishLocale[] = L"en-us";
493 name = QWindowsDirectWriteFontDatabase::localeString(names, englishLocale);
494 }
495
496 axis.setName(name);
497 names->Release();
498 }
499
500 m_variableAxes.append(axis);
501 }
502 }
503 }
504 }
505 fontResource->Release();
506 }
507 face5->Release();
508 }
509#endif
510}
511
512QFixed QWindowsFontEngineDirectWrite::underlinePosition() const
513{
514 if (m_underlinePosition > 0)
515 return m_underlinePosition;
516 else
517 return QFontEngine::underlinePosition();
518}
519
520QFixed QWindowsFontEngineDirectWrite::lineThickness() const
521{
522 if (m_lineThickness > 0)
523 return m_lineThickness;
524 else
525 return QFontEngine::lineThickness();
526}
527
528bool QWindowsFontEngineDirectWrite::getSfntTableData(uint tag, uchar *buffer, uint *length) const
529{
530 bool ret = false;
531
532 const void *tableData = 0;
533 UINT32 tableSize;
534 void *tableContext = 0;
535 BOOL exists;
536 HRESULT hr = m_directWriteFontFace->TryGetFontTable(qbswap<quint32>(tag),
537 &tableData, &tableSize,
538 &tableContext, &exists);
539 if (SUCCEEDED(hr)) {
540 if (exists) {
541 if (buffer && *length >= tableSize)
542 memcpy(buffer, tableData, tableSize);
543 *length = tableSize;
544 ret = (*length) > 0;
545 }
546 m_directWriteFontFace->ReleaseFontTable(tableContext);
547 } else {
548 qErrnoWarning("%s: TryGetFontTable failed", __FUNCTION__);
549 }
550
551 return ret;
552}
553
554QFixed QWindowsFontEngineDirectWrite::emSquareSize() const
555{
556 return m_unitsPerEm;
557}
558
559glyph_t QWindowsFontEngineDirectWrite::glyphIndex(uint ucs4) const
560{
561 UINT16 glyphIndex;
562
563 HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(&ucs4, 1, &glyphIndex);
564 if (FAILED(hr)) {
565 qErrnoWarning("%s: glyphIndex failed", __FUNCTION__);
566 glyphIndex = 0;
567 }
568
569 return glyphIndex;
570}
571
572int QWindowsFontEngineDirectWrite::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
573 int *nglyphs, QFontEngine::ShaperFlags flags) const
574{
575 Q_ASSERT(glyphs->numGlyphs >= *nglyphs);
576 if (*nglyphs < len) {
577 *nglyphs = len;
578 return -1;
579 }
580
581 QVarLengthArray<UINT32> codePoints(len);
582 int actualLength = 0;
583 QStringIterator it(str, str + len);
584 while (it.hasNext())
585 codePoints[actualLength++] = it.next();
586
587 QVarLengthArray<UINT16> glyphIndices(actualLength);
588 HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(codePoints.data(), actualLength,
589 glyphIndices.data());
590 if (FAILED(hr)) {
591 qErrnoWarning("%s: GetGlyphIndicesW failed", __FUNCTION__);
592 return -1;
593 }
594
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)))
599 mappedGlyphs++;
600 }
601
602 *nglyphs = actualLength;
603 glyphs->numGlyphs = actualLength;
604
605 if (!(flags & GlyphIndicesOnly))
606 recalcAdvances(glyphs, {});
607
608 return mappedGlyphs;
609}
610
611QFontEngine::FaceId QWindowsFontEngineDirectWrite::faceId() const
612{
613 return m_faceId;
614}
615
616void QWindowsFontEngineDirectWrite::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags shaperFlags) const
617{
618 QVarLengthArray<UINT16> glyphIndices(glyphs->numGlyphs);
619
620 // ### Caching?
621 for(int i=0; i<glyphs->numGlyphs; i++)
622 glyphIndices[i] = UINT16(glyphs->glyphs[i]);
623
624 QVarLengthArray<DWRITE_GLYPH_METRICS> glyphMetrics(glyphIndices.size());
625
626 HRESULT hr;
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;
633
634 hr = m_directWriteFontFace->GetGdiCompatibleGlyphMetrics(float(fontDef.pixelSize),
635 1.0f,
636 NULL,
637 needsNaturalMetrics,
638 glyphIndices.data(),
639 glyphIndices.size(),
640 glyphMetrics.data());
641 } else {
642 hr = m_directWriteFontFace->GetDesignGlyphMetrics(glyphIndices.data(),
643 glyphIndices.size(),
644 glyphMetrics.data());
645 }
646 if (SUCCEEDED(hr)) {
647 qreal stretch = fontDef.stretch != QFont::AnyStretch ? fontDef.stretch / 100.0 : 1.0;
648 for (int i = 0; i < glyphs->numGlyphs; ++i)
649 glyphs->advances[i] = DESIGN_TO_LOGICAL(glyphMetrics[i].advanceWidth * stretch);
650 } else {
651 qErrnoWarning("%s: GetDesignGlyphMetrics failed", __FUNCTION__);
652 }
653}
654
655QPainterPath QWindowsFontEngineDirectWrite::unscaledGlyph(glyph_t glyph) const
656{
657 float advance = 0.0f;
658 UINT16 g = glyph;
659 DWRITE_GLYPH_OFFSET offset;
660 offset.advanceOffset = 0;
661 offset.ascenderOffset = 0;
662
663 QPainterPath ret;
664 GeometrySink geometrySink(&ret);
665 HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline(m_unitsPerEm,
666 &g,
667 &advance,
668 &offset,
669 1,
670 false,
671 false,
672 &geometrySink);
673 if (FAILED(hr))
674 qErrnoWarning("%s: GetGlyphRunOutline failed", __FUNCTION__);
675
676 return ret;
677}
678
679void QWindowsFontEngineDirectWrite::getUnscaledGlyph(glyph_t glyph,
680 QPainterPath *path,
681 glyph_metrics_t *metric)
682{
683 *path = unscaledGlyph(glyph);
684
685 UINT16 g = glyph;
686 DWRITE_GLYPH_METRICS glyphMetrics;
687 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&g, 1, &glyphMetrics);
688 if (FAILED(hr)) {
689 qErrnoWarning("%s: GetDesignGlyphMetrics failed", __FUNCTION__);
690 return;
691 }
692
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,
704 width,
705 height,
706 advanceWidth,
707 0);
708}
709
710void QWindowsFontEngineDirectWrite::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
711 QPainterPath *path, QTextItem::RenderFlags flags)
712{
713 Q_UNUSED(flags);
714 QVarLengthArray<UINT16> glyphIndices(nglyphs);
715 QVarLengthArray<DWRITE_GLYPH_OFFSET> glyphOffsets(nglyphs);
716 QVarLengthArray<FLOAT> glyphAdvances(nglyphs);
717
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;
723 }
724
725 GeometrySink geometrySink(path);
726 HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline(
727 fontDef.pixelSize,
728 glyphIndices.data(),
729 glyphAdvances.data(),
730 glyphOffsets.data(),
731 nglyphs,
732 false,
733 false,
734 &geometrySink
735 );
736
737 if (FAILED(hr))
738 qErrnoWarning("%s: GetGlyphRunOutline failed", __FUNCTION__);
739}
740
741glyph_metrics_t QWindowsFontEngineDirectWrite::boundingBox(const QGlyphLayout &glyphs)
742{
743 if (glyphs.numGlyphs == 0)
744 return glyph_metrics_t();
745 QFixed w = 0;
746 for (int i = 0; i < glyphs.numGlyphs; ++i)
747 w += glyphs.effectiveAdvance(i);
748
749 const QFixed leftBearing = firstLeftBearing(glyphs);
750 return glyph_metrics_t(leftBearing, -ascent(), w - leftBearing - lastRightBearing(glyphs),
751 ascent() + descent(), w, 0);
752}
753
754glyph_metrics_t QWindowsFontEngineDirectWrite::boundingBox(glyph_t g)
755{
756 UINT16 glyphIndex = g;
757
758 DWRITE_GLYPH_METRICS glyphMetrics;
759 HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&glyphIndex, 1, &glyphMetrics);
760 if (SUCCEEDED(hr)) {
761 QFixed advanceWidth = DESIGN_TO_LOGICAL(glyphMetrics.advanceWidth);
762 QFixed leftSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.leftSideBearing);
763 QFixed rightSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.rightSideBearing);
764 QFixed advanceHeight = DESIGN_TO_LOGICAL(glyphMetrics.advanceHeight);
765 QFixed verticalOriginY = DESIGN_TO_LOGICAL(glyphMetrics.verticalOriginY);
766 QFixed topSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.topSideBearing);
767 QFixed bottomSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.bottomSideBearing);
768 QFixed width = advanceWidth - leftSideBearing - rightSideBearing;
769 QFixed height = advanceHeight - topSideBearing - bottomSideBearing;
770 return glyph_metrics_t(leftSideBearing,
771 -verticalOriginY + topSideBearing,
772 width,
773 height,
774 advanceWidth,
775 0);
776 } else {
777 qErrnoWarning("%s: GetDesignGlyphMetrics failed", __FUNCTION__);
778 }
779
780 return glyph_metrics_t();
781}
782
783QFixed QWindowsFontEngineDirectWrite::capHeight() const
784{
785 if (m_capHeight <= 0)
786 return calculatedCapHeight();
787
788 return m_capHeight;
789}
790
791QFixed QWindowsFontEngineDirectWrite::xHeight() const
792{
793 return m_xHeight;
794}
795
796qreal QWindowsFontEngineDirectWrite::maxCharWidth() const
797{
798 return m_maxAdvanceWidth.toReal();
799}
800
801QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph,
802 const QFixedPoint &subPixelPosition,
803 const QTransform &t)
804{
805 QImage im = imageForGlyph(glyph, subPixelPosition, glyphMargin(Format_A8), t);
806
807 if (!im.isNull()) {
808 QImage alphaMap(im.width(), im.height(), QImage::Format_Alpha8);
809
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) {
814 *dst = qGray(*src);
815 ++dst;
816 ++src;
817 }
818 }
819
820 return alphaMap;
821 } else {
822 return QFontEngine::alphaMapForGlyph(glyph, t);
823 }
824}
825
826QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph,
827 const QFixedPoint &subPixelPosition)
828{
829 return alphaMapForGlyph(glyph, subPixelPosition, QTransform());
830}
831
832bool QWindowsFontEngineDirectWrite::supportsHorizontalSubPixelPositions() const
833{
834 QFont::HintingPreference hinting = determineHinting(fontDef);
835 return (hinting != QFont::PreferFullHinting && !(fontDef.styleStrategy & QFont::NoAntialias));
836}
837
838QFontEngine::Properties QWindowsFontEngineDirectWrite::properties() const
839{
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);
845
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;
857
858 directWriteFontFace2->Release();
859 return p;
860 } else {
861 return QFontEngine::properties();
862 }
863}
864
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,
871 QColor color,
872 QRect boundingRect) const
873{
874 ComPtr<IDWriteFactory2> factory2;
875 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
876 &factory2);
877 if (FAILED(hr))
878 return false;
879
880 ComPtr<IDWriteGlyphRunAnalysis> colorGlyphsAnalysis;
881 hr = factory2->CreateGlyphRunAnalysis(
882 &colorGlyphRun->glyphRun,
883 &transform,
884 renderMode,
885 measureMode,
886 gridFitMode,
887 DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
888 0.0, 0.0,
889 &colorGlyphsAnalysis
890 );
891
892 if (FAILED(hr)) {
893 qErrnoWarning(hr, "%s: CreateGlyphRunAnalysis failed for color run", __FUNCTION__);
894 return false;
895 }
896
897 float r, g, b, a;
898 if (colorGlyphRun->paletteIndex == 0xFFFF) {
899 r = float(color.redF());
900 g = float(color.greenF());
901 b = float(color.blueF());
902 a = 1.0;
903 } else {
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);
908 }
909
910 if (!qFuzzyIsNull(a))
911 renderGlyphRun(image, r, g, b, a, colorGlyphsAnalysis.Get(), boundingRect, renderMode);
912
913 return true;
914}
915
916#if QT_CONFIG(directwritecolrv1)
917static inline QTransform matrixToTransform(const DWRITE_MATRIX &matrix,
918 int unitsPerEm = 1)
919{
920 return QTransform(matrix.m11, matrix.m12,
921 matrix.m21, matrix.m22,
922 matrix.dx * unitsPerEm, matrix.dy * unitsPerEm);
923}
924
925static inline QColor colorToColor(const DWRITE_COLOR_F &color, float alphaMultiplier = 1.0)
926{
927 return QColor::fromRgbF(color.r, color.g, color.b, color.a * alphaMultiplier);
928}
929
930static inline QGradient::Spread extendToSpread(UINT32 extendMode)
931{
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;
936 };
937}
938
939static inline QPainter::CompositionMode compositeToCompositionMode(DWRITE_COLOR_COMPOSITE_MODE mode)
940{
941 switch (mode) {
942 case DWRITE_COLOR_COMPOSITE_CLEAR:
943 return QPainter::CompositionMode_Clear;
944
945 case DWRITE_COLOR_COMPOSITE_SRC:
946 return QPainter::CompositionMode_Source;
947
948 case DWRITE_COLOR_COMPOSITE_DEST:
949 return QPainter::CompositionMode_Destination;
950
951 case DWRITE_COLOR_COMPOSITE_SRC_OVER:
952 return QPainter::CompositionMode_SourceOver;
953
954 case DWRITE_COLOR_COMPOSITE_DEST_OVER:
955 return QPainter::CompositionMode_DestinationOver;
956
957 case DWRITE_COLOR_COMPOSITE_SRC_IN:
958 return QPainter::CompositionMode_SourceIn;
959
960 case DWRITE_COLOR_COMPOSITE_DEST_IN:
961 return QPainter::CompositionMode_DestinationIn;
962
963 case DWRITE_COLOR_COMPOSITE_SRC_OUT:
964 return QPainter::CompositionMode_SourceOut;
965
966 case DWRITE_COLOR_COMPOSITE_DEST_OUT:
967 return QPainter::CompositionMode_DestinationOut;
968
969 case DWRITE_COLOR_COMPOSITE_SRC_ATOP:
970 return QPainter::CompositionMode_SourceAtop;
971
972 case DWRITE_COLOR_COMPOSITE_DEST_ATOP:
973 return QPainter::CompositionMode_DestinationAtop;
974
975 case DWRITE_COLOR_COMPOSITE_XOR:
976 return QPainter::CompositionMode_Xor;
977
978 case DWRITE_COLOR_COMPOSITE_PLUS:
979 return QPainter::CompositionMode_Plus;
980
981 case DWRITE_COLOR_COMPOSITE_SCREEN:
982 return QPainter::CompositionMode_Screen;
983
984 case DWRITE_COLOR_COMPOSITE_OVERLAY:
985 return QPainter::CompositionMode_Overlay;
986
987 case DWRITE_COLOR_COMPOSITE_DARKEN:
988 return QPainter::CompositionMode_Darken;
989
990 case DWRITE_COLOR_COMPOSITE_LIGHTEN:
991 return QPainter::CompositionMode_Lighten;
992
993 case DWRITE_COLOR_COMPOSITE_COLOR_DODGE:
994 return QPainter::CompositionMode_ColorDodge;
995
996 case DWRITE_COLOR_COMPOSITE_COLOR_BURN:
997 return QPainter::CompositionMode_ColorBurn;
998
999 case DWRITE_COLOR_COMPOSITE_HARD_LIGHT:
1000 return QPainter::CompositionMode_HardLight;
1001
1002 case DWRITE_COLOR_COMPOSITE_SOFT_LIGHT:
1003 return QPainter::CompositionMode_SoftLight;
1004
1005 case DWRITE_COLOR_COMPOSITE_DIFFERENCE:
1006 return QPainter::CompositionMode_Difference;
1007
1008 case DWRITE_COLOR_COMPOSITE_EXCLUSION:
1009 return QPainter::CompositionMode_Exclusion;
1010
1011 case DWRITE_COLOR_COMPOSITE_MULTIPLY:
1012 return QPainter::CompositionMode_Multiply;
1013
1014 default:
1015 qCWarning(lcColrv1) << "Unhandled color composite mode:" << mode;
1016 return QPainter::CompositionMode_SourceOver;
1017 };
1018}
1019#endif // QT_CONFIG(directwritecolrv1)
1020
1021QRect QWindowsFontEngineDirectWrite::paintGraphBounds(glyph_t glyph,
1022 const DWRITE_MATRIX &matrix) const
1023{
1024#if QT_CONFIG(directwritecolrv1)
1025 ComPtr<IDWriteFontFace7> face7;
1026 HRESULT hr = m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace7),
1027 &face7);
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)
1031 return QRect{};
1032
1033 ComPtr<IDWritePaintReader> paintReader;
1034 hr = face7->CreatePaintReader(DWRITE_GLYPH_IMAGE_FORMATS_COLR_PAINT_TREE,
1035 featureLevel,
1036 &paintReader);
1037 if (FAILED(hr)) {
1038 qErrnoWarning(hr, "%s: CreatePaintReader failed", __FUNCTION__);
1039 return QRect{};
1040 }
1041
1042 DWRITE_PAINT_ELEMENT paintElement;
1043 D2D_RECT_F clipBox;
1044 hr = paintReader->SetCurrentGlyph(glyph,
1045 &paintElement,
1046 sizeof(paintElement),
1047 &clipBox,
1048 nullptr);
1049
1050 if (FAILED(hr)) {
1051 qErrnoWarning(hr, "%s: SetCurrentGlyph failed", __FUNCTION__);
1052 return QRect{};
1053 }
1054
1055 if (paintElement.paintType == DWRITE_PAINT_TYPE_NONE)
1056 return QRect{};
1057
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();
1065 }
1066
1067 QTransform initialTransform;
1068 initialTransform.scale(fontDef.pixelSize, fontDef.pixelSize);
1069 boundingRect = initialTransform.mapRect(boundingRect);
1070
1071 QTransform originalXform = matrixToTransform(matrix);
1072 boundingRect = originalXform.mapRect(boundingRect);
1073
1074 return boundingRect.toAlignedRect();
1075 } else {
1076 qCDebug(lcColrv1) << "Font face does not support IDWriteFontFace7 interface";
1077 }
1078#else
1079 Q_UNUSED(glyph);
1080 Q_UNUSED(matrix);
1081#endif
1082
1083 return QRect{};
1084}
1085
1086#if QT_CONFIG(directwritecolrv1)
1087bool QWindowsFontEngineDirectWrite::traverseColr1(IDWritePaintReader *paintReader,
1088 IDWriteFontFace7 *face7,
1089 const DWRITE_PAINT_ELEMENT *paintElement,
1090 QColrPaintGraphRenderer *paintGraphRenderer,
1091 int depth) const
1092{
1093 if (maxColrv1NestingDepth() > 0 && depth > maxColrv1NestingDepth()) {
1094 qCWarning(lcColrv1) << "COLRv1 graph nested deeper than" << maxColrv1NestingDepth()
1095 << "levels; aborting traversal";
1096 return false;
1097 }
1098
1099 paintGraphRenderer->save();
1100 auto cleanup = qScopeGuard([&paintGraphRenderer]() {
1101 paintGraphRenderer->restore();
1102 });
1103
1104 auto traverseChildren = [&](quint32 childCount) {
1105 DWRITE_PAINT_ELEMENT childPaintElement;
1106 if (FAILED(paintReader->MoveToFirstChild(&childPaintElement, sizeof(DWRITE_PAINT_ELEMENT))))
1107 return false;
1108
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)))) {
1113 return false;
1114 }
1115 }
1116 }
1117
1118 return SUCCEEDED(paintReader->MoveToParent());
1119 };
1120
1121 auto collectStops = [&paintReader](int stopCount) {
1122 QGradientStops ret;
1123
1124 QVarLengthArray<D2D1_GRADIENT_STOP> stops(stopCount);
1125 HRESULT hr = paintReader->GetGradientStops(0, stopCount, stops.data());
1126 if (FAILED(hr))
1127 return ret;
1128
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});
1133 }
1134
1135 return ret;
1136 };
1137
1138 switch (paintElement->paintType) {
1139 case DWRITE_PAINT_TYPE_LAYERS:
1140 {
1141 if (!traverseChildren(paintElement->paint.layers.childCount))
1142 return false;
1143
1144 break;
1145 }
1146
1147 case DWRITE_PAINT_TYPE_SOLID_GLYPH:
1148 {
1149 QPainterPath glyphPath = unscaledGlyph(paintElement->paint.solidGlyph.glyphIndex);
1150
1151 QColor color = colorToColor(paintElement->paint.solidGlyph.color.value);
1152 paintGraphRenderer->setPath(glyphPath);
1153 paintGraphRenderer->setSolidColor(color);
1154 paintGraphRenderer->drawCurrentPath();
1155
1156 break;
1157 }
1158
1159 case DWRITE_PAINT_TYPE_SOLID:
1160 {
1161 QColor color = colorToColor(paintElement->paint.solid.value,
1162 paintElement->paint.solid.alphaMultiplier);
1163 paintGraphRenderer->setSolidColor(color);
1164 paintGraphRenderer->drawCurrentPath();
1165 break;
1166 }
1167
1168 case DWRITE_PAINT_TYPE_COMPOSITE:
1169 {
1170 if (!paintGraphRenderer->isRendering()) {
1171 traverseChildren(2);
1172 } else {
1173 DWRITE_PAINT_ELEMENT childElement;
1174
1175 HRESULT hr = paintReader->MoveToFirstChild(&childElement, sizeof(DWRITE_PAINT_ELEMENT));
1176 if (FAILED(hr)) {
1177 qErrnoWarning(hr, "%s: Cannot move to first child of composite node",
1178 __FUNCTION__);
1179 return false;
1180 }
1181
1182 // First draw back drop which is the second child
1183 hr = paintReader->MoveToNextSibling(&childElement, sizeof(DWRITE_PAINT_ELEMENT));
1184 if (FAILED(hr)) {
1185 qErrnoWarning(hr, "%s: Cannot move to second child of composite node",
1186 __FUNCTION__);
1187 return false;
1188 }
1189
1190 DWRITE_COLOR_COMPOSITE_MODE compositeMode = paintElement->paint.composite.mode;
1191
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))
1197 return false;
1198
1199 // Then draw source which is the first child
1200 hr = paintReader->MoveToParent();
1201 if (FAILED(hr)) {
1202 qErrnoWarning(hr, "%s: Cannot move back to parent composite node",
1203 __FUNCTION__);
1204 return false;
1205 }
1206
1207 hr = paintReader->MoveToFirstChild(&childElement, sizeof(DWRITE_PAINT_ELEMENT));
1208 if (FAILED(hr)) {
1209 qErrnoWarning(hr, "%s: Cannot move to first child of composite node",
1210 __FUNCTION__);
1211 return false;
1212 }
1213
1214 compositeRenderer.setCompositionMode(compositeToCompositionMode(compositeMode));
1215 if (!traverseColr1(paintReader, face7, &childElement, &compositeRenderer, depth + 1))
1216 return false;
1217
1218 hr = paintReader->MoveToParent();
1219 if (FAILED(hr)) {
1220 qErrnoWarning(hr, "%s: Cannot move back to parent composite node",
1221 __FUNCTION__);
1222 return false;
1223 }
1224
1225 paintGraphRenderer->drawImage(compositeRenderer.endRender());
1226 }
1227
1228 break;
1229 }
1230
1231 case DWRITE_PAINT_TYPE_RADIAL_GRADIENT:
1232 {
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;
1239
1240 const QGradient::Spread spread
1241 = extendToSpread(paintElement->paint.radialGradient.extendMode);
1242
1243 const QGradientStops gradientStops
1244 = collectStops(paintElement->paint.radialGradient.gradientStopCount);
1245
1246 paintGraphRenderer->setRadialGradient(c0, r0, c1, r1, spread, gradientStops);
1247 paintGraphRenderer->drawCurrentPath();
1248 break;
1249 }
1250
1251 case DWRITE_PAINT_TYPE_SWEEP_GRADIENT:
1252 {
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;
1257
1258 const QGradient::Spread spread
1259 = extendToSpread(paintElement->paint.radialGradient.extendMode);
1260 const QGradientStops gradientStops
1261 = collectStops(paintElement->paint.radialGradient.gradientStopCount);
1262
1263 paintGraphRenderer->setConicalGradient(center,
1264 startAngle,
1265 endAngle,
1266 spread,
1267 gradientStops);
1268 paintGraphRenderer->drawCurrentPath();
1269 break;
1270 }
1271
1272 case DWRITE_PAINT_TYPE_LINEAR_GRADIENT:
1273 {
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);
1280
1281 const QGradient::Spread spread
1282 = extendToSpread(paintElement->paint.linearGradient.extendMode);
1283 const QGradientStops gradientStops
1284 = collectStops(paintElement->paint.linearGradient.gradientStopCount);
1285
1286 paintGraphRenderer->setLinearGradient(p0, p1, p2, spread, gradientStops);
1287 paintGraphRenderer->drawCurrentPath();
1288 break;
1289 }
1290
1291 case DWRITE_PAINT_TYPE_GLYPH:
1292 {
1293 QPainterPath glyphPath = unscaledGlyph(paintElement->paint.glyph.glyphIndex);
1294 paintGraphRenderer->appendPath(glyphPath);
1295 if (!traverseChildren(1))
1296 return false;
1297 break;
1298 }
1299
1300 case DWRITE_PAINT_TYPE_COLOR_GLYPH:
1301 {
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);
1309
1310 paintGraphRenderer->setClip(clipBox);
1311 }
1312
1313 DWRITE_PAINT_ELEMENT childElement;
1314 if (FAILED(paintReader->MoveToFirstChild(&childElement, sizeof(DWRITE_PAINT_ELEMENT))))
1315 return false;
1316
1317 if (!traverseColr1(paintReader, face7, &childElement, paintGraphRenderer, depth + 1))
1318 return false;
1319
1320 if (FAILED(paintReader->MoveToParent()))
1321 return false;
1322
1323 break;
1324 }
1325
1326 case DWRITE_PAINT_TYPE_TRANSFORM:
1327 {
1328 QTransform transform = matrixToTransform(paintElement->paint.transform, m_unitsPerEm);
1329 paintGraphRenderer->prependTransform(transform);
1330 if (!traverseChildren(1))
1331 return false;
1332
1333 break;
1334 }
1335
1336 default:
1337 qCDebug(lcColrv1) << "Unhandled paint graph node type" << paintElement->paintType;
1338 break;
1339 };
1340
1341 return true;
1342}
1343
1344bool QWindowsFontEngineDirectWrite::renderColr1GlyphRun(QImage *image,
1345 const DWRITE_GLYPH_RUN *glyphRun,
1346 const DWRITE_MATRIX &matrix,
1347 QColor color) const
1348{
1349 qCDebug(lcColrv1) << "renderColr1GlyphRun,"
1350 << "families:" << fontDef.families;
1351 ComPtr<IDWriteFontFace7> face7;
1352 HRESULT hr = m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace7),
1353 &face7);
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;
1359 return true;
1360 }
1361
1362 ComPtr<IDWritePaintReader> paintReader;
1363 hr = face7->CreatePaintReader(DWRITE_GLYPH_IMAGE_FORMATS_COLR_PAINT_TREE,
1364 featureLevel,
1365 &paintReader);
1366 if (FAILED(hr)) {
1367 qErrnoWarning(hr, "%s: CreatePaintReader failed", __FUNCTION__);
1368 return false;
1369 }
1370
1371 Q_ASSERT(glyphRun->glyphCount == 1);
1372 DWRITE_PAINT_ELEMENT paintElement;
1373 D2D_RECT_F clipBox;
1374 hr = paintReader->SetCurrentGlyph(glyphRun->glyphIndices[0],
1375 &paintElement,
1376 sizeof(DWRITE_PAINT_ELEMENT),
1377 &clipBox,
1378 nullptr);
1379 if (FAILED(hr)) {
1380 qErrnoWarning(hr, "%s: SetCurrentGlyph failed", __FUNCTION__);
1381 return false;
1382 }
1383
1384 if (paintElement.paintType == DWRITE_PAINT_TYPE_NONE) {
1385 qCDebug(lcColrv1) << "Glyph" << glyphRun->glyphIndices[0]
1386 << "does not have a paint graph";
1387 return false;
1388 }
1389
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);
1396
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();
1404 }
1405
1406 QTransform initialTransform;
1407 initialTransform.scale(fontDef.pixelSize, fontDef.pixelSize);
1408 boundingRect = initialTransform.mapRect(boundingRect);
1409
1410 QTransform originalXform = matrixToTransform(matrix);
1411 boundingRect = originalXform.mapRect(boundingRect);
1412
1413 qCDebug(lcColrv1).noquote() << "Bounds of"
1414 << glyphRun->glyphIndices[0]
1415 << " in device coordinates:"
1416 << boundingRect;
1417
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))
1422 return false;
1423
1424 *image = graphRenderer.endRender();
1425 } else {
1426 qCDebug(lcColrv1) << "Font face does not support IDWriteFontFace7 interface";
1427 }
1428
1429 return true;
1430}
1431#endif // QT_CONFIG(directwritecolrv1)
1432
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,
1438 QColor color,
1439 QRect boundingRect) const
1440{
1441 QImage ret;
1442
1443#if QT_CONFIG(directwritecolrv1)
1444 // Start by trying COLRv1 glyph, where we need to get the paint nodes ourselves and render
1445 // them.
1446 renderColr1GlyphRun(&ret, glyphRun, transform, color);
1447#endif // QT_CONFIG(directwritecolrv1)
1448
1449#if QT_CONFIG(directwrite3)
1450 // If not successful, we try the modern API that supports both embedded pixmaps or COLRv0
1451 // glyphs, or a combination.
1452 if (ret.isNull()) {
1453 ComPtr<IDWriteFactory4> factory4;
1454 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory4),
1455 &factory4);
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);
1461
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);
1467
1468 ComPtr<IDWriteColorGlyphRunEnumerator1> enumerator;
1469 hr = factory4->TranslateColorGlyphRun(D2D1::Point2F(0.0f, 0.0f),
1470 glyphRun,
1471 NULL,
1472 glyphFormats,
1473 measureMode,
1474 NULL,
1475 0,
1476 &enumerator);
1477 BOOL ok = true;
1478 while (SUCCEEDED(hr) && ok) {
1479 hr = enumerator->MoveNext(&ok);
1480 if (!ok)
1481 break;
1482
1483 const DWRITE_COLOR_GLYPH_RUN1 *colorGlyphRun = nullptr;
1484 hr = enumerator->GetCurrentRun(&colorGlyphRun);
1485 if (FAILED(hr)) {
1486 qErrnoWarning(hr, "%s: IDWriteColorGlyphRunEnumerator::GetCurrentRun failed", __FUNCTION__);
1487 return QImage{};
1488 }
1489
1490 if (colorGlyphRun->glyphImageFormat == DWRITE_GLYPH_IMAGE_FORMATS_NONE) {
1491 // On some older platforms, we get a glyph run with format NONE before
1492 // the actual ones
1493 continue;
1494 } else if (colorGlyphRun->glyphImageFormat == DWRITE_GLYPH_IMAGE_FORMATS_COLR) {
1495 if (ret.isNull()) {
1496 ret = QImage(boundingRect.size(), QImage::Format_ARGB32_Premultiplied);
1497 ret.fill(0);
1498 }
1499
1500 if (renderColr0GlyphRun(&ret,
1501 reinterpret_cast<const DWRITE_COLOR_GLYPH_RUN *>(colorGlyphRun), // Broken inheritance in MinGW
1502 transform,
1503 renderMode,
1504 measureMode,
1505 gridFitMode,
1506 color,
1507 boundingRect)) {
1508 break;
1509 }
1510 } else if (colorGlyphRun->glyphImageFormat & supportedBitmapFormats) {
1511 ComPtr<IDWriteFontFace4> face4;
1512 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace4),
1513 &face4))) {
1514 DWRITE_GLYPH_IMAGE_DATA data;
1515 void *ctx;
1516 Q_ASSERT(glyphRun->glyphCount == 1);
1517 HRESULT hr = face4->GetGlyphImageData(glyphRun->glyphIndices[0],
1518 fontDef.pixelSize,
1519 DWRITE_GLYPH_IMAGE_FORMATS(colorGlyphRun->glyphImageFormat & supportedBitmapFormats),
1520 &data,
1521 &ctx);
1522 if (FAILED(hr)) {
1523 qErrnoWarning("%s: GetGlyphImageData failed", __FUNCTION__);
1524 return QImage{};
1525 }
1526
1527 auto fnc = qScopeGuard([&]() {
1528 if (data.imageData != nullptr)
1529 face4->ReleaseGlyphImageData(ctx);
1530 });
1531
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]
1536 << "in font:"
1537 << fontDef.families
1538 << "with formats:"
1539 << colorGlyphRun->glyphImageFormat;
1540 } else {
1541 const char *format;
1542 switch (colorGlyphRun->glyphImageFormat) {
1543 case DWRITE_GLYPH_IMAGE_FORMATS_JPEG:
1544 format = "JPEG";
1545 break;
1546 case DWRITE_GLYPH_IMAGE_FORMATS_TIFF:
1547 format = "TIFF";
1548 break;
1549 default:
1550 format = "PNG";
1551 break;
1552 };
1553
1554 ret = QImage::fromData(reinterpret_cast<const uchar *>(data.imageData),
1555 data.imageDataSize,
1556 format);
1557 ret.convertTo(QImage::Format_ARGB32_Premultiplied);
1558
1559 QTransform matrix(transform.m11, transform.m12,
1560 transform.m21, transform.m22,
1561 transform.dx, transform.dy);
1562
1563 const qreal scale = fontDef.pixelSize / data.pixelsPerEm;
1564 matrix.scale(scale, scale);
1565
1566 if (!matrix.isIdentity())
1567 ret = ret.transformed(matrix, Qt::SmoothTransformation);
1568
1569 break;
1570 }
1571 }
1572
1573 } else {
1574 qCDebug(lcQpaFonts) << "Found glyph run with unsupported format"
1575 << colorGlyphRun->glyphImageFormat;
1576 }
1577 }
1578 }
1579 }
1580#endif // QT_CONFIG(directwrite3)
1581
1582 // If all else fails, we go through the pre-dwrite3 version, which just supports COLRv0.
1583 if (ret.isNull()) {
1584 ComPtr<IDWriteFactory2> factory2;
1585 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
1586 &factory2);
1587 if (FAILED(hr))
1588 return ret;
1589
1590 ComPtr<IDWriteColorGlyphRunEnumerator> enumerator;
1591 hr = factory2->TranslateColorGlyphRun(0.0f,
1592 0.0f,
1593 glyphRun,
1594 NULL,
1595 measureMode,
1596 NULL,
1597 0,
1598 &enumerator);
1599 if (SUCCEEDED(hr)) {
1600 ret = QImage(boundingRect.size(), QImage::Format_ARGB32_Premultiplied);
1601 ret.fill(0);
1602
1603 BOOL ok = true;
1604 while (SUCCEEDED(hr) && ok) {
1605 hr = enumerator->MoveNext(&ok);
1606 if (FAILED(hr)) {
1607 qErrnoWarning(hr, "%s: IDWriteColorGlyphRunEnumerator::MoveNext failed", __FUNCTION__);
1608 return QImage{};
1609 }
1610
1611 if (ok) {
1612 const DWRITE_COLOR_GLYPH_RUN *colorGlyphRun = nullptr;
1613 hr = enumerator->GetCurrentRun(&colorGlyphRun);
1614 if (FAILED(hr)) { // No colored runs, only outline
1615 qErrnoWarning(hr, "%s: IDWriteColorGlyphRunEnumerator::GetCurrentRun failed", __FUNCTION__);
1616 return QImage{};
1617 }
1618
1619 if (!renderColr0GlyphRun(&ret,
1620 colorGlyphRun,
1621 transform,
1622 renderMode,
1623 measureMode,
1624 gridFitMode,
1625 color,
1626 boundingRect)) {
1627 return QImage{};
1628 }
1629 }
1630 }
1631 }
1632 }
1633
1634 return ret;
1635}
1636
1637QImage QWindowsFontEngineDirectWrite::imageForGlyph(glyph_t t,
1638 const QFixedPoint &subPixelPosition,
1639 int margin,
1640 const QTransform &originalTransform,
1641 const QColor &color)
1642{
1643 UINT16 glyphIndex = t;
1644 FLOAT glyphAdvance = 0;
1645
1646 DWRITE_GLYPH_OFFSET glyphOffset;
1647 glyphOffset.advanceOffset = 0;
1648 glyphOffset.ascenderOffset = 0;
1649
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;
1659
1660 QTransform xform = originalTransform;
1661 if (fontDef.stretch != 100 && fontDef.stretch != QFont::AnyStretch)
1662 xform.scale(fontDef.stretch / 100.0, 1.0);
1663
1664 DWRITE_MATRIX transform;
1665 transform.dx = subPixelPosition.x.toReal();
1666 transform.dy = 0;
1667 transform.m11 = xform.m11();
1668 transform.m12 = xform.m12();
1669 transform.m21 = xform.m21();
1670 transform.m22 = xform.m22();
1671
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;
1677
1678 ComPtr<IDWriteFactory2> factory2;
1679 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
1680 &factory2);
1681 ComPtr<IDWriteGlyphRunAnalysis> glyphAnalysis;
1682 if (!SUCCEEDED(hr)) {
1683 qErrnoWarning(hr, "%s: Failed to query IDWriteFactory2 interface.", __FUNCTION__);
1684 hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis(
1685 &glyphRun,
1686 1.0f,
1687 &transform,
1688 renderMode,
1689 measureMode,
1690 0.0, 0.0,
1691 &glyphAnalysis
1692 );
1693 } else {
1694 hr = factory2->CreateGlyphRunAnalysis(
1695 &glyphRun,
1696 &transform,
1697 renderMode,
1698 measureMode,
1699 gridFitMode,
1700 DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
1701 0.0, 0.0,
1702 &glyphAnalysis
1703 );
1704 }
1705
1706 if (SUCCEEDED(hr)) {
1707 QRect rect = paintGraphBounds(t, transform);
1708 if (rect.isEmpty())
1709 rect = alphaTextureBounds(t, transform);
1710 if (rect.isEmpty())
1711 rect = colorBitmapBounds(t, transform);
1712
1713 if (rect.isEmpty()) {
1714 qCDebug(lcQpaFonts) << __FUNCTION__ << "Cannot get alpha texture bounds. Falling back to slower rendering path.";
1715 return QImage();
1716 }
1717
1718 if (glyphBoundingBoxExceedsLimit(rect.width(),
1719 rect.height(),
1720 effectivePixelSizeSquared(xform))) {
1721 return QImage();
1722 }
1723
1724 QRect boundingRect = rect.adjusted(-margin, -margin, margin, margin);
1725
1726 QImage image;
1727 if (glyphFormat == QFontEngine::Format_ARGB) {
1728 image = renderColorGlyph(&glyphRun,
1729 transform,
1730 renderMode,
1731 measureMode,
1732 gridFitMode,
1733 color,
1734 boundingRect);
1735 }
1736
1737 // Not a color glyph, fall back to regular glyph rendering
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);
1744
1745 float r, g, b, a;
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());
1751 } else {
1752 r = g = b = a = 0.0;
1753 }
1754
1755 renderGlyphRun(&image,
1756 r,
1757 g,
1758 b,
1759 a,
1760 glyphAnalysis.Get(),
1761 boundingRect,
1762 renderMode);
1763 }
1764
1765 return image;
1766 } else {
1767 qErrnoWarning(hr, "%s: CreateGlyphRunAnalysis failed", __FUNCTION__);
1768 return QImage();
1769 }
1770}
1771
1772void QWindowsFontEngineDirectWrite::renderGlyphRun(QImage *destination,
1773 float r,
1774 float g,
1775 float b,
1776 float a,
1777 IDWriteGlyphRunAnalysis *glyphAnalysis,
1778 const QRect &boundingRect,
1779 DWRITE_RENDERING_MODE renderMode) const
1780{
1781 const int width = destination->width();
1782 const int height = destination->height();
1783
1784 r *= 255.0;
1785 g *= 255.0;
1786 b *= 255.0;
1787
1788 const int size = width * height * 3;
1789 if (size > 0) {
1790 RECT rect;
1791 rect.left = boundingRect.left();
1792 rect.top = boundingRect.top();
1793 rect.right = boundingRect.left() + boundingRect.width();
1794 rect.bottom = boundingRect.top() + boundingRect.height();
1795
1796 QVarLengthArray<BYTE, 1024> alphaValueArray(size);
1797 BYTE *alphaValues = alphaValueArray.data();
1798 memset(alphaValues, 0, size);
1799
1800 HRESULT hr = glyphAnalysis->CreateAlphaTexture(renderMode == DWRITE_RENDERING_MODE_ALIASED
1801 ? DWRITE_TEXTURE_ALIASED_1x1
1802 : DWRITE_TEXTURE_CLEARTYPE_3x1,
1803 &rect,
1804 alphaValues,
1805 size);
1806 if (SUCCEEDED(hr)) {
1807 if (destination->hasAlphaChannel()) { // Color glyphs
1808 for (int y = 0; y < height; ++y) {
1809 uint *dest = reinterpret_cast<uint *>(destination->scanLine(y));
1810 BYTE *src = alphaValues + width * 3 * y;
1811
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;
1817
1818 if (m_pixelGeometry == DWRITE_PIXEL_GEOMETRY_BGR)
1819 qSwap(redAlpha, blueAlpha);
1820
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));
1826 }
1827 }
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;
1832
1833 for (int x = 0; x < width; ++x) {
1834 int alpha = *(src++);
1835 dest[x] = (alpha << 16) + (alpha << 8) + alpha;
1836 }
1837 }
1838 } else {
1839 for (int y = 0; y < height; ++y) {
1840 uint *dest = reinterpret_cast<uint *>(destination->scanLine(y));
1841 BYTE *src = alphaValues + width * 3 * y;
1842
1843 for (int x = 0; x < width; ++x) {
1844 BYTE redAlpha = *(src + 0);
1845 BYTE greenAlpha = *(src + 1);
1846 BYTE blueAlpha = *(src + 2);
1847
1848 if (m_pixelGeometry == DWRITE_PIXEL_GEOMETRY_BGR)
1849 qSwap(redAlpha, blueAlpha);
1850
1851 dest[x] = qRgb(redAlpha, greenAlpha, blueAlpha);
1852 src += 3;
1853 }
1854 }
1855 }
1856 } else {
1857 qErrnoWarning("%s: CreateAlphaTexture failed", __FUNCTION__);
1858 }
1859 }
1860}
1861
1862QImage QWindowsFontEngineDirectWrite::alphaRGBMapForGlyph(glyph_t t,
1863 const QFixedPoint &subPixelPosition,
1864 const QTransform &xform)
1865{
1866 QImage mask = imageForGlyph(t,
1867 subPixelPosition,
1868 glyphMargin(QFontEngine::Format_A32),
1869 xform);
1870
1871 if (mask.isNull()) {
1872 if (xform.type() > QTransform::TxTranslate && glyphTransformExceedsLimit(t, xform))
1873 return QImage();
1874
1875 mask = QFontEngine::renderedPathForGlyph(t, Qt::white);
1876 if (!xform.isIdentity())
1877 mask = mask.transformed(xform);
1878 }
1879
1880 return mask.depth() == 32
1881 ? mask
1882 : mask.convertToFormat(QImage::Format_RGB32);
1883}
1884
1885QFontEngine *QWindowsFontEngineDirectWrite::cloneWithSize(qreal pixelSize) const
1886{
1887 QWindowsFontEngineDirectWrite *fontEngine = new QWindowsFontEngineDirectWrite(m_directWriteFontFace,
1888 pixelSize,
1889 m_fontEngineData);
1890
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);
1897 }
1898
1899 return fontEngine;
1900}
1901
1902Qt::HANDLE QWindowsFontEngineDirectWrite::handle() const
1903{
1904 return m_directWriteFontFace;
1905}
1906
1907void QWindowsFontEngineDirectWrite::initFontInfo(const QFontDef &request,
1908 int dpi)
1909{
1910 fontDef = request;
1911
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.);
1916
1917 m_faceId.variableAxes = request.variableAxisValues;
1918
1919#if QT_CONFIG(directwrite3)
1920 IDWriteFontFace3 *face3 = nullptr;
1921 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace3),
1922 reinterpret_cast<void **>(&face3)))) {
1923
1924 fontDef.weight = QWindowsDirectWriteFontDatabase::fromDirectWriteWeight(face3->GetWeight());
1925 fontDef.style = QWindowsDirectWriteFontDatabase::fromDirectWriteStyle(face3->GetStyle());
1926
1927 IDWriteLocalizedStrings *names;
1928 if (SUCCEEDED(face3->GetFaceNames(&names))) {
1929 wchar_t englishLocale[] = L"en-us";
1930 fontDef.styleName = QWindowsDirectWriteFontDatabase::localeString(names, englishLocale);
1931 names->Release();
1932 }
1933
1934 // Color font
1935 if (face3->IsColorFont())
1936 glyphFormat = QFontEngine::Format_ARGB;
1937
1938 face3->Release();
1939 }
1940#endif
1941}
1942
1943QString QWindowsFontEngineDirectWrite::fontNameSubstitute(const QString &familyName)
1944{
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;
1950}
1951
1952QRect QWindowsFontEngineDirectWrite::alphaTextureBounds(glyph_t glyph,
1953 const DWRITE_MATRIX &transform)
1954{
1955 UINT16 glyphIndex = glyph;
1956 FLOAT glyphAdvance = 0;
1957
1958 DWRITE_GLYPH_OFFSET glyphOffset;
1959 glyphOffset.advanceOffset = 0;
1960 glyphOffset.ascenderOffset = 0;
1961
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;
1971
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;
1977
1978 ComPtr<IDWriteFactory2> factory2 = nullptr;
1979 HRESULT hr = m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2),
1980 &factory2);
1981
1982 ComPtr<IDWriteGlyphRunAnalysis> glyphAnalysis;
1983 if (SUCCEEDED(hr)) {
1984 hr = factory2->CreateGlyphRunAnalysis(
1985 &glyphRun,
1986 &transform,
1987 renderMode,
1988 measureMode,
1989 gridFitMode,
1990 DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
1991 0.0, 0.0,
1992 &glyphAnalysis
1993 );
1994 } else {
1995 hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis(
1996 &glyphRun,
1997 1.0f,
1998 &transform,
1999 renderMode,
2000 measureMode,
2001 0.0, 0.0,
2002 &glyphAnalysis
2003 );
2004 }
2005
2006 if (SUCCEEDED(hr)) {
2007 RECT rect;
2008 hr = glyphAnalysis->GetAlphaTextureBounds(renderMode == DWRITE_RENDERING_MODE_ALIASED
2009 ? DWRITE_TEXTURE_ALIASED_1x1
2010 : DWRITE_TEXTURE_CLEARTYPE_3x1,
2011 &rect);
2012 if (FAILED(hr) || rect.left == rect.right || rect.top == rect.bottom)
2013 return QRect{};
2014
2015 return QRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
2016 } else {
2017 return QRect{};
2018 }
2019}
2020
2021QRect QWindowsFontEngineDirectWrite::colorBitmapBounds(glyph_t glyph, const DWRITE_MATRIX &transform)
2022{
2023#if QT_CONFIG(directwrite3)
2024 ComPtr<IDWriteFontFace4> face4;
2025 if (SUCCEEDED(m_directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace4),
2026 &face4))) {
2027 DWRITE_GLYPH_IMAGE_FORMATS formats = face4->GetGlyphImageFormats();
2028
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);
2033
2034 if (formats & supportedBitmapFormats) {
2035 DWRITE_GLYPH_IMAGE_DATA data;
2036 void *ctx;
2037 HRESULT hr = face4->GetGlyphImageData(glyph,
2038 fontDef.pixelSize,
2039 DWRITE_GLYPH_IMAGE_FORMATS(formats & supportedBitmapFormats),
2040 &data,
2041 &ctx);
2042 if (FAILED(hr)) {
2043 qErrnoWarning("%s: GetGlyphImageData failed", __FUNCTION__);
2044 return QRect{};
2045 }
2046
2047 auto fnc = qScopeGuard([&]() {
2048 if (data.imageData != nullptr)
2049 face4->ReleaseGlyphImageData(ctx);
2050 });
2051
2052 if (data.pixelsPerEm == 0 || data.imageData == nullptr || data.imageDataSize == 0)
2053 return QRect{};
2054
2055 QRect rect(-data.horizontalLeftOrigin.x,
2056 -data.horizontalLeftOrigin.y,
2057 data.pixelSize.width,
2058 data.pixelSize.height);
2059
2060 QTransform matrix(transform.m11, transform.m12,
2061 transform.m21, transform.m22,
2062 transform.dx, transform.dy);
2063
2064 // GetGlyphImageData returns the closest matching size, which we need to scale down
2065 const qreal scale = fontDef.pixelSize / data.pixelsPerEm;
2066 matrix.scale(scale, scale);
2067 rect = matrix.mapRect(rect);
2068
2069 return rect;
2070 }
2071 }
2072
2073 return QRect{};
2074#else
2075 Q_UNUSED(glyph);
2076 Q_UNUSED(transform);
2077 return QRect{};
2078#endif // QT_CONFIG(directwrite3)
2079}
2080
2081glyph_metrics_t QWindowsFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph,
2082 const QFixedPoint &subPixelPosition,
2083 const QTransform &originalTransform,
2084 GlyphFormat format)
2085{
2086 QTransform matrix = originalTransform;
2087 if (fontDef.stretch != 100 && fontDef.stretch != QFont::AnyStretch)
2088 matrix.scale(fontDef.stretch / 100.0, 1.0);
2089
2090 glyph_metrics_t bbox = QFontEngine::boundingBox(glyph, matrix); // To get transformed advance
2091
2092 DWRITE_MATRIX transform;
2093 transform.dx = subPixelPosition.x.toReal();
2094 transform.dy = 0;
2095 transform.m11 = matrix.m11();
2096 transform.m12 = matrix.m12();
2097 transform.m21 = matrix.m21();
2098 transform.m22 = matrix.m22();
2099
2100 // Try COLRv1 approach first
2101 QRect rect = paintGraphBounds(glyph, transform);
2102
2103 // Then try general approach (works with regular truetype glyphs as well as COLRv0)
2104 if (rect.isEmpty())
2105 rect = alphaTextureBounds(glyph, transform);
2106
2107 // If this fails, we check if it is an embedded color bitmap
2108 if (rect.isEmpty())
2109 rect = colorBitmapBounds(glyph, transform);
2110
2111 // If we are unable to find metrics, just return the design metrics
2112 if (rect.isEmpty())
2113 return bbox;
2114
2115 int margin = glyphMargin(format);
2116 return glyph_metrics_t(rect.left(),
2117 rect.top(),
2118 rect.width() + margin * 2,
2119 rect.height() + margin * 2,
2120 bbox.xoff, bbox.yoff);
2121}
2122
2123QImage QWindowsFontEngineDirectWrite::bitmapForGlyph(glyph_t glyph,
2124 const QFixedPoint &subPixelPosition,
2125 const QTransform &t,
2126 const QColor &color)
2127{
2128 return imageForGlyph(glyph, subPixelPosition, glyphMargin(QFontEngine::Format_ARGB), t, color);
2129}
2130
2131QList<QFontVariableAxis> QWindowsFontEngineDirectWrite::variableAxes() const
2132{
2133 return m_variableAxes;
2134}
2135
2136bool QWindowsFontEngineDirectWrite::expectsGammaCorrectedBlending(QFontEngine::GlyphFormat format) const
2137{
2138 return format == QFontEngine::Format_A32;
2139}
2140
2141QT_END_NAMESPACE
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)