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