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