SkCanvas.h revision 2a5cd60bfff32c92cf44a8cfc3e8c017b9aee456
1/*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef SkCanvas_DEFINED
9#define SkCanvas_DEFINED
10
11#include "SkTypes.h"
12#include "SkBitmap.h"
13#include "SkDeque.h"
14#include "SkClipStack.h"
15#include "SkPaint.h"
16#include "SkRefCnt.h"
17#include "SkPath.h"
18#include "SkRegion.h"
19#include "SkXfermode.h"
20
21// if not defined, we always assume ClipToLayer for saveLayer()
22//#define SK_SUPPORT_LEGACY_CLIPTOLAYERFLAG
23
24
25//#define SK_SUPPORT_LEGACY_GETCLIPTYPE
26//#define SK_SUPPORT_LEGACY_GETTOTALCLIP
27//#define SK_SUPPORT_LEGACY_GETTOPDEVICE
28
29//#define SK_SUPPORT_LEGACY_DRAWTEXT_VIRTUAL
30#ifdef SK_SUPPORT_LEGACY_DRAWTEXT_VIRTUAL
31    #define SK_LEGACY_DRAWTEXT_VIRTUAL  virtual
32#else
33    #define SK_LEGACY_DRAWTEXT_VIRTUAL
34#endif
35
36class SkBounder;
37class SkBaseDevice;
38class SkDraw;
39class SkDrawFilter;
40class SkMetaData;
41class SkPicture;
42class SkRRect;
43class SkSurface;
44class SkSurface_Base;
45class GrContext;
46class GrRenderTarget;
47
48/** \class SkCanvas
49
50    A Canvas encapsulates all of the state about drawing into a device (bitmap).
51    This includes a reference to the device itself, and a stack of matrix/clip
52    values. For any given draw call (e.g. drawRect), the geometry of the object
53    being drawn is transformed by the concatenation of all the matrices in the
54    stack. The transformed geometry is clipped by the intersection of all of
55    the clips in the stack.
56
57    While the Canvas holds the state of the drawing device, the state (style)
58    of the object being drawn is held by the Paint, which is provided as a
59    parameter to each of the draw() methods. The Paint holds attributes such as
60    color, typeface, textSize, strokeWidth, shader (e.g. gradients, patterns),
61    etc.
62*/
63class SK_API SkCanvas : public SkRefCnt {
64public:
65    SK_DECLARE_INST_COUNT(SkCanvas)
66
67    /**
68     *  Attempt to allocate an offscreen raster canvas, matching the ImageInfo.
69     *  On success, return a new canvas that will draw into that offscreen.
70     *
71     *  The caller can access the pixels after drawing into this canvas by
72     *  calling readPixels() or peekPixels().
73     *
74     *  If the requested ImageInfo is opaque (either the colortype is
75     *  intrinsically opaque like RGB_565, or the info's alphatype is kOpaque)
76     *  then the pixel memory may be uninitialized. Otherwise, the pixel memory
77     *  will be initialized to 0, which is interpreted as transparent.
78     *
79     *  On failure, return NULL. This can fail for several reasons:
80     *  1. the memory allocation failed (e.g. request is too large)
81     *  2. invalid ImageInfo (e.g. negative dimensions)
82     *  3. unsupported ImageInfo for a canvas
83     *      - kUnknown_SkColorType, kIndex_8_SkColorType
84     *      - kIgnore_SkAlphaType
85     *      - this list is not complete, so others may also be unsupported
86     *
87     *  Note: it is valid to request a supported ImageInfo, but with zero
88     *  dimensions.
89     */
90    static SkCanvas* NewRaster(const SkImageInfo&);
91
92    static SkCanvas* NewRasterN32(int width, int height) {
93        return NewRaster(SkImageInfo::MakeN32Premul(width, height));
94    }
95
96    /**
97     *  Attempt to allocate raster canvas, matching the ImageInfo, that will draw directly into the
98     *  specified pixels. To access the pixels after drawing to them, the caller should call
99     *  flush() or call peekPixels(...).
100     *
101     *  On failure, return NULL. This can fail for several reasons:
102     *  1. invalid ImageInfo (e.g. negative dimensions)
103     *  2. unsupported ImageInfo for a canvas
104     *      - kUnknown_SkColorType, kIndex_8_SkColorType
105     *      - kIgnore_SkAlphaType
106     *      - this list is not complete, so others may also be unsupported
107     *
108     *  Note: it is valid to request a supported ImageInfo, but with zero
109     *  dimensions.
110     */
111    static SkCanvas* NewRasterDirect(const SkImageInfo&, void*, size_t);
112
113    static SkCanvas* NewRasterDirectN32(int width, int height, SkPMColor* pixels, size_t rowBytes) {
114        return NewRasterDirect(SkImageInfo::MakeN32Premul(width, height), pixels, rowBytes);
115    }
116
117    /**
118     *  Creates an empty canvas with no backing device/pixels, and zero
119     *  dimensions.
120     */
121    SkCanvas();
122
123    /**
124     *  Creates a canvas of the specified dimensions, but explicitly not backed
125     *  by any device/pixels. Typically this use used by subclasses who handle
126     *  the draw calls in some other way.
127     */
128    SkCanvas(int width, int height);
129
130    /** Construct a canvas with the specified device to draw into.
131
132        @param device   Specifies a device for the canvas to draw into.
133    */
134    explicit SkCanvas(SkBaseDevice* device);
135
136    /** Construct a canvas with the specified bitmap to draw into.
137        @param bitmap   Specifies a bitmap for the canvas to draw into. Its
138                        structure are copied to the canvas.
139    */
140    explicit SkCanvas(const SkBitmap& bitmap);
141    virtual ~SkCanvas();
142
143    SkMetaData& getMetaData();
144
145    /**
146     *  Return ImageInfo for this canvas. If the canvas is not backed by pixels
147     *  (cpu or gpu), then the info's ColorType will be kUnknown_SkColorType.
148     */
149    SkImageInfo imageInfo() const;
150
151    ///////////////////////////////////////////////////////////////////////////
152
153    /**
154     *  Trigger the immediate execution of all pending draw operations.
155     */
156    void flush();
157
158    /**
159     * Gets the size of the base or root layer in global canvas coordinates. The
160     * origin of the base layer is always (0,0). The current drawable area may be
161     * smaller (due to clipping or saveLayer).
162     */
163    SkISize getBaseLayerSize() const;
164
165    /**
166     *  DEPRECATED: call getBaseLayerSize
167     */
168    SkISize getDeviceSize() const { return this->getBaseLayerSize(); }
169
170    /**
171     *  DEPRECATED.
172     *  Return the canvas' device object, which may be null. The device holds
173     *  the bitmap of the pixels that the canvas draws into. The reference count
174     *  of the returned device is not changed by this call.
175     */
176    SkBaseDevice* getDevice() const;
177
178    /**
179     *  saveLayer() can create another device (which is later drawn onto
180     *  the previous device). getTopDevice() returns the top-most device current
181     *  installed. Note that this can change on other calls like save/restore,
182     *  so do not access this device after subsequent canvas calls.
183     *  The reference count of the device is not changed.
184     *
185     * @param updateMatrixClip If this is true, then before the device is
186     *        returned, we ensure that its has been notified about the current
187     *        matrix and clip. Note: this happens automatically when the device
188     *        is drawn to, but is optional here, as there is a small perf hit
189     *        sometimes.
190     */
191#ifndef SK_SUPPORT_LEGACY_GETTOPDEVICE
192private:
193#endif
194    SkBaseDevice* getTopDevice(bool updateMatrixClip = false) const;
195public:
196
197    /**
198     *  Create a new surface matching the specified info, one that attempts to
199     *  be maximally compatible when used with this canvas. If there is no matching Surface type,
200     *  NULL is returned.
201     */
202    SkSurface* newSurface(const SkImageInfo&);
203
204    /**
205     * Return the GPU context of the device that is associated with the canvas.
206     * For a canvas with non-GPU device, NULL is returned.
207     */
208    GrContext* getGrContext();
209
210    ///////////////////////////////////////////////////////////////////////////
211
212    /**
213     *  If the canvas has writable pixels in its top layer (and is not recording to a picture
214     *  or other non-raster target) and has direct access to its pixels (i.e. they are in
215     *  local RAM) return the address of those pixels, and if not null,
216     *  return the ImageInfo, rowBytes and origin. The returned address is only valid
217     *  while the canvas object is in scope and unchanged. Any API calls made on
218     *  canvas (or its parent surface if any) will invalidate the
219     *  returned address (and associated information).
220     *
221     *  On failure, returns NULL and the info, rowBytes, and origin parameters are ignored.
222     */
223    void* accessTopLayerPixels(SkImageInfo* info, size_t* rowBytes, SkIPoint* origin = NULL);
224
225    /**
226     *  If the canvas has readable pixels in its base layer (and is not recording to a picture
227     *  or other non-raster target) and has direct access to its pixels (i.e. they are in
228     *  local RAM) return the const-address of those pixels, and if not null,
229     *  return the ImageInfo and rowBytes. The returned address is only valid
230     *  while the canvas object is in scope and unchanged. Any API calls made on
231     *  canvas (or its parent surface if any) will invalidate the
232     *  returned address (and associated information).
233     *
234     *  On failure, returns NULL and the info and rowBytes parameters are
235     *  ignored.
236     */
237    const void* peekPixels(SkImageInfo* info, size_t* rowBytes);
238
239    /**
240     *  Copy the pixels from the base-layer into the specified buffer (pixels + rowBytes),
241     *  converting them into the requested format (SkImageInfo). The base-layer pixels are read
242     *  starting at the specified (x,y) location in the coordinate system of the base-layer.
243     *
244     *  The specified ImageInfo and (x,y) offset specifies a source rectangle
245     *
246     *      srcR(x, y, info.width(), info.height());
247     *
248     *  SrcR is intersected with the bounds of the base-layer. If this intersection is not empty,
249     *  then we have two sets of pixels (of equal size), the "src" specified by base-layer at (x,y)
250     *  and the "dst" by info+pixels+rowBytes. Replace the dst pixels with the corresponding src
251     *  pixels, performing any colortype/alphatype transformations needed (in the case where the
252     *  src and dst have different colortypes or alphatypes).
253     *
254     *  This call can fail, returning false, for several reasons:
255     *  - If the requested colortype/alphatype cannot be converted from the base-layer's types.
256     *  - If this canvas is not backed by pixels (e.g. picture or PDF)
257     */
258    bool readPixels(const SkImageInfo&, void* pixels, size_t rowBytes, int x, int y);
259
260    /**
261     *  Helper for calling readPixels(info, ...). This call will check if bitmap has been allocated.
262     *  If not, it will attempt to call allocPixels(). If this fails, it will return false. If not,
263     *  it calls through to readPixels(info, ...) and returns its result.
264     */
265    bool readPixels(SkBitmap* bitmap, int x, int y);
266
267    /**
268     *  Helper for allocating pixels and then calling readPixels(info, ...). The bitmap is resized
269     *  to the intersection of srcRect and the base-layer bounds. On success, pixels will be
270     *  allocated in bitmap and true returned. On failure, false is returned and bitmap will be
271     *  set to empty.
272     */
273    bool readPixels(const SkIRect& srcRect, SkBitmap* bitmap);
274
275    /**
276     *  This method affects the pixels in the base-layer, and operates in pixel coordinates,
277     *  ignoring the matrix and clip.
278     *
279     *  The specified ImageInfo and (x,y) offset specifies a rectangle: target.
280     *
281     *      target.setXYWH(x, y, info.width(), info.height());
282     *
283     *  Target is intersected with the bounds of the base-layer. If this intersection is not empty,
284     *  then we have two sets of pixels (of equal size), the "src" specified by info+pixels+rowBytes
285     *  and the "dst" by the canvas' backend. Replace the dst pixels with the corresponding src
286     *  pixels, performing any colortype/alphatype transformations needed (in the case where the
287     *  src and dst have different colortypes or alphatypes).
288     *
289     *  This call can fail, returning false, for several reasons:
290     *  - If the src colortype/alphatype cannot be converted to the canvas' types
291     *  - If this canvas is not backed by pixels (e.g. picture or PDF)
292     */
293    bool writePixels(const SkImageInfo&, const void* pixels, size_t rowBytes, int x, int y);
294
295    /**
296     *  Helper for calling writePixels(info, ...) by passing its pixels and rowbytes. If the bitmap
297     *  is just wrapping a texture, returns false and does nothing.
298     */
299    bool writePixels(const SkBitmap& bitmap, int x, int y);
300
301    ///////////////////////////////////////////////////////////////////////////
302
303    enum SaveFlags {
304        /** save the matrix state, restoring it on restore() */
305        kMatrix_SaveFlag            = 0x01,
306        /** save the clip state, restoring it on restore() */
307        kClip_SaveFlag              = 0x02,
308        /** the layer needs to support per-pixel alpha */
309        kHasAlphaLayer_SaveFlag     = 0x04,
310        /** the layer needs to support 8-bits per color component */
311        kFullColorLayer_SaveFlag    = 0x08,
312        /**
313         *  the layer should clip against the bounds argument
314         *
315         *  if SK_SUPPORT_LEGACY_CLIPTOLAYERFLAG is undefined, this is treated as always on.
316         */
317        kClipToLayer_SaveFlag       = 0x10,
318
319        // helper masks for common choices
320        kMatrixClip_SaveFlag        = 0x03,
321#ifdef SK_SUPPORT_LEGACY_CLIPTOLAYERFLAG
322        kARGB_NoClipLayer_SaveFlag  = 0x0F,
323#endif
324        kARGB_ClipLayer_SaveFlag    = 0x1F
325    };
326
327    /** This call saves the current matrix, clip, and drawFilter, and pushes a
328        copy onto a private stack. Subsequent calls to translate, scale,
329        rotate, skew, concat or clipRect, clipPath, and setDrawFilter all
330        operate on this copy.
331        When the balancing call to restore() is made, the previous matrix, clip,
332        and drawFilter are restored.
333
334        @return The value to pass to restoreToCount() to balance this save()
335    */
336    int save();
337
338    /** DEPRECATED - use save() instead.
339
340        This behaves the same as save(), but it allows fine-grained control of
341        which state bits to be saved (and subsequently restored).
342
343        @param flags The flags govern what portion of the Matrix/Clip/drawFilter
344                     state the save (and matching restore) effect. For example,
345                     if only kMatrix is specified, then only the matrix state
346                     will be pushed and popped. Likewise for the clip if kClip
347                     is specified.  However, the drawFilter is always affected
348                     by calls to save/restore.
349        @return The value to pass to restoreToCount() to balance this save()
350    */
351    SK_ATTR_EXTERNALLY_DEPRECATED("SaveFlags use is deprecated")
352    int save(SaveFlags flags);
353
354    /** This behaves the same as save(), but in addition it allocates an
355        offscreen bitmap. All drawing calls are directed there, and only when
356        the balancing call to restore() is made is that offscreen transfered to
357        the canvas (or the previous layer).
358        @param bounds (may be null) This rect, if non-null, is used as a hint to
359                      limit the size of the offscreen, and thus drawing may be
360                      clipped to it, though that clipping is not guaranteed to
361                      happen. If exact clipping is desired, use clipRect().
362        @param paint (may be null) This is copied, and is applied to the
363                     offscreen when restore() is called
364        @return The value to pass to restoreToCount() to balance this save()
365    */
366    int saveLayer(const SkRect* bounds, const SkPaint* paint);
367
368    /** DEPRECATED - use saveLayer(const SkRect*, const SkPaint*) instead.
369
370        This behaves the same as saveLayer(const SkRect*, const SkPaint*),
371        but it allows fine-grained control of which state bits to be saved
372        (and subsequently restored).
373
374        @param bounds (may be null) This rect, if non-null, is used as a hint to
375                      limit the size of the offscreen, and thus drawing may be
376                      clipped to it, though that clipping is not guaranteed to
377                      happen. If exact clipping is desired, use clipRect().
378        @param paint (may be null) This is copied, and is applied to the
379                     offscreen when restore() is called
380        @param flags  LayerFlags
381        @return The value to pass to restoreToCount() to balance this save()
382    */
383    SK_ATTR_EXTERNALLY_DEPRECATED("SaveFlags use is deprecated")
384    int saveLayer(const SkRect* bounds, const SkPaint* paint, SaveFlags flags);
385
386    /** This behaves the same as save(), but in addition it allocates an
387        offscreen bitmap. All drawing calls are directed there, and only when
388        the balancing call to restore() is made is that offscreen transfered to
389        the canvas (or the previous layer).
390        @param bounds (may be null) This rect, if non-null, is used as a hint to
391                      limit the size of the offscreen, and thus drawing may be
392                      clipped to it, though that clipping is not guaranteed to
393                      happen. If exact clipping is desired, use clipRect().
394        @param alpha  This is applied to the offscreen when restore() is called.
395        @return The value to pass to restoreToCount() to balance this save()
396    */
397    int saveLayerAlpha(const SkRect* bounds, U8CPU alpha);
398
399    /** DEPRECATED - use saveLayerAlpha(const SkRect*, U8CPU) instead.
400
401        This behaves the same as saveLayerAlpha(const SkRect*, U8CPU),
402        but it allows fine-grained control of which state bits to be saved
403        (and subsequently restored).
404
405        @param bounds (may be null) This rect, if non-null, is used as a hint to
406                      limit the size of the offscreen, and thus drawing may be
407                      clipped to it, though that clipping is not guaranteed to
408                      happen. If exact clipping is desired, use clipRect().
409        @param alpha  This is applied to the offscreen when restore() is called.
410        @param flags  LayerFlags
411        @return The value to pass to restoreToCount() to balance this save()
412    */
413    SK_ATTR_EXTERNALLY_DEPRECATED("SaveFlags use is deprecated")
414    int saveLayerAlpha(const SkRect* bounds, U8CPU alpha, SaveFlags flags);
415
416    /** This call balances a previous call to save(), and is used to remove all
417        modifications to the matrix/clip/drawFilter state since the last save
418        call.
419        It is an error to call restore() more times than save() was called.
420    */
421    void restore();
422
423    /** Returns the number of matrix/clip states on the SkCanvas' private stack.
424        This will equal # save() calls - # restore() calls + 1. The save count on
425        a new canvas is 1.
426    */
427    int getSaveCount() const;
428
429    /** Efficient way to pop any calls to save() that happened after the save
430        count reached saveCount. It is an error for saveCount to be greater than
431        getSaveCount(). To pop all the way back to the initial matrix/clip context
432        pass saveCount == 1.
433        @param saveCount    The number of save() levels to restore from
434    */
435    void restoreToCount(int saveCount);
436
437    /** Returns true if drawing is currently going to a layer (from saveLayer)
438     *  rather than to the root device.
439     */
440    virtual bool isDrawingToLayer() const;
441
442    /** Preconcat the current matrix with the specified translation
443        @param dx   The distance to translate in X
444        @param dy   The distance to translate in Y
445    */
446    void translate(SkScalar dx, SkScalar dy);
447
448    /** Preconcat the current matrix with the specified scale.
449        @param sx   The amount to scale in X
450        @param sy   The amount to scale in Y
451    */
452    void scale(SkScalar sx, SkScalar sy);
453
454    /** Preconcat the current matrix with the specified rotation.
455        @param degrees  The amount to rotate, in degrees
456    */
457    void rotate(SkScalar degrees);
458
459    /** Preconcat the current matrix with the specified skew.
460        @param sx   The amount to skew in X
461        @param sy   The amount to skew in Y
462    */
463    void skew(SkScalar sx, SkScalar sy);
464
465    /** Preconcat the current matrix with the specified matrix.
466        @param matrix   The matrix to preconcatenate with the current matrix
467    */
468    void concat(const SkMatrix& matrix);
469
470    /** Replace the current matrix with a copy of the specified matrix.
471        @param matrix The matrix that will be copied into the current matrix.
472    */
473    void setMatrix(const SkMatrix& matrix);
474
475    /** Helper for setMatrix(identity). Sets the current matrix to identity.
476    */
477    void resetMatrix();
478
479    /**
480     *  Modify the current clip with the specified rectangle.
481     *  @param rect The rect to combine with the current clip
482     *  @param op The region op to apply to the current clip
483     *  @param doAntiAlias true if the clip should be antialiased
484     */
485    void clipRect(const SkRect& rect,
486                  SkRegion::Op op = SkRegion::kIntersect_Op,
487                  bool doAntiAlias = false);
488
489    /**
490     *  Modify the current clip with the specified SkRRect.
491     *  @param rrect The rrect to combine with the current clip
492     *  @param op The region op to apply to the current clip
493     *  @param doAntiAlias true if the clip should be antialiased
494     */
495    void clipRRect(const SkRRect& rrect,
496                   SkRegion::Op op = SkRegion::kIntersect_Op,
497                   bool doAntiAlias = false);
498
499    /**
500     *  Modify the current clip with the specified path.
501     *  @param path The path to combine with the current clip
502     *  @param op The region op to apply to the current clip
503     *  @param doAntiAlias true if the clip should be antialiased
504     */
505    void clipPath(const SkPath& path,
506                  SkRegion::Op op = SkRegion::kIntersect_Op,
507                  bool doAntiAlias = false);
508
509    /** EXPERIMENTAL -- only used for testing
510        Set to false to force clips to be hard, even if doAntiAlias=true is
511        passed to clipRect or clipPath.
512     */
513    void setAllowSoftClip(bool allow) {
514        fAllowSoftClip = allow;
515    }
516
517    /** EXPERIMENTAL -- only used for testing
518        Set to simplify clip stack using path ops.
519     */
520    void setAllowSimplifyClip(bool allow) {
521        fAllowSimplifyClip = allow;
522    }
523
524    /** Modify the current clip with the specified region. Note that unlike
525        clipRect() and clipPath() which transform their arguments by the current
526        matrix, clipRegion() assumes its argument is already in device
527        coordinates, and so no transformation is performed.
528        @param deviceRgn    The region to apply to the current clip
529        @param op The region op to apply to the current clip
530    */
531    void clipRegion(const SkRegion& deviceRgn,
532                    SkRegion::Op op = SkRegion::kIntersect_Op);
533
534    /** Helper for clipRegion(rgn, kReplace_Op). Sets the current clip to the
535        specified region. This does not intersect or in any other way account
536        for the existing clip region.
537        @param deviceRgn The region to copy into the current clip.
538    */
539    void setClipRegion(const SkRegion& deviceRgn) {
540        this->clipRegion(deviceRgn, SkRegion::kReplace_Op);
541    }
542
543    /** Return true if the specified rectangle, after being transformed by the
544        current matrix, would lie completely outside of the current clip. Call
545        this to check if an area you intend to draw into is clipped out (and
546        therefore you can skip making the draw calls).
547        @param rect the rect to compare with the current clip
548        @return true if the rect (transformed by the canvas' matrix) does not
549                     intersect with the canvas' clip
550    */
551    bool quickReject(const SkRect& rect) const;
552
553    /** Return true if the specified path, after being transformed by the
554        current matrix, would lie completely outside of the current clip. Call
555        this to check if an area you intend to draw into is clipped out (and
556        therefore you can skip making the draw calls). Note, for speed it may
557        return false even if the path itself might not intersect the clip
558        (i.e. the bounds of the path intersects, but the path does not).
559        @param path The path to compare with the current clip
560        @return true if the path (transformed by the canvas' matrix) does not
561                     intersect with the canvas' clip
562    */
563    bool quickReject(const SkPath& path) const;
564
565    /** Return true if the horizontal band specified by top and bottom is
566        completely clipped out. This is a conservative calculation, meaning
567        that it is possible that if the method returns false, the band may still
568        in fact be clipped out, but the converse is not true. If this method
569        returns true, then the band is guaranteed to be clipped out.
570        @param top  The top of the horizontal band to compare with the clip
571        @param bottom The bottom of the horizontal and to compare with the clip
572        @return true if the horizontal band is completely clipped out (i.e. does
573                     not intersect the current clip)
574    */
575    bool quickRejectY(SkScalar top, SkScalar bottom) const {
576        SkASSERT(top <= bottom);
577
578#ifndef SK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT
579        // TODO: add a hasPerspective method similar to getLocalClipBounds. This
580        // would cache the SkMatrix::hasPerspective result. Alternatively, have
581        // the MC stack just set a hasPerspective boolean as it is updated.
582        if (this->getTotalMatrix().hasPerspective()) {
583            // TODO: consider implementing some half-plane test between the
584            // two Y planes and the device-bounds (i.e., project the top and
585            // bottom Y planes and then determine if the clip bounds is completely
586            // outside either one).
587            return false;
588        }
589#endif
590
591        const SkRect& clipR = this->getLocalClipBounds();
592        // In the case where the clip is empty and we are provided with a
593        // negative top and positive bottom parameter then this test will return
594        // false even though it will be clipped. We have chosen to exclude that
595        // check as it is rare and would result double the comparisons.
596        return top >= clipR.fBottom || bottom <= clipR.fTop;
597    }
598
599    /** Return the bounds of the current clip (in local coordinates) in the
600        bounds parameter, and return true if it is non-empty. This can be useful
601        in a way similar to quickReject, in that it tells you that drawing
602        outside of these bounds will be clipped out.
603    */
604    virtual bool getClipBounds(SkRect* bounds) const;
605
606    /** Return the bounds of the current clip, in device coordinates; returns
607        true if non-empty. Maybe faster than getting the clip explicitly and
608        then taking its bounds.
609    */
610    virtual bool getClipDeviceBounds(SkIRect* bounds) const;
611
612
613    /** Fill the entire canvas' bitmap (restricted to the current clip) with the
614        specified ARGB color, using the specified mode.
615        @param a    the alpha component (0..255) of the color to fill the canvas
616        @param r    the red component (0..255) of the color to fill the canvas
617        @param g    the green component (0..255) of the color to fill the canvas
618        @param b    the blue component (0..255) of the color to fill the canvas
619        @param mode the mode to apply the color in (defaults to SrcOver)
620    */
621    void drawARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b,
622                  SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode);
623
624    /** Fill the entire canvas' bitmap (restricted to the current clip) with the
625        specified color and mode.
626        @param color    the color to draw with
627        @param mode the mode to apply the color in (defaults to SrcOver)
628    */
629    void drawColor(SkColor color,
630                   SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode);
631
632    /**
633     *  This erases the entire drawing surface to the specified color,
634     *  irrespective of the clip. It does not blend with the previous pixels,
635     *  but always overwrites them.
636     *
637     *  It is roughly equivalent to the following:
638     *      canvas.save();
639     *      canvas.clipRect(hugeRect, kReplace_Op);
640     *      paint.setColor(color);
641     *      paint.setXfermodeMode(kSrc_Mode);
642     *      canvas.drawPaint(paint);
643     *      canvas.restore();
644     *  though it is almost always much more efficient.
645     */
646    virtual void clear(SkColor);
647
648    /**
649     * This makes the contents of the canvas undefined. Subsequent calls that
650     * require reading the canvas contents will produce undefined results. Examples
651     * include blending and readPixels. The actual implementation is backend-
652     * dependent and one legal implementation is to do nothing. Like clear(), this
653     * ignores the clip.
654     *
655     * This function should only be called if the caller intends to subsequently
656     * draw to the canvas. The canvas may do real work at discard() time in order
657     * to optimize performance on subsequent draws. Thus, if you call this and then
658     * never draw to the canvas subsequently you may pay a perfomance penalty.
659     */
660    void discard() { this->onDiscard(); }
661
662    /**
663     *  Fill the entire canvas' bitmap (restricted to the current clip) with the
664     *  specified paint.
665     *  @param paint    The paint used to fill the canvas
666     */
667    virtual void drawPaint(const SkPaint& paint);
668
669    enum PointMode {
670        /** drawPoints draws each point separately */
671        kPoints_PointMode,
672        /** drawPoints draws each pair of points as a line segment */
673        kLines_PointMode,
674        /** drawPoints draws the array of points as a polygon */
675        kPolygon_PointMode
676    };
677
678    /** Draw a series of points, interpreted based on the PointMode mode. For
679        all modes, the count parameter is interpreted as the total number of
680        points. For kLine mode, count/2 line segments are drawn.
681        For kPoint mode, each point is drawn centered at its coordinate, and its
682        size is specified by the paint's stroke-width. It draws as a square,
683        unless the paint's cap-type is round, in which the points are drawn as
684        circles.
685        For kLine mode, each pair of points is drawn as a line segment,
686        respecting the paint's settings for cap/join/width.
687        For kPolygon mode, the entire array is drawn as a series of connected
688        line segments.
689        Note that, while similar, kLine and kPolygon modes draw slightly
690        differently than the equivalent path built with a series of moveto,
691        lineto calls, in that the path will draw all of its contours at once,
692        with no interactions if contours intersect each other (think XOR
693        xfermode). drawPoints always draws each element one at a time.
694        @param mode     PointMode specifying how to draw the array of points.
695        @param count    The number of points in the array
696        @param pts      Array of points to draw
697        @param paint    The paint used to draw the points
698    */
699    virtual void drawPoints(PointMode mode, size_t count, const SkPoint pts[],
700                            const SkPaint& paint);
701
702    /** Helper method for drawing a single point. See drawPoints() for a more
703        details.
704    */
705    void drawPoint(SkScalar x, SkScalar y, const SkPaint& paint);
706
707    /** Draws a single pixel in the specified color.
708        @param x        The X coordinate of which pixel to draw
709        @param y        The Y coordiante of which pixel to draw
710        @param color    The color to draw
711    */
712    void drawPoint(SkScalar x, SkScalar y, SkColor color);
713
714    /** Draw a line segment with the specified start and stop x,y coordinates,
715        using the specified paint. NOTE: since a line is always "framed", the
716        paint's Style is ignored.
717        @param x0    The x-coordinate of the start point of the line
718        @param y0    The y-coordinate of the start point of the line
719        @param x1    The x-coordinate of the end point of the line
720        @param y1    The y-coordinate of the end point of the line
721        @param paint The paint used to draw the line
722    */
723    void drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1,
724                  const SkPaint& paint);
725
726    /** Draw the specified rectangle using the specified paint. The rectangle
727        will be filled or stroked based on the Style in the paint.
728        @param rect     The rect to be drawn
729        @param paint    The paint used to draw the rect
730    */
731    virtual void drawRect(const SkRect& rect, const SkPaint& paint);
732
733    /** Draw the specified rectangle using the specified paint. The rectangle
734        will be filled or framed based on the Style in the paint.
735        @param rect     The rect to be drawn
736        @param paint    The paint used to draw the rect
737    */
738    void drawIRect(const SkIRect& rect, const SkPaint& paint) {
739        SkRect r;
740        r.set(rect);    // promotes the ints to scalars
741        this->drawRect(r, paint);
742    }
743
744    /** Draw the specified rectangle using the specified paint. The rectangle
745        will be filled or framed based on the Style in the paint.
746        @param left     The left side of the rectangle to be drawn
747        @param top      The top side of the rectangle to be drawn
748        @param right    The right side of the rectangle to be drawn
749        @param bottom   The bottom side of the rectangle to be drawn
750        @param paint    The paint used to draw the rect
751    */
752    void drawRectCoords(SkScalar left, SkScalar top, SkScalar right,
753                        SkScalar bottom, const SkPaint& paint);
754
755    /** Draw the specified oval using the specified paint. The oval will be
756        filled or framed based on the Style in the paint.
757        @param oval     The rectangle bounds of the oval to be drawn
758        @param paint    The paint used to draw the oval
759    */
760    virtual void drawOval(const SkRect& oval, const SkPaint&);
761
762    /**
763     *  Draw the specified RRect using the specified paint The rrect will be filled or stroked
764     *  based on the Style in the paint.
765     *
766     *  @param rrect    The round-rect to draw
767     *  @param paint    The paint used to draw the round-rect
768     */
769    virtual void drawRRect(const SkRRect& rrect, const SkPaint& paint);
770
771    /**
772     *  Draw the annulus formed by the outer and inner rrects. The results
773     *  are undefined if the outer does not contain the inner.
774     */
775    void drawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint&);
776
777    /** Draw the specified circle using the specified paint. If radius is <= 0,
778        then nothing will be drawn. The circle will be filled
779        or framed based on the Style in the paint.
780        @param cx       The x-coordinate of the center of the cirle to be drawn
781        @param cy       The y-coordinate of the center of the cirle to be drawn
782        @param radius   The radius of the cirle to be drawn
783        @param paint    The paint used to draw the circle
784    */
785    void drawCircle(SkScalar cx, SkScalar cy, SkScalar radius,
786                    const SkPaint& paint);
787
788    /** Draw the specified arc, which will be scaled to fit inside the
789        specified oval. If the sweep angle is >= 360, then the oval is drawn
790        completely. Note that this differs slightly from SkPath::arcTo, which
791        treats the sweep angle mod 360.
792        @param oval The bounds of oval used to define the shape of the arc
793        @param startAngle Starting angle (in degrees) where the arc begins
794        @param sweepAngle Sweep angle (in degrees) measured clockwise
795        @param useCenter true means include the center of the oval. For filling
796                         this will draw a wedge. False means just use the arc.
797        @param paint    The paint used to draw the arc
798    */
799    void drawArc(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle,
800                 bool useCenter, const SkPaint& paint);
801
802    /** Draw the specified round-rect using the specified paint. The round-rect
803        will be filled or framed based on the Style in the paint.
804        @param rect     The rectangular bounds of the roundRect to be drawn
805        @param rx       The x-radius of the oval used to round the corners
806        @param ry       The y-radius of the oval used to round the corners
807        @param paint    The paint used to draw the roundRect
808    */
809    void drawRoundRect(const SkRect& rect, SkScalar rx, SkScalar ry,
810                       const SkPaint& paint);
811
812    /** Draw the specified path using the specified paint. The path will be
813        filled or framed based on the Style in the paint.
814        @param path     The path to be drawn
815        @param paint    The paint used to draw the path
816    */
817    virtual void drawPath(const SkPath& path, const SkPaint& paint);
818
819    /** Draw the specified bitmap, with its top/left corner at (x,y), using the
820        specified paint, transformed by the current matrix. Note: if the paint
821        contains a maskfilter that generates a mask which extends beyond the
822        bitmap's original width/height, then the bitmap will be drawn as if it
823        were in a Shader with CLAMP mode. Thus the color outside of the original
824        width/height will be the edge color replicated.
825
826        If a shader is present on the paint it will be ignored, except in the
827        case where the bitmap is kAlpha_8_SkColorType. In that case, the color is
828        generated by the shader.
829
830        @param bitmap   The bitmap to be drawn
831        @param left     The position of the left side of the bitmap being drawn
832        @param top      The position of the top side of the bitmap being drawn
833        @param paint    The paint used to draw the bitmap, or NULL
834    */
835    virtual void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
836                            const SkPaint* paint = NULL);
837
838    enum DrawBitmapRectFlags {
839        kNone_DrawBitmapRectFlag            = 0x0,
840        /**
841         *  When filtering is enabled, allow the color samples outside of
842         *  the src rect (but still in the src bitmap) to bleed into the
843         *  drawn portion
844         */
845        kBleed_DrawBitmapRectFlag           = 0x1,
846    };
847
848    /** Draw the specified bitmap, with the specified matrix applied (before the
849        canvas' matrix is applied).
850        @param bitmap   The bitmap to be drawn
851        @param src      Optional: specify the subset of the bitmap to be drawn
852        @param dst      The destination rectangle where the scaled/translated
853                        image will be drawn
854        @param paint    The paint used to draw the bitmap, or NULL
855    */
856    virtual void drawBitmapRectToRect(const SkBitmap& bitmap, const SkRect* src,
857                                      const SkRect& dst,
858                                      const SkPaint* paint = NULL,
859                                      DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag);
860
861    void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst,
862                        const SkPaint* paint = NULL) {
863        this->drawBitmapRectToRect(bitmap, NULL, dst, paint, kNone_DrawBitmapRectFlag);
864    }
865
866    void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* isrc,
867                        const SkRect& dst, const SkPaint* paint = NULL,
868                        DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag) {
869        SkRect realSrcStorage;
870        SkRect* realSrcPtr = NULL;
871        if (isrc) {
872            realSrcStorage.set(*isrc);
873            realSrcPtr = &realSrcStorage;
874        }
875        this->drawBitmapRectToRect(bitmap, realSrcPtr, dst, paint, flags);
876    }
877
878    virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m,
879                                  const SkPaint* paint = NULL);
880
881    /**
882     *  Draw the bitmap stretched differentially to fit into dst.
883     *  center is a rect within the bitmap, and logically divides the bitmap
884     *  into 9 sections (3x3). For example, if the middle pixel of a [5x5]
885     *  bitmap is the "center", then the center-rect should be [2, 2, 3, 3].
886     *
887     *  If the dst is >= the bitmap size, then...
888     *  - The 4 corners are not stretched at all.
889     *  - The sides are stretched in only one axis.
890     *  - The center is stretched in both axes.
891     * Else, for each axis where dst < bitmap,
892     *  - The corners shrink proportionally
893     *  - The sides (along the shrink axis) and center are not drawn
894     */
895    virtual void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
896                                const SkRect& dst, const SkPaint* paint = NULL);
897
898    /** Draw the specified bitmap, with its top/left corner at (x,y),
899        NOT transformed by the current matrix. Note: if the paint
900        contains a maskfilter that generates a mask which extends beyond the
901        bitmap's original width/height, then the bitmap will be drawn as if it
902        were in a Shader with CLAMP mode. Thus the color outside of the original
903        width/height will be the edge color replicated.
904        @param bitmap   The bitmap to be drawn
905        @param left     The position of the left side of the bitmap being drawn
906        @param top      The position of the top side of the bitmap being drawn
907        @param paint    The paint used to draw the bitmap, or NULL
908    */
909    virtual void drawSprite(const SkBitmap& bitmap, int left, int top,
910                            const SkPaint* paint = NULL);
911
912    /** Draw the text, with origin at (x,y), using the specified paint.
913        The origin is interpreted based on the Align setting in the paint.
914        @param text The text to be drawn
915        @param byteLength   The number of bytes to read from the text parameter
916        @param x        The x-coordinate of the origin of the text being drawn
917        @param y        The y-coordinate of the origin of the text being drawn
918        @param paint    The paint used for the text (e.g. color, size, style)
919    */
920    SK_LEGACY_DRAWTEXT_VIRTUAL void drawText(const void* text, size_t byteLength, SkScalar x,
921                          SkScalar y, const SkPaint& paint);
922
923    /** Draw the text, with each character/glyph origin specified by the pos[]
924        array. The origin is interpreted by the Align setting in the paint.
925        @param text The text to be drawn
926        @param byteLength   The number of bytes to read from the text parameter
927        @param pos      Array of positions, used to position each character
928        @param paint    The paint used for the text (e.g. color, size, style)
929        */
930    SK_LEGACY_DRAWTEXT_VIRTUAL void drawPosText(const void* text, size_t byteLength,
931                             const SkPoint pos[], const SkPaint& paint);
932
933    /** Draw the text, with each character/glyph origin specified by the x
934        coordinate taken from the xpos[] array, and the y from the constY param.
935        The origin is interpreted by the Align setting in the paint.
936        @param text The text to be drawn
937        @param byteLength   The number of bytes to read from the text parameter
938        @param xpos     Array of x-positions, used to position each character
939        @param constY   The shared Y coordinate for all of the positions
940        @param paint    The paint used for the text (e.g. color, size, style)
941        */
942    SK_LEGACY_DRAWTEXT_VIRTUAL void drawPosTextH(const void* text, size_t byteLength,
943                              const SkScalar xpos[], SkScalar constY,
944                              const SkPaint& paint);
945
946    /** Draw the text, with origin at (x,y), using the specified paint, along
947        the specified path. The paint's Align setting determins where along the
948        path to start the text.
949        @param text The text to be drawn
950        @param byteLength   The number of bytes to read from the text parameter
951        @param path         The path the text should follow for its baseline
952        @param hOffset      The distance along the path to add to the text's
953                            starting position
954        @param vOffset      The distance above(-) or below(+) the path to
955                            position the text
956        @param paint        The paint used for the text
957    */
958    void drawTextOnPathHV(const void* text, size_t byteLength,
959                          const SkPath& path, SkScalar hOffset,
960                          SkScalar vOffset, const SkPaint& paint);
961
962    /** Draw the text, with origin at (x,y), using the specified paint, along
963        the specified path. The paint's Align setting determins where along the
964        path to start the text.
965        @param text The text to be drawn
966        @param byteLength   The number of bytes to read from the text parameter
967        @param path         The path the text should follow for its baseline
968        @param matrix       (may be null) Applied to the text before it is
969                            mapped onto the path
970        @param paint        The paint used for the text
971        */
972    SK_LEGACY_DRAWTEXT_VIRTUAL void drawTextOnPath(const void* text, size_t byteLength,
973                                const SkPath& path, const SkMatrix* matrix,
974                                const SkPaint& paint);
975
976    /** PRIVATE / EXPERIMENTAL -- do not call
977        Perform back-end analysis/optimization of a picture. This may attach
978        optimization data to the picture which can be used by a later
979        drawPicture call.
980        @param picture The recorded drawing commands to analyze/optimize
981    */
982    void EXPERIMENTAL_optimize(SkPicture* picture);
983
984    /** PRIVATE / EXPERIMENTAL -- do not call
985        Purge all the discardable optimization information associated with
986        'picture'. If NULL is passed in, purge all discardable information.
987    */
988    void EXPERIMENTAL_purge(SkPicture* picture);
989
990    /** Draw the picture into this canvas. This method effective brackets the
991        playback of the picture's draw calls with save/restore, so the state
992        of this canvas will be unchanged after this call.
993        @param picture The recorded drawing commands to playback into this
994                       canvas.
995    */
996    virtual void drawPicture(SkPicture& picture);
997
998    enum VertexMode {
999        kTriangles_VertexMode,
1000        kTriangleStrip_VertexMode,
1001        kTriangleFan_VertexMode
1002    };
1003
1004    /** Draw the array of vertices, interpreted as triangles (based on mode).
1005
1006        If both textures and vertex-colors are NULL, it strokes hairlines with
1007        the paint's color. This behavior is a useful debugging mode to visualize
1008        the mesh.
1009
1010        @param vmode How to interpret the array of vertices
1011        @param vertexCount The number of points in the vertices array (and
1012                    corresponding texs and colors arrays if non-null)
1013        @param vertices Array of vertices for the mesh
1014        @param texs May be null. If not null, specifies the coordinate
1015                    in _texture_ space (not uv space) for each vertex.
1016        @param colors May be null. If not null, specifies a color for each
1017                      vertex, to be interpolated across the triangle.
1018        @param xmode Used if both texs and colors are present. In this
1019                    case the colors are combined with the texture using mode,
1020                    before being drawn using the paint. If mode is null, then
1021                    kModulate_Mode is used.
1022        @param indices If not null, array of indices to reference into the
1023                    vertex (texs, colors) array.
1024        @param indexCount number of entries in the indices array (if not null)
1025        @param paint Specifies the shader/texture if present.
1026    */
1027    virtual void drawVertices(VertexMode vmode, int vertexCount,
1028                              const SkPoint vertices[], const SkPoint texs[],
1029                              const SkColor colors[], SkXfermode* xmode,
1030                              const uint16_t indices[], int indexCount,
1031                              const SkPaint& paint);
1032
1033    /** Send a blob of data to the canvas.
1034        For canvases that draw, this call is effectively a no-op, as the data
1035        is not parsed, but just ignored. However, this call exists for
1036        subclasses like SkPicture's recording canvas, that can store the data
1037        and then play it back later (via another call to drawData).
1038     */
1039    virtual void drawData(const void* data, size_t length) {
1040        // do nothing. Subclasses may do something with the data
1041    }
1042
1043    /** Add comments. beginCommentGroup/endCommentGroup open/close a new group.
1044        Each comment added via addComment is notionally attached to its
1045        enclosing group. Top-level comments simply belong to no group.
1046     */
1047    virtual void beginCommentGroup(const char* description) {
1048        // do nothing. Subclasses may do something
1049    }
1050    virtual void addComment(const char* kywd, const char* value) {
1051        // do nothing. Subclasses may do something
1052    }
1053    virtual void endCommentGroup() {
1054        // do nothing. Subclasses may do something
1055    }
1056
1057    /**
1058     *  With this call the client asserts that subsequent draw operations (up to the
1059     *  matching popCull()) are fully contained within the given bounding box. The assertion
1060     *  is not enforced, but the information might be used to quick-reject command blocks,
1061     *  so an incorrect bounding box may result in incomplete rendering.
1062     */
1063    void pushCull(const SkRect& cullRect);
1064
1065    /**
1066     *  Terminates the current culling block, and restores the previous one (if any).
1067     */
1068    void popCull();
1069
1070    //////////////////////////////////////////////////////////////////////////
1071
1072    /** Get the current bounder object.
1073        The bounder's reference count is unchaged.
1074        @return the canva's bounder (or NULL).
1075    */
1076    SkBounder*  getBounder() const { return fBounder; }
1077
1078    /** Set a new bounder (or NULL).
1079        Pass NULL to clear any previous bounder.
1080        As a convenience, the parameter passed is also returned.
1081        If a previous bounder exists, its reference count is decremented.
1082        If bounder is not NULL, its reference count is incremented.
1083        @param bounder the new bounder (or NULL) to be installed in the canvas
1084        @return the set bounder object
1085    */
1086    virtual SkBounder* setBounder(SkBounder* bounder);
1087
1088    /** Get the current filter object. The filter's reference count is not
1089        affected. The filter is saved/restored, just like the matrix and clip.
1090        @return the canvas' filter (or NULL).
1091    */
1092    SkDrawFilter* getDrawFilter() const;
1093
1094    /** Set the new filter (or NULL). Pass NULL to clear any existing filter.
1095        As a convenience, the parameter is returned. If an existing filter
1096        exists, its refcnt is decrement. If the new filter is not null, its
1097        refcnt is incremented. The filter is saved/restored, just like the
1098        matrix and clip.
1099        @param filter the new filter (or NULL)
1100        @return the new filter
1101    */
1102    virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter);
1103
1104    //////////////////////////////////////////////////////////////////////////
1105
1106    /**
1107     *  Return true if the current clip is empty (i.e. nothing will draw).
1108     *  Note: this is not always a free call, so it should not be used
1109     *  more often than necessary. However, once the canvas has computed this
1110     *  result, subsequent calls will be cheap (until the clip state changes,
1111     *  which can happen on any clip..() or restore() call.
1112     */
1113    virtual bool isClipEmpty() const;
1114
1115    /**
1116     *  Returns true if the current clip is just a (non-empty) rectangle.
1117     *  Returns false if the clip is empty, or if it is complex.
1118     */
1119    virtual bool isClipRect() const;
1120
1121    /** Return the current matrix on the canvas.
1122        This does not account for the translate in any of the devices.
1123        @return The current matrix on the canvas.
1124    */
1125    const SkMatrix& getTotalMatrix() const;
1126
1127#ifdef SK_SUPPORT_LEGACY_GETCLIPTYPE
1128    enum ClipType {
1129        kEmpty_ClipType = 0,
1130        kRect_ClipType,
1131        kComplex_ClipType
1132    };
1133    /** Returns a description of the total clip; may be cheaper than
1134        getting the clip and querying it directly.
1135    */
1136    virtual ClipType getClipType() const;
1137#endif
1138
1139#ifdef SK_SUPPORT_LEGACY_GETTOTALCLIP
1140    /** DEPRECATED -- need to move this guy to private/friend
1141     *  Return the current device clip (concatenation of all clip calls).
1142     *  This does not account for the translate in any of the devices.
1143     *  @return the current device clip (concatenation of all clip calls).
1144     */
1145    const SkRegion& getTotalClip() const;
1146#endif
1147
1148    /** Return the clip stack. The clip stack stores all the individual
1149     *  clips organized by the save/restore frame in which they were
1150     *  added.
1151     *  @return the current clip stack ("list" of individual clip elements)
1152     */
1153    const SkClipStack* getClipStack() const {
1154        return &fClipStack;
1155    }
1156
1157    class ClipVisitor {
1158    public:
1159        virtual ~ClipVisitor();
1160        virtual void clipRect(const SkRect&, SkRegion::Op, bool antialias) = 0;
1161        virtual void clipRRect(const SkRRect&, SkRegion::Op, bool antialias) = 0;
1162        virtual void clipPath(const SkPath&, SkRegion::Op, bool antialias) = 0;
1163    };
1164
1165    /**
1166     *  Replays the clip operations, back to front, that have been applied to
1167     *  the canvas, calling the appropriate method on the visitor for each
1168     *  clip. All clips have already been transformed into device space.
1169     */
1170    void replayClips(ClipVisitor*) const;
1171
1172    ///////////////////////////////////////////////////////////////////////////
1173
1174    /** After calling saveLayer(), there can be any number of devices that make
1175        up the top-most drawing area. LayerIter can be used to iterate through
1176        those devices. Note that the iterator is only valid until the next API
1177        call made on the canvas. Ownership of all pointers in the iterator stays
1178        with the canvas, so none of them should be modified or deleted.
1179    */
1180    class SK_API LayerIter /*: SkNoncopyable*/ {
1181    public:
1182        /** Initialize iterator with canvas, and set values for 1st device */
1183        LayerIter(SkCanvas*, bool skipEmptyClips);
1184        ~LayerIter();
1185
1186        /** Return true if the iterator is done */
1187        bool done() const { return fDone; }
1188        /** Cycle to the next device */
1189        void next();
1190
1191        // These reflect the current device in the iterator
1192
1193        SkBaseDevice*   device() const;
1194        const SkMatrix& matrix() const;
1195        const SkRegion& clip() const;
1196        const SkPaint&  paint() const;
1197        int             x() const;
1198        int             y() const;
1199
1200    private:
1201        // used to embed the SkDrawIter object directly in our instance, w/o
1202        // having to expose that class def to the public. There is an assert
1203        // in our constructor to ensure that fStorage is large enough
1204        // (though needs to be a compile-time-assert!). We use intptr_t to work
1205        // safely with 32 and 64 bit machines (to ensure the storage is enough)
1206        intptr_t          fStorage[32];
1207        class SkDrawIter* fImpl;    // this points at fStorage
1208        SkPaint           fDefaultPaint;
1209        bool              fDone;
1210    };
1211
1212    // don't call
1213    const SkRegion& internal_private_getTotalClip() const;
1214    // don't call
1215    void internal_private_getTotalClipAsPath(SkPath*) const;
1216    // don't call
1217    GrRenderTarget* internal_private_accessTopLayerRenderTarget();
1218
1219protected:
1220    // default impl defers to getDevice()->newSurface(info)
1221    virtual SkSurface* onNewSurface(const SkImageInfo&);
1222
1223    // default impl defers to its device
1224    virtual const void* onPeekPixels(SkImageInfo*, size_t* rowBytes);
1225    virtual void* onAccessTopLayerPixels(SkImageInfo*, size_t* rowBytes);
1226
1227    // Subclass save/restore notifiers.
1228    // Overriders should call the corresponding INHERITED method up the inheritance chain.
1229    // willSaveLayer()'s return value may suppress full layer allocation.
1230    enum SaveLayerStrategy {
1231        kFullLayer_SaveLayerStrategy,
1232        kNoLayer_SaveLayerStrategy
1233    };
1234
1235    virtual void willSave(SaveFlags) {}
1236    virtual SaveLayerStrategy willSaveLayer(const SkRect*, const SkPaint*, SaveFlags) {
1237        return kFullLayer_SaveLayerStrategy;
1238    }
1239    virtual void willRestore() {}
1240    virtual void didConcat(const SkMatrix&) {}
1241    virtual void didSetMatrix(const SkMatrix&) {}
1242
1243    virtual void onDrawDRRect(const SkRRect&, const SkRRect&, const SkPaint&);
1244
1245    virtual void onDrawText(const void* text, size_t byteLength, SkScalar x,
1246                            SkScalar y, const SkPaint& paint);
1247
1248    virtual void onDrawPosText(const void* text, size_t byteLength,
1249                               const SkPoint pos[], const SkPaint& paint);
1250
1251    virtual void onDrawPosTextH(const void* text, size_t byteLength,
1252                                const SkScalar xpos[], SkScalar constY,
1253                                const SkPaint& paint);
1254
1255    virtual void onDrawTextOnPath(const void* text, size_t byteLength,
1256                                  const SkPath& path, const SkMatrix* matrix,
1257                                  const SkPaint& paint);
1258
1259    enum ClipEdgeStyle {
1260        kHard_ClipEdgeStyle,
1261        kSoft_ClipEdgeStyle
1262    };
1263
1264    virtual void onClipRect(const SkRect& rect, SkRegion::Op op, ClipEdgeStyle edgeStyle);
1265    virtual void onClipRRect(const SkRRect& rrect, SkRegion::Op op, ClipEdgeStyle edgeStyle);
1266    virtual void onClipPath(const SkPath& path, SkRegion::Op op, ClipEdgeStyle edgeStyle);
1267    virtual void onClipRegion(const SkRegion& deviceRgn, SkRegion::Op op);
1268
1269    virtual void onDiscard();
1270
1271    // Returns the canvas to be used by DrawIter. Default implementation
1272    // returns this. Subclasses that encapsulate an indirect canvas may
1273    // need to overload this method. The impl must keep track of this, as it
1274    // is not released or deleted by the caller.
1275    virtual SkCanvas* canvasForDrawIter();
1276
1277    // Clip rectangle bounds. Called internally by saveLayer.
1278    // returns false if the entire rectangle is entirely clipped out
1279    // If non-NULL, The imageFilter parameter will be used to expand the clip
1280    // and offscreen bounds for any margin required by the filter DAG.
1281    bool clipRectBounds(const SkRect* bounds, SaveFlags flags,
1282                        SkIRect* intersection,
1283                        const SkImageFilter* imageFilter = NULL);
1284
1285    // Called by child classes that override clipPath and clipRRect to only
1286    // track fast conservative clip bounds, rather than exact clips.
1287    void updateClipConservativelyUsingBounds(const SkRect&, SkRegion::Op,
1288                                             bool inverseFilled);
1289
1290    // notify our surface (if we have one) that we are about to draw, so it
1291    // can perform copy-on-write or invalidate any cached images
1292    void predrawNotify();
1293
1294    virtual void onPushCull(const SkRect& cullRect);
1295    virtual void onPopCull();
1296
1297private:
1298    class MCRec;
1299
1300    SkClipStack fClipStack;
1301    SkDeque     fMCStack;
1302    // points to top of stack
1303    MCRec*      fMCRec;
1304    // the first N recs that can fit here mean we won't call malloc
1305    uint32_t    fMCRecStorage[32];
1306
1307    SkBounder*  fBounder;
1308    int         fSaveLayerCount;    // number of successful saveLayer calls
1309    int         fCullCount;         // number of active culls
1310
1311    SkMetaData* fMetaData;
1312
1313    SkSurface_Base*  fSurfaceBase;
1314    SkSurface_Base* getSurfaceBase() const { return fSurfaceBase; }
1315    void setSurfaceBase(SkSurface_Base* sb) {
1316        fSurfaceBase = sb;
1317    }
1318    friend class SkSurface_Base;
1319    friend class SkSurface_Gpu;
1320
1321    bool fDeviceCMDirty;            // cleared by updateDeviceCMCache()
1322    void updateDeviceCMCache();
1323
1324    friend class SkDrawIter;        // needs setupDrawForLayerDevice()
1325    friend class AutoDrawLooper;
1326    friend class SkLua;             // needs top layer size and offset
1327    friend class SkDebugCanvas;     // needs experimental fAllowSimplifyClip
1328    friend class SkDeferredDevice;  // needs getTopDevice()
1329
1330    SkBaseDevice* createLayerDevice(const SkImageInfo&);
1331
1332    SkBaseDevice* init(SkBaseDevice*);
1333
1334    /**
1335     *  DEPRECATED
1336     *
1337     *  Specify a device for this canvas to draw into. If it is not null, its
1338     *  reference count is incremented. If the canvas was already holding a
1339     *  device, its reference count is decremented. The new device is returned.
1340     */
1341    SkBaseDevice* setRootDevice(SkBaseDevice* device);
1342
1343    /**
1344     * Gets the size/origin of the top level layer in global canvas coordinates. We don't want this
1345     * to be public because it exposes decisions about layer sizes that are internal to the canvas.
1346     */
1347    SkISize getTopLayerSize() const;
1348    SkIPoint getTopLayerOrigin() const;
1349
1350    // internal methods are not virtual, so they can safely be called by other
1351    // canvas apis, without confusing subclasses (like SkPictureRecording)
1352    void internalDrawBitmap(const SkBitmap&, const SkMatrix& m, const SkPaint* paint);
1353    void internalDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src,
1354                                const SkRect& dst, const SkPaint* paint,
1355                                DrawBitmapRectFlags flags);
1356    void internalDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
1357                                const SkRect& dst, const SkPaint* paint);
1358    void internalDrawPaint(const SkPaint& paint);
1359    int internalSaveLayer(const SkRect* bounds, const SkPaint* paint,
1360                          SaveFlags, bool justForImageFilter, SaveLayerStrategy strategy);
1361    void internalDrawDevice(SkBaseDevice*, int x, int y, const SkPaint*);
1362
1363    // shared by save() and saveLayer()
1364    int internalSave(SaveFlags flags);
1365    void internalRestore();
1366    static void DrawRect(const SkDraw& draw, const SkPaint& paint,
1367                         const SkRect& r, SkScalar textSize);
1368    static void DrawTextDecorations(const SkDraw& draw, const SkPaint& paint,
1369                                    const char text[], size_t byteLength,
1370                                    SkScalar x, SkScalar y);
1371
1372    /*  These maintain a cache of the clip bounds in local coordinates,
1373        (converted to 2s-compliment if floats are slow).
1374     */
1375    mutable SkRect fCachedLocalClipBounds;
1376    mutable bool   fCachedLocalClipBoundsDirty;
1377    bool fAllowSoftClip;
1378    bool fAllowSimplifyClip;
1379
1380    const SkRect& getLocalClipBounds() const {
1381        if (fCachedLocalClipBoundsDirty) {
1382            if (!this->getClipBounds(&fCachedLocalClipBounds)) {
1383                fCachedLocalClipBounds.setEmpty();
1384            }
1385            fCachedLocalClipBoundsDirty = false;
1386        }
1387        return fCachedLocalClipBounds;
1388    }
1389
1390    class AutoValidateClip : ::SkNoncopyable {
1391    public:
1392        explicit AutoValidateClip(SkCanvas* canvas) : fCanvas(canvas) {
1393            fCanvas->validateClip();
1394        }
1395        ~AutoValidateClip() { fCanvas->validateClip(); }
1396
1397    private:
1398        const SkCanvas* fCanvas;
1399    };
1400
1401#ifdef SK_DEBUG
1402    // The cull stack rects are in device-space
1403    SkTDArray<SkIRect> fCullStack;
1404    void validateCull(const SkIRect&);
1405    void validateClip() const;
1406#else
1407    void validateClip() const {}
1408#endif
1409
1410    typedef SkRefCnt INHERITED;
1411};
1412
1413/** Stack helper class to automatically call restoreToCount() on the canvas
1414    when this object goes out of scope. Use this to guarantee that the canvas
1415    is restored to a known state.
1416*/
1417class SkAutoCanvasRestore : SkNoncopyable {
1418public:
1419    SkAutoCanvasRestore(SkCanvas* canvas, bool doSave) : fCanvas(canvas), fSaveCount(0) {
1420        if (fCanvas) {
1421            fSaveCount = canvas->getSaveCount();
1422            if (doSave) {
1423                canvas->save();
1424            }
1425        }
1426    }
1427    ~SkAutoCanvasRestore() {
1428        if (fCanvas) {
1429            fCanvas->restoreToCount(fSaveCount);
1430        }
1431    }
1432
1433    /**
1434     *  Perform the restore now, instead of waiting for the destructor. Will
1435     *  only do this once.
1436     */
1437    void restore() {
1438        if (fCanvas) {
1439            fCanvas->restoreToCount(fSaveCount);
1440            fCanvas = NULL;
1441        }
1442    }
1443
1444private:
1445    SkCanvas*   fCanvas;
1446    int         fSaveCount;
1447};
1448#define SkAutoCanvasRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoCanvasRestore)
1449
1450/** Stack helper class to automatically open and close a comment block
1451 */
1452class SkAutoCommentBlock : SkNoncopyable {
1453public:
1454    SkAutoCommentBlock(SkCanvas* canvas, const char* description) {
1455        fCanvas = canvas;
1456        if (NULL != fCanvas) {
1457            fCanvas->beginCommentGroup(description);
1458        }
1459    }
1460
1461    ~SkAutoCommentBlock() {
1462        if (NULL != fCanvas) {
1463            fCanvas->endCommentGroup();
1464        }
1465    }
1466
1467private:
1468    SkCanvas* fCanvas;
1469};
1470#define SkAutoCommentBlock(...) SK_REQUIRE_LOCAL_VAR(SkAutoCommentBlock)
1471
1472/**
1473 *  If the caller wants read-only access to the pixels in a canvas, it can just
1474 *  call canvas->peekPixels(), since that is the fastest way to "peek" at the
1475 *  pixels on a raster-backed canvas.
1476 *
1477 *  If the canvas has pixels, but they are not readily available to the CPU
1478 *  (e.g. gpu-backed), then peekPixels() will fail, but readPixels() will
1479 *  succeed (though be slower, since it will return a copy of the pixels).
1480 *
1481 *  SkAutoROCanvasPixels encapsulates these two techniques, trying first to call
1482 *  peekPixels() (for performance), but if that fails, calling readPixels() and
1483 *  storing the copy locally.
1484 *
1485 *  The caller must respect the restrictions associated with peekPixels(), since
1486 *  that may have been called: The returned information is invalidated if...
1487 *      - any API is called on the canvas (or its parent surface if present)
1488 *      - the canvas goes out of scope
1489 */
1490class SkAutoROCanvasPixels : SkNoncopyable {
1491public:
1492    SkAutoROCanvasPixels(SkCanvas* canvas);
1493
1494    // returns NULL on failure
1495    const void* addr() const { return fAddr; }
1496
1497    // undefined if addr() == NULL
1498    size_t rowBytes() const { return fRowBytes; }
1499
1500    // undefined if addr() == NULL
1501    const SkImageInfo& info() const { return fInfo; }
1502
1503    // helper that, if returns true, installs the pixels into the bitmap. Note
1504    // that the bitmap may reference the address returned by peekPixels(), so
1505    // the caller must respect the restrictions associated with peekPixels().
1506    bool asROBitmap(SkBitmap*) const;
1507
1508private:
1509    SkBitmap    fBitmap;    // used if peekPixels() fails
1510    const void* fAddr;      // NULL on failure
1511    SkImageInfo fInfo;
1512    size_t      fRowBytes;
1513};
1514
1515static inline SkCanvas::SaveFlags operator|(const SkCanvas::SaveFlags lhs,
1516                                            const SkCanvas::SaveFlags rhs) {
1517    return static_cast<SkCanvas::SaveFlags>(lhs | rhs);
1518}
1519
1520static inline SkCanvas::SaveFlags& operator|=(SkCanvas::SaveFlags& lhs,
1521                                              const SkCanvas::SaveFlags rhs) {
1522    lhs = lhs | rhs;
1523    return lhs;
1524}
1525
1526
1527#endif
1528