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