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