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