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