SkPicture.h revision 68cd2aa797f707a9847f8eba0758787cafd43e43
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 "SkDrawPictureCallback.h"
15#include "SkImageDecoder.h"
16#include "SkRefCnt.h"
17#include "SkTDArray.h"
18
19#if SK_SUPPORT_GPU
20class GrContext;
21#endif
22
23class GrReplacements;
24class SkBBoxHierarchy;
25class SkCanvas;
26class SkData;
27class SkPictureData;
28class SkPictureRecord;
29class SkStream;
30class SkWStream;
31
32struct SkPictInfo;
33
34class SkRecord;
35
36/** \class SkPicture
37
38    The SkPicture class records the drawing commands made to a canvas, to
39    be played back at a later time.
40*/
41class SK_API SkPicture : public SkRefCnt {
42public:
43    SK_DECLARE_INST_COUNT(SkPicture)
44
45    // AccelData provides a base class for device-specific acceleration
46    // data. It is added to the picture via a call to a device's optimize
47    // method.
48    class AccelData : public SkRefCnt {
49    public:
50        typedef uint8_t Domain;
51        typedef uint32_t Key;
52
53        AccelData(Key key) : fKey(key) { }
54
55        const Key& getKey() const { return fKey; }
56
57        // This entry point allows user's to get a unique domain prefix
58        // for their keys
59        static Domain GenerateDomain();
60    private:
61        Key fKey;
62
63        typedef SkRefCnt INHERITED;
64    };
65
66    /**  PRIVATE / EXPERIMENTAL -- do not call */
67    void EXPERIMENTAL_addAccelData(const AccelData*) const;
68
69    /**  PRIVATE / EXPERIMENTAL -- do not call */
70    const AccelData* EXPERIMENTAL_getAccelData(AccelData::Key) const;
71
72    /**
73     *  Function signature defining a function that sets up an SkBitmap from encoded data. On
74     *  success, the SkBitmap should have its Config, width, height, rowBytes and pixelref set.
75     *  If the installed pixelref has decoded the data into pixels, then the src buffer need not be
76     *  copied. If the pixelref defers the actual decode until its lockPixels() is called, then it
77     *  must make a copy of the src buffer.
78     *  @param src Encoded data.
79     *  @param length Size of the encoded data, in bytes.
80     *  @param dst SkBitmap to install the pixel ref on.
81     *  @param bool Whether or not a pixel ref was successfully installed.
82     */
83    typedef bool (*InstallPixelRefProc)(const void* src, size_t length, SkBitmap* dst);
84
85    /**
86     *  Recreate a picture that was serialized into a stream.
87     *  @param SkStream Serialized picture data.
88     *  @param proc Function pointer for installing pixelrefs on SkBitmaps representing the
89     *              encoded bitmap data from the stream.
90     *  @return A new SkPicture representing the serialized data, or NULL if the stream is
91     *          invalid.
92     */
93    static SkPicture* CreateFromStream(SkStream*,
94                                       InstallPixelRefProc proc = &SkImageDecoder::DecodeMemory);
95
96    /**
97     *  Recreate a picture that was serialized into a buffer. If the creation requires bitmap
98     *  decoding, the decoder must be set on the SkReadBuffer parameter by calling
99     *  SkReadBuffer::setBitmapDecoder() before calling SkPicture::CreateFromBuffer().
100     *  @param SkReadBuffer Serialized picture data.
101     *  @return A new SkPicture representing the serialized data, or NULL if the buffer is
102     *          invalid.
103     */
104    static SkPicture* CreateFromBuffer(SkReadBuffer&);
105
106    virtual ~SkPicture();
107
108    /** Replays the drawing commands on the specified canvas. Note that
109        this has the effect of unfurling this picture into the destination
110        canvas. Using the SkCanvas::drawPicture entry point gives the destination
111        canvas the option of just taking a ref.
112        @param canvas the canvas receiving the drawing commands.
113        @param callback a callback that allows interruption of playback
114    */
115    void playback(SkCanvas* canvas, SkDrawPictureCallback* = NULL) const;
116
117#ifdef SK_LEGACY_PICTURE_DRAW_API
118    void draw(SkCanvas* canvas, SkDrawPictureCallback* callback = NULL) const {
119        this->playback(canvas, callback);
120    }
121#endif
122
123#ifdef SK_LEGACY_PICTURE_SIZE_API
124    int width() const  { return SkScalarCeilToInt(fCullWidth); }
125    int height() const { return SkScalarCeilToInt(fCullHeight); }
126#endif
127
128    /** Return the cull rect used when creating this picture: { 0, 0, cullWidth, cullHeight }.
129        It does not necessarily reflect the bounds of what has been recorded into the picture.
130        @return the cull rect used to create this picture
131    */
132    const SkRect cullRect() const { return SkRect::MakeWH(fCullWidth, fCullHeight); }
133
134    /** Return a non-zero, unique value representing the picture. This call is
135        only valid when not recording. Between a beginRecording/endRecording
136        pair it will just return 0 (the invalid ID). Each beginRecording/
137        endRecording pair will cause a different generation ID to be returned.
138    */
139    uint32_t uniqueID() const;
140
141    /**
142     *  Function to encode an SkBitmap to an SkData. A function with this
143     *  signature can be passed to serialize() and SkWriteBuffer.
144     *  Returning NULL will tell the SkWriteBuffer to use
145     *  SkBitmap::flatten() to store the bitmap.
146     *
147     *  @param pixelRefOffset DEPRECATED -- caller assumes it will return 0.
148     *  @return SkData If non-NULL, holds encoded data representing the passed
149     *      in bitmap. The caller is responsible for calling unref().
150     */
151    typedef SkData* (*EncodeBitmap)(size_t* pixelRefOffset, const SkBitmap& bm);
152
153    /**
154     *  Serialize to a stream. If non NULL, encoder will be used to encode
155     *  any bitmaps in the picture.
156     *  encoder will never be called with a NULL pixelRefOffset.
157     */
158    void serialize(SkWStream*, EncodeBitmap encoder = NULL) const;
159
160    /**
161     *  Serialize to a buffer.
162     */
163    void flatten(SkWriteBuffer&) const;
164
165    /**
166     * Returns true if any bitmaps may be produced when this SkPicture
167     * is replayed.
168     */
169    bool willPlayBackBitmaps() const;
170
171    /** Return true if the SkStream/Buffer represents a serialized picture, and
172        fills out SkPictInfo. After this function returns, the data source is not
173        rewound so it will have to be manually reset before passing to
174        CreateFromStream or CreateFromBuffer. Note, CreateFromStream and
175        CreateFromBuffer perform this check internally so these entry points are
176        intended for stand alone tools.
177        If false is returned, SkPictInfo is unmodified.
178    */
179    static bool InternalOnly_StreamIsSKP(SkStream*, SkPictInfo*);
180    static bool InternalOnly_BufferIsSKP(SkReadBuffer*, SkPictInfo*);
181
182    /** Return true if the picture is suitable for rendering on the GPU.
183     */
184
185#if SK_SUPPORT_GPU
186    bool suitableForGpuRasterization(GrContext*, const char ** = NULL) const;
187#endif
188
189    class DeletionListener : public SkRefCnt {
190    public:
191        virtual void onDeletion(uint32_t pictureID) = 0;
192    };
193
194    // Takes ref on listener.
195    void addDeletionListener(DeletionListener* listener) const;
196
197    /** Return the approximate number of operations in this picture.  This
198     *  number may be greater or less than the number of SkCanvas calls
199     *  recorded: some calls may be recorded as more than one operation, or some
200     *  calls may be optimized away.
201     */
202    int approximateOpCount() const;
203
204    /** Return true if this picture contains text.
205     */
206    bool hasText() const;
207
208private:
209    // V2 : adds SkPixelRef's generation ID.
210    // V3 : PictInfo tag at beginning, and EOF tag at the end
211    // V4 : move SkPictInfo to be the header
212    // V5 : don't read/write FunctionPtr on cross-process (we can detect that)
213    // V6 : added serialization of SkPath's bounds (and packed its flags tighter)
214    // V7 : changed drawBitmapRect(IRect) to drawBitmapRectToRect(Rect)
215    // V8 : Add an option for encoding bitmaps
216    // V9 : Allow the reader and writer of an SKP disagree on whether to support
217    //      SK_SUPPORT_HINTING_SCALE_FACTOR
218    // V10: add drawRRect, drawOval, clipRRect
219    // V11: modify how readBitmap and writeBitmap store their info.
220    // V12: add conics to SkPath, use new SkPathRef flattening
221    // V13: add flag to drawBitmapRectToRect
222    //      parameterize blurs by sigma rather than radius
223    // V14: Add flags word to PathRef serialization
224    // V15: Remove A1 bitmap config (and renumber remaining configs)
225    // V16: Move SkPath's isOval flag to SkPathRef
226    // V17: SkPixelRef now writes SkImageInfo
227    // V18: SkBitmap now records x,y for its pixelref origin, instead of offset.
228    // V19: encode matrices and regions into the ops stream
229    // V20: added bool to SkPictureImageFilter's serialization (to allow SkPicture serialization)
230    // V21: add pushCull, popCull
231    // V22: SK_PICT_FACTORY_TAG's size is now the chunk size in bytes
232    // V23: SkPaint::FilterLevel became a real enum
233    // V24: SkTwoPointConicalGradient now has fFlipped flag for gradient flipping
234    // V25: SkDashPathEffect now only writes phase and interval array when flattening
235    // V26: Removed boolean from SkColorShader for inheriting color from SkPaint.
236    // V27: Remove SkUnitMapper from gradients (and skia).
237    // V28: No longer call bitmap::flatten inside SkWriteBuffer::writeBitmap.
238    // V29: Removed SaveFlags parameter from save().
239    // V30: Remove redundant SkMatrix from SkLocalMatrixShader.
240    // V31: Add a serialized UniqueID to SkImageFilter.
241    // V32: Removed SkPaintOptionsAndroid from SkPaint
242    // V33: Serialize only public API of effects.
243    // V34: Add SkTextBlob serialization.
244    // V35: Store SkRect (rather then width & height) in header
245    // V36: Remove (obsolete) alphatype from SkColorTable
246
247    // Note: If the picture version needs to be increased then please follow the
248    // steps to generate new SKPs in (only accessible to Googlers): http://goo.gl/qATVcw
249
250    // Only SKPs within the min/current picture version range (inclusive) can be read.
251    static const uint32_t MIN_PICTURE_VERSION = 19;
252    static const uint32_t CURRENT_PICTURE_VERSION = 36;
253
254    mutable uint32_t      fUniqueID;
255
256    SkAutoTDelete<const SkPictureData>    fData;
257    const SkScalar                        fCullWidth;
258    const SkScalar                        fCullHeight;
259    mutable SkAutoTUnref<const AccelData> fAccelData;
260
261    mutable SkTDArray<DeletionListener*> fDeletionListeners;  // pointers are refed
262
263    void needsNewGenID() { fUniqueID = SK_InvalidGenID; }
264    void callDeletionListeners();
265
266    // Create a new SkPicture from an existing SkPictureData. The new picture
267    // takes ownership of 'data'.
268    SkPicture(SkPictureData* data, SkScalar width, SkScalar height);
269
270    SkPicture(SkScalar width, SkScalar height, const SkPictureRecord& record, bool deepCopyOps);
271
272    void createHeader(SkPictInfo* info) const;
273    static bool IsValidPictInfo(const SkPictInfo& info);
274
275    friend class SkPictureRecorder;            // just for SkPicture-based constructor
276    friend class SkGpuDevice;                  // for fData access
277    friend class GrLayerHoister;               // access to fRecord
278    friend class CollectLayers;                // access to fRecord
279    friend class SkPicturePlayback;            // to get fData
280    friend class ReplaceDraw;
281
282    typedef SkRefCnt INHERITED;
283
284    // Takes ownership of the SkRecord, refs the (optional) BBH.
285    SkPicture(SkScalar width, SkScalar height, SkRecord*, SkBBoxHierarchy*);
286    // Return as a new SkPicture that's backed by SkRecord.
287    static SkPicture* Forwardport(const SkPicture&);
288
289    SkAutoTDelete<SkRecord>       fRecord;
290    SkAutoTUnref<SkBBoxHierarchy> fBBH;
291
292    struct PathCounter;
293
294    struct Analysis {
295        Analysis() {}  // Only used by SkPictureData codepath.
296        explicit Analysis(const SkRecord&);
297
298        bool suitableForGpuRasterization(const char** reason, int sampleCount) const;
299
300        bool        fWillPlaybackBitmaps;
301        bool        fHasText;
302        int         fNumPaintWithPathEffectUses;
303        int         fNumFastPathDashEffects;
304        int         fNumAAConcavePaths;
305        int         fNumAAHairlineConcavePaths;
306    } fAnalysis;
307};
308
309#endif
310