Home | History | Annotate | Download | only in core
      1 
      2 /*
      3  * Copyright 2007 The Android Open Source Project
      4  *
      5  * Use of this source code is governed by a BSD-style license that can be
      6  * found in the LICENSE file.
      7  */
      8 
      9 
     10 #ifndef SkPicture_DEFINED
     11 #define SkPicture_DEFINED
     12 
     13 #include "SkBitmap.h"
     14 #include "SkImageDecoder.h"
     15 #include "SkRefCnt.h"
     16 
     17 #if SK_SUPPORT_GPU
     18 class GrContext;
     19 #endif
     20 
     21 class SkBBHFactory;
     22 class SkBBoxHierarchy;
     23 class SkCanvas;
     24 class SkDrawPictureCallback;
     25 class SkData;
     26 class SkPicturePlayback;
     27 class SkPictureRecord;
     28 class SkStream;
     29 class SkWStream;
     30 
     31 struct SkPictInfo;
     32 
     33 /** \class SkPicture
     34 
     35     The SkPicture class records the drawing commands made to a canvas, to
     36     be played back at a later time.
     37 */
     38 class SK_API SkPicture : public SkRefCnt {
     39 public:
     40     SK_DECLARE_INST_COUNT(SkPicture)
     41 
     42     // AccelData provides a base class for device-specific acceleration
     43     // data. It is added to the picture via a call to a device's optimize
     44     // method.
     45     class AccelData : public SkRefCnt {
     46     public:
     47         typedef uint8_t Domain;
     48         typedef uint32_t Key;
     49 
     50         AccelData(Key key) : fKey(key) { }
     51 
     52         const Key& getKey() const { return fKey; }
     53 
     54         // This entry point allows user's to get a unique domain prefix
     55         // for their keys
     56         static Domain GenerateDomain();
     57     private:
     58         Key fKey;
     59 
     60         typedef SkRefCnt INHERITED;
     61     };
     62 
     63     SkPicture();
     64     /** Make a copy of the contents of src. If src records more drawing after
     65         this call, those elements will not appear in this picture.
     66     */
     67     SkPicture(const SkPicture& src);
     68 
     69     /**  PRIVATE / EXPERIMENTAL -- do not call */
     70     void EXPERIMENTAL_addAccelData(const AccelData* data) const {
     71         SkRefCnt_SafeAssign(fAccelData, data);
     72     }
     73     /**  PRIVATE / EXPERIMENTAL -- do not call */
     74     const AccelData* EXPERIMENTAL_getAccelData(AccelData::Key key) const {
     75         if (NULL != fAccelData && fAccelData->getKey() == key) {
     76             return fAccelData;
     77         }
     78         return NULL;
     79     }
     80 
     81     /**
     82      *  Function signature defining a function that sets up an SkBitmap from encoded data. On
     83      *  success, the SkBitmap should have its Config, width, height, rowBytes and pixelref set.
     84      *  If the installed pixelref has decoded the data into pixels, then the src buffer need not be
     85      *  copied. If the pixelref defers the actual decode until its lockPixels() is called, then it
     86      *  must make a copy of the src buffer.
     87      *  @param src Encoded data.
     88      *  @param length Size of the encoded data, in bytes.
     89      *  @param dst SkBitmap to install the pixel ref on.
     90      *  @param bool Whether or not a pixel ref was successfully installed.
     91      */
     92     typedef bool (*InstallPixelRefProc)(const void* src, size_t length, SkBitmap* dst);
     93 
     94     /**
     95      *  Recreate a picture that was serialized into a stream.
     96      *  @param SkStream Serialized picture data.
     97      *  @param proc Function pointer for installing pixelrefs on SkBitmaps representing the
     98      *              encoded bitmap data from the stream.
     99      *  @return A new SkPicture representing the serialized data, or NULL if the stream is
    100      *          invalid.
    101      */
    102     static SkPicture* CreateFromStream(SkStream*,
    103                                        InstallPixelRefProc proc = &SkImageDecoder::DecodeMemory);
    104 
    105     /**
    106      *  Recreate a picture that was serialized into a buffer. If the creation requires bitmap
    107      *  decoding, the decoder must be set on the SkReadBuffer parameter by calling
    108      *  SkReadBuffer::setBitmapDecoder() before calling SkPicture::CreateFromBuffer().
    109      *  @param SkReadBuffer Serialized picture data.
    110      *  @return A new SkPicture representing the serialized data, or NULL if the buffer is
    111      *          invalid.
    112      */
    113     static SkPicture* CreateFromBuffer(SkReadBuffer&);
    114 
    115     virtual ~SkPicture();
    116 
    117     /**
    118      *  Swap the contents of the two pictures. Guaranteed to succeed.
    119      */
    120     void swap(SkPicture& other);
    121 
    122     /**
    123      *  Creates a thread-safe clone of the picture that is ready for playback.
    124      */
    125     SkPicture* clone() const;
    126 
    127     /**
    128      * Creates multiple thread-safe clones of this picture that are ready for
    129      * playback. The resulting clones are stored in the provided array of
    130      * SkPictures.
    131      */
    132     void clone(SkPicture* pictures, int count) const;
    133 
    134     /** Replays the drawing commands on the specified canvas.
    135         @param canvas the canvas receiving the drawing commands.
    136     */
    137     void draw(SkCanvas* canvas, SkDrawPictureCallback* = NULL) const;
    138 
    139     /** Return the width of the picture's recording canvas. This
    140         value reflects what was passed to setSize(), and does not necessarily
    141         reflect the bounds of what has been recorded into the picture.
    142         @return the width of the picture's recording canvas
    143     */
    144     int width() const { return fWidth; }
    145 
    146     /** Return the height of the picture's recording canvas. This
    147         value reflects what was passed to setSize(), and does not necessarily
    148         reflect the bounds of what has been recorded into the picture.
    149         @return the height of the picture's recording canvas
    150     */
    151     int height() const { return fHeight; }
    152 
    153     /** Return a non-zero, unique value representing the picture. This call is
    154         only valid when not recording. Between a beginRecording/endRecording
    155         pair it will just return 0 (the invalid ID). Each beginRecording/
    156         endRecording pair will cause a different generation ID to be returned.
    157     */
    158     uint32_t uniqueID() const;
    159 
    160     /**
    161      *  Function to encode an SkBitmap to an SkData. A function with this
    162      *  signature can be passed to serialize() and SkWriteBuffer.
    163      *  Returning NULL will tell the SkWriteBuffer to use
    164      *  SkBitmap::flatten() to store the bitmap.
    165      *
    166      *  @param pixelRefOffset DEPRECATED -- caller assumes it will return 0.
    167      *  @return SkData If non-NULL, holds encoded data representing the passed
    168      *      in bitmap. The caller is responsible for calling unref().
    169      */
    170     typedef SkData* (*EncodeBitmap)(size_t* pixelRefOffset, const SkBitmap& bm);
    171 
    172     /**
    173      *  Serialize to a stream. If non NULL, encoder will be used to encode
    174      *  any bitmaps in the picture.
    175      *  encoder will never be called with a NULL pixelRefOffset.
    176      */
    177     void serialize(SkWStream*, EncodeBitmap encoder = NULL) const;
    178 
    179     /**
    180      *  Serialize to a buffer.
    181      */
    182     void flatten(SkWriteBuffer&) const;
    183 
    184     /**
    185      * Returns true if any bitmaps may be produced when this SkPicture
    186      * is replayed.
    187      * Returns false if called while still recording.
    188      */
    189     bool willPlayBackBitmaps() const;
    190 
    191 #ifdef SK_BUILD_FOR_ANDROID
    192     /** Signals that the caller is prematurely done replaying the drawing
    193         commands. This can be called from a canvas virtual while the picture
    194         is drawing. Has no effect if the picture is not drawing.
    195         @deprecated preserving for legacy purposes
    196     */
    197     void abortPlayback();
    198 #endif
    199 
    200     /** Return true if the SkStream/Buffer represents a serialized picture, and
    201         fills out SkPictInfo. After this function returns, the data source is not
    202         rewound so it will have to be manually reset before passing to
    203         CreateFromStream or CreateFromBuffer. Note, CreateFromStream and
    204         CreateFromBuffer perform this check internally so these entry points are
    205         intended for stand alone tools.
    206         If false is returned, SkPictInfo is unmodified.
    207     */
    208     static bool InternalOnly_StreamIsSKP(SkStream*, SkPictInfo*);
    209     static bool InternalOnly_BufferIsSKP(SkReadBuffer&, SkPictInfo*);
    210 
    211     /** Return true if the picture is suitable for rendering on the GPU.
    212      */
    213 
    214 #if SK_SUPPORT_GPU
    215     bool suitableForGpuRasterization(GrContext*, const char ** = NULL) const;
    216 #endif
    217 
    218 protected:
    219     // V2 : adds SkPixelRef's generation ID.
    220     // V3 : PictInfo tag at beginning, and EOF tag at the end
    221     // V4 : move SkPictInfo to be the header
    222     // V5 : don't read/write FunctionPtr on cross-process (we can detect that)
    223     // V6 : added serialization of SkPath's bounds (and packed its flags tighter)
    224     // V7 : changed drawBitmapRect(IRect) to drawBitmapRectToRect(Rect)
    225     // V8 : Add an option for encoding bitmaps
    226     // V9 : Allow the reader and writer of an SKP disagree on whether to support
    227     //      SK_SUPPORT_HINTING_SCALE_FACTOR
    228     // V10: add drawRRect, drawOval, clipRRect
    229     // V11: modify how readBitmap and writeBitmap store their info.
    230     // V12: add conics to SkPath, use new SkPathRef flattening
    231     // V13: add flag to drawBitmapRectToRect
    232     //      parameterize blurs by sigma rather than radius
    233     // V14: Add flags word to PathRef serialization
    234     // V15: Remove A1 bitmap config (and renumber remaining configs)
    235     // V16: Move SkPath's isOval flag to SkPathRef
    236     // V17: SkPixelRef now writes SkImageInfo
    237     // V18: SkBitmap now records x,y for its pixelref origin, instead of offset.
    238     // V19: encode matrices and regions into the ops stream
    239     // V20: added bool to SkPictureImageFilter's serialization (to allow SkPicture serialization)
    240     // V21: add pushCull, popCull
    241     // V22: SK_PICT_FACTORY_TAG's size is now the chunk size in bytes
    242     // V23: SkPaint::FilterLevel became a real enum
    243     // V24: SkTwoPointConicalGradient now has fFlipped flag for gradient flipping
    244     // V25: SkDashPathEffect now only writes phase and interval array when flattening
    245     // V26: Removed boolean from SkColorShader for inheriting color from SkPaint.
    246     // V27: Remove SkUnitMapper from gradients (and skia).
    247     // V28: No longer call bitmap::flatten inside SkWriteBuffer::writeBitmap.
    248 
    249     // Note: If the picture version needs to be increased then please follow the
    250     // steps to generate new SKPs in (only accessible to Googlers): http://goo.gl/qATVcw
    251 
    252     // Only SKPs within the min/current picture version range (inclusive) can be read.
    253     static const uint32_t MIN_PICTURE_VERSION = 19;
    254     static const uint32_t CURRENT_PICTURE_VERSION = 28;
    255 
    256     mutable uint32_t      fUniqueID;
    257 
    258     // fPlayback, fRecord, fWidth & fHeight are protected to allow derived classes to
    259     // install their own SkPicturePlayback-derived players,SkPictureRecord-derived
    260     // recorders and set the picture size
    261     SkPicturePlayback*    fPlayback;
    262     int                   fWidth, fHeight;
    263     mutable const AccelData* fAccelData;
    264 
    265     void needsNewGenID() { fUniqueID = SK_InvalidGenID; }
    266 
    267     // Create a new SkPicture from an existing SkPicturePlayback. Ref count of
    268     // playback is unchanged.
    269     SkPicture(SkPicturePlayback*, int width, int height);
    270 
    271     SkPicture(int width, int height, const SkPictureRecord& record, bool deepCopyOps);
    272 
    273 private:
    274     static void WriteTagSize(SkWriteBuffer& buffer, uint32_t tag, size_t size);
    275     static void WriteTagSize(SkWStream* stream, uint32_t tag, size_t size);
    276 
    277     // An OperationList encapsulates a set of operation offsets into the picture byte
    278     // stream along with the CTMs needed for those operation.
    279     class OperationList : ::SkNoncopyable {
    280     public:
    281         virtual ~OperationList() {}
    282 
    283         // If valid returns false then there is no optimization data
    284         // present. All the draw operations need to be issued.
    285         virtual bool valid() const { return false; }
    286 
    287         // The following three entry points should only be accessed if
    288         // 'valid' returns true.
    289         virtual int numOps() const { SkASSERT(false); return 0; };
    290         // The offset in the picture of the operation to execute.
    291         virtual uint32_t offset(int index) const { SkASSERT(false); return 0; };
    292         // The CTM that must be installed for the operation to behave correctly
    293         virtual const SkMatrix& matrix(int index) const { SkASSERT(false); return SkMatrix::I(); }
    294 
    295         static const OperationList& InvalidList();
    296     };
    297 
    298     /** PRIVATE / EXPERIMENTAL -- do not call
    299         Return the operations required to render the content inside 'queryRect'.
    300     */
    301     const OperationList& EXPERIMENTAL_getActiveOps(const SkIRect& queryRect) const;
    302 
    303     /** PRIVATE / EXPERIMENTAL -- do not call
    304         Return the ID of the operation currently being executed when playing
    305         back. 0 indicates no call is active.
    306     */
    307     size_t EXPERIMENTAL_curOpID() const;
    308 
    309     void createHeader(SkPictInfo* info) const;
    310     static bool IsValidPictInfo(const SkPictInfo& info);
    311 
    312     friend class SkFlatPicture;
    313     friend class SkPicturePlayback;
    314     friend class SkPictureRecorder; // just for SkPicture-based constructor
    315     friend class SkGpuDevice;
    316     friend class GrGatherCanvas;
    317     friend class GrGatherDevice;
    318     friend class SkDebugCanvas;
    319 
    320     typedef SkRefCnt INHERITED;
    321 };
    322 
    323 /**
    324  *  Subclasses of this can be passed to canvas.drawPicture. During the drawing
    325  *  of the picture, this callback will periodically be invoked. If its
    326  *  abortDrawing() returns true, then picture playback will be interrupted.
    327  *
    328  *  The resulting drawing is undefined, as there is no guarantee how often the
    329  *  callback will be invoked. If the abort happens inside some level of nested
    330  *  calls to save(), restore will automatically be called to return the state
    331  *  to the same level it was before the drawPicture call was made.
    332  */
    333 class SK_API SkDrawPictureCallback {
    334 public:
    335     SkDrawPictureCallback() {}
    336     virtual ~SkDrawPictureCallback() {}
    337 
    338     virtual bool abortDrawing() = 0;
    339 };
    340 
    341 #endif
    342