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