Debian Codegraph @

src/ports/SkScalerContext_win_dw.cpp

raw
1 /*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7 #include "src/utils/win/SkDWriteNTDDI_VERSION.h"
8
9 #include "include/core/SkTypes.h"
10 #if defined(SK_BUILD_FOR_WIN)
11
12 #undef GetGlyphIndices
13
14 #include "include/core/SkBBHFactory.h"
15 #include "include/core/SkBitmap.h"
16 #include "include/core/SkData.h"
17 #include "include/core/SkDrawable.h"
18 #include "include/core/SkFontMetrics.h"
19 #include "include/core/SkGraphics.h"
20 #include "include/core/SkImage.h"
21 #include "include/core/SkOpenTypeSVGDecoder.h"
22 #include "include/core/SkPath.h"
23 #include "include/core/SkPictureRecorder.h"
24 #include "include/core/SkSpan.h"
25 #include "include/effects/SkGradient.h"
26 #include "include/private/base/SkMutex.h"
27 #include "include/private/base/SkTo.h"
28 #include "src/base/SkEndian.h"
29 #include "src/base/SkScopeExit.h"
30 #include "src/base/SkSharedMutex.h"
31 #include "src/codec/SkCodecPriv.h"
32 #include "src/core/SkDraw.h"
33 #include "src/core/SkGlyph.h"
34 #include "src/core/SkMaskGamma.h"
35 #include "src/core/SkRasterClip.h"
36 #include "src/core/SkScalerContext.h"
37 #include "src/ports/SkScalerContext_win_dw.h"
38 #include "src/ports/SkTypeface_win_dw.h"
39 #include "src/sfnt/SkOTTable_EBLC.h"
40 #include "src/sfnt/SkOTTable_EBSC.h"
41 #include "src/sfnt/SkOTTable_gasp.h"
42 #include "src/sfnt/SkOTTable_maxp.h"
43 #include "src/utils/SkMatrix22.h"
44 #include "src/utils/win/SkDWrite.h"
45 #include "src/utils/win/SkDWriteGeometrySink.h"
46 #include "src/utils/win/SkHRESULT.h"
47 #include "src/utils/win/SkTScopedComPtr.h"
48
49 #include <dwrite.h>
50 #include <dwrite_1.h>
51 #include <dwrite_3.h>
52
53 namespace {
54 static inline const constexpr bool kSkShowTextBlitCoverage = false;
55
56 /* Note:
57 * In versions 8 and 8.1 of Windows, some calls in DWrite are not thread safe.
58 * The mutex returned from maybe_dw_mutex protects the calls that are
59 * problematic.
60 */
61 static SkSharedMutex* maybe_dw_mutex(DWriteFontTypeface& typeface) {
62 static SkSharedMutex mutex;
63 return typeface.fDWriteFontFace4 ? nullptr : &mutex;
64 }
65
66 class SK_SCOPED_CAPABILITY Exclusive {
67 public:
68 explicit Exclusive(SkSharedMutex* maybe_lock) SK_ACQUIRE(*maybe_lock)
69 : fLock(maybe_lock) {
70 if (fLock) {
71 fLock->acquire();
72 }
73 }
74 ~Exclusive() SK_RELEASE_CAPABILITY() {
75 if (fLock) {
76 fLock->release();
77 }
78 }
79
80 private:
81 SkSharedMutex* fLock;
82 };
83 class SK_SCOPED_CAPABILITY Shared {
84 public:
85 explicit Shared(SkSharedMutex* maybe_lock) SK_ACQUIRE_SHARED(*maybe_lock)
86 : fLock(maybe_lock) {
87 if (fLock) {
88 fLock->acquireShared();
89 }
90 }
91
92 // You would think this should be SK_RELEASE_SHARED_CAPABILITY, but SK_SCOPED_CAPABILITY
93 // doesn't fully understand the difference between shared and exclusive.
94 // Please review https://reviews.llvm.org/D52578 for more information.
95 ~Shared() SK_RELEASE_CAPABILITY() {
96 if (fLock) {
97 fLock->releaseShared();
98 }
99 }
100
101 private:
102 SkSharedMutex* fLock;
103 };
104
105 static bool isLCD(const SkScalerContextRec& rec) {
106 return SkMask::kLCD16_Format == rec.fMaskFormat;
107 }
108
109 static bool is_hinted(DWriteFontTypeface* typeface) {
110 Exclusive l(maybe_dw_mutex(*typeface));
111 AutoTDWriteTable<SkOTTableMaximumProfile> maxp(typeface->fDWriteFontFace.get());
112 if (!maxp.fExists) {
113 return false;
114 }
115 if (maxp.fSize < sizeof(SkOTTableMaximumProfile::Version::TT)) {
116 return false;
117 }
118 if (maxp->version.version != SkOTTableMaximumProfile::Version::TT::VERSION) {
119 return false;
120 }
121 return (0 != maxp->version.tt.maxSizeOfInstructions);
122 }
123
124 /** A GaspRange is inclusive, [min, max]. */
125 struct GaspRange {
126 using Behavior = SkOTTableGridAndScanProcedure::GaspRange::behavior;
127 GaspRange(int min, int max, int version, Behavior flags)
128 : fMin(min), fMax(max), fVersion(version), fFlags(flags) { }
129 int fMin;
130 int fMax;
131 int fVersion;
132 Behavior fFlags;
133 };
134
135 bool get_gasp_range(DWriteFontTypeface* typeface, int size, GaspRange* range) {
136 AutoTDWriteTable<SkOTTableGridAndScanProcedure> gasp(typeface->fDWriteFontFace.get());
137 if (!gasp.fExists) {
138 return false;
139 }
140 if (gasp.fSize < sizeof(SkOTTableGridAndScanProcedure)) {
141 return false;
142 }
143 if (gasp->version != SkOTTableGridAndScanProcedure::version0 &&
144 gasp->version != SkOTTableGridAndScanProcedure::version1)
145 {
146 return false;
147 }
148
149 uint16_t numRanges = SkEndianSwap16(gasp->numRanges);
150 if (numRanges > 1024 ||
151 gasp.fSize < sizeof(SkOTTableGridAndScanProcedure) +
152 sizeof(SkOTTableGridAndScanProcedure::GaspRange) * numRanges)
153 {
154 return false;
155 }
156
157 const SkOTTableGridAndScanProcedure::GaspRange* rangeTable =
158 SkTAfter<const SkOTTableGridAndScanProcedure::GaspRange>(gasp.get());
159 int minPPEM = -1;
160 for (uint16_t i = 0; i < numRanges; ++i, ++rangeTable) {
161 int maxPPEM = SkEndianSwap16(rangeTable->maxPPEM);
162 if (minPPEM < size && size <= maxPPEM) {
163 range->fMin = minPPEM + 1;
164 range->fMax = maxPPEM;
165 range->fVersion = SkEndian_SwapBE16(gasp->version);
166 range->fFlags = rangeTable->flags;
167 return true;
168 }
169 minPPEM = maxPPEM;
170 }
171 return false;
172 }
173 /** If the rendering mode for the specified 'size' is gridfit, then place
174 * the gridfit range into 'range'. Otherwise, leave 'range' alone.
175 */
176 static bool is_gridfit_only(GaspRange::Behavior flags) {
177 return flags.raw.value == GaspRange::Behavior::Raw::GridfitMask;
178 }
179
180 static bool has_bitmap_strike(DWriteFontTypeface* typeface, GaspRange range) {
181 Exclusive l(maybe_dw_mutex(*typeface));
182 {
183 AutoTDWriteTable<SkOTTableEmbeddedBitmapLocation> eblc(typeface->fDWriteFontFace.get());
184 if (!eblc.fExists) {
185 return false;
186 }
187 if (eblc.fSize < sizeof(SkOTTableEmbeddedBitmapLocation)) {
188 return false;
189 }
190 if (eblc->version != SkOTTableEmbeddedBitmapLocation::version_initial) {
191 return false;
192 }
193
194 uint32_t numSizes = SkEndianSwap32(eblc->numSizes);
195 if (numSizes > 1024 ||
196 eblc.fSize < sizeof(SkOTTableEmbeddedBitmapLocation) +
197 sizeof(SkOTTableEmbeddedBitmapLocation::BitmapSizeTable) * numSizes)
198 {
199 return false;
200 }
201
202 const SkOTTableEmbeddedBitmapLocation::BitmapSizeTable* sizeTable =
203 SkTAfter<const SkOTTableEmbeddedBitmapLocation::BitmapSizeTable>(eblc.get());
204 for (uint32_t i = 0; i < numSizes; ++i, ++sizeTable) {
205 if (sizeTable->ppemX == sizeTable->ppemY &&
206 range.fMin <= sizeTable->ppemX && sizeTable->ppemX <= range.fMax)
207 {
208 // TODO: determine if we should dig through IndexSubTableArray/IndexSubTable
209 // to determine the actual number of glyphs with bitmaps.
210
211 // TODO: Ensure that the bitmaps actually cover a significant portion of the strike.
212
213 // TODO: Ensure that the bitmaps are bi-level?
214 if (sizeTable->endGlyphIndex >= sizeTable->startGlyphIndex + 3) {
215 return true;
216 }
217 }
218 }
219 }
220
221 {
222 AutoTDWriteTable<SkOTTableEmbeddedBitmapScaling> ebsc(typeface->fDWriteFontFace.get());
223 if (!ebsc.fExists) {
224 return false;
225 }
226 if (ebsc.fSize < sizeof(SkOTTableEmbeddedBitmapScaling)) {
227 return false;
228 }
229 if (ebsc->version != SkOTTableEmbeddedBitmapScaling::version_initial) {
230 return false;
231 }
232
233 uint32_t numSizes = SkEndianSwap32(ebsc->numSizes);
234 if (numSizes > 1024 ||
235 ebsc.fSize < sizeof(SkOTTableEmbeddedBitmapScaling) +
236 sizeof(SkOTTableEmbeddedBitmapScaling::BitmapScaleTable) * numSizes)
237 {
238 return false;
239 }
240
241 const SkOTTableEmbeddedBitmapScaling::BitmapScaleTable* scaleTable =
242 SkTAfter<const SkOTTableEmbeddedBitmapScaling::BitmapScaleTable>(ebsc.get());
243 for (uint32_t i = 0; i < numSizes; ++i, ++scaleTable) {
244 if (scaleTable->ppemX == scaleTable->ppemY &&
245 range.fMin <= scaleTable->ppemX && scaleTable->ppemX <= range.fMax) {
246 // EBSC tables are normally only found in bitmap only fonts.
247 return true;
248 }
249 }
250 }
251
252 return false;
253 }
254
255 static bool both_zero(SkScalar a, SkScalar b) {
256 return 0 == a && 0 == b;
257 }
258
259 // returns false if there is any non-90-rotation or skew
260 static bool is_axis_aligned(const SkScalerContextRec& rec) {
261 return 0 == rec.fPreSkewX &&
262 (both_zero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
263 both_zero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
264 }
265
266 } //namespace
267
268 SkScalerContext_DW::SkScalerContext_DW(DWriteFontTypeface& typefaceRef,
269 const SkScalerContextEffects& effects,
270 const SkDescriptor* desc)
271 : SkScalerContext(typefaceRef, effects, desc)
272 {
273 DWriteFontTypeface* typeface = this->getDWriteTypeface();
274 fGlyphCount = typeface->fDWriteFontFace->GetGlyphCount();
275
276 // In general, all glyphs should use NATURAL_SYMMETRIC
277 // except when bi-level rendering is requested or there are embedded
278 // bi-level bitmaps (and the embedded bitmap flag is set and no rotation).
279 //
280 // DirectWrite's IDWriteFontFace::GetRecommendedRenderingMode does not do
281 // this. As a result, determine the actual size of the text and then see if
282 // there are any embedded bi-level bitmaps of that size. If there are, then
283 // force bitmaps by requesting bi-level rendering.
284 //
285 // FreeType allows for separate ppemX and ppemY, but DirectWrite assumes
286 // square pixels and only uses ppemY. Therefore the transform must track any
287 // non-uniform x-scale.
288 //
289 // Also, rotated glyphs should have the same absolute advance widths as
290 // horizontal glyphs and the subpixel flag should not affect glyph shapes.
291
292 SkVector scale;
293 fRec.computeMatrices(SkScalerContextRec::PreMatrixScale::kVertical, &scale, &fSkXform);
294
295 fXform.m11 = SkScalarToFloat(fSkXform.getScaleX());
296 fXform.m12 = SkScalarToFloat(fSkXform.getSkewY());
297 fXform.m21 = SkScalarToFloat(fSkXform.getSkewX());
298 fXform.m22 = SkScalarToFloat(fSkXform.getScaleY());
299 fXform.dx = 0;
300 fXform.dy = 0;
301
302 // realTextSize is the actual device size we want (as opposed to the size the user requested).
303 // gdiTextSize is the size we request when GDI compatible.
304 // If the scale is negative, this means the matrix will do the flip anyway.
305 const SkScalar realTextSize = scale.fY;
306 // Due to floating point math, the lower bits are suspect. Round carefully.
307 SkScalar gdiTextSize = SkScalarRoundToScalar(realTextSize * 64.0f) / 64.0f;
308 if (gdiTextSize == 0) {
309 gdiTextSize = SK_Scalar1;
310 }
311
312 bool bitmapRequested = SkToBool(fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag);
313 bool treatLikeBitmap = false;
314 bool axisAlignedBitmap = false;
315 if (bitmapRequested) {
316 // When embedded bitmaps are requested, treat the entire range like
317 // a bitmap strike if the range is gridfit only and contains a bitmap.
318 int bitmapPPEM = SkScalarTruncToInt(gdiTextSize);
319 GaspRange range(bitmapPPEM, bitmapPPEM, 0, GaspRange::Behavior());
320 if (get_gasp_range(typeface, bitmapPPEM, &range)) {
321 if (!is_gridfit_only(range.fFlags)) {
322 range = GaspRange(bitmapPPEM, bitmapPPEM, 0, GaspRange::Behavior());
323 }
324 }
325 treatLikeBitmap = has_bitmap_strike(typeface, range);
326
327 axisAlignedBitmap = is_axis_aligned(fRec);
328 }
329
330 GaspRange range(0, 0xFFFF, 0, GaspRange::Behavior());
331
332 // If the user requested aliased, do so with aliased compatible metrics.
333 if (SkMask::kBW_Format == fRec.fMaskFormat) {
334 fTextSizeRender = gdiTextSize;
335 fRenderingMode = DWRITE_RENDERING_MODE_ALIASED;
336 fTextureType = DWRITE_TEXTURE_ALIASED_1x1;
337 fTextSizeMeasure = gdiTextSize;
338 fMeasuringMode = DWRITE_MEASURING_MODE_GDI_CLASSIC;
339
340 // If we can use a bitmap, use gdi classic rendering and measurement.
341 // This will not always provide a bitmap, but matches expected behavior.
342 } else if (treatLikeBitmap && axisAlignedBitmap) {
343 fTextSizeRender = gdiTextSize;
344 fRenderingMode = DWRITE_RENDERING_MODE_GDI_CLASSIC;
345 fTextureType = DWRITE_TEXTURE_CLEARTYPE_3x1;
346 fTextSizeMeasure = gdiTextSize;
347 fMeasuringMode = DWRITE_MEASURING_MODE_GDI_CLASSIC;
348
349 // If rotated but the horizontal text could have used a bitmap,
350 // render high quality rotated glyphs but measure using bitmap metrics.
351 } else if (treatLikeBitmap) {
352 fTextSizeRender = gdiTextSize;
353 fRenderingMode = DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC;
354 fTextureType = DWRITE_TEXTURE_CLEARTYPE_3x1;
355 fTextSizeMeasure = gdiTextSize;
356 fMeasuringMode = DWRITE_MEASURING_MODE_GDI_CLASSIC;
357
358 // If the font has a gasp table version 1, use it to determine symmetric rendering.
359 } else if (get_gasp_range(typeface, SkScalarRoundToInt(gdiTextSize), &range) &&
360 range.fVersion >= 1)
361 {
362 fTextSizeRender = realTextSize;
363 fRenderingMode = range.fFlags.field.SymmetricSmoothing
364 ? DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC
365 : DWRITE_RENDERING_MODE_NATURAL;
366 fTextureType = DWRITE_TEXTURE_CLEARTYPE_3x1;
367 fTextSizeMeasure = realTextSize;
368 fMeasuringMode = DWRITE_MEASURING_MODE_NATURAL;
369
370 // If the requested size is above 20px or there are no bytecode hints, use symmetric rendering.
371 } else if (realTextSize > SkIntToScalar(20) || !is_hinted(typeface)) {
372 fTextSizeRender = realTextSize;
373 fRenderingMode = DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC;
374 fTextureType = DWRITE_TEXTURE_CLEARTYPE_3x1;
375 fTextSizeMeasure = realTextSize;
376 fMeasuringMode = DWRITE_MEASURING_MODE_NATURAL;
377
378 // Fonts with hints, no gasp or gasp version 0, and below 20px get non-symmetric rendering.
379 // Often such fonts have hints which were only tested with GDI ClearType classic.
380 // Some of these fonts rely on drop out control in the y direction in order to be legible.
381 // Tenor Sans
382 // https://fonts.google.com/specimen/Tenor+Sans
383 // Gill Sans W04
384 // https://cdn.leagueoflegends.com/lolkit/1.1.9/resources/fonts/gill-sans-w04-book.woff
385 // https://na.leagueoflegends.com/en/news/game-updates/patch/patch-410-notes
386 // See https://crbug.com/385897
387 } else {
388 fTextSizeRender = gdiTextSize;
389 fRenderingMode = DWRITE_RENDERING_MODE_NATURAL;
390 fTextureType = DWRITE_TEXTURE_CLEARTYPE_3x1;
391 fTextSizeMeasure = realTextSize;
392 fMeasuringMode = DWRITE_MEASURING_MODE_NATURAL;
393 }
394
395 // DirectWrite2 allows for grayscale hinting.
396 fAntiAliasMode = DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE;
397 if (typeface->fFactory2 && typeface->fDWriteFontFace2 &&
398 SkMask::kA8_Format == fRec.fMaskFormat &&
399 !(fRec.fFlags & SkScalerContext::kGenA8FromLCD_Flag))
400 {
401 // DWRITE_TEXTURE_ALIASED_1x1 is now misnamed, it must also be used with grayscale.
402 fTextureType = DWRITE_TEXTURE_ALIASED_1x1;
403 fAntiAliasMode = DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE;
404 }
405
406 // DirectWrite2 allows hinting to be disabled.
407 fGridFitMode = DWRITE_GRID_FIT_MODE_ENABLED;
408 if (fRec.getHinting() == SkFontHinting::kNone) {
409 fGridFitMode = DWRITE_GRID_FIT_MODE_DISABLED;
410 if (fRenderingMode != DWRITE_RENDERING_MODE_ALIASED) {
411 fRenderingMode = DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC;
412 }
413 }
414
415 if (this->isLinearMetrics()) {
416 fTextSizeMeasure = realTextSize;
417 fMeasuringMode = DWRITE_MEASURING_MODE_NATURAL;
418 }
419
420 // The GDI measuring modes don't seem to work well with CBDT fonts (DWrite.dll 10.0.18362.836).
421 if (fMeasuringMode != DWRITE_MEASURING_MODE_NATURAL) {
422 constexpr UINT32 CBDTTag = DWRITE_MAKE_OPENTYPE_TAG('C','B','D','T');
423 AutoDWriteTable CBDT(typeface->fDWriteFontFace.get(), CBDTTag);
424 if (CBDT.fExists) {
425 fMeasuringMode = DWRITE_MEASURING_MODE_NATURAL;
426 }
427 }
428 }
429
430 SkScalerContext_DW::~SkScalerContext_DW() {
431 }
432
433 #if DWRITE_CORE || (defined(NTDDI_WIN11_ZN) && NTDDI_VERSION >= NTDDI_WIN11_ZN)
434
435 namespace {
436 SkColor4f sk_color_from(DWRITE_COLOR_F const& color) {
437 // DWRITE_COLOR_F and SkColor4f are laid out the same and this should be a no-op.
438 return SkColor4f{ color.r, color.g, color.b, color.a };
439 }
440 DWRITE_COLOR_F dw_color_from(SkColor4f const& color) {
441 // DWRITE_COLOR_F and SkColor4f are laid out the same and this should be a no-op.
442 // Avoid brace initialization as DWRITE_COLOR_F can be defined as four floats (dxgitype.h,
443 // d3d9types.h) or four unions of two floats (dwrite_2.h, d3dtypes.h). The type changed in
444 // Direct3D 10, but the change does not appear to be documented.
445 DWRITE_COLOR_F dwColor;
446 dwColor.r = color.fR;
447 dwColor.g = color.fG;
448 dwColor.b = color.fB;
449 dwColor.a = color.fA;
450 return dwColor;
451 }
452
453 SkRect sk_rect_from(D2D_RECT_F const& rect) {
454 // D2D_RECT_F and SkRect are both y-down and laid the same so this should be a no-op.
455 return SkRect{ rect.left, rect.top, rect.right, rect.bottom };
456 }
457 constexpr bool D2D_RECT_F_is_empty(const D2D_RECT_F& r) {
458 return r.right <= r.left || r.bottom <= r.top;
459 }
460
461 SkMatrix sk_matrix_from(DWRITE_MATRIX const& m) {
462 // DWRITE_MATRIX and SkMatrix are y-down. However DWRITE_MATRIX is affine only.
463 return SkMatrix::MakeAll(
464 m.m11, m.m21, m.dx,
465 m.m12, m.m22, m.dy,
466 0, 0, 1);
467 }
468
469 SkTileMode sk_tile_mode_from(D2D1_EXTEND_MODE extendMode) {
470 switch (extendMode) {
471 case D2D1_EXTEND_MODE_CLAMP:
472 return SkTileMode::kClamp;
473 case D2D1_EXTEND_MODE_WRAP:
474 return SkTileMode::kRepeat;
475 case D2D1_EXTEND_MODE_MIRROR:
476 return SkTileMode::kMirror;
477 default:
478 return SkTileMode::kClamp;
479 }
480 }
481
482 SkBlendMode sk_blend_mode_from(DWRITE_COLOR_COMPOSITE_MODE compositeMode) {
483 switch (compositeMode) {
484 case DWRITE_COLOR_COMPOSITE_CLEAR:
485 return SkBlendMode::kClear;
486 case DWRITE_COLOR_COMPOSITE_SRC:
487 return SkBlendMode::kSrc;
488 case DWRITE_COLOR_COMPOSITE_DEST:
489 return SkBlendMode::kDst;
490 case DWRITE_COLOR_COMPOSITE_SRC_OVER:
491 return SkBlendMode::kSrcOver;
492 case DWRITE_COLOR_COMPOSITE_DEST_OVER:
493 return SkBlendMode::kDstOver;
494 case DWRITE_COLOR_COMPOSITE_SRC_IN:
495 return SkBlendMode::kSrcIn;
496 case DWRITE_COLOR_COMPOSITE_DEST_IN:
497 return SkBlendMode::kDstIn;
498 case DWRITE_COLOR_COMPOSITE_SRC_OUT:
499 return SkBlendMode::kSrcOut;
500 case DWRITE_COLOR_COMPOSITE_DEST_OUT:
501 return SkBlendMode::kDstOut;
502 case DWRITE_COLOR_COMPOSITE_SRC_ATOP:
503 return SkBlendMode::kSrcATop;
504 case DWRITE_COLOR_COMPOSITE_DEST_ATOP:
505 return SkBlendMode::kDstATop;
506 case DWRITE_COLOR_COMPOSITE_XOR:
507 return SkBlendMode::kXor;
508 case DWRITE_COLOR_COMPOSITE_PLUS:
509 return SkBlendMode::kPlus;
510
511 case DWRITE_COLOR_COMPOSITE_SCREEN:
512 return SkBlendMode::kScreen;
513 case DWRITE_COLOR_COMPOSITE_OVERLAY:
514 return SkBlendMode::kOverlay;
515 case DWRITE_COLOR_COMPOSITE_DARKEN:
516 return SkBlendMode::kDarken;
517 case DWRITE_COLOR_COMPOSITE_LIGHTEN:
518 return SkBlendMode::kLighten;
519 case DWRITE_COLOR_COMPOSITE_COLOR_DODGE:
520 return SkBlendMode::kColorDodge;
521 case DWRITE_COLOR_COMPOSITE_COLOR_BURN:
522 return SkBlendMode::kColorBurn;
523 case DWRITE_COLOR_COMPOSITE_HARD_LIGHT:
524 return SkBlendMode::kHardLight;
525 case DWRITE_COLOR_COMPOSITE_SOFT_LIGHT:
526 return SkBlendMode::kSoftLight;
527 case DWRITE_COLOR_COMPOSITE_DIFFERENCE:
528 return SkBlendMode::kDifference;
529 case DWRITE_COLOR_COMPOSITE_EXCLUSION:
530 return SkBlendMode::kExclusion;
531 case DWRITE_COLOR_COMPOSITE_MULTIPLY:
532 return SkBlendMode::kMultiply;
533
534 case DWRITE_COLOR_COMPOSITE_HSL_HUE:
535 return SkBlendMode::kHue;
536 case DWRITE_COLOR_COMPOSITE_HSL_SATURATION:
537 return SkBlendMode::kSaturation;
538 case DWRITE_COLOR_COMPOSITE_HSL_COLOR:
539 return SkBlendMode::kColor;
540 case DWRITE_COLOR_COMPOSITE_HSL_LUMINOSITY:
541 return SkBlendMode::kLuminosity;
542 default:
543 return SkBlendMode::kDst;
544 }
545 }
546
547 inline SkPoint SkVectorProjection(SkPoint a, SkPoint b) {
548 SkScalar length = b.length();
549 if (!length) {
550 return SkPoint();
551 }
552 SkPoint bNormalized = b;
553 bNormalized.normalize();
554 bNormalized.scale(SkPoint::DotProduct(a, b) / length);
555 return bNormalized;
556 }
557
558 // This linear interpolation is used for calculating a truncated color line in special edge cases.
559 // This interpolation needs to be kept in sync with what the gradient shader would normally do when
560 // truncating and drawing color lines. When drawing into N32 surfaces, this is expected to be true.
561 // If that changes, or if we support other color spaces in CPAL tables at some point, this needs to
562 // be looked at.
563 D2D1_COLOR_F lerpSkColor(D2D1_COLOR_F c0, D2D1_COLOR_F c1, float t) {
564 // Due to the floating point calculation in the caller, when interpolating between very narrow
565 // stops, we may get values outside the interpolation range, guard against these.
566 if (t < 0) {
567 return c0;
568 }
569 if (t > 1) {
570 return c1;
571 }
572 const auto c0_4f = skvx::float4(c0.r, c0.g, c0.b, c0.a),
573 c1_4f = skvx::float4(c1.r, c1.g, c1.b, c1.a),
574 c_4f = c0_4f + (c1_4f - c0_4f) * t;
575 D2D1_COLOR_F r;
576 c_4f.store(&r);
577 return r;
578 }
579
580 enum TruncateStops {
581 TruncateStart,
582 TruncateEnd,
583 };
584 // Truncate a vector of color stops at a previously computed stop position and insert at that
585 // position the color interpolated between the surrounding stops.
586 void truncateToStopInterpolating(SkScalar zeroRadiusStop,
587 std::vector<D2D1_GRADIENT_STOP>& stops,
588 TruncateStops truncateStops) {
589 if (stops.size() <= 1u ||
590 zeroRadiusStop < stops.front().position || stops.back().position < zeroRadiusStop) {
591 return;
592 }
593
594 auto lcmp = [](D2D1_GRADIENT_STOP const& stop, SkScalar position) {
595 return stop.position < position;
596 };
597 auto ucmp = [](SkScalar position, D2D1_GRADIENT_STOP const& stop) {
598 return position < stop.position;
599 };
600 size_t afterIndex = (truncateStops == TruncateStart)
601 ? std::lower_bound(stops.begin(), stops.end(), zeroRadiusStop, lcmp) - stops.begin()
602 : std::upper_bound(stops.begin(), stops.end(), zeroRadiusStop, ucmp) - stops.begin();
603
604 const float t = (zeroRadiusStop - stops[afterIndex - 1].position) /
605 (stops[afterIndex].position - stops[afterIndex - 1].position);
606 D2D1_COLOR_F lerpColor = lerpSkColor(stops[afterIndex - 1].color, stops[afterIndex].color, t);
607
608 if (truncateStops == TruncateStart) {
609 stops.erase(stops.begin(), stops.begin() + afterIndex);
610 stops.insert(stops.begin(), { 0, lerpColor });
611 } else {
612 stops.erase(stops.begin() + afterIndex, stops.end());
613 stops.insert(stops.end(), { 1, lerpColor });
614 }
615 }
616 } // namespace
617
618 bool SkScalerContext_DW::drawColorV1Paint(SkCanvas& canvas,
619 IDWritePaintReader& reader,
620 DWRITE_PAINT_ELEMENT const & element)
621 {
622 // Helper to draw the specified number of children.
623 auto drawChildren = [&](uint32_t childCount) -> bool {
624 if (childCount != 0) {
625 DWRITE_PAINT_ELEMENT childElement;
626 HRB(reader.MoveToFirstChild(&childElement));
627 this->drawColorV1Paint(canvas, reader, childElement);
628
629 for (uint32_t i = 1; i < childCount; i++) {
630 HRB(reader.MoveToNextSibling(&childElement));
631 this->drawColorV1Paint(canvas, reader, childElement);
632 }
633
634 HRB(reader.MoveToParent());
635 }
636 return true;
637 };
638
639 SkAutoCanvasRestore restoreCanvas(&canvas, true);
640 switch (element.paintType) {
641 case DWRITE_PAINT_TYPE_NONE:
642 return true;
643
644 case DWRITE_PAINT_TYPE_LAYERS: {
645 // A layers paint element has a variable number of children.
646 return drawChildren(element.paint.layers.childCount);
647 }
648
649 case DWRITE_PAINT_TYPE_SOLID_GLYPH: {
650 // A solid glyph paint element has no children.
651 // glyphIndex, color.value, color.paletteEntryIndex, color.alpha, color.colorAttributes
652 auto const& solidGlyph = element.paint.solidGlyph;
653
654 SkPathBuilder builder;
655 SkTScopedComPtr<IDWriteGeometrySink> geometryToPath;
656 HRBM(SkDWriteGeometrySink::Create(&builder, &geometryToPath),
657 "Could not create geometry to path converter.");
658 UINT16 glyphId = SkTo<UINT16>(solidGlyph.glyphIndex);
659 {
660 Exclusive l(maybe_dw_mutex(*this->getDWriteTypeface()));
661 HRBM(this->getDWriteTypeface()->fDWriteFontFace->GetGlyphRunOutline(
662 SkScalarToFloat(fTextSizeRender),
663 &glyphId,
664 nullptr, //advances
665 nullptr, //offsets
666 1, //num glyphs
667 FALSE, //sideways
668 FALSE, //rtl
669 geometryToPath.get()),
670 "Could not create glyph outline.");
671 }
672
673 builder.transform(SkMatrix::Scale(1.0f / fTextSizeRender, 1.0f / fTextSizeRender));
674 SkPaint skPaint;
675 skPaint.setColor4f(sk_color_from(solidGlyph.color.value));
676 skPaint.setAntiAlias(fRenderingMode != DWRITE_RENDERING_MODE_ALIASED);
677 canvas.drawPath(builder.detach(), skPaint);
678 return true;
679 }
680
681 case DWRITE_PAINT_TYPE_SOLID: {
682 // A solid paint element has no children.
683 // value, paletteEntryIndex, alphaMultiplier, colorAttributes
684 SkPaint skPaint;
685 skPaint.setColor4f(sk_color_from(element.paint.solid.value));
686 canvas.drawPaint(skPaint);
687 return true;
688 }
689
690 case DWRITE_PAINT_TYPE_LINEAR_GRADIENT: {
691 auto const& linearGradient = element.paint.linearGradient;
692 // A linear gradient paint element has no children.
693 // x0, y0, x1, y1, x2, y2, extendMode, gradientStopCount, [colorStops]
694
695 if (linearGradient.gradientStopCount == 0) {
696 return true;
697 }
698 std::vector<D2D1_GRADIENT_STOP> stops;
699 stops.resize(linearGradient.gradientStopCount);
700
701 // If success stops will be ordered.
702 HRBM(reader.GetGradientStops(0, stops.size(), stops.data()),
703 "Could not get linear gradient stops.");
704 SkPaint skPaint;
705 if (stops.size() == 1) {
706 skPaint.setColor4f(sk_color_from(stops[0].color));
707 canvas.drawPaint(skPaint);
708 return true;
709 }
710 SkPoint linePositions[2] = { {linearGradient.x0, linearGradient.y0},
711 {linearGradient.x1, linearGradient.y1} };
712 SkPoint p0 = linePositions[0];
713 SkPoint p1 = linePositions[1];
714 SkPoint p2 = SkPoint::Make(linearGradient.x2, linearGradient.y2);
715
716 // If p0p1 or p0p2 are degenerate probably nothing should be drawn.
717 // If p0p1 and p0p2 are parallel then one side is the first color and the other side is
718 // the last color, depending on the direction.
719 // For now, just use the first color.
720 if (p1 == p0 || p2 == p0 || !SkPoint::CrossProduct(p1 - p0, p2 - p0)) {
721 skPaint.setColor4f(sk_color_from(stops[0].color));
722 canvas.drawPaint(skPaint);
723 return true;
724 }
725
726 // Follow implementation note in nanoemoji:
727 // https://github.com/googlefonts/nanoemoji/blob/0ac6e7bb4d8202db692574d8530a9b643f1b3b3c/src/nanoemoji/svg.py#L188
728 // to compute a new gradient end point P3 as the orthogonal
729 // projection of the vector from p0 to p1 onto a line perpendicular
730 // to line p0p2 and passing through p0.
731 SkVector perpendicularToP2P0 = (p2 - p0);
732 perpendicularToP2P0 = SkPoint::Make( perpendicularToP2P0.y(),
733 -perpendicularToP2P0.x());
734 SkVector p3 = p0 + SkVectorProjection((p1 - p0), perpendicularToP2P0);
735 linePositions[1] = p3;
736
737 // Project/scale points according to stop extrema along p0p3 line,
738 // p3 being the result of the projection above, then scale stops to
739 // to [0, 1] range so that repeat modes work. The Skia linear
740 // gradient shader performs the repeat modes over the 0 to 1 range,
741 // that's why we need to scale the stops to within that range.
742 SkTileMode tileMode = sk_tile_mode_from(SkTo<D2D1_EXTEND_MODE>(linearGradient.extendMode));
743 SkScalar colorStopRange = stops.back().position - stops.front().position;
744 // If the color stops are all at the same offset position, repeat and reflect modes
745 // become meaningless.
746 if (colorStopRange == 0.f) {
747 if (tileMode != SkTileMode::kClamp) {
748 //skPaint.setColor(SK_ColorTRANSPARENT);
749 return true;
750 } else {
751 // Insert duplicated fake color stop in pad case at +1.0f to enable the projection
752 // of circles for an originally 0-length color stop range. Adding this stop will
753 // paint the equivalent gradient, because: All font specified color stops are in the
754 // same spot, mode is pad, so everything before this spot is painted with the first
755 // color, everything after this spot is painted with the last color. Not adding this
756 // stop will skip the projection and result in specifying non-normalized color stops
757 // to the shader.
758 stops.push_back({ stops.back().position + 1.0f, stops.back().color });
759 colorStopRange = 1.0f;
760 }
761 }
762 SkASSERT(colorStopRange != 0.f);
763
764 // If the colorStopRange is 0 at this point, the default behavior of the shader is to
765 // clamp to 1 color stops that are above 1, clamp to 0 for color stops that are below 0,
766 // and repeat the outer color stops at 0 and 1 if the color stops are inside the
767 // range. That will result in the correct rendering.
768 if ((colorStopRange != 1 || stops.front().position != 0.f)) {
769 SkVector p0p3 = p3 - p0;
770 SkVector p0Offset = p0p3;
771 p0Offset.scale(stops.front().position);
772 SkVector p1Offset = p0p3;
773 p1Offset.scale(stops.back().position);
774
775 linePositions[0] = p0 + p0Offset;
776 linePositions[1] = p0 + p1Offset;
777
778 SkScalar scaleFactor = 1 / colorStopRange;
779 SkScalar startOffset = stops.front().position;
780 for (D2D1_GRADIENT_STOP& stop : stops) {
781 stop.position = (stop.position - startOffset) * scaleFactor;
782 }
783 }
784
785 std::unique_ptr<SkColor4f[]> skColors(new SkColor4f[stops.size()]);
786 std::unique_ptr<SkScalar[]> skStops(new SkScalar[stops.size()]);
787 for (size_t i = 0; i < stops.size(); ++i) {
788 skColors[i] = sk_color_from(stops[i].color);
789 skStops[i] = stops[i].position;
790 }
791
792 sk_sp<SkShader> shader(SkShaders::LinearGradient(
793 linePositions,
794 SkGradient(
795 SkGradient::Colors(
796 SkSpan(skColors.get(), stops.size()),
797 SkSpan(skStops.get(), stops.size()),
798 tileMode),
799 SkGradient::Interpolation{
800 SkGradient::Interpolation::InPremul::kNo,
801 SkGradient::Interpolation::ColorSpace::kSRGB,
802 SkGradient::Interpolation::HueMethod::kShorter
803 }
804 )
805 ));
806
807 SkASSERT(shader);
808 // An opaque color is needed to ensure the gradient is not modulated by alpha.
809 skPaint.setColor(SK_ColorBLACK);
810 skPaint.setShader(shader);
811 canvas.drawPaint(skPaint);
812 return true;
813 }
814
815 case DWRITE_PAINT_TYPE_RADIAL_GRADIENT: {
816 auto const& radialGradient = element.paint.radialGradient;
817 // A radial gradient paint element has no children.
818 // x0, y0, radius0, x1, y1, radius1, extendMode, gradientStopCount, [colorsStops]
819
820 SkPoint start = SkPoint::Make(radialGradient.x0, radialGradient.y0);
821 SkScalar startRadius = radialGradient.radius0;
822 SkPoint end = SkPoint::Make(radialGradient.x1, radialGradient.y1);
823 SkScalar endRadius = radialGradient.radius1;
824
825 if (radialGradient.gradientStopCount == 0) {
826 return true;
827 }
828 std::vector<D2D1_GRADIENT_STOP> stops;
829 stops.resize(radialGradient.gradientStopCount);
830
831 // If success stops will be ordered.
832 HRBM(reader.GetGradientStops(0, stops.size(), stops.data()),
833 "Could not get radial gradient stops.");
834 SkPaint skPaint;
835 if (stops.size() == 1) {
836 skPaint.setColor4f(sk_color_from(stops[0].color));
837 canvas.drawPaint(skPaint);
838 return true;
839 }
840
841 SkScalar colorStopRange = stops.back().position - stops.front().position;
842 SkTileMode tileMode = sk_tile_mode_from(SkTo<D2D1_EXTEND_MODE>(radialGradient.extendMode));
843
844 if (colorStopRange == 0.f) {
845 if (tileMode != SkTileMode::kClamp) {
846 //skPaint.setColor(SK_ColorTRANSPARENT);
847 return true;
848 } else {
849 // Insert duplicated fake color stop in pad case at +1.0f to enable the projection
850 // of circles for an originally 0-length color stop range. Adding this stop will
851 // paint the equivalent gradient, because: All font specified color stops are in the
852 // same spot, mode is pad, so everything before this spot is painted with the first
853 // color, everything after this spot is painted with the last color. Not adding this
854 // stop will skip the projection and result in specifying non-normalized color stops
855 // to the shader.
856 stops.push_back({ stops.back().position + 1.0f, stops.back().color });
857 colorStopRange = 1.0f;
858 }
859 }
860 SkASSERT(colorStopRange != 0.f);
861
862 // If the colorStopRange is 0 at this point, the default behavior of the shader is to
863 // clamp to 1 color stops that are above 1, clamp to 0 for color stops that are below 0,
864 // and repeat the outer color stops at 0 and 1 if the color stops are inside the
865 // range. That will result in the correct rendering.
866 if (colorStopRange != 1 || stops.front().position != 0.f) {
867 // For the Skia two-point caonical shader to understand the
868 // COLRv1 color stops we need to scale stops to 0 to 1 range and
869 // interpolate new centers and radii. Otherwise the shader
870 // clamps stops outside the range to 0 and 1 (larger interval)
871 // or repeats the outer stops at 0 and 1 if the (smaller
872 // interval).
873 SkVector startToEnd = end - start;
874 SkScalar radiusDiff = endRadius - startRadius;
875 SkScalar scaleFactor = 1 / colorStopRange;
876 SkScalar stopsStartOffset = stops.front().position;
877
878 SkVector startOffset = startToEnd;
879 startOffset.scale(stops.front().position);
880 SkVector endOffset = startToEnd;
881 endOffset.scale(stops.back().position);
882
883 // The order of the following computations is important in order to avoid
884 // overwriting start or startRadius before the second reassignment.
885 end = start + endOffset;
886 start = start + startOffset;
887 endRadius = startRadius + radiusDiff * stops.back().position;
888 startRadius = startRadius + radiusDiff * stops.front().position;
889
890 for (auto& stop : stops) {
891 stop.position = (stop.position - stopsStartOffset) * scaleFactor;
892 }
893 }
894
895 // For negative radii, interpolation is needed to prepare parameters suitable
896 // for invoking the shader. Implementation below as resolution discussed in
897 // https://github.com/googlefonts/colr-gradients-spec/issues/367.
898 // Truncate to manually interpolated color for tile mode clamp, otherwise
899 // calculate positive projected circles.
900 if (startRadius < 0 || endRadius < 0) {
901 if (startRadius == endRadius && startRadius < 0) {
902 //skPaint.setColor(SK_ColorTRANSPARENT);
903 return true;
904 }
905
906 if (tileMode == SkTileMode::kClamp) {
907 SkVector startToEnd = end - start;
908 SkScalar radiusDiff = endRadius - startRadius;
909 SkScalar zeroRadiusStop = 0.f;
910 TruncateStops truncateSide = TruncateStart;
911 if (startRadius < 0) {
912 truncateSide = TruncateStart;
913
914 // Compute color stop position where radius is = 0. After the scaling
915 // of stop positions to the normal 0,1 range that we have done above,
916 // the size of the radius as a function of the color stops is: r(x) = r0
917 // + x*(r1-r0) Solving this function for r(x) = 0, we get: x = -r0 /
918 // (r1-r0)
919 zeroRadiusStop = -startRadius / (endRadius - startRadius);
920 startRadius = 0.f;
921 SkVector startEndDiff = end - start;
922 startEndDiff.scale(zeroRadiusStop);
923 start = start + startEndDiff;
924 }
925
926 if (endRadius < 0) {
927 truncateSide = TruncateEnd;
928 zeroRadiusStop = -startRadius / (endRadius - startRadius);
929 endRadius = 0.f;
930 SkVector startEndDiff = end - start;
931 startEndDiff.scale(1 - zeroRadiusStop);
932 end = end - startEndDiff;
933 }
934
935 if (!(startRadius == 0 && endRadius == 0)) {
936 truncateToStopInterpolating(zeroRadiusStop, stops, truncateSide);
937 } else {
938 // If both radii have become negative and where clamped to 0, we need to
939 // produce a single color cone, otherwise the shader colors the whole
940 // plane in a single color when two radii are specified as 0.
941 if (radiusDiff > 0) {
942 end = start + startToEnd;
943 endRadius = radiusDiff;
944 stops.erase(stops.begin(), stops.end() - 1);
945 } else {
946 start -= startToEnd;
947 startRadius = -radiusDiff;
948 stops.erase(stops.begin() + 1, stops.end());
949 }
950 }
951 } else {
952 if (startRadius < 0 || endRadius < 0) {
953 auto roundIntegerMultiple = [](SkScalar factorZeroCrossing,
954 SkTileMode tileMode) {
955 int roundedMultiple = factorZeroCrossing > 0
956 ? ceilf(factorZeroCrossing)
957 : floorf(factorZeroCrossing) - 1;
958 if (tileMode == SkTileMode::kMirror && roundedMultiple % 2 != 0) {
959 roundedMultiple += roundedMultiple < 0 ? -1 : 1;
960 }
961 return roundedMultiple;
962 };
963
964 SkVector startToEnd = end - start;
965 SkScalar radiusDiff = endRadius - startRadius;
966 SkScalar factorZeroCrossing = (startRadius / (startRadius - endRadius));
967 bool inRange = 0.f <= factorZeroCrossing && factorZeroCrossing <= 1.0f;
968 SkScalar direction = inRange && radiusDiff < 0 ? -1.0f : 1.0f;
969 SkScalar circleProjectionFactor =
970 roundIntegerMultiple(factorZeroCrossing * direction, tileMode);
971 startToEnd.scale(circleProjectionFactor);
972 startRadius += circleProjectionFactor * radiusDiff;
973 endRadius += circleProjectionFactor * radiusDiff;
974 start += startToEnd;
975 end += startToEnd;
976 }
977 }
978 }
979
980 std::unique_ptr<SkColor4f[]> skColors(new SkColor4f[stops.size()]);
981 std::unique_ptr<SkScalar[]> skStops(new SkScalar[stops.size()]);
982 for (size_t i = 0; i < stops.size(); ++i) {
983 skColors[i] = sk_color_from(stops[i].color);
984 skStops[i] = stops[i].position;
985 }
986
987 // An opaque color is needed to ensure the gradient is not modulated by alpha.
988 skPaint.setColor(SK_ColorBLACK);
989 skPaint.setShader(SkShaders::TwoPointConicalGradient(
990 start, startRadius, end, endRadius,
991 SkGradient(
992 SkGradient::Colors(
993 SkSpan(skColors.get(), stops.size()),
994 SkSpan(skStops.get(), stops.size()),
995 tileMode),
996 SkGradient::Interpolation{
997 SkGradient::Interpolation::InPremul::kNo,
998 SkGradient::Interpolation::ColorSpace::kSRGB,
999 SkGradient::Interpolation::HueMethod::kShorter
1000 }
1001 )
1002 ));
1003 canvas.drawPaint(skPaint);
1004 return true;
1005 }
1006
1007 case DWRITE_PAINT_TYPE_SWEEP_GRADIENT: {
1008 auto const& sweepGradient = element.paint.sweepGradient;
1009 // A sweep gradient paint element has no children.
1010 // centerX, centerY, startAngle, endAngle, extendMode, gradientStopCount, [colorStops]
1011
1012 if (sweepGradient.gradientStopCount == 0) {
1013 return true;
1014 }
1015 std::vector<D2D1_GRADIENT_STOP> stops;
1016 stops.resize(sweepGradient.gradientStopCount);
1017
1018 // If success stops will be ordered.
1019 HRBM(reader.GetGradientStops(0, stops.size(), stops.data()),
1020 "Could not get sweep gradient stops");
1021 SkPaint skPaint;
1022 if (stops.size() == 1) {
1023 skPaint.setColor4f(sk_color_from(stops[0].color));
1024 canvas.drawPaint(skPaint);
1025 return true;
1026 }
1027
1028 SkPoint center = SkPoint::Make(sweepGradient.centerX, sweepGradient.centerY);
1029
1030 SkScalar startAngle = sweepGradient.startAngle;
1031 SkScalar endAngle = sweepGradient.endAngle;
1032 // OpenType 1.9.1 adds a shift to the angle to ease specification of a 0 to 360
1033 // degree sweep. This appears to already be applied by DW.
1034 //startAngle += 180.0f;
1035 //endAngle += 180.0f;
1036
1037 // An opaque color is needed to ensure the gradient is not modulated by alpha.
1038 skPaint.setColor(SK_ColorBLACK);
1039
1040 // New (Var)SweepGradient implementation compliant with OpenType 1.9.1 from here.
1041
1042 // The shader expects stops from 0 to 1, so we need to account for
1043 // minimum and maximum stop positions being different from 0 and
1044 // 1. We do that by scaling minimum and maximum stop positions to
1045 // the 0 to 1 interval and scaling the angles inverse proportionally.
1046
1047 // 1) Scale angles to their equivalent positions if stops were from 0 to 1.
1048
1049 SkScalar sectorAngle = endAngle - startAngle;
1050 SkTileMode tileMode = sk_tile_mode_from(SkTo<D2D1_EXTEND_MODE>(sweepGradient.extendMode));
1051 if (sectorAngle == 0 && tileMode != SkTileMode::kClamp) {
1052 // "If the ColorLine's extend mode is reflect or repeat and start and end angle
1053 // are equal, nothing is drawn.".
1054 //skPaint.setColor(SK_ColorTRANSPARENT);
1055 return true;
1056 }
1057
1058 SkScalar startAngleScaled = startAngle + sectorAngle * stops.front().position;
1059 SkScalar endAngleScaled = startAngle + sectorAngle * stops.back().position;
1060
1061 // 2) Scale stops accordingly to 0 to 1 range.
1062
1063 float colorStopRange = stops.back().position - stops.front().position;
1064 if (colorStopRange == 0.f) {
1065 if (tileMode != SkTileMode::kClamp) {
1066 //skPaint.setColor(SK_ColorTRANSPARENT);
1067 return true;
1068 } else {
1069 // Insert duplicated fake color stop in pad case at +1.0f to feed the shader correct
1070 // values and enable painting a pad sweep gradient with two colors. Adding this stop
1071 // will paint the equivalent gradient, because: All font specified color stops are
1072 // in the same spot, mode is pad, so everything before this spot is painted with the
1073 // first color, everything after this spot is painted with the last color. Not
1074 // adding this stop will skip the projection and result in specifying non-normalized
1075 // color stops to the shader.
1076 stops.push_back({ stops.back().position + 1.0f, stops.back().color });
1077 colorStopRange = 1.0f;
1078 }
1079 }
1080
1081 SkScalar scaleFactor = 1 / colorStopRange;
1082 SkScalar startOffset = stops.front().position;
1083
1084 for (D2D1_GRADIENT_STOP& stop : stops) {
1085 stop.position = (stop.position - startOffset) * scaleFactor;
1086 }
1087
1088 /* https://docs.microsoft.com/en-us/typography/opentype/spec/colr#sweep-gradients
1089 * "The angles are expressed in counter-clockwise degrees from
1090 * the direction of the positive x-axis on the design
1091 * grid. [...] The color line progresses from the start angle
1092 * to the end angle in the counter-clockwise direction;" -
1093 * Convert angles and stops from counter-clockwise to clockwise
1094 * for the shader if the gradient is not already reversed due to
1095 * start angle being larger than end angle. */
1096 startAngleScaled = 360.f - startAngleScaled;
1097 endAngleScaled = 360.f - endAngleScaled;
1098 if (startAngleScaled >= endAngleScaled) {
1099 std::swap(startAngleScaled, endAngleScaled);
1100 std::reverse(stops.begin(), stops.end());
1101 for (auto& stop : stops) {
1102 stop.position = 1.0f - stop.position;
1103 }
1104 }
1105
1106 std::unique_ptr<SkColor4f[]> skColors(new SkColor4f[stops.size()]);
1107 std::unique_ptr<SkScalar[]> skStops(new SkScalar[stops.size()]);
1108 for (size_t i = 0; i < stops.size(); ++i) {
1109 skColors[i] = sk_color_from(stops[i].color);
1110 skStops[i] = stops[i].position;
1111 }
1112
1113 skPaint.setShader(SkShaders::SweepGradient(
1114 center, startAngleScaled, endAngleScaled,
1115 SkGradient(
1116 SkGradient::Colors(
1117 SkSpan(skColors.get(), stops.size()),
1118 SkSpan(skStops.get(), stops.size()),
1119 tileMode),
1120 SkGradient::Interpolation{
1121 SkGradient::Interpolation::InPremul::kNo,
1122 SkGradient::Interpolation::ColorSpace::kSRGB,
1123 SkGradient::Interpolation::HueMethod::kShorter
1124 }
1125 )
1126 ));
1127 canvas.drawPaint(skPaint);
1128 return true;
1129 }
1130
1131 case DWRITE_PAINT_TYPE_GLYPH: {
1132 // A glyph paint element has one child, which is the fill for the glyph shape glyphIndex.
1133 SkPathBuilder builder;
1134 SkTScopedComPtr<IDWriteGeometrySink> geometryToPath;
1135 HRBM(SkDWriteGeometrySink::Create(&builder, &geometryToPath),
1136 "Could not create geometry to path converter.");
1137 UINT16 glyphId = SkTo<UINT16>(element.paint.glyph.glyphIndex);
1138 {
1139 Exclusive l(maybe_dw_mutex(*this->getDWriteTypeface()));
1140 HRBM(this->getDWriteTypeface()->fDWriteFontFace->GetGlyphRunOutline(
1141 SkScalarToFloat(fTextSizeRender),
1142 &glyphId,
1143 nullptr, //advances
1144 nullptr, //offsets
1145 1, //num glyphs
1146 FALSE, //sideways
1147 FALSE, //rtl
1148 geometryToPath.get()),
1149 "Could not create glyph outline.");
1150 }
1151
1152 builder.transform(SkMatrix::Scale(1.0f / fTextSizeRender, 1.0f / fTextSizeRender));
1153 canvas.clipPath(builder.detach(), fRenderingMode != DWRITE_RENDERING_MODE_ALIASED);
1154
1155 drawChildren(1);
1156 return true;
1157 }
1158
1159 case DWRITE_PAINT_TYPE_COLOR_GLYPH: {
1160 auto const& colorGlyph = element.paint.colorGlyph;
1161 // A color glyph paint element has one child, the root of the paint tree for glyphIndex.
1162 // glyphIndex, clipBox
1163 if (D2D_RECT_F_is_empty(colorGlyph.clipBox)) {
1164 // Does not have a clip box
1165 } else {
1166 SkRect r = sk_rect_from(colorGlyph.clipBox);
1167 canvas.clipRect(r, fRenderingMode != DWRITE_RENDERING_MODE_ALIASED);
1168 }
1169
1170 drawChildren(1);
1171 return true;
1172 }
1173
1174 case DWRITE_PAINT_TYPE_TRANSFORM: {
1175 // A transform paint element always has one child, the transformed content.
1176 canvas.concat(sk_matrix_from(element.paint.transform));
1177 drawChildren(1);
1178 return true;
1179 }
1180
1181 case DWRITE_PAINT_TYPE_COMPOSITE: {
1182 // A composite paint element has two children, the source and destination of the operation.
1183
1184 SkPaint blendModePaint;
1185 blendModePaint.setBlendMode(sk_blend_mode_from(element.paint.composite.mode));
1186
1187 SkAutoCanvasRestore acr(&canvas, false);
1188
1189 // Need to visit the second child first and do savelayers, so manually handle children.
1190 DWRITE_PAINT_ELEMENT sourceElement;
1191 DWRITE_PAINT_ELEMENT backdropElement;
1192
1193 HRBM(reader.MoveToFirstChild(&sourceElement), "Could not move to child.");
1194 HRBM(reader.MoveToNextSibling(&backdropElement), "Could not move to sibiling.");
1195 canvas.saveLayer(nullptr, nullptr);
1196 this->drawColorV1Paint(canvas, reader, backdropElement);
1197
1198 HRBM(reader.MoveToParent(), "Could not move to parent.");
1199 HRBM(reader.MoveToFirstChild(&sourceElement), "Could not move to child.");
1200 canvas.saveLayer(nullptr, &blendModePaint);
1201 this->drawColorV1Paint(canvas, reader, sourceElement);
1202
1203 HRBM(reader.MoveToParent(), "Could not move to parent.");
1204
1205 return true;
1206 }
1207
1208 default:
1209 return false;
1210 }
1211 }
1212
1213 bool SkScalerContext_DW::drawColorV1Image(const SkGlyph& glyph, SkCanvas& canvas) {
1214 DWriteFontTypeface* typeface = this->getDWriteTypeface();
1215 IDWriteFontFace7* fontFace = typeface->fDWriteFontFace7/*.get()*/;
1216 if (!fontFace) {
1217 return false;
1218 }
1219 UINT32 glyphIndex = glyph.getGlyphID();
1220
1221 SkTScopedComPtr<IDWritePaintReader> paintReader;
1222 HRBM(fontFace->CreatePaintReader(DWRITE_GLYPH_IMAGE_FORMATS_COLR_PAINT_TREE,
1223 DWRITE_PAINT_FEATURE_LEVEL_COLR_V1,
1224 &paintReader),
1225 "Could not create paint reader.");
1226
1227 DWRITE_PAINT_ELEMENT paintElement;
1228 D2D_RECT_F clipBox;
1229 DWRITE_PAINT_ATTRIBUTES attributes;
1230 HRBM(paintReader->SetCurrentGlyph(glyphIndex, &paintElement, &clipBox, &attributes),
1231 "Could not set current glyph.");
1232
1233 if (paintElement.paintType == DWRITE_PAINT_TYPE_NONE) {
1234 // Does not have paint layers, try another format.
1235 return false;
1236 }
1237
1238 // All coordinates (including top level clip) are reported in "em"s (1 == em).
1239 // Size up all em units to the current size and transform.
1240 // Get glyph paths at render size, divide out the render size to get em units.
1241
1242 SkMatrix matrix = fSkXform;
1243 SkScalar scale = fTextSizeRender;
1244 matrix.preScale(scale, scale);
1245 if (this->isSubpixel()) {
1246 matrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1247 SkFixedToScalar(glyph.getSubYFixed()));
1248 }
1249 canvas.concat(matrix);
1250
1251 if (D2D_RECT_F_is_empty(clipBox)) {
1252 // Does not have a clip box
1253 } else {
1254 canvas.clipRect(sk_rect_from(clipBox));
1255 }
1256
1257 // The DirectWrite interface returns resolved colors if these are provided.
1258 // Indexes and alphas are reported but there is no reason to duplicate the color calculation.
1259 paintReader->SetTextColor(dw_color_from(SkColor4f::FromColor(fRec.fForegroundColor)));
1260 paintReader->SetCustomColorPalette(typeface->fDWPalette.get(), typeface->fPaletteEntryCount);
1261
1262 return this->drawColorV1Paint(canvas, *paintReader, paintElement);
1263 }
1264
1265 bool SkScalerContext_DW::generateColorV1Image(const SkGlyph& glyph, void* imageBuffer) {
1266 SkASSERT(glyph.maskFormat() == SkMask::Format::kARGB32_Format);
1267
1268 SkBitmap dstBitmap;
1269 // TODO: mark this as sRGB when the blits will be sRGB.
1270 dstBitmap.installPixels(
1271 SkImageInfo::Make(glyph.width(), glyph.height(), kN32_SkColorType, kPremul_SkAlphaType),
1272 imageBuffer,
1273 glyph.rowBytes());
1274
1275 SkCanvas canvas(dstBitmap);
1276 if constexpr (kSkShowTextBlitCoverage) {
1277 canvas.clear(0x33FF0000);
1278 } else {
1279 canvas.clear(SK_ColorTRANSPARENT);
1280 }
1281 canvas.translate(-SkIntToScalar(glyph.left()), -SkIntToScalar(glyph.top()));
1282
1283 return this->drawColorV1Image(glyph, canvas);
1284 }
1285
1286 bool SkScalerContext_DW::generateColorV1PaintBounds(
1287 SkMatrix* ctm, SkRect* bounds,
1288 IDWritePaintReader& reader, DWRITE_PAINT_ELEMENT const & element)
1289 {
1290 // Helper to iterate over the specified number of children.
1291 auto boundChildren = [&](UINT32 childCount) -> bool {
1292 if (childCount == 0) {
1293 return true;
1294 }
1295 DWRITE_PAINT_ELEMENT childElement;
1296 HRB(reader.MoveToFirstChild(&childElement));
1297 this->generateColorV1PaintBounds(ctm, bounds, reader, childElement);
1298
1299 for (uint32_t i = 1; i < childCount; ++i) {
1300 HRB(reader.MoveToNextSibling(&childElement));
1301 this->generateColorV1PaintBounds(ctm, bounds, reader, childElement);
1302 }
1303
1304 HRB(reader.MoveToParent());
1305 return true;
1306 };
1307
1308 SkMatrix restoreMatrix = *ctm;
1309 SK_AT_SCOPE_EXIT(*ctm = restoreMatrix);
1310
1311 switch (element.paintType) {
1312 case DWRITE_PAINT_TYPE_NONE:
1313 return false;
1314
1315 case DWRITE_PAINT_TYPE_LAYERS: {
1316 // A layers paint element has a variable number of children.
1317 return boundChildren(element.paint.layers.childCount);
1318 }
1319
1320 case DWRITE_PAINT_TYPE_SOLID_GLYPH: {
1321 // A solid glyph paint element has no children.
1322 // glyphIndex, color.value, color.paletteEntryIndex, color.alpha, color.colorAttributes
1323
1324 SkPathBuilder builder;
1325 SkTScopedComPtr<IDWriteGeometrySink> geometryToPath;
1326 HRBM(SkDWriteGeometrySink::Create(&builder, &geometryToPath),
1327 "Could not create geometry to path converter.");
1328 UINT16 glyphId = SkTo<UINT16>(element.paint.solidGlyph.glyphIndex);
1329 {
1330 Exclusive l(maybe_dw_mutex(*this->getDWriteTypeface()));
1331 HRBM(this->getDWriteTypeface()->fDWriteFontFace->GetGlyphRunOutline(
1332 SkScalarToFloat(fTextSizeRender),
1333 &glyphId,
1334 nullptr, //advances
1335 nullptr, //offsets
1336 1, //num glyphs
1337 FALSE, //sideways
1338 FALSE, //rtl
1339 geometryToPath.get()),
1340 "Could not create glyph outline.");
1341 }
1342
1343 SkMatrix t = *ctm;
1344 t.preConcat(SkMatrix::Scale(1.0f / fTextSizeRender, 1.0f / fTextSizeRender));
1345 builder.transform(t);
1346 bounds->join(builder.detach().getBounds());
1347 return true;
1348 }
1349
1350 case DWRITE_PAINT_TYPE_SOLID: {
1351 return true;
1352 }
1353
1354 case DWRITE_PAINT_TYPE_LINEAR_GRADIENT: {
1355 return true;
1356 }
1357
1358 case DWRITE_PAINT_TYPE_RADIAL_GRADIENT: {
1359 return true;
1360 }
1361
1362 case DWRITE_PAINT_TYPE_SWEEP_GRADIENT: {
1363 return true;
1364 }
1365
1366 case DWRITE_PAINT_TYPE_GLYPH: {
1367 // A glyph paint element has one child, which is the fill for the glyph shape glyphIndex.
1368 SkPathBuilder builder;
1369 SkTScopedComPtr<IDWriteGeometrySink> geometryToPath;
1370 HRBM(SkDWriteGeometrySink::Create(&builder, &geometryToPath),
1371 "Could not create geometry to path converter.");
1372 UINT16 glyphId = SkTo<UINT16>(element.paint.glyph.glyphIndex);
1373 {
1374 Exclusive l(maybe_dw_mutex(*this->getDWriteTypeface()));
1375 HRBM(this->getDWriteTypeface()->fDWriteFontFace->GetGlyphRunOutline(
1376 SkScalarToFloat(fTextSizeRender),
1377 &glyphId,
1378 nullptr, //advances
1379 nullptr, //offsets
1380 1, //num glyphs
1381 FALSE, //sideways
1382 FALSE, //rtl
1383 geometryToPath.get()),
1384 "Could not create glyph outline.");
1385 }
1386
1387 SkMatrix t = *ctm;
1388 t.preConcat(SkMatrix::Scale(1.0f / fTextSizeRender, 1.0f / fTextSizeRender));
1389 builder.transform(t);
1390 bounds->join(builder.detach().getBounds());
1391 return true;
1392 }
1393
1394 case DWRITE_PAINT_TYPE_COLOR_GLYPH: {
1395 // A color glyph paint element has one child, which is the root
1396 // of the paint tree for the glyph specified by glyphIndex.
1397 auto const& colorGlyph = element.paint.colorGlyph;
1398 if (D2D_RECT_F_is_empty(colorGlyph.clipBox)) {
1399 // Does not have a clip box
1400 return boundChildren(1);
1401 }
1402 SkRect r = sk_rect_from(colorGlyph.clipBox);
1403 ctm->mapRect(r);
1404 bounds->join(r);
1405 return true;
1406 }
1407
1408 case DWRITE_PAINT_TYPE_TRANSFORM: {
1409 // A transform paint element always has one child, which is the transformed content.
1410 ctm->preConcat(sk_matrix_from(element.paint.transform));
1411 return boundChildren(1);
1412 }
1413
1414 case DWRITE_PAINT_TYPE_COMPOSITE: {
1415 // A composite paint element has two children, the source and destination of the operation.
1416 return boundChildren(2);
1417 }
1418
1419 default:
1420 return false;
1421 }
1422 }
1423
1424 bool SkScalerContext_DW::generateColorV1Metrics(const SkGlyph& glyph, SkRect* bounds) {
1425 DWriteFontTypeface* typeface = this->getDWriteTypeface();
1426 IDWriteFontFace7* fontFace = typeface->fDWriteFontFace7/*.get()*/;
1427 if (!fontFace) {
1428 return false;
1429 }
1430 UINT32 glyphIndex = glyph.getGlyphID();
1431
1432 SkTScopedComPtr<IDWritePaintReader> paintReader;
1433 HRESULT hr;
1434 // No message on failure here, since this will fail if the font has no color glyphs.
1435 hr = fontFace->CreatePaintReader(DWRITE_GLYPH_IMAGE_FORMATS_COLR_PAINT_TREE,
1436 DWRITE_PAINT_FEATURE_LEVEL_COLR_V1,
1437 &paintReader);
1438 if (FAILED(hr)) {
1439 return false;
1440 }
1441
1442 DWRITE_PAINT_ELEMENT paintElement;
1443 D2D_RECT_F clipBox;
1444 DWRITE_PAINT_ATTRIBUTES attributes;
1445 // If the glyph is not color this will succeed but return paintType NONE.
1446 HRBM(paintReader->SetCurrentGlyph(glyphIndex, &paintElement, &clipBox, &attributes),
1447 "Could not set the current glyph.");
1448
1449 if (paintElement.paintType == DWRITE_PAINT_TYPE_NONE) {
1450 // Does not have paint layers, try another format.
1451 return false;
1452 }
1453
1454 // All coordinates (including top level clip) are reported in "em"s (1 == em).
1455 // Size up all em units to the current size and transform.
1456
1457 SkMatrix matrix = fSkXform;
1458 SkScalar scale = fTextSizeRender;
1459 matrix.preScale(scale, scale);
1460 if (this->isSubpixel()) {
1461 matrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1462 SkFixedToScalar(glyph.getSubYFixed()));
1463 }
1464
1465 SkRect r;
1466 if (D2D_RECT_F_is_empty(clipBox)) {
1467 // Does not have a clip box.
1468 r = SkRect::MakeEmpty();
1469 if (!this->generateColorV1PaintBounds(&matrix, &r, *paintReader, paintElement)) {
1470 return false;
1471 }
1472 *bounds = r;
1473 } else {
1474 *bounds = sk_rect_from(clipBox);
1475 matrix.mapRect(bounds);
1476 }
1477 return true;
1478 }
1479
1480 #else // DWRITE_CORE || (defined(NTDDI_WIN11_ZN) && NTDDI_VERSION >= NTDDI_WIN11_ZN)
1481
1482 bool SkScalerContext_DW::generateColorV1Metrics(const SkGlyph&, SkRect*) { return false; }
1483 bool SkScalerContext_DW::generateColorV1Image(const SkGlyph&, void*) { return false; }
1484 bool SkScalerContext_DW::drawColorV1Image(const SkGlyph&, SkCanvas&) { return false; }
1485
1486 #endif // DWRITE_CORE || (defined(NTDDI_WIN11_ZN) && NTDDI_VERSION >= NTDDI_WIN11_ZN)
1487
1488 bool SkScalerContext_DW::setAdvance(const SkGlyph& glyph, SkVector* advance) {
1489 *advance = {0, 0};
1490 UINT16 glyphId = glyph.getGlyphID();
1491 DWriteFontTypeface* typeface = this->getDWriteTypeface();
1492
1493 // DirectWrite treats all out of bounds glyph ids as having the same data as glyph 0.
1494 // For consistency with all other backends, treat out of range glyph ids as an error.
1495 if (fGlyphCount <= glyphId) {
1496 return false;
1497 }
1498
1499 DWRITE_GLYPH_METRICS gm;
1500
1501 if (DWRITE_MEASURING_MODE_GDI_CLASSIC == fMeasuringMode ||
1502 DWRITE_MEASURING_MODE_GDI_NATURAL == fMeasuringMode)
1503 {
1504 Exclusive l(maybe_dw_mutex(*typeface));
1505 HRBM(typeface->fDWriteFontFace->GetGdiCompatibleGlyphMetrics(
1506 fTextSizeMeasure,
1507 1.0f, // pixelsPerDip
1508 // This parameter does not act like the lpmat2 parameter to GetGlyphOutlineW.
1509 // If it did then GsA here and G_inv below to mapVectors.
1510 nullptr,
1511 DWRITE_MEASURING_MODE_GDI_NATURAL == fMeasuringMode,
1512 &glyphId, 1,
1513 &gm),
1514 "Could not get gdi compatible glyph metrics.");
1515 } else {
1516 Exclusive l(maybe_dw_mutex(*typeface));
1517 HRBM(typeface->fDWriteFontFace->GetDesignGlyphMetrics(&glyphId, 1, &gm),
1518 "Could not get design metrics.");
1519 }
1520
1521 DWRITE_FONT_METRICS dwfm;
1522 {
1523 Shared l(maybe_dw_mutex(*typeface));
1524 typeface->fDWriteFontFace->GetMetrics(&dwfm);
1525 }
1526 SkScalar advanceX = fTextSizeMeasure * gm.advanceWidth / dwfm.designUnitsPerEm;
1527
1528 *advance = { advanceX, 0 };
1529 if (DWRITE_MEASURING_MODE_GDI_CLASSIC == fMeasuringMode ||
1530 DWRITE_MEASURING_MODE_GDI_NATURAL == fMeasuringMode)
1531 {
1532 // DirectWrite produced 'compatible' metrics, but while close,
1533 // the end result is not always an integer as it would be with GDI.
1534 advance->fX = SkScalarRoundToScalar(advance->fX);
1535 }
1536 *advance = fSkXform.mapVector(*advance);
1537 return true;
1538 }
1539
1540 bool SkScalerContext_DW::generateDWMetrics(const SkGlyph& glyph,
1541 DWRITE_RENDERING_MODE renderingMode,
1542 DWRITE_TEXTURE_TYPE textureType,
1543 SkRect* bounds)
1544 {
1545 DWriteFontTypeface* typeface = this->getDWriteTypeface();
1546
1547 //Measure raster size.
1548 fXform.dx = SkFixedToFloat(glyph.getSubXFixed());
1549 fXform.dy = SkFixedToFloat(glyph.getSubYFixed());
1550
1551 FLOAT advance = 0;
1552
1553 UINT16 glyphId = glyph.getGlyphID();
1554
1555 DWRITE_GLYPH_OFFSET offset;
1556 offset.advanceOffset = 0.0f;
1557 offset.ascenderOffset = 0.0f;
1558
1559 DWRITE_GLYPH_RUN run;
1560 run.glyphCount = 1;
1561 run.glyphAdvances = &advance;
1562 run.fontFace = typeface->fDWriteFontFace.get();
1563 run.fontEmSize = SkScalarToFloat(fTextSizeRender);
1564 run.bidiLevel = 0;
1565 run.glyphIndices = &glyphId;
1566 run.isSideways = FALSE;
1567 run.glyphOffsets = &offset;
1568
1569 SkTScopedComPtr<IDWriteGlyphRunAnalysis> glyphRunAnalysis;
1570 {
1571 Exclusive l(maybe_dw_mutex(*typeface));
1572 // IDWriteFactory2::CreateGlyphRunAnalysis is very bad at aliased glyphs.
1573 if (typeface->fFactory2 &&
1574 (fGridFitMode == DWRITE_GRID_FIT_MODE_DISABLED ||
1575 fAntiAliasMode == DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE))
1576 {
1577 HRBM(typeface->fFactory2->CreateGlyphRunAnalysis(
1578 &run,
1579 &fXform,
1580 renderingMode,
1581 fMeasuringMode,
1582 fGridFitMode,
1583 fAntiAliasMode,
1584 0.0f, // baselineOriginX,
1585 0.0f, // baselineOriginY,
1586 &glyphRunAnalysis),
1587 "Could not create DW2 glyph run analysis.");
1588 } else {
1589 HRBM(typeface->fFactory->CreateGlyphRunAnalysis(&run,
1590 1.0f, // pixelsPerDip,
1591 &fXform,
1592 renderingMode,
1593 fMeasuringMode,
1594 0.0f, // baselineOriginX,
1595 0.0f, // baselineOriginY,
1596 &glyphRunAnalysis),
1597 "Could not create glyph run analysis.");
1598 }
1599 }
1600 RECT bbox;
1601 {
1602 Shared l(maybe_dw_mutex(*typeface));
1603 HRBM(glyphRunAnalysis->GetAlphaTextureBounds(textureType, &bbox),
1604 "Could not get texture bounds.");
1605 }
1606
1607 // GetAlphaTextureBounds succeeds but sometimes returns empty bounds like
1608 // { 0x80000000, 0x80000000, 0x80000000, 0x80000000 }
1609 // for small but not quite zero and large (but not really large) glyphs,
1610 // Only set as non-empty if the returned bounds are non-empty.
1611 if (bbox.left >= bbox.right || bbox.top >= bbox.bottom) {
1612 return false;
1613 }
1614
1615 *bounds = SkRect::MakeLTRB(bbox.left, bbox.top, bbox.right, bbox.bottom);
1616 return true;
1617 }
1618
1619 bool SkScalerContext_DW::getColorGlyphRun(const SkGlyph& glyph,
1620 IDWriteColorGlyphRunEnumerator** colorGlyph)
1621 {
1622 FLOAT advance = 0;
1623 UINT16 glyphId = glyph.getGlyphID();
1624
1625 DWRITE_GLYPH_OFFSET offset;
1626 offset.advanceOffset = 0.0f;
1627 offset.ascenderOffset = 0.0f;
1628
1629 DWRITE_GLYPH_RUN run;
1630 run.glyphCount = 1;
1631 run.glyphAdvances = &advance;
1632 run.fontFace = this->getDWriteTypeface()->fDWriteFontFace.get();
1633 run.fontEmSize = SkScalarToFloat(fTextSizeRender);
1634 run.bidiLevel = 0;
1635 run.glyphIndices = &glyphId;
1636 run.isSideways = FALSE;
1637 run.glyphOffsets = &offset;
1638
1639 HRESULT hr = this->getDWriteTypeface()->fFactory2->TranslateColorGlyphRun(
1640 0, 0, &run, nullptr, fMeasuringMode, &fXform, 0, colorGlyph);
1641 if (hr == DWRITE_E_NOCOLOR) {
1642 return false;
1643 }
1644 HRBM(hr, "Failed to translate color glyph run");
1645 return true;
1646 }
1647
1648 bool SkScalerContext_DW::generateColorMetrics(const SkGlyph& glyph, SkRect* bounds) {
1649 SkTScopedComPtr<IDWriteColorGlyphRunEnumerator> colorLayers;
1650 if (!getColorGlyphRun(glyph, &colorLayers)) {
1651 return false;
1652 }
1653 SkASSERT(colorLayers.get());
1654
1655 *bounds = SkRect::MakeEmpty();
1656 BOOL hasNextRun = FALSE;
1657 while (SUCCEEDED(colorLayers->MoveNext(&hasNextRun)) && hasNextRun) {
1658 const DWRITE_COLOR_GLYPH_RUN* colorGlyph;
1659 HRBM(colorLayers->GetCurrentRun(&colorGlyph), "Could not get current color glyph run");
1660
1661 SkPathBuilder builder;
1662 SkTScopedComPtr<IDWriteGeometrySink> geometryToPath;
1663 HRBM(SkDWriteGeometrySink::Create(&builder, &geometryToPath),
1664 "Could not create geometry to path converter.");
1665 {
1666 Exclusive l(maybe_dw_mutex(*this->getDWriteTypeface()));
1667 HRBM(colorGlyph->glyphRun.fontFace->GetGlyphRunOutline(
1668 colorGlyph->glyphRun.fontEmSize,
1669 colorGlyph->glyphRun.glyphIndices,
1670 colorGlyph->glyphRun.glyphAdvances,
1671 colorGlyph->glyphRun.glyphOffsets,
1672 colorGlyph->glyphRun.glyphCount,
1673 colorGlyph->glyphRun.isSideways,
1674 colorGlyph->glyphRun.bidiLevel % 2, //rtl
1675 geometryToPath.get()),
1676 "Could not create glyph outline.");
1677 }
1678 bounds->join(builder.detach().getBounds());
1679 }
1680 SkMatrix matrix = fSkXform;
1681 if (this->isSubpixel()) {
1682 matrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1683 SkFixedToScalar(glyph.getSubYFixed()));
1684 }
1685 matrix.mapRect(bounds);
1686 return true;
1687 }
1688
1689 bool SkScalerContext_DW::generateSVGMetrics(const SkGlyph& glyph, SkRect* bounds) {
1690 SkPictureRecorder recorder;
1691 SkRect infiniteRect = SkRect::MakeLTRB(-SK_ScalarInfinity, -SK_ScalarInfinity,
1692 SK_ScalarInfinity, SK_ScalarInfinity);
1693 sk_sp<SkBBoxHierarchy> bboxh = SkRTreeFactory()();
1694 SkCanvas* recordingCanvas = recorder.beginRecording(infiniteRect, bboxh);
1695 if (!this->drawSVGImage(glyph, *recordingCanvas)) {
1696 return false;
1697 }
1698 sk_sp<SkPicture> pic = recorder.finishRecordingAsPicture();
1699 *bounds = pic->cullRect();
1700 SkASSERT(bounds->isFinite());
1701 bounds->roundOut(bounds);
1702 return true;
1703 }
1704
1705 namespace {
1706 struct Context {
1707 SkTScopedComPtr<IDWriteFontFace4> fontFace4;
1708 void* glyphDataContext;
1709 Context(IDWriteFontFace4* face4, void* context)
1710 : fontFace4(SkRefComPtr(face4))
1711 , glyphDataContext(context)
1712 {}
1713 };
1714
1715 static void ReleaseProc(const void* ptr, void* context) {
1716 Context* ctx = (Context*)context;
1717 ctx->fontFace4->ReleaseGlyphImageData(ctx->glyphDataContext);
1718 delete ctx;
1719 }
1720 }
1721
1722 static void check_png() {
1723 SkASSERTF(SkCodecs::HasDecoder("png"),
1724 "No PNG decoder registered. A call to SkCodecs::Register is necessary.");
1725 }
1726
1727 bool SkScalerContext_DW::generatePngMetrics(const SkGlyph& glyph, SkRect* bounds) {
1728 IDWriteFontFace4* fontFace4 = this->getDWriteTypeface()->fDWriteFontFace4.get();
1729 if (!fontFace4) {
1730 return false;
1731 }
1732
1733 DWRITE_GLYPH_IMAGE_FORMATS imageFormats;
1734 HRBM(fontFace4->GetGlyphImageFormats(glyph.getGlyphID(), 0, UINT32_MAX, &imageFormats),
1735 "Cannot get glyph image formats.");
1736 if (!(imageFormats & DWRITE_GLYPH_IMAGE_FORMATS_PNG)) {
1737 return false;
1738 }
1739
1740 DWRITE_GLYPH_IMAGE_DATA glyphData;
1741 void* glyphDataContext;
1742 HRBM(fontFace4->GetGlyphImageData(glyph.getGlyphID(),
1743 fTextSizeRender,
1744 DWRITE_GLYPH_IMAGE_FORMATS_PNG,
1745 &glyphData,
1746 &glyphDataContext),
1747 "Glyph image data could not be acquired.");
1748
1749 Context* context = new Context(fontFace4, glyphDataContext);
1750 sk_sp<SkData> data = SkData::MakeWithProc(glyphData.imageData,
1751 glyphData.imageDataSize,
1752 &ReleaseProc,
1753 context);
1754
1755 sk_sp<SkImage> image = SkImages::DeferredFromEncodedData(std::move(data));
1756 if (!image) {
1757 check_png();
1758 return false;
1759 }
1760
1761 SkImageInfo info = image->imageInfo();
1762 *bounds = SkRect::Make(info.bounds());
1763
1764 SkMatrix matrix = fSkXform;
1765 SkScalar scale = fTextSizeRender / glyphData.pixelsPerEm;
1766 matrix.preScale(scale, scale);
1767 matrix.preTranslate(-glyphData.horizontalLeftOrigin.x, -glyphData.horizontalLeftOrigin.y);
1768 if (this->isSubpixel()) {
1769 matrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1770 SkFixedToScalar(glyph.getSubYFixed()));
1771 }
1772 matrix.mapRect(bounds);
1773 bounds->roundOut(bounds);
1774 return true;
1775 }
1776
1777 SkScalerContext::GlyphMetrics SkScalerContext_DW::generateMetrics(const SkGlyph& glyph,
1778 SkArenaAlloc* alloc) {
1779 GlyphMetrics mx(glyph.maskFormat());
1780
1781 mx.extraBits = ScalerContextBits::NONE;
1782
1783 if (!this->setAdvance(glyph, &mx.advance)) {
1784 return mx;
1785 }
1786
1787 DWriteFontTypeface* typeface = this->getDWriteTypeface();
1788 if (typeface->fIsColorFont) {
1789 if (generateColorV1Metrics(glyph, &mx.bounds)) {
1790 mx.maskFormat = SkMask::kARGB32_Format;
1791 mx.extraBits |= ScalerContextBits::COLRv1;
1792 mx.neverRequestPath = true;
1793 return mx;
1794 }
1795
1796 if (generateColorMetrics(glyph, &mx.bounds)) {
1797 mx.maskFormat = SkMask::kARGB32_Format;
1798 mx.extraBits |= ScalerContextBits::COLR;
1799 mx.neverRequestPath = true;
1800 return mx;
1801 }
1802
1803 if (generateSVGMetrics(glyph, &mx.bounds)) {
1804 mx.maskFormat = SkMask::kARGB32_Format;
1805 mx.extraBits |= ScalerContextBits::SVG;
1806 mx.neverRequestPath = true;
1807 return mx;
1808 }
1809
1810 if (generatePngMetrics(glyph, &mx.bounds)) {
1811 mx.maskFormat = SkMask::kARGB32_Format;
1812 mx.extraBits |= ScalerContextBits::PNG;
1813 mx.neverRequestPath = true;
1814 return mx;
1815 }
1816 }
1817
1818 if (this->generateDWMetrics(glyph, fRenderingMode, fTextureType, &mx.bounds)) {
1819 mx.extraBits = ScalerContextBits::DW;
1820 return mx;
1821 }
1822
1823 // GetAlphaTextureBounds succeeds but returns an empty RECT if there are no
1824 // glyphs of the specified texture type or it is too big for smoothing.
1825 // When this happens, try with the alternate texture type.
1826 if (DWRITE_TEXTURE_ALIASED_1x1 != fTextureType ||
1827 DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE == fAntiAliasMode)
1828 {
1829 if (this->generateDWMetrics(glyph,
1830 DWRITE_RENDERING_MODE_ALIASED,
1831 DWRITE_TEXTURE_ALIASED_1x1,
1832 &mx.bounds))
1833 {
1834 mx.maskFormat = SkMask::kBW_Format;
1835 mx.extraBits = ScalerContextBits::DW_1;
1836 return mx;
1837 }
1838 }
1839 // TODO: Try DWRITE_TEXTURE_CLEARTYPE_3x1 if DWRITE_TEXTURE_ALIASED_1x1 fails
1840
1841 // GetAlphaTextureBounds can fail for various reasons.
1842 // As a fallback, attempt to generate the metrics and image from the path.
1843 mx.computeFromPath = true;
1844 mx.extraBits = ScalerContextBits::PATH;
1845 return mx;
1846 }
1847
1848 void SkScalerContext_DW::generateFontMetrics(SkFontMetrics* metrics) {
1849 if (nullptr == metrics) {
1850 return;
1851 }
1852
1853 sk_bzero(metrics, sizeof(*metrics));
1854
1855 IDWriteFontFace* fontFace = this->getDWriteTypeface()->fDWriteFontFace.get();
1856 DWRITE_FONT_METRICS dwfm;
1857 if (DWRITE_MEASURING_MODE_GDI_CLASSIC == fMeasuringMode ||
1858 DWRITE_MEASURING_MODE_GDI_NATURAL == fMeasuringMode)
1859 {
1860 fontFace->GetGdiCompatibleMetrics(
1861 fTextSizeRender,
1862 1.0f, // pixelsPerDip
1863 &fXform,
1864 &dwfm);
1865 } else {
1866 fontFace->GetMetrics(&dwfm);
1867 }
1868
1869 SkScalar upem = SkIntToScalar(dwfm.designUnitsPerEm);
1870
1871 metrics->fAscent = -fTextSizeRender * SkIntToScalar(dwfm.ascent) / upem;
1872 metrics->fDescent = fTextSizeRender * SkIntToScalar(dwfm.descent) / upem;
1873 metrics->fLeading = fTextSizeRender * SkIntToScalar(dwfm.lineGap) / upem;
1874 metrics->fXHeight = fTextSizeRender * SkIntToScalar(dwfm.xHeight) / upem;
1875 metrics->fCapHeight = fTextSizeRender * SkIntToScalar(dwfm.capHeight) / upem;
1876 metrics->fUnderlineThickness = fTextSizeRender * SkIntToScalar(dwfm.underlineThickness) / upem;
1877 metrics->fUnderlinePosition = -(fTextSizeRender * SkIntToScalar(dwfm.underlinePosition) / upem);
1878 metrics->fStrikeoutThickness = fTextSizeRender * SkIntToScalar(dwfm.strikethroughThickness) / upem;
1879 metrics->fStrikeoutPosition = -(fTextSizeRender * SkIntToScalar(dwfm.strikethroughPosition) / upem);
1880
1881 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1882 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
1883 metrics->fFlags |= SkFontMetrics::kStrikeoutThicknessIsValid_Flag;
1884 metrics->fFlags |= SkFontMetrics::kStrikeoutPositionIsValid_Flag;
1885
1886 IDWriteFontFace5* fontFace5 = this->getDWriteTypeface()->fDWriteFontFace5.get();
1887 if (fontFace5 && fontFace5->HasVariations()) {
1888 // The bounds are only valid for the default variation.
1889 metrics->fFlags |= SkFontMetrics::kBoundsInvalid_Flag;
1890 }
1891
1892 IDWriteFontFace1* fontFace1 = this->getDWriteTypeface()->fDWriteFontFace1.get();
1893 if (fontFace1) {
1894 DWRITE_FONT_METRICS1 dwfm1;
1895 fontFace1->GetMetrics(&dwfm1);
1896 metrics->fTop = -fTextSizeRender * SkIntToScalar(dwfm1.glyphBoxTop) / upem;
1897 metrics->fBottom = -fTextSizeRender * SkIntToScalar(dwfm1.glyphBoxBottom) / upem;
1898 metrics->fXMin = fTextSizeRender * SkIntToScalar(dwfm1.glyphBoxLeft) / upem;
1899 metrics->fXMax = fTextSizeRender * SkIntToScalar(dwfm1.glyphBoxRight) / upem;
1900
1901 metrics->fMaxCharWidth = metrics->fXMax - metrics->fXMin;
1902 return;
1903 }
1904
1905 AutoTDWriteTable<SkOTTableHead> head(fontFace);
1906 if (head.fExists &&
1907 head.fSize >= sizeof(SkOTTableHead) &&
1908 head->version == SkOTTableHead::version1)
1909 {
1910 metrics->fTop = -fTextSizeRender * (int16_t)SkEndian_SwapBE16(head->yMax) / upem;
1911 metrics->fBottom = -fTextSizeRender * (int16_t)SkEndian_SwapBE16(head->yMin) / upem;
1912 metrics->fXMin = fTextSizeRender * (int16_t)SkEndian_SwapBE16(head->xMin) / upem;
1913 metrics->fXMax = fTextSizeRender * (int16_t)SkEndian_SwapBE16(head->xMax) / upem;
1914
1915 metrics->fMaxCharWidth = metrics->fXMax - metrics->fXMin;
1916 return;
1917 }
1918
1919 // The real bounds weren't actually available.
1920 metrics->fFlags |= SkFontMetrics::kBoundsInvalid_Flag;
1921 metrics->fTop = metrics->fAscent;
1922 metrics->fBottom = metrics->fDescent;
1923 }
1924
1925 ///////////////////////////////////////////////////////////////////////////////
1926
1927 #include "src/core/SkColorData.h"
1928
1929 void SkScalerContext_DW::BilevelToBW(const uint8_t* SK_RESTRICT src,
1930 const SkGlyph& glyph, void* imageBuffer) {
1931 const int width = glyph.width();
1932 const size_t dstRB = (width + 7) >> 3;
1933 uint8_t* SK_RESTRICT dst = static_cast<uint8_t*>(imageBuffer);
1934
1935 int byteCount = width >> 3;
1936 int bitCount = width & 7;
1937
1938 for (int y = 0; y < glyph.height(); ++y) {
1939 if (byteCount > 0) {
1940 for (int i = 0; i < byteCount; ++i) {
1941 unsigned byte = 0;
1942 byte |= src[0] & (1 << 7);
1943 byte |= src[1] & (1 << 6);
1944 byte |= src[2] & (1 << 5);
1945 byte |= src[3] & (1 << 4);
1946 byte |= src[4] & (1 << 3);
1947 byte |= src[5] & (1 << 2);
1948 byte |= src[6] & (1 << 1);
1949 byte |= src[7] & (1 << 0);
1950 dst[i] = byte;
1951 src += 8;
1952 }
1953 }
1954 if (bitCount > 0) {
1955 unsigned byte = 0;
1956 unsigned mask = 0x80;
1957 for (int i = 0; i < bitCount; i++) {
1958 byte |= (src[i]) & mask;
1959 mask >>= 1;
1960 }
1961 dst[byteCount] = byte;
1962 }
1963 src += bitCount;
1964 dst += dstRB;
1965 }
1966
1967 if constexpr (kSkShowTextBlitCoverage) {
1968 dst = static_cast<uint8_t*>(imageBuffer);
1969 for (unsigned y = 0; y < (unsigned)glyph.height(); y += 2) {
1970 for (unsigned x = (y & 0x2); x < (unsigned)glyph.width(); x+=4) {
1971 uint8_t& b = dst[(dstRB * y) + (x >> 3)];
1972 b = b ^ (1 << (0x7 - (x & 0x7)));
1973 }
1974 }
1975 }
1976 }
1977
1978 template<bool APPLY_PREBLEND>
1979 void SkScalerContext_DW::GrayscaleToA8(const uint8_t* SK_RESTRICT src,
1980 const SkGlyph& glyph, void* imageBuffer,
1981 const uint8_t* table8) {
1982 const size_t dstRB = glyph.rowBytes();
1983 const int width = glyph.width();
1984 uint8_t* SK_RESTRICT dst = static_cast<uint8_t*>(imageBuffer);
1985
1986 for (int y = 0; y < glyph.height(); y++) {
1987 for (int i = 0; i < width; i++) {
1988 U8CPU a = *(src++);
1989 dst[i] = sk_apply_lut_if<APPLY_PREBLEND>(a, table8);
1990 if constexpr (kSkShowTextBlitCoverage) {
1991 dst[i] = std::max<U8CPU>(0x30, dst[i]);
1992 }
1993 }
1994 dst = SkTAddOffset<uint8_t>(dst, dstRB);
1995 }
1996 }
1997
1998 template<bool APPLY_PREBLEND>
1999 void SkScalerContext_DW::RGBToA8(const uint8_t* SK_RESTRICT src,
2000 const SkGlyph& glyph, void* imageBuffer,
2001 const uint8_t* table8) {
2002 const size_t dstRB = glyph.rowBytes();
2003 const int width = glyph.width();
2004 uint8_t* SK_RESTRICT dst = static_cast<uint8_t*>(imageBuffer);
2005
2006 for (int y = 0; y < glyph.height(); y++) {
2007 for (int i = 0; i < width; i++) {
2008 U8CPU r = *(src++);
2009 U8CPU g = *(src++);
2010 U8CPU b = *(src++);
2011 dst[i] = sk_apply_lut_if<APPLY_PREBLEND>((r + g + b) / 3, table8);
2012 if constexpr (kSkShowTextBlitCoverage) {
2013 dst[i] = std::max<U8CPU>(0x30, dst[i]);
2014 }
2015 }
2016 dst = SkTAddOffset<uint8_t>(dst, dstRB);
2017 }
2018 }
2019
2020 template<bool APPLY_PREBLEND, bool RGB>
2021 void SkScalerContext_DW::RGBToLcd16(const uint8_t* SK_RESTRICT src, const SkGlyph& glyph,
2022 void* imageBuffer,
2023 const uint8_t* tableR, const uint8_t* tableG,
2024 const uint8_t* tableB) {
2025 const size_t dstRB = glyph.rowBytes();
2026 const int width = glyph.width();
2027 uint16_t* SK_RESTRICT dst = static_cast<uint16_t*>(imageBuffer);
2028
2029 for (int y = 0; y < glyph.height(); y++) {
2030 for (int i = 0; i < width; i++) {
2031 U8CPU r, g, b;
2032 if (RGB) {
2033 r = sk_apply_lut_if<APPLY_PREBLEND>(*(src++), tableR);
2034 g = sk_apply_lut_if<APPLY_PREBLEND>(*(src++), tableG);
2035 b = sk_apply_lut_if<APPLY_PREBLEND>(*(src++), tableB);
2036 } else {
2037 b = sk_apply_lut_if<APPLY_PREBLEND>(*(src++), tableB);
2038 g = sk_apply_lut_if<APPLY_PREBLEND>(*(src++), tableG);
2039 r = sk_apply_lut_if<APPLY_PREBLEND>(*(src++), tableR);
2040 }
2041 if constexpr (kSkShowTextBlitCoverage) {
2042 r = std::max<U8CPU>(0x30, r);
2043 g = std::max<U8CPU>(0x30, g);
2044 b = std::max<U8CPU>(0x30, b);
2045 }
2046 dst[i] = SkPack888ToRGB16(r, g, b);
2047 }
2048 dst = SkTAddOffset<uint16_t>(dst, dstRB);
2049 }
2050 }
2051
2052 const void* SkScalerContext_DW::getDWMaskBits(const SkGlyph& glyph,
2053 DWRITE_RENDERING_MODE renderingMode,
2054 DWRITE_TEXTURE_TYPE textureType)
2055 {
2056 DWriteFontTypeface* typeface = this->getDWriteTypeface();
2057
2058 int sizeNeeded = glyph.width() * glyph.height();
2059 if (DWRITE_TEXTURE_CLEARTYPE_3x1 == textureType) {
2060 sizeNeeded *= 3;
2061 }
2062 if (sizeNeeded > fBits.size()) {
2063 fBits.resize(sizeNeeded);
2064 }
2065
2066 // erase
2067 memset(fBits.begin(), 0, sizeNeeded);
2068
2069 fXform.dx = SkFixedToFloat(glyph.getSubXFixed());
2070 fXform.dy = SkFixedToFloat(glyph.getSubYFixed());
2071
2072 FLOAT advance = 0.0f;
2073
2074 UINT16 index = glyph.getGlyphID();
2075
2076 DWRITE_GLYPH_OFFSET offset;
2077 offset.advanceOffset = 0.0f;
2078 offset.ascenderOffset = 0.0f;
2079
2080 DWRITE_GLYPH_RUN run;
2081 run.glyphCount = 1;
2082 run.glyphAdvances = &advance;
2083 run.fontFace = typeface->fDWriteFontFace.get();
2084 run.fontEmSize = SkScalarToFloat(fTextSizeRender);
2085 run.bidiLevel = 0;
2086 run.glyphIndices = &index;
2087 run.isSideways = FALSE;
2088 run.glyphOffsets = &offset;
2089 {
2090 SkTScopedComPtr<IDWriteGlyphRunAnalysis> glyphRunAnalysis;
2091 {
2092 Exclusive l(maybe_dw_mutex(*typeface));
2093 // IDWriteFactory2::CreateGlyphRunAnalysis is very bad at aliased glyphs.
2094 if (typeface->fFactory2 &&
2095 (fGridFitMode == DWRITE_GRID_FIT_MODE_DISABLED ||
2096 fAntiAliasMode == DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE))
2097 {
2098 HRNM(typeface->fFactory2->CreateGlyphRunAnalysis(&run,
2099 &fXform,
2100 renderingMode,
2101 fMeasuringMode,
2102 fGridFitMode,
2103 fAntiAliasMode,
2104 0.0f, // baselineOriginX,
2105 0.0f, // baselineOriginY,
2106 &glyphRunAnalysis),
2107 "Could not create DW2 glyph run analysis.");
2108 } else {
2109 HRNM(typeface->fFactory->CreateGlyphRunAnalysis(&run,
2110 1.0f, // pixelsPerDip,
2111 &fXform,
2112 renderingMode,
2113 fMeasuringMode,
2114 0.0f, // baselineOriginX,
2115 0.0f, // baselineOriginY,
2116 &glyphRunAnalysis),
2117 "Could not create glyph run analysis.");
2118 }
2119 }
2120 //NOTE: this assumes that the glyph has already been measured
2121 //with an exact same glyph run analysis.
2122 RECT bbox;
2123 bbox.left = glyph.left();
2124 bbox.top = glyph.top();
2125 bbox.right = glyph.left() + glyph.width();
2126 bbox.bottom = glyph.top() + glyph.height();
2127 {
2128 Shared l(maybe_dw_mutex(*typeface));
2129 HRNM(glyphRunAnalysis->CreateAlphaTexture(textureType,
2130 &bbox,
2131 fBits.begin(),
2132 sizeNeeded),
2133 "Could not draw mask.");
2134 }
2135 }
2136 return fBits.begin();
2137 }
2138
2139 bool SkScalerContext_DW::generateDWImage(const SkGlyph& glyph, void* imageBuffer) {
2140 //Create the mask.
2141 ScalerContextBits::value_type format = glyph.extraBits();
2142 DWRITE_RENDERING_MODE renderingMode = fRenderingMode;
2143 DWRITE_TEXTURE_TYPE textureType = fTextureType;
2144 if (format == ScalerContextBits::DW_1) {
2145 renderingMode = DWRITE_RENDERING_MODE_ALIASED;
2146 textureType = DWRITE_TEXTURE_ALIASED_1x1;
2147 }
2148 const void* bits = this->getDWMaskBits(glyph, renderingMode, textureType);
2149 if (!bits) {
2150 sk_bzero(imageBuffer, glyph.imageSize());
2151 return false;
2152 }
2153
2154 //Copy the mask into the glyph.
2155 const uint8_t* src = (const uint8_t*)bits;
2156 if (DWRITE_RENDERING_MODE_ALIASED == renderingMode) {
2157 SkASSERT(SkMask::kBW_Format == glyph.maskFormat());
2158 SkASSERT(DWRITE_TEXTURE_ALIASED_1x1 == textureType);
2159 BilevelToBW(src, glyph, imageBuffer);
2160 } else if (!isLCD(fRec)) {
2161 if (textureType == DWRITE_TEXTURE_ALIASED_1x1) {
2162 if (fPreBlend.isApplicable()) {
2163 GrayscaleToA8<true>(src, glyph, imageBuffer, fPreBlend.fG);
2164 } else {
2165 GrayscaleToA8<false>(src, glyph, imageBuffer, fPreBlend.fG);
2166 }
2167 } else {
2168 if (fPreBlend.isApplicable()) {
2169 RGBToA8<true>(src, glyph, imageBuffer, fPreBlend.fG);
2170 } else {
2171 RGBToA8<false>(src, glyph, imageBuffer, fPreBlend.fG);
2172 }
2173 }
2174 } else {
2175 SkASSERT(SkMask::kLCD16_Format == glyph.maskFormat());
2176 if (fPreBlend.isApplicable()) {
2177 if (fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag) {
2178 RGBToLcd16<true, false>(src, glyph, imageBuffer,
2179 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
2180 } else {
2181 RGBToLcd16<true, true>(src, glyph, imageBuffer,
2182 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
2183 }
2184 } else {
2185 if (fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag) {
2186 RGBToLcd16<false, false>(src, glyph, imageBuffer,
2187 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
2188 } else {
2189 RGBToLcd16<false, true>(src, glyph, imageBuffer,
2190 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
2191 }
2192 }
2193 }
2194 return true;
2195 }
2196
2197 bool SkScalerContext_DW::drawColorImage(const SkGlyph& glyph, SkCanvas& canvas) {
2198 SkTScopedComPtr<IDWriteColorGlyphRunEnumerator> colorLayers;
2199 if (!getColorGlyphRun(glyph, &colorLayers)) {
2200 SkASSERTF(false, "Could not get color layers");
2201 return false;
2202 }
2203
2204 SkPaint paint;
2205 paint.setAntiAlias(fRenderingMode != DWRITE_RENDERING_MODE_ALIASED);
2206
2207 if (this->isSubpixel()) {
2208 canvas.translate(SkFixedToScalar(glyph.getSubXFixed()),
2209 SkFixedToScalar(glyph.getSubYFixed()));
2210 }
2211 canvas.concat(fSkXform);
2212
2213 DWriteFontTypeface* typeface = this->getDWriteTypeface();
2214 size_t paletteEntryCount = typeface->fPaletteEntryCount;
2215 SkColor* palette = typeface->fPalette.get();
2216 BOOL hasNextRun = FALSE;
2217 while (SUCCEEDED(colorLayers->MoveNext(&hasNextRun)) && hasNextRun) {
2218 const DWRITE_COLOR_GLYPH_RUN* colorGlyph;
2219 HRBM(colorLayers->GetCurrentRun(&colorGlyph), "Could not get current color glyph run");
2220
2221 SkColor color;
2222 if (colorGlyph->paletteIndex == 0xffff) {
2223 color = fRec.fForegroundColor;
2224 } else if (colorGlyph->paletteIndex < paletteEntryCount) {
2225 color = palette[colorGlyph->paletteIndex];
2226 } else {
2227 SK_TRACEHR(DWRITE_E_NOCOLOR, "Invalid palette index.");
2228 color = SK_ColorBLACK;
2229 }
2230 paint.setColor(color);
2231
2232 SkPathBuilder builder;
2233 SkTScopedComPtr<IDWriteGeometrySink> geometryToPath;
2234 HRBM(SkDWriteGeometrySink::Create(&builder, &geometryToPath),
2235 "Could not create geometry to path converter.");
2236 {
2237 Exclusive l(maybe_dw_mutex(*this->getDWriteTypeface()));
2238 HRBM(colorGlyph->glyphRun.fontFace->GetGlyphRunOutline(
2239 colorGlyph->glyphRun.fontEmSize,
2240 colorGlyph->glyphRun.glyphIndices,
2241 colorGlyph->glyphRun.glyphAdvances,
2242 colorGlyph->glyphRun.glyphOffsets,
2243 colorGlyph->glyphRun.glyphCount,
2244 colorGlyph->glyphRun.isSideways,
2245 colorGlyph->glyphRun.bidiLevel % 2, //rtl
2246 geometryToPath.get()),
2247 "Could not create glyph outline.");
2248 }
2249 canvas.drawPath(builder.detach(), paint);
2250 }
2251 return true;
2252 }
2253
2254 bool SkScalerContext_DW::generateColorImage(const SkGlyph& glyph, void* imageBuffer) {
2255 SkASSERT(glyph.maskFormat() == SkMask::Format::kARGB32_Format);
2256
2257 SkBitmap dstBitmap;
2258 // TODO: mark this as sRGB when the blits will be sRGB.
2259 dstBitmap.installPixels(
2260 SkImageInfo::Make(glyph.width(), glyph.height(), kN32_SkColorType, kPremul_SkAlphaType),
2261 imageBuffer,
2262 glyph.rowBytes());
2263
2264 SkCanvas canvas(dstBitmap);
2265 if constexpr (kSkShowTextBlitCoverage) {
2266 canvas.clear(0x33FF0000);
2267 } else {
2268 canvas.clear(SK_ColorTRANSPARENT);
2269 }
2270 canvas.translate(-SkIntToScalar(glyph.left()), -SkIntToScalar(glyph.top()));
2271
2272 return this->drawColorImage(glyph, canvas);
2273 }
2274
2275 bool SkScalerContext_DW::drawSVGImage(const SkGlyph& glyph, SkCanvas& canvas) {
2276 DWriteFontTypeface* typeface = this->getDWriteTypeface();
2277 IDWriteFontFace4* fontFace4 = typeface->fDWriteFontFace4.get();
2278 if (!fontFace4) {
2279 return false;
2280 }
2281
2282 DWRITE_GLYPH_IMAGE_FORMATS imageFormats;
2283 HRBM(fontFace4->GetGlyphImageFormats(glyph.getGlyphID(), 0, UINT32_MAX, &imageFormats),
2284 "Cannot get glyph image formats.");
2285 if (!(imageFormats & DWRITE_GLYPH_IMAGE_FORMATS_SVG)) {
2286 return false;
2287 }
2288
2289 SkGraphics::OpenTypeSVGDecoderFactory svgFactory = SkGraphics::GetOpenTypeSVGDecoderFactory();
2290 if (!svgFactory) {
2291 return false;
2292 }
2293
2294 DWRITE_GLYPH_IMAGE_DATA glyphData;
2295 void* glyphDataContext;
2296 HRBM(fontFace4->GetGlyphImageData(glyph.getGlyphID(),
2297 fTextSizeRender,
2298 DWRITE_GLYPH_IMAGE_FORMATS_SVG,
2299 &glyphData,
2300 &glyphDataContext),
2301 "Glyph SVG data could not be acquired.");
2302 auto svgDecoder = svgFactory((const uint8_t*)glyphData.imageData, glyphData.imageDataSize);
2303 fontFace4->ReleaseGlyphImageData(glyphDataContext);
2304 if (!svgDecoder) {
2305 return false;
2306 }
2307
2308 size_t paletteEntryCount = typeface->fPaletteEntryCount;
2309 SkColor* palette = typeface->fPalette.get();
2310 int upem = typeface->getUnitsPerEm();
2311
2312 SkMatrix matrix = fSkXform;
2313 SkScalar scale = fTextSizeRender / upem;
2314 matrix.preScale(scale, scale);
2315 matrix.preTranslate(-glyphData.horizontalLeftOrigin.x, -glyphData.horizontalLeftOrigin.y);
2316 if (this->isSubpixel()) {
2317 matrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
2318 SkFixedToScalar(glyph.getSubYFixed()));
2319 }
2320 canvas.concat(matrix);
2321
2322 return svgDecoder->render(canvas, upem, glyph.getGlyphID(),
2323 fRec.fForegroundColor, SkSpan(palette, paletteEntryCount));
2324 }
2325
2326 bool SkScalerContext_DW::generateSVGImage(const SkGlyph& glyph, void* imageBuffer) {
2327 SkASSERT(glyph.maskFormat() == SkMask::Format::kARGB32_Format);
2328
2329 SkBitmap dstBitmap;
2330 // TODO: mark this as sRGB when the blits will be sRGB.
2331 dstBitmap.installPixels(
2332 SkImageInfo::Make(glyph.width(), glyph.height(), kN32_SkColorType, kPremul_SkAlphaType),
2333 imageBuffer,
2334 glyph.rowBytes());
2335
2336 SkCanvas canvas(dstBitmap);
2337 if constexpr (kSkShowTextBlitCoverage) {
2338 canvas.clear(0x33FF0000);
2339 } else {
2340 canvas.clear(SK_ColorTRANSPARENT);
2341 }
2342 canvas.translate(-SkIntToScalar(glyph.left()), -SkIntToScalar(glyph.top()));
2343
2344 return this->drawSVGImage(glyph, canvas);
2345 }
2346
2347 bool SkScalerContext_DW::drawPngImage(const SkGlyph& glyph, SkCanvas& canvas) {
2348 IDWriteFontFace4* fontFace4 = this->getDWriteTypeface()->fDWriteFontFace4.get();
2349 if (!fontFace4) {
2350 return false;
2351 }
2352
2353 DWRITE_GLYPH_IMAGE_DATA glyphData;
2354 void* glyphDataContext;
2355 HRBM(fontFace4->GetGlyphImageData(glyph.getGlyphID(),
2356 fTextSizeRender,
2357 DWRITE_GLYPH_IMAGE_FORMATS_PNG,
2358 &glyphData,
2359 &glyphDataContext),
2360 "Glyph image data could not be acquired.");
2361 Context* context = new Context(fontFace4, glyphDataContext);
2362 sk_sp<SkData> data = SkData::MakeWithProc(glyphData.imageData,
2363 glyphData.imageDataSize,
2364 &ReleaseProc,
2365 context);
2366 sk_sp<SkImage> image = SkImages::DeferredFromEncodedData(std::move(data));
2367 if (!image) {
2368 check_png();
2369 return false;
2370 }
2371
2372 if (this->isSubpixel()) {
2373 canvas.translate(SkFixedToScalar(glyph.getSubXFixed()),
2374 SkFixedToScalar(glyph.getSubYFixed()));
2375 }
2376 canvas.concat(fSkXform);
2377 SkScalar ratio = fTextSizeRender / glyphData.pixelsPerEm;
2378 canvas.scale(ratio, ratio);
2379 canvas.translate(-glyphData.horizontalLeftOrigin.x, -glyphData.horizontalLeftOrigin.y);
2380 canvas.drawImage(image, 0, 0);
2381 return true;
2382 }
2383
2384 bool SkScalerContext_DW::generatePngImage(const SkGlyph& glyph, void* imageBuffer) {
2385 SkASSERT(glyph.maskFormat() == SkMask::Format::kARGB32_Format);
2386
2387 SkBitmap dstBitmap;
2388 dstBitmap.installPixels(
2389 SkImageInfo::Make(glyph.width(), glyph.height(), kN32_SkColorType, kPremul_SkAlphaType),
2390 imageBuffer,
2391 glyph.rowBytes());
2392
2393 SkCanvas canvas(dstBitmap);
2394 canvas.clear(SK_ColorTRANSPARENT);
2395 canvas.translate(-glyph.left(), -glyph.top());
2396
2397 return this->drawPngImage(glyph, canvas);
2398 }
2399
2400 void SkScalerContext_DW::generateImage(const SkGlyph& glyph, void* imageBuffer) {
2401 ScalerContextBits::value_type format = glyph.extraBits();
2402 if (format == ScalerContextBits::DW ||
2403 format == ScalerContextBits::DW_1)
2404 {
2405 this->generateDWImage(glyph, imageBuffer);
2406 } else if (format == ScalerContextBits::COLRv1) {
2407 this->generateColorV1Image(glyph, imageBuffer);
2408 } else if (format == ScalerContextBits::COLR) {
2409 this->generateColorImage(glyph, imageBuffer);
2410 } else if (format == ScalerContextBits::SVG) {
2411 this->generateSVGImage(glyph, imageBuffer);
2412 } else if (format == ScalerContextBits::PNG) {
2413 this->generatePngImage(glyph, imageBuffer);
2414 } else if (format == ScalerContextBits::PATH) {
2415 this->generateImageFromPath(glyph, imageBuffer);
2416 } else {
2417 SK_ABORT("Bad format");
2418 }
2419 }
2420
2421 std::optional<SkScalerContext::GeneratedPath>
2422 SkScalerContext_DW::generatePath(const SkGlyph& glyph) {
2423 SkGlyphID glyphID = glyph.getGlyphID();
2424
2425 // DirectWrite treats all out of bounds glyph ids as having the same data as glyph 0.
2426 // For consistency with all other backends, treat out of range glyph ids as an error.
2427 if (fGlyphCount <= glyphID) {
2428 return {};
2429 }
2430
2431 SkPathBuilder builder;
2432 SkTScopedComPtr<IDWriteGeometrySink> geometryToPath;
2433 HR_GENERAL(SkDWriteGeometrySink::Create(&builder, &geometryToPath),
2434 "Could not create geometry to path converter.", {});
2435 UINT16 glyphId = SkTo<UINT16>(glyphID);
2436 {
2437 Exclusive l(maybe_dw_mutex(*this->getDWriteTypeface()));
2438 //TODO: convert to<->from DIUs? This would make a difference if hinting.
2439 //It may not be needed, it appears that DirectWrite only hints at em size.
2440 HR_GENERAL(this->getDWriteTypeface()->fDWriteFontFace->GetGlyphRunOutline(
2441 SkScalarToFloat(fTextSizeRender),
2442 &glyphId,
2443 nullptr, //advances
2444 nullptr, //offsets
2445 1, //num glyphs
2446 FALSE, //sideways
2447 FALSE, //rtl
2448 geometryToPath.get()),
2449 "Could not create glyph outline.", {});
2450 }
2451
2452 builder.transform(fSkXform);
2453 return {{builder.detach(), false}};
2454 }
2455
2456 sk_sp<SkDrawable> SkScalerContext_DW::generateDrawable(const SkGlyph& glyph) {
2457 struct GlyphDrawable : public SkDrawable {
2458 SkScalerContext_DW* fSelf;
2459 SkGlyph fGlyph;
2460 GlyphDrawable(SkScalerContext_DW* self, const SkGlyph& glyph) : fSelf(self), fGlyph(glyph){}
2461 SkRect onGetBounds() override { return fGlyph.rect(); }
2462 size_t onApproximateBytesUsed() override { return sizeof(GlyphDrawable); }
2463 void maybeShowTextBlitCoverage(SkCanvas* canvas) {
2464 if constexpr (kSkShowTextBlitCoverage) {
2465 SkPaint paint;
2466 paint.setColor(0x3300FF00);
2467 paint.setStyle(SkPaint::kFill_Style);
2468 canvas->drawRect(this->onGetBounds(), paint);
2469 }
2470 }
2471 };
2472 struct COLRv1GlyphDrawable : public GlyphDrawable {
2473 using GlyphDrawable::GlyphDrawable;
2474 void onDraw(SkCanvas* canvas) override {
2475 this->maybeShowTextBlitCoverage(canvas);
2476 fSelf->drawColorV1Image(fGlyph, *canvas);
2477 }
2478 };
2479 struct COLRGlyphDrawable : public GlyphDrawable {
2480 using GlyphDrawable::GlyphDrawable;
2481 void onDraw(SkCanvas* canvas) override {
2482 this->maybeShowTextBlitCoverage(canvas);
2483 fSelf->drawColorImage(fGlyph, *canvas);
2484 }
2485 };
2486 struct SVGGlyphDrawable : public GlyphDrawable {
2487 using GlyphDrawable::GlyphDrawable;
2488 void onDraw(SkCanvas* canvas) override {
2489 this->maybeShowTextBlitCoverage(canvas);
2490 fSelf->drawSVGImage(fGlyph, *canvas);
2491 }
2492 };
2493 ScalerContextBits::value_type format = glyph.extraBits();
2494 if (format == ScalerContextBits::COLRv1) {
2495 return sk_sp<SkDrawable>(new COLRv1GlyphDrawable(this, glyph));
2496 }
2497 if (format == ScalerContextBits::COLR) {
2498 return sk_sp<SkDrawable>(new COLRGlyphDrawable(this, glyph));
2499 }
2500 if (format == ScalerContextBits::SVG) {
2501 return sk_sp<SkDrawable>(new SVGGlyphDrawable(this, glyph));
2502 }
2503 return nullptr;
2504 }
2505
2506 #endif//defined(SK_BUILD_FOR_WIN)