Debian Codegraph @

src/core/SkScalerContext.cpp

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 } else {
576 dst.reset(info, dstMask.image(), dstMask.fRowBytes);
577 }
578 sk_bzero(dst.writable_addr(), dst.computeByteSize());
579
580 skcpu::Draw draw;
581 draw.fBlitterChooser = SkA8Blitter_Choose;
582 draw.fDst = dst;
583 draw.fRC = &clip;
584 draw.fCTM = &matrix;
585 // We can save a copy if we had to use the local strokePath
586 draw.drawPath(*pathToUse, paint, nullptr);
587
588 switch (dstMask.fFormat) {
589 case SkMask::kBW_Format:
590 packA8ToA1(dstMask, dst.addr8(0, 0), dst.rowBytes());
591 break;
592 case SkMask::kA8_Format:
593 if (fromLCD) {
594 pack4xHToMask(dst, dstMask, maskPreBlend, doBGR, verticalLCD);
595 } else if (maskPreBlend.isApplicable()) {
596 applyLUTToA8Mask(dstMask, maskPreBlend.fG);
597 }
598 break;
599 case SkMask::kLCD16_Format:
600 pack4xHToMask(dst, dstMask, maskPreBlend, doBGR, verticalLCD);
601 break;
602 default:
603 break;
604 }
605 }
606
607 void SkScalerContext::getImage(const SkGlyph& origGlyph) {
608 SkASSERT(origGlyph.fAdvancesBoundsFormatAndInitialPathDone);
609
610 const SkGlyph* unfilteredGlyph = &origGlyph;
611 // in case we need to call generateImage on a mask-format that is different
612 // (i.e. larger) than what our caller allocated by looking at origGlyph.
613 SkAutoMalloc tmpGlyphImageStorage;
614 SkGlyph tmpGlyph;
615 SkSTArenaAlloc<sizeof(SkGlyph::PathData)> tmpGlyphPathDataStorage;
616 if (fMaskFilter) {
617 // need the original bounds, sans our maskfilter
618 sk_sp<SkMaskFilter> mf = std::move(fMaskFilter);
619 tmpGlyph = this->makeGlyph(origGlyph.getPackedID(), &tmpGlyphPathDataStorage);
620 fMaskFilter = std::move(mf);
621
622 // Use the origGlyph storage for the temporary unfiltered mask if it will fit.
623 if (tmpGlyph.fMaskFormat == origGlyph.fMaskFormat &&
624 tmpGlyph.imageSize() <= origGlyph.imageSize())
625 {
626 tmpGlyph.fImage = origGlyph.fImage;
627 } else {
628 tmpGlyphImageStorage.reset(tmpGlyph.imageSize());
629 tmpGlyph.fImage = tmpGlyphImageStorage.get();
630 }
631 unfilteredGlyph = &tmpGlyph;
632 }
633
634 if (!fGenerateImageFromPath) {
635 generateImage(*unfilteredGlyph, unfilteredGlyph->fImage);
636 } else {
637 SkASSERT(origGlyph.setPathHasBeenCalled());
638 const SkPath* devPath = origGlyph.path();
639
640 if (!devPath) {
641 generateImage(*unfilteredGlyph, unfilteredGlyph->fImage);
642 } else {
643 SkMaskBuilder mask(static_cast<uint8_t*>(unfilteredGlyph->fImage),
644 unfilteredGlyph->iRect(), unfilteredGlyph->rowBytes(),
645 unfilteredGlyph->maskFormat());
646 SkASSERT(SkMask::kARGB32_Format != origGlyph.fMaskFormat);
647 SkASSERT(SkMask::kARGB32_Format != mask.fFormat);
648 const bool doBGR = SkToBool(fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag);
649 const bool doVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
650 const bool a8LCD = SkToBool(fRec.fFlags & SkScalerContext::kGenA8FromLCD_Flag);
651 const bool hairline = origGlyph.pathIsHairline();
652 GenerateImageFromPath(mask, *devPath, fPreBlend, doBGR, doVert, a8LCD, hairline);
653 }
654 }
655
656 if (fMaskFilter) {
657 // k3D_Format should not be mask filtered.
658 SkASSERT(SkMask::k3D_Format != unfilteredGlyph->fMaskFormat);
659
660 SkMaskBuilder srcMask;
661 SkAutoMaskFreeImage srcMaskOwnedImage(nullptr);
662
663 if (as_MFB(fMaskFilter)->filterMask(&srcMask, unfilteredGlyph->mask(),
664 fRec.getMatrixFrom2x2(), nullptr)) {
665 // Filter succeeded; srcMask.fImage was allocated.
666 srcMaskOwnedImage.reset(srcMask.image());
667 } else if (unfilteredGlyph->fImage == tmpGlyphImageStorage.get()) {
668 // Filter did nothing; unfiltered mask is independent of origGlyph.fImage.
669 srcMask = SkMaskBuilder(static_cast<uint8_t*>(unfilteredGlyph->fImage),
670 unfilteredGlyph->iRect(), unfilteredGlyph->rowBytes(),
671 unfilteredGlyph->maskFormat());
672 } else if (origGlyph.iRect() == unfilteredGlyph->iRect()) {
673 // Filter did nothing; the unfiltered mask is in origGlyph.fImage and matches.
674 return;
675 } else {
676 // Filter did nothing; the unfiltered mask is in origGlyph.fImage and conflicts.
677 srcMask = SkMaskBuilder(static_cast<uint8_t*>(unfilteredGlyph->fImage),
678 unfilteredGlyph->iRect(), unfilteredGlyph->rowBytes(),
679 unfilteredGlyph->maskFormat());
680 size_t imageSize = unfilteredGlyph->imageSize();
681 tmpGlyphImageStorage.reset(imageSize);
682 srcMask.image() = static_cast<uint8_t*>(tmpGlyphImageStorage.get());
683 memcpy(srcMask.image(), unfilteredGlyph->fImage, imageSize);
684 }
685
686 SkASSERT_RELEASE(srcMask.fFormat == origGlyph.fMaskFormat);
687 SkMaskBuilder dstMask = SkMaskBuilder(static_cast<uint8_t*>(origGlyph.fImage),
688 origGlyph.iRect(), origGlyph.rowBytes(),
689 origGlyph.maskFormat());
690 SkIRect origBounds = dstMask.fBounds;
691
692 // Find the intersection of src and dst while updating the fImages.
693 if (srcMask.fBounds.fTop < dstMask.fBounds.fTop) {
694 int32_t topDiff = dstMask.fBounds.fTop - srcMask.fBounds.fTop;
695 srcMask.image() += srcMask.fRowBytes * topDiff;
696 srcMask.bounds().fTop = dstMask.fBounds.fTop;
697 }
698 if (dstMask.fBounds.fTop < srcMask.fBounds.fTop) {
699 int32_t topDiff = srcMask.fBounds.fTop - dstMask.fBounds.fTop;
700 dstMask.image() += dstMask.fRowBytes * topDiff;
701 dstMask.bounds().fTop = srcMask.fBounds.fTop;
702 }
703
704 if (srcMask.fBounds.fLeft < dstMask.fBounds.fLeft) {
705 int32_t leftDiff = dstMask.fBounds.fLeft - srcMask.fBounds.fLeft;
706 srcMask.image() += leftDiff;
707 srcMask.bounds().fLeft = dstMask.fBounds.fLeft;
708 }
709 if (dstMask.fBounds.fLeft < srcMask.fBounds.fLeft) {
710 int32_t leftDiff = srcMask.fBounds.fLeft - dstMask.fBounds.fLeft;
711 dstMask.image() += leftDiff;
712 dstMask.bounds().fLeft = srcMask.fBounds.fLeft;
713 }
714
715 if (srcMask.fBounds.fBottom < dstMask.fBounds.fBottom) {
716 dstMask.bounds().fBottom = srcMask.fBounds.fBottom;
717 }
718 if (dstMask.fBounds.fBottom < srcMask.fBounds.fBottom) {
719 srcMask.bounds().fBottom = dstMask.fBounds.fBottom;
720 }
721
722 if (srcMask.fBounds.fRight < dstMask.fBounds.fRight) {
723 dstMask.bounds().fRight = srcMask.fBounds.fRight;
724 }
725 if (dstMask.fBounds.fRight < srcMask.fBounds.fRight) {
726 srcMask.bounds().fRight = dstMask.fBounds.fRight;
727 }
728
729 SkASSERT(srcMask.fBounds == dstMask.fBounds);
730 int width = srcMask.fBounds.width();
731 int height = srcMask.fBounds.height();
732 int dstRB = dstMask.fRowBytes;
733 int srcRB = srcMask.fRowBytes;
734
735 const uint8_t* src = srcMask.fImage;
736 uint8_t* dst = dstMask.image();
737
738 if (SkMask::k3D_Format == srcMask.fFormat) {
739 // we have to copy 3 times as much
740 height *= 3;
741 }
742
743 // If not filling the full original glyph, clear it out first.
744 if (dstMask.fBounds != origBounds) {
745 sk_bzero(origGlyph.fImage, origGlyph.fHeight * origGlyph.rowBytes());
746 }
747
748 while (--height >= 0) {
749 memcpy(dst, src, width);
750 src += srcRB;
751 dst += dstRB;
752 }
753 }
754 }
755
756 void SkScalerContext::getPath(SkGlyph& glyph, SkArenaAlloc* alloc) {
757 this->internalGetPath(glyph, alloc, std::nullopt);
758 }
759
760 sk_sp<SkDrawable> SkScalerContext::getDrawable(SkGlyph& glyph) {
761 return this->generateDrawable(glyph);
762 }
763 //TODO: make pure virtual
764 sk_sp<SkDrawable> SkScalerContext::generateDrawable(const SkGlyph&) {
765 return nullptr;
766 }
767
768 void SkScalerContext::getFontMetrics(SkFontMetrics* fm) {
769 SkASSERT(fm);
770 this->generateFontMetrics(fm);
771 }
772
773 ///////////////////////////////////////////////////////////////////////////////
774
775 void SkScalerContext::internalGetPath(SkGlyph& glyph, SkArenaAlloc* alloc,
776 std::optional<GeneratedPath>&& generatedPath) {
777 SkASSERT(glyph.fAdvancesBoundsFormatAndInitialPathDone);
778
779 if (glyph.setPathHasBeenCalled()) {
780 return;
781 }
782
783 if (!generatedPath) {
784 generatedPath = this->generatePath(glyph);
785 }
786 if (!generatedPath) {
787 glyph.setPath(alloc, (SkPath*)nullptr, false, false);
788 return;
789 }
790
791 SkPath path = std::move(generatedPath->path);
792 bool pathModified = std::move(generatedPath->modified);
793
794 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
795 SkPackedGlyphID glyphID = glyph.getPackedID();
796 SkFixed dx = glyphID.getSubXFixed();
797 SkFixed dy = glyphID.getSubYFixed();
798 if (dx | dy) {
799 pathModified = true;
800 path = path.makeOffset(SkFixedToScalar(dx), SkFixedToScalar(dy));
801 }
802 }
803
804 if (fRec.fFrameWidth < 0 && fPathEffect == nullptr) {
805 glyph.setPath(alloc, &path, false, pathModified);
806 return;
807 }
808
809 pathModified = true; // It could still end up the same, but it's probably going to change.
810
811 // need the path in user-space, with only the point-size applied
812 // so that our stroking and effects will operate the same way they
813 // would if the user had extracted the path themself, and then
814 // called drawPath
815 SkMatrix matrix = fRec.getMatrixFrom2x2();
816
817 // We apply the inverse, so that localPath is only affected by the paint settings
818 // and not the canvas matrix.
819 auto inverse = matrix.invert();
820 if (!inverse) {
821 SkPath empty;
822 glyph.setPath(alloc, &empty, false, pathModified);
823 return;
824 }
825 auto localPath = path.makeTransform(*inverse);
826
827 SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
828
829 if (fRec.fFrameWidth >= 0) {
830 rec.setStrokeStyle(fRec.fFrameWidth,
831 SkToBool(fRec.fFlags & kFrameAndFill_Flag));
832 // glyphs are always closed contours, so cap type is ignored,
833 // so we just pass something.
834 rec.setStrokeParams((SkPaint::Cap)fRec.fStrokeCap,
835 (SkPaint::Join)fRec.fStrokeJoin,
836 fRec.fMiterLimit);
837 }
838
839 if (fPathEffect) {
840 SkPathBuilder builder;
841 if (fPathEffect->filterPath(&builder, localPath, &rec, nullptr, matrix)) {
842 localPath = builder.detach();
843 }
844 }
845
846 if (rec.needToApply()) {
847 SkPathBuilder builder;
848 if (rec.applyToPath(&builder, localPath)) {
849 localPath = builder.detach();
850 }
851 }
852
853 auto devPath = localPath.makeTransform(matrix);
854 glyph.setPath(alloc, &devPath, rec.isHairlineStyle(), pathModified);
855 }
856
857
858 SkMatrix SkScalerContextRec::getMatrixFrom2x2() const {
859 return SkMatrix::MakeAll(fPost2x2[0][0], fPost2x2[0][1], 0,
860 fPost2x2[1][0], fPost2x2[1][1], 0,
861 0, 0, 1);
862 }
863
864 SkMatrix SkScalerContextRec::getLocalMatrix() const {
865 return SkFontPriv::MakeTextMatrix(fTextSize, fPreScaleX, fPreSkewX);
866 }
867
868 SkMatrix SkScalerContextRec::getSingleMatrix() const {
869 return this->getLocalMatrix().postConcat(this->getMatrixFrom2x2());
870 }
871
872 bool SkScalerContextRec::computeMatrices(PreMatrixScale preMatrixScale, SkVector* s, SkMatrix* sA,
873 SkMatrix* GsA, SkMatrix* G_inv, SkMatrix* A_out) const
874 {
875 // A is the 'total' matrix.
876 const SkMatrix A = this->getSingleMatrix();
877
878 // The caller may find the 'total' matrix useful when dealing directly with EM sizes.
879 if (A_out) {
880 *A_out = A;
881 }
882
883 // GA is the matrix A with rotation removed.
884 SkMatrix GA;
885 bool skewedOrFlipped = A.getSkewX() || A.getSkewY() || A.getScaleX() < 0 || A.getScaleY() < 0;
886 if (skewedOrFlipped) {
887 // QR by Givens rotations. G is Q^T and GA is R. G is rotational (no reflections).
888 // h is where A maps the horizontal baseline.
889 SkPoint h = A.mapPoint({SK_Scalar1, 0});
890
891 // G is the Givens Matrix for A (rotational matrix where GA[0][1] == 0).
892 SkMatrix G;
893 SkComputeGivensRotation(h, &G);
894
895 GA = G;
896 GA.preConcat(A);
897
898 // The 'remainingRotation' is G inverse, which is fairly simple since G is 2x2 rotational.
899 if (G_inv) {
900 G_inv->setAll(
901 G.get(SkMatrix::kMScaleX), -G.get(SkMatrix::kMSkewX), G.get(SkMatrix::kMTransX),
902 -G.get(SkMatrix::kMSkewY), G.get(SkMatrix::kMScaleY), G.get(SkMatrix::kMTransY),
903 G.get(SkMatrix::kMPersp0), G.get(SkMatrix::kMPersp1), G.get(SkMatrix::kMPersp2));
904 }
905 } else {
906 GA = A;
907 if (G_inv) {
908 G_inv->reset();
909 }
910 }
911
912 // If the 'total' matrix is singular, set the 'scale' to something finite and zero the matrices.
913 // All underlying ports have issues with zero text size, so use the matricies to zero.
914 // If one of the scale factors is less than 1/256 then an EM filling square will
915 // never affect any pixels.
916 // If there are any nonfinite numbers in the matrix, bail out and set the matrices to zero.
917 if (SkScalarAbs(GA.get(SkMatrix::kMScaleX)) <= SK_ScalarNearlyZero ||
918 SkScalarAbs(GA.get(SkMatrix::kMScaleY)) <= SK_ScalarNearlyZero ||
919 !GA.isFinite())
920 {
921 s->fX = SK_Scalar1;
922 s->fY = SK_Scalar1;
923 sA->setScale(0, 0);
924 if (GsA) {
925 GsA->setScale(0, 0);
926 }
927 if (G_inv) {
928 G_inv->reset();
929 }
930 return false;
931 }
932
933 // At this point, given GA, create s.
934 switch (preMatrixScale) {
935 case PreMatrixScale::kFull:
936 s->fX = SkScalarAbs(GA.get(SkMatrix::kMScaleX));
937 s->fY = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
938 break;
939 case PreMatrixScale::kVertical: {
940 SkScalar yScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
941 s->fX = yScale;
942 s->fY = yScale;
943 break;
944 }
945 case PreMatrixScale::kVerticalInteger: {
946 SkScalar realYScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
947 SkScalar intYScale = SkScalarRoundToScalar(realYScale);
948 if (intYScale == 0) {
949 intYScale = SK_Scalar1;
950 }
951 s->fX = intYScale;
952 s->fY = intYScale;
953 break;
954 }
955 }
956
957 // The 'remaining' matrix sA is the total matrix A without the scale.
958 if (!skewedOrFlipped && (
959 (PreMatrixScale::kFull == preMatrixScale) ||
960 (PreMatrixScale::kVertical == preMatrixScale && A.getScaleX() == A.getScaleY())))
961 {
962 // If GA == A and kFull, sA is identity.
963 // If GA == A and kVertical and A.scaleX == A.scaleY, sA is identity.
964 sA->reset();
965 } else if (!skewedOrFlipped && PreMatrixScale::kVertical == preMatrixScale) {
966 // If GA == A and kVertical, sA.scaleY is SK_Scalar1.
967 sA->reset();
968 sA->setScaleX(A.getScaleX() / s->fY);
969 } else {
970 // TODO: like kVertical, kVerticalInteger with int scales.
971 *sA = A;
972 sA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
973 }
974
975 // The 'remainingWithoutRotation' matrix GsA is the non-rotational part of A without the scale.
976 if (GsA) {
977 *GsA = GA;
978 // G is rotational so reorders with the scale.
979 GsA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
980 }
981
982 return true;
983 }
984
985 SkAxisAlignment SkScalerContext::computeAxisAlignmentForHText() const {
986 return fRec.computeAxisAlignmentForHText();
987 }
988
989 SkAxisAlignment SkScalerContextRec::computeAxisAlignmentForHText() const {
990 // Why fPost2x2 can be used here.
991 // getSingleMatrix multiplies in getLocalMatrix, which consists of
992 // * fTextSize (a scale, which has no effect)
993 // * fPreScaleX (a scale in x, which has no effect)
994 // * fPreSkewX (has no effect, but would on vertical text alignment).
995 // In other words, making the text bigger, stretching it along the
996 // horizontal axis, or fake italicizing it does not move the baseline.
997 if (!SkToBool(fFlags & SkScalerContext::kBaselineSnap_Flag)) {
998 return SkAxisAlignment::kNone;
999 }
1000
1001 if (0 == fPost2x2[1][0]) {
1002 // The x axis is mapped onto the x axis.
1003 return SkAxisAlignment::kX;
1004 }
1005 if (0 == fPost2x2[0][0]) {
1006 // The x axis is mapped onto the y axis.
1007 return SkAxisAlignment::kY;
1008 }
1009 return SkAxisAlignment::kNone;
1010 }
1011
1012 void SkScalerContextRec::setLuminanceColor(SkColor c) {
1013 fLumBits = SkMaskGamma::CanonicalColor(
1014 SkColorSetRGB(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c)));
1015 }
1016
1017 void SkScalerContextRec::useStrokeForFakeBold() {
1018 if (!SkToBool(fFlags & SkScalerContext::kEmbolden_Flag)) {
1019 return;
1020 }
1021 fFlags &= ~SkScalerContext::kEmbolden_Flag;
1022
1023 SkScalar fakeBoldScale = SkFloatInterpFunc(fTextSize,
1024 kStdFakeBoldInterpKeys,
1025 kStdFakeBoldInterpValues,
1026 kStdFakeBoldInterpLength);
1027 SkScalar extra = fTextSize * fakeBoldScale;
1028
1029 if (fFrameWidth >= 0) {
1030 fFrameWidth += extra;
1031 } else {
1032 fFlags |= SkScalerContext::kFrameAndFill_Flag;
1033 fFrameWidth = extra;
1034 SkPaint paint;
1035 fMiterLimit = paint.getStrokeMiter();
1036 fStrokeJoin = SkToU8(paint.getStrokeJoin());
1037 fStrokeCap = SkToU8(paint.getStrokeCap());
1038 }
1039 }
1040
1041 /*
1042 * Return the scalar with only limited fractional precision. Used to consolidate matrices
1043 * that vary only slightly when we create our key into the font cache, since the font scaler
1044 * typically returns the same looking resuts for tiny changes in the matrix.
1045 */
1046 static SkScalar sk_relax(SkScalar x) {
1047 SkScalar n = SkScalarRoundToScalar(x * 1024);
1048 return n / 1024.0f;
1049 }
1050
1051 static SkMask::Format compute_mask_format(const SkFont& font) {
1052 switch (font.getEdging()) {
1053 case SkFont::Edging::kAlias:
1054 return SkMask::kBW_Format;
1055 case SkFont::Edging::kAntiAlias:
1056 return SkMask::kA8_Format;
1057 case SkFont::Edging::kSubpixelAntiAlias:
1058 return SkMask::kLCD16_Format;
1059 }
1060 SkASSERT(false);
1061 return SkMask::kA8_Format;
1062 }
1063
1064 // Beyond this size, LCD doesn't appreciably improve quality, but it always
1065 // cost more RAM and draws slower, so we set a cap.
1066 #ifndef SK_MAX_SIZE_FOR_LCDTEXT
1067 #define SK_MAX_SIZE_FOR_LCDTEXT 48
1068 #endif
1069
1070 const SkScalar gMaxSize2ForLCDText = SK_MAX_SIZE_FOR_LCDTEXT * SK_MAX_SIZE_FOR_LCDTEXT;
1071
1072 static bool too_big_for_lcd(const SkScalerContextRec& rec, bool checkPost2x2) {
1073 if (checkPost2x2) {
1074 SkScalar area = rec.fPost2x2[0][0] * rec.fPost2x2[1][1] -
1075 rec.fPost2x2[1][0] * rec.fPost2x2[0][1];
1076 area *= rec.fTextSize * rec.fTextSize;
1077 return area > gMaxSize2ForLCDText;
1078 } else {
1079 return rec.fTextSize > SK_MAX_SIZE_FOR_LCDTEXT;
1080 }
1081 }
1082
1083 // The only reason this is not file static is because it needs the context of SkScalerContext to
1084 // access SkPaint::computeLuminanceColor.
1085 void SkScalerContext::MakeRecAndEffects(const SkFont& font, const SkPaint& paint,
1086 const SkSurfaceProps& surfaceProps,
1087 SkScalerContextFlags scalerContextFlags,
1088 const SkMatrix& deviceMatrix,
1089 SkScalerContextRec* rec,
1090 SkScalerContextEffects* effects) {
1091 SkASSERT(!deviceMatrix.hasPerspective());
1092
1093 sk_bzero(rec, sizeof(SkScalerContextRec));
1094
1095 SkTypeface* typeface = font.getTypeface();
1096
1097 rec->fTypefaceID = typeface->uniqueID();
1098 rec->fTextSize = font.getSize();
1099 rec->fPreScaleX = font.getScaleX();
1100 rec->fPreSkewX = font.getSkewX();
1101
1102 bool checkPost2x2 = false;
1103
1104 const SkMatrix::TypeMask mask = deviceMatrix.getType();
1105 if (mask & SkMatrix::kScale_Mask) {
1106 rec->fPost2x2[0][0] = sk_relax(deviceMatrix.getScaleX());
1107 rec->fPost2x2[1][1] = sk_relax(deviceMatrix.getScaleY());
1108 checkPost2x2 = true;
1109 } else {
1110 rec->fPost2x2[0][0] = rec->fPost2x2[1][1] = SK_Scalar1;
1111 }
1112 if (mask & SkMatrix::kAffine_Mask) {
1113 rec->fPost2x2[0][1] = sk_relax(deviceMatrix.getSkewX());
1114 rec->fPost2x2[1][0] = sk_relax(deviceMatrix.getSkewY());
1115 checkPost2x2 = true;
1116 } else {
1117 rec->fPost2x2[0][1] = rec->fPost2x2[1][0] = 0;
1118 }
1119
1120 SkPaint::Style style = paint.getStyle();
1121 SkScalar strokeWidth = paint.getStrokeWidth();
1122
1123 unsigned flags = 0;
1124
1125 if (font.isEmbolden()) {
1126 flags |= SkScalerContext::kEmbolden_Flag;
1127 }
1128
1129 if (style != SkPaint::kFill_Style && strokeWidth >= 0) {
1130 rec->fFrameWidth = strokeWidth;
1131 rec->fMiterLimit = paint.getStrokeMiter();
1132 rec->fStrokeJoin = SkToU8(paint.getStrokeJoin());
1133 rec->fStrokeCap = SkToU8(paint.getStrokeCap());
1134
1135 if (style == SkPaint::kStrokeAndFill_Style) {
1136 flags |= SkScalerContext::kFrameAndFill_Flag;
1137 }
1138 } else {
1139 rec->fFrameWidth = -1;
1140 rec->fMiterLimit = 0;
1141 rec->fStrokeJoin = 0;
1142 rec->fStrokeCap = 0;
1143 }
1144
1145 rec->fMaskFormat = compute_mask_format(font);
1146
1147 // NOTE: SDFLCD text will never have kLCD16_Format at this point, and effectively skips this
1148 // block. Instead the subPixelGeometry is piped in during drawAtlasSubrun.
1149 if (SkMask::kLCD16_Format == rec->fMaskFormat) {
1150 if (too_big_for_lcd(*rec, checkPost2x2)) {
1151 rec->fMaskFormat = SkMask::kA8_Format;
1152 flags |= SkScalerContext::kGenA8FromLCD_Flag;
1153 } else {
1154 SkPixelGeometry geometry = surfaceProps.pixelGeometry();
1155
1156 switch (geometry) {
1157 case kUnknown_SkPixelGeometry:
1158 // eeek, can't support LCD
1159 rec->fMaskFormat = SkMask::kA8_Format;
1160 flags |= SkScalerContext::kGenA8FromLCD_Flag;
1161 break;
1162 case kRGB_H_SkPixelGeometry:
1163 // our default, do nothing.
1164 break;
1165 case kBGR_H_SkPixelGeometry:
1166 flags |= SkScalerContext::kLCD_BGROrder_Flag;
1167 break;
1168 case kRGB_V_SkPixelGeometry:
1169 flags |= SkScalerContext::kLCD_Vertical_Flag;
1170 break;
1171 case kBGR_V_SkPixelGeometry:
1172 flags |= SkScalerContext::kLCD_Vertical_Flag;
1173 flags |= SkScalerContext::kLCD_BGROrder_Flag;
1174 break;
1175 }
1176 }
1177 }
1178
1179 if (font.isEmbeddedBitmaps()) {
1180 flags |= SkScalerContext::kEmbeddedBitmapText_Flag;
1181 }
1182 if (font.isSubpixel()) {
1183 flags |= SkScalerContext::kSubpixelPositioning_Flag;
1184 }
1185 if (font.isForceAutoHinting()) {
1186 flags |= SkScalerContext::kForceAutohinting_Flag;
1187 }
1188 if (font.isLinearMetrics()) {
1189 flags |= SkScalerContext::kLinearMetrics_Flag;
1190 }
1191 if (font.isBaselineSnap()) {
1192 flags |= SkScalerContext::kBaselineSnap_Flag;
1193 }
1194 if (typeface->glyphMaskNeedsCurrentColor()) {
1195 flags |= SkScalerContext::kNeedsForegroundColor_Flag;
1196 rec->fForegroundColor = paint.getColor();
1197 }
1198 rec->fFlags = SkToU16(flags);
1199
1200 // these modify fFlags, so do them after assigning fFlags
1201 rec->setHinting(font.getHinting());
1202 rec->setLuminanceColor(SkPaintPriv::ComputeLuminanceColor(paint));
1203
1204 // The paint color is always converted to the device colr space,
1205 // so the paint gamma is now always equal to the device gamma.
1206 // The math in SkMaskGamma can handle them being different,
1207 // but it requires superluminous masks when
1208 // Ex : deviceGamma(x) < paintGamma(x) and x is sufficiently large.
1209 rec->setDeviceGamma(surfaceProps.textGamma());
1210 rec->setContrast(surfaceProps.textContrast());
1211
1212 if (!SkToBool(scalerContextFlags & SkScalerContextFlags::kFakeGamma)) {
1213 rec->ignoreGamma();
1214 }
1215 if (!SkToBool(scalerContextFlags & SkScalerContextFlags::kBoostContrast)) {
1216 rec->setContrast(0);
1217 }
1218
1219 new (effects) SkScalerContextEffects{paint};
1220 }
1221
1222 SkDescriptor* SkScalerContext::CreateDescriptorAndEffectsUsingPaint(
1223 const SkFont& font, const SkPaint& paint, const SkSurfaceProps& surfaceProps,
1224 SkScalerContextFlags scalerContextFlags, const SkMatrix& deviceMatrix, SkAutoDescriptor* ad,
1225 SkScalerContextEffects* effects)
1226 {
1227 SkScalerContextRec rec;
1228 MakeRecAndEffects(font, paint, surfaceProps, scalerContextFlags, deviceMatrix, &rec, effects);
1229 return AutoDescriptorGivenRecAndEffects(rec, *effects, ad);
1230 }
1231
1232 static size_t calculate_size_and_flatten(const SkScalerContextRec& rec,
1233 const SkScalerContextEffects& effects,
1234 SkBinaryWriteBuffer* effectBuffer) {
1235 size_t descSize = sizeof(rec);
1236 int entryCount = 1;
1237
1238 if (effects.fPathEffect || effects.fMaskFilter) {
1239 if (effects.fPathEffect) { effectBuffer->writeFlattenable(effects.fPathEffect); }
1240 if (effects.fMaskFilter) { effectBuffer->writeFlattenable(effects.fMaskFilter); }
1241 entryCount += 1;
1242 descSize += effectBuffer->bytesWritten();
1243 }
1244
1245 descSize += SkDescriptor::ComputeOverhead(entryCount);
1246 return descSize;
1247 }
1248
1249 static void generate_descriptor(const SkScalerContextRec& rec,
1250 const SkBinaryWriteBuffer& effectBuffer,
1251 SkDescriptor* desc) {
1252 desc->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec);
1253
1254 if (effectBuffer.bytesWritten() > 0) {
1255 effectBuffer.writeToMemory(desc->addEntry(kEffects_SkDescriptorTag,
1256 effectBuffer.bytesWritten(),
1257 nullptr));
1258 }
1259
1260 desc->computeChecksum();
1261 }
1262
1263 SkDescriptor* SkScalerContext::AutoDescriptorGivenRecAndEffects(
1264 const SkScalerContextRec& rec,
1265 const SkScalerContextEffects& effects,
1266 SkAutoDescriptor* ad)
1267 {
1268 SkBinaryWriteBuffer buf({});
1269
1270 ad->reset(calculate_size_and_flatten(rec, effects, &buf));
1271 generate_descriptor(rec, buf, ad->getDesc());
1272
1273 return ad->getDesc();
1274 }
1275
1276 std::unique_ptr<SkDescriptor> SkScalerContext::DescriptorGivenRecAndEffects(
1277 const SkScalerContextRec& rec,
1278 const SkScalerContextEffects& effects)
1279 {
1280 SkBinaryWriteBuffer buf({});
1281
1282 auto desc = SkDescriptor::Alloc(calculate_size_and_flatten(rec, effects, &buf));
1283 generate_descriptor(rec, buf, desc.get());
1284
1285 return desc;
1286 }
1287
1288 void SkScalerContext::DescriptorBufferGiveRec(const SkScalerContextRec& rec, void* buffer) {
1289 generate_descriptor(rec, SkBinaryWriteBuffer({}), (SkDescriptor*)buffer);
1290 }
1291
1292 bool SkScalerContext::CheckBufferSizeForRec(const SkScalerContextRec& rec,
1293 const SkScalerContextEffects& effects,
1294 size_t size) {
1295 SkBinaryWriteBuffer buf({});
1296 return size >= calculate_size_and_flatten(rec, effects, &buf);
1297 }
1298
1299 std::unique_ptr<SkScalerContext> SkScalerContext::MakeEmpty(
1300 SkTypeface& typeface, const SkScalerContextEffects& effects,
1301 const SkDescriptor* desc) {
1302 class SkScalerContext_Empty : public SkScalerContext {
1303 public:
1304 SkScalerContext_Empty(SkTypeface& typeface, const SkScalerContextEffects& effects,
1305 const SkDescriptor* desc)
1306 : SkScalerContext(typeface, effects, desc) {}
1307
1308 protected:
1309 GlyphMetrics generateMetrics(const SkGlyph& glyph, SkArenaAlloc*) override {
1310 return {glyph.maskFormat()};
1311 }
1312 void generateImage(const SkGlyph&, void*) override {}
1313 std::optional<GeneratedPath> generatePath(const SkGlyph& glyph) override {
1314 return {};
1315 }
1316 void generateFontMetrics(SkFontMetrics* metrics) override {
1317 if (metrics) {
1318 sk_bzero(metrics, sizeof(*metrics));
1319 }
1320 }
1321 };
1322
1323 return std::make_unique<SkScalerContext_Empty>(typeface, effects, desc);
1324 }
1325
1326
1327
1328