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