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