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