• 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 "SkScalerContext.h"
9 
10 #include "SkAutoMalloc.h"
11 #include "SkAutoPixmapStorage.h"
12 #include "SkColorPriv.h"
13 #include "SkDescriptor.h"
14 #include "SkDraw.h"
15 #include "SkGlyph.h"
16 #include "SkMakeUnique.h"
17 #include "SkMaskFilter.h"
18 #include "SkMaskGamma.h"
19 #include "SkMatrix22.h"
20 #include "SkPaintPriv.h"
21 #include "SkPathEffect.h"
22 #include "SkRasterClip.h"
23 #include "SkRasterizer.h"
24 #include "SkReadBuffer.h"
25 #include "SkStroke.h"
26 #include "SkStrokeRec.h"
27 #include "SkWriteBuffer.h"
28 
29 #define ComputeBWRowBytes(width)        (((unsigned)(width) + 7) >> 3)
30 
toMask(SkMask * mask) const31 void SkGlyph::toMask(SkMask* mask) const {
32     SkASSERT(mask);
33 
34     mask->fImage = (uint8_t*)fImage;
35     mask->fBounds.set(fLeft, fTop, fLeft + fWidth, fTop + fHeight);
36     mask->fRowBytes = this->rowBytes();
37     mask->fFormat = static_cast<SkMask::Format>(fMaskFormat);
38 }
39 
computeImageSize() const40 size_t SkGlyph::computeImageSize() const {
41     const size_t size = this->rowBytes() * fHeight;
42 
43     switch (fMaskFormat) {
44         case SkMask::k3D_Format:
45             return 3 * size;
46         default:
47             return size;
48     }
49 }
50 
zeroMetrics()51 void SkGlyph::zeroMetrics() {
52     fAdvanceX = 0;
53     fAdvanceY = 0;
54     fWidth    = 0;
55     fHeight   = 0;
56     fTop      = 0;
57     fLeft     = 0;
58     fRsbDelta = 0;
59     fLsbDelta = 0;
60 }
61 
62 ///////////////////////////////////////////////////////////////////////////////
63 
64 #ifdef SK_DEBUG
65     #define DUMP_RECx
66 #endif
67 
SkScalerContext(sk_sp<SkTypeface> typeface,const SkScalerContextEffects & effects,const SkDescriptor * desc)68 SkScalerContext::SkScalerContext(sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
69                                  const SkDescriptor* desc)
70     : fRec(*static_cast<const Rec*>(desc->findEntry(kRec_SkDescriptorTag, nullptr)))
71 
72     , fTypeface(std::move(typeface))
73     , fPathEffect(sk_ref_sp(effects.fPathEffect))
74     , fMaskFilter(sk_ref_sp(effects.fMaskFilter))
75     , fRasterizer(sk_ref_sp(effects.fRasterizer))
76       // Initialize based on our settings. Subclasses can also force this.
77     , fGenerateImageFromPath(fRec.fFrameWidth > 0 || fPathEffect != nullptr || fRasterizer != nullptr)
78 
79     , fPreBlend(fMaskFilter ? SkMaskGamma::PreBlend() : SkScalerContext::GetMaskPreBlend(fRec))
80     , fPreBlendForFilter(fMaskFilter ? SkScalerContext::GetMaskPreBlend(fRec)
81                                      : SkMaskGamma::PreBlend())
82 {
83 #ifdef DUMP_REC
84     desc->assertChecksum();
85     SkDebugf("SkScalerContext checksum %x count %d length %d\n",
86              desc->getChecksum(), desc->getCount(), desc->getLength());
87     SkDebugf(" textsize %g prescale %g preskew %g post [%g %g %g %g]\n",
88         rec->fTextSize, rec->fPreScaleX, rec->fPreSkewX, rec->fPost2x2[0][0],
89         rec->fPost2x2[0][1], rec->fPost2x2[1][0], rec->fPost2x2[1][1]);
90     SkDebugf("  frame %g miter %g hints %d framefill %d format %d join %d cap %d\n",
91         rec->fFrameWidth, rec->fMiterLimit, rec->fHints, rec->fFrameAndFill,
92         rec->fMaskFormat, rec->fStrokeJoin, rec->fStrokeCap);
93     SkDebugf("  pathEffect %x maskFilter %x\n",
94              desc->findEntry(kPathEffect_SkDescriptorTag, nullptr),
95         desc->findEntry(kMaskFilter_SkDescriptorTag, nullptr));
96 #endif
97 }
98 
~SkScalerContext()99 SkScalerContext::~SkScalerContext() {}
100 
getAdvance(SkGlyph * glyph)101 void SkScalerContext::getAdvance(SkGlyph* glyph) {
102     // mark us as just having a valid advance
103     glyph->fMaskFormat = MASK_FORMAT_JUST_ADVANCE;
104     // we mark the format before making the call, in case the impl
105     // internally ends up calling its generateMetrics, which is OK
106     // albeit slower than strictly necessary
107     generateAdvance(glyph);
108 }
109 
getMetrics(SkGlyph * glyph)110 void SkScalerContext::getMetrics(SkGlyph* glyph) {
111     generateMetrics(glyph);
112 
113     // for now we have separate cache entries for devkerning on and off
114     // in the future we might share caches, but make our measure/draw
115     // code make the distinction. Thus we zap the values if the caller
116     // has not asked for them.
117     if ((fRec.fFlags & SkScalerContext::kDevKernText_Flag) == 0) {
118         // no devkern, so zap the fields
119         glyph->fLsbDelta = glyph->fRsbDelta = 0;
120     }
121 
122     // if either dimension is empty, zap the image bounds of the glyph
123     if (0 == glyph->fWidth || 0 == glyph->fHeight) {
124         glyph->fWidth   = 0;
125         glyph->fHeight  = 0;
126         glyph->fTop     = 0;
127         glyph->fLeft    = 0;
128         glyph->fMaskFormat = 0;
129         return;
130     }
131 
132     if (fGenerateImageFromPath) {
133         SkPath      devPath, fillPath;
134         SkMatrix    fillToDevMatrix;
135 
136         this->internalGetPath(glyph->getPackedID(), &fillPath, &devPath, &fillToDevMatrix);
137 
138         if (fRasterizer) {
139             SkMask  mask;
140 
141             if (fRasterizer->rasterize(fillPath, fillToDevMatrix, nullptr,
142                                        fMaskFilter.get(), &mask,
143                                        SkMask::kJustComputeBounds_CreateMode)) {
144                 glyph->fLeft    = mask.fBounds.fLeft;
145                 glyph->fTop     = mask.fBounds.fTop;
146                 glyph->fWidth   = SkToU16(mask.fBounds.width());
147                 glyph->fHeight  = SkToU16(mask.fBounds.height());
148             } else {
149                 goto SK_ERROR;
150             }
151         } else {
152             // just use devPath
153             const SkIRect ir = devPath.getBounds().roundOut();
154 
155             if (ir.isEmpty() || !ir.is16Bit()) {
156                 goto SK_ERROR;
157             }
158             glyph->fLeft    = ir.fLeft;
159             glyph->fTop     = ir.fTop;
160             glyph->fWidth   = SkToU16(ir.width());
161             glyph->fHeight  = SkToU16(ir.height());
162 
163             if (glyph->fWidth > 0) {
164                 switch (fRec.fMaskFormat) {
165                 case SkMask::kLCD16_Format:
166                     glyph->fWidth += 2;
167                     glyph->fLeft -= 1;
168                     break;
169                 default:
170                     break;
171                 }
172             }
173         }
174     }
175 
176     if (SkMask::kARGB32_Format != glyph->fMaskFormat) {
177         glyph->fMaskFormat = fRec.fMaskFormat;
178     }
179 
180     // If we are going to create the mask, then we cannot keep the color
181     if ((fGenerateImageFromPath || fMaskFilter) &&
182             SkMask::kARGB32_Format == glyph->fMaskFormat) {
183         glyph->fMaskFormat = SkMask::kA8_Format;
184     }
185 
186     if (fMaskFilter) {
187         SkMask      src, dst;
188         SkMatrix    matrix;
189 
190         glyph->toMask(&src);
191         fRec.getMatrixFrom2x2(&matrix);
192 
193         src.fImage = nullptr;  // only want the bounds from the filter
194         if (fMaskFilter->filterMask(&dst, src, matrix, nullptr)) {
195             if (dst.fBounds.isEmpty() || !dst.fBounds.is16Bit()) {
196                 goto SK_ERROR;
197             }
198             SkASSERT(dst.fImage == nullptr);
199             glyph->fLeft    = dst.fBounds.fLeft;
200             glyph->fTop     = dst.fBounds.fTop;
201             glyph->fWidth   = SkToU16(dst.fBounds.width());
202             glyph->fHeight  = SkToU16(dst.fBounds.height());
203             glyph->fMaskFormat = dst.fFormat;
204         }
205     }
206     return;
207 
208 SK_ERROR:
209     // draw nothing 'cause we failed
210     glyph->fLeft    = 0;
211     glyph->fTop     = 0;
212     glyph->fWidth   = 0;
213     glyph->fHeight  = 0;
214     // put a valid value here, in case it was earlier set to
215     // MASK_FORMAT_JUST_ADVANCE
216     glyph->fMaskFormat = fRec.fMaskFormat;
217 }
218 
219 #define SK_SHOW_TEXT_BLIT_COVERAGE 0
220 
applyLUTToA8Mask(const SkMask & mask,const uint8_t * lut)221 static void applyLUTToA8Mask(const SkMask& mask, const uint8_t* lut) {
222     uint8_t* SK_RESTRICT dst = (uint8_t*)mask.fImage;
223     unsigned rowBytes = mask.fRowBytes;
224 
225     for (int y = mask.fBounds.height() - 1; y >= 0; --y) {
226         for (int x = mask.fBounds.width() - 1; x >= 0; --x) {
227             dst[x] = lut[dst[x]];
228         }
229         dst += rowBytes;
230     }
231 }
232 
233 template<bool APPLY_PREBLEND>
pack4xHToLCD16(const SkPixmap & src,const SkMask & dst,const SkMaskGamma::PreBlend & maskPreBlend)234 static void pack4xHToLCD16(const SkPixmap& src, const SkMask& dst,
235                            const SkMaskGamma::PreBlend& maskPreBlend) {
236 #define SAMPLES_PER_PIXEL 4
237 #define LCD_PER_PIXEL 3
238     SkASSERT(kAlpha_8_SkColorType == src.colorType());
239     SkASSERT(SkMask::kLCD16_Format == dst.fFormat);
240 
241     const int sample_width = src.width();
242     const int height = src.height();
243 
244     uint16_t* dstP = (uint16_t*)dst.fImage;
245     size_t dstRB = dst.fRowBytes;
246     // An N tap FIR is defined by
247     // out[n] = coeff[0]*x[n] + coeff[1]*x[n-1] + ... + coeff[N]*x[n-N]
248     // or
249     // out[n] = sum(i, 0, N, coeff[i]*x[n-i])
250 
251     // The strategy is to use one FIR (different coefficients) for each of r, g, and b.
252     // This means using every 4th FIR output value of each FIR and discarding the rest.
253     // The FIRs are aligned, and the coefficients reach 5 samples to each side of their 'center'.
254     // (For r and b this is technically incorrect, but the coeffs outside round to zero anyway.)
255 
256     // These are in some fixed point repesentation.
257     // Adding up to more than one simulates ink spread.
258     // For implementation reasons, these should never add up to more than two.
259 
260     // Coefficients determined by a gausian where 5 samples = 3 std deviations (0x110 'contrast').
261     // Calculated using tools/generate_fir_coeff.py
262     // With this one almost no fringing is ever seen, but it is imperceptibly blurry.
263     // The lcd smoothed text is almost imperceptibly different from gray,
264     // but is still sharper on small stems and small rounded corners than gray.
265     // This also seems to be about as wide as one can get and only have a three pixel kernel.
266     // TODO: caculate these at runtime so parameters can be adjusted (esp contrast).
267     static const unsigned int coefficients[LCD_PER_PIXEL][SAMPLES_PER_PIXEL*3] = {
268         //The red subpixel is centered inside the first sample (at 1/6 pixel), and is shifted.
269         { 0x03, 0x0b, 0x1c, 0x33,  0x40, 0x39, 0x24, 0x10,  0x05, 0x01, 0x00, 0x00, },
270         //The green subpixel is centered between two samples (at 1/2 pixel), so is symetric
271         { 0x00, 0x02, 0x08, 0x16,  0x2b, 0x3d, 0x3d, 0x2b,  0x16, 0x08, 0x02, 0x00, },
272         //The blue subpixel is centered inside the last sample (at 5/6 pixel), and is shifted.
273         { 0x00, 0x00, 0x01, 0x05,  0x10, 0x24, 0x39, 0x40,  0x33, 0x1c, 0x0b, 0x03, },
274     };
275 
276     for (int y = 0; y < height; ++y) {
277         const uint8_t* srcP = src.addr8(0, y);
278 
279         // TODO: this fir filter implementation is straight forward, but slow.
280         // It should be possible to make it much faster.
281         for (int sample_x = -4, pixel_x = 0; sample_x < sample_width + 4; sample_x += 4, ++pixel_x) {
282             int fir[LCD_PER_PIXEL] = { 0 };
283             for (int sample_index = SkMax32(0, sample_x - 4), coeff_index = sample_index - (sample_x - 4)
284                 ; sample_index < SkMin32(sample_x + 8, sample_width)
285                 ; ++sample_index, ++coeff_index)
286             {
287                 int sample_value = srcP[sample_index];
288                 for (int subpxl_index = 0; subpxl_index < LCD_PER_PIXEL; ++subpxl_index) {
289                     fir[subpxl_index] += coefficients[subpxl_index][coeff_index] * sample_value;
290                 }
291             }
292             for (int subpxl_index = 0; subpxl_index < LCD_PER_PIXEL; ++subpxl_index) {
293                 fir[subpxl_index] /= 0x100;
294                 fir[subpxl_index] = SkMin32(fir[subpxl_index], 255);
295             }
296 
297             U8CPU r = sk_apply_lut_if<APPLY_PREBLEND>(fir[0], maskPreBlend.fR);
298             U8CPU g = sk_apply_lut_if<APPLY_PREBLEND>(fir[1], maskPreBlend.fG);
299             U8CPU b = sk_apply_lut_if<APPLY_PREBLEND>(fir[2], maskPreBlend.fB);
300 #if SK_SHOW_TEXT_BLIT_COVERAGE
301             r = SkMax32(r, 10); g = SkMax32(g, 10); b = SkMax32(b, 10);
302 #endif
303             dstP[pixel_x] = SkPack888ToRGB16(r, g, b);
304         }
305         dstP = (uint16_t*)((char*)dstP + dstRB);
306     }
307 }
308 
convert_8_to_1(unsigned byte)309 static inline int convert_8_to_1(unsigned byte) {
310     SkASSERT(byte <= 0xFF);
311     return byte >> 7;
312 }
313 
pack_8_to_1(const uint8_t alpha[8])314 static uint8_t pack_8_to_1(const uint8_t alpha[8]) {
315     unsigned bits = 0;
316     for (int i = 0; i < 8; ++i) {
317         bits <<= 1;
318         bits |= convert_8_to_1(alpha[i]);
319     }
320     return SkToU8(bits);
321 }
322 
packA8ToA1(const SkMask & mask,const uint8_t * src,size_t srcRB)323 static void packA8ToA1(const SkMask& mask, const uint8_t* src, size_t srcRB) {
324     const int height = mask.fBounds.height();
325     const int width = mask.fBounds.width();
326     const int octs = width >> 3;
327     const int leftOverBits = width & 7;
328 
329     uint8_t* dst = mask.fImage;
330     const int dstPad = mask.fRowBytes - SkAlign8(width)/8;
331     SkASSERT(dstPad >= 0);
332 
333     SkASSERT(width >= 0);
334     SkASSERT(srcRB >= (size_t)width);
335     const size_t srcPad = srcRB - width;
336 
337     for (int y = 0; y < height; ++y) {
338         for (int i = 0; i < octs; ++i) {
339             *dst++ = pack_8_to_1(src);
340             src += 8;
341         }
342         if (leftOverBits > 0) {
343             unsigned bits = 0;
344             int shift = 7;
345             for (int i = 0; i < leftOverBits; ++i, --shift) {
346                 bits |= convert_8_to_1(*src++) << shift;
347             }
348             *dst++ = bits;
349         }
350         src += srcPad;
351         dst += dstPad;
352     }
353 }
354 
generateMask(const SkMask & mask,const SkPath & path,const SkMaskGamma::PreBlend & maskPreBlend)355 static void generateMask(const SkMask& mask, const SkPath& path,
356                          const SkMaskGamma::PreBlend& maskPreBlend) {
357     SkPaint paint;
358 
359     int srcW = mask.fBounds.width();
360     int srcH = mask.fBounds.height();
361     int dstW = srcW;
362     int dstH = srcH;
363     int dstRB = mask.fRowBytes;
364 
365     SkMatrix matrix;
366     matrix.setTranslate(-SkIntToScalar(mask.fBounds.fLeft),
367                         -SkIntToScalar(mask.fBounds.fTop));
368 
369     paint.setAntiAlias(SkMask::kBW_Format != mask.fFormat);
370     switch (mask.fFormat) {
371         case SkMask::kBW_Format:
372             dstRB = 0;  // signals we need a copy
373             break;
374         case SkMask::kA8_Format:
375             break;
376         case SkMask::kLCD16_Format:
377             // TODO: trigger off LCD orientation
378             dstW = 4*dstW - 8;
379             matrix.setTranslate(-SkIntToScalar(mask.fBounds.fLeft + 1),
380                                 -SkIntToScalar(mask.fBounds.fTop));
381             matrix.postScale(SkIntToScalar(4), SK_Scalar1);
382             dstRB = 0;  // signals we need a copy
383             break;
384         default:
385             SkDEBUGFAIL("unexpected mask format");
386     }
387 
388     SkRasterClip clip;
389     clip.setRect(SkIRect::MakeWH(dstW, dstH));
390 
391     const SkImageInfo info = SkImageInfo::MakeA8(dstW, dstH);
392     SkAutoPixmapStorage dst;
393 
394     if (0 == dstRB) {
395         if (!dst.tryAlloc(info)) {
396             // can't allocate offscreen, so empty the mask and return
397             sk_bzero(mask.fImage, mask.computeImageSize());
398             return;
399         }
400     } else {
401         dst.reset(info, mask.fImage, dstRB);
402     }
403     sk_bzero(dst.writable_addr(), dst.getSafeSize());
404 
405     SkDraw  draw;
406     draw.fDst   = dst;
407     draw.fRC    = &clip;
408     draw.fMatrix = &matrix;
409     draw.drawPath(path, paint);
410 
411     switch (mask.fFormat) {
412         case SkMask::kBW_Format:
413             packA8ToA1(mask, dst.addr8(0, 0), dst.rowBytes());
414             break;
415         case SkMask::kA8_Format:
416             if (maskPreBlend.isApplicable()) {
417                 applyLUTToA8Mask(mask, maskPreBlend.fG);
418             }
419             break;
420         case SkMask::kLCD16_Format:
421             if (maskPreBlend.isApplicable()) {
422                 pack4xHToLCD16<true>(dst, mask, maskPreBlend);
423             } else {
424                 pack4xHToLCD16<false>(dst, mask, maskPreBlend);
425             }
426             break;
427         default:
428             break;
429     }
430 }
431 
extract_alpha(const SkMask & dst,const SkPMColor * srcRow,size_t srcRB)432 static void extract_alpha(const SkMask& dst,
433                           const SkPMColor* srcRow, size_t srcRB) {
434     int width = dst.fBounds.width();
435     int height = dst.fBounds.height();
436     int dstRB = dst.fRowBytes;
437     uint8_t* dstRow = dst.fImage;
438 
439     for (int y = 0; y < height; ++y) {
440         for (int x = 0; x < width; ++x) {
441             dstRow[x] = SkGetPackedA32(srcRow[x]);
442         }
443         // zero any padding on each row
444         for (int x = width; x < dstRB; ++x) {
445             dstRow[x] = 0;
446         }
447         dstRow += dstRB;
448         srcRow = (const SkPMColor*)((const char*)srcRow + srcRB);
449     }
450 }
451 
getImage(const SkGlyph & origGlyph)452 void SkScalerContext::getImage(const SkGlyph& origGlyph) {
453     const SkGlyph*  glyph = &origGlyph;
454     SkGlyph         tmpGlyph;
455 
456     // in case we need to call generateImage on a mask-format that is different
457     // (i.e. larger) than what our caller allocated by looking at origGlyph.
458     SkAutoMalloc tmpGlyphImageStorage;
459 
460     // If we are going to draw-from-path, then we cannot generate color, since
461     // the path only makes a mask. This case should have been caught up in
462     // generateMetrics().
463     SkASSERT(!fGenerateImageFromPath ||
464              SkMask::kARGB32_Format != origGlyph.fMaskFormat);
465 
466     if (fMaskFilter) {   // restore the prefilter bounds
467         tmpGlyph.initWithGlyphID(origGlyph.getPackedID());
468 
469         // need the original bounds, sans our maskfilter
470         SkMaskFilter* mf = fMaskFilter.release();   // temp disable
471         this->getMetrics(&tmpGlyph);
472         fMaskFilter = sk_sp<SkMaskFilter>(mf);      // restore
473 
474         // we need the prefilter bounds to be <= filter bounds
475         SkASSERT(tmpGlyph.fWidth <= origGlyph.fWidth);
476         SkASSERT(tmpGlyph.fHeight <= origGlyph.fHeight);
477 
478         if (tmpGlyph.fMaskFormat == origGlyph.fMaskFormat) {
479             tmpGlyph.fImage = origGlyph.fImage;
480         } else {
481             tmpGlyphImageStorage.reset(tmpGlyph.computeImageSize());
482             tmpGlyph.fImage = tmpGlyphImageStorage.get();
483         }
484         glyph = &tmpGlyph;
485     }
486 
487     if (fGenerateImageFromPath) {
488         SkPath      devPath, fillPath;
489         SkMatrix    fillToDevMatrix;
490         SkMask      mask;
491 
492         this->internalGetPath(glyph->getPackedID(), &fillPath, &devPath, &fillToDevMatrix);
493         glyph->toMask(&mask);
494 
495         if (fRasterizer) {
496             mask.fFormat = SkMask::kA8_Format;
497             sk_bzero(glyph->fImage, mask.computeImageSize());
498 
499             if (!fRasterizer->rasterize(fillPath, fillToDevMatrix, nullptr,
500                                         fMaskFilter.get(), &mask,
501                                         SkMask::kJustRenderImage_CreateMode)) {
502                 return;
503             }
504             if (fPreBlend.isApplicable()) {
505                 applyLUTToA8Mask(mask, fPreBlend.fG);
506             }
507         } else {
508             SkASSERT(SkMask::kARGB32_Format != mask.fFormat);
509             generateMask(mask, devPath, fPreBlend);
510         }
511     } else {
512         generateImage(*glyph);
513     }
514 
515     if (fMaskFilter) {
516         SkMask      srcM, dstM;
517         SkMatrix    matrix;
518 
519         // the src glyph image shouldn't be 3D
520         SkASSERT(SkMask::k3D_Format != glyph->fMaskFormat);
521 
522         SkAutoSMalloc<32*32> a8storage;
523         glyph->toMask(&srcM);
524         if (SkMask::kARGB32_Format == srcM.fFormat) {
525             // now we need to extract the alpha-channel from the glyph's image
526             // and copy it into a temp buffer, and then point srcM at that temp.
527             srcM.fFormat = SkMask::kA8_Format;
528             srcM.fRowBytes = SkAlign4(srcM.fBounds.width());
529             size_t size = srcM.computeImageSize();
530             a8storage.reset(size);
531             srcM.fImage = (uint8_t*)a8storage.get();
532             extract_alpha(srcM,
533                           (const SkPMColor*)glyph->fImage, glyph->rowBytes());
534         }
535 
536         fRec.getMatrixFrom2x2(&matrix);
537 
538         if (fMaskFilter->filterMask(&dstM, srcM, matrix, nullptr)) {
539             int width = SkFastMin32(origGlyph.fWidth, dstM.fBounds.width());
540             int height = SkFastMin32(origGlyph.fHeight, dstM.fBounds.height());
541             int dstRB = origGlyph.rowBytes();
542             int srcRB = dstM.fRowBytes;
543 
544             const uint8_t* src = (const uint8_t*)dstM.fImage;
545             uint8_t* dst = (uint8_t*)origGlyph.fImage;
546 
547             if (SkMask::k3D_Format == dstM.fFormat) {
548                 // we have to copy 3 times as much
549                 height *= 3;
550             }
551 
552             // clean out our glyph, since it may be larger than dstM
553             //sk_bzero(dst, height * dstRB);
554 
555             while (--height >= 0) {
556                 memcpy(dst, src, width);
557                 src += srcRB;
558                 dst += dstRB;
559             }
560             SkMask::FreeImage(dstM.fImage);
561 
562             if (fPreBlendForFilter.isApplicable()) {
563                 applyLUTToA8Mask(srcM, fPreBlendForFilter.fG);
564             }
565         }
566     }
567 }
568 
getPath(SkPackedGlyphID glyphID,SkPath * path)569 void SkScalerContext::getPath(SkPackedGlyphID glyphID, SkPath* path) {
570     this->internalGetPath(glyphID, nullptr, path, nullptr);
571 }
572 
getFontMetrics(SkPaint::FontMetrics * fm)573 void SkScalerContext::getFontMetrics(SkPaint::FontMetrics* fm) {
574     SkASSERT(fm);
575     this->generateFontMetrics(fm);
576 }
577 
generateGlyphToChar(uint16_t glyph)578 SkUnichar SkScalerContext::generateGlyphToChar(uint16_t glyph) {
579     return 0;
580 }
581 
582 ///////////////////////////////////////////////////////////////////////////////
583 
internalGetPath(SkPackedGlyphID glyphID,SkPath * fillPath,SkPath * devPath,SkMatrix * fillToDevMatrix)584 void SkScalerContext::internalGetPath(SkPackedGlyphID glyphID, SkPath* fillPath,
585                                       SkPath* devPath, SkMatrix* fillToDevMatrix) {
586     SkPath  path;
587     generatePath(glyphID.code(), &path);
588 
589     if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
590         SkFixed dx = glyphID.getSubXFixed();
591         SkFixed dy = glyphID.getSubYFixed();
592         if (dx | dy) {
593             path.offset(SkFixedToScalar(dx), SkFixedToScalar(dy));
594         }
595     }
596 
597     if (fRec.fFrameWidth > 0 || fPathEffect != nullptr) {
598         // need the path in user-space, with only the point-size applied
599         // so that our stroking and effects will operate the same way they
600         // would if the user had extracted the path themself, and then
601         // called drawPath
602         SkPath      localPath;
603         SkMatrix    matrix, inverse;
604 
605         fRec.getMatrixFrom2x2(&matrix);
606         if (!matrix.invert(&inverse)) {
607             // assume fillPath and devPath are already empty.
608             return;
609         }
610         path.transform(inverse, &localPath);
611         // now localPath is only affected by the paint settings, and not the canvas matrix
612 
613         SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
614 
615         if (fRec.fFrameWidth > 0) {
616             rec.setStrokeStyle(fRec.fFrameWidth,
617                                SkToBool(fRec.fFlags & kFrameAndFill_Flag));
618             // glyphs are always closed contours, so cap type is ignored,
619             // so we just pass something.
620             rec.setStrokeParams((SkPaint::Cap)fRec.fStrokeCap,
621                                 (SkPaint::Join)fRec.fStrokeJoin,
622                                 fRec.fMiterLimit);
623         }
624 
625         if (fPathEffect) {
626             SkPath effectPath;
627             if (fPathEffect->filterPath(&effectPath, localPath, &rec, nullptr)) {
628                 localPath.swap(effectPath);
629             }
630         }
631 
632         if (rec.needToApply()) {
633             SkPath strokePath;
634             if (rec.applyToPath(&strokePath, localPath)) {
635                 localPath.swap(strokePath);
636             }
637         }
638 
639         // now return stuff to the caller
640         if (fillToDevMatrix) {
641             *fillToDevMatrix = matrix;
642         }
643         if (devPath) {
644             localPath.transform(matrix, devPath);
645         }
646         if (fillPath) {
647             fillPath->swap(localPath);
648         }
649     } else {   // nothing tricky to do
650         if (fillToDevMatrix) {
651             fillToDevMatrix->reset();
652         }
653         if (devPath) {
654             if (fillPath == nullptr) {
655                 devPath->swap(path);
656             } else {
657                 *devPath = path;
658             }
659         }
660 
661         if (fillPath) {
662             fillPath->swap(path);
663         }
664     }
665 
666     if (devPath) {
667         devPath->updateBoundsCache();
668     }
669     if (fillPath) {
670         fillPath->updateBoundsCache();
671     }
672 }
673 
674 
getMatrixFrom2x2(SkMatrix * dst) const675 void SkScalerContextRec::getMatrixFrom2x2(SkMatrix* dst) const {
676     dst->setAll(fPost2x2[0][0], fPost2x2[0][1], 0,
677                 fPost2x2[1][0], fPost2x2[1][1], 0,
678                 0,              0,              1);
679 }
680 
getLocalMatrix(SkMatrix * m) const681 void SkScalerContextRec::getLocalMatrix(SkMatrix* m) const {
682     SkPaintPriv::MakeTextMatrix(m, fTextSize, fPreScaleX, fPreSkewX);
683 }
684 
getSingleMatrix(SkMatrix * m) const685 void SkScalerContextRec::getSingleMatrix(SkMatrix* m) const {
686     this->getLocalMatrix(m);
687 
688     //  now concat the device matrix
689     SkMatrix    deviceMatrix;
690     this->getMatrixFrom2x2(&deviceMatrix);
691     m->postConcat(deviceMatrix);
692 }
693 
computeMatrices(PreMatrixScale preMatrixScale,SkVector * s,SkMatrix * sA,SkMatrix * GsA,SkMatrix * G_inv,SkMatrix * A_out)694 bool SkScalerContextRec::computeMatrices(PreMatrixScale preMatrixScale, SkVector* s, SkMatrix* sA,
695                                          SkMatrix* GsA, SkMatrix* G_inv, SkMatrix* A_out)
696 {
697     // A is the 'total' matrix.
698     SkMatrix A;
699     this->getSingleMatrix(&A);
700 
701     // The caller may find the 'total' matrix useful when dealing directly with EM sizes.
702     if (A_out) {
703         *A_out = A;
704     }
705 
706     // GA is the matrix A with rotation removed.
707     SkMatrix GA;
708     bool skewedOrFlipped = A.getSkewX() || A.getSkewY() || A.getScaleX() < 0 || A.getScaleY() < 0;
709     if (skewedOrFlipped) {
710         // QR by Givens rotations. G is Q^T and GA is R. G is rotational (no reflections).
711         // h is where A maps the horizontal baseline.
712         SkPoint h = SkPoint::Make(SK_Scalar1, 0);
713         A.mapPoints(&h, 1);
714 
715         // G is the Givens Matrix for A (rotational matrix where GA[0][1] == 0).
716         SkMatrix G;
717         SkComputeGivensRotation(h, &G);
718 
719         GA = G;
720         GA.preConcat(A);
721 
722         // The 'remainingRotation' is G inverse, which is fairly simple since G is 2x2 rotational.
723         if (G_inv) {
724             G_inv->setAll(
725                 G.get(SkMatrix::kMScaleX), -G.get(SkMatrix::kMSkewX), G.get(SkMatrix::kMTransX),
726                 -G.get(SkMatrix::kMSkewY), G.get(SkMatrix::kMScaleY), G.get(SkMatrix::kMTransY),
727                 G.get(SkMatrix::kMPersp0), G.get(SkMatrix::kMPersp1), G.get(SkMatrix::kMPersp2));
728         }
729     } else {
730         GA = A;
731         if (G_inv) {
732             G_inv->reset();
733         }
734     }
735 
736     // If the 'total' matrix is singular, set the 'scale' to something finite and zero the matrices.
737     // All underlying ports have issues with zero text size, so use the matricies to zero.
738     // If one of the scale factors is less than 1/256 then an EM filling square will
739     // never affect any pixels.
740     if (SkScalarAbs(GA.get(SkMatrix::kMScaleX)) <= SK_ScalarNearlyZero ||
741         SkScalarAbs(GA.get(SkMatrix::kMScaleY)) <= SK_ScalarNearlyZero)
742     {
743         s->fX = SK_Scalar1;
744         s->fY = SK_Scalar1;
745         sA->setScale(0, 0);
746         if (GsA) {
747             GsA->setScale(0, 0);
748         }
749         if (G_inv) {
750             G_inv->reset();
751         }
752         return false;
753     }
754 
755     // At this point, given GA, create s.
756     switch (preMatrixScale) {
757         case kFull_PreMatrixScale:
758             s->fX = SkScalarAbs(GA.get(SkMatrix::kMScaleX));
759             s->fY = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
760             break;
761         case kVertical_PreMatrixScale: {
762             SkScalar yScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
763             s->fX = yScale;
764             s->fY = yScale;
765             break;
766         }
767         case kVerticalInteger_PreMatrixScale: {
768             SkScalar realYScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
769             SkScalar intYScale = SkScalarRoundToScalar(realYScale);
770             if (intYScale == 0) {
771                 intYScale = SK_Scalar1;
772             }
773             s->fX = intYScale;
774             s->fY = intYScale;
775             break;
776         }
777     }
778 
779     // The 'remaining' matrix sA is the total matrix A without the scale.
780     if (!skewedOrFlipped && (
781             (kFull_PreMatrixScale == preMatrixScale) ||
782             (kVertical_PreMatrixScale == preMatrixScale && A.getScaleX() == A.getScaleY())))
783     {
784         // If GA == A and kFull_PreMatrixScale, sA is identity.
785         // If GA == A and kVertical_PreMatrixScale and A.scaleX == A.scaleY, sA is identity.
786         sA->reset();
787     } else if (!skewedOrFlipped && kVertical_PreMatrixScale == preMatrixScale) {
788         // If GA == A and kVertical_PreMatrixScale, sA.scaleY is SK_Scalar1.
789         sA->reset();
790         sA->setScaleX(A.getScaleX() / s->fY);
791     } else {
792         // TODO: like kVertical_PreMatrixScale, kVerticalInteger_PreMatrixScale with int scales.
793         *sA = A;
794         sA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
795     }
796 
797     // The 'remainingWithoutRotation' matrix GsA is the non-rotational part of A without the scale.
798     if (GsA) {
799         *GsA = GA;
800          // G is rotational so reorders with the scale.
801         GsA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
802     }
803 
804     return true;
805 }
806 
computeAxisAlignmentForHText()807 SkAxisAlignment SkScalerContext::computeAxisAlignmentForHText() {
808     // Why fPost2x2 can be used here.
809     // getSingleMatrix multiplies in getLocalMatrix, which consists of
810     // * fTextSize (a scale, which has no effect)
811     // * fPreScaleX (a scale in x, which has no effect)
812     // * fPreSkewX (has no effect, but would on vertical text alignment).
813     // In other words, making the text bigger, stretching it along the
814     // horizontal axis, or fake italicizing it does not move the baseline.
815 
816     if (0 == fRec.fPost2x2[1][0]) {
817         // The x axis is mapped onto the x axis.
818         return kX_SkAxisAlignment;
819     }
820     if (0 == fRec.fPost2x2[0][0]) {
821         // The x axis is mapped onto the y axis.
822         return kY_SkAxisAlignment;
823     }
824     return kNone_SkAxisAlignment;
825 }
826 
827 ///////////////////////////////////////////////////////////////////////////////
828 
829 class SkScalerContext_Empty : public SkScalerContext {
830 public:
SkScalerContext_Empty(sk_sp<SkTypeface> typeface,const SkScalerContextEffects & effects,const SkDescriptor * desc)831     SkScalerContext_Empty(sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
832                           const SkDescriptor* desc)
833         : SkScalerContext(std::move(typeface), effects, desc) {}
834 
835 protected:
generateGlyphCount()836     unsigned generateGlyphCount() override {
837         return 0;
838     }
generateCharToGlyph(SkUnichar uni)839     uint16_t generateCharToGlyph(SkUnichar uni) override {
840         return 0;
841     }
generateAdvance(SkGlyph * glyph)842     void generateAdvance(SkGlyph* glyph) override {
843         glyph->zeroMetrics();
844     }
generateMetrics(SkGlyph * glyph)845     void generateMetrics(SkGlyph* glyph) override {
846         glyph->zeroMetrics();
847     }
generateImage(const SkGlyph & glyph)848     void generateImage(const SkGlyph& glyph) override {}
generatePath(SkGlyphID glyph,SkPath * path)849     void generatePath(SkGlyphID glyph, SkPath* path) override {}
generateFontMetrics(SkPaint::FontMetrics * metrics)850     void generateFontMetrics(SkPaint::FontMetrics* metrics) override {
851         if (metrics) {
852             sk_bzero(metrics, sizeof(*metrics));
853         }
854     }
855 };
856 
857 extern SkScalerContext* SkCreateColorScalerContext(const SkDescriptor* desc);
858 
createScalerContext(const SkScalerContextEffects & effects,const SkDescriptor * desc,bool allowFailure) const859 std::unique_ptr<SkScalerContext> SkTypeface::createScalerContext(
860     const SkScalerContextEffects& effects, const SkDescriptor* desc, bool allowFailure) const
861 {
862     std::unique_ptr<SkScalerContext> c(this->onCreateScalerContext(effects, desc));
863     if (!c && !allowFailure) {
864         c = skstd::make_unique<SkScalerContext_Empty>(sk_ref_sp(const_cast<SkTypeface*>(this)),
865                                                       effects, desc);
866     }
867     return c;
868 }
869