Debian Codegraph @

src/core/SkScalerContext.h

raw
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 #ifndef SkScalerContext_DEFINED
9 #define SkScalerContext_DEFINED
10
11 #include "include/core/SkColor.h"
12 #include "include/core/SkFourByteTag.h"
13 #include "include/core/SkMatrix.h"
14 #include "include/core/SkPaint.h"
15 #include "include/core/SkPath.h"
16 #include "include/core/SkRect.h"
17 #include "include/core/SkRefCnt.h"
18 #include "include/core/SkScalar.h"
19 #include "include/core/SkString.h"
20 #include "include/core/SkSurfaceProps.h"
21 #include "include/core/SkTypeface.h"
22 #include "include/core/SkTypes.h"
23 #include "include/private/base/SkMacros.h"
24 #include "include/private/base/SkPoint_impl.h"
25 #include "include/private/base/SkTemplates.h"
26 #include "include/private/base/SkTo.h"
27 #include "src/core/SkGlyph.h"
28 #include "src/core/SkMask.h"
29 #include "src/core/SkMaskGamma.h"
30
31 #include <cstddef>
32 #include <cstdint>
33 #include <memory>
34 #include <optional>
35
36 class SkArenaAlloc;
37 class SkAutoDescriptor;
38 class SkDescriptor;
39 class SkDrawable;
40 class SkFont;
41 class SkMaskFilter;
42 class SkPathEffect;
43 enum class SkFontHinting;
44 struct SkFontMetrics;
45
46 //The following typedef hides from the rest of the implementation the number of
47 //most significant bits to consider when creating mask gamma tables. Two bits
48 //per channel was chosen as a balance between fidelity (more bits) and cache
49 //sizes (fewer bits). Three bits per channel was chosen when #303942; (used by
50 //the Chrome UI) turned out too green.
51 typedef SkTMaskGamma<3, 3, 3> SkMaskGamma;
52
53 enum class SkScalerContextFlags : uint32_t {
54 kNone = 0,
55 kFakeGamma = 1 << 0,
56 kBoostContrast = 1 << 1,
57 kFakeGammaAndBoostContrast = kFakeGamma | kBoostContrast,
58 };
59 SK_MAKE_BITFIELD_OPS(SkScalerContextFlags)
60
61 /*
62 * To allow this to be forward-declared, it must be its own typename, rather
63 * than a nested struct inside SkScalerContext (where it started).
64 *
65 * SkScalerContextRec must be dense, and all bytes must be set to a know quantity because this
66 * structure is used to calculate a checksum.
67 */
68 SK_BEGIN_REQUIRE_DENSE
69 struct SkScalerContextRec {
70 SkTypefaceID fTypefaceID;
71 SkScalar fTextSize, fPreScaleX, fPreSkewX;
72 SkScalar fPost2x2[2][2];
73 SkScalar fFrameWidth, fMiterLimit;
74
75 // This will be set if to the paint's foreground color if
76 // kNeedsForegroundColor is set, which will usually be the case for COLRv0 and
77 // COLRv1 fonts.
78 uint32_t fForegroundColor{SK_ColorBLACK};
79
80 private:
81 //These describe the parameters to create (uniquely identify) the pre-blend.
82 uint32_t fLumBits;
83 uint8_t fDeviceGamma; //2.6, (0.0, 4.0) gamma, 0.0 for sRGB
84 const uint8_t fReservedAlign2{0};
85 uint8_t fContrast; //0.8+1, [0.0, 1.0] artificial contrast
86 const uint8_t fReservedAlign{0};
87
88 static constexpr SkScalar ExternalGammaFromInternal(uint8_t g) {
89 return SkIntToScalar(g) / (1 << 6);
90 }
91 static constexpr uint8_t InternalGammaFromExternal(SkScalar g) {
92 // C++23 use constexpr std::floor
93 return static_cast<uint8_t>(g * (1 << 6));
94 }
95 static constexpr SkScalar ExternalContrastFromInternal(uint8_t c) {
96 return SkIntToScalar(c) / ((1 << 8) - 1);
97 }
98 static constexpr uint8_t InternalContrastFromExternal(SkScalar c) {
99 // C++23 use constexpr std::round
100 return static_cast<uint8_t>((c * ((1 << 8) - 1)) + 0.5f);
101 }
102 public:
103 void setDeviceGamma(SkScalar g) {
104 sk_ignore_unused_variable(fReservedAlign2);
105 SkASSERT(SkSurfaceProps::kMinGammaInclusive <= g &&
106 g < SkIntToScalar(SkSurfaceProps::kMaxGammaExclusive));
107 fDeviceGamma = InternalGammaFromExternal(g);
108 }
109
110 void setContrast(SkScalar c) {
111 sk_ignore_unused_variable(fReservedAlign);
112 SkASSERT(SkSurfaceProps::kMinContrastInclusive <= c &&
113 c <= SkIntToScalar(SkSurfaceProps::kMaxContrastInclusive));
114 fContrast = InternalContrastFromExternal(c);
115 }
116
117 static const SkMaskGamma& CachedMaskGamma(uint8_t contrast, uint8_t gamma);
118 const SkMaskGamma& cachedMaskGamma() const {
119 return CachedMaskGamma(fContrast, fDeviceGamma);
120 }
121
122 /**
123 * Causes the luminance color to be ignored, and the paint and device
124 * gamma to be effectively 1.0
125 */
126 void ignoreGamma() {
127 setLuminanceColor(SK_ColorTRANSPARENT);
128 setDeviceGamma(SK_Scalar1);
129 }
130
131 /**
132 * Causes the luminance color and contrast to be ignored, and the
133 * paint and device gamma to be effectively 1.0.
134 */
135 void ignorePreBlend() {
136 ignoreGamma();
137 setContrast(0);
138 }
139
140 /** If the kEmbolden_Flag is set, drop it and use stroking instead. */
141 void useStrokeForFakeBold();
142
143 SkMask::Format fMaskFormat;
144
145 private:
146 uint8_t fStrokeJoin : 4;
147 uint8_t fStrokeCap : 4;
148
149 public:
150 uint16_t fFlags;
151
152 // Warning: when adding members note that the size of this structure
153 // must be a multiple of 4. SkDescriptor requires that its arguments be
154 // multiples of four and this structure is put in an SkDescriptor in
155 // SkPaint::MakeRecAndEffects.
156
157 SkString dump() const {
158 SkString msg;
159 msg.appendf(" Rec\n");
160 msg.appendf(" textsize %a prescale %a preskew %a post [%a %a %a %a]\n",
161 fTextSize, fPreScaleX, fPreSkewX, fPost2x2[0][0],
162 fPost2x2[0][1], fPost2x2[1][0], fPost2x2[1][1]);
163 msg.appendf(" frame %g miter %g format %d join %d cap %d flags %#hx\n",
164 fFrameWidth, fMiterLimit, fMaskFormat, fStrokeJoin, fStrokeCap, fFlags);
165 msg.appendf(" lum bits %x, device gamma %d, contrast %d\n", fLumBits,
166 fDeviceGamma, fContrast);
167 msg.appendf(" foreground color %x\n", fForegroundColor);
168 return msg;
169 }
170
171 SkMatrix getMatrixFrom2x2() const;
172 SkMatrix getLocalMatrix() const;
173 SkMatrix getSingleMatrix() const;
174
175 /** The kind of scale which will be applied by the underlying port (pre-matrix). */
176 enum class PreMatrixScale {
177 kFull, // The underlying port can apply both x and y scale.
178 kVertical, // The underlying port can only apply a y scale.
179 kVerticalInteger // The underlying port can only apply an integer y scale.
180 };
181 /**
182 * Compute useful matrices for use with sizing in underlying libraries.
183 *
184 * There are two kinds of text size, a 'requested/logical size' which is like asking for size
185 * '12' and a 'real' size which is the size after the matrix is applied. The matrices produced
186 * by this method are based on the 'real' size. This method effectively finds the total device
187 * matrix and decomposes it in various ways.
188 *
189 * The most useful decomposition is into 'scale' and 'remaining'. The 'scale' is applied first
190 * and then the 'remaining' to fully apply the total matrix. This decomposition is useful when
191 * the text size ('scale') may have meaning apart from the total matrix. This is true when
192 * hinting, and sometimes true for other properties as well.
193 *
194 * The second (optional) decomposition is of 'remaining' into a non-rotational part
195 * 'remainingWithoutRotation' and a rotational part 'remainingRotation'. The 'scale' is applied
196 * first, then 'remainingWithoutRotation', then 'remainingRotation' to fully apply the total
197 * matrix. This decomposition is helpful when only horizontal metrics can be trusted, so the
198 * 'scale' and 'remainingWithoutRotation' will be handled by the underlying library, but
199 * the final rotation 'remainingRotation' will be handled manually.
200 *
201 * The 'total' matrix is also (optionally) available. This is useful in cases where the
202 * underlying library will not be used, often when working directly with font data.
203 *
204 * The parameters 'scale' and 'remaining' are required, the other pointers may be nullptr.
205 *
206 * @param preMatrixScale the kind of scale to extract from the total matrix.
207 * @param scale the scale extracted from the total matrix (both values positive).
208 * @param remaining apply after scale to apply the total matrix.
209 * @param remainingWithoutRotation apply after scale to apply the total matrix sans rotation.
210 * @param remainingRotation apply after remainingWithoutRotation to apply the total matrix.
211 * @param total the total matrix.
212 * @return false if the matrix was singular. The output will be valid but not invertible.
213 */
214 bool computeMatrices(PreMatrixScale preMatrixScale,
215 SkVector* scale, SkMatrix* remaining,
216 SkMatrix* remainingWithoutRotation = nullptr,
217 SkMatrix* remainingRotation = nullptr,
218 SkMatrix* total = nullptr) const;
219
220 SkAxisAlignment computeAxisAlignmentForHText() const;
221
222 inline SkFontHinting getHinting() const;
223 inline void setHinting(SkFontHinting);
224
225 SkMask::Format getFormat() const {
226 return fMaskFormat;
227 }
228
229 SkColor getLuminanceColor() const {
230 return fLumBits;
231 }
232
233 // setLuminanceColor forces the alpha to be 0xFF because the blitter that draws the glyph
234 // will apply the alpha from the paint. Don't apply the alpha twice.
235 void setLuminanceColor(SkColor c);
236
237 private:
238 // TODO: remove
239 friend class SkScalerContext;
240 };
241 SK_END_REQUIRE_DENSE
242
243 // TODO: rename SkScalerContextEffects -> SkStrikeEffects
244 struct SkScalerContextEffects {
245 SkScalerContextEffects() : fPathEffect(nullptr), fMaskFilter(nullptr) {}
246 SkScalerContextEffects(SkPathEffect* pe, SkMaskFilter* mf)
247 : fPathEffect(pe), fMaskFilter(mf) {}
248 explicit SkScalerContextEffects(const SkPaint& paint)
249 : fPathEffect(paint.getPathEffect())
250 , fMaskFilter(paint.getMaskFilter()) {}
251
252 SkPathEffect* fPathEffect;
253 SkMaskFilter* fMaskFilter;
254 };
255
256 class SkScalerContext {
257 public:
258 enum Flags {
259 kFrameAndFill_Flag = 0x0001,
260 kUnused = 0x0002,
261 kEmbeddedBitmapText_Flag = 0x0004,
262 kEmbolden_Flag = 0x0008,
263 kSubpixelPositioning_Flag = 0x0010,
264 kForceAutohinting_Flag = 0x0020, // Use auto instead of bytcode hinting if hinting.
265
266 // together, these two flags resulting in a two bit value which matches
267 // up with the SkPaint::Hinting enum.
268 kHinting_Shift = 7, // to shift into the other flags above
269 kHintingBit1_Flag = 0x0080,
270 kHintingBit2_Flag = 0x0100,
271
272 // Pixel geometry information.
273 // only meaningful if fMaskFormat is kLCD16
274 kLCD_Vertical_Flag = 0x0200, // else Horizontal
275 kLCD_BGROrder_Flag = 0x0400, // else RGB order
276
277 // Generate A8 from LCD source (for GDI and CoreGraphics).
278 // only meaningful if fMaskFormat is kA8
279 kGenA8FromLCD_Flag = 0x0800, // could be 0x200 (bit meaning dependent on fMaskFormat)
280 kLinearMetrics_Flag = 0x1000,
281 kBaselineSnap_Flag = 0x2000,
282
283 kNeedsForegroundColor_Flag = 0x4000,
284 };
285
286 // computed values
287 enum {
288 kHinting_Mask = kHintingBit1_Flag | kHintingBit2_Flag,
289 };
290
291 SkScalerContext(SkTypeface&, const SkScalerContextEffects&, const SkDescriptor*);
292 virtual ~SkScalerContext();
293
294 SkTypeface* getTypeface() const { return &fTypeface; }
295
296 SkMask::Format getMaskFormat() const {
297 return fRec.fMaskFormat;
298 }
299
300 bool isSubpixel() const {
301 return SkToBool(fRec.fFlags & kSubpixelPositioning_Flag);
302 }
303
304 bool isLinearMetrics() const {
305 return SkToBool(fRec.fFlags & kLinearMetrics_Flag);
306 }
307
308 // DEPRECATED
309 bool isVertical() const { return false; }
310
311 SkGlyph makeGlyph(SkPackedGlyphID, SkArenaAlloc*);
312 void getImage(const SkGlyph&);
313 void getPath(SkGlyph&, SkArenaAlloc*);
314 sk_sp<SkDrawable> getDrawable(SkGlyph&);
315 void getFontMetrics(SkFontMetrics*);
316
317 /** Return the size in bytes of the associated gamma lookup table
318 */
319 static size_t GetGammaLUTSize(SkScalar contrast, SkScalar deviceGamma,
320 int* width, int* height);
321
322 /** Get the associated gamma lookup table. The 'data' pointer must point to pre-allocated
323 * memory, with size in bytes greater than or equal to the return value of getGammaLUTSize().
324 *
325 * If the lookup table hasn't been initialized (e.g., it's linear), this will return false.
326 */
327 static bool GetGammaLUTData(SkScalar contrast, SkScalar deviceGamma, uint8_t* data);
328
329 static void MakeRecAndEffects(const SkFont& font, const SkPaint& paint,
330 const SkSurfaceProps& surfaceProps,
331 SkScalerContextFlags scalerContextFlags,
332 const SkMatrix& deviceMatrix,
333 SkScalerContextRec* rec,
334 SkScalerContextEffects* effects);
335
336 // If we are creating rec and effects from a font only, then there is no device around either.
337 static void MakeRecAndEffectsFromFont(const SkFont& font,
338 SkScalerContextRec* rec,
339 SkScalerContextEffects* effects) {
340 SkPaint paint;
341 return MakeRecAndEffects(
342 font, paint, SkSurfaceProps(),
343 SkScalerContextFlags::kNone, SkMatrix::I(), rec, effects);
344 }
345
346 static std::unique_ptr<SkScalerContext> MakeEmpty(
347 SkTypeface& typeface, const SkScalerContextEffects& effects,
348 const SkDescriptor* desc);
349
350 static SkDescriptor* AutoDescriptorGivenRecAndEffects(
351 const SkScalerContextRec& rec,
352 const SkScalerContextEffects& effects,
353 SkAutoDescriptor* ad);
354
355 static std::unique_ptr<SkDescriptor> DescriptorGivenRecAndEffects(
356 const SkScalerContextRec& rec,
357 const SkScalerContextEffects& effects);
358
359 static void DescriptorBufferGiveRec(const SkScalerContextRec& rec, void* buffer);
360 static bool CheckBufferSizeForRec(const SkScalerContextRec& rec,
361 const SkScalerContextEffects& effects,
362 size_t size);
363
364 static SkMaskGamma::PreBlend GetMaskPreBlend(const SkScalerContextRec& rec);
365
366 const SkScalerContextRec& getRec() const { return fRec; }
367
368 SkScalerContextEffects getEffects() const {
369 return { fPathEffect.get(), fMaskFilter.get() };
370 }
371
372 /**
373 * Return the axis (if any) that the baseline for horizontal text should land on.
374 * As an example, the identity matrix will return SkAxisAlignment::kX.
375 */
376 SkAxisAlignment computeAxisAlignmentForHText() const;
377
378 static SkDescriptor* CreateDescriptorAndEffectsUsingPaint(
379 const SkFont&, const SkPaint&, const SkSurfaceProps&,
380 SkScalerContextFlags scalerContextFlags,
381 const SkMatrix& deviceMatrix, SkAutoDescriptor* ad,
382 SkScalerContextEffects* effects);
383
384 protected:
385 const SkScalerContextRec fRec;
386
387 struct GeneratedPath {
388 SkPath path;
389 bool modified;
390 };
391 struct GlyphMetrics {
392 SkVector advance;
393 SkRect bounds;
394 SkMask::Format maskFormat;
395 uint16_t extraBits;
396 bool neverRequestPath;
397 bool computeFromPath;
398 std::optional<GeneratedPath> generatedPath;
399 GlyphMetrics(SkMask::Format format)
400 : advance{0, 0}
401 , bounds{0, 0, 0, 0}
402 , maskFormat(format)
403 , extraBits(0)
404 , neverRequestPath(false)
405 , computeFromPath(false)
406 , generatedPath{std::nullopt}
407 {}
408 };
409
410 virtual GlyphMetrics generateMetrics(const SkGlyph&, SkArenaAlloc*) = 0;
411
412 static void GenerateMetricsFromPath(
413 SkGlyph* glyph, const SkPath& path, SkMask::Format format,
414 bool verticalLCD, bool a8FromLCD, bool hairline);
415
416 static void SaturateGlyphBounds(SkGlyph* glyph, SkRect&&);
417 static void SaturateGlyphBounds(SkGlyph* glyph, SkIRect const &);
418
419 /** Generates the contents of glyph.fImage.
420 * When called, glyph.fImage will be pointing to a pre-allocated,
421 * uninitialized region of memory of size glyph.imageSize().
422 * This method may not change glyph.fMaskFormat.
423 *
424 * Because glyph.imageSize() will determine the size of fImage,
425 * generateMetrics will be called before generateImage.
426 */
427 virtual void generateImage(const SkGlyph& glyph, void* imageBuffer) = 0;
428 static void GenerateImageFromPath(
429 SkMaskBuilder& dst, const SkPath& path, const SkMaskGamma::PreBlend& maskPreBlend,
430 bool doBGR, bool verticalLCD, bool a8FromLCD, bool hairline);
431 void generateImageFromPath(const SkGlyph& glyph, void* imageBuffer);
432
433 /** Return the glyph's outline, or if the glyph cannot be converted to one, return {}.
434 * Does not apply subpixel positioning to the path.
435 */
436 [[nodiscard]] virtual std::optional<GeneratedPath> generatePath(const SkGlyph&) = 0;
437
438 /** Returns the drawable for the glyph (if any).
439 *
440 * The generated drawable will be lifetime scoped to the lifetime of this scaler context.
441 * This means the drawable may refer to the scaler context and associated font data.
442 *
443 * The drawable does not need to be flattenable (e.g. implement getFactory and getTypeName).
444 * Any necessary serialization will be done with makePictureSnapshot.
445 */
446 virtual sk_sp<SkDrawable> generateDrawable(const SkGlyph&); // TODO: = 0
447
448 /** Retrieves font metrics. */
449 virtual void generateFontMetrics(SkFontMetrics*) = 0;
450
451 private:
452 friend class PathText; // For debug purposes
453 friend class PathTextBench; // For debug purposes
454 friend class RandomScalerContext; // For debug purposes
455 friend class SkScalerContext_proxy;
456
457 static SkScalerContextRec PreprocessRec(const SkTypeface&,
458 const SkScalerContextEffects&,
459 const SkDescriptor&);
460
461 // In order for a SkScalerContext to be in use this typeface must exist.
462 // The SkScalerContext does not keep a reference to this typeface, so this reference may be
463 // a dangling reference when the SkScalerContext is destroyed.
464 SkTypeface& fTypeface;
465
466 // optional objects, which may be null
467 sk_sp<SkPathEffect> fPathEffect;
468 sk_sp<SkMaskFilter> fMaskFilter;
469
470 // if this is set, we draw the image from a path, rather than
471 // calling generateImage.
472 const bool fGenerateImageFromPath;
473
474 void internalGetPath(SkGlyph&, SkArenaAlloc*, std::optional<GeneratedPath>&&);
475 SkGlyph internalMakeGlyph(SkPackedGlyphID, SkMask::Format, SkArenaAlloc*);
476
477 protected:
478 // SkMaskGamma::PreBlend converts linear masks to gamma correcting masks.
479 // Visible to subclasses so that generateImage can apply the pre-blend directly.
480 const SkMaskGamma::PreBlend fPreBlend;
481 };
482
483 #define kRec_SkDescriptorTag SkSetFourByteTag('s', 'r', 'e', 'c')
484 #define kEffects_SkDescriptorTag SkSetFourByteTag('e', 'f', 'c', 't')
485
486 ///////////////////////////////////////////////////////////////////////////////
487
488 SkFontHinting SkScalerContextRec::getHinting() const {
489 unsigned hint = (fFlags & SkScalerContext::kHinting_Mask) >>
490 SkScalerContext::kHinting_Shift;
491 return static_cast<SkFontHinting>(hint);
492 }
493
494 void SkScalerContextRec::setHinting(SkFontHinting hinting) {
495 fFlags = (fFlags & ~SkScalerContext::kHinting_Mask) |
496 (static_cast<unsigned>(hinting) << SkScalerContext::kHinting_Shift);
497 }
498
499
500 #endif