1 /*
2 * Copyright 2006 The Android Open Source Project
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
8 #include "SkGlyphCache.h"
9 #include "SkPaint.h"
10 #include "SkScalerContext.h"
11
12 #include "SkAutoMalloc.h"
13 #include "SkAutoPixmapStorage.h"
14 #include "SkColorData.h"
15 #include "SkDescriptor.h"
16 #include "SkDraw.h"
17 #include "SkGlyph.h"
18 #include "SkMakeUnique.h"
19 #include "SkMaskFilter.h"
20 #include "SkMaskGamma.h"
21 #include "SkMatrix22.h"
22 #include "SkPaintPriv.h"
23 #include "SkPathEffect.h"
24 #include "SkRasterClip.h"
25 #include "SkReadBuffer.h"
26 #include "SkStroke.h"
27 #include "SkStrokeRec.h"
28 #include "SkSurfacePriv.h"
29 #include "SkTextFormatParams.h"
30 #include "SkWriteBuffer.h"
31
toMask(SkMask * mask) const32 void SkGlyph::toMask(SkMask* mask) const {
33 SkASSERT(mask);
34
35 mask->fImage = (uint8_t*)fImage;
36 mask->fBounds.set(fLeft, fTop, fLeft + fWidth, fTop + fHeight);
37 mask->fRowBytes = this->rowBytes();
38 mask->fFormat = static_cast<SkMask::Format>(fMaskFormat);
39 }
40
computeImageSize() const41 size_t SkGlyph::computeImageSize() const {
42 const size_t size = this->rowBytes() * fHeight;
43
44 switch (fMaskFormat) {
45 case SkMask::k3D_Format:
46 return 3 * size;
47 default:
48 return size;
49 }
50 }
51
zeroMetrics()52 void SkGlyph::zeroMetrics() {
53 fAdvanceX = 0;
54 fAdvanceY = 0;
55 fWidth = 0;
56 fHeight = 0;
57 fTop = 0;
58 fLeft = 0;
59 fRsbDelta = 0;
60 fLsbDelta = 0;
61 }
62
63 ///////////////////////////////////////////////////////////////////////////////
64
65 #ifdef SK_DEBUG
66 #define DUMP_RECx
67 #endif
68
SkScalerContext(sk_sp<SkTypeface> typeface,const SkScalerContextEffects & effects,const SkDescriptor * desc)69 SkScalerContext::SkScalerContext(sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
70 const SkDescriptor* desc)
71 : fRec(*static_cast<const SkScalerContextRec*>(desc->findEntry(kRec_SkDescriptorTag, nullptr)))
72
73 , fTypeface(std::move(typeface))
74 , fPathEffect(sk_ref_sp(effects.fPathEffect))
75 , fMaskFilter(sk_ref_sp(effects.fMaskFilter))
76 // Initialize based on our settings. Subclasses can also force this.
77 , fGenerateImageFromPath(fRec.fFrameWidth > 0 || fPathEffect != nullptr)
78
79 , fPreBlend(fMaskFilter ? SkMaskGamma::PreBlend() : SkScalerContext::GetMaskPreBlend(fRec))
80 , fPreBlendForFilter(fMaskFilter ? SkScalerContext::GetMaskPreBlend(fRec)
81 : SkMaskGamma::PreBlend())
82 {
83 #ifdef DUMP_REC
84 desc->assertChecksum();
85 SkDebugf("SkScalerContext checksum %x count %d length %d\n",
86 desc->getChecksum(), desc->getCount(), desc->getLength());
87 SkDebugf(" textsize %g prescale %g preskew %g post [%g %g %g %g]\n",
88 rec->fTextSize, rec->fPreScaleX, rec->fPreSkewX, rec->fPost2x2[0][0],
89 rec->fPost2x2[0][1], rec->fPost2x2[1][0], rec->fPost2x2[1][1]);
90 SkDebugf(" frame %g miter %g hints %d framefill %d format %d join %d cap %d\n",
91 rec->fFrameWidth, rec->fMiterLimit, rec->fHints, rec->fFrameAndFill,
92 rec->fMaskFormat, rec->fStrokeJoin, rec->fStrokeCap);
93 SkDebugf(" pathEffect %x maskFilter %x\n",
94 desc->findEntry(kPathEffect_SkDescriptorTag, nullptr),
95 desc->findEntry(kMaskFilter_SkDescriptorTag, nullptr));
96 #endif
97 }
98
~SkScalerContext()99 SkScalerContext::~SkScalerContext() {}
100
getAdvance(SkGlyph * glyph)101 void SkScalerContext::getAdvance(SkGlyph* glyph) {
102 // mark us as just having a valid advance
103 glyph->fMaskFormat = MASK_FORMAT_JUST_ADVANCE;
104 // we mark the format before making the call, in case the impl
105 // internally ends up calling its generateMetrics, which is OK
106 // albeit slower than strictly necessary
107 generateAdvance(glyph);
108 }
109
getMetrics(SkGlyph * glyph)110 void SkScalerContext::getMetrics(SkGlyph* glyph) {
111 generateMetrics(glyph);
112
113 // for now we have separate cache entries for devkerning on and off
114 // in the future we might share caches, but make our measure/draw
115 // code make the distinction. Thus we zap the values if the caller
116 // has not asked for them.
117 if ((fRec.fFlags & SkScalerContext::kDevKernText_Flag) == 0) {
118 // no devkern, so zap the fields
119 glyph->fLsbDelta = glyph->fRsbDelta = 0;
120 }
121
122 // if either dimension is empty, zap the image bounds of the glyph
123 if (0 == glyph->fWidth || 0 == glyph->fHeight) {
124 glyph->fWidth = 0;
125 glyph->fHeight = 0;
126 glyph->fTop = 0;
127 glyph->fLeft = 0;
128 glyph->fMaskFormat = 0;
129 return;
130 }
131
132 bool generatingImageFromPath = fGenerateImageFromPath;
133 if (fGenerateImageFromPath) {
134 SkPath devPath, fillPath;
135 SkMatrix fillToDevMatrix;
136
137 this->internalGetPath(glyph->getPackedID(), &fillPath, &devPath, &fillToDevMatrix);
138 if (fillPath.isEmpty()) {
139 generatingImageFromPath = false;
140 } else {
141 // just use devPath
142 const SkIRect ir = devPath.getBounds().roundOut();
143
144 if (ir.isEmpty() || !ir.is16Bit()) {
145 goto SK_ERROR;
146 }
147 glyph->fLeft = ir.fLeft;
148 glyph->fTop = ir.fTop;
149 glyph->fWidth = SkToU16(ir.width());
150 glyph->fHeight = SkToU16(ir.height());
151
152 if (glyph->fWidth > 0) {
153 switch (fRec.fMaskFormat) {
154 case SkMask::kLCD16_Format:
155 glyph->fWidth += 2;
156 glyph->fLeft -= 1;
157 break;
158 default:
159 break;
160 }
161 }
162 }
163 }
164
165 if (SkMask::kARGB32_Format != glyph->fMaskFormat) {
166 glyph->fMaskFormat = fRec.fMaskFormat;
167 }
168
169 // If we are going to create the mask, then we cannot keep the color
170 if ((generatingImageFromPath || fMaskFilter) && SkMask::kARGB32_Format == glyph->fMaskFormat) {
171 glyph->fMaskFormat = SkMask::kA8_Format;
172 }
173
174 if (fMaskFilter) {
175 SkMask src, dst;
176 SkMatrix matrix;
177
178 glyph->toMask(&src);
179 fRec.getMatrixFrom2x2(&matrix);
180
181 src.fImage = nullptr; // only want the bounds from the filter
182 if (as_MFB(fMaskFilter)->filterMask(&dst, src, matrix, nullptr)) {
183 if (dst.fBounds.isEmpty() || !dst.fBounds.is16Bit()) {
184 goto SK_ERROR;
185 }
186 SkASSERT(dst.fImage == nullptr);
187 glyph->fLeft = dst.fBounds.fLeft;
188 glyph->fTop = dst.fBounds.fTop;
189 glyph->fWidth = SkToU16(dst.fBounds.width());
190 glyph->fHeight = SkToU16(dst.fBounds.height());
191 glyph->fMaskFormat = dst.fFormat;
192 }
193 }
194 return;
195
196 SK_ERROR:
197 // draw nothing 'cause we failed
198 glyph->fLeft = 0;
199 glyph->fTop = 0;
200 glyph->fWidth = 0;
201 glyph->fHeight = 0;
202 // put a valid value here, in case it was earlier set to
203 // MASK_FORMAT_JUST_ADVANCE
204 glyph->fMaskFormat = fRec.fMaskFormat;
205 }
206
207 #define SK_SHOW_TEXT_BLIT_COVERAGE 0
208
applyLUTToA8Mask(const SkMask & mask,const uint8_t * lut)209 static void applyLUTToA8Mask(const SkMask& mask, const uint8_t* lut) {
210 uint8_t* SK_RESTRICT dst = (uint8_t*)mask.fImage;
211 unsigned rowBytes = mask.fRowBytes;
212
213 for (int y = mask.fBounds.height() - 1; y >= 0; --y) {
214 for (int x = mask.fBounds.width() - 1; x >= 0; --x) {
215 dst[x] = lut[dst[x]];
216 }
217 dst += rowBytes;
218 }
219 }
220
221 template<bool APPLY_PREBLEND>
pack4xHToLCD16(const SkPixmap & src,const SkMask & dst,const SkMaskGamma::PreBlend & maskPreBlend)222 static void pack4xHToLCD16(const SkPixmap& src, const SkMask& dst,
223 const SkMaskGamma::PreBlend& maskPreBlend) {
224 #define SAMPLES_PER_PIXEL 4
225 #define LCD_PER_PIXEL 3
226 SkASSERT(kAlpha_8_SkColorType == src.colorType());
227 SkASSERT(SkMask::kLCD16_Format == dst.fFormat);
228
229 const int sample_width = src.width();
230 const int height = src.height();
231
232 uint16_t* dstP = (uint16_t*)dst.fImage;
233 size_t dstRB = dst.fRowBytes;
234 // An N tap FIR is defined by
235 // out[n] = coeff[0]*x[n] + coeff[1]*x[n-1] + ... + coeff[N]*x[n-N]
236 // or
237 // out[n] = sum(i, 0, N, coeff[i]*x[n-i])
238
239 // The strategy is to use one FIR (different coefficients) for each of r, g, and b.
240 // This means using every 4th FIR output value of each FIR and discarding the rest.
241 // The FIRs are aligned, and the coefficients reach 5 samples to each side of their 'center'.
242 // (For r and b this is technically incorrect, but the coeffs outside round to zero anyway.)
243
244 // These are in some fixed point repesentation.
245 // Adding up to more than one simulates ink spread.
246 // For implementation reasons, these should never add up to more than two.
247
248 // Coefficients determined by a gausian where 5 samples = 3 std deviations (0x110 'contrast').
249 // Calculated using tools/generate_fir_coeff.py
250 // With this one almost no fringing is ever seen, but it is imperceptibly blurry.
251 // The lcd smoothed text is almost imperceptibly different from gray,
252 // but is still sharper on small stems and small rounded corners than gray.
253 // This also seems to be about as wide as one can get and only have a three pixel kernel.
254 // TODO: caculate these at runtime so parameters can be adjusted (esp contrast).
255 static const unsigned int coefficients[LCD_PER_PIXEL][SAMPLES_PER_PIXEL*3] = {
256 //The red subpixel is centered inside the first sample (at 1/6 pixel), and is shifted.
257 { 0x03, 0x0b, 0x1c, 0x33, 0x40, 0x39, 0x24, 0x10, 0x05, 0x01, 0x00, 0x00, },
258 //The green subpixel is centered between two samples (at 1/2 pixel), so is symetric
259 { 0x00, 0x02, 0x08, 0x16, 0x2b, 0x3d, 0x3d, 0x2b, 0x16, 0x08, 0x02, 0x00, },
260 //The blue subpixel is centered inside the last sample (at 5/6 pixel), and is shifted.
261 { 0x00, 0x00, 0x01, 0x05, 0x10, 0x24, 0x39, 0x40, 0x33, 0x1c, 0x0b, 0x03, },
262 };
263
264 for (int y = 0; y < height; ++y) {
265 const uint8_t* srcP = src.addr8(0, y);
266
267 // TODO: this fir filter implementation is straight forward, but slow.
268 // It should be possible to make it much faster.
269 for (int sample_x = -4, pixel_x = 0; sample_x < sample_width + 4; sample_x += 4, ++pixel_x) {
270 int fir[LCD_PER_PIXEL] = { 0 };
271 for (int sample_index = SkMax32(0, sample_x - 4), coeff_index = sample_index - (sample_x - 4)
272 ; sample_index < SkMin32(sample_x + 8, sample_width)
273 ; ++sample_index, ++coeff_index)
274 {
275 int sample_value = srcP[sample_index];
276 for (int subpxl_index = 0; subpxl_index < LCD_PER_PIXEL; ++subpxl_index) {
277 fir[subpxl_index] += coefficients[subpxl_index][coeff_index] * sample_value;
278 }
279 }
280 for (int subpxl_index = 0; subpxl_index < LCD_PER_PIXEL; ++subpxl_index) {
281 fir[subpxl_index] /= 0x100;
282 fir[subpxl_index] = SkMin32(fir[subpxl_index], 255);
283 }
284
285 U8CPU r = sk_apply_lut_if<APPLY_PREBLEND>(fir[0], maskPreBlend.fR);
286 U8CPU g = sk_apply_lut_if<APPLY_PREBLEND>(fir[1], maskPreBlend.fG);
287 U8CPU b = sk_apply_lut_if<APPLY_PREBLEND>(fir[2], maskPreBlend.fB);
288 #if SK_SHOW_TEXT_BLIT_COVERAGE
289 r = SkMax32(r, 10); g = SkMax32(g, 10); b = SkMax32(b, 10);
290 #endif
291 dstP[pixel_x] = SkPack888ToRGB16(r, g, b);
292 }
293 dstP = (uint16_t*)((char*)dstP + dstRB);
294 }
295 }
296
convert_8_to_1(unsigned byte)297 static inline int convert_8_to_1(unsigned byte) {
298 SkASSERT(byte <= 0xFF);
299 return byte >> 7;
300 }
301
pack_8_to_1(const uint8_t alpha[8])302 static uint8_t pack_8_to_1(const uint8_t alpha[8]) {
303 unsigned bits = 0;
304 for (int i = 0; i < 8; ++i) {
305 bits <<= 1;
306 bits |= convert_8_to_1(alpha[i]);
307 }
308 return SkToU8(bits);
309 }
310
packA8ToA1(const SkMask & mask,const uint8_t * src,size_t srcRB)311 static void packA8ToA1(const SkMask& mask, const uint8_t* src, size_t srcRB) {
312 const int height = mask.fBounds.height();
313 const int width = mask.fBounds.width();
314 const int octs = width >> 3;
315 const int leftOverBits = width & 7;
316
317 uint8_t* dst = mask.fImage;
318 const int dstPad = mask.fRowBytes - SkAlign8(width)/8;
319 SkASSERT(dstPad >= 0);
320
321 SkASSERT(width >= 0);
322 SkASSERT(srcRB >= (size_t)width);
323 const size_t srcPad = srcRB - width;
324
325 for (int y = 0; y < height; ++y) {
326 for (int i = 0; i < octs; ++i) {
327 *dst++ = pack_8_to_1(src);
328 src += 8;
329 }
330 if (leftOverBits > 0) {
331 unsigned bits = 0;
332 int shift = 7;
333 for (int i = 0; i < leftOverBits; ++i, --shift) {
334 bits |= convert_8_to_1(*src++) << shift;
335 }
336 *dst++ = bits;
337 }
338 src += srcPad;
339 dst += dstPad;
340 }
341 }
342
generateMask(const SkMask & mask,const SkPath & path,const SkMaskGamma::PreBlend & maskPreBlend)343 static void generateMask(const SkMask& mask, const SkPath& path,
344 const SkMaskGamma::PreBlend& maskPreBlend) {
345 SkPaint paint;
346
347 int srcW = mask.fBounds.width();
348 int srcH = mask.fBounds.height();
349 int dstW = srcW;
350 int dstH = srcH;
351 int dstRB = mask.fRowBytes;
352
353 SkMatrix matrix;
354 matrix.setTranslate(-SkIntToScalar(mask.fBounds.fLeft),
355 -SkIntToScalar(mask.fBounds.fTop));
356
357 paint.setAntiAlias(SkMask::kBW_Format != mask.fFormat);
358 switch (mask.fFormat) {
359 case SkMask::kBW_Format:
360 dstRB = 0; // signals we need a copy
361 break;
362 case SkMask::kA8_Format:
363 break;
364 case SkMask::kLCD16_Format:
365 // TODO: trigger off LCD orientation
366 dstW = 4*dstW - 8;
367 matrix.setTranslate(-SkIntToScalar(mask.fBounds.fLeft + 1),
368 -SkIntToScalar(mask.fBounds.fTop));
369 matrix.postScale(SkIntToScalar(4), SK_Scalar1);
370 dstRB = 0; // signals we need a copy
371 break;
372 default:
373 SkDEBUGFAIL("unexpected mask format");
374 }
375
376 SkRasterClip clip;
377 clip.setRect(SkIRect::MakeWH(dstW, dstH));
378
379 const SkImageInfo info = SkImageInfo::MakeA8(dstW, dstH);
380 SkAutoPixmapStorage dst;
381
382 if (0 == dstRB) {
383 if (!dst.tryAlloc(info)) {
384 // can't allocate offscreen, so empty the mask and return
385 sk_bzero(mask.fImage, mask.computeImageSize());
386 return;
387 }
388 } else {
389 dst.reset(info, mask.fImage, dstRB);
390 }
391 sk_bzero(dst.writable_addr(), dst.computeByteSize());
392
393 SkDraw draw;
394 draw.fDst = dst;
395 draw.fRC = &clip;
396 draw.fMatrix = &matrix;
397 draw.drawPath(path, paint);
398
399 switch (mask.fFormat) {
400 case SkMask::kBW_Format:
401 packA8ToA1(mask, dst.addr8(0, 0), dst.rowBytes());
402 break;
403 case SkMask::kA8_Format:
404 if (maskPreBlend.isApplicable()) {
405 applyLUTToA8Mask(mask, maskPreBlend.fG);
406 }
407 break;
408 case SkMask::kLCD16_Format:
409 if (maskPreBlend.isApplicable()) {
410 pack4xHToLCD16<true>(dst, mask, maskPreBlend);
411 } else {
412 pack4xHToLCD16<false>(dst, mask, maskPreBlend);
413 }
414 break;
415 default:
416 break;
417 }
418 }
419
extract_alpha(const SkMask & dst,const SkPMColor * srcRow,size_t srcRB)420 static void extract_alpha(const SkMask& dst,
421 const SkPMColor* srcRow, size_t srcRB) {
422 int width = dst.fBounds.width();
423 int height = dst.fBounds.height();
424 int dstRB = dst.fRowBytes;
425 uint8_t* dstRow = dst.fImage;
426
427 for (int y = 0; y < height; ++y) {
428 for (int x = 0; x < width; ++x) {
429 dstRow[x] = SkGetPackedA32(srcRow[x]);
430 }
431 // zero any padding on each row
432 for (int x = width; x < dstRB; ++x) {
433 dstRow[x] = 0;
434 }
435 dstRow += dstRB;
436 srcRow = (const SkPMColor*)((const char*)srcRow + srcRB);
437 }
438 }
439
getImage(const SkGlyph & origGlyph)440 void SkScalerContext::getImage(const SkGlyph& origGlyph) {
441 const SkGlyph* glyph = &origGlyph;
442 SkGlyph tmpGlyph;
443
444 // in case we need to call generateImage on a mask-format that is different
445 // (i.e. larger) than what our caller allocated by looking at origGlyph.
446 SkAutoMalloc tmpGlyphImageStorage;
447
448 if (fMaskFilter) { // restore the prefilter bounds
449 tmpGlyph.initWithGlyphID(origGlyph.getPackedID());
450
451 // need the original bounds, sans our maskfilter
452 SkMaskFilter* mf = fMaskFilter.release(); // temp disable
453 this->getMetrics(&tmpGlyph);
454 fMaskFilter = sk_sp<SkMaskFilter>(mf); // restore
455
456 // we need the prefilter bounds to be <= filter bounds
457 SkASSERT(tmpGlyph.fWidth <= origGlyph.fWidth);
458 SkASSERT(tmpGlyph.fHeight <= origGlyph.fHeight);
459
460 if (tmpGlyph.fMaskFormat == origGlyph.fMaskFormat) {
461 tmpGlyph.fImage = origGlyph.fImage;
462 } else {
463 tmpGlyphImageStorage.reset(tmpGlyph.computeImageSize());
464 tmpGlyph.fImage = tmpGlyphImageStorage.get();
465 }
466 glyph = &tmpGlyph;
467 }
468
469 if (fGenerateImageFromPath) {
470 SkPath devPath, fillPath;
471 SkMatrix fillToDevMatrix;
472 SkMask mask;
473
474 this->internalGetPath(glyph->getPackedID(), &fillPath, &devPath, &fillToDevMatrix);
475 glyph->toMask(&mask);
476
477 if (fillPath.isEmpty()) {
478 generateImage(*glyph);
479 } else {
480 SkASSERT(SkMask::kARGB32_Format != origGlyph.fMaskFormat);
481 SkASSERT(SkMask::kARGB32_Format != mask.fFormat);
482 generateMask(mask, devPath, fPreBlend);
483 }
484 } else {
485 generateImage(*glyph);
486 }
487
488 if (fMaskFilter) {
489 SkMask srcM, dstM;
490 SkMatrix matrix;
491
492 // the src glyph image shouldn't be 3D
493 SkASSERT(SkMask::k3D_Format != glyph->fMaskFormat);
494
495 SkAutoSMalloc<32*32> a8storage;
496 glyph->toMask(&srcM);
497 if (SkMask::kARGB32_Format == srcM.fFormat) {
498 // now we need to extract the alpha-channel from the glyph's image
499 // and copy it into a temp buffer, and then point srcM at that temp.
500 srcM.fFormat = SkMask::kA8_Format;
501 srcM.fRowBytes = SkAlign4(srcM.fBounds.width());
502 size_t size = srcM.computeImageSize();
503 a8storage.reset(size);
504 srcM.fImage = (uint8_t*)a8storage.get();
505 extract_alpha(srcM,
506 (const SkPMColor*)glyph->fImage, glyph->rowBytes());
507 }
508
509 fRec.getMatrixFrom2x2(&matrix);
510
511 if (as_MFB(fMaskFilter)->filterMask(&dstM, srcM, matrix, nullptr)) {
512 int width = SkFastMin32(origGlyph.fWidth, dstM.fBounds.width());
513 int height = SkFastMin32(origGlyph.fHeight, dstM.fBounds.height());
514 int dstRB = origGlyph.rowBytes();
515 int srcRB = dstM.fRowBytes;
516
517 const uint8_t* src = (const uint8_t*)dstM.fImage;
518 uint8_t* dst = (uint8_t*)origGlyph.fImage;
519
520 if (SkMask::k3D_Format == dstM.fFormat) {
521 // we have to copy 3 times as much
522 height *= 3;
523 }
524
525 // clean out our glyph, since it may be larger than dstM
526 //sk_bzero(dst, height * dstRB);
527
528 while (--height >= 0) {
529 memcpy(dst, src, width);
530 src += srcRB;
531 dst += dstRB;
532 }
533 SkMask::FreeImage(dstM.fImage);
534
535 if (fPreBlendForFilter.isApplicable()) {
536 applyLUTToA8Mask(srcM, fPreBlendForFilter.fG);
537 }
538 }
539 }
540 }
541
getPath(SkPackedGlyphID glyphID,SkPath * path)542 void SkScalerContext::getPath(SkPackedGlyphID glyphID, SkPath* path) {
543 this->internalGetPath(glyphID, nullptr, path, nullptr);
544 }
545
getFontMetrics(SkPaint::FontMetrics * fm)546 void SkScalerContext::getFontMetrics(SkPaint::FontMetrics* fm) {
547 SkASSERT(fm);
548 this->generateFontMetrics(fm);
549 }
550
generateGlyphToChar(uint16_t glyph)551 SkUnichar SkScalerContext::generateGlyphToChar(uint16_t glyph) {
552 return 0;
553 }
554
555 ///////////////////////////////////////////////////////////////////////////////
556
internalGetPath(SkPackedGlyphID glyphID,SkPath * fillPath,SkPath * devPath,SkMatrix * fillToDevMatrix)557 void SkScalerContext::internalGetPath(SkPackedGlyphID glyphID, SkPath* fillPath,
558 SkPath* devPath, SkMatrix* fillToDevMatrix) {
559 SkPath path;
560 generatePath(glyphID.code(), &path);
561
562 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
563 SkFixed dx = glyphID.getSubXFixed();
564 SkFixed dy = glyphID.getSubYFixed();
565 if (dx | dy) {
566 path.offset(SkFixedToScalar(dx), SkFixedToScalar(dy));
567 }
568 }
569
570 if (fRec.fFrameWidth > 0 || fPathEffect != nullptr) {
571 // need the path in user-space, with only the point-size applied
572 // so that our stroking and effects will operate the same way they
573 // would if the user had extracted the path themself, and then
574 // called drawPath
575 SkPath localPath;
576 SkMatrix matrix, inverse;
577
578 fRec.getMatrixFrom2x2(&matrix);
579 if (!matrix.invert(&inverse)) {
580 // assume fillPath and devPath are already empty.
581 return;
582 }
583 path.transform(inverse, &localPath);
584 // now localPath is only affected by the paint settings, and not the canvas matrix
585
586 SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
587
588 if (fRec.fFrameWidth > 0) {
589 rec.setStrokeStyle(fRec.fFrameWidth,
590 SkToBool(fRec.fFlags & kFrameAndFill_Flag));
591 // glyphs are always closed contours, so cap type is ignored,
592 // so we just pass something.
593 rec.setStrokeParams((SkPaint::Cap)fRec.fStrokeCap,
594 (SkPaint::Join)fRec.fStrokeJoin,
595 fRec.fMiterLimit);
596 }
597
598 if (fPathEffect) {
599 SkPath effectPath;
600 if (fPathEffect->filterPath(&effectPath, localPath, &rec, nullptr)) {
601 localPath.swap(effectPath);
602 }
603 }
604
605 if (rec.needToApply()) {
606 SkPath strokePath;
607 if (rec.applyToPath(&strokePath, localPath)) {
608 localPath.swap(strokePath);
609 }
610 }
611
612 // now return stuff to the caller
613 if (fillToDevMatrix) {
614 *fillToDevMatrix = matrix;
615 }
616 if (devPath) {
617 localPath.transform(matrix, devPath);
618 }
619 if (fillPath) {
620 fillPath->swap(localPath);
621 }
622 } else { // nothing tricky to do
623 if (fillToDevMatrix) {
624 fillToDevMatrix->reset();
625 }
626 if (devPath) {
627 if (fillPath == nullptr) {
628 devPath->swap(path);
629 } else {
630 *devPath = path;
631 }
632 }
633
634 if (fillPath) {
635 fillPath->swap(path);
636 }
637 }
638
639 if (devPath) {
640 devPath->updateBoundsCache();
641 }
642 if (fillPath) {
643 fillPath->updateBoundsCache();
644 }
645 }
646
647
getMatrixFrom2x2(SkMatrix * dst) const648 void SkScalerContextRec::getMatrixFrom2x2(SkMatrix* dst) const {
649 dst->setAll(fPost2x2[0][0], fPost2x2[0][1], 0,
650 fPost2x2[1][0], fPost2x2[1][1], 0,
651 0, 0, 1);
652 }
653
getLocalMatrix(SkMatrix * m) const654 void SkScalerContextRec::getLocalMatrix(SkMatrix* m) const {
655 SkPaintPriv::MakeTextMatrix(m, fTextSize, fPreScaleX, fPreSkewX);
656 }
657
getSingleMatrix(SkMatrix * m) const658 void SkScalerContextRec::getSingleMatrix(SkMatrix* m) const {
659 this->getLocalMatrix(m);
660
661 // now concat the device matrix
662 SkMatrix deviceMatrix;
663 this->getMatrixFrom2x2(&deviceMatrix);
664 m->postConcat(deviceMatrix);
665 }
666
computeMatrices(PreMatrixScale preMatrixScale,SkVector * s,SkMatrix * sA,SkMatrix * GsA,SkMatrix * G_inv,SkMatrix * A_out)667 bool SkScalerContextRec::computeMatrices(PreMatrixScale preMatrixScale, SkVector* s, SkMatrix* sA,
668 SkMatrix* GsA, SkMatrix* G_inv, SkMatrix* A_out)
669 {
670 // A is the 'total' matrix.
671 SkMatrix A;
672 this->getSingleMatrix(&A);
673
674 // The caller may find the 'total' matrix useful when dealing directly with EM sizes.
675 if (A_out) {
676 *A_out = A;
677 }
678
679 // GA is the matrix A with rotation removed.
680 SkMatrix GA;
681 bool skewedOrFlipped = A.getSkewX() || A.getSkewY() || A.getScaleX() < 0 || A.getScaleY() < 0;
682 if (skewedOrFlipped) {
683 // QR by Givens rotations. G is Q^T and GA is R. G is rotational (no reflections).
684 // h is where A maps the horizontal baseline.
685 SkPoint h = SkPoint::Make(SK_Scalar1, 0);
686 A.mapPoints(&h, 1);
687
688 // G is the Givens Matrix for A (rotational matrix where GA[0][1] == 0).
689 SkMatrix G;
690 SkComputeGivensRotation(h, &G);
691
692 GA = G;
693 GA.preConcat(A);
694
695 // The 'remainingRotation' is G inverse, which is fairly simple since G is 2x2 rotational.
696 if (G_inv) {
697 G_inv->setAll(
698 G.get(SkMatrix::kMScaleX), -G.get(SkMatrix::kMSkewX), G.get(SkMatrix::kMTransX),
699 -G.get(SkMatrix::kMSkewY), G.get(SkMatrix::kMScaleY), G.get(SkMatrix::kMTransY),
700 G.get(SkMatrix::kMPersp0), G.get(SkMatrix::kMPersp1), G.get(SkMatrix::kMPersp2));
701 }
702 } else {
703 GA = A;
704 if (G_inv) {
705 G_inv->reset();
706 }
707 }
708
709 // If the 'total' matrix is singular, set the 'scale' to something finite and zero the matrices.
710 // All underlying ports have issues with zero text size, so use the matricies to zero.
711 // If one of the scale factors is less than 1/256 then an EM filling square will
712 // never affect any pixels.
713 if (SkScalarAbs(GA.get(SkMatrix::kMScaleX)) <= SK_ScalarNearlyZero ||
714 SkScalarAbs(GA.get(SkMatrix::kMScaleY)) <= SK_ScalarNearlyZero)
715 {
716 s->fX = SK_Scalar1;
717 s->fY = SK_Scalar1;
718 sA->setScale(0, 0);
719 if (GsA) {
720 GsA->setScale(0, 0);
721 }
722 if (G_inv) {
723 G_inv->reset();
724 }
725 return false;
726 }
727
728 // At this point, given GA, create s.
729 switch (preMatrixScale) {
730 case kFull_PreMatrixScale:
731 s->fX = SkScalarAbs(GA.get(SkMatrix::kMScaleX));
732 s->fY = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
733 break;
734 case kVertical_PreMatrixScale: {
735 SkScalar yScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
736 s->fX = yScale;
737 s->fY = yScale;
738 break;
739 }
740 case kVerticalInteger_PreMatrixScale: {
741 SkScalar realYScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
742 SkScalar intYScale = SkScalarRoundToScalar(realYScale);
743 if (intYScale == 0) {
744 intYScale = SK_Scalar1;
745 }
746 s->fX = intYScale;
747 s->fY = intYScale;
748 break;
749 }
750 }
751
752 // The 'remaining' matrix sA is the total matrix A without the scale.
753 if (!skewedOrFlipped && (
754 (kFull_PreMatrixScale == preMatrixScale) ||
755 (kVertical_PreMatrixScale == preMatrixScale && A.getScaleX() == A.getScaleY())))
756 {
757 // If GA == A and kFull_PreMatrixScale, sA is identity.
758 // If GA == A and kVertical_PreMatrixScale and A.scaleX == A.scaleY, sA is identity.
759 sA->reset();
760 } else if (!skewedOrFlipped && kVertical_PreMatrixScale == preMatrixScale) {
761 // If GA == A and kVertical_PreMatrixScale, sA.scaleY is SK_Scalar1.
762 sA->reset();
763 sA->setScaleX(A.getScaleX() / s->fY);
764 } else {
765 // TODO: like kVertical_PreMatrixScale, kVerticalInteger_PreMatrixScale with int scales.
766 *sA = A;
767 sA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
768 }
769
770 // The 'remainingWithoutRotation' matrix GsA is the non-rotational part of A without the scale.
771 if (GsA) {
772 *GsA = GA;
773 // G is rotational so reorders with the scale.
774 GsA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
775 }
776
777 return true;
778 }
779
computeAxisAlignmentForHText()780 SkAxisAlignment SkScalerContext::computeAxisAlignmentForHText() {
781 // Why fPost2x2 can be used here.
782 // getSingleMatrix multiplies in getLocalMatrix, which consists of
783 // * fTextSize (a scale, which has no effect)
784 // * fPreScaleX (a scale in x, which has no effect)
785 // * fPreSkewX (has no effect, but would on vertical text alignment).
786 // In other words, making the text bigger, stretching it along the
787 // horizontal axis, or fake italicizing it does not move the baseline.
788
789 if (0 == fRec.fPost2x2[1][0]) {
790 // The x axis is mapped onto the x axis.
791 return kX_SkAxisAlignment;
792 }
793 if (0 == fRec.fPost2x2[0][0]) {
794 // The x axis is mapped onto the y axis.
795 return kY_SkAxisAlignment;
796 }
797 return kNone_SkAxisAlignment;
798 }
799
800 ///////////////////////////////////////////////////////////////////////////////
801
802 class SkScalerContext_Empty : public SkScalerContext {
803 public:
SkScalerContext_Empty(sk_sp<SkTypeface> typeface,const SkScalerContextEffects & effects,const SkDescriptor * desc)804 SkScalerContext_Empty(sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
805 const SkDescriptor* desc)
806 : SkScalerContext(std::move(typeface), effects, desc) {}
807
808 protected:
generateGlyphCount()809 unsigned generateGlyphCount() override {
810 return 0;
811 }
generateCharToGlyph(SkUnichar uni)812 uint16_t generateCharToGlyph(SkUnichar uni) override {
813 return 0;
814 }
generateAdvance(SkGlyph * glyph)815 void generateAdvance(SkGlyph* glyph) override {
816 glyph->zeroMetrics();
817 }
generateMetrics(SkGlyph * glyph)818 void generateMetrics(SkGlyph* glyph) override {
819 glyph->zeroMetrics();
820 }
generateImage(const SkGlyph & glyph)821 void generateImage(const SkGlyph& glyph) override {}
generatePath(SkGlyphID glyph,SkPath * path)822 void generatePath(SkGlyphID glyph, SkPath* path) override {}
generateFontMetrics(SkPaint::FontMetrics * metrics)823 void generateFontMetrics(SkPaint::FontMetrics* metrics) override {
824 if (metrics) {
825 sk_bzero(metrics, sizeof(*metrics));
826 }
827 }
828 };
829
830 extern SkScalerContext* SkCreateColorScalerContext(const SkDescriptor* desc);
831
createScalerContext(const SkScalerContextEffects & effects,const SkDescriptor * desc,bool allowFailure) const832 std::unique_ptr<SkScalerContext> SkTypeface::createScalerContext(
833 const SkScalerContextEffects& effects, const SkDescriptor* desc, bool allowFailure) const
834 {
835 std::unique_ptr<SkScalerContext> c(this->onCreateScalerContext(effects, desc));
836 if (!c && !allowFailure) {
837 c = skstd::make_unique<SkScalerContext_Empty>(sk_ref_sp(const_cast<SkTypeface*>(this)),
838 effects, desc);
839 }
840 return c;
841 }
842
843 /*
844 * Return the scalar with only limited fractional precision. Used to consolidate matrices
845 * that vary only slightly when we create our key into the font cache, since the font scaler
846 * typically returns the same looking resuts for tiny changes in the matrix.
847 */
sk_relax(SkScalar x)848 static SkScalar sk_relax(SkScalar x) {
849 SkScalar n = SkScalarRoundToScalar(x * 1024);
850 return n / 1024.0f;
851 }
852
compute_mask_format(const SkPaint & paint)853 static SkMask::Format compute_mask_format(const SkPaint& paint) {
854 uint32_t flags = paint.getFlags();
855
856 // Antialiasing being disabled trumps all other settings.
857 if (!(flags & SkPaint::kAntiAlias_Flag)) {
858 return SkMask::kBW_Format;
859 }
860
861 if (flags & SkPaint::kLCDRenderText_Flag) {
862 return SkMask::kLCD16_Format;
863 }
864
865 return SkMask::kA8_Format;
866 }
867
868 // Beyond this size, LCD doesn't appreciably improve quality, but it always
869 // cost more RAM and draws slower, so we set a cap.
870 #ifndef SK_MAX_SIZE_FOR_LCDTEXT
871 #define SK_MAX_SIZE_FOR_LCDTEXT 48
872 #endif
873
874 const SkScalar gMaxSize2ForLCDText = SK_MAX_SIZE_FOR_LCDTEXT * SK_MAX_SIZE_FOR_LCDTEXT;
875
too_big_for_lcd(const SkScalerContextRec & rec,bool checkPost2x2)876 static bool too_big_for_lcd(const SkScalerContextRec& rec, bool checkPost2x2) {
877 if (checkPost2x2) {
878 SkScalar area = rec.fPost2x2[0][0] * rec.fPost2x2[1][1] -
879 rec.fPost2x2[1][0] * rec.fPost2x2[0][1];
880 area *= rec.fTextSize * rec.fTextSize;
881 return area > gMaxSize2ForLCDText;
882 } else {
883 return rec.fTextSize > SK_MAX_SIZE_FOR_LCDTEXT;
884 }
885 }
886
887 // if linear-text is on, then we force hinting to be off (since that's sort of
888 // the point of linear-text.
computeHinting(const SkPaint & paint)889 static SkPaint::Hinting computeHinting(const SkPaint& paint) {
890 SkPaint::Hinting h = paint.getHinting();
891 if (paint.isLinearText()) {
892 h = SkPaint::kNo_Hinting;
893 }
894 return h;
895 }
896
897 // The only reason this is not file static is because it needs the context of SkScalerContext to
898 // access SkPaint::computeLuminanceColor.
MakeRecAndEffects(const SkPaint & paint,const SkSurfaceProps * surfaceProps,const SkMatrix * deviceMatrix,SkScalerContextFlags scalerContextFlags,SkScalerContextRec * rec,SkScalerContextEffects * effects)899 void SkScalerContext::MakeRecAndEffects(const SkPaint& paint,
900 const SkSurfaceProps* surfaceProps,
901 const SkMatrix* deviceMatrix,
902 SkScalerContextFlags scalerContextFlags,
903 SkScalerContextRec* rec,
904 SkScalerContextEffects* effects) {
905 SkASSERT(deviceMatrix == nullptr || !deviceMatrix->hasPerspective());
906
907 SkTypeface* typeface = paint.getTypeface();
908 if (nullptr == typeface) {
909 typeface = SkTypeface::GetDefaultTypeface();
910 }
911 rec->fFontID = typeface->uniqueID();
912 rec->fTextSize = paint.getTextSize();
913 rec->fPreScaleX = paint.getTextScaleX();
914 rec->fPreSkewX = paint.getTextSkewX();
915
916 bool checkPost2x2 = false;
917
918 if (deviceMatrix) {
919 const SkMatrix::TypeMask mask = deviceMatrix->getType();
920 if (mask & SkMatrix::kScale_Mask) {
921 rec->fPost2x2[0][0] = sk_relax(deviceMatrix->getScaleX());
922 rec->fPost2x2[1][1] = sk_relax(deviceMatrix->getScaleY());
923 checkPost2x2 = true;
924 } else {
925 rec->fPost2x2[0][0] = rec->fPost2x2[1][1] = SK_Scalar1;
926 }
927 if (mask & SkMatrix::kAffine_Mask) {
928 rec->fPost2x2[0][1] = sk_relax(deviceMatrix->getSkewX());
929 rec->fPost2x2[1][0] = sk_relax(deviceMatrix->getSkewY());
930 checkPost2x2 = true;
931 } else {
932 rec->fPost2x2[0][1] = rec->fPost2x2[1][0] = 0;
933 }
934 } else {
935 rec->fPost2x2[0][0] = rec->fPost2x2[1][1] = SK_Scalar1;
936 rec->fPost2x2[0][1] = rec->fPost2x2[1][0] = 0;
937 }
938
939 SkPaint::Style style = paint.getStyle();
940 SkScalar strokeWidth = paint.getStrokeWidth();
941
942 unsigned flags = 0;
943
944 if (paint.isFakeBoldText()) {
945 #ifdef SK_USE_FREETYPE_EMBOLDEN
946 flags |= SkScalerContext::kEmbolden_Flag;
947 #else
948 SkScalar fakeBoldScale = SkScalarInterpFunc(paint.getTextSize(),
949 kStdFakeBoldInterpKeys,
950 kStdFakeBoldInterpValues,
951 kStdFakeBoldInterpLength);
952 SkScalar extra = paint.getTextSize() * fakeBoldScale;
953
954 if (style == SkPaint::kFill_Style) {
955 style = SkPaint::kStrokeAndFill_Style;
956 strokeWidth = extra; // ignore paint's strokeWidth if it was "fill"
957 } else {
958 strokeWidth += extra;
959 }
960 #endif
961 }
962
963 if (paint.isDevKernText()) {
964 flags |= SkScalerContext::kDevKernText_Flag;
965 }
966
967 if (style != SkPaint::kFill_Style && strokeWidth > 0) {
968 rec->fFrameWidth = strokeWidth;
969 rec->fMiterLimit = paint.getStrokeMiter();
970 rec->fStrokeJoin = SkToU8(paint.getStrokeJoin());
971 rec->fStrokeCap = SkToU8(paint.getStrokeCap());
972
973 if (style == SkPaint::kStrokeAndFill_Style) {
974 flags |= SkScalerContext::kFrameAndFill_Flag;
975 }
976 } else {
977 rec->fFrameWidth = 0;
978 rec->fMiterLimit = 0;
979 rec->fStrokeJoin = 0;
980 rec->fStrokeCap = 0;
981 }
982
983 rec->fMaskFormat = SkToU8(compute_mask_format(paint));
984
985 if (SkMask::kLCD16_Format == rec->fMaskFormat) {
986 if (too_big_for_lcd(*rec, checkPost2x2)) {
987 rec->fMaskFormat = SkMask::kA8_Format;
988 flags |= SkScalerContext::kGenA8FromLCD_Flag;
989 } else {
990 SkPixelGeometry geometry = surfaceProps
991 ? surfaceProps->pixelGeometry()
992 : SkSurfacePropsDefaultPixelGeometry();
993 switch (geometry) {
994 case kUnknown_SkPixelGeometry:
995 // eeek, can't support LCD
996 rec->fMaskFormat = SkMask::kA8_Format;
997 flags |= SkScalerContext::kGenA8FromLCD_Flag;
998 break;
999 case kRGB_H_SkPixelGeometry:
1000 // our default, do nothing.
1001 break;
1002 case kBGR_H_SkPixelGeometry:
1003 flags |= SkScalerContext::kLCD_BGROrder_Flag;
1004 break;
1005 case kRGB_V_SkPixelGeometry:
1006 flags |= SkScalerContext::kLCD_Vertical_Flag;
1007 break;
1008 case kBGR_V_SkPixelGeometry:
1009 flags |= SkScalerContext::kLCD_Vertical_Flag;
1010 flags |= SkScalerContext::kLCD_BGROrder_Flag;
1011 break;
1012 }
1013 }
1014 }
1015
1016 if (paint.isEmbeddedBitmapText()) {
1017 flags |= SkScalerContext::kEmbeddedBitmapText_Flag;
1018 }
1019 if (paint.isSubpixelText()) {
1020 flags |= SkScalerContext::kSubpixelPositioning_Flag;
1021 }
1022 if (paint.isAutohinted()) {
1023 flags |= SkScalerContext::kForceAutohinting_Flag;
1024 }
1025 if (paint.isVerticalText()) {
1026 flags |= SkScalerContext::kVertical_Flag;
1027 }
1028 if (paint.getFlags() & SkPaint::kGenA8FromLCD_Flag) {
1029 flags |= SkScalerContext::kGenA8FromLCD_Flag;
1030 }
1031 rec->fFlags = SkToU16(flags);
1032
1033 // these modify fFlags, so do them after assigning fFlags
1034 rec->setHinting(computeHinting(paint));
1035
1036 rec->setLuminanceColor(paint.computeLuminanceColor());
1037
1038 // For now always set the paint gamma equal to the device gamma.
1039 // The math in SkMaskGamma can handle them being different,
1040 // but it requires superluminous masks when
1041 // Ex : deviceGamma(x) < paintGamma(x) and x is sufficiently large.
1042 rec->setDeviceGamma(SK_GAMMA_EXPONENT);
1043 rec->setPaintGamma(SK_GAMMA_EXPONENT);
1044
1045 #ifdef SK_GAMMA_CONTRAST
1046 rec->setContrast(SK_GAMMA_CONTRAST);
1047 #else
1048 // A value of 0.5 for SK_GAMMA_CONTRAST appears to be a good compromise.
1049 // With lower values small text appears washed out (though correctly so).
1050 // With higher values lcd fringing is worse and the smoothing effect of
1051 // partial coverage is diminished.
1052 rec->setContrast(0.5f);
1053 #endif
1054
1055 rec->fReservedAlign = 0;
1056
1057 // Allow the fonthost to modify our rec before we use it as a key into the
1058 // cache. This way if we're asking for something that they will ignore,
1059 // they can modify our rec up front, so we don't create duplicate cache
1060 // entries.
1061 typeface->onFilterRec(rec);
1062
1063 if (!SkToBool(scalerContextFlags & SkScalerContextFlags::kFakeGamma)) {
1064 rec->ignoreGamma();
1065 }
1066 if (!SkToBool(scalerContextFlags & SkScalerContextFlags::kBoostContrast)) {
1067 rec->setContrast(0);
1068 }
1069
1070 new (effects) SkScalerContextEffects{paint};
1071 if (effects->fPathEffect) {
1072 rec->fMaskFormat = SkMask::kA8_Format; // force antialiasing when we do the scan conversion
1073 // seems like we could support kLCD as well at this point...
1074 }
1075 if (effects->fMaskFilter) {
1076 // force antialiasing with maskfilters
1077 rec->fMaskFormat = SkMask::kA8_Format;
1078 // Pre-blend is not currently applied to filtered text.
1079 // The primary filter is blur, for which contrast makes no sense,
1080 // and for which the destination guess error is more visible.
1081 // Also, all existing users of blur have calibrated for linear.
1082 rec->ignorePreBlend();
1083 }
1084
1085 // If we're asking for A8, we force the colorlum to be gray, since that
1086 // limits the number of unique entries, and the scaler will only look at
1087 // the lum of one of them.
1088 switch (rec->fMaskFormat) {
1089 case SkMask::kLCD16_Format: {
1090 // filter down the luminance color to a finite number of bits
1091 SkColor color = rec->getLuminanceColor();
1092 rec->setLuminanceColor(SkMaskGamma::CanonicalColor(color));
1093 break;
1094 }
1095 case SkMask::kA8_Format: {
1096 // filter down the luminance to a single component, since A8 can't
1097 // use per-component information
1098 SkColor color = rec->getLuminanceColor();
1099 U8CPU lum = SkComputeLuminance(SkColorGetR(color),
1100 SkColorGetG(color),
1101 SkColorGetB(color));
1102 // reduce to our finite number of bits
1103 color = SkColorSetRGB(lum, lum, lum);
1104 rec->setLuminanceColor(SkMaskGamma::CanonicalColor(color));
1105 break;
1106 }
1107 case SkMask::kBW_Format:
1108 // No need to differentiate gamma or apply contrast if we're BW
1109 rec->ignorePreBlend();
1110 break;
1111 }
1112 }
1113
1114
CreateDescriptorAndEffectsUsingPaint(const SkPaint & paint,const SkSurfaceProps * surfaceProps,SkScalerContextFlags scalerContextFlags,const SkMatrix * deviceMatrix,SkAutoDescriptor * ad,SkScalerContextEffects * effects)1115 SkDescriptor* SkScalerContext::CreateDescriptorAndEffectsUsingPaint(
1116 const SkPaint& paint, const SkSurfaceProps* surfaceProps,
1117 SkScalerContextFlags scalerContextFlags,
1118 const SkMatrix* deviceMatrix, SkAutoDescriptor* ad,
1119 SkScalerContextEffects* effects) {
1120
1121 SkScalerContextRec rec;
1122 MakeRecAndEffects(paint, surfaceProps, deviceMatrix, scalerContextFlags, &rec, effects);
1123 return AutoDescriptorGivenRecAndEffects(rec, *effects, ad);
1124 }
1125
calculate_size_and_flatten(const SkScalerContextRec & rec,const SkScalerContextEffects & effects,SkBinaryWriteBuffer * pathEffectBuffer,SkBinaryWriteBuffer * maskFilterBuffer)1126 static size_t calculate_size_and_flatten(
1127 const SkScalerContextRec& rec,
1128 const SkScalerContextEffects& effects,
1129 SkBinaryWriteBuffer* pathEffectBuffer,
1130 SkBinaryWriteBuffer* maskFilterBuffer)
1131 {
1132 size_t descSize = sizeof(rec);
1133 int entryCount = 1;
1134
1135 if (effects.fPathEffect) {
1136 effects.fPathEffect->flatten(*pathEffectBuffer);
1137 descSize += pathEffectBuffer->bytesWritten();
1138 entryCount += 1;
1139 }
1140 if (effects.fMaskFilter) {
1141 effects.fMaskFilter->flatten(*maskFilterBuffer);
1142 descSize += maskFilterBuffer->bytesWritten();
1143 entryCount += 1;
1144 }
1145
1146 descSize += SkDescriptor::ComputeOverhead(entryCount);
1147 return descSize;
1148 }
1149
1150 #ifdef SK_DEBUG
1151 #define TEST_DESC
1152 #endif
1153
1154 #ifdef TEST_DESC
test_desc(const SkScalerContextRec & rec,const SkScalerContextEffects & effects,SkBinaryWriteBuffer * peBuffer,SkBinaryWriteBuffer * mfBuffer,const SkDescriptor * desc)1155 static void test_desc(const SkScalerContextRec& rec,
1156 const SkScalerContextEffects& effects,
1157 SkBinaryWriteBuffer* peBuffer,
1158 SkBinaryWriteBuffer* mfBuffer,
1159 const SkDescriptor* desc) {
1160 // Check that we completely write the bytes in desc (our key), and that
1161 // there are no uninitialized bytes. If there were, then we would get
1162 // false-misses (or worse, false-hits) in our fontcache.
1163 //
1164 // We do this buy filling 2 others, one with 0s and the other with 1s
1165 // and create those, and then check that all 3 are identical.
1166 SkAutoDescriptor ad1(desc->getLength());
1167 SkAutoDescriptor ad2(desc->getLength());
1168 SkDescriptor* desc1 = ad1.getDesc();
1169 SkDescriptor* desc2 = ad2.getDesc();
1170
1171 memset(desc1, 0x00, desc->getLength());
1172 memset(desc2, 0xFF, desc->getLength());
1173
1174 desc1->init();
1175 desc2->init();
1176 desc1->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec);
1177 desc2->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec);
1178
1179 auto add_flattenable = [](SkDescriptor* desc, uint32_t tag,
1180 SkBinaryWriteBuffer* buffer) {
1181 buffer->writeToMemory(desc->addEntry(tag, buffer->bytesWritten(), nullptr));
1182 };
1183
1184 if (effects.fPathEffect) {
1185 add_flattenable(desc1, kPathEffect_SkDescriptorTag, peBuffer);
1186 add_flattenable(desc2, kPathEffect_SkDescriptorTag, peBuffer);
1187 }
1188 if (effects.fMaskFilter) {
1189 add_flattenable(desc1, kMaskFilter_SkDescriptorTag, mfBuffer);
1190 add_flattenable(desc2, kMaskFilter_SkDescriptorTag, mfBuffer);
1191 }
1192
1193 SkASSERT(desc->getLength() == desc1->getLength());
1194 SkASSERT(desc->getLength() == desc2->getLength());
1195 desc1->computeChecksum();
1196 desc2->computeChecksum();
1197 SkASSERT(!memcmp(desc, desc1, desc->getLength()));
1198 SkASSERT(!memcmp(desc, desc2, desc->getLength()));
1199 }
1200 #endif
1201
generate_descriptor(const SkScalerContextRec & rec,const SkScalerContextEffects & effects,SkBinaryWriteBuffer * pathEffectBuffer,SkBinaryWriteBuffer * maskFilterBuffer,SkDescriptor * desc)1202 void generate_descriptor(
1203 const SkScalerContextRec& rec,
1204 const SkScalerContextEffects& effects,
1205 SkBinaryWriteBuffer* pathEffectBuffer,
1206 SkBinaryWriteBuffer* maskFilterBuffer,
1207 SkDescriptor* desc)
1208 {
1209 desc->init();
1210 desc->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec);
1211
1212 auto add = [&desc](uint32_t tag, SkBinaryWriteBuffer* buffer) {
1213 buffer->writeToMemory(desc->addEntry(tag, buffer->bytesWritten(), nullptr));
1214 };
1215
1216 if (effects.fPathEffect) {
1217 add(kPathEffect_SkDescriptorTag, pathEffectBuffer);
1218 }
1219 if (effects.fMaskFilter) {
1220 add(kMaskFilter_SkDescriptorTag, maskFilterBuffer);
1221 }
1222
1223 desc->computeChecksum();
1224 #ifdef TEST_DESC
1225 test_desc(rec, effects, pathEffectBuffer, maskFilterBuffer, desc);
1226 #endif
1227 }
1228
AutoDescriptorGivenRecAndEffects(const SkScalerContextRec & rec,const SkScalerContextEffects & effects,SkAutoDescriptor * ad)1229 SkDescriptor* SkScalerContext::AutoDescriptorGivenRecAndEffects(
1230 const SkScalerContextRec& rec,
1231 const SkScalerContextEffects& effects,
1232 SkAutoDescriptor* ad)
1233 {
1234 SkBinaryWriteBuffer peBuffer, mfBuffer;
1235
1236 ad->reset(calculate_size_and_flatten(rec, effects, &peBuffer, &mfBuffer));
1237
1238 generate_descriptor(rec, effects, &peBuffer, &mfBuffer, ad->getDesc());
1239
1240 return ad->getDesc();
1241 }
1242
DescriptorGivenRecAndEffects(const SkScalerContextRec & rec,const SkScalerContextEffects & effects)1243 std::unique_ptr<SkDescriptor> SkScalerContext::DescriptorGivenRecAndEffects(
1244 const SkScalerContextRec& rec,
1245 const SkScalerContextEffects& effects)
1246 {
1247 SkBinaryWriteBuffer peBuffer, mfBuffer;
1248
1249 auto desc = SkDescriptor::Alloc(calculate_size_and_flatten(rec, effects, &peBuffer, &mfBuffer));
1250
1251 generate_descriptor(rec, effects, &peBuffer, &mfBuffer, desc.get());
1252
1253 return desc;
1254 }
1255
DescriptorBufferGiveRec(const SkScalerContextRec & rec,void * buffer)1256 void SkScalerContext::DescriptorBufferGiveRec(const SkScalerContextRec& rec, void* buffer) {
1257 SkScalerContextEffects noEffects;
1258 SkBinaryWriteBuffer peBuffer, mfBuffer;
1259 generate_descriptor(rec, noEffects, &peBuffer, &mfBuffer, (SkDescriptor*)buffer);
1260 }
1261
CheckBufferSizeForRec(const SkScalerContextRec & rec,const SkScalerContextEffects & effects,size_t size)1262 bool SkScalerContext::CheckBufferSizeForRec(const SkScalerContextRec& rec,
1263 const SkScalerContextEffects& effects,
1264 size_t size) {
1265 SkBinaryWriteBuffer peBuffer, mfBuffer;
1266
1267 return size >= calculate_size_and_flatten(rec, effects, &peBuffer, &mfBuffer);
1268 }
1269
1270
1271
1272
1273