Debian Codegraph @

src/core/SkScalerContext.cpp

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