• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/SkMaskGamma.h"
24 #include "src/core/SkMatrixProvider.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 
makeGlyph(SkPackedGlyphID packedID)180 SkGlyph SkScalerContext::makeGlyph(SkPackedGlyphID packedID) {
181     return internalMakeGlyph(packedID, fRec.fMaskFormat);
182 }
183 
internalMakeGlyph(SkPackedGlyphID packedID,SkMask::Format format)184 SkGlyph SkScalerContext::internalMakeGlyph(SkPackedGlyphID packedID, SkMask::Format format) {
185     SkGlyph glyph{packedID};
186     glyph.fMaskFormat = format;
187     bool generatingImageFromPath = fGenerateImageFromPath;
188     if (!generatingImageFromPath) {
189         generateMetrics(&glyph);
190     } else {
191         SkPath devPath;
192         bool hairline;
193         generatingImageFromPath = this->internalGetPath(glyph.getPackedID(), &devPath, &hairline);
194         if (!generatingImageFromPath) {
195             generateMetrics(&glyph);
196         } else {
197             if (!generateAdvance(&glyph)) {
198                 generateMetrics(&glyph);
199             }
200 
201             // If we are going to create the mask, then we cannot keep the color
202             if (SkMask::kARGB32_Format == glyph.fMaskFormat) {
203                 glyph.fMaskFormat = SkMask::kA8_Format;
204             }
205 
206             const SkIRect ir = devPath.getBounds().roundOut();
207             if (ir.isEmpty() || !SkRectPriv::Is16Bit(ir)) {
208                 goto SK_ERROR;
209             }
210             glyph.fLeft    = ir.fLeft;
211             glyph.fTop     = ir.fTop;
212             glyph.fWidth   = SkToU16(ir.width());
213             glyph.fHeight  = SkToU16(ir.height());
214 
215             const bool a8FromLCD = fRec.fFlags & SkScalerContext::kGenA8FromLCD_Flag;
216             const bool fromLCD = (glyph.fMaskFormat == SkMask::kLCD16_Format) ||
217                                  (glyph.fMaskFormat == SkMask::kA8_Format && a8FromLCD);
218             const bool notEmptyAndFromLCD = 0 < glyph.fWidth && fromLCD;
219             const bool verticalLCD = fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag;
220 
221             const bool needExtraWidth  = (notEmptyAndFromLCD && !verticalLCD) || hairline;
222             const bool needExtraHeight = (notEmptyAndFromLCD &&  verticalLCD) || hairline;
223             if (needExtraWidth) {
224                 glyph.fWidth += 2;
225                 glyph.fLeft -= 1;
226             }
227             if (needExtraHeight) {
228                 glyph.fHeight += 2;
229                 glyph.fTop -= 1;
230             }
231         }
232     }
233 
234     // if either dimension is empty, zap the image bounds of the glyph
235     if (0 == glyph.fWidth || 0 == glyph.fHeight) {
236         glyph.fWidth   = 0;
237         glyph.fHeight  = 0;
238         glyph.fTop     = 0;
239         glyph.fLeft    = 0;
240         glyph.fMaskFormat = SkMask::kBW_Format;
241         return glyph;
242     }
243 
244     if (fMaskFilter) {
245         SkMask      src = glyph.mask(),
246                     dst;
247         SkMatrix    matrix;
248 
249         fRec.getMatrixFrom2x2(&matrix);
250 
251         src.fImage = nullptr;  // only want the bounds from the filter
252         if (as_MFB(fMaskFilter)->filterMask(&dst, src, matrix, nullptr)) {
253             if (dst.fBounds.isEmpty() || !SkRectPriv::Is16Bit(dst.fBounds)) {
254                 goto SK_ERROR;
255             }
256             SkASSERT(dst.fImage == nullptr);
257             glyph.fLeft    = dst.fBounds.fLeft;
258             glyph.fTop     = dst.fBounds.fTop;
259             glyph.fWidth   = SkToU16(dst.fBounds.width());
260             glyph.fHeight  = SkToU16(dst.fBounds.height());
261             glyph.fMaskFormat = dst.fFormat;
262         }
263     }
264     return glyph;
265 
266 SK_ERROR:
267     // draw nothing 'cause we failed
268     glyph.fLeft     = 0;
269     glyph.fTop      = 0;
270     glyph.fWidth    = 0;
271     glyph.fHeight   = 0;
272     glyph.fMaskFormat = fRec.fMaskFormat;
273     return glyph;
274 }
275 
276 #define SK_SHOW_TEXT_BLIT_COVERAGE 0
277 
applyLUTToA8Mask(const SkMask & mask,const uint8_t * lut)278 static void applyLUTToA8Mask(const SkMask& mask, const uint8_t* lut) {
279     uint8_t* SK_RESTRICT dst = (uint8_t*)mask.fImage;
280     unsigned rowBytes = mask.fRowBytes;
281 
282     for (int y = mask.fBounds.height() - 1; y >= 0; --y) {
283         for (int x = mask.fBounds.width() - 1; x >= 0; --x) {
284             dst[x] = lut[dst[x]];
285         }
286         dst += rowBytes;
287     }
288 }
289 
pack4xHToMask(const SkPixmap & src,const SkMask & dst,const SkMaskGamma::PreBlend & maskPreBlend,const bool doBGR,const bool doVert)290 static void pack4xHToMask(const SkPixmap& src, const SkMask& dst,
291                           const SkMaskGamma::PreBlend& maskPreBlend,
292                           const bool doBGR, const bool doVert) {
293 #define SAMPLES_PER_PIXEL 4
294 #define LCD_PER_PIXEL 3
295     SkASSERT(kAlpha_8_SkColorType == src.colorType());
296 
297     const bool toA8 = SkMask::kA8_Format == dst.fFormat;
298     SkASSERT(SkMask::kLCD16_Format == dst.fFormat || toA8);
299 
300     // doVert in this function means swap x and y when writing to dst.
301     if (doVert) {
302         SkASSERT(src.width() == (dst.fBounds.height() - 2) * 4);
303         SkASSERT(src.height() == dst.fBounds.width());
304     } else {
305         SkASSERT(src.width() == (dst.fBounds.width() - 2) * 4);
306         SkASSERT(src.height() == dst.fBounds.height());
307     }
308 
309     const int sample_width = src.width();
310     const int height = src.height();
311 
312     uint8_t* dstImage = dst.fImage;
313     size_t dstRB = dst.fRowBytes;
314     // An N tap FIR is defined by
315     // out[n] = coeff[0]*x[n] + coeff[1]*x[n-1] + ... + coeff[N]*x[n-N]
316     // or
317     // out[n] = sum(i, 0, N, coeff[i]*x[n-i])
318 
319     // The strategy is to use one FIR (different coefficients) for each of r, g, and b.
320     // This means using every 4th FIR output value of each FIR and discarding the rest.
321     // The FIRs are aligned, and the coefficients reach 5 samples to each side of their 'center'.
322     // (For r and b this is technically incorrect, but the coeffs outside round to zero anyway.)
323 
324     // These are in some fixed point repesentation.
325     // Adding up to more than one simulates ink spread.
326     // For implementation reasons, these should never add up to more than two.
327 
328     // Coefficients determined by a gausian where 5 samples = 3 std deviations (0x110 'contrast').
329     // Calculated using tools/generate_fir_coeff.py
330     // With this one almost no fringing is ever seen, but it is imperceptibly blurry.
331     // The lcd smoothed text is almost imperceptibly different from gray,
332     // but is still sharper on small stems and small rounded corners than gray.
333     // This also seems to be about as wide as one can get and only have a three pixel kernel.
334     // TODO: calculate these at runtime so parameters can be adjusted (esp contrast).
335     static const unsigned int coefficients[LCD_PER_PIXEL][SAMPLES_PER_PIXEL*3] = {
336         //The red subpixel is centered inside the first sample (at 1/6 pixel), and is shifted.
337         { 0x03, 0x0b, 0x1c, 0x33,  0x40, 0x39, 0x24, 0x10,  0x05, 0x01, 0x00, 0x00, },
338         //The green subpixel is centered between two samples (at 1/2 pixel), so is symetric
339         { 0x00, 0x02, 0x08, 0x16,  0x2b, 0x3d, 0x3d, 0x2b,  0x16, 0x08, 0x02, 0x00, },
340         //The blue subpixel is centered inside the last sample (at 5/6 pixel), and is shifted.
341         { 0x00, 0x00, 0x01, 0x05,  0x10, 0x24, 0x39, 0x40,  0x33, 0x1c, 0x0b, 0x03, },
342     };
343 
344     size_t dstPB = toA8 ? sizeof(uint8_t) : sizeof(uint16_t);
345     for (int y = 0; y < height; ++y) {
346         uint8_t* dstP;
347         size_t dstPDelta;
348         if (doVert) {
349             dstP = SkTAddOffset<uint8_t>(dstImage, y * dstPB);
350             dstPDelta = dstRB;
351         } else {
352             dstP = SkTAddOffset<uint8_t>(dstImage, y * dstRB);
353             dstPDelta = dstPB;
354         }
355 
356         const uint8_t* srcP = src.addr8(0, y);
357 
358         // TODO: this fir filter implementation is straight forward, but slow.
359         // It should be possible to make it much faster.
360         for (int sample_x = -4; sample_x < sample_width + 4; sample_x += 4) {
361             int fir[LCD_PER_PIXEL] = { 0 };
362             for (int sample_index = std::max(0, sample_x - 4), coeff_index = sample_index - (sample_x - 4)
363                 ; sample_index < std::min(sample_x + 8, sample_width)
364                 ; ++sample_index, ++coeff_index)
365             {
366                 int sample_value = srcP[sample_index];
367                 for (int subpxl_index = 0; subpxl_index < LCD_PER_PIXEL; ++subpxl_index) {
368                     fir[subpxl_index] += coefficients[subpxl_index][coeff_index] * sample_value;
369                 }
370             }
371             for (int subpxl_index = 0; subpxl_index < LCD_PER_PIXEL; ++subpxl_index) {
372                 fir[subpxl_index] /= 0x100;
373                 fir[subpxl_index] = std::min(fir[subpxl_index], 255);
374             }
375 
376             U8CPU r, g, b;
377             if (doBGR) {
378                 r = fir[2];
379                 g = fir[1];
380                 b = fir[0];
381             } else {
382                 r = fir[0];
383                 g = fir[1];
384                 b = fir[2];
385             }
386 #if SK_SHOW_TEXT_BLIT_COVERAGE
387             r = std::max(r, 10); g = std::max(g, 10); b = std::max(b, 10);
388 #endif
389             if (toA8) {
390                 U8CPU a = (r + g + b) / 3;
391                 if (maskPreBlend.isApplicable()) {
392                     a = maskPreBlend.fG[a];
393                 }
394                 *dstP = a;
395             } else {
396                 if (maskPreBlend.isApplicable()) {
397                     r = maskPreBlend.fR[r];
398                     g = maskPreBlend.fG[g];
399                     b = maskPreBlend.fB[b];
400                 }
401                 *(uint16_t*)dstP = SkPack888ToRGB16(r, g, b);
402             }
403             dstP = SkTAddOffset<uint8_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,const bool doBGR,const bool doVert,const bool a8FromLCD,const bool hairline)454 static void generateMask(const SkMask& mask, const SkPath& path,
455                          const SkMaskGamma::PreBlend& maskPreBlend,
456                          const bool doBGR, const bool doVert, const bool a8FromLCD,
457                          const bool hairline) {
458     SkASSERT(mask.fFormat == SkMask::kBW_Format ||
459              mask.fFormat == SkMask::kA8_Format ||
460              mask.fFormat == SkMask::kLCD16_Format);
461 
462     SkPaint paint;
463     SkPath strokePath;
464     const SkPath* pathToUse = &path;
465 
466     int srcW = mask.fBounds.width();
467     int srcH = mask.fBounds.height();
468     int dstW = srcW;
469     int dstH = srcH;
470 
471     SkMatrix matrix;
472     matrix.setTranslate(-SkIntToScalar(mask.fBounds.fLeft),
473                         -SkIntToScalar(mask.fBounds.fTop));
474 
475     paint.setStroke(hairline);
476     paint.setAntiAlias(SkMask::kBW_Format != mask.fFormat);
477 
478     const bool fromLCD = (mask.fFormat == SkMask::kLCD16_Format) ||
479                          (mask.fFormat == SkMask::kA8_Format && a8FromLCD);
480     const bool intermediateDst = fromLCD || mask.fFormat == SkMask::kBW_Format;
481     if (fromLCD) {
482         if (doVert) {
483             dstW = 4*dstH - 8;
484             dstH = srcW;
485             matrix.setAll(0, 4, -SkIntToScalar(mask.fBounds.fTop + 1) * 4,
486                           1, 0, -SkIntToScalar(mask.fBounds.fLeft),
487                           0, 0, 1);
488         } else {
489             dstW = 4*dstW - 8;
490             matrix.setAll(4, 0, -SkIntToScalar(mask.fBounds.fLeft + 1) * 4,
491                           0, 1, -SkIntToScalar(mask.fBounds.fTop),
492                           0, 0, 1);
493         }
494 
495         // LCD hairline doesn't line up with the pixels, so do it the expensive way.
496         SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
497         if (hairline) {
498             rec.setStrokeStyle(1.0f, false);
499             rec.setStrokeParams(SkPaint::kButt_Cap, SkPaint::kRound_Join, 0.0f);
500         }
501         if (rec.needToApply() && rec.applyToPath(&strokePath, path)) {
502             pathToUse = &strokePath;
503             paint.setStyle(SkPaint::kFill_Style);
504         }
505     }
506 
507     SkRasterClip clip;
508     clip.setRect(SkIRect::MakeWH(dstW, dstH));
509 
510     const SkImageInfo info = SkImageInfo::MakeA8(dstW, dstH);
511     SkAutoPixmapStorage dst;
512 
513     if (intermediateDst) {
514         if (!dst.tryAlloc(info)) {
515             // can't allocate offscreen, so empty the mask and return
516             sk_bzero(mask.fImage, mask.computeImageSize());
517             return;
518         }
519     } else {
520         dst.reset(info, mask.fImage, mask.fRowBytes);
521     }
522     sk_bzero(dst.writable_addr(), dst.computeByteSize());
523 
524     SkDraw  draw;
525     SkSimpleMatrixProvider matrixProvider(matrix);
526     draw.fDst            = dst;
527     draw.fRC             = &clip;
528     draw.fMatrixProvider = &matrixProvider;
529     draw.drawPath(*pathToUse, paint);
530 
531     switch (mask.fFormat) {
532         case SkMask::kBW_Format:
533             packA8ToA1(mask, dst.addr8(0, 0), dst.rowBytes());
534             break;
535         case SkMask::kA8_Format:
536             if (fromLCD) {
537                 pack4xHToMask(dst, mask, maskPreBlend, doBGR, doVert);
538             } else if (maskPreBlend.isApplicable()) {
539                 applyLUTToA8Mask(mask, maskPreBlend.fG);
540             }
541             break;
542         case SkMask::kLCD16_Format:
543             pack4xHToMask(dst, mask, maskPreBlend, doBGR, doVert);
544             break;
545         default:
546             break;
547     }
548 }
549 
getImage(const SkGlyph & origGlyph)550 void SkScalerContext::getImage(const SkGlyph& origGlyph) {
551     const SkGlyph* unfilteredGlyph = &origGlyph;
552     // in case we need to call generateImage on a mask-format that is different
553     // (i.e. larger) than what our caller allocated by looking at origGlyph.
554     SkAutoMalloc tmpGlyphImageStorage;
555     SkGlyph tmpGlyph;
556     if (fMaskFilter) {
557         // need the original bounds, sans our maskfilter
558         sk_sp<SkMaskFilter> mf = std::move(fMaskFilter);
559         tmpGlyph = this->internalMakeGlyph(origGlyph.getPackedID(), fRec.fMaskFormat);
560         fMaskFilter = std::move(mf);
561 
562         // Use the origGlyph storage for the temporary unfiltered mask if it will fit.
563         if (tmpGlyph.fMaskFormat == origGlyph.fMaskFormat &&
564             tmpGlyph.imageSize() <= origGlyph.imageSize())
565         {
566             tmpGlyph.fImage = origGlyph.fImage;
567         } else {
568             tmpGlyphImageStorage.reset(tmpGlyph.imageSize());
569             tmpGlyph.fImage = tmpGlyphImageStorage.get();
570         }
571         unfilteredGlyph = &tmpGlyph;
572     }
573 
574     if (!fGenerateImageFromPath) {
575         generateImage(*unfilteredGlyph);
576     } else {
577         SkPath devPath;
578         SkMask mask = unfilteredGlyph->mask();
579         bool hairline;
580 
581         if (!this->internalGetPath(unfilteredGlyph->getPackedID(), &devPath, &hairline)) {
582             generateImage(*unfilteredGlyph);
583         } else {
584             SkASSERT(SkMask::kARGB32_Format != origGlyph.fMaskFormat);
585             SkASSERT(SkMask::kARGB32_Format != mask.fFormat);
586             const bool doBGR = SkToBool(fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag);
587             const bool doVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
588             const bool a8LCD = SkToBool(fRec.fFlags & SkScalerContext::kGenA8FromLCD_Flag);
589             generateMask(mask, devPath, fPreBlend, doBGR, doVert, a8LCD, hairline);
590         }
591     }
592 
593     if (fMaskFilter) {
594         // k3D_Format should not be mask filtered.
595         SkASSERT(SkMask::k3D_Format != unfilteredGlyph->fMaskFormat);
596 
597         SkMask filteredMask;
598         SkMask srcMask;
599         SkMatrix m;
600         fRec.getMatrixFrom2x2(&m);
601 
602         if (as_MFB(fMaskFilter)->filterMask(&filteredMask, unfilteredGlyph->mask(), m, nullptr)) {
603             // Filter succeeded; filteredMask.fImage was allocated.
604             srcMask = filteredMask;
605         } else if (unfilteredGlyph->fImage == tmpGlyphImageStorage.get()) {
606             // Filter did nothing; unfiltered mask is independent of origGlyph.fImage.
607             srcMask = unfilteredGlyph->mask();
608         } else if (origGlyph.iRect() == unfilteredGlyph->iRect()) {
609             // Filter did nothing; the unfiltered mask is in origGlyph.fImage and matches.
610             return;
611         } else {
612             // Filter did nothing; the unfiltered mask is in origGlyph.fImage and conflicts.
613             srcMask = unfilteredGlyph->mask();
614             size_t imageSize = unfilteredGlyph->imageSize();
615             tmpGlyphImageStorage.reset(imageSize);
616             srcMask.fImage = static_cast<uint8_t*>(tmpGlyphImageStorage.get());
617             memcpy(srcMask.fImage, unfilteredGlyph->fImage, imageSize);
618         }
619 
620         SkASSERT_RELEASE(srcMask.fFormat == origGlyph.fMaskFormat);
621         SkMask dstMask = origGlyph.mask();
622         SkIRect origBounds = dstMask.fBounds;
623 
624         // Find the intersection of src and dst while updating the fImages.
625         if (srcMask.fBounds.fTop < dstMask.fBounds.fTop) {
626             int32_t topDiff = dstMask.fBounds.fTop - srcMask.fBounds.fTop;
627             srcMask.fImage += srcMask.fRowBytes * topDiff;
628             srcMask.fBounds.fTop = dstMask.fBounds.fTop;
629         }
630         if (dstMask.fBounds.fTop < srcMask.fBounds.fTop) {
631             int32_t topDiff = srcMask.fBounds.fTop - dstMask.fBounds.fTop;
632             dstMask.fImage += dstMask.fRowBytes * topDiff;
633             dstMask.fBounds.fTop = srcMask.fBounds.fTop;
634         }
635 
636         if (srcMask.fBounds.fLeft < dstMask.fBounds.fLeft) {
637             int32_t leftDiff = dstMask.fBounds.fLeft - srcMask.fBounds.fLeft;
638             srcMask.fImage += leftDiff;
639             srcMask.fBounds.fLeft = dstMask.fBounds.fLeft;
640         }
641         if (dstMask.fBounds.fLeft < srcMask.fBounds.fLeft) {
642             int32_t leftDiff = srcMask.fBounds.fLeft - dstMask.fBounds.fLeft;
643             dstMask.fImage += leftDiff;
644             dstMask.fBounds.fLeft = srcMask.fBounds.fLeft;
645         }
646 
647         if (srcMask.fBounds.fBottom < dstMask.fBounds.fBottom) {
648             dstMask.fBounds.fBottom = srcMask.fBounds.fBottom;
649         }
650         if (dstMask.fBounds.fBottom < srcMask.fBounds.fBottom) {
651             srcMask.fBounds.fBottom = dstMask.fBounds.fBottom;
652         }
653 
654         if (srcMask.fBounds.fRight < dstMask.fBounds.fRight) {
655             dstMask.fBounds.fRight = srcMask.fBounds.fRight;
656         }
657         if (dstMask.fBounds.fRight < srcMask.fBounds.fRight) {
658             srcMask.fBounds.fRight = dstMask.fBounds.fRight;
659         }
660 
661         SkASSERT(srcMask.fBounds == dstMask.fBounds);
662         int width = srcMask.fBounds.width();
663         int height = srcMask.fBounds.height();
664         int dstRB = dstMask.fRowBytes;
665         int srcRB = srcMask.fRowBytes;
666 
667         const uint8_t* src = srcMask.fImage;
668         uint8_t* dst = dstMask.fImage;
669 
670         if (SkMask::k3D_Format == filteredMask.fFormat) {
671             // we have to copy 3 times as much
672             height *= 3;
673         }
674 
675         // If not filling the full original glyph, clear it out first.
676         if (dstMask.fBounds != origBounds) {
677             sk_bzero(origGlyph.fImage, origGlyph.fHeight * origGlyph.rowBytes());
678         }
679 
680         while (--height >= 0) {
681             memcpy(dst, src, width);
682             src += srcRB;
683             dst += dstRB;
684         }
685         SkMask::FreeImage(filteredMask.fImage);
686     }
687 }
688 
getPath(SkPackedGlyphID glyphID,SkPath * path)689 bool SkScalerContext::getPath(SkPackedGlyphID glyphID, SkPath* path) {
690     // TODO: return hairline so user knows to stroke.
691     // Most users get the fill path without path effect and then draw that, so don't need this.
692     return this->internalGetPath(glyphID, path, nullptr);
693 }
694 
getFontMetrics(SkFontMetrics * fm)695 void SkScalerContext::getFontMetrics(SkFontMetrics* fm) {
696     SkASSERT(fm);
697     this->generateFontMetrics(fm);
698 }
699 
700 ///////////////////////////////////////////////////////////////////////////////
701 
internalGetPath(SkPackedGlyphID glyphID,SkPath * devPath,bool * hairline)702 bool SkScalerContext::internalGetPath(SkPackedGlyphID glyphID, SkPath* devPath, bool* hairline) {
703     SkPath  path;
704     if (!generatePath(glyphID.glyphID(), &path)) {
705         return false;
706     }
707 
708     if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
709         SkFixed dx = glyphID.getSubXFixed();
710         SkFixed dy = glyphID.getSubYFixed();
711         if (dx | dy) {
712             path.offset(SkFixedToScalar(dx), SkFixedToScalar(dy));
713         }
714     }
715 
716     if (hairline) {
717         *hairline = false;
718     }
719 
720     if (fRec.fFrameWidth >= 0 || fPathEffect != nullptr) {
721         // need the path in user-space, with only the point-size applied
722         // so that our stroking and effects will operate the same way they
723         // would if the user had extracted the path themself, and then
724         // called drawPath
725         SkPath      localPath;
726         SkMatrix    matrix, inverse;
727 
728         fRec.getMatrixFrom2x2(&matrix);
729         if (!matrix.invert(&inverse)) {
730             // assume devPath is already empty.
731             return true;
732         }
733         path.transform(inverse, &localPath);
734         // now localPath is only affected by the paint settings, and not the canvas matrix
735 
736         SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
737 
738         if (fRec.fFrameWidth > 0) {
739             rec.setStrokeStyle(fRec.fFrameWidth,
740                                SkToBool(fRec.fFlags & kFrameAndFill_Flag));
741             // glyphs are always closed contours, so cap type is ignored,
742             // so we just pass something.
743             rec.setStrokeParams((SkPaint::Cap)fRec.fStrokeCap,
744                                 (SkPaint::Join)fRec.fStrokeJoin,
745                                 fRec.fMiterLimit);
746         }
747 
748         if (fPathEffect) {
749             SkPath effectPath;
750             if (fPathEffect->filterPath(&effectPath, localPath, &rec, nullptr, matrix)) {
751                 localPath.swap(effectPath);
752             }
753         }
754 
755         if (rec.needToApply()) {
756             SkPath strokePath;
757             if (rec.applyToPath(&strokePath, localPath)) {
758                 localPath.swap(strokePath);
759             }
760         }
761 
762         // The path effect may have modified 'rec', so wait to here to check hairline status.
763         if (hairline && rec.isHairlineStyle()) {
764             *hairline = true;
765         }
766 
767         // now return stuff to the caller
768         if (devPath) {
769             localPath.transform(matrix, devPath);
770         }
771     } else {   // nothing tricky to do
772         if (devPath) {
773             devPath->swap(path);
774         }
775     }
776 
777     if (devPath) {
778         devPath->updateBoundsCache();
779     }
780     return true;
781 }
782 
783 
getMatrixFrom2x2(SkMatrix * dst) const784 void SkScalerContextRec::getMatrixFrom2x2(SkMatrix* dst) const {
785     dst->setAll(fPost2x2[0][0], fPost2x2[0][1], 0,
786                 fPost2x2[1][0], fPost2x2[1][1], 0,
787                 0,              0,              1);
788 }
789 
getLocalMatrix(SkMatrix * m) const790 void SkScalerContextRec::getLocalMatrix(SkMatrix* m) const {
791     *m = SkFontPriv::MakeTextMatrix(fTextSize, fPreScaleX, fPreSkewX);
792 }
793 
getSingleMatrix(SkMatrix * m) const794 void SkScalerContextRec::getSingleMatrix(SkMatrix* m) const {
795     this->getLocalMatrix(m);
796 
797     //  now concat the device matrix
798     SkMatrix    deviceMatrix;
799     this->getMatrixFrom2x2(&deviceMatrix);
800     m->postConcat(deviceMatrix);
801 }
802 
computeMatrices(PreMatrixScale preMatrixScale,SkVector * s,SkMatrix * sA,SkMatrix * GsA,SkMatrix * G_inv,SkMatrix * A_out)803 bool SkScalerContextRec::computeMatrices(PreMatrixScale preMatrixScale, SkVector* s, SkMatrix* sA,
804                                          SkMatrix* GsA, SkMatrix* G_inv, SkMatrix* A_out)
805 {
806     // A is the 'total' matrix.
807     SkMatrix A;
808     this->getSingleMatrix(&A);
809 
810     // The caller may find the 'total' matrix useful when dealing directly with EM sizes.
811     if (A_out) {
812         *A_out = A;
813     }
814 
815     // GA is the matrix A with rotation removed.
816     SkMatrix GA;
817     bool skewedOrFlipped = A.getSkewX() || A.getSkewY() || A.getScaleX() < 0 || A.getScaleY() < 0;
818     if (skewedOrFlipped) {
819         // QR by Givens rotations. G is Q^T and GA is R. G is rotational (no reflections).
820         // h is where A maps the horizontal baseline.
821         SkPoint h = SkPoint::Make(SK_Scalar1, 0);
822         A.mapPoints(&h, 1);
823 
824         // G is the Givens Matrix for A (rotational matrix where GA[0][1] == 0).
825         SkMatrix G;
826         SkComputeGivensRotation(h, &G);
827 
828         GA = G;
829         GA.preConcat(A);
830 
831         // The 'remainingRotation' is G inverse, which is fairly simple since G is 2x2 rotational.
832         if (G_inv) {
833             G_inv->setAll(
834                 G.get(SkMatrix::kMScaleX), -G.get(SkMatrix::kMSkewX), G.get(SkMatrix::kMTransX),
835                 -G.get(SkMatrix::kMSkewY), G.get(SkMatrix::kMScaleY), G.get(SkMatrix::kMTransY),
836                 G.get(SkMatrix::kMPersp0), G.get(SkMatrix::kMPersp1), G.get(SkMatrix::kMPersp2));
837         }
838     } else {
839         GA = A;
840         if (G_inv) {
841             G_inv->reset();
842         }
843     }
844 
845     // If the 'total' matrix is singular, set the 'scale' to something finite and zero the matrices.
846     // All underlying ports have issues with zero text size, so use the matricies to zero.
847     // If one of the scale factors is less than 1/256 then an EM filling square will
848     // never affect any pixels.
849     // If there are any nonfinite numbers in the matrix, bail out and set the matrices to zero.
850     if (SkScalarAbs(GA.get(SkMatrix::kMScaleX)) <= SK_ScalarNearlyZero ||
851         SkScalarAbs(GA.get(SkMatrix::kMScaleY)) <= SK_ScalarNearlyZero ||
852         !GA.isFinite())
853     {
854         s->fX = SK_Scalar1;
855         s->fY = SK_Scalar1;
856         sA->setScale(0, 0);
857         if (GsA) {
858             GsA->setScale(0, 0);
859         }
860         if (G_inv) {
861             G_inv->reset();
862         }
863         return false;
864     }
865 
866     // At this point, given GA, create s.
867     switch (preMatrixScale) {
868         case kFull_PreMatrixScale:
869             s->fX = SkScalarAbs(GA.get(SkMatrix::kMScaleX));
870             s->fY = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
871             break;
872         case kVertical_PreMatrixScale: {
873             SkScalar yScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
874             s->fX = yScale;
875             s->fY = yScale;
876             break;
877         }
878         case kVerticalInteger_PreMatrixScale: {
879             SkScalar realYScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
880             SkScalar intYScale = SkScalarRoundToScalar(realYScale);
881             if (intYScale == 0) {
882                 intYScale = SK_Scalar1;
883             }
884             s->fX = intYScale;
885             s->fY = intYScale;
886             break;
887         }
888     }
889 
890     // The 'remaining' matrix sA is the total matrix A without the scale.
891     if (!skewedOrFlipped && (
892             (kFull_PreMatrixScale == preMatrixScale) ||
893             (kVertical_PreMatrixScale == preMatrixScale && A.getScaleX() == A.getScaleY())))
894     {
895         // If GA == A and kFull_PreMatrixScale, sA is identity.
896         // If GA == A and kVertical_PreMatrixScale and A.scaleX == A.scaleY, sA is identity.
897         sA->reset();
898     } else if (!skewedOrFlipped && kVertical_PreMatrixScale == preMatrixScale) {
899         // If GA == A and kVertical_PreMatrixScale, sA.scaleY is SK_Scalar1.
900         sA->reset();
901         sA->setScaleX(A.getScaleX() / s->fY);
902     } else {
903         // TODO: like kVertical_PreMatrixScale, kVerticalInteger_PreMatrixScale with int scales.
904         *sA = A;
905         sA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
906     }
907 
908     // The 'remainingWithoutRotation' matrix GsA is the non-rotational part of A without the scale.
909     if (GsA) {
910         *GsA = GA;
911          // G is rotational so reorders with the scale.
912         GsA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
913     }
914 
915     return true;
916 }
917 
computeAxisAlignmentForHText() const918 SkAxisAlignment SkScalerContext::computeAxisAlignmentForHText() const {
919     return fRec.computeAxisAlignmentForHText();
920 }
921 
computeAxisAlignmentForHText() const922 SkAxisAlignment SkScalerContextRec::computeAxisAlignmentForHText() const {
923     // Why fPost2x2 can be used here.
924     // getSingleMatrix multiplies in getLocalMatrix, which consists of
925     // * fTextSize (a scale, which has no effect)
926     // * fPreScaleX (a scale in x, which has no effect)
927     // * fPreSkewX (has no effect, but would on vertical text alignment).
928     // In other words, making the text bigger, stretching it along the
929     // horizontal axis, or fake italicizing it does not move the baseline.
930     if (!SkToBool(fFlags & SkScalerContext::kBaselineSnap_Flag)) {
931         return kNone_SkAxisAlignment;
932     }
933 
934     if (0 == fPost2x2[1][0]) {
935         // The x axis is mapped onto the x axis.
936         return kX_SkAxisAlignment;
937     }
938     if (0 == fPost2x2[0][0]) {
939         // The x axis is mapped onto the y axis.
940         return kY_SkAxisAlignment;
941     }
942     return kNone_SkAxisAlignment;
943 }
944 
setLuminanceColor(SkColor c)945 void SkScalerContextRec::setLuminanceColor(SkColor c) {
946     fLumBits = SkMaskGamma::CanonicalColor(
947             SkColorSetRGB(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c)));
948 }
949 
950 /*
951  *  Return the scalar with only limited fractional precision. Used to consolidate matrices
952  *  that vary only slightly when we create our key into the font cache, since the font scaler
953  *  typically returns the same looking resuts for tiny changes in the matrix.
954  */
sk_relax(SkScalar x)955 static SkScalar sk_relax(SkScalar x) {
956     SkScalar n = SkScalarRoundToScalar(x * 1024);
957     return n / 1024.0f;
958 }
959 
compute_mask_format(const SkFont & font)960 static SkMask::Format compute_mask_format(const SkFont& font) {
961     switch (font.getEdging()) {
962         case SkFont::Edging::kAlias:
963             return SkMask::kBW_Format;
964         case SkFont::Edging::kAntiAlias:
965             return SkMask::kA8_Format;
966         case SkFont::Edging::kSubpixelAntiAlias:
967             return SkMask::kLCD16_Format;
968     }
969     SkASSERT(false);
970     return SkMask::kA8_Format;
971 }
972 
973 // Beyond this size, LCD doesn't appreciably improve quality, but it always
974 // cost more RAM and draws slower, so we set a cap.
975 #ifndef SK_MAX_SIZE_FOR_LCDTEXT
976     #define SK_MAX_SIZE_FOR_LCDTEXT    48
977 #endif
978 
979 const SkScalar gMaxSize2ForLCDText = SK_MAX_SIZE_FOR_LCDTEXT * SK_MAX_SIZE_FOR_LCDTEXT;
980 
too_big_for_lcd(const SkScalerContextRec & rec,bool checkPost2x2)981 static bool too_big_for_lcd(const SkScalerContextRec& rec, bool checkPost2x2) {
982     if (checkPost2x2) {
983         SkScalar area = rec.fPost2x2[0][0] * rec.fPost2x2[1][1] -
984                         rec.fPost2x2[1][0] * rec.fPost2x2[0][1];
985         area *= rec.fTextSize * rec.fTextSize;
986         return area > gMaxSize2ForLCDText;
987     } else {
988         return rec.fTextSize > SK_MAX_SIZE_FOR_LCDTEXT;
989     }
990 }
991 
992 // The only reason this is not file static is because it needs the context of SkScalerContext to
993 // access SkPaint::computeLuminanceColor.
MakeRecAndEffects(const SkFont & font,const SkPaint & paint,const SkSurfaceProps & surfaceProps,SkScalerContextFlags scalerContextFlags,const SkMatrix & deviceMatrix,SkScalerContextRec * rec,SkScalerContextEffects * effects)994 void SkScalerContext::MakeRecAndEffects(const SkFont& font, const SkPaint& paint,
995                                         const SkSurfaceProps& surfaceProps,
996                                         SkScalerContextFlags scalerContextFlags,
997                                         const SkMatrix& deviceMatrix,
998                                         SkScalerContextRec* rec,
999                                         SkScalerContextEffects* effects) {
1000     SkASSERT(!deviceMatrix.hasPerspective());
1001 
1002     sk_bzero(rec, sizeof(SkScalerContextRec));
1003 
1004     SkTypeface* typeface = font.getTypefaceOrDefault();
1005 
1006     rec->fFontID = typeface->uniqueID();
1007     rec->fTextSize = font.getSize();
1008     rec->fPreScaleX = font.getScaleX();
1009     rec->fPreSkewX  = font.getSkewX();
1010 
1011     bool checkPost2x2 = false;
1012 
1013     const SkMatrix::TypeMask mask = deviceMatrix.getType();
1014     if (mask & SkMatrix::kScale_Mask) {
1015         rec->fPost2x2[0][0] = sk_relax(deviceMatrix.getScaleX());
1016         rec->fPost2x2[1][1] = sk_relax(deviceMatrix.getScaleY());
1017         checkPost2x2 = true;
1018     } else {
1019         rec->fPost2x2[0][0] = rec->fPost2x2[1][1] = SK_Scalar1;
1020     }
1021     if (mask & SkMatrix::kAffine_Mask) {
1022         rec->fPost2x2[0][1] = sk_relax(deviceMatrix.getSkewX());
1023         rec->fPost2x2[1][0] = sk_relax(deviceMatrix.getSkewY());
1024         checkPost2x2 = true;
1025     } else {
1026         rec->fPost2x2[0][1] = rec->fPost2x2[1][0] = 0;
1027     }
1028 
1029     SkPaint::Style  style = paint.getStyle();
1030     SkScalar        strokeWidth = paint.getStrokeWidth();
1031 
1032     unsigned flags = 0;
1033 
1034     if (font.isEmbolden()) {
1035 #ifdef SK_USE_FREETYPE_EMBOLDEN
1036         flags |= SkScalerContext::kEmbolden_Flag;
1037 #else
1038         SkScalar fakeBoldScale = SkScalarInterpFunc(font.getSize(),
1039                                                     kStdFakeBoldInterpKeys,
1040                                                     kStdFakeBoldInterpValues,
1041                                                     kStdFakeBoldInterpLength);
1042         SkScalar extra = font.getSize() * fakeBoldScale;
1043 
1044         if (style == SkPaint::kFill_Style) {
1045             style = SkPaint::kStrokeAndFill_Style;
1046             strokeWidth = extra;    // ignore paint's strokeWidth if it was "fill"
1047         } else {
1048             strokeWidth += extra;
1049         }
1050 #endif
1051     }
1052 
1053     if (style != SkPaint::kFill_Style && strokeWidth >= 0) {
1054         rec->fFrameWidth = strokeWidth;
1055         rec->fMiterLimit = paint.getStrokeMiter();
1056         rec->fStrokeJoin = SkToU8(paint.getStrokeJoin());
1057         rec->fStrokeCap = SkToU8(paint.getStrokeCap());
1058 
1059         if (style == SkPaint::kStrokeAndFill_Style) {
1060             flags |= SkScalerContext::kFrameAndFill_Flag;
1061         }
1062     } else {
1063         rec->fFrameWidth = -1;
1064         rec->fMiterLimit = 0;
1065         rec->fStrokeJoin = 0;
1066         rec->fStrokeCap = 0;
1067     }
1068 
1069     rec->fMaskFormat = compute_mask_format(font);
1070 
1071     if (SkMask::kLCD16_Format == rec->fMaskFormat) {
1072         if (too_big_for_lcd(*rec, checkPost2x2)) {
1073             rec->fMaskFormat = SkMask::kA8_Format;
1074             flags |= SkScalerContext::kGenA8FromLCD_Flag;
1075         } else {
1076             SkPixelGeometry geometry = surfaceProps.pixelGeometry();
1077 
1078             switch (geometry) {
1079                 case kUnknown_SkPixelGeometry:
1080                     // eeek, can't support LCD
1081                     rec->fMaskFormat = SkMask::kA8_Format;
1082                     flags |= SkScalerContext::kGenA8FromLCD_Flag;
1083                     break;
1084                 case kRGB_H_SkPixelGeometry:
1085                     // our default, do nothing.
1086                     break;
1087                 case kBGR_H_SkPixelGeometry:
1088                     flags |= SkScalerContext::kLCD_BGROrder_Flag;
1089                     break;
1090                 case kRGB_V_SkPixelGeometry:
1091                     flags |= SkScalerContext::kLCD_Vertical_Flag;
1092                     break;
1093                 case kBGR_V_SkPixelGeometry:
1094                     flags |= SkScalerContext::kLCD_Vertical_Flag;
1095                     flags |= SkScalerContext::kLCD_BGROrder_Flag;
1096                     break;
1097             }
1098         }
1099     }
1100 
1101     if (font.isEmbeddedBitmaps()) {
1102         flags |= SkScalerContext::kEmbeddedBitmapText_Flag;
1103     }
1104     if (font.isSubpixel()) {
1105         flags |= SkScalerContext::kSubpixelPositioning_Flag;
1106     }
1107     if (font.isForceAutoHinting()) {
1108         flags |= SkScalerContext::kForceAutohinting_Flag;
1109     }
1110     if (font.isLinearMetrics()) {
1111         flags |= SkScalerContext::kLinearMetrics_Flag;
1112     }
1113     if (font.isBaselineSnap()) {
1114         flags |= SkScalerContext::kBaselineSnap_Flag;
1115     }
1116     if (typeface->glyphMaskNeedsCurrentColor()) {
1117         flags |= SkScalerContext::kNeedsForegroundColor_Flag;
1118         rec->fForegroundColor = paint.getColor();
1119     }
1120     rec->fFlags = SkToU16(flags);
1121 
1122     // these modify fFlags, so do them after assigning fFlags
1123     rec->setHinting(font.getHinting());
1124     rec->setLuminanceColor(SkPaintPriv::ComputeLuminanceColor(paint));
1125 
1126     // For now always set the paint gamma equal to the device gamma.
1127     // The math in SkMaskGamma can handle them being different,
1128     // but it requires superluminous masks when
1129     // Ex : deviceGamma(x) < paintGamma(x) and x is sufficiently large.
1130     rec->setDeviceGamma(SK_GAMMA_EXPONENT);
1131     rec->setPaintGamma(SK_GAMMA_EXPONENT);
1132 
1133 #ifdef SK_GAMMA_CONTRAST
1134     rec->setContrast(SK_GAMMA_CONTRAST);
1135 #else
1136     // A value of 0.5 for SK_GAMMA_CONTRAST appears to be a good compromise.
1137     // With lower values small text appears washed out (though correctly so).
1138     // With higher values lcd fringing is worse and the smoothing effect of
1139     // partial coverage is diminished.
1140     rec->setContrast(0.5f);
1141 #endif
1142 
1143     if (!SkToBool(scalerContextFlags & SkScalerContextFlags::kFakeGamma)) {
1144         rec->ignoreGamma();
1145     }
1146     if (!SkToBool(scalerContextFlags & SkScalerContextFlags::kBoostContrast)) {
1147         rec->setContrast(0);
1148     }
1149 
1150     new (effects) SkScalerContextEffects{paint};
1151 }
1152 
CreateDescriptorAndEffectsUsingPaint(const SkFont & font,const SkPaint & paint,const SkSurfaceProps & surfaceProps,SkScalerContextFlags scalerContextFlags,const SkMatrix & deviceMatrix,SkAutoDescriptor * ad,SkScalerContextEffects * effects)1153 SkDescriptor* SkScalerContext::CreateDescriptorAndEffectsUsingPaint(
1154     const SkFont& font, const SkPaint& paint, const SkSurfaceProps& surfaceProps,
1155     SkScalerContextFlags scalerContextFlags, const SkMatrix& deviceMatrix, SkAutoDescriptor* ad,
1156     SkScalerContextEffects* effects)
1157 {
1158     SkScalerContextRec rec;
1159     MakeRecAndEffects(font, paint, surfaceProps, scalerContextFlags, deviceMatrix, &rec, effects);
1160     return AutoDescriptorGivenRecAndEffects(rec, *effects, ad);
1161 }
1162 
calculate_size_and_flatten(const SkScalerContextRec & rec,const SkScalerContextEffects & effects,SkBinaryWriteBuffer * effectBuffer)1163 static size_t calculate_size_and_flatten(const SkScalerContextRec& rec,
1164                                          const SkScalerContextEffects& effects,
1165                                          SkBinaryWriteBuffer* effectBuffer) {
1166     size_t descSize = sizeof(rec);
1167     int entryCount = 1;
1168 
1169     if (effects.fPathEffect || effects.fMaskFilter) {
1170         if (effects.fPathEffect) { effectBuffer->writeFlattenable(effects.fPathEffect); }
1171         if (effects.fMaskFilter) { effectBuffer->writeFlattenable(effects.fMaskFilter); }
1172         entryCount += 1;
1173         descSize += effectBuffer->bytesWritten();
1174     }
1175 
1176     descSize += SkDescriptor::ComputeOverhead(entryCount);
1177     return descSize;
1178 }
1179 
generate_descriptor(const SkScalerContextRec & rec,const SkBinaryWriteBuffer & effectBuffer,SkDescriptor * desc)1180 static void generate_descriptor(const SkScalerContextRec& rec,
1181                                 const SkBinaryWriteBuffer& effectBuffer,
1182                                 SkDescriptor* desc) {
1183     desc->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec);
1184 
1185     if (effectBuffer.bytesWritten() > 0) {
1186         effectBuffer.writeToMemory(desc->addEntry(kEffects_SkDescriptorTag,
1187                                                   effectBuffer.bytesWritten(),
1188                                                   nullptr));
1189     }
1190 
1191     desc->computeChecksum();
1192 }
1193 
AutoDescriptorGivenRecAndEffects(const SkScalerContextRec & rec,const SkScalerContextEffects & effects,SkAutoDescriptor * ad)1194 SkDescriptor* SkScalerContext::AutoDescriptorGivenRecAndEffects(
1195     const SkScalerContextRec& rec,
1196     const SkScalerContextEffects& effects,
1197     SkAutoDescriptor* ad)
1198 {
1199     SkBinaryWriteBuffer buf;
1200 
1201     ad->reset(calculate_size_and_flatten(rec, effects, &buf));
1202     generate_descriptor(rec, buf, ad->getDesc());
1203 
1204     return ad->getDesc();
1205 }
1206 
DescriptorGivenRecAndEffects(const SkScalerContextRec & rec,const SkScalerContextEffects & effects)1207 std::unique_ptr<SkDescriptor> SkScalerContext::DescriptorGivenRecAndEffects(
1208     const SkScalerContextRec& rec,
1209     const SkScalerContextEffects& effects)
1210 {
1211     SkBinaryWriteBuffer buf;
1212 
1213     auto desc = SkDescriptor::Alloc(calculate_size_and_flatten(rec, effects, &buf));
1214     generate_descriptor(rec, buf, desc.get());
1215 
1216     return desc;
1217 }
1218 
DescriptorBufferGiveRec(const SkScalerContextRec & rec,void * buffer)1219 void SkScalerContext::DescriptorBufferGiveRec(const SkScalerContextRec& rec, void* buffer) {
1220     generate_descriptor(rec, SkBinaryWriteBuffer{}, (SkDescriptor*)buffer);
1221 }
1222 
CheckBufferSizeForRec(const SkScalerContextRec & rec,const SkScalerContextEffects & effects,size_t size)1223 bool SkScalerContext::CheckBufferSizeForRec(const SkScalerContextRec& rec,
1224                                             const SkScalerContextEffects& effects,
1225                                             size_t size) {
1226     SkBinaryWriteBuffer buf;
1227     return size >= calculate_size_and_flatten(rec, effects, &buf);
1228 }
1229 
MakeEmpty(sk_sp<SkTypeface> typeface,const SkScalerContextEffects & effects,const SkDescriptor * desc)1230 std::unique_ptr<SkScalerContext> SkScalerContext::MakeEmpty(
1231         sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
1232         const SkDescriptor* desc) {
1233     class SkScalerContext_Empty : public SkScalerContext {
1234     public:
1235         SkScalerContext_Empty(sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
1236                               const SkDescriptor* desc)
1237                 : SkScalerContext(std::move(typeface), effects, desc) {}
1238 
1239     protected:
1240         bool generateAdvance(SkGlyph* glyph) override {
1241             glyph->zeroMetrics();
1242             return true;
1243         }
1244         void generateMetrics(SkGlyph* glyph) override {
1245             glyph->fMaskFormat = fRec.fMaskFormat;
1246             glyph->zeroMetrics();
1247         }
1248         void generateImage(const SkGlyph& glyph) override {}
1249         bool generatePath(SkGlyphID glyph, SkPath* path) override {
1250             path->reset();
1251             return false;
1252         }
1253         void generateFontMetrics(SkFontMetrics* metrics) override {
1254             if (metrics) {
1255                 sk_bzero(metrics, sizeof(*metrics));
1256             }
1257         }
1258     };
1259 
1260     return std::make_unique<SkScalerContext_Empty>(std::move(typeface), effects, desc);
1261 }
1262 
1263 
1264 
1265 
1266