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