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