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