Debian Codegraph @

src/ports/SkFontHost_FreeType_common.cpp

raw
1 /*
2 * Copyright 2006-2012 The Android Open Source Project
3 * Copyright 2012 Mozilla Foundation
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9 #include "src/ports/SkFontHost_FreeType_common.h"
10
11 #include "include/core/SkBitmap.h"
12 #include "include/core/SkCanvas.h"
13 #include "include/core/SkColor.h"
14 #include "include/core/SkDrawable.h"
15 #include "include/core/SkGraphics.h"
16 #include "include/core/SkImage.h"
17 #include "include/core/SkOpenTypeSVGDecoder.h"
18 #include "include/core/SkPath.h"
19 #include "include/core/SkPathBuilder.h"
20 #include "include/effects/SkGradient.h"
21 #include "include/private/base/SkTo.h"
22 #include "src/core/SkColorData.h"
23 #include "src/core/SkFDot6.h"
24 #include "src/core/SkSwizzlePriv.h"
25 #include "src/core/SkTHash.h"
26
27 #include <algorithm>
28 #include <optional>
29 #include <utility>
30 #include <vector>
31
32 #include <ft2build.h>
33 #include <freetype/freetype.h>
34 #include <freetype/ftbitmap.h>
35 #ifdef FT_COLOR_H
36 # include <freetype/ftcolor.h>
37 #endif
38 #include <freetype/ftimage.h>
39 #include <freetype/ftoutln.h>
40 #include <freetype/ftsizes.h>
41 // In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
42 #include <freetype/ftsynth.h>
43
44 using namespace skia_private;
45
46 namespace {
47 [[maybe_unused]] static inline const constexpr bool kSkShowTextBlitCoverage = false;
48 }
49
50 #if defined(FT_CONFIG_OPTION_SVG)
51 # include <freetype/otsvg.h>
52 #endif
53
54 #ifdef TT_SUPPORT_COLRV1
55 // FT_ClipBox and FT_Get_Color_Glyph_ClipBox introduced VER-2-11-0-18-g47cf8ebf4
56 // FT_COLR_COMPOSITE_PLUS and renumbering introduced VER-2-11-0-21-ge40ae7569
57 // FT_SIZEOF_LONG_LONG introduced VER-2-11-0-31-gffdac8d67
58 // FT_PaintRadialGradient changed size and layout at VER-2-11-0-147-gd3d3ff76d
59 // FT_STATIC_CAST introduced VER-2-11-0-172-g9079c5d91
60 // So undefine TT_SUPPORT_COLRV1 before 2.11.1 but not if FT_STATIC_CAST is defined.
61 #if (((FREETYPE_MAJOR) < 2) || \
62 ((FREETYPE_MAJOR) == 2 && (FREETYPE_MINOR) < 11) || \
63 ((FREETYPE_MAJOR) == 2 && (FREETYPE_MINOR) == 11 && (FREETYPE_PATCH) < 1)) && \
64 !defined(FT_STATIC_CAST)
65 # undef TT_SUPPORT_COLRV1
66 #else
67 # include "src/base/SkScopeExit.h"
68 #endif
69 #endif
70
71 // FT_OUTLINE_OVERLAP was added in FreeType 2.10.3
72 #ifndef FT_OUTLINE_OVERLAP
73 # define FT_OUTLINE_OVERLAP 0x40
74 #endif
75
76 // FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
77 // were introduced in FreeType 2.5.0.
78 // The following may be removed once FreeType 2.5.0 is required to build.
79 #ifndef FT_LOAD_COLOR
80 # define FT_LOAD_COLOR ( 1L << 20 )
81 # define FT_PIXEL_MODE_BGRA 7
82 #endif
83
84 #ifdef SK_DEBUG
85 const char* SkTraceFtrGetError(int e) {
86 switch ((FT_Error)e) {
87 #undef FTERRORS_H_
88 #define FT_ERRORDEF( e, v, s ) case v: return s;
89 #define FT_ERROR_START_LIST
90 #define FT_ERROR_END_LIST
91 #include FT_ERRORS_H
92 #undef FT_ERRORDEF
93 #undef FT_ERROR_START_LIST
94 #undef FT_ERROR_END_LIST
95 default: return "";
96 }
97 }
98 #endif // SK_DEBUG
99
100 #ifdef TT_SUPPORT_COLRV1
101 bool operator==(const FT_OpaquePaint& a, const FT_OpaquePaint& b) {
102 return a.p == b.p && a.insert_root_transform == b.insert_root_transform;
103 }
104
105 // The stop_offset field is being upgraded to a larger representation in FreeType, and changed from
106 // 2.14 to 16.16. Adjust the shift factor depending on size type.
107 static_assert(sizeof(FT_Fixed) != sizeof(FT_F2Dot14));
108 constexpr float kColorStopShift =
109 sizeof(FT_ColorStop::stop_offset) == sizeof(FT_F2Dot14) ? 1 << 14 : 1 << 16;
110 #endif
111
112 namespace {
113 using SkUniqueFTSize = std::unique_ptr<FT_SizeRec, SkFunctionObject<FT_Done_Size>>;
114
115 FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
116 switch (format) {
117 case SkMask::kBW_Format:
118 return FT_PIXEL_MODE_MONO;
119 case SkMask::kA8_Format:
120 default:
121 return FT_PIXEL_MODE_GRAY;
122 }
123 }
124
125 ///////////////////////////////////////////////////////////////////////////////
126
127 uint16_t packTriple(U8CPU r, U8CPU g, U8CPU b) {
128 if constexpr (kSkShowTextBlitCoverage) {
129 r = std::max(r, (U8CPU)0x40);
130 g = std::max(g, (U8CPU)0x40);
131 b = std::max(b, (U8CPU)0x40);
132 }
133 return SkPack888ToRGB16(r, g, b);
134 }
135
136 uint16_t grayToRGB16(U8CPU gray) {
137 if constexpr (kSkShowTextBlitCoverage) {
138 gray = std::max(gray, (U8CPU)0x40);
139 }
140 return SkPack888ToRGB16(gray, gray, gray);
141 }
142
143 int bittst(const uint8_t data[], int bitOffset) {
144 SkASSERT(bitOffset >= 0);
145 int lowBit = data[bitOffset >> 3] >> (~bitOffset & 7);
146 return lowBit & 1;
147 }
148
149 /**
150 * Copies a FT_Bitmap into an SkMask with the same dimensions.
151 *
152 * FT_PIXEL_MODE_MONO
153 * FT_PIXEL_MODE_GRAY
154 * FT_PIXEL_MODE_LCD
155 * FT_PIXEL_MODE_LCD_V
156 */
157 template<bool APPLY_PREBLEND>
158 void copyFT2LCD16(const FT_Bitmap& bitmap, SkMaskBuilder* dstMask, int lcdIsBGR,
159 const uint8_t* tableR, const uint8_t* tableG, const uint8_t* tableB)
160 {
161 SkASSERT(SkMask::kLCD16_Format == dstMask->fFormat);
162 if (FT_PIXEL_MODE_LCD != bitmap.pixel_mode) {
163 SkASSERT(dstMask->fBounds.width() == static_cast<int>(bitmap.width));
164 }
165 if (FT_PIXEL_MODE_LCD_V != bitmap.pixel_mode) {
166 SkASSERT(dstMask->fBounds.height() == static_cast<int>(bitmap.rows));
167 }
168
169 const uint8_t* src = bitmap.buffer;
170 uint16_t* dst = reinterpret_cast<uint16_t*>(dstMask->image());
171 const size_t dstRB = dstMask->fRowBytes;
172
173 const int width = dstMask->fBounds.width();
174 const int height = dstMask->fBounds.height();
175
176 switch (bitmap.pixel_mode) {
177 case FT_PIXEL_MODE_MONO:
178 for (int y = height; y --> 0;) {
179 for (int x = 0; x < width; ++x) {
180 dst[x] = -bittst(src, x);
181 }
182 dst = (uint16_t*)((char*)dst + dstRB);
183 src += bitmap.pitch;
184 }
185 break;
186 case FT_PIXEL_MODE_GRAY:
187 for (int y = height; y --> 0;) {
188 for (int x = 0; x < width; ++x) {
189 dst[x] = grayToRGB16(src[x]);
190 }
191 dst = (uint16_t*)((char*)dst + dstRB);
192 src += bitmap.pitch;
193 }
194 break;
195 case FT_PIXEL_MODE_LCD:
196 SkASSERT(3 * dstMask->fBounds.width() == static_cast<int>(bitmap.width));
197 for (int y = height; y --> 0;) {
198 const uint8_t* triple = src;
199 if (lcdIsBGR) {
200 for (int x = 0; x < width; x++) {
201 dst[x] = packTriple(sk_apply_lut_if<APPLY_PREBLEND>(triple[2], tableR),
202 sk_apply_lut_if<APPLY_PREBLEND>(triple[1], tableG),
203 sk_apply_lut_if<APPLY_PREBLEND>(triple[0], tableB));
204 triple += 3;
205 }
206 } else {
207 for (int x = 0; x < width; x++) {
208 dst[x] = packTriple(sk_apply_lut_if<APPLY_PREBLEND>(triple[0], tableR),
209 sk_apply_lut_if<APPLY_PREBLEND>(triple[1], tableG),
210 sk_apply_lut_if<APPLY_PREBLEND>(triple[2], tableB));
211 triple += 3;
212 }
213 }
214 src += bitmap.pitch;
215 dst = (uint16_t*)((char*)dst + dstRB);
216 }
217 break;
218 case FT_PIXEL_MODE_LCD_V:
219 SkASSERT(3 * dstMask->fBounds.height() == static_cast<int>(bitmap.rows));
220 for (int y = height; y --> 0;) {
221 const uint8_t* srcR = src;
222 const uint8_t* srcG = srcR + bitmap.pitch;
223 const uint8_t* srcB = srcG + bitmap.pitch;
224 if (lcdIsBGR) {
225 using std::swap;
226 swap(srcR, srcB);
227 }
228 for (int x = 0; x < width; x++) {
229 dst[x] = packTriple(sk_apply_lut_if<APPLY_PREBLEND>(*srcR++, tableR),
230 sk_apply_lut_if<APPLY_PREBLEND>(*srcG++, tableG),
231 sk_apply_lut_if<APPLY_PREBLEND>(*srcB++, tableB));
232 }
233 src += 3 * bitmap.pitch;
234 dst = (uint16_t*)((char*)dst + dstRB);
235 }
236 break;
237 default:
238 SkDEBUGF("FT_Pixel_Mode %d", bitmap.pixel_mode);
239 SkDEBUGFAIL("unsupported FT_Pixel_Mode for LCD16");
240 break;
241 }
242 }
243
244 /**
245 * Copies a FT_Bitmap into an SkMask with the same dimensions.
246 *
247 * Yes, No, Never Requested, Never Produced
248 *
249 * kBW kA8 k3D kARGB32 kLCD16
250 * FT_PIXEL_MODE_MONO Y Y NR N Y
251 * FT_PIXEL_MODE_GRAY N Y NR N Y
252 * FT_PIXEL_MODE_GRAY2 NP NP NR NP NP
253 * FT_PIXEL_MODE_GRAY4 NP NP NR NP NP
254 * FT_PIXEL_MODE_LCD NP NP NR NP NP
255 * FT_PIXEL_MODE_LCD_V NP NP NR NP NP
256 * FT_PIXEL_MODE_BGRA N N NR Y N
257 *
258 * TODO: All of these N need to be Y or otherwise ruled out.
259 */
260 void copyFTBitmap(const FT_Bitmap& srcFTBitmap, SkMaskBuilder* dstMask) {
261 SkASSERTF(dstMask->fBounds.width() == static_cast<int>(srcFTBitmap.width),
262 "dstMask.fBounds.width() = %d\n"
263 "static_cast<int>(srcFTBitmap.width) = %d",
264 dstMask->fBounds.width(),
265 static_cast<int>(srcFTBitmap.width)
266 );
267 SkASSERTF(dstMask->fBounds.height() == static_cast<int>(srcFTBitmap.rows),
268 "dstMask.fBounds.height() = %d\n"
269 "static_cast<int>(srcFTBitmap.rows) = %d",
270 dstMask->fBounds.height(),
271 static_cast<int>(srcFTBitmap.rows)
272 );
273
274 const uint8_t* src = reinterpret_cast<const uint8_t*>(srcFTBitmap.buffer);
275 const FT_Pixel_Mode srcFormat = static_cast<FT_Pixel_Mode>(srcFTBitmap.pixel_mode);
276 // FT_Bitmap::pitch is an int and allowed to be negative.
277 const int srcPitch = srcFTBitmap.pitch;
278 const size_t srcRowBytes = SkTAbs(srcPitch);
279
280 uint8_t* dst = dstMask->image();
281 const SkMask::Format dstFormat = dstMask->fFormat;
282 const size_t dstRowBytes = dstMask->fRowBytes;
283
284 const size_t width = srcFTBitmap.width;
285 const size_t height = srcFTBitmap.rows;
286
287 if (SkMask::kLCD16_Format == dstFormat) {
288 copyFT2LCD16<false>(srcFTBitmap, dstMask, false, nullptr, nullptr, nullptr);
289 return;
290 }
291
292 if ((FT_PIXEL_MODE_MONO == srcFormat && SkMask::kBW_Format == dstFormat) ||
293 (FT_PIXEL_MODE_GRAY == srcFormat && SkMask::kA8_Format == dstFormat))
294 {
295 size_t commonRowBytes = std::min(srcRowBytes, dstRowBytes);
296 for (size_t y = height; y --> 0;) {
297 memcpy(dst, src, commonRowBytes);
298 src += srcPitch;
299 dst += dstRowBytes;
300 }
301 } else if (FT_PIXEL_MODE_MONO == srcFormat && SkMask::kA8_Format == dstFormat) {
302 for (size_t y = height; y --> 0;) {
303 uint8_t byte = 0;
304 int bits = 0;
305 const uint8_t* src_row = src;
306 uint8_t* dst_row = dst;
307 for (size_t x = width; x --> 0;) {
308 if (0 == bits) {
309 byte = *src_row++;
310 bits = 8;
311 }
312 *dst_row++ = byte & 0x80 ? 0xff : 0x00;
313 bits--;
314 byte <<= 1;
315 }
316 src += srcPitch;
317 dst += dstRowBytes;
318 }
319 } else if (FT_PIXEL_MODE_BGRA == srcFormat && SkMask::kARGB32_Format == dstFormat) {
320 // FT_PIXEL_MODE_BGRA is pre-multiplied.
321 for (size_t y = height; y --> 0;) {
322 const uint8_t* src_row = src;
323 SkPMColor* dst_row = reinterpret_cast<SkPMColor*>(dst);
324 for (size_t x = 0; x < width; ++x) {
325 uint8_t b = *src_row++;
326 uint8_t g = *src_row++;
327 uint8_t r = *src_row++;
328 uint8_t a = *src_row++;
329 *dst_row++ = SkPackARGB32(a, r, g, b);
330 if constexpr (kSkShowTextBlitCoverage) {
331 *(dst_row-1) = SkFourByteInterp256(*(dst_row-1), SK_ColorWHITE, 0x40);
332 }
333 }
334 src += srcPitch;
335 dst += dstRowBytes;
336 }
337 } else {
338 SkDEBUGF("FT_Pixel_Mode %d, SkMask::Format %d\n", srcFormat, dstFormat);
339 SkDEBUGFAIL("unsupported combination of FT_Pixel_Mode and SkMask::Format");
340 }
341 }
342
343 inline int convert_8_to_1(unsigned byte) {
344 SkASSERT(byte <= 0xFF);
345 // Arbitrary decision that making the cutoff at 1/4 instead of 1/2 in general looks better.
346 return (byte >> 6) != 0;
347 }
348
349 uint8_t pack_8_to_1(const uint8_t alpha[8]) {
350 unsigned bits = 0;
351 for (int i = 0; i < 8; ++i) {
352 bits <<= 1;
353 bits |= convert_8_to_1(alpha[i]);
354 }
355 return SkToU8(bits);
356 }
357
358 void packA8ToA1(SkMaskBuilder* dstMask, const uint8_t* src, size_t srcRB) {
359 const int height = dstMask->fBounds.height();
360 const int width = dstMask->fBounds.width();
361 const int octs = width >> 3;
362 const int leftOverBits = width & 7;
363
364 uint8_t* dst = dstMask->image();
365 const int dstPad = dstMask->fRowBytes - SkAlign8(width)/8;
366 SkASSERT(dstPad >= 0);
367
368 const int srcPad = srcRB - width;
369 SkASSERT(srcPad >= 0);
370
371 for (int y = 0; y < height; ++y) {
372 for (int i = 0; i < octs; ++i) {
373 *dst++ = pack_8_to_1(src);
374 src += 8;
375 }
376 if (leftOverBits > 0) {
377 unsigned bits = 0;
378 int shift = 7;
379 for (int i = 0; i < leftOverBits; ++i, --shift) {
380 bits |= convert_8_to_1(*src++) << shift;
381 }
382 *dst++ = bits;
383 }
384 src += srcPad;
385 dst += dstPad;
386 }
387 }
388
389 inline SkMask::Format SkMaskFormat_for_SkColorType(SkColorType colorType) {
390 switch (colorType) {
391 case kAlpha_8_SkColorType:
392 return SkMask::kA8_Format;
393 case kN32_SkColorType:
394 return SkMask::kARGB32_Format;
395 default:
396 SkDEBUGFAIL("unsupported SkBitmap::Config");
397 return SkMask::kA8_Format;
398 }
399 }
400
401 inline SkColorType SkColorType_for_FTPixelMode(FT_Pixel_Mode pixel_mode) {
402 switch (pixel_mode) {
403 case FT_PIXEL_MODE_MONO:
404 case FT_PIXEL_MODE_GRAY:
405 return kAlpha_8_SkColorType;
406 case FT_PIXEL_MODE_BGRA:
407 return kN32_SkColorType;
408 default:
409 SkDEBUGFAIL("unsupported FT_PIXEL_MODE");
410 return kAlpha_8_SkColorType;
411 }
412 }
413
414 inline SkColorType SkColorType_for_SkMaskFormat(SkMask::Format format) {
415 switch (format) {
416 case SkMask::kBW_Format:
417 case SkMask::kA8_Format:
418 case SkMask::kLCD16_Format:
419 return kAlpha_8_SkColorType;
420 case SkMask::kARGB32_Format:
421 return kN32_SkColorType;
422 default:
423 SkDEBUGFAIL("unsupported destination SkBitmap::Config");
424 return kAlpha_8_SkColorType;
425 }
426 }
427
428 // Only build COLRv1 rendering code if FreeType is new enough to have COLRv1
429 // additions. FreeType defines a macro in the ftoption header to tell us whether
430 // it does support these features.
431 #ifdef TT_SUPPORT_COLRV1
432
433 const uint16_t kForegroundColorPaletteIndex = 0xFFFF;
434
435 // This linear interpolation is used for calculating a truncated color line in special edge cases.
436 // This interpolation needs to be kept in sync with what the gradient shader would normally do when
437 // truncating and drawing color lines. When drawing into N32 surfaces, this is expected to be true.
438 // If that changes, or if we support other color spaces in CPAL tables at some point, this needs to
439 // be looked at.
440 SkColor4f lerpSkColor(SkColor4f c0, SkColor4f c1, float t) {
441 // Due to the floating point calculation in the caller, when interpolating between very narrow
442 // stops, we may get values outside the interpolation range, guard against these.
443 if (t < 0) {
444 return c0;
445 }
446 if (t > 1) {
447 return c1;
448 }
449
450 const auto c0_4f = skvx::float4::Load(c0.vec());
451 const auto c1_4f = skvx::float4::Load(c1.vec());
452 const auto c_4f = c0_4f + (c1_4f - c0_4f) * t;
453
454 SkColor4f l;
455 c_4f.store(l.vec());
456 return l;
457 }
458
459 enum TruncateStops {
460 TruncateStart,
461 TruncateEnd
462 };
463
464 // Truncate a vector of color stops at a previously computed stop position and insert at that
465 // position the color interpolated between the surrounding stops.
466 void truncateToStopInterpolating(SkScalar zeroRadiusStop,
467 std::vector<SkColor4f>& colors,
468 std::vector<SkScalar>& stops,
469 TruncateStops truncateStops) {
470 if (stops.size() <= 1u ||
471 zeroRadiusStop < stops.front() || stops.back() < zeroRadiusStop)
472 {
473 return;
474 }
475
476 size_t afterIndex = (truncateStops == TruncateStart)
477 ? std::lower_bound(stops.begin(), stops.end(), zeroRadiusStop) - stops.begin()
478 : std::upper_bound(stops.begin(), stops.end(), zeroRadiusStop) - stops.begin();
479
480 const float t = (zeroRadiusStop - stops[afterIndex - 1]) /
481 (stops[afterIndex] - stops[afterIndex - 1]);
482 SkColor4f lerpColor = lerpSkColor(colors[afterIndex - 1], colors[afterIndex], t);
483
484 if (truncateStops == TruncateStart) {
485 stops.erase(stops.begin(), stops.begin() + afterIndex);
486 colors.erase(colors.begin(), colors.begin() + afterIndex);
487 stops.insert(stops.begin(), 0);
488 colors.insert(colors.begin(), lerpColor);
489 } else {
490 stops.erase(stops.begin() + afterIndex, stops.end());
491 colors.erase(colors.begin() + afterIndex, colors.end());
492 stops.insert(stops.end(), 1);
493 colors.insert(colors.end(), lerpColor);
494 }
495 }
496
497 struct OpaquePaintHasher {
498 size_t operator()(const FT_OpaquePaint& opaquePaint) {
499 return SkGoodHash()(opaquePaint.p) ^
500 SkGoodHash()(opaquePaint.insert_root_transform);
501 }
502 };
503
504 using VisitedSet = THashSet<FT_OpaquePaint, OpaquePaintHasher>;
505
506 std::optional<SkPath> generateFacePathCOLRv1(FT_Face face, SkGlyphID glyphID,
507 const SkMatrix* = nullptr);
508
509 inline float SkColrV1AlphaToFloat(uint16_t alpha) { return (alpha / float(1 << 14)); }
510
511
512 inline SkTileMode ToSkTileMode(FT_PaintExtend extendMode) {
513 switch (extendMode) {
514 case FT_COLR_PAINT_EXTEND_REPEAT:
515 return SkTileMode::kRepeat;
516 case FT_COLR_PAINT_EXTEND_REFLECT:
517 return SkTileMode::kMirror;
518 default:
519 return SkTileMode::kClamp;
520 }
521 }
522
523 inline SkBlendMode ToSkBlendMode(FT_Composite_Mode compositeMode) {
524 switch (compositeMode) {
525 case FT_COLR_COMPOSITE_CLEAR:
526 return SkBlendMode::kClear;
527 case FT_COLR_COMPOSITE_SRC:
528 return SkBlendMode::kSrc;
529 case FT_COLR_COMPOSITE_DEST:
530 return SkBlendMode::kDst;
531 case FT_COLR_COMPOSITE_SRC_OVER:
532 return SkBlendMode::kSrcOver;
533 case FT_COLR_COMPOSITE_DEST_OVER:
534 return SkBlendMode::kDstOver;
535 case FT_COLR_COMPOSITE_SRC_IN:
536 return SkBlendMode::kSrcIn;
537 case FT_COLR_COMPOSITE_DEST_IN:
538 return SkBlendMode::kDstIn;
539 case FT_COLR_COMPOSITE_SRC_OUT:
540 return SkBlendMode::kSrcOut;
541 case FT_COLR_COMPOSITE_DEST_OUT:
542 return SkBlendMode::kDstOut;
543 case FT_COLR_COMPOSITE_SRC_ATOP:
544 return SkBlendMode::kSrcATop;
545 case FT_COLR_COMPOSITE_DEST_ATOP:
546 return SkBlendMode::kDstATop;
547 case FT_COLR_COMPOSITE_XOR:
548 return SkBlendMode::kXor;
549 case FT_COLR_COMPOSITE_PLUS:
550 return SkBlendMode::kPlus;
551 case FT_COLR_COMPOSITE_SCREEN:
552 return SkBlendMode::kScreen;
553 case FT_COLR_COMPOSITE_OVERLAY:
554 return SkBlendMode::kOverlay;
555 case FT_COLR_COMPOSITE_DARKEN:
556 return SkBlendMode::kDarken;
557 case FT_COLR_COMPOSITE_LIGHTEN:
558 return SkBlendMode::kLighten;
559 case FT_COLR_COMPOSITE_COLOR_DODGE:
560 return SkBlendMode::kColorDodge;
561 case FT_COLR_COMPOSITE_COLOR_BURN:
562 return SkBlendMode::kColorBurn;
563 case FT_COLR_COMPOSITE_HARD_LIGHT:
564 return SkBlendMode::kHardLight;
565 case FT_COLR_COMPOSITE_SOFT_LIGHT:
566 return SkBlendMode::kSoftLight;
567 case FT_COLR_COMPOSITE_DIFFERENCE:
568 return SkBlendMode::kDifference;
569 case FT_COLR_COMPOSITE_EXCLUSION:
570 return SkBlendMode::kExclusion;
571 case FT_COLR_COMPOSITE_MULTIPLY:
572 return SkBlendMode::kMultiply;
573 case FT_COLR_COMPOSITE_HSL_HUE:
574 return SkBlendMode::kHue;
575 case FT_COLR_COMPOSITE_HSL_SATURATION:
576 return SkBlendMode::kSaturation;
577 case FT_COLR_COMPOSITE_HSL_COLOR:
578 return SkBlendMode::kColor;
579 case FT_COLR_COMPOSITE_HSL_LUMINOSITY:
580 return SkBlendMode::kLuminosity;
581 default:
582 return SkBlendMode::kDst;
583 }
584 }
585
586 inline SkMatrix ToSkMatrix(FT_Affine23 affine23) {
587 // Convert from FreeType's FT_Affine23 column major order to SkMatrix row-major order.
588 return SkMatrix::MakeAll(
589 SkFixedToScalar(affine23.xx), -SkFixedToScalar(affine23.xy), SkFixedToScalar(affine23.dx),
590 -SkFixedToScalar(affine23.yx), SkFixedToScalar(affine23.yy), -SkFixedToScalar(affine23.dy),
591 0, 0, 1);
592 }
593
594 inline SkPoint SkVectorProjection(SkPoint a, SkPoint b) {
595 SkScalar length = b.length();
596 if (!length) {
597 return SkPoint();
598 }
599 SkPoint bNormalized = b;
600 bNormalized.normalize();
601 bNormalized.scale(SkPoint::DotProduct(a, b) / length);
602 return bNormalized;
603 }
604
605 bool colrv1_configure_skpaint(FT_Face face,
606 const SkSpan<SkColor>& palette,
607 const SkColor foregroundColor,
608 const FT_COLR_Paint& colrPaint,
609 SkPaint* paint) {
610 auto fetchColorStops = [&face, &palette, &foregroundColor](
611 const FT_ColorStopIterator& colorStopIterator,
612 std::vector<SkScalar>& stops,
613 std::vector<SkColor4f>& colors) -> bool {
614 const FT_UInt colorStopCount = colorStopIterator.num_color_stops;
615 if (colorStopCount == 0) {
616 return false;
617 }
618
619 // 5.7.11.2.4 ColorIndex, ColorStop and ColorLine
620 // "Applications shall apply the colorStops in increasing stopOffset order."
621 struct ColorStop {
622 SkScalar pos;
623 SkColor4f color;
624 };
625 std::vector<ColorStop> colorStopsSorted;
626 colorStopsSorted.resize(colorStopCount);
627
628 FT_ColorStop ftStop;
629 FT_ColorStopIterator mutable_color_stop_iterator = colorStopIterator;
630 while (FT_Get_Colorline_Stops(face, &ftStop, &mutable_color_stop_iterator)) {
631 FT_UInt index = mutable_color_stop_iterator.current_color_stop - 1;
632 ColorStop& skStop = colorStopsSorted[index];
633 skStop.pos = ftStop.stop_offset / kColorStopShift;
634 FT_UInt16& palette_index = ftStop.color.palette_index;
635 if (palette_index == kForegroundColorPaletteIndex) {
636 skStop.color = SkColor4f::FromColor(foregroundColor);
637 } else if (palette_index >= palette.size()) {
638 return false;
639 } else {
640 skStop.color = SkColor4f::FromColor(palette[palette_index]);
641 }
642 skStop.color.fA *= SkColrV1AlphaToFloat(ftStop.color.alpha);
643 }
644
645 std::stable_sort(colorStopsSorted.begin(), colorStopsSorted.end(),
646 [](const ColorStop& a, const ColorStop& b) { return a.pos < b.pos; });
647
648 stops.resize(colorStopCount);
649 colors.resize(colorStopCount);
650 for (size_t i = 0; i < colorStopCount; ++i) {
651 stops[i] = colorStopsSorted[i].pos;
652 colors[i] = colorStopsSorted[i].color;
653 }
654 return true;
655 };
656
657 switch (colrPaint.format) {
658 case FT_COLR_PAINTFORMAT_SOLID: {
659 FT_PaintSolid solid = colrPaint.u.solid;
660
661 // Dont' draw anything with this color if the palette index is out of bounds.
662 SkColor4f color = SkColors::kTransparent;
663 if (solid.color.palette_index == kForegroundColorPaletteIndex) {
664 color = SkColor4f::FromColor(foregroundColor);
665 } else if (solid.color.palette_index >= palette.size()) {
666 return false;
667 } else {
668 color = SkColor4f::FromColor(palette[solid.color.palette_index]);
669 }
670 color.fA *= SkColrV1AlphaToFloat(solid.color.alpha);
671 paint->setShader(nullptr);
672 paint->setColor(color);
673 return true;
674 }
675 case FT_COLR_PAINTFORMAT_LINEAR_GRADIENT: {
676 const FT_PaintLinearGradient& linearGradient = colrPaint.u.linear_gradient;
677 std::vector<SkScalar> stops;
678 std::vector<SkColor4f> colors;
679
680 if (!fetchColorStops(linearGradient.colorline.color_stop_iterator, stops, colors)) {
681 return false;
682 }
683
684 if (stops.size() == 1) {
685 paint->setColor(colors[0]);
686 return true;
687 }
688
689 SkPoint linePositions[2] = {SkPoint::Make( SkFixedToScalar(linearGradient.p0.x),
690 -SkFixedToScalar(linearGradient.p0.y)),
691 SkPoint::Make( SkFixedToScalar(linearGradient.p1.x),
692 -SkFixedToScalar(linearGradient.p1.y))};
693 SkPoint p0 = linePositions[0];
694 SkPoint p1 = linePositions[1];
695 SkPoint p2 = SkPoint::Make( SkFixedToScalar(linearGradient.p2.x),
696 -SkFixedToScalar(linearGradient.p2.y));
697
698 // If p0p1 or p0p2 are degenerate probably nothing should be drawn.
699 // If p0p1 and p0p2 are parallel then one side is the first color and the other side is
700 // the last color, depending on the direction.
701 // For now, just use the first color.
702 if (p1 == p0 || p2 == p0 || !SkPoint::CrossProduct(p1 - p0, p2 - p0)) {
703 paint->setColor(colors[0]);
704 return true;
705 }
706
707 // Follow implementation note in nanoemoji:
708 // https://github.com/googlefonts/nanoemoji/blob/0ac6e7bb4d8202db692574d8530a9b643f1b3b3c/src/nanoemoji/svg.py#L188
709 // to compute a new gradient end point P3 as the orthogonal
710 // projection of the vector from p0 to p1 onto a line perpendicular
711 // to line p0p2 and passing through p0.
712 SkVector perpendicularToP2P0 = (p2 - p0);
713 perpendicularToP2P0 = SkPoint::Make( perpendicularToP2P0.y(),
714 -perpendicularToP2P0.x());
715 SkVector p3 = p0 + SkVectorProjection((p1 - p0), perpendicularToP2P0);
716 linePositions[1] = p3;
717
718 // Project/scale points according to stop extrema along p0p3 line,
719 // p3 being the result of the projection above, then scale stops to
720 // to [0, 1] range so that repeat modes work. The Skia linear
721 // gradient shader performs the repeat modes over the 0 to 1 range,
722 // that's why we need to scale the stops to within that range.
723 SkTileMode tileMode = ToSkTileMode(linearGradient.colorline.extend);
724 SkScalar colorStopRange = stops.back() - stops.front();
725 // If the color stops are all at the same offset position, repeat and reflect modes
726 // become meaningless.
727 if (colorStopRange == 0.f) {
728 if (tileMode != SkTileMode::kClamp) {
729 paint->setColor(SK_ColorTRANSPARENT);
730 return true;
731 } else {
732 // Insert duplicated fake color stop in pad case at +1.0f to enable the projection
733 // of circles for an originally 0-length color stop range. Adding this stop will
734 // paint the equivalent gradient, because: All font specified color stops are in the
735 // same spot, mode is pad, so everything before this spot is painted with the first
736 // color, everything after this spot is painted with the last color. Not adding this
737 // stop will skip the projection and result in specifying non-normalized color stops
738 // to the shader.
739 stops.push_back(stops.back() + 1.0f);
740 colors.push_back(colors.back());
741 colorStopRange = 1.0f;
742 }
743 }
744 SkASSERT(colorStopRange != 0.f);
745
746 // If the colorStopRange is 0 at this point, the default behavior of the shader is to
747 // clamp to 1 color stops that are above 1, clamp to 0 for color stops that are below 0,
748 // and repeat the outer color stops at 0 and 1 if the color stops are inside the
749 // range. That will result in the correct rendering.
750 if ((colorStopRange != 1 || stops.front() != 0.f)) {
751 SkVector p0p3 = p3 - p0;
752 SkVector p0Offset = p0p3;
753 p0Offset.scale(stops.front());
754 SkVector p1Offset = p0p3;
755 p1Offset.scale(stops.back());
756
757 linePositions[0] = p0 + p0Offset;
758 linePositions[1] = p0 + p1Offset;
759
760 SkScalar scaleFactor = 1 / colorStopRange;
761 SkScalar startOffset = stops.front();
762 for (SkScalar& stop : stops) {
763 stop = (stop - startOffset) * scaleFactor;
764 }
765 }
766
767 sk_sp<SkShader> shader(SkShaders::LinearGradient(
768 linePositions,
769 {{colors, stops, tileMode, SkColorSpace::MakeSRGB()},
770 SkGradient::Interpolation{
771 SkGradient::Interpolation::InPremul::kNo,
772 SkGradient::Interpolation::ColorSpace::kSRGB,
773 SkGradient::Interpolation::HueMethod::kShorter
774 }}));
775
776 SkASSERT(shader);
777 // An opaque color is needed to ensure the gradient is not modulated by alpha.
778 paint->setColor(SK_ColorBLACK);
779 paint->setShader(shader);
780 return true;
781 }
782 case FT_COLR_PAINTFORMAT_RADIAL_GRADIENT: {
783 const FT_PaintRadialGradient& radialGradient = colrPaint.u.radial_gradient;
784 SkPoint start = SkPoint::Make( SkFixedToScalar(radialGradient.c0.x),
785 -SkFixedToScalar(radialGradient.c0.y));
786 SkScalar startRadius = SkFixedToScalar(radialGradient.r0);
787 SkPoint end = SkPoint::Make( SkFixedToScalar(radialGradient.c1.x),
788 -SkFixedToScalar(radialGradient.c1.y));
789 SkScalar endRadius = SkFixedToScalar(radialGradient.r1);
790
791
792 std::vector<SkScalar> stops;
793 std::vector<SkColor4f> colors;
794 if (!fetchColorStops(radialGradient.colorline.color_stop_iterator, stops, colors)) {
795 return false;
796 }
797
798 if (stops.size() == 1) {
799 paint->setColor(colors[0]);
800 return true;
801 }
802
803 SkScalar colorStopRange = stops.back() - stops.front();
804 SkTileMode tileMode = ToSkTileMode(radialGradient.colorline.extend);
805
806 if (colorStopRange == 0.f) {
807 if (tileMode != SkTileMode::kClamp) {
808 paint->setColor(SK_ColorTRANSPARENT);
809 return true;
810 } else {
811 // Insert duplicated fake color stop in pad case at +1.0f to enable the projection
812 // of circles for an originally 0-length color stop range. Adding this stop will
813 // paint the equivalent gradient, because: All font specified color stops are in the
814 // same spot, mode is pad, so everything before this spot is painted with the first
815 // color, everything after this spot is painted with the last color. Not adding this
816 // stop will skip the projection and result in specifying non-normalized color stops
817 // to the shader.
818 stops.push_back(stops.back() + 1.0f);
819 colors.push_back(colors.back());
820 colorStopRange = 1.0f;
821 }
822 }
823 SkASSERT(colorStopRange != 0.f);
824
825 // If the colorStopRange is 0 at this point, the default behavior of the shader is to
826 // clamp to 1 color stops that are above 1, clamp to 0 for color stops that are below 0,
827 // and repeat the outer color stops at 0 and 1 if the color stops are inside the
828 // range. That will result in the correct rendering.
829 if (colorStopRange != 1 || stops.front() != 0.f) {
830 // For the Skia two-point caonical shader to understand the
831 // COLRv1 color stops we need to scale stops to 0 to 1 range and
832 // interpolate new centers and radii. Otherwise the shader
833 // clamps stops outside the range to 0 and 1 (larger interval)
834 // or repeats the outer stops at 0 and 1 if the (smaller
835 // interval).
836 SkVector startToEnd = end - start;
837 SkScalar radiusDiff = endRadius - startRadius;
838 SkScalar scaleFactor = 1 / colorStopRange;
839 SkScalar stopsStartOffset = stops.front();
840
841 SkVector startOffset = startToEnd;
842 startOffset.scale(stops.front());
843 SkVector endOffset = startToEnd;
844 endOffset.scale(stops.back());
845
846 // The order of the following computations is important in order to avoid
847 // overwriting start or startRadius before the second reassignment.
848 end = start + endOffset;
849 start = start + startOffset;
850 endRadius = startRadius + radiusDiff * stops.back();
851 startRadius = startRadius + radiusDiff * stops.front();
852
853 for (auto& stop : stops) {
854 stop = (stop - stopsStartOffset) * scaleFactor;
855 }
856 }
857
858 // For negative radii, interpolation is needed to prepare parameters suitable
859 // for invoking the shader. Implementation below as resolution discussed in
860 // https://github.com/googlefonts/colr-gradients-spec/issues/367.
861 // Truncate to manually interpolated color for tile mode clamp, otherwise
862 // calculate positive projected circles.
863 if (startRadius < 0 || endRadius < 0) {
864 if (startRadius == endRadius && startRadius < 0) {
865 paint->setColor(SK_ColorTRANSPARENT);
866 return true;
867 }
868
869 if (tileMode == SkTileMode::kClamp) {
870 SkVector startToEnd = end - start;
871 SkScalar radiusDiff = endRadius - startRadius;
872 SkScalar zeroRadiusStop = 0.f;
873 TruncateStops truncateSide = TruncateStart;
874 if (startRadius < 0) {
875 truncateSide = TruncateStart;
876
877 // Compute color stop position where radius is = 0. After the scaling
878 // of stop positions to the normal 0,1 range that we have done above,
879 // the size of the radius as a function of the color stops is: r(x) = r0
880 // + x*(r1-r0) Solving this function for r(x) = 0, we get: x = -r0 /
881 // (r1-r0)
882 zeroRadiusStop = -startRadius / (endRadius - startRadius);
883 startRadius = 0.f;
884 SkVector startEndDiff = end - start;
885 startEndDiff.scale(zeroRadiusStop);
886 start = start + startEndDiff;
887 }
888
889 if (endRadius < 0) {
890 truncateSide = TruncateEnd;
891 zeroRadiusStop = -startRadius / (endRadius - startRadius);
892 endRadius = 0.f;
893 SkVector startEndDiff = end - start;
894 startEndDiff.scale(1 - zeroRadiusStop);
895 end = end - startEndDiff;
896 }
897
898 if (!(startRadius == 0 && endRadius == 0)) {
899 truncateToStopInterpolating(
900 zeroRadiusStop, colors, stops, truncateSide);
901 } else {
902 // If both radii have become negative and where clamped to 0, we need to
903 // produce a single color cone, otherwise the shader colors the whole
904 // plane in a single color when two radii are specified as 0.
905 if (radiusDiff > 0) {
906 end = start + startToEnd;
907 endRadius = radiusDiff;
908 colors.erase(colors.begin(), colors.end() - 1);
909 stops.erase(stops.begin(), stops.end() - 1);
910 } else {
911 start -= startToEnd;
912 startRadius = -radiusDiff;
913 colors.erase(colors.begin() + 1, colors.end());
914 stops.erase(stops.begin() + 1, stops.end());
915 }
916 }
917 } else {
918 if (startRadius < 0 || endRadius < 0) {
919 auto roundIntegerMultiple = [](SkScalar factorZeroCrossing,
920 SkTileMode tileMode) {
921 int roundedMultiple = factorZeroCrossing > 0
922 ? ceilf(factorZeroCrossing)
923 : floorf(factorZeroCrossing) - 1;
924 if (tileMode == SkTileMode::kMirror && roundedMultiple % 2 != 0) {
925 roundedMultiple += roundedMultiple < 0 ? -1 : 1;
926 }
927 return roundedMultiple;
928 };
929
930 SkVector startToEnd = end - start;
931 SkScalar radiusDiff = endRadius - startRadius;
932 SkScalar factorZeroCrossing = (startRadius / (startRadius - endRadius));
933 bool inRange = 0.f <= factorZeroCrossing && factorZeroCrossing <= 1.0f;
934 SkScalar direction = inRange && radiusDiff < 0 ? -1.0f : 1.0f;
935 SkScalar circleProjectionFactor =
936 roundIntegerMultiple(factorZeroCrossing * direction, tileMode);
937 startToEnd.scale(circleProjectionFactor);
938 startRadius += circleProjectionFactor * radiusDiff;
939 endRadius += circleProjectionFactor * radiusDiff;
940 start += startToEnd;
941 end += startToEnd;
942 }
943 }
944 }
945
946 // An opaque color is needed to ensure the gradient is not modulated by alpha.
947 paint->setColor(SK_ColorBLACK);
948
949 paint->setShader(SkShaders::TwoPointConicalGradient(
950 start, startRadius, end, endRadius,
951 {{colors, stops, tileMode, SkColorSpace::MakeSRGB()},
952 SkGradient::Interpolation{
953 SkGradient::Interpolation::InPremul::kNo,
954 SkGradient::Interpolation::ColorSpace::kSRGB,
955 SkGradient::Interpolation::HueMethod::kShorter
956 }},
957 nullptr));
958
959 return true;
960 }
961 case FT_COLR_PAINTFORMAT_SWEEP_GRADIENT: {
962 const FT_PaintSweepGradient& sweepGradient = colrPaint.u.sweep_gradient;
963 SkPoint center = SkPoint::Make( SkFixedToScalar(sweepGradient.center.x),
964 -SkFixedToScalar(sweepGradient.center.y));
965
966
967 SkScalar startAngle = SkFixedToScalar(sweepGradient.start_angle * 180.0f);
968 SkScalar endAngle = SkFixedToScalar(sweepGradient.end_angle * 180.0f);
969 // OpenType 1.9.1 adds a shift to the angle to ease specification of a 0 to 360
970 // degree sweep.
971 startAngle += 180.0f;
972 endAngle += 180.0f;
973
974 std::vector<SkScalar> stops;
975 std::vector<SkColor4f> colors;
976 if (!fetchColorStops(sweepGradient.colorline.color_stop_iterator, stops, colors)) {
977 return false;
978 }
979
980 if (stops.size() == 1) {
981 paint->setColor(colors[0]);
982 return true;
983 }
984
985 // An opaque color is needed to ensure the gradient is not modulated by alpha.
986 paint->setColor(SK_ColorBLACK);
987
988 // New (Var)SweepGradient implementation compliant with OpenType 1.9.1 from here.
989
990 // The shader expects stops from 0 to 1, so we need to account for
991 // minimum and maximum stop positions being different from 0 and
992 // 1. We do that by scaling minimum and maximum stop positions to
993 // the 0 to 1 interval and scaling the angles inverse proportionally.
994
995 // 1) Scale angles to their equivalent positions if stops were from 0 to 1.
996
997 SkScalar sectorAngle = endAngle - startAngle;
998 SkTileMode tileMode = ToSkTileMode(sweepGradient.colorline.extend);
999 if (sectorAngle == 0 && tileMode != SkTileMode::kClamp) {
1000 // "If the ColorLine's extend mode is reflect or repeat and start and end angle
1001 // are equal, nothing is drawn.".
1002 paint->setColor(SK_ColorTRANSPARENT);
1003 return true;
1004 }
1005
1006
1007 SkScalar startAngleScaled = startAngle + sectorAngle * stops.front();
1008 SkScalar endAngleScaled = startAngle + sectorAngle * stops.back();
1009
1010 // 2) Scale stops accordingly to 0 to 1 range.
1011
1012 float colorStopRange = stops.back() - stops.front();
1013 if (colorStopRange == 0.f) {
1014 if (tileMode != SkTileMode::kClamp) {
1015 paint->setColor(SK_ColorTRANSPARENT);
1016 return true;
1017 } else {
1018 // Insert duplicated fake color stop in pad case at +1.0f to feed the shader correct
1019 // values and enable painting a pad sweep gradient with two colors. Adding this stop
1020 // will paint the equivalent gradient, because: All font specified color stops are
1021 // in the same spot, mode is pad, so everything before this spot is painted with the
1022 // first color, everything after this spot is painted with the last color. Not
1023 // adding this stop will skip the projection and result in specifying non-normalized
1024 // color stops to the shader.
1025 stops.push_back(stops.back() + 1.0f);
1026 colors.push_back(colors.back());
1027 colorStopRange = 1.0f;
1028 }
1029 }
1030
1031 SkScalar scaleFactor = 1 / colorStopRange;
1032 SkScalar startOffset = stops.front();
1033
1034 for (SkScalar& stop : stops) {
1035 stop = (stop - startOffset) * scaleFactor;
1036 }
1037
1038 /* https://docs.microsoft.com/en-us/typography/opentype/spec/colr#sweep-gradients
1039 * "The angles are expressed in counter-clockwise degrees from
1040 * the direction of the positive x-axis on the design
1041 * grid. [...] The color line progresses from the start angle
1042 * to the end angle in the counter-clockwise direction;" -
1043 * Convert angles and stops from counter-clockwise to clockwise
1044 * for the shader if the gradient is not already reversed due to
1045 * start angle being larger than end angle. */
1046 startAngleScaled = 360.f - startAngleScaled;
1047 endAngleScaled = 360.f - endAngleScaled;
1048 if (startAngleScaled >= endAngleScaled) {
1049 std::swap(startAngleScaled, endAngleScaled);
1050 std::reverse(stops.begin(), stops.end());
1051 std::reverse(colors.begin(), colors.end());
1052 for (auto& stop : stops) {
1053 stop = 1.0f - stop;
1054 }
1055 }
1056
1057 paint->setShader(SkShaders::SweepGradient(
1058 center, startAngleScaled, endAngleScaled,
1059 {{colors, stops, tileMode, SkColorSpace::MakeSRGB()},
1060 {
1061 SkGradient::Interpolation::InPremul::kNo,
1062 SkGradient::Interpolation::ColorSpace::kSRGB,
1063 SkGradient::Interpolation::HueMethod::kShorter
1064 }},
1065 nullptr));
1066
1067 return true;
1068 }
1069 default: {
1070 SkASSERT(false);
1071 return false;
1072 }
1073 }
1074 SkUNREACHABLE;
1075 }
1076
1077 bool colrv1_draw_paint(SkCanvas* canvas,
1078 const SkSpan<SkColor>& palette,
1079 const SkColor foregroundColor,
1080 FT_Face face,
1081 const FT_COLR_Paint& colrPaint) {
1082 switch (colrPaint.format) {
1083 case FT_COLR_PAINTFORMAT_GLYPH: {
1084 auto path = generateFacePathCOLRv1(face, colrPaint.u.glyph.glyphID);
1085 if (!path) {
1086 return false;
1087 }
1088 if constexpr (kSkShowTextBlitCoverage) {
1089 SkPaint highlight_paint;
1090 highlight_paint.setColor(0x33FF0000);
1091 canvas->drawRect(path->getBounds(), highlight_paint);
1092 }
1093 canvas->clipPath(*path, true /* doAntiAlias */);
1094 return true;
1095 }
1096 case FT_COLR_PAINTFORMAT_SOLID:
1097 case FT_COLR_PAINTFORMAT_LINEAR_GRADIENT:
1098 case FT_COLR_PAINTFORMAT_RADIAL_GRADIENT:
1099 case FT_COLR_PAINTFORMAT_SWEEP_GRADIENT: {
1100 SkPaint skPaint;
1101 if (!colrv1_configure_skpaint(face, palette, foregroundColor, colrPaint, &skPaint)) {
1102 return false;
1103 }
1104 canvas->drawPaint(skPaint);
1105 return true;
1106 }
1107 case FT_COLR_PAINTFORMAT_TRANSFORM:
1108 case FT_COLR_PAINTFORMAT_TRANSLATE:
1109 case FT_COLR_PAINTFORMAT_SCALE:
1110 case FT_COLR_PAINTFORMAT_ROTATE:
1111 case FT_COLR_PAINTFORMAT_SKEW:
1112 [[fallthrough]]; // Transforms handled in colrv1_transform.
1113 default:
1114 SkASSERT(false);
1115 return false;
1116 }
1117 SkUNREACHABLE;
1118 }
1119
1120 bool colrv1_draw_glyph_with_path(SkCanvas* canvas,
1121 const SkSpan<SkColor>& palette, SkColor foregroundColor,
1122 FT_Face face,
1123 const FT_COLR_Paint& glyphPaint, const FT_COLR_Paint& fillPaint) {
1124 SkASSERT(glyphPaint.format == FT_COLR_PAINTFORMAT_GLYPH);
1125 SkASSERT(fillPaint.format == FT_COLR_PAINTFORMAT_SOLID ||
1126 fillPaint.format == FT_COLR_PAINTFORMAT_LINEAR_GRADIENT ||
1127 fillPaint.format == FT_COLR_PAINTFORMAT_RADIAL_GRADIENT ||
1128 fillPaint.format == FT_COLR_PAINTFORMAT_SWEEP_GRADIENT);
1129
1130 SkPaint skiaFillPaint;
1131 skiaFillPaint.setAntiAlias(true);
1132 if (!colrv1_configure_skpaint(face, palette, foregroundColor, fillPaint, &skiaFillPaint)) {
1133 return false;
1134 }
1135
1136 auto path = generateFacePathCOLRv1(face, glyphPaint.u.glyph.glyphID);
1137 if (!path) {
1138 return false;
1139 }
1140 if constexpr (kSkShowTextBlitCoverage) {
1141 SkPaint highlightPaint;
1142 highlightPaint.setColor(0x33FF0000);
1143 canvas->drawRect(path->getBounds(), highlightPaint);
1144 }
1145 canvas->drawPath(*path, skiaFillPaint);
1146 return true;
1147 }
1148
1149
1150 /* In drawing mode, concatenates the transforms directly on SkCanvas. In
1151 * bounding box calculation mode, no SkCanvas is specified, but we only want to
1152 * retrieve the transform from the FreeType paint object. */
1153 void colrv1_transform(FT_Face face,
1154 const FT_COLR_Paint& colrPaint,
1155 SkCanvas* canvas,
1156 SkMatrix* outTransform = nullptr) {
1157 SkMatrix transform;
1158
1159 SkASSERT(canvas || outTransform);
1160
1161 switch (colrPaint.format) {
1162 case FT_COLR_PAINTFORMAT_TRANSFORM: {
1163 transform = ToSkMatrix(colrPaint.u.transform.affine);
1164 break;
1165 }
1166 case FT_COLR_PAINTFORMAT_TRANSLATE: {
1167 transform = SkMatrix::Translate( SkFixedToScalar(colrPaint.u.translate.dx),
1168 -SkFixedToScalar(colrPaint.u.translate.dy));
1169 break;
1170 }
1171 case FT_COLR_PAINTFORMAT_SCALE: {
1172 transform.setScale( SkFixedToScalar(colrPaint.u.scale.scale_x),
1173 SkFixedToScalar(colrPaint.u.scale.scale_y),
1174 SkFixedToScalar(colrPaint.u.scale.center_x),
1175 -SkFixedToScalar(colrPaint.u.scale.center_y));
1176 break;
1177 }
1178 case FT_COLR_PAINTFORMAT_ROTATE: {
1179 // COLRv1 angles are counter-clockwise, compare
1180 // https://docs.microsoft.com/en-us/typography/opentype/spec/colr#formats-24-to-27-paintrotate-paintvarrotate-paintrotatearoundcenter-paintvarrotatearoundcenter
1181 transform = SkMatrix::RotateDeg(
1182 -SkFixedToScalar(colrPaint.u.rotate.angle) * 180.0f,
1183 SkPoint::Make( SkFixedToScalar(colrPaint.u.rotate.center_x),
1184 -SkFixedToScalar(colrPaint.u.rotate.center_y)));
1185 break;
1186 }
1187 case FT_COLR_PAINTFORMAT_SKEW: {
1188 // In the PAINTFORMAT_ROTATE implementation, SkMatrix setRotate
1189 // snaps to 0 for values very close to 0. Do the same here.
1190
1191 SkScalar xDeg = SkFixedToScalar(colrPaint.u.skew.x_skew_angle) * 180.0f;
1192 SkScalar xRad = SkDegreesToRadians(xDeg);
1193 SkScalar xTan = SkScalarTan(xRad);
1194 xTan = SkScalarNearlyZero(xTan) ? 0.0f : xTan;
1195
1196 SkScalar yDeg = SkFixedToScalar(colrPaint.u.skew.y_skew_angle) * 180.0f;
1197 // Negate y_skew_angle due to Skia's y-down coordinate system to achieve
1198 // counter-clockwise skew along the y-axis.
1199 SkScalar yRad = SkDegreesToRadians(-yDeg);
1200 SkScalar yTan = SkScalarTan(yRad);
1201 yTan = SkScalarNearlyZero(yTan) ? 0.0f : yTan;
1202
1203 transform.setSkew(xTan, yTan,
1204 SkFixedToScalar(colrPaint.u.skew.center_x),
1205 -SkFixedToScalar(colrPaint.u.skew.center_y));
1206 break;
1207 }
1208 default: {
1209 SkASSERT(false); // Only transforms are handled in this function.
1210 }
1211 }
1212 if (canvas) {
1213 canvas->concat(transform);
1214 }
1215 if (outTransform) {
1216 *outTransform = transform;
1217 }
1218 }
1219
1220 bool colrv1_start_glyph(SkCanvas* canvas,
1221 const SkSpan<SkColor>& palette,
1222 SkColor foregroundColor,
1223 FT_Face face,
1224 SkGlyphID glyphId,
1225 FT_Color_Root_Transform rootTransform,
1226 VisitedSet* activePaints);
1227
1228 bool colrv1_traverse_paint(SkCanvas* canvas,
1229 const SkSpan<SkColor>& palette,
1230 const SkColor foregroundColor,
1231 FT_Face face,
1232 FT_OpaquePaint opaquePaint,
1233 VisitedSet* activePaints) {
1234 // Cycle detection, see section "5.7.11.1.9 Color glyphs as a directed acyclic graph".
1235 if (activePaints->contains(opaquePaint)) {
1236 return true;
1237 }
1238
1239 activePaints->add(opaquePaint);
1240 SK_AT_SCOPE_EXIT(activePaints->remove(opaquePaint));
1241
1242 FT_COLR_Paint paint;
1243 if (!FT_Get_Paint(face, opaquePaint, &paint)) {
1244 return false;
1245 }
1246
1247 SkAutoCanvasRestore autoRestore(canvas, true /* doSave */);
1248 switch (paint.format) {
1249 case FT_COLR_PAINTFORMAT_COLR_LAYERS: {
1250 FT_LayerIterator& layerIterator = paint.u.colr_layers.layer_iterator;
1251 FT_OpaquePaint layerPaint{nullptr, 1};
1252 while (FT_Get_Paint_Layers(face, &layerIterator, &layerPaint)) {
1253 if (!colrv1_traverse_paint(canvas, palette, foregroundColor, face,
1254 layerPaint, activePaints)) {
1255 return false;
1256 }
1257 }
1258 return true;
1259 }
1260 case FT_COLR_PAINTFORMAT_GLYPH:
1261 // Special case paint graph leaf situations to improve
1262 // performance. These are situations in the graph where a GlyphPaint
1263 // is followed by either a solid or a gradient fill. Here we can use
1264 // drawPath() + SkPaint directly which is faster than setting a
1265 // clipPath() followed by a drawPaint().
1266 FT_COLR_Paint fillPaint;
1267 if (!FT_Get_Paint(face, paint.u.glyph.paint, &fillPaint)) {
1268 return false;
1269 }
1270 if (fillPaint.format == FT_COLR_PAINTFORMAT_SOLID ||
1271 fillPaint.format == FT_COLR_PAINTFORMAT_LINEAR_GRADIENT ||
1272 fillPaint.format == FT_COLR_PAINTFORMAT_RADIAL_GRADIENT ||
1273 fillPaint.format == FT_COLR_PAINTFORMAT_SWEEP_GRADIENT)
1274 {
1275 return colrv1_draw_glyph_with_path(canvas, palette, foregroundColor,
1276 face, paint, fillPaint);
1277 }
1278 if (!colrv1_draw_paint(canvas, palette, foregroundColor, face, paint)) {
1279 return false;
1280 }
1281 return colrv1_traverse_paint(canvas, palette, foregroundColor,
1282 face, paint.u.glyph.paint, activePaints);
1283 case FT_COLR_PAINTFORMAT_COLR_GLYPH:
1284 return colrv1_start_glyph(canvas, palette, foregroundColor,
1285 face, paint.u.colr_glyph.glyphID, FT_COLOR_NO_ROOT_TRANSFORM,
1286 activePaints);
1287 case FT_COLR_PAINTFORMAT_TRANSFORM:
1288 colrv1_transform(face, paint, canvas);
1289 return colrv1_traverse_paint(canvas, palette, foregroundColor,
1290 face, paint.u.transform.paint, activePaints);
1291 case FT_COLR_PAINTFORMAT_TRANSLATE:
1292 colrv1_transform(face, paint, canvas);
1293 return colrv1_traverse_paint(canvas, palette, foregroundColor,
1294 face, paint.u.translate.paint, activePaints);
1295 case FT_COLR_PAINTFORMAT_SCALE:
1296 colrv1_transform(face, paint, canvas);
1297 return colrv1_traverse_paint(canvas, palette, foregroundColor,
1298 face, paint.u.scale.paint, activePaints);
1299 case FT_COLR_PAINTFORMAT_ROTATE:
1300 colrv1_transform(face, paint, canvas);
1301 return colrv1_traverse_paint(canvas, palette, foregroundColor,
1302 face, paint.u.rotate.paint, activePaints);
1303 case FT_COLR_PAINTFORMAT_SKEW:
1304 colrv1_transform(face, paint, canvas);
1305 return colrv1_traverse_paint(canvas, palette, foregroundColor,
1306 face, paint.u.skew.paint, activePaints);
1307 case FT_COLR_PAINTFORMAT_COMPOSITE: {
1308 SkAutoCanvasRestore acr(canvas, false);
1309 canvas->saveLayer(nullptr, nullptr);
1310 if (!colrv1_traverse_paint(canvas, palette, foregroundColor,
1311 face, paint.u.composite.backdrop_paint, activePaints)) {
1312 return false;
1313 }
1314 SkPaint blendModePaint;
1315 blendModePaint.setBlendMode(ToSkBlendMode(paint.u.composite.composite_mode));
1316 canvas->saveLayer(nullptr, &blendModePaint);
1317 return colrv1_traverse_paint(canvas, palette, foregroundColor,
1318 face, paint.u.composite.source_paint, activePaints);
1319 }
1320 case FT_COLR_PAINTFORMAT_SOLID:
1321 case FT_COLR_PAINTFORMAT_LINEAR_GRADIENT:
1322 case FT_COLR_PAINTFORMAT_RADIAL_GRADIENT:
1323 case FT_COLR_PAINTFORMAT_SWEEP_GRADIENT: {
1324 return colrv1_draw_paint(canvas, palette, foregroundColor, face, paint);
1325 }
1326 default:
1327 SkASSERT(false);
1328 return false;
1329 }
1330 SkUNREACHABLE;
1331 }
1332
1333 SkPath GetClipBoxPath(FT_Face face, SkGlyphID glyphId, bool untransformed) {
1334 SkPath resultPath;
1335 SkUniqueFTSize unscaledFtSize = nullptr;
1336 FT_Size oldSize = face->size;
1337 FT_Matrix oldTransform;
1338 FT_Vector oldDelta;
1339 FT_Error err = 0;
1340
1341 if (untransformed) {
1342 unscaledFtSize.reset(
1343 [face]() -> FT_Size {
1344 FT_Size size;
1345 FT_Error err = FT_New_Size(face, &size);
1346 if (err != 0) {
1347 SK_TRACEFTR(err,
1348 "FT_New_Size(%s) failed in generateFacePathStaticCOLRv1.",
1349 face->family_name);
1350 return nullptr;
1351 }
1352 return size;
1353 }());
1354 if (!unscaledFtSize) {
1355 return resultPath;
1356 }
1357
1358 err = FT_Activate_Size(unscaledFtSize.get());
1359 if (err != 0) {
1360 return resultPath;
1361 }
1362
1363 err = FT_Set_Char_Size(face, SkIntToFDot6(face->units_per_EM), 0, 0, 0);
1364 if (err != 0) {
1365 return resultPath;
1366 }
1367
1368 FT_Get_Transform(face, &oldTransform, &oldDelta);
1369 FT_Set_Transform(face, nullptr, nullptr);
1370 }
1371
1372 FT_ClipBox colrGlyphClipBox;
1373 if (FT_Get_Color_Glyph_ClipBox(face, glyphId, &colrGlyphClipBox)) {
1374 resultPath = SkPath::Polygon({{{ SkFDot6ToScalar(colrGlyphClipBox.bottom_left.x),
1375 -SkFDot6ToScalar(colrGlyphClipBox.bottom_left.y)},
1376 { SkFDot6ToScalar(colrGlyphClipBox.top_left.x),
1377 -SkFDot6ToScalar(colrGlyphClipBox.top_left.y)},
1378 { SkFDot6ToScalar(colrGlyphClipBox.top_right.x),
1379 -SkFDot6ToScalar(colrGlyphClipBox.top_right.y)},
1380 { SkFDot6ToScalar(colrGlyphClipBox.bottom_right.x),
1381 -SkFDot6ToScalar(colrGlyphClipBox.bottom_right.y)}}},
1382 true);
1383 }
1384
1385 if (untransformed) {
1386 err = FT_Activate_Size(oldSize);
1387 if (err != 0) {
1388 return resultPath;
1389 }
1390 FT_Set_Transform(face, &oldTransform, &oldDelta);
1391 }
1392
1393 return resultPath;
1394 }
1395
1396 bool colrv1_start_glyph(SkCanvas* canvas,
1397 const SkSpan<SkColor>& palette,
1398 SkColor foregroundColor,
1399 FT_Face face,
1400 uint16_t glyphId,
1401 FT_Color_Root_Transform rootTransform,
1402 VisitedSet* activePaints) {
1403 FT_OpaquePaint opaquePaint{nullptr, 1};
1404 if (!FT_Get_Color_Glyph_Paint(face, glyphId, rootTransform, &opaquePaint)) {
1405 return false;
1406 }
1407
1408 bool untransformed = rootTransform == FT_COLOR_NO_ROOT_TRANSFORM;
1409 SkPath clipBoxPath = GetClipBoxPath(face, glyphId, untransformed);
1410 if (!clipBoxPath.isEmpty()) {
1411 canvas->clipPath(clipBoxPath, true);
1412 }
1413
1414 if (!colrv1_traverse_paint(canvas, palette, foregroundColor,
1415 face, opaquePaint, activePaints)) {
1416 return false;
1417 }
1418
1419 return true;
1420 }
1421
1422 bool colrv1_start_glyph_bounds(SkMatrix *ctm,
1423 SkRect* bounds,
1424 FT_Face face,
1425 SkGlyphID glyphId,
1426 FT_Color_Root_Transform rootTransform,
1427 VisitedSet* activePaints);
1428
1429 bool colrv1_traverse_paint_bounds(SkMatrix* ctm,
1430 SkRect* bounds,
1431 FT_Face face,
1432 FT_OpaquePaint opaquePaint,
1433 VisitedSet* activePaints) {
1434 // Cycle detection, see section "5.7.11.1.9 Color glyphs as a directed acyclic graph".
1435 if (activePaints->contains(opaquePaint)) {
1436 return false;
1437 }
1438
1439 activePaints->add(opaquePaint);
1440 SK_AT_SCOPE_EXIT(activePaints->remove(opaquePaint));
1441
1442 FT_COLR_Paint paint;
1443 if (!FT_Get_Paint(face, opaquePaint, &paint)) {
1444 return false;
1445 }
1446
1447 SkMatrix restoreMatrix = *ctm;
1448 SK_AT_SCOPE_EXIT(*ctm = restoreMatrix);
1449
1450 switch (paint.format) {
1451 case FT_COLR_PAINTFORMAT_COLR_LAYERS: {
1452 FT_LayerIterator& layerIterator = paint.u.colr_layers.layer_iterator;
1453 FT_OpaquePaint layerPaint{nullptr, 1};
1454 while (FT_Get_Paint_Layers(face, &layerIterator, &layerPaint)) {
1455 if (!colrv1_traverse_paint_bounds(ctm, bounds, face, layerPaint, activePaints)) {
1456 return false;
1457 }
1458 }
1459 return true;
1460 }
1461 case FT_COLR_PAINTFORMAT_GLYPH: {
1462 auto path = generateFacePathCOLRv1(face, paint.u.glyph.glyphID, ctm);
1463 if (!path) {
1464 return false;
1465 }
1466 bounds->join(path->getBounds());
1467 return true;
1468 }
1469 case FT_COLR_PAINTFORMAT_COLR_GLYPH: {
1470 FT_UInt glyphID = paint.u.colr_glyph.glyphID;
1471 return colrv1_start_glyph_bounds(ctm, bounds, face, glyphID, FT_COLOR_NO_ROOT_TRANSFORM,
1472 activePaints);
1473 }
1474 case FT_COLR_PAINTFORMAT_TRANSFORM: {
1475 SkMatrix transformMatrix;
1476 colrv1_transform(face, paint, nullptr, &transformMatrix);
1477 ctm->preConcat(transformMatrix);
1478 FT_OpaquePaint& transformPaint = paint.u.transform.paint;
1479 return colrv1_traverse_paint_bounds(ctm, bounds, face, transformPaint, activePaints);
1480 }
1481 case FT_COLR_PAINTFORMAT_TRANSLATE: {
1482 SkMatrix transformMatrix;
1483 colrv1_transform(face, paint, nullptr, &transformMatrix);
1484 ctm->preConcat(transformMatrix);
1485 FT_OpaquePaint& translatePaint = paint.u.translate.paint;
1486 return colrv1_traverse_paint_bounds(ctm, bounds, face, translatePaint, activePaints);
1487 }
1488 case FT_COLR_PAINTFORMAT_SCALE: {
1489 SkMatrix transformMatrix;
1490 colrv1_transform(face, paint, nullptr, &transformMatrix);
1491 ctm->preConcat(transformMatrix);
1492 FT_OpaquePaint& scalePaint = paint.u.scale.paint;
1493 return colrv1_traverse_paint_bounds(ctm, bounds, face, scalePaint, activePaints);
1494 }
1495 case FT_COLR_PAINTFORMAT_ROTATE: {
1496 SkMatrix transformMatrix;
1497 colrv1_transform(face, paint, nullptr, &transformMatrix);
1498 ctm->preConcat(transformMatrix);
1499 FT_OpaquePaint& rotatePaint = paint.u.rotate.paint;
1500 return colrv1_traverse_paint_bounds(ctm, bounds, face, rotatePaint, activePaints);
1501 }
1502 case FT_COLR_PAINTFORMAT_SKEW: {
1503 SkMatrix transformMatrix;
1504 colrv1_transform(face, paint, nullptr, &transformMatrix);
1505 ctm->preConcat(transformMatrix);
1506 FT_OpaquePaint& skewPaint = paint.u.skew.paint;
1507 return colrv1_traverse_paint_bounds(ctm, bounds, face, skewPaint, activePaints);
1508 }
1509 case FT_COLR_PAINTFORMAT_COMPOSITE: {
1510 FT_OpaquePaint& backdropPaint = paint.u.composite.backdrop_paint;
1511 FT_OpaquePaint& sourcePaint = paint.u.composite. source_paint;
1512 return colrv1_traverse_paint_bounds(ctm, bounds, face, backdropPaint, activePaints) &&
1513 colrv1_traverse_paint_bounds(ctm, bounds, face, sourcePaint, activePaints);
1514 }
1515 case FT_COLR_PAINTFORMAT_SOLID:
1516 case FT_COLR_PAINTFORMAT_LINEAR_GRADIENT:
1517 case FT_COLR_PAINTFORMAT_RADIAL_GRADIENT:
1518 case FT_COLR_PAINTFORMAT_SWEEP_GRADIENT: {
1519 return true;
1520 }
1521 default:
1522 SkASSERT(false);
1523 return false;
1524 }
1525 SkUNREACHABLE;
1526 }
1527
1528
1529 bool colrv1_start_glyph_bounds(SkMatrix *ctm,
1530 SkRect* bounds,
1531 FT_Face face,
1532 uint16_t glyphId,
1533 FT_Color_Root_Transform rootTransform,
1534 VisitedSet* activePaints) {
1535 FT_OpaquePaint opaquePaint{nullptr, 1};
1536 return FT_Get_Color_Glyph_Paint(face, glyphId, rootTransform, &opaquePaint) &&
1537 colrv1_traverse_paint_bounds(ctm, bounds, face, opaquePaint, activePaints);
1538 }
1539 #endif // TT_SUPPORT_COLRV1
1540
1541 } // namespace
1542
1543 ////////////////
1544
1545 void SkScalerContextFTUtils::init(SkColor fgColor, SkScalerContext::Flags flags) {
1546 fForegroundColor = fgColor;
1547 fFlags = flags;
1548 }
1549
1550 #ifdef TT_SUPPORT_COLRV1
1551 bool SkScalerContextFTUtils::drawCOLRv1Glyph(FT_Face face, const SkGlyph& glyph, uint32_t loadGlyphFlags,
1552 SkSpan<SkColor> palette, SkCanvas* canvas) const {
1553 if (this->isSubpixel()) {
1554 canvas->translate(SkFixedToScalar(glyph.getSubXFixed()),
1555 SkFixedToScalar(glyph.getSubYFixed()));
1556 }
1557
1558 VisitedSet activePaints;
1559 return colrv1_start_glyph(canvas, palette, fForegroundColor,
1560 face, glyph.getGlyphID(),
1561 FT_COLOR_INCLUDE_ROOT_TRANSFORM, &activePaints);
1562 }
1563 #endif // TT_SUPPORT_COLRV1
1564
1565 #ifdef FT_COLOR_H
1566 bool SkScalerContextFTUtils::drawCOLRv0Glyph(FT_Face face, const SkGlyph& glyph, LoadGlyphFlags flags,
1567 SkSpan<SkColor> palette, SkCanvas* canvas) const {
1568 if (this->isSubpixel()) {
1569 canvas->translate(SkFixedToScalar(glyph.getSubXFixed()),
1570 SkFixedToScalar(glyph.getSubYFixed()));
1571 }
1572
1573 bool haveLayers = false;
1574 FT_LayerIterator layerIterator;
1575 layerIterator.p = nullptr;
1576 FT_UInt layerGlyphIndex = 0;
1577 FT_UInt layerColorIndex = 0;
1578 SkPaint paint;
1579 paint.setAntiAlias(!(flags & FT_LOAD_TARGET_MONO));
1580 while (FT_Get_Color_Glyph_Layer(face, glyph.getGlyphID(), &layerGlyphIndex,
1581 &layerColorIndex, &layerIterator)) {
1582 haveLayers = true;
1583 if (layerColorIndex == 0xFFFF) {
1584 paint.setColor(fForegroundColor);
1585 } else {
1586 paint.setColor(palette[layerColorIndex]);
1587 }
1588 SkPathBuilder builder;
1589 if (this->generateFacePath(face, layerGlyphIndex, flags, &builder)) {
1590 canvas->drawPath(builder.detach(), paint);
1591 }
1592 }
1593 SkASSERTF(haveLayers, "Could not get COLRv0 layers from '%s'.", face->family_name);
1594 return haveLayers;
1595 }
1596 #endif // FT_COLOR_H
1597
1598 #if defined(FT_CONFIG_OPTION_SVG)
1599 bool SkScalerContextFTUtils::drawSVGGlyph(FT_Face face, const SkGlyph& glyph, LoadGlyphFlags flags,
1600 SkSpan<SkColor> palette, SkCanvas* canvas) const {
1601 SkASSERT(face->glyph->format == FT_GLYPH_FORMAT_SVG);
1602
1603 FT_SVG_Document ftSvg = (FT_SVG_Document)face->glyph->other;
1604 SkMatrix m;
1605 FT_Matrix ftMatrix = ftSvg->transform;
1606 FT_Vector ftOffset = ftSvg->delta;
1607 m.setAll(
1608 SkFixedToFloat(ftMatrix.xx), -SkFixedToFloat(ftMatrix.xy), SkFixedToFloat(ftOffset.x),
1609 -SkFixedToFloat(ftMatrix.yx), SkFixedToFloat(ftMatrix.yy), -SkFixedToFloat(ftOffset.y),
1610 0 , 0 , 1 );
1611 m.postScale(SkFixedToFloat(ftSvg->metrics.x_scale) / 64.0f,
1612 SkFixedToFloat(ftSvg->metrics.y_scale) / 64.0f);
1613 if (this->isSubpixel()) {
1614 m.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1615 SkFixedToScalar(glyph.getSubYFixed()));
1616 }
1617 canvas->concat(m);
1618
1619 SkGraphics::OpenTypeSVGDecoderFactory svgFactory = SkGraphics::GetOpenTypeSVGDecoderFactory();
1620 if (!svgFactory) {
1621 return false;
1622 }
1623 auto svgDecoder = svgFactory(ftSvg->svg_document, ftSvg->svg_document_length);
1624 if (!svgDecoder) {
1625 return false;
1626 }
1627 return svgDecoder->render(*canvas, ftSvg->units_per_EM, glyph.getGlyphID(),
1628 fForegroundColor, palette);
1629 }
1630 #endif // FT_CONFIG_OPTION_SVG
1631
1632 void SkScalerContextFTUtils::generateGlyphImage(FT_Face face, const SkGlyph& glyph, void* imageBuffer,
1633 const SkMatrix& bitmapTransform,
1634 const SkMaskGamma::PreBlend& preBlend) const {
1635 switch ( face->glyph->format ) {
1636 case FT_GLYPH_FORMAT_OUTLINE: {
1637 FT_Outline* outline = &face->glyph->outline;
1638
1639 int dx = 0, dy = 0;
1640 if (this->isSubpixel()) {
1641 dx = SkFixedToFDot6(glyph.getSubXFixed());
1642 dy = SkFixedToFDot6(glyph.getSubYFixed());
1643 // negate dy since freetype-y-goes-up and skia-y-goes-down
1644 dy = -dy;
1645 }
1646
1647 memset(imageBuffer, 0, glyph.rowBytes() * glyph.height());
1648
1649 if (SkMask::kLCD16_Format == glyph.maskFormat()) {
1650 const bool doBGR = SkToBool(fFlags & SkScalerContext::kLCD_BGROrder_Flag);
1651 const bool doVert = SkToBool(fFlags & SkScalerContext::kLCD_Vertical_Flag);
1652
1653 FT_Outline_Translate(outline, dx, dy);
1654 FT_Error err = FT_Render_Glyph(face->glyph, doVert ? FT_RENDER_MODE_LCD_V :
1655 FT_RENDER_MODE_LCD);
1656 if (err) {
1657 SK_TRACEFTR(err, "Could not render glyph %p.", face->glyph);
1658 return;
1659 }
1660
1661 SkMaskBuilder mask(static_cast<uint8_t*>(imageBuffer),
1662 glyph.iRect(), glyph.rowBytes(), glyph.maskFormat());
1663
1664 if constexpr (kSkShowTextBlitCoverage) {
1665 memset(mask.image(), 0x80, mask.fBounds.height() * mask.fRowBytes);
1666 }
1667 FT_GlyphSlotRec& ftGlyph = *face->glyph;
1668
1669 if (!SkIRect::Intersects(mask.fBounds,
1670 SkIRect::MakeXYWH( ftGlyph.bitmap_left,
1671 -ftGlyph.bitmap_top,
1672 ftGlyph.bitmap.width,
1673 ftGlyph.bitmap.rows)))
1674 {
1675 return;
1676 }
1677
1678 // If the FT_Bitmap extent is larger, discard bits of the bitmap outside the mask.
1679 // If the SkMask extent is larger, shrink mask to fit bitmap (clearing discarded).
1680 unsigned char* origBuffer = ftGlyph.bitmap.buffer;
1681 // First align the top left (origin).
1682 if (-ftGlyph.bitmap_top < mask.fBounds.fTop) {
1683 int32_t topDiff = mask.fBounds.fTop - (-ftGlyph.bitmap_top);
1684 ftGlyph.bitmap.buffer += ftGlyph.bitmap.pitch * topDiff;
1685 ftGlyph.bitmap.rows -= topDiff;
1686 ftGlyph.bitmap_top = -mask.fBounds.fTop;
1687 }
1688 if (ftGlyph.bitmap_left < mask.fBounds.fLeft) {
1689 int32_t leftDiff = mask.fBounds.fLeft - ftGlyph.bitmap_left;
1690 ftGlyph.bitmap.buffer += leftDiff;
1691 ftGlyph.bitmap.width -= leftDiff;
1692 ftGlyph.bitmap_left = mask.fBounds.fLeft;
1693 }
1694 if (mask.fBounds.fTop < -ftGlyph.bitmap_top) {
1695 mask.image() += mask.fRowBytes * (-ftGlyph.bitmap_top - mask.fBounds.fTop);
1696 mask.bounds().fTop = -ftGlyph.bitmap_top;
1697 }
1698 if (mask.fBounds.fLeft < ftGlyph.bitmap_left) {
1699 mask.image() += sizeof(uint16_t) * (ftGlyph.bitmap_left - mask.fBounds.fLeft);
1700 mask.bounds().fLeft = ftGlyph.bitmap_left;
1701 }
1702 // Origins aligned, clean up the width and height.
1703 int ftVertScale = (doVert ? 3 : 1);
1704 int ftHoriScale = (doVert ? 1 : 3);
1705 if (mask.fBounds.height() * ftVertScale < SkToInt(ftGlyph.bitmap.rows)) {
1706 ftGlyph.bitmap.rows = mask.fBounds.height() * ftVertScale;
1707 }
1708 if (mask.fBounds.width() * ftHoriScale < SkToInt(ftGlyph.bitmap.width)) {
1709 ftGlyph.bitmap.width = mask.fBounds.width() * ftHoriScale;
1710 }
1711 if (SkToInt(ftGlyph.bitmap.rows) < mask.fBounds.height() * ftVertScale) {
1712 mask.bounds().fBottom = mask.fBounds.fTop + ftGlyph.bitmap.rows / ftVertScale;
1713 }
1714 if (SkToInt(ftGlyph.bitmap.width) < mask.fBounds.width() * ftHoriScale) {
1715 mask.bounds().fRight = mask.fBounds.fLeft + ftGlyph.bitmap.width / ftHoriScale;
1716 }
1717 if (preBlend.isApplicable()) {
1718 copyFT2LCD16<true>(ftGlyph.bitmap, &mask, doBGR,
1719 preBlend.fR, preBlend.fG, preBlend.fB);
1720 } else {
1721 copyFT2LCD16<false>(ftGlyph.bitmap, &mask, doBGR,
1722 preBlend.fR, preBlend.fG, preBlend.fB);
1723 }
1724 // Restore the buffer pointer so FreeType can properly free it.
1725 ftGlyph.bitmap.buffer = origBuffer;
1726 } else {
1727 FT_BBox bbox;
1728 FT_Bitmap target;
1729 FT_Outline_Get_CBox(outline, &bbox);
1730 /*
1731 what we really want to do for subpixel is
1732 offset(dx, dy)
1733 compute_bounds
1734 offset(bbox & !63)
1735 but that is two calls to offset, so we do the following, which
1736 achieves the same thing with only one offset call.
1737 */
1738 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
1739 dy - ((bbox.yMin + dy) & ~63));
1740
1741 target.width = glyph.width();
1742 target.rows = glyph.height();
1743 target.pitch = glyph.rowBytes();
1744 target.buffer = static_cast<uint8_t*>(imageBuffer);
1745 target.pixel_mode = compute_pixel_mode(glyph.maskFormat());
1746 target.num_grays = 256;
1747
1748 FT_Outline_Get_Bitmap(face->glyph->library, outline, &target);
1749 if constexpr (kSkShowTextBlitCoverage) {
1750 if (glyph.maskFormat() == SkMask::kBW_Format) {
1751 for (unsigned y = 0; y < target.rows; y += 2) {
1752 for (unsigned x = (y & 0x2); x < target.width; x+=4) {
1753 uint8_t& b = target.buffer[(target.pitch * y) + (x >> 3)];
1754 b = b ^ (1 << (0x7 - (x & 0x7)));
1755 }
1756 }
1757 } else {
1758 for (unsigned y = 0; y < target.rows; ++y) {
1759 for (unsigned x = 0; x < target.width; ++x) {
1760 uint8_t& a = target.buffer[(target.pitch * y) + x];
1761 a = std::max<uint8_t>(a, 0x20);
1762 }
1763 }
1764 }
1765 }
1766 }
1767 } break;
1768
1769 case FT_GLYPH_FORMAT_BITMAP: {
1770 FT_Pixel_Mode pixel_mode = static_cast<FT_Pixel_Mode>(face->glyph->bitmap.pixel_mode);
1771 SkMask::Format maskFormat = glyph.maskFormat();
1772
1773 // Assume that the other formats do not exist.
1774 SkASSERT(FT_PIXEL_MODE_MONO == pixel_mode ||
1775 FT_PIXEL_MODE_GRAY == pixel_mode ||
1776 FT_PIXEL_MODE_BGRA == pixel_mode);
1777
1778 // These are the only formats this ScalerContext should request.
1779 SkASSERT(SkMask::kBW_Format == maskFormat ||
1780 SkMask::kA8_Format == maskFormat ||
1781 SkMask::kARGB32_Format == maskFormat ||
1782 SkMask::kLCD16_Format == maskFormat);
1783
1784 // If no scaling needed, directly copy glyph bitmap.
1785 if (bitmapTransform.isIdentity()) {
1786 SkMaskBuilder dstMask = SkMaskBuilder(static_cast<uint8_t*>(imageBuffer),
1787 glyph.iRect(), glyph.rowBytes(),
1788 glyph.maskFormat());
1789 copyFTBitmap(face->glyph->bitmap, &dstMask);
1790 break;
1791 }
1792
1793 // Otherwise, scale the bitmap.
1794
1795 // Copy the FT_Bitmap into an SkBitmap (either A8 or ARGB)
1796 SkBitmap unscaledBitmap;
1797 // TODO: mark this as sRGB when the blits will be sRGB.
1798 unscaledBitmap.setInfo(SkImageInfo::Make(face->glyph->bitmap.width,
1799 face->glyph->bitmap.rows,
1800 SkColorType_for_FTPixelMode(pixel_mode),
1801 kPremul_SkAlphaType));
1802 if (!unscaledBitmap.tryAllocPixels()) {
1803 // TODO: set the imageBuffer to indicate "missing"
1804 memset(imageBuffer, 0, glyph.rowBytes() * glyph.height());
1805 return;
1806 }
1807
1808 SkMaskBuilder unscaledBitmapAlias(
1809 reinterpret_cast<uint8_t*>(unscaledBitmap.getPixels()),
1810 SkIRect::MakeWH(unscaledBitmap.width(), unscaledBitmap.height()),
1811 unscaledBitmap.rowBytes(),
1812 SkMaskFormat_for_SkColorType(unscaledBitmap.colorType()));
1813 copyFTBitmap(face->glyph->bitmap, &unscaledBitmapAlias);
1814
1815 // Wrap the glyph's mask in a bitmap, unless the glyph's mask is BW or LCD.
1816 // BW requires an A8 target for resizing, which can then be down sampled.
1817 // LCD should use a 4x A8 target, which will then be down sampled.
1818 // For simplicity, LCD uses A8 and is replicated.
1819 int bitmapRowBytes = 0;
1820 if (SkMask::kBW_Format != maskFormat && SkMask::kLCD16_Format != maskFormat) {
1821 bitmapRowBytes = glyph.rowBytes();
1822 }
1823 SkBitmap dstBitmap;
1824 // TODO: mark this as sRGB when the blits will be sRGB.
1825 dstBitmap.setInfo(SkImageInfo::Make(glyph.width(), glyph.height(),
1826 SkColorType_for_SkMaskFormat(maskFormat),
1827 kPremul_SkAlphaType),
1828 bitmapRowBytes);
1829 if (SkMask::kBW_Format == maskFormat || SkMask::kLCD16_Format == maskFormat) {
1830 if (!dstBitmap.tryAllocPixels()) {
1831 // TODO: set the fImage to indicate "missing"
1832 memset(imageBuffer, 0, glyph.rowBytes() * glyph.height());
1833 return;
1834 }
1835 } else {
1836 dstBitmap.setPixels(imageBuffer);
1837 }
1838
1839 // Scale unscaledBitmap into dstBitmap.
1840 SkCanvas canvas(dstBitmap);
1841 if constexpr (kSkShowTextBlitCoverage) {
1842 canvas.clear(0x33FF0000);
1843 } else {
1844 canvas.clear(SK_ColorTRANSPARENT);
1845 }
1846 canvas.translate(-glyph.left(), -glyph.top());
1847 canvas.concat(bitmapTransform);
1848 canvas.translate(face->glyph->bitmap_left, -face->glyph->bitmap_top);
1849
1850 SkSamplingOptions sampling(SkFilterMode::kLinear, SkMipmapMode::kNearest);
1851 canvas.drawImage(unscaledBitmap.asImage().get(), 0, 0, sampling, nullptr);
1852
1853 // If the destination is BW or LCD, convert from A8.
1854 if (SkMask::kBW_Format == maskFormat) {
1855 // Copy the A8 dstBitmap into the A1 imageBuffer.
1856 SkMaskBuilder dstMask(static_cast<uint8_t*>(imageBuffer),
1857 glyph.iRect(), glyph.rowBytes(), glyph.maskFormat());
1858 packA8ToA1(&dstMask, dstBitmap.getAddr8(0, 0), dstBitmap.rowBytes());
1859 } else if (SkMask::kLCD16_Format == maskFormat) {
1860 // Copy the A8 dstBitmap into the LCD16 imageBuffer.
1861 uint8_t* src = dstBitmap.getAddr8(0, 0);
1862 uint16_t* dst = reinterpret_cast<uint16_t*>(imageBuffer);
1863 for (int y = dstBitmap.height(); y --> 0;) {
1864 for (int x = 0; x < dstBitmap.width(); ++x) {
1865 dst[x] = grayToRGB16(src[x]);
1866 }
1867 dst = (uint16_t*)((char*)dst + glyph.rowBytes());
1868 src += dstBitmap.rowBytes();
1869 }
1870 }
1871 } break;
1872
1873 default:
1874 SkDEBUGFAIL("unknown glyph format");
1875 memset(imageBuffer, 0, glyph.rowBytes() * glyph.height());
1876 return;
1877 }
1878
1879 // We used to always do this pre-USE_COLOR_LUMINANCE, but with colorlum,
1880 // it is optional
1881 #if defined(SK_GAMMA_APPLY_TO_A8)
1882 if (SkMask::kA8_Format == glyph.maskFormat() && preBlend.isApplicable()) {
1883 uint8_t* SK_RESTRICT dst = (uint8_t*)imageBuffer;
1884 unsigned rowBytes = glyph.rowBytes();
1885
1886 for (int y = glyph.height() - 1; y >= 0; --y) {
1887 for (int x = glyph.width() - 1; x >= 0; --x) {
1888 dst[x] = preBlend.fG[dst[x]];
1889 }
1890 dst += rowBytes;
1891 }
1892 }
1893 #endif
1894 }
1895
1896 ///////////////////////////////////////////////////////////////////////////////
1897
1898 namespace {
1899
1900 class SkFTGeometrySink {
1901 SkPathBuilder* fBuilder;
1902 bool fStarted;
1903 FT_Vector fCurrent;
1904
1905 void goingTo(const FT_Vector* pt) {
1906 if (!fStarted) {
1907 fStarted = true;
1908 fBuilder->moveTo(SkFDot6ToScalar(fCurrent.x), -SkFDot6ToScalar(fCurrent.y));
1909 }
1910 fCurrent = *pt;
1911 }
1912
1913 bool currentIsNot(const FT_Vector* pt) {
1914 return fCurrent.x != pt->x || fCurrent.y != pt->y;
1915 }
1916
1917 static int Move(const FT_Vector* pt, void* ctx) {
1918 SkFTGeometrySink& self = *(SkFTGeometrySink*)ctx;
1919 if (self.fStarted) {
1920 self.fBuilder->close();
1921 self.fStarted = false;
1922 }
1923 self.fCurrent = *pt;
1924 return 0;
1925 }
1926
1927 static int Line(const FT_Vector* pt, void* ctx) {
1928 SkFTGeometrySink& self = *(SkFTGeometrySink*)ctx;
1929 if (self.currentIsNot(pt)) {
1930 self.goingTo(pt);
1931 self.fBuilder->lineTo(SkFDot6ToScalar(pt->x), -SkFDot6ToScalar(pt->y));
1932 }
1933 return 0;
1934 }
1935
1936 static int Quad(const FT_Vector* pt0, const FT_Vector* pt1, void* ctx) {
1937 SkFTGeometrySink& self = *(SkFTGeometrySink*)ctx;
1938 if (self.currentIsNot(pt0) || self.currentIsNot(pt1)) {
1939 self.goingTo(pt1);
1940 self.fBuilder->quadTo(SkFDot6ToScalar(pt0->x), -SkFDot6ToScalar(pt0->y),
1941 SkFDot6ToScalar(pt1->x), -SkFDot6ToScalar(pt1->y));
1942 }
1943 return 0;
1944 }
1945
1946 static int Cubic(const FT_Vector* pt0, const FT_Vector* pt1, const FT_Vector* pt2, void* ctx) {
1947 SkFTGeometrySink& self = *(SkFTGeometrySink*)ctx;
1948 if (self.currentIsNot(pt0) || self.currentIsNot(pt1) || self.currentIsNot(pt2)) {
1949 self.goingTo(pt2);
1950 self.fBuilder->cubicTo(SkFDot6ToScalar(pt0->x), -SkFDot6ToScalar(pt0->y),
1951 SkFDot6ToScalar(pt1->x), -SkFDot6ToScalar(pt1->y),
1952 SkFDot6ToScalar(pt2->x), -SkFDot6ToScalar(pt2->y));
1953 }
1954 return 0;
1955 }
1956
1957 public:
1958 SkFTGeometrySink(SkPathBuilder* builder) : fBuilder{builder}, fStarted{false}, fCurrent{0,0} {}
1959
1960 inline static constexpr const FT_Outline_Funcs Funcs{
1961 /*move_to =*/ SkFTGeometrySink::Move,
1962 /*line_to =*/ SkFTGeometrySink::Line,
1963 /*conic_to =*/ SkFTGeometrySink::Quad,
1964 /*cubic_to =*/ SkFTGeometrySink::Cubic,
1965 /*shift = */ 0,
1966 /*delta =*/ 0,
1967 };
1968 };
1969
1970 bool generateGlyphPathStatic(FT_Face face, SkPathBuilder* builder) {
1971 SkFTGeometrySink sink{builder};
1972 if (face->glyph->format != FT_GLYPH_FORMAT_OUTLINE ||
1973 FT_Outline_Decompose(&face->glyph->outline, &SkFTGeometrySink::Funcs, &sink))
1974 {
1975 return false;
1976 }
1977 builder->close();
1978 return true;
1979 }
1980
1981 bool generateFacePathStatic(FT_Face face, SkGlyphID glyphID,
1982 SkScalerContextFTUtils::LoadGlyphFlags flags, SkPathBuilder* builder) {
1983 flags |= FT_LOAD_BITMAP_METRICS_ONLY; // Don't decode any bitmaps.
1984 flags |= FT_LOAD_NO_BITMAP; // Ignore embedded bitmaps.
1985 flags &= ~FT_LOAD_RENDER; // Don't scan convert.
1986 flags &= ~FT_LOAD_COLOR; // Ignore SVG.
1987 if (FT_Load_Glyph(face, glyphID, flags)) {
1988 return false;
1989 }
1990 return generateGlyphPathStatic(face, builder);
1991 }
1992
1993 #ifdef TT_SUPPORT_COLRV1
1994 /* TODO: Currently this call retrieves the path at units_per_em size. If we want to get
1995 * correct hinting for the scaled size under the transforms at this point in the color
1996 * glyph graph, we need to extract at least the requested glyph width and height and
1997 * pass that to the path generation. */
1998 std::optional<SkPath> generateFacePathCOLRv1(FT_Face face, SkGlyphID glyphID, const SkMatrix* mx) {
1999 uint32_t flags = 0;
2000 flags |= FT_LOAD_BITMAP_METRICS_ONLY; // Don't decode any bitmaps.
2001 flags |= FT_LOAD_NO_BITMAP; // Ignore embedded bitmaps.
2002 flags &= ~FT_LOAD_RENDER; // Don't scan convert.
2003 flags &= ~FT_LOAD_COLOR; // Ignore SVG.
2004 flags |= FT_LOAD_NO_HINTING;
2005 flags |= FT_LOAD_NO_AUTOHINT;
2006 flags |= FT_LOAD_IGNORE_TRANSFORM;
2007
2008 SkUniqueFTSize unscaledFtSize([face]() -> FT_Size {
2009 FT_Size size;
2010 FT_Error err = FT_New_Size(face, &size);
2011 if (err != 0) {
2012 SK_TRACEFTR(err, "FT_New_Size(%s) failed in generateFacePathStaticCOLRv1.",
2013 face->family_name);
2014 return nullptr;
2015 }
2016 return size;
2017 }());
2018
2019 if (!unscaledFtSize) {
2020 return {};
2021 }
2022
2023 FT_Size oldSize = face->size;
2024 SkPathBuilder builder;
2025
2026 auto tryGeneratePath = [face, &unscaledFtSize, glyphID, flags, &builder]() {
2027 FT_Error err = 0;
2028
2029 err = FT_Activate_Size(unscaledFtSize.get());
2030 if (err != 0) {
2031 return false;
2032 }
2033
2034 err = FT_Set_Char_Size(face, SkIntToFDot6(face->units_per_EM),
2035 SkIntToFDot6(face->units_per_EM), 72, 72);
2036 if (err != 0) {
2037 return false;
2038 }
2039
2040 err = FT_Load_Glyph(face, glyphID, flags);
2041 if (err != 0) {
2042 return false;
2043 }
2044
2045 return generateGlyphPathStatic(face, &builder);
2046 };
2047
2048 bool pathGenerationResult = tryGeneratePath();
2049
2050 FT_Activate_Size(oldSize);
2051
2052 if (pathGenerationResult) {
2053 if (mx) {
2054 builder.transform(*mx);
2055 }
2056 return builder.detach();
2057 } else {
2058 return {};
2059 }
2060 }
2061 #endif
2062
2063 } // namespace
2064
2065 bool SkScalerContextFTUtils::generateGlyphPath(FT_Face face, SkPathBuilder* builder) const {
2066 // We used to try simplifying overlapping contours (flags & FT_OUTLINE_OVERLAP)
2067 // at this stage, but that was not 100% reliable, and other font backends
2068 // (e.g. CoreText) do not attempt this, so we removed it.
2069
2070 return generateGlyphPathStatic(face, builder);
2071 }
2072
2073 bool SkScalerContextFTUtils::generateFacePath(FT_Face face, SkGlyphID glyphID, LoadGlyphFlags flags,
2074 SkPathBuilder* builder) const {
2075 return generateFacePathStatic(face, glyphID, flags, builder);
2076 }
2077
2078 #ifdef TT_SUPPORT_COLRV1
2079 bool SkScalerContextFTUtils::computeColrV1GlyphBoundingBox(FT_Face face, SkGlyphID glyphID,
2080 SkRect* bounds) {
2081 SkMatrix ctm;
2082 *bounds = SkRect::MakeEmpty();
2083 VisitedSet activePaints;
2084 return colrv1_start_glyph_bounds(&ctm, bounds, face, glyphID,
2085 FT_COLOR_INCLUDE_ROOT_TRANSFORM, &activePaints);
2086 }
2087 #endif