SkPicture.h revision b7425173f96e93b090787e2386ba5f022b6c2869
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#ifdef SK_SUPPORT_LEGACY_DEFAULT_PICTURE_CTOR
66    SkPicture();
67#endif
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#ifdef SK_SUPPORT_LEGACY_PICTURE_CLONE
112    /**
113     *  Creates a thread-safe clone of the picture that is ready for playback.
114     */
115    SkPicture* clone() const;
116#endif
117
118    /** Replays the drawing commands on the specified canvas.
119        @param canvas the canvas receiving the drawing commands.
120    */
121    void draw(SkCanvas* canvas, SkDrawPictureCallback* = NULL) const;
122
123    /** Return the width of the picture's recording canvas. This
124        value reflects what was passed to setSize(), and does not necessarily
125        reflect the bounds of what has been recorded into the picture.
126        @return the width of the picture's recording canvas
127    */
128    int width() const { return fWidth; }
129
130    /** Return the height of the picture's recording canvas. This
131        value reflects what was passed to setSize(), and does not necessarily
132        reflect the bounds of what has been recorded into the picture.
133        @return the height of the picture's recording canvas
134    */
135    int height() const { return fHeight; }
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
248    // Note: If the picture version needs to be increased then please follow the
249    // steps to generate new SKPs in (only accessible to Googlers): http://goo.gl/qATVcw
250
251    // Only SKPs within the min/current picture version range (inclusive) can be read.
252    static const uint32_t MIN_PICTURE_VERSION = 19;
253    static const uint32_t CURRENT_PICTURE_VERSION = 34;
254
255    mutable uint32_t      fUniqueID;
256
257    // TODO: make SkPictureData const when clone method goes away
258    SkAutoTDelete<SkPictureData> fData;
259    int                   fWidth, fHeight;
260    mutable SkAutoTUnref<const AccelData> fAccelData;
261
262    mutable SkTDArray<DeletionListener*> fDeletionListeners;  // pointers are refed
263
264    void needsNewGenID() { fUniqueID = SK_InvalidGenID; }
265    void callDeletionListeners();
266
267    // Create a new SkPicture from an existing SkPictureData. The new picture
268    // takes ownership of 'data'.
269    SkPicture(SkPictureData* data, int width, int height);
270
271    SkPicture(int width, int height, const SkPictureRecord& record, bool deepCopyOps);
272
273    // An OperationList encapsulates a set of operation offsets into the picture byte
274    // stream along with the CTMs needed for those operation.
275    class OperationList : ::SkNoncopyable {
276    public:
277        // The following three entry points should only be accessed if
278        // 'valid' returns true.
279        int numOps() const { return fOps.count(); }
280        // The offset in the picture of the operation to execute.
281        uint32_t offset(int index) const;
282        // The CTM that must be installed for the operation to behave correctly
283        const SkMatrix& matrix(int index) const;
284
285        SkTDArray<void*> fOps;
286    };
287
288    /** PRIVATE / EXPERIMENTAL -- do not call
289        Return the operations required to render the content inside 'queryRect'.
290    */
291    const OperationList* EXPERIMENTAL_getActiveOps(const SkIRect& queryRect) const;
292
293    void createHeader(SkPictInfo* info) const;
294    static bool IsValidPictInfo(const SkPictInfo& info);
295
296    friend class SkPictureData;                // to access OperationList
297    friend class SkPictureRecorder;            // just for SkPicture-based constructor
298    friend class SkGpuDevice;                  // for EXPERIMENTAL_getActiveOps/OperationList
299    friend class GrGatherCanvas;               // needs to know if old or new picture
300    friend class SkPicturePlayback;            // to get fData & OperationList
301    friend class SkPictureReplacementPlayback; // to access OperationList
302
303    typedef SkRefCnt INHERITED;
304
305    // Takes ownership of the SkRecord, refs the (optional) BBH.
306    SkPicture(int width, int height, SkRecord*, SkBBoxHierarchy*);
307    // Return as a new SkPicture that's backed by SkRecord.
308    static SkPicture* Forwardport(const SkPicture&);
309
310    SkAutoTDelete<SkRecord>       fRecord;
311    SkAutoTUnref<SkBBoxHierarchy> fBBH;
312
313    struct PathCounter;
314
315    struct Analysis {
316        Analysis() {}  // Only used by SkPictureData codepath.
317        explicit Analysis(const SkRecord&);
318
319        bool suitableForGpuRasterization(const char** reason, int sampleCount) const;
320
321        bool        fWillPlaybackBitmaps;
322        bool        fHasText;
323        int         fNumPaintWithPathEffectUses;
324        int         fNumFastPathDashEffects;
325        int         fNumAAConcavePaths;
326        int         fNumAAHairlineConcavePaths;
327    } fAnalysis;
328};
329
330#endif
331