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