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