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 SkPaint_DEFINED
9 #define SkPaint_DEFINED
10 
11 #include "SkColor.h"
12 #include "SkDrawLooper.h"
13 #include "SkFilterQuality.h"
14 #include "SkMatrix.h"
15 #include "SkXfermode.h"
16 
17 class SkAnnotation;
18 class SkAutoDescriptor;
19 class SkAutoGlyphCache;
20 class SkColorFilter;
21 class SkData;
22 class SkDescriptor;
23 struct SkDeviceProperties;
24 class SkReadBuffer;
25 class SkWriteBuffer;
26 class SkGlyph;
27 struct SkRect;
28 class SkGlyphCache;
29 class SkImageFilter;
30 class SkMaskFilter;
31 class SkPath;
32 class SkPathEffect;
33 struct SkPoint;
34 class SkRasterizer;
35 class SkShader;
36 class SkTypeface;
37 
38 typedef const SkGlyph& (*SkDrawCacheProc)(SkGlyphCache*, const char**,
39                                            SkFixed x, SkFixed y);
40 
41 typedef const SkGlyph& (*SkMeasureCacheProc)(SkGlyphCache*, const char**);
42 
43 #define kBicubicFilterBitmap_Flag kHighQualityFilterBitmap_Flag
44 
45 /** \class SkPaint
46 
47     The SkPaint class holds the style and color information about how to draw
48     geometries, text and bitmaps.
49 */
50 
51 class SK_API SkPaint {
52 public:
53     SkPaint();
54     SkPaint(const SkPaint& paint);
55     ~SkPaint();
56 
57     SkPaint& operator=(const SkPaint&);
58 
59     /** operator== may give false negatives: two paints that draw equivalently
60         may return false.  It will never give false positives: two paints that
61         are not equivalent always return false.
62     */
63     SK_API friend bool operator==(const SkPaint& a, const SkPaint& b);
64     friend bool operator!=(const SkPaint& a, const SkPaint& b) {
65         return !(a == b);
66     }
67 
68     /** getHash() is a shallow hash, with the same limitations as operator==.
69      *  If operator== returns true for two paints, getHash() returns the same value for each.
70      */
71     uint32_t getHash() const;
72 
73     void flatten(SkWriteBuffer&) const;
74     void unflatten(SkReadBuffer&);
75 
76     /** Restores the paint to its initial settings.
77     */
78     void reset();
79 
80     /** Specifies the level of hinting to be performed. These names are taken
81         from the Gnome/Cairo names for the same. They are translated into
82         Freetype concepts the same as in cairo-ft-font.c:
83            kNo_Hinting     -> FT_LOAD_NO_HINTING
84            kSlight_Hinting -> FT_LOAD_TARGET_LIGHT
85            kNormal_Hinting -> <default, no option>
86            kFull_Hinting   -> <same as kNormalHinting, unless we are rendering
87                               subpixel glyphs, in which case TARGET_LCD or
88                               TARGET_LCD_V is used>
89     */
90     enum Hinting {
91         kNo_Hinting            = 0,
92         kSlight_Hinting        = 1,
93         kNormal_Hinting        = 2,     //!< this is the default
94         kFull_Hinting          = 3
95     };
96 
getHinting()97     Hinting getHinting() const {
98         return static_cast<Hinting>(fBitfields.fHinting);
99     }
100 
101     void setHinting(Hinting hintingLevel);
102 
103     /** Specifies the bit values that are stored in the paint's flags.
104     */
105     enum Flags {
106         kAntiAlias_Flag       = 0x01,   //!< mask to enable antialiasing
107         kDither_Flag          = 0x04,   //!< mask to enable dithering
108         kUnderlineText_Flag   = 0x08,   //!< mask to enable underline text
109         kStrikeThruText_Flag  = 0x10,   //!< mask to enable strike-thru text
110         kFakeBoldText_Flag    = 0x20,   //!< mask to enable fake-bold text
111         kLinearText_Flag      = 0x40,   //!< mask to enable linear-text
112         kSubpixelText_Flag    = 0x80,   //!< mask to enable subpixel text positioning
113         kDevKernText_Flag     = 0x100,  //!< mask to enable device kerning text
114         kLCDRenderText_Flag   = 0x200,  //!< mask to enable subpixel glyph renderering
115         kEmbeddedBitmapText_Flag = 0x400, //!< mask to enable embedded bitmap strikes
116         kAutoHinting_Flag     = 0x800,  //!< mask to force Freetype's autohinter
117         kVerticalText_Flag    = 0x1000,
118         kGenA8FromLCD_Flag    = 0x2000, // hack for GDI -- do not use if you can help it
119         kDistanceFieldTextTEMP_Flag = 0x4000, //!< TEMPORARY mask to enable distance fields
120                                               // currently overrides LCD and subpixel rendering
121         // when adding extra flags, note that the fFlags member is specified
122         // with a bit-width and you'll have to expand it.
123 
124         kAllFlags = 0xFFFF
125     };
126 
127     /** Return the paint's flags. Use the Flag enum to test flag values.
128         @return the paint's flags (see enums ending in _Flag for bit masks)
129     */
getFlags()130     uint32_t getFlags() const { return fBitfields.fFlags; }
131 
132     /** Set the paint's flags. Use the Flag enum to specific flag values.
133         @param flags    The new flag bits for the paint (see Flags enum)
134     */
135     void setFlags(uint32_t flags);
136 
137     /** Helper for getFlags(), returning true if kAntiAlias_Flag bit is set
138         @return true if the antialias bit is set in the paint's flags.
139         */
isAntiAlias()140     bool isAntiAlias() const {
141         return SkToBool(this->getFlags() & kAntiAlias_Flag);
142     }
143 
144     /** Helper for setFlags(), setting or clearing the kAntiAlias_Flag bit
145         @param aa   true to enable antialiasing, false to disable it
146         */
147     void setAntiAlias(bool aa);
148 
149     /** Helper for getFlags(), returning true if kDither_Flag bit is set
150         @return true if the dithering bit is set in the paint's flags.
151         */
isDither()152     bool isDither() const {
153         return SkToBool(this->getFlags() & kDither_Flag);
154     }
155 
156     /** Helper for setFlags(), setting or clearing the kDither_Flag bit
157         @param dither   true to enable dithering, false to disable it
158         */
159     void setDither(bool dither);
160 
161     /** Helper for getFlags(), returning true if kLinearText_Flag bit is set
162         @return true if the lineartext bit is set in the paint's flags
163     */
isLinearText()164     bool isLinearText() const {
165         return SkToBool(this->getFlags() & kLinearText_Flag);
166     }
167 
168     /** Helper for setFlags(), setting or clearing the kLinearText_Flag bit
169         @param linearText true to set the linearText bit in the paint's flags,
170                           false to clear it.
171     */
172     void setLinearText(bool linearText);
173 
174     /** Helper for getFlags(), returning true if kSubpixelText_Flag bit is set
175         @return true if the lineartext bit is set in the paint's flags
176     */
isSubpixelText()177     bool isSubpixelText() const {
178         return SkToBool(this->getFlags() & kSubpixelText_Flag);
179     }
180 
181     /**
182      *  Helper for setFlags(), setting or clearing the kSubpixelText_Flag.
183      *  @param subpixelText true to set the subpixelText bit in the paint's
184      *                      flags, false to clear it.
185      */
186     void setSubpixelText(bool subpixelText);
187 
isLCDRenderText()188     bool isLCDRenderText() const {
189         return SkToBool(this->getFlags() & kLCDRenderText_Flag);
190     }
191 
192     /**
193      *  Helper for setFlags(), setting or clearing the kLCDRenderText_Flag.
194      *  Note: antialiasing must also be on for lcd rendering
195      *  @param lcdText true to set the LCDRenderText bit in the paint's flags,
196      *                 false to clear it.
197      */
198     void setLCDRenderText(bool lcdText);
199 
isEmbeddedBitmapText()200     bool isEmbeddedBitmapText() const {
201         return SkToBool(this->getFlags() & kEmbeddedBitmapText_Flag);
202     }
203 
204     /** Helper for setFlags(), setting or clearing the kEmbeddedBitmapText_Flag bit
205         @param useEmbeddedBitmapText true to set the kEmbeddedBitmapText bit in the paint's flags,
206                                      false to clear it.
207     */
208     void setEmbeddedBitmapText(bool useEmbeddedBitmapText);
209 
isAutohinted()210     bool isAutohinted() const {
211         return SkToBool(this->getFlags() & kAutoHinting_Flag);
212     }
213 
214     /** Helper for setFlags(), setting or clearing the kAutoHinting_Flag bit
215         @param useAutohinter true to set the kEmbeddedBitmapText bit in the
216                                   paint's flags,
217                              false to clear it.
218     */
219     void setAutohinted(bool useAutohinter);
220 
isVerticalText()221     bool isVerticalText() const {
222         return SkToBool(this->getFlags() & kVerticalText_Flag);
223     }
224 
225     /**
226      *  Helper for setting or clearing the kVerticalText_Flag bit in
227      *  setFlags(...).
228      *
229      *  If this bit is set, then advances are treated as Y values rather than
230      *  X values, and drawText will places its glyphs vertically rather than
231      *  horizontally.
232      */
233     void setVerticalText(bool);
234 
235     /** Helper for getFlags(), returning true if kUnderlineText_Flag bit is set
236         @return true if the underlineText bit is set in the paint's flags.
237     */
isUnderlineText()238     bool isUnderlineText() const {
239         return SkToBool(this->getFlags() & kUnderlineText_Flag);
240     }
241 
242     /** Helper for setFlags(), setting or clearing the kUnderlineText_Flag bit
243         @param underlineText true to set the underlineText bit in the paint's
244                              flags, false to clear it.
245     */
246     void setUnderlineText(bool underlineText);
247 
248     /** Helper for getFlags(), returns true if kStrikeThruText_Flag bit is set
249         @return true if the strikeThruText bit is set in the paint's flags.
250     */
isStrikeThruText()251     bool isStrikeThruText() const {
252         return SkToBool(this->getFlags() & kStrikeThruText_Flag);
253     }
254 
255     /** Helper for setFlags(), setting or clearing the kStrikeThruText_Flag bit
256         @param strikeThruText   true to set the strikeThruText bit in the
257                                 paint's flags, false to clear it.
258     */
259     void setStrikeThruText(bool strikeThruText);
260 
261     /** Helper for getFlags(), returns true if kFakeBoldText_Flag bit is set
262         @return true if the kFakeBoldText_Flag bit is set in the paint's flags.
263     */
isFakeBoldText()264     bool isFakeBoldText() const {
265         return SkToBool(this->getFlags() & kFakeBoldText_Flag);
266     }
267 
268     /** Helper for setFlags(), setting or clearing the kFakeBoldText_Flag bit
269         @param fakeBoldText true to set the kFakeBoldText_Flag bit in the paint's
270                             flags, false to clear it.
271     */
272     void setFakeBoldText(bool fakeBoldText);
273 
274     /** Helper for getFlags(), returns true if kDevKernText_Flag bit is set
275         @return true if the kernText bit is set in the paint's flags.
276     */
isDevKernText()277     bool isDevKernText() const {
278         return SkToBool(this->getFlags() & kDevKernText_Flag);
279     }
280 
281     /** Helper for setFlags(), setting or clearing the kKernText_Flag bit
282         @param kernText true to set the kKernText_Flag bit in the paint's
283                             flags, false to clear it.
284     */
285     void setDevKernText(bool devKernText);
286 
287     /** Helper for getFlags(), returns true if kDistanceFieldTextTEMP_Flag bit is set
288      @return true if the distanceFieldText bit is set in the paint's flags.
289      */
isDistanceFieldTextTEMP()290     bool isDistanceFieldTextTEMP() const {
291         return SkToBool(this->getFlags() & kDistanceFieldTextTEMP_Flag);
292     }
293 
294     /** Helper for setFlags(), setting or clearing the kDistanceFieldTextTEMP_Flag bit
295      @param distanceFieldText true to set the kDistanceFieldTextTEMP_Flag bit in the paint's
296      flags, false to clear it.
297      */
298     void setDistanceFieldTextTEMP(bool distanceFieldText);
299 
300 #ifdef SK_SUPPORT_LEGACY_FILTERLEVEL_ENUM
301     enum FilterLevel {
302         kNone_FilterLevel   = kNone_SkFilterQuality,
303         kLow_FilterLevel    = kLow_SkFilterQuality,
304         kMedium_FilterLevel = kMedium_SkFilterQuality,
305         kHigh_FilterLevel   = kHigh_SkFilterQuality
306     };
307 
308     /**
309      *  Return the filter level. This affects the quality (and performance) of
310      *  drawing scaled images.
311      */
getFilterLevel()312     FilterLevel getFilterLevel() const {
313         return (FilterLevel)this->getFilterQuality();
314     }
315 
316     /**
317      *  Set the filter level. This affects the quality (and performance) of
318      *  drawing scaled images.
319      */
setFilterLevel(FilterLevel level)320     void setFilterLevel(FilterLevel level) {
321         this->setFilterQuality((SkFilterQuality)level);
322     }
323 #endif
324 
325     /**
326      *  Return the filter level. This affects the quality (and performance) of
327      *  drawing scaled images.
328      */
getFilterQuality()329     SkFilterQuality getFilterQuality() const {
330         return (SkFilterQuality)fBitfields.fFilterQuality;
331     }
332 
333     /**
334      *  Set the filter quality. This affects the quality (and performance) of
335      *  drawing scaled images.
336      */
337     void setFilterQuality(SkFilterQuality quality);
338 
339     /** Styles apply to rect, oval, path, and text.
340         Bitmaps are always drawn in "fill", and lines are always drawn in
341         "stroke".
342 
343         Note: strokeandfill implicitly draws the result with
344         SkPath::kWinding_FillType, so if the original path is even-odd, the
345         results may not appear the same as if it was drawn twice, filled and
346         then stroked.
347     */
348     enum Style {
349         kFill_Style,            //!< fill the geometry
350         kStroke_Style,          //!< stroke the geometry
351         kStrokeAndFill_Style,   //!< fill and stroke the geometry
352     };
353     enum {
354         kStyleCount = kStrokeAndFill_Style + 1
355     };
356 
357     /** Return the paint's style, used for controlling how primitives'
358         geometries are interpreted (except for drawBitmap, which always assumes
359         kFill_Style).
360         @return the paint's Style
361     */
getStyle()362     Style getStyle() const { return (Style)fBitfields.fStyle; }
363 
364     /** Set the paint's style, used for controlling how primitives'
365         geometries are interpreted (except for drawBitmap, which always assumes
366         Fill).
367         @param style    The new style to set in the paint
368     */
369     void setStyle(Style style);
370 
371     /** Return the paint's color. Note that the color is a 32bit value
372         containing alpha as well as r,g,b. This 32bit value is not
373         premultiplied, meaning that its alpha can be any value, regardless of
374         the values of r,g,b.
375         @return the paint's color (and alpha).
376     */
getColor()377     SkColor getColor() const { return fColor; }
378 
379     /** Set the paint's color. Note that the color is a 32bit value containing
380         alpha as well as r,g,b. This 32bit value is not premultiplied, meaning
381         that its alpha can be any value, regardless of the values of r,g,b.
382         @param color    The new color (including alpha) to set in the paint.
383     */
384     void setColor(SkColor color);
385 
386     /** Helper to getColor() that just returns the color's alpha value.
387         @return the alpha component of the paint's color.
388         */
getAlpha()389     uint8_t getAlpha() const { return SkToU8(SkColorGetA(fColor)); }
390 
391     /** Helper to setColor(), that only assigns the color's alpha value,
392         leaving its r,g,b values unchanged.
393         @param a    set the alpha component (0..255) of the paint's color.
394     */
395     void setAlpha(U8CPU a);
396 
397     /** Helper to setColor(), that takes a,r,g,b and constructs the color value
398         using SkColorSetARGB()
399         @param a    The new alpha component (0..255) of the paint's color.
400         @param r    The new red component (0..255) of the paint's color.
401         @param g    The new green component (0..255) of the paint's color.
402         @param b    The new blue component (0..255) of the paint's color.
403     */
404     void setARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
405 
406     /** Return the width for stroking.
407         <p />
408         A value of 0 strokes in hairline mode.
409         Hairlines always draw 1-pixel wide, regardless of the matrix.
410         @return the paint's stroke width, used whenever the paint's style is
411                 Stroke or StrokeAndFill.
412     */
getStrokeWidth()413     SkScalar getStrokeWidth() const { return fWidth; }
414 
415     /** Set the width for stroking.
416         Pass 0 to stroke in hairline mode.
417         Hairlines always draw 1-pixel wide, regardless of the matrix.
418         @param width set the paint's stroke width, used whenever the paint's
419                      style is Stroke or StrokeAndFill.
420     */
421     void setStrokeWidth(SkScalar width);
422 
423     /** Return the paint's stroke miter value. This is used to control the
424         behavior of miter joins when the joins angle is sharp.
425         @return the paint's miter limit, used whenever the paint's style is
426                 Stroke or StrokeAndFill.
427     */
getStrokeMiter()428     SkScalar getStrokeMiter() const { return fMiterLimit; }
429 
430     /** Set the paint's stroke miter value. This is used to control the
431         behavior of miter joins when the joins angle is sharp. This value must
432         be >= 0.
433         @param miter    set the miter limit on the paint, used whenever the
434                         paint's style is Stroke or StrokeAndFill.
435     */
436     void setStrokeMiter(SkScalar miter);
437 
438     /** Cap enum specifies the settings for the paint's strokecap. This is the
439         treatment that is applied to the beginning and end of each non-closed
440         contour (e.g. lines).
441     */
442     enum Cap {
443         kButt_Cap,      //!< begin/end contours with no extension
444         kRound_Cap,     //!< begin/end contours with a semi-circle extension
445         kSquare_Cap,    //!< begin/end contours with a half square extension
446 
447         kCapCount,
448         kDefault_Cap = kButt_Cap
449     };
450 
451     /** Join enum specifies the settings for the paint's strokejoin. This is
452         the treatment that is applied to corners in paths and rectangles.
453     */
454     enum Join {
455         kMiter_Join,    //!< connect path segments with a sharp join
456         kRound_Join,    //!< connect path segments with a round join
457         kBevel_Join,    //!< connect path segments with a flat bevel join
458 
459         kJoinCount,
460         kDefault_Join = kMiter_Join
461     };
462 
463     /** Return the paint's stroke cap type, controlling how the start and end
464         of stroked lines and paths are treated.
465         @return the line cap style for the paint, used whenever the paint's
466                 style is Stroke or StrokeAndFill.
467     */
getStrokeCap()468     Cap getStrokeCap() const { return (Cap)fBitfields.fCapType; }
469 
470     /** Set the paint's stroke cap type.
471         @param cap  set the paint's line cap style, used whenever the paint's
472                     style is Stroke or StrokeAndFill.
473     */
474     void setStrokeCap(Cap cap);
475 
476     /** Return the paint's stroke join type.
477         @return the paint's line join style, used whenever the paint's style is
478                 Stroke or StrokeAndFill.
479     */
getStrokeJoin()480     Join getStrokeJoin() const { return (Join)fBitfields.fJoinType; }
481 
482     /** Set the paint's stroke join type.
483         @param join set the paint's line join style, used whenever the paint's
484                     style is Stroke or StrokeAndFill.
485     */
486     void setStrokeJoin(Join join);
487 
488     /**
489      *  Applies any/all effects (patheffect, stroking) to src, returning the
490      *  result in dst. The result is that drawing src with this paint will be
491      *  the same as drawing dst with a default paint (at least from the
492      *  geometric perspective).
493      *
494      *  @param src  input path
495      *  @param dst  output path (may be the same as src)
496      *  @param cullRect If not null, the dst path may be culled to this rect.
497      *  @param resScale If > 1, increase precision, else if (0 < res < 1) reduce precision
498      *              in favor of speed/size.
499      *  @return     true if the path should be filled, or false if it should be
500      *              drawn with a hairline (width == 0)
501      */
502     bool getFillPath(const SkPath& src, SkPath* dst, const SkRect* cullRect,
503                      SkScalar resScale = 1) const;
504 
getFillPath(const SkPath & src,SkPath * dst)505     bool getFillPath(const SkPath& src, SkPath* dst) const {
506         return this->getFillPath(src, dst, NULL, 1);
507     }
508 
509     /** Get the paint's shader object.
510         <p />
511       The shader's reference count is not affected.
512         @return the paint's shader (or NULL)
513     */
getShader()514     SkShader* getShader() const { return fShader; }
515 
516     /** Set or clear the shader object.
517      *  Shaders specify the source color(s) for what is being drawn. If a paint
518      *  has no shader, then the paint's color is used. If the paint has a
519      *  shader, then the shader's color(s) are use instead, but they are
520      *  modulated by the paint's alpha. This makes it easy to create a shader
521      *  once (e.g. bitmap tiling or gradient) and then change its transparency
522      *  w/o having to modify the original shader... only the paint's alpha needs
523      *  to be modified.
524      *
525      *  There is an exception to this only-respect-paint's-alpha rule: If the shader only generates
526      *  alpha (e.g. SkShader::CreateBitmapShader(bitmap, ...) where bitmap's colortype is kAlpha_8)
527      *  then the shader will use the paint's entire color to "colorize" its output (modulating the
528      *  bitmap's alpha with the paint's color+alpha).
529      *
530      *  Pass NULL to clear any previous shader.
531      *  As a convenience, the parameter passed is also returned.
532      *  If a previous shader exists, its reference count is decremented.
533      *  If shader is not NULL, its reference count is incremented.
534      *  @param shader   May be NULL. The shader to be installed in the paint
535      *  @return         shader
536      */
537     SkShader* setShader(SkShader* shader);
538 
539     /** Get the paint's colorfilter. If there is a colorfilter, its reference
540         count is not changed.
541         @return the paint's colorfilter (or NULL)
542     */
getColorFilter()543     SkColorFilter* getColorFilter() const { return fColorFilter; }
544 
545     /** Set or clear the paint's colorfilter, returning the parameter.
546         <p />
547         If the paint already has a filter, its reference count is decremented.
548         If filter is not NULL, its reference count is incremented.
549         @param filter   May be NULL. The filter to be installed in the paint
550         @return         filter
551     */
552     SkColorFilter* setColorFilter(SkColorFilter* filter);
553 
554     /** Get the paint's xfermode object.
555         <p />
556       The xfermode's reference count is not affected.
557         @return the paint's xfermode (or NULL)
558     */
getXfermode()559     SkXfermode* getXfermode() const { return fXfermode; }
560 
561     /** Set or clear the xfermode object.
562         <p />
563         Pass NULL to clear any previous xfermode.
564         As a convenience, the parameter passed is also returned.
565         If a previous xfermode exists, its reference count is decremented.
566         If xfermode is not NULL, its reference count is incremented.
567         @param xfermode May be NULL. The new xfermode to be installed in the
568                         paint
569         @return         xfermode
570     */
571     SkXfermode* setXfermode(SkXfermode* xfermode);
572 
573     /** Create an xfermode based on the specified Mode, and assign it into the
574         paint, returning the mode that was set. If the Mode is SrcOver, then
575         the paint's xfermode is set to null.
576      */
577     SkXfermode* setXfermodeMode(SkXfermode::Mode);
578 
579     /** Get the paint's patheffect object.
580         <p />
581       The patheffect reference count is not affected.
582         @return the paint's patheffect (or NULL)
583     */
getPathEffect()584     SkPathEffect* getPathEffect() const { return fPathEffect; }
585 
586     /** Set or clear the patheffect object.
587         <p />
588         Pass NULL to clear any previous patheffect.
589         As a convenience, the parameter passed is also returned.
590         If a previous patheffect exists, its reference count is decremented.
591         If patheffect is not NULL, its reference count is incremented.
592         @param effect   May be NULL. The new patheffect to be installed in the
593                         paint
594         @return         effect
595     */
596     SkPathEffect* setPathEffect(SkPathEffect* effect);
597 
598     /** Get the paint's maskfilter object.
599         <p />
600       The maskfilter reference count is not affected.
601         @return the paint's maskfilter (or NULL)
602     */
getMaskFilter()603     SkMaskFilter* getMaskFilter() const { return fMaskFilter; }
604 
605     /** Set or clear the maskfilter object.
606         <p />
607         Pass NULL to clear any previous maskfilter.
608         As a convenience, the parameter passed is also returned.
609         If a previous maskfilter exists, its reference count is decremented.
610         If maskfilter is not NULL, its reference count is incremented.
611         @param maskfilter   May be NULL. The new maskfilter to be installed in
612                             the paint
613         @return             maskfilter
614     */
615     SkMaskFilter* setMaskFilter(SkMaskFilter* maskfilter);
616 
617     // These attributes are for text/fonts
618 
619     /** Get the paint's typeface object.
620         <p />
621         The typeface object identifies which font to use when drawing or
622         measuring text. The typeface reference count is not affected.
623         @return the paint's typeface (or NULL)
624     */
getTypeface()625     SkTypeface* getTypeface() const { return fTypeface; }
626 
627     /** Set or clear the typeface object.
628         <p />
629         Pass NULL to clear any previous typeface.
630         As a convenience, the parameter passed is also returned.
631         If a previous typeface exists, its reference count is decremented.
632         If typeface is not NULL, its reference count is incremented.
633         @param typeface May be NULL. The new typeface to be installed in the
634                         paint
635         @return         typeface
636     */
637     SkTypeface* setTypeface(SkTypeface* typeface);
638 
639     /** Get the paint's rasterizer (or NULL).
640         <p />
641         The raster controls how paths/text are turned into alpha masks.
642         @return the paint's rasterizer (or NULL)
643     */
getRasterizer()644     SkRasterizer* getRasterizer() const { return fRasterizer; }
645 
646     /** Set or clear the rasterizer object.
647         <p />
648         Pass NULL to clear any previous rasterizer.
649         As a convenience, the parameter passed is also returned.
650         If a previous rasterizer exists in the paint, its reference count is
651         decremented. If rasterizer is not NULL, its reference count is
652         incremented.
653         @param rasterizer May be NULL. The new rasterizer to be installed in
654                           the paint.
655         @return           rasterizer
656     */
657     SkRasterizer* setRasterizer(SkRasterizer* rasterizer);
658 
getImageFilter()659     SkImageFilter* getImageFilter() const { return fImageFilter; }
660     SkImageFilter* setImageFilter(SkImageFilter*);
661 
getAnnotation()662     SkAnnotation* getAnnotation() const { return fAnnotation; }
663     SkAnnotation* setAnnotation(SkAnnotation*);
664 
665     /**
666      *  Returns true if there is an annotation installed on this paint, and
667      *  the annotation specifics no-drawing.
668      */
669     SK_ATTR_DEPRECATED("use getAnnotation and check for non-null")
isNoDrawAnnotation()670     bool isNoDrawAnnotation() const { return this->getAnnotation() != NULL; }
671 
672     /**
673      *  Return the paint's SkDrawLooper (if any). Does not affect the looper's
674      *  reference count.
675      */
getLooper()676     SkDrawLooper* getLooper() const { return fLooper; }
677 
678     /**
679      *  Set or clear the looper object.
680      *  <p />
681      *  Pass NULL to clear any previous looper.
682      *  As a convenience, the parameter passed is also returned.
683      *  If a previous looper exists in the paint, its reference count is
684      *  decremented. If looper is not NULL, its reference count is
685      *  incremented.
686      *  @param looper May be NULL. The new looper to be installed in the paint.
687      *  @return looper
688      */
689     SkDrawLooper* setLooper(SkDrawLooper* looper);
690 
691     enum Align {
692         kLeft_Align,
693         kCenter_Align,
694         kRight_Align,
695     };
696     enum {
697         kAlignCount = 3
698     };
699 
700     /** Return the paint's Align value for drawing text.
701         @return the paint's Align value for drawing text.
702     */
getTextAlign()703     Align   getTextAlign() const { return (Align)fBitfields.fTextAlign; }
704 
705     /** Set the paint's text alignment.
706         @param align set the paint's Align value for drawing text.
707     */
708     void    setTextAlign(Align align);
709 
710     /** Return the paint's text size.
711         @return the paint's text size.
712     */
getTextSize()713     SkScalar getTextSize() const { return fTextSize; }
714 
715     /** Set the paint's text size. This value must be > 0
716         @param textSize set the paint's text size.
717     */
718     void setTextSize(SkScalar textSize);
719 
720     /** Return the paint's horizontal scale factor for text. The default value
721         is 1.0.
722         @return the paint's scale factor in X for drawing/measuring text
723     */
getTextScaleX()724     SkScalar getTextScaleX() const { return fTextScaleX; }
725 
726     /** Set the paint's horizontal scale factor for text. The default value
727         is 1.0. Values > 1.0 will stretch the text wider. Values < 1.0 will
728         stretch the text narrower.
729         @param scaleX   set the paint's scale factor in X for drawing/measuring
730                         text.
731     */
732     void setTextScaleX(SkScalar scaleX);
733 
734     /** Return the paint's horizontal skew factor for text. The default value
735         is 0.
736         @return the paint's skew factor in X for drawing text.
737     */
getTextSkewX()738     SkScalar getTextSkewX() const { return fTextSkewX; }
739 
740     /** Set the paint's horizontal skew factor for text. The default value
741         is 0. For approximating oblique text, use values around -0.25.
742         @param skewX set the paint's skew factor in X for drawing text.
743     */
744     void setTextSkewX(SkScalar skewX);
745 
746     /** Describes how to interpret the text parameters that are passed to paint
747         methods like measureText() and getTextWidths().
748     */
749     enum TextEncoding {
750         kUTF8_TextEncoding,     //!< the text parameters are UTF8
751         kUTF16_TextEncoding,    //!< the text parameters are UTF16
752         kUTF32_TextEncoding,    //!< the text parameters are UTF32
753         kGlyphID_TextEncoding   //!< the text parameters are glyph indices
754     };
755 
getTextEncoding()756     TextEncoding getTextEncoding() const {
757       return (TextEncoding)fBitfields.fTextEncoding;
758     }
759 
760     void setTextEncoding(TextEncoding encoding);
761 
762     struct FontMetrics {
763         /** Flags which indicate the confidence level of various metrics.
764             A set flag indicates that the metric may be trusted.
765         */
766         enum FontMetricsFlags {
767             kUnderlineThinknessIsValid_Flag = 1 << 0,
768             kUnderlinePositionIsValid_Flag = 1 << 1,
769         };
770 
771         uint32_t    fFlags;       //!< Bit field to identify which values are unknown
772         SkScalar    fTop;       //!< The greatest distance above the baseline for any glyph (will be <= 0)
773         SkScalar    fAscent;    //!< The recommended distance above the baseline (will be <= 0)
774         SkScalar    fDescent;   //!< The recommended distance below the baseline (will be >= 0)
775         SkScalar    fBottom;    //!< The greatest distance below the baseline for any glyph (will be >= 0)
776         SkScalar    fLeading;   //!< The recommended distance to add between lines of text (will be >= 0)
777         SkScalar    fAvgCharWidth;  //!< the average character width (>= 0)
778         SkScalar    fMaxCharWidth;  //!< the max character width (>= 0)
779         SkScalar    fXMin;      //!< The minimum bounding box x value for all glyphs
780         SkScalar    fXMax;      //!< The maximum bounding box x value for all glyphs
781         SkScalar    fXHeight;   //!< The height of an 'x' in px, or 0 if no 'x' in face
782         SkScalar    fCapHeight;  //!< The cap height (> 0), or 0 if cannot be determined.
783         SkScalar    fUnderlineThickness; //!< underline thickness, or 0 if cannot be determined
784 
785         /**  Underline Position - position of the top of the Underline stroke
786                 relative to the baseline, this can have following values
787                 - Negative - means underline should be drawn above baseline.
788                 - Positive - means below baseline.
789                 - Zero     - mean underline should be drawn on baseline.
790          */
791         SkScalar    fUnderlinePosition; //!< underline position, or 0 if cannot be determined
792 
793         /**  If the fontmetrics has a valid underlinethickness, return true, and set the
794                 thickness param to that value. If it doesn't return false and ignore the
795                 thickness param.
796         */
hasUnderlineThicknessFontMetrics797         bool hasUnderlineThickness(SkScalar* thickness) const {
798             if (SkToBool(fFlags & kUnderlineThinknessIsValid_Flag)) {
799                 *thickness = fUnderlineThickness;
800                 return true;
801             }
802             return false;
803         }
804 
805         /**  If the fontmetrics has a valid underlineposition, return true, and set the
806                 thickness param to that value. If it doesn't return false and ignore the
807                 thickness param.
808         */
hasUnderlinePositionFontMetrics809         bool hasUnderlinePosition(SkScalar* position) const {
810             if (SkToBool(fFlags & kUnderlinePositionIsValid_Flag)) {
811                 *position = fUnderlinePosition;
812                 return true;
813             }
814             return false;
815         }
816 
817     };
818 
819     /** Return the recommend spacing between lines (which will be
820         fDescent - fAscent + fLeading).
821         If metrics is not null, return in it the font metrics for the
822         typeface/pointsize/etc. currently set in the paint.
823         @param metrics      If not null, returns the font metrics for the
824                             current typeface/pointsize/etc setting in this
825                             paint.
826         @param scale        If not 0, return width as if the canvas were scaled
827                             by this value
828         @param return the recommended spacing between lines
829     */
830     SkScalar getFontMetrics(FontMetrics* metrics, SkScalar scale = 0) const;
831 
832     /** Return the recommend line spacing. This will be
833         fDescent - fAscent + fLeading
834     */
getFontSpacing()835     SkScalar getFontSpacing() const { return this->getFontMetrics(NULL, 0); }
836 
837     /** Convert the specified text into glyph IDs, returning the number of
838         glyphs ID written. If glyphs is NULL, it is ignore and only the count
839         is returned.
840     */
841     int textToGlyphs(const void* text, size_t byteLength,
842                      uint16_t glyphs[]) const;
843 
844     /** Return true if all of the specified text has a corresponding non-zero
845         glyph ID. If any of the code-points in the text are not supported in
846         the typeface (i.e. the glyph ID would be zero), then return false.
847 
848         If the text encoding for the paint is kGlyph_TextEncoding, then this
849         returns true if all of the specified glyph IDs are non-zero.
850      */
851     bool containsText(const void* text, size_t byteLength) const;
852 
853     /** Convert the glyph array into Unichars. Unconvertable glyphs are mapped
854         to zero. Note: this does not look at the text-encoding setting in the
855         paint, only at the typeface.
856     */
857     void glyphsToUnichars(const uint16_t glyphs[], int count,
858                           SkUnichar text[]) const;
859 
860     /** Return the number of drawable units in the specified text buffer.
861         This looks at the current TextEncoding field of the paint. If you also
862         want to have the text converted into glyph IDs, call textToGlyphs
863         instead.
864     */
countText(const void * text,size_t byteLength)865     int countText(const void* text, size_t byteLength) const {
866         return this->textToGlyphs(text, byteLength, NULL);
867     }
868 
869     /** Return the width of the text. This will return the vertical measure
870      *  if isVerticalText() is true, in which case the returned value should
871      *  be treated has a height instead of a width.
872      *
873      *  @param text         The text to be measured
874      *  @param length       Number of bytes of text to measure
875      *  @param bounds       If not NULL, returns the bounds of the text,
876      *                      relative to (0, 0).
877      *  @return             The advance width of the text
878      */
879     SkScalar measureText(const void* text, size_t length, SkRect* bounds) const;
880 
881     /** Return the width of the text. This will return the vertical measure
882      *  if isVerticalText() is true, in which case the returned value should
883      *  be treated has a height instead of a width.
884      *
885      *  @param text     Address of the text
886      *  @param length   Number of bytes of text to measure
887      *  @return         The advance width of the text
888      */
measureText(const void * text,size_t length)889     SkScalar measureText(const void* text, size_t length) const {
890         return this->measureText(text, length, NULL);
891     }
892 
893     /** Return the number of bytes of text that were measured. If
894      *  isVerticalText() is true, then the vertical advances are used for
895      *  the measurement.
896      *
897      *  @param text     The text to be measured
898      *  @param length   Number of bytes of text to measure
899      *  @param maxWidth Maximum width. Only the subset of text whose accumulated
900      *                  widths are <= maxWidth are measured.
901      *  @param measuredWidth Optional. If non-null, this returns the actual
902      *                  width of the measured text.
903      *  @return         The number of bytes of text that were measured. Will be
904      *                  <= length.
905      */
906     size_t  breakText(const void* text, size_t length, SkScalar maxWidth,
907                       SkScalar* measuredWidth = NULL) const;
908 
909     /** Return the advances for the text. These will be vertical advances if
910      *  isVerticalText() returns true.
911      *
912      *  @param text         the text
913      *  @param byteLength   number of bytes to of text
914      *  @param widths       If not null, returns the array of advances for
915      *                      the glyphs. If not NULL, must be at least a large
916      *                      as the number of unichars in the specified text.
917      *  @param bounds       If not null, returns the bounds for each of
918      *                      character, relative to (0, 0)
919      *  @return the number of unichars in the specified text.
920      */
921     int getTextWidths(const void* text, size_t byteLength, SkScalar widths[],
922                       SkRect bounds[] = NULL) const;
923 
924     /** Return the path (outline) for the specified text.
925         Note: just like SkCanvas::drawText, this will respect the Align setting
926               in the paint.
927     */
928     void getTextPath(const void* text, size_t length, SkScalar x, SkScalar y,
929                      SkPath* path) const;
930 
931     void getPosTextPath(const void* text, size_t length,
932                         const SkPoint pos[], SkPath* path) const;
933 
934     /**
935      *  Return a rectangle that represents the union of the bounds of all
936      *  of the glyphs, but each one positioned at (0,0). This may be conservatively large, and
937      *  will not take into account any hinting, but will respect any text-scale-x or text-skew-x
938      *  on this paint.
939      */
940     SkRect getFontBounds() const;
941 
942     // returns true if the paint's settings (e.g. xfermode + alpha) resolve to
943     // mean that we need not draw at all (e.g. SrcOver + 0-alpha)
944     bool nothingToDraw() const;
945 
946     ///////////////////////////////////////////////////////////////////////////
947     // would prefer to make these private...
948 
949     /** Returns true if the current paint settings allow for fast computation of
950      bounds (i.e. there is nothing complex like a patheffect that would make
951      the bounds computation expensive.
952      */
canComputeFastBounds()953     bool canComputeFastBounds() const {
954         if (this->getLooper()) {
955             return this->getLooper()->canComputeFastBounds(*this);
956         }
957         return !this->getRasterizer();
958     }
959 
960     /** Only call this if canComputeFastBounds() returned true. This takes a
961      raw rectangle (the raw bounds of a shape), and adjusts it for stylistic
962      effects in the paint (e.g. stroking). If needed, it uses the storage
963      rect parameter. It returns the adjusted bounds that can then be used
964      for quickReject tests.
965 
966      The returned rect will either be orig or storage, thus the caller
967      should not rely on storage being set to the result, but should always
968      use the retured value. It is legal for orig and storage to be the same
969      rect.
970 
971      e.g.
972      if (paint.canComputeFastBounds()) {
973      SkRect r, storage;
974      path.computeBounds(&r, SkPath::kFast_BoundsType);
975      const SkRect& fastR = paint.computeFastBounds(r, &storage);
976      if (canvas->quickReject(fastR, ...)) {
977      // don't draw the path
978      }
979      }
980      */
computeFastBounds(const SkRect & orig,SkRect * storage)981     const SkRect& computeFastBounds(const SkRect& orig, SkRect* storage) const {
982         SkPaint::Style style = this->getStyle();
983         // ultra fast-case: filling with no effects that affect geometry
984         if (kFill_Style == style) {
985             uintptr_t effects = reinterpret_cast<uintptr_t>(this->getLooper());
986             effects |= reinterpret_cast<uintptr_t>(this->getMaskFilter());
987             effects |= reinterpret_cast<uintptr_t>(this->getPathEffect());
988             effects |= reinterpret_cast<uintptr_t>(this->getImageFilter());
989             if (!effects) {
990                 return orig;
991             }
992         }
993 
994         return this->doComputeFastBounds(orig, storage, style);
995     }
996 
computeFastStrokeBounds(const SkRect & orig,SkRect * storage)997     const SkRect& computeFastStrokeBounds(const SkRect& orig,
998                                           SkRect* storage) const {
999         return this->doComputeFastBounds(orig, storage, kStroke_Style);
1000     }
1001 
1002     // Take the style explicitly, so the caller can force us to be stroked
1003     // without having to make a copy of the paint just to change that field.
1004     const SkRect& doComputeFastBounds(const SkRect& orig, SkRect* storage,
1005                                       Style) const;
1006 
1007     /**
1008      *  Return a matrix that applies the paint's text values: size, scale, skew
1009      */
SetTextMatrix(SkMatrix * matrix,SkScalar size,SkScalar scaleX,SkScalar skewX)1010     static SkMatrix* SetTextMatrix(SkMatrix* matrix, SkScalar size,
1011                                    SkScalar scaleX, SkScalar skewX) {
1012         matrix->setScale(size * scaleX, size);
1013         if (skewX) {
1014             matrix->postSkew(skewX, 0);
1015         }
1016         return matrix;
1017     }
1018 
setTextMatrix(SkMatrix * matrix)1019     SkMatrix* setTextMatrix(SkMatrix* matrix) const {
1020         return SetTextMatrix(matrix, fTextSize, fTextScaleX, fTextSkewX);
1021     }
1022 
1023     SK_TO_STRING_NONVIRT()
1024 
1025 private:
1026     SkTypeface*     fTypeface;
1027     SkPathEffect*   fPathEffect;
1028     SkShader*       fShader;
1029     SkXfermode*     fXfermode;
1030     SkMaskFilter*   fMaskFilter;
1031     SkColorFilter*  fColorFilter;
1032     SkRasterizer*   fRasterizer;
1033     SkDrawLooper*   fLooper;
1034     SkImageFilter*  fImageFilter;
1035     SkAnnotation*   fAnnotation;
1036 
1037     SkScalar        fTextSize;
1038     SkScalar        fTextScaleX;
1039     SkScalar        fTextSkewX;
1040     SkColor         fColor;
1041     SkScalar        fWidth;
1042     SkScalar        fMiterLimit;
1043     union {
1044         struct {
1045             // all of these bitfields should add up to 32
1046             unsigned        fFlags : 16;
1047             unsigned        fTextAlign : 2;
1048             unsigned        fCapType : 2;
1049             unsigned        fJoinType : 2;
1050             unsigned        fStyle : 2;
1051             unsigned        fTextEncoding : 2;  // 3 values
1052             unsigned        fHinting : 2;
1053             unsigned        fFilterQuality : 2;
1054             //unsigned      fFreeBits : 2;
1055         } fBitfields;
1056         uint32_t fBitfieldsUInt;
1057     };
1058 
1059     SkDrawCacheProc    getDrawCacheProc() const;
1060     SkMeasureCacheProc getMeasureCacheProc(bool needFullMetrics) const;
1061 
1062     SkScalar measure_text(SkGlyphCache*, const char* text, size_t length,
1063                           int* count, SkRect* bounds) const;
1064 
1065     /*
1066      * Allocs an SkDescriptor on the heap and return it to the caller as a refcnted
1067      * SkData.  Caller is responsible for managing the lifetime of this object.
1068      */
1069     void getScalerContextDescriptor(SkAutoDescriptor*, const SkDeviceProperties* deviceProperties,
1070                                     const SkMatrix*, bool ignoreGamma) const;
1071 
1072     SkGlyphCache* detachCache(const SkDeviceProperties* deviceProperties, const SkMatrix*,
1073                               bool ignoreGamma) const;
1074 
1075     void descriptorProc(const SkDeviceProperties* deviceProperties, const SkMatrix* deviceMatrix,
1076                         void (*proc)(SkTypeface*, const SkDescriptor*, void*),
1077                         void* context, bool ignoreGamma = false) const;
1078 
1079     /*
1080      * The luminance color is used to determine which Gamma Canonical color to map to.  This is
1081      * really only used by backends which want to cache glyph masks, and need some way to know if
1082      * they need to generate new masks based off a given color.
1083      */
1084     SkColor computeLuminanceColor() const;
1085 
1086     static void Term();
1087 
1088     enum {
1089         /*  This is the size we use when we ask for a glyph's path. We then
1090          *  post-transform it as we draw to match the request.
1091          *  This is done to try to re-use cache entries for the path.
1092          *
1093          *  This value is somewhat arbitrary. In theory, it could be 1, since
1094          *  we store paths as floats. However, we get the path from the font
1095          *  scaler, and it may represent its paths as fixed-point (or 26.6),
1096          *  so we shouldn't ask for something too big (might overflow 16.16)
1097          *  or too small (underflow 26.6).
1098          *
1099          *  This value could track kMaxSizeForGlyphCache, assuming the above
1100          *  constraints, but since we ask for unhinted paths, the two values
1101          *  need not match per-se.
1102          */
1103         kCanonicalTextSizeForPaths  = 64,
1104 
1105         /*
1106          *  Above this size (taking into account CTM and textSize), we never use
1107          *  the cache for bits or metrics (we might overflow), so we just ask
1108          *  for a caononical size and post-transform that.
1109          */
1110         kMaxSizeForGlyphCache       = 256,
1111     };
1112 
1113     static bool TooBigToUseCache(const SkMatrix& ctm, const SkMatrix& textM);
1114 
1115     // Set flags/hinting/textSize up to use for drawing text as paths.
1116     // Returns scale factor to restore the original textSize, since will will
1117     // have change it to kCanonicalTextSizeForPaths.
1118     SkScalar setupForAsPaths();
1119 
MaxCacheSize2()1120     static SkScalar MaxCacheSize2() {
1121         static const SkScalar kMaxSize = SkIntToScalar(kMaxSizeForGlyphCache);
1122         static const SkScalar kMag2Max = kMaxSize * kMaxSize;
1123         return kMag2Max;
1124     }
1125 
1126     friend class SkAutoGlyphCache;
1127     friend class SkAutoGlyphCacheNoGamma;
1128     friend class SkCanvas;
1129     friend class SkDraw;
1130     friend class SkGraphics; // So Term() can be called.
1131     friend class SkPDFDevice;
1132     friend class GrBitmapTextContext;
1133     friend class GrAtlasTextContext;
1134     friend class GrDistanceFieldTextContext;
1135     friend class GrStencilAndCoverTextContext;
1136     friend class GrPathRendering;
1137     friend class GrTextContext;
1138     friend class GrGLPathRendering;
1139     friend class SkScalerContext;
1140     friend class SkTextToPathIter;
1141     friend class SkCanonicalizePaint;
1142 };
1143 
1144 #endif
1145