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 <memory>
12
13 #include "include/core/SkFont.h"
14 #include "include/core/SkFontTypes.h"
15 #include "include/core/SkMaskFilter.h"
16 #include "include/core/SkMatrix.h"
17 #include "include/core/SkPaint.h"
18 #include "include/core/SkTypeface.h"
19 #include "include/private/SkMacros.h"
20 #include "src/core/SkGlyph.h"
21 #include "src/core/SkMask.h"
22 #include "src/core/SkMaskGamma.h"
23 #include "src/core/SkStrikeForGPU.h"
24 #include "src/core/SkSurfacePriv.h"
25 #include "src/core/SkWriteBuffer.h"
26
27 class SkAutoDescriptor;
28 class SkDescriptor;
29 class SkMaskFilter;
30 class SkPathEffect;
31 class SkScalerContext;
32 class SkScalerContext_DW;
33
34 enum SkScalerContextFlags : uint32_t {
35 kNone = 0,
36 kFakeGamma = 1 << 0,
37 kBoostContrast = 1 << 1,
38 kFakeGammaAndBoostContrast = kFakeGamma | kBoostContrast,
39 };
40
41 enum SkAxisAlignment : uint32_t {
42 kNone_SkAxisAlignment,
43 kX_SkAxisAlignment,
44 kY_SkAxisAlignment
45 };
46
47 /*
48 * To allow this to be forward-declared, it must be its own typename, rather
49 * than a nested struct inside SkScalerContext (where it started).
50 *
51 * SkScalerContextRec must be dense, and all bytes must be set to a know quantity because this
52 * structure is used to calculate a checksum.
53 */
54 SK_BEGIN_REQUIRE_DENSE
55 struct SkScalerContextRec {
56 uint32_t fFontID;
57 SkScalar fTextSize, fPreScaleX, fPreSkewX;
58 SkScalar fPost2x2[2][2];
59 SkScalar fFrameWidth, fMiterLimit;
60
61 private:
62 //These describe the parameters to create (uniquely identify) the pre-blend.
63 uint32_t fLumBits;
64 uint8_t fDeviceGamma; //2.6, (0.0, 4.0) gamma, 0.0 for sRGB
65 uint8_t fPaintGamma; //2.6, (0.0, 4.0) gamma, 0.0 for sRGB
66 uint8_t fContrast; //0.8+1, [0.0, 1.0] artificial contrast
67 const uint8_t fReservedAlign{0};
68
69 public:
70
getDeviceGammaSkScalerContextRec71 SkScalar getDeviceGamma() const {
72 return SkIntToScalar(fDeviceGamma) / (1 << 6);
73 }
setDeviceGammaSkScalerContextRec74 void setDeviceGamma(SkScalar dg) {
75 SkASSERT(0 <= dg && dg < SkIntToScalar(4));
76 fDeviceGamma = SkScalarFloorToInt(dg * (1 << 6));
77 }
78
getPaintGammaSkScalerContextRec79 SkScalar getPaintGamma() const {
80 return SkIntToScalar(fPaintGamma) / (1 << 6);
81 }
setPaintGammaSkScalerContextRec82 void setPaintGamma(SkScalar pg) {
83 SkASSERT(0 <= pg && pg < SkIntToScalar(4));
84 fPaintGamma = SkScalarFloorToInt(pg * (1 << 6));
85 }
86
getContrastSkScalerContextRec87 SkScalar getContrast() const {
88 sk_ignore_unused_variable(fReservedAlign);
89 return SkIntToScalar(fContrast) / ((1 << 8) - 1);
90 }
setContrastSkScalerContextRec91 void setContrast(SkScalar c) {
92 SkASSERT(0 <= c && c <= SK_Scalar1);
93 fContrast = SkScalarRoundToInt(c * ((1 << 8) - 1));
94 }
95
96 /**
97 * Causes the luminance color to be ignored, and the paint and device
98 * gamma to be effectively 1.0
99 */
ignoreGammaSkScalerContextRec100 void ignoreGamma() {
101 setLuminanceColor(SK_ColorTRANSPARENT);
102 setPaintGamma(SK_Scalar1);
103 setDeviceGamma(SK_Scalar1);
104 }
105
106 /**
107 * Causes the luminance color and contrast to be ignored, and the
108 * paint and device gamma to be effectively 1.0.
109 */
ignorePreBlendSkScalerContextRec110 void ignorePreBlend() {
111 ignoreGamma();
112 setContrast(0);
113 }
114
115 SkMask::Format fMaskFormat;
116
117 private:
118 uint8_t fStrokeJoin : 4;
119 uint8_t fStrokeCap : 4;
120
121 public:
122 uint16_t fFlags;
123
124 // Warning: when adding members note that the size of this structure
125 // must be a multiple of 4. SkDescriptor requires that its arguments be
126 // multiples of four and this structure is put in an SkDescriptor in
127 // SkPaint::MakeRecAndEffects.
128
dumpSkScalerContextRec129 SkString dump() const {
130 SkString msg;
131 msg.appendf(" Rec\n");
132 msg.appendf(" textsize %a prescale %a preskew %a post [%a %a %a %a]\n",
133 fTextSize, fPreScaleX, fPreSkewX, fPost2x2[0][0],
134 fPost2x2[0][1], fPost2x2[1][0], fPost2x2[1][1]);
135 msg.appendf(" frame %g miter %g format %d join %d cap %d flags %#hx\n",
136 fFrameWidth, fMiterLimit, fMaskFormat, fStrokeJoin, fStrokeCap, fFlags);
137 msg.appendf(" lum bits %x, device gamma %d, paint gamma %d contrast %d\n", fLumBits,
138 fDeviceGamma, fPaintGamma, fContrast);
139 return msg;
140 }
141
142 void getMatrixFrom2x2(SkMatrix*) const;
143 void getLocalMatrix(SkMatrix*) const;
144 void getSingleMatrix(SkMatrix*) const;
145
146 /** The kind of scale which will be applied by the underlying port (pre-matrix). */
147 enum PreMatrixScale {
148 kFull_PreMatrixScale, // The underlying port can apply both x and y scale.
149 kVertical_PreMatrixScale, // The underlying port can only apply a y scale.
150 kVerticalInteger_PreMatrixScale // The underlying port can only apply an integer y scale.
151 };
152 /**
153 * Compute useful matrices for use with sizing in underlying libraries.
154 *
155 * There are two kinds of text size, a 'requested/logical size' which is like asking for size
156 * '12' and a 'real' size which is the size after the matrix is applied. The matrices produced
157 * by this method are based on the 'real' size. This method effectively finds the total device
158 * matrix and decomposes it in various ways.
159 *
160 * The most useful decomposition is into 'scale' and 'remaining'. The 'scale' is applied first
161 * and then the 'remaining' to fully apply the total matrix. This decomposition is useful when
162 * the text size ('scale') may have meaning apart from the total matrix. This is true when
163 * hinting, and sometimes true for other properties as well.
164 *
165 * The second (optional) decomposition is of 'remaining' into a non-rotational part
166 * 'remainingWithoutRotation' and a rotational part 'remainingRotation'. The 'scale' is applied
167 * first, then 'remainingWithoutRotation', then 'remainingRotation' to fully apply the total
168 * matrix. This decomposition is helpful when only horizontal metrics can be trusted, so the
169 * 'scale' and 'remainingWithoutRotation' will be handled by the underlying library, but
170 * the final rotation 'remainingRotation' will be handled manually.
171 *
172 * The 'total' matrix is also (optionally) available. This is useful in cases where the
173 * underlying library will not be used, often when working directly with font data.
174 *
175 * The parameters 'scale' and 'remaining' are required, the other pointers may be nullptr.
176 *
177 * @param preMatrixScale the kind of scale to extract from the total matrix.
178 * @param scale the scale extracted from the total matrix (both values positive).
179 * @param remaining apply after scale to apply the total matrix.
180 * @param remainingWithoutRotation apply after scale to apply the total matrix sans rotation.
181 * @param remainingRotation apply after remainingWithoutRotation to apply the total matrix.
182 * @param total the total matrix.
183 * @return false if the matrix was singular. The output will be valid but not invertible.
184 */
185 bool computeMatrices(PreMatrixScale preMatrixScale,
186 SkVector* scale, SkMatrix* remaining,
187 SkMatrix* remainingWithoutRotation = nullptr,
188 SkMatrix* remainingRotation = nullptr,
189 SkMatrix* total = nullptr);
190
191 SkAxisAlignment computeAxisAlignmentForHText() const;
192
193 inline SkFontHinting getHinting() const;
194 inline void setHinting(SkFontHinting);
195
getFormatSkScalerContextRec196 SkMask::Format getFormat() const {
197 return fMaskFormat;
198 }
199
getLuminanceColorSkScalerContextRec200 SkColor getLuminanceColor() const {
201 return fLumBits;
202 }
203
204 // setLuminanceColor forces the alpha to be 0xFF because the blitter that draws the glyph
205 // will apply the alpha from the paint. Don't apply the alpha twice.
206 void setLuminanceColor(SkColor c);
207
208 private:
209 // TODO: remove
210 friend class SkScalerContext;
211 };
212 SK_END_REQUIRE_DENSE
213
214 // TODO: rename SkScalerContextEffects -> SkStrikeEffects
215 struct SkScalerContextEffects {
SkScalerContextEffectsSkScalerContextEffects216 SkScalerContextEffects() : fPathEffect(nullptr), fMaskFilter(nullptr) {}
SkScalerContextEffectsSkScalerContextEffects217 SkScalerContextEffects(SkPathEffect* pe, SkMaskFilter* mf)
218 : fPathEffect(pe), fMaskFilter(mf) {}
SkScalerContextEffectsSkScalerContextEffects219 explicit SkScalerContextEffects(const SkPaint& paint)
220 : fPathEffect(paint.getPathEffect())
221 , fMaskFilter(paint.getMaskFilter()) {}
222
223 SkPathEffect* fPathEffect;
224 SkMaskFilter* fMaskFilter;
225 };
226
227 //The following typedef hides from the rest of the implementation the number of
228 //most significant bits to consider when creating mask gamma tables. Two bits
229 //per channel was chosen as a balance between fidelity (more bits) and cache
230 //sizes (fewer bits). Three bits per channel was chosen when #303942; (used by
231 //the Chrome UI) turned out too green.
232 typedef SkTMaskGamma<3, 3, 3> SkMaskGamma;
233
234 class SkScalerContext {
235 public:
236 enum Flags {
237 kFrameAndFill_Flag = 0x0001,
238 kUnused = 0x0002,
239 kEmbeddedBitmapText_Flag = 0x0004,
240 kEmbolden_Flag = 0x0008,
241 kSubpixelPositioning_Flag = 0x0010,
242 kForceAutohinting_Flag = 0x0020, // Use auto instead of bytcode hinting if hinting.
243
244 // together, these two flags resulting in a two bit value which matches
245 // up with the SkPaint::Hinting enum.
246 kHinting_Shift = 7, // to shift into the other flags above
247 kHintingBit1_Flag = 0x0080,
248 kHintingBit2_Flag = 0x0100,
249
250 // Pixel geometry information.
251 // only meaningful if fMaskFormat is kLCD16
252 kLCD_Vertical_Flag = 0x0200, // else Horizontal
253 kLCD_BGROrder_Flag = 0x0400, // else RGB order
254
255 // Generate A8 from LCD source (for GDI and CoreGraphics).
256 // only meaningful if fMaskFormat is kA8
257 kGenA8FromLCD_Flag = 0x0800, // could be 0x200 (bit meaning dependent on fMaskFormat)
258 kLinearMetrics_Flag = 0x1000,
259 kBaselineSnap_Flag = 0x2000,
260 };
261
262 // computed values
263 enum {
264 kHinting_Mask = kHintingBit1_Flag | kHintingBit2_Flag,
265 };
266
267 SkScalerContext(sk_sp<SkTypeface>, const SkScalerContextEffects&, const SkDescriptor*);
268 virtual ~SkScalerContext();
269
getTypeface()270 SkTypeface* getTypeface() const { return fTypeface.get(); }
271
getMaskFormat()272 SkMask::Format getMaskFormat() const {
273 return fRec.fMaskFormat;
274 }
275
isSubpixel()276 bool isSubpixel() const {
277 return SkToBool(fRec.fFlags & kSubpixelPositioning_Flag);
278 }
279
isLinearMetrics()280 bool isLinearMetrics() const {
281 return SkToBool(fRec.fFlags & kLinearMetrics_Flag);
282 }
283
284 // DEPRECATED
isVertical()285 bool isVertical() const { return false; }
286
287 SkGlyph makeGlyph(SkPackedGlyphID);
288 void getImage(const SkGlyph&);
289 bool SK_WARN_UNUSED_RESULT getPath(SkPackedGlyphID, SkPath*);
290 void getFontMetrics(SkFontMetrics*);
291
292 /** Return the size in bytes of the associated gamma lookup table
293 */
294 static size_t GetGammaLUTSize(SkScalar contrast, SkScalar paintGamma, SkScalar deviceGamma,
295 int* width, int* height);
296
297 /** Get the associated gamma lookup table. The 'data' pointer must point to pre-allocated
298 * memory, with size in bytes greater than or equal to the return value of getGammaLUTSize().
299 *
300 * If the lookup table hasn't been initialized (e.g., it's linear), this will return false.
301 */
302 static bool GetGammaLUTData(SkScalar contrast, SkScalar paintGamma, SkScalar deviceGamma,
303 uint8_t* data);
304
305 static void MakeRecAndEffects(const SkFont& font, const SkPaint& paint,
306 const SkSurfaceProps& surfaceProps,
307 SkScalerContextFlags scalerContextFlags,
308 const SkMatrix& deviceMatrix,
309 SkScalerContextRec* rec,
310 SkScalerContextEffects* effects);
311
312 // If we are creating rec and effects from a font only, then there is no device around either.
MakeRecAndEffectsFromFont(const SkFont & font,SkScalerContextRec * rec,SkScalerContextEffects * effects)313 static void MakeRecAndEffectsFromFont(const SkFont& font,
314 SkScalerContextRec* rec,
315 SkScalerContextEffects* effects) {
316 SkPaint paint;
317 return MakeRecAndEffects(
318 font, paint, SkSurfaceProps(),
319 SkScalerContextFlags::kNone, SkMatrix::I(), rec, effects);
320 }
321
322 static std::unique_ptr<SkScalerContext> MakeEmpty(
323 sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
324 const SkDescriptor* desc);
325
326 static SkDescriptor* AutoDescriptorGivenRecAndEffects(
327 const SkScalerContextRec& rec,
328 const SkScalerContextEffects& effects,
329 SkAutoDescriptor* ad);
330
331 static std::unique_ptr<SkDescriptor> DescriptorGivenRecAndEffects(
332 const SkScalerContextRec& rec,
333 const SkScalerContextEffects& effects);
334
335 static void DescriptorBufferGiveRec(const SkScalerContextRec& rec, void* buffer);
336 static bool CheckBufferSizeForRec(const SkScalerContextRec& rec,
337 const SkScalerContextEffects& effects,
338 size_t size);
339
340 static SkMaskGamma::PreBlend GetMaskPreBlend(const SkScalerContextRec& rec);
341
getRec()342 const SkScalerContextRec& getRec() const { return fRec; }
343
getEffects()344 SkScalerContextEffects getEffects() const {
345 return { fPathEffect.get(), fMaskFilter.get() };
346 }
347
348 /**
349 * Return the axis (if any) that the baseline for horizontal text should land on.
350 * As an example, the identity matrix will return kX_SkAxisAlignment
351 */
352 SkAxisAlignment computeAxisAlignmentForHText() const;
353
354 static SkDescriptor* CreateDescriptorAndEffectsUsingPaint(
355 const SkFont&, const SkPaint&, const SkSurfaceProps&,
356 SkScalerContextFlags scalerContextFlags,
357 const SkMatrix& deviceMatrix, SkAutoDescriptor* ad,
358 SkScalerContextEffects* effects);
359
360 protected:
361 SkScalerContextRec fRec;
362
363 /** Generates the contents of glyph.fAdvanceX and glyph.fAdvanceY if it can do so quickly.
364 * Returns true if it could, false otherwise.
365 */
366 virtual bool generateAdvance(SkGlyph* glyph) = 0;
367
368 /** Generates the contents of glyph.fWidth, fHeight, fTop, fLeft,
369 * as well as fAdvanceX and fAdvanceY if not already set.
370 *
371 * TODO: fMaskFormat is set by internalMakeGlyph later; cannot be set here.
372 */
373 virtual void generateMetrics(SkGlyph* glyph) = 0;
374
375 /** Generates the contents of glyph.fImage.
376 * When called, glyph.fImage will be pointing to a pre-allocated,
377 * uninitialized region of memory of size glyph.imageSize().
378 * This method may change glyph.fMaskFormat if the new image size is
379 * less than or equal to the old image size.
380 *
381 * Because glyph.imageSize() will determine the size of fImage,
382 * generateMetrics will be called before generateImage.
383 */
384 virtual void generateImage(const SkGlyph& glyph) = 0;
385
386 /** Sets the passed path to the glyph outline.
387 * If this cannot be done the path is set to empty;
388 * @return false if this glyph does not have any path.
389 */
390 virtual bool SK_WARN_UNUSED_RESULT generatePath(SkGlyphID glyphId, SkPath* path) = 0;
391
392 /** Retrieves font metrics. */
393 virtual void generateFontMetrics(SkFontMetrics*) = 0;
394
forceGenerateImageFromPath()395 void forceGenerateImageFromPath() { fGenerateImageFromPath = true; }
forceOffGenerateImageFromPath()396 void forceOffGenerateImageFromPath() { fGenerateImageFromPath = false; }
397
398 private:
399 friend class RandomScalerContext; // For debug purposes
400
401 static SkScalerContextRec PreprocessRec(const SkTypeface& typeface,
402 const SkScalerContextEffects& effects,
403 const SkDescriptor& desc);
404
405 // never null
406 sk_sp<SkTypeface> fTypeface;
407
408 // optional objects, which may be null
409 sk_sp<SkPathEffect> fPathEffect;
410 sk_sp<SkMaskFilter> fMaskFilter;
411
412 // if this is set, we draw the image from a path, rather than
413 // calling generateImage.
414 bool fGenerateImageFromPath;
415
416 /** Returns false if the glyph has no path at all. */
417 bool internalGetPath(SkPackedGlyphID id, SkPath* devPath);
418 SkGlyph internalMakeGlyph(SkPackedGlyphID packedID, SkMask::Format format);
419
420 // SkMaskGamma::PreBlend converts linear masks to gamma correcting masks.
421 protected:
422 // Visible to subclasses so that generateImage can apply the pre-blend directly.
423 const SkMaskGamma::PreBlend fPreBlend;
424 };
425
426 #define kRec_SkDescriptorTag SkSetFourByteTag('s', 'r', 'e', 'c')
427 #define kEffects_SkDescriptorTag SkSetFourByteTag('e', 'f', 'c', 't')
428
429 ///////////////////////////////////////////////////////////////////////////////
430
getHinting()431 SkFontHinting SkScalerContextRec::getHinting() const {
432 unsigned hint = (fFlags & SkScalerContext::kHinting_Mask) >>
433 SkScalerContext::kHinting_Shift;
434 return static_cast<SkFontHinting>(hint);
435 }
436
setHinting(SkFontHinting hinting)437 void SkScalerContextRec::setHinting(SkFontHinting hinting) {
438 fFlags = (fFlags & ~SkScalerContext::kHinting_Mask) |
439 (static_cast<unsigned>(hinting) << SkScalerContext::kHinting_Shift);
440 }
441
442
443 #endif
444