SkPicturePlayback.cpp revision 06e975252112eb5ca62ebacd484118a640c19168
1
2/*
3 * Copyright 2011 Google Inc.
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#include "SkPicturePlayback.h"
9#include "SkPictureRecord.h"
10#include "SkTypeface.h"
11#include "SkReadBuffer.h"
12#include "SkWriteBuffer.h"
13#include <new>
14#include "SkBBoxHierarchy.h"
15#include "SkPictureStateTree.h"
16#include "SkTSort.h"
17
18template <typename T> int SafeCount(const T* obj) {
19    return obj ? obj->count() : 0;
20}
21
22/*  Define this to spew out a debug statement whenever we skip the remainder of
23    a save/restore block because a clip... command returned false (empty).
24 */
25#define SPEW_CLIP_SKIPPINGx
26
27SkPicturePlayback::SkPicturePlayback() {
28    this->init();
29}
30
31SkPicturePlayback::SkPicturePlayback(const SkPictureRecord& record, bool deepCopy) {
32#ifdef SK_DEBUG_SIZE
33    size_t overallBytes, bitmapBytes, matricesBytes,
34    paintBytes, pathBytes, pictureBytes, regionBytes;
35    int bitmaps = record.bitmaps(&bitmapBytes);
36    int matrices = record.matrices(&matricesBytes);
37    int paints = record.paints(&paintBytes);
38    int paths = record.paths(&pathBytes);
39    int pictures = record.pictures(&pictureBytes);
40    int regions = record.regions(&regionBytes);
41    SkDebugf("picture record mem used %zd (stream %zd) ", record.size(),
42             record.streamlen());
43    if (bitmaps != 0)
44        SkDebugf("bitmaps size %zd (bitmaps:%d) ", bitmapBytes, bitmaps);
45    if (matrices != 0)
46        SkDebugf("matrices size %zd (matrices:%d) ", matricesBytes, matrices);
47    if (paints != 0)
48        SkDebugf("paints size %zd (paints:%d) ", paintBytes, paints);
49    if (paths != 0)
50        SkDebugf("paths size %zd (paths:%d) ", pathBytes, paths);
51    if (pictures != 0)
52        SkDebugf("pictures size %zd (pictures:%d) ", pictureBytes, pictures);
53    if (regions != 0)
54        SkDebugf("regions size %zd (regions:%d) ", regionBytes, regions);
55    if (record.fPointWrites != 0)
56        SkDebugf("points size %zd (points:%d) ", record.fPointBytes, record.fPointWrites);
57    if (record.fRectWrites != 0)
58        SkDebugf("rects size %zd (rects:%d) ", record.fRectBytes, record.fRectWrites);
59    if (record.fTextWrites != 0)
60        SkDebugf("text size %zd (text strings:%d) ", record.fTextBytes, record.fTextWrites);
61
62    SkDebugf("\n");
63#endif
64#ifdef SK_DEBUG_DUMP
65    record.dumpMatrices();
66    record.dumpPaints();
67#endif
68
69    record.validate(record.writeStream().bytesWritten(), 0);
70    const SkWriter32& writer = record.writeStream();
71    init();
72    if (writer.bytesWritten() == 0) {
73        fOpData = SkData::NewEmpty();
74        return;
75    }
76
77    fBoundingHierarchy = record.fBoundingHierarchy;
78    fStateTree = record.fStateTree;
79
80    SkSafeRef(fBoundingHierarchy);
81    SkSafeRef(fStateTree);
82
83    if (NULL != fBoundingHierarchy) {
84        fBoundingHierarchy->flushDeferredInserts();
85    }
86
87    {
88        size_t size = writer.bytesWritten();
89        void* buffer = sk_malloc_throw(size);
90        writer.flatten(buffer);
91        SkASSERT(!fOpData);
92        fOpData = SkData::NewFromMalloc(buffer, size);
93    }
94
95    // copy over the refcnt dictionary to our reader
96    record.fFlattenableHeap.setupPlaybacks();
97
98    fBitmaps = record.fBitmapHeap->extractBitmaps();
99    fPaints = record.fPaints.unflattenToArray();
100
101    fBitmapHeap.reset(SkSafeRef(record.fBitmapHeap));
102    fPathHeap.reset(SkSafeRef(record.fPathHeap));
103
104    // ensure that the paths bounds are pre-computed
105    if (fPathHeap.get()) {
106        for (int i = 0; i < fPathHeap->count(); i++) {
107            (*fPathHeap)[i].updateBoundsCache();
108        }
109    }
110
111    const SkTDArray<SkPicture* >& pictures = record.getPictureRefs();
112    fPictureCount = pictures.count();
113    if (fPictureCount > 0) {
114        fPictureRefs = SkNEW_ARRAY(SkPicture*, fPictureCount);
115        for (int i = 0; i < fPictureCount; i++) {
116            if (deepCopy) {
117                fPictureRefs[i] = pictures[i]->clone();
118            } else {
119                fPictureRefs[i] = pictures[i];
120                fPictureRefs[i]->ref();
121            }
122        }
123    }
124
125#ifdef SK_DEBUG_SIZE
126    int overall = fPlayback->size(&overallBytes);
127    bitmaps = fPlayback->bitmaps(&bitmapBytes);
128    paints = fPlayback->paints(&paintBytes);
129    paths = fPlayback->paths(&pathBytes);
130    pictures = fPlayback->pictures(&pictureBytes);
131    regions = fPlayback->regions(&regionBytes);
132    SkDebugf("playback size %zd (objects:%d) ", overallBytes, overall);
133    if (bitmaps != 0)
134        SkDebugf("bitmaps size %zd (bitmaps:%d) ", bitmapBytes, bitmaps);
135    if (paints != 0)
136        SkDebugf("paints size %zd (paints:%d) ", paintBytes, paints);
137    if (paths != 0)
138        SkDebugf("paths size %zd (paths:%d) ", pathBytes, paths);
139    if (pictures != 0)
140        SkDebugf("pictures size %zd (pictures:%d) ", pictureBytes, pictures);
141    if (regions != 0)
142        SkDebugf("regions size %zd (regions:%d) ", regionBytes, regions);
143    SkDebugf("\n");
144#endif
145}
146
147static bool needs_deep_copy(const SkPaint& paint) {
148    /*
149     *  These fields are known to be immutable, and so can be shallow-copied
150     *
151     *  getTypeface()
152     *  getAnnotation()
153     *  paint.getColorFilter()
154     *  getXfermode()
155     */
156
157    return paint.getPathEffect() ||
158           paint.getShader() ||
159           paint.getMaskFilter() ||
160           paint.getRasterizer() ||
161           paint.getLooper() ||
162           paint.getImageFilter();
163}
164
165SkPicturePlayback::SkPicturePlayback(const SkPicturePlayback& src, SkPictCopyInfo* deepCopyInfo) {
166    this->init();
167
168    fBitmapHeap.reset(SkSafeRef(src.fBitmapHeap.get()));
169    fPathHeap.reset(SkSafeRef(src.fPathHeap.get()));
170
171    fOpData = SkSafeRef(src.fOpData);
172
173    fBoundingHierarchy = src.fBoundingHierarchy;
174    fStateTree = src.fStateTree;
175
176    SkSafeRef(fBoundingHierarchy);
177    SkSafeRef(fStateTree);
178
179    if (deepCopyInfo) {
180        int paintCount = SafeCount(src.fPaints);
181
182        if (src.fBitmaps) {
183            fBitmaps = SkTRefArray<SkBitmap>::Create(src.fBitmaps->begin(), src.fBitmaps->count());
184        }
185
186        if (!deepCopyInfo->initialized) {
187            /* The alternative to doing this is to have a clone method on the paint and have it make
188             * the deep copy of its internal structures as needed. The holdup to doing that is at
189             * this point we would need to pass the SkBitmapHeap so that we don't unnecessarily
190             * flatten the pixels in a bitmap shader.
191             */
192            deepCopyInfo->paintData.setCount(paintCount);
193
194            /* Use an SkBitmapHeap to avoid flattening bitmaps in shaders. If there already is one,
195             * use it. If this SkPicturePlayback was created from a stream, fBitmapHeap will be
196             * NULL, so create a new one.
197             */
198            if (fBitmapHeap.get() == NULL) {
199                // FIXME: Put this on the stack inside SkPicture::clone. Further, is it possible to
200                // do the rest of this initialization in SkPicture::clone as well?
201                SkBitmapHeap* heap = SkNEW(SkBitmapHeap);
202                deepCopyInfo->controller.setBitmapStorage(heap);
203                heap->unref();
204            } else {
205                deepCopyInfo->controller.setBitmapStorage(fBitmapHeap);
206            }
207
208            SkDEBUGCODE(int heapSize = SafeCount(fBitmapHeap.get());)
209            for (int i = 0; i < paintCount; i++) {
210                if (needs_deep_copy(src.fPaints->at(i))) {
211                    deepCopyInfo->paintData[i] =
212                        SkFlatData::Create<SkPaint::FlatteningTraits>(&deepCopyInfo->controller,
213                                                          src.fPaints->at(i), 0);
214
215                } else {
216                    // this is our sentinel, which we use in the unflatten loop
217                    deepCopyInfo->paintData[i] = NULL;
218                }
219            }
220            SkASSERT(SafeCount(fBitmapHeap.get()) == heapSize);
221
222            // needed to create typeface playback
223            deepCopyInfo->controller.setupPlaybacks();
224            deepCopyInfo->initialized = true;
225        }
226
227        fPaints = SkTRefArray<SkPaint>::Create(paintCount);
228        SkASSERT(deepCopyInfo->paintData.count() == paintCount);
229        SkBitmapHeap* bmHeap = deepCopyInfo->controller.getBitmapHeap();
230        SkTypefacePlayback* tfPlayback = deepCopyInfo->controller.getTypefacePlayback();
231        for (int i = 0; i < paintCount; i++) {
232            if (deepCopyInfo->paintData[i]) {
233                deepCopyInfo->paintData[i]->unflatten<SkPaint::FlatteningTraits>(
234                    &fPaints->writableAt(i), bmHeap, tfPlayback);
235            } else {
236                // needs_deep_copy was false, so just need to assign
237                fPaints->writableAt(i) = src.fPaints->at(i);
238            }
239        }
240
241    } else {
242        fBitmaps = SkSafeRef(src.fBitmaps);
243        fPaints = SkSafeRef(src.fPaints);
244    }
245
246    fPictureCount = src.fPictureCount;
247    fPictureRefs = SkNEW_ARRAY(SkPicture*, fPictureCount);
248    for (int i = 0; i < fPictureCount; i++) {
249        if (deepCopyInfo) {
250            fPictureRefs[i] = src.fPictureRefs[i]->clone();
251        } else {
252            fPictureRefs[i] = src.fPictureRefs[i];
253            fPictureRefs[i]->ref();
254        }
255    }
256}
257
258void SkPicturePlayback::init() {
259    fBitmaps = NULL;
260    fPaints = NULL;
261    fPictureRefs = NULL;
262    fPictureCount = 0;
263    fOpData = NULL;
264    fFactoryPlayback = NULL;
265    fBoundingHierarchy = NULL;
266    fStateTree = NULL;
267}
268
269SkPicturePlayback::~SkPicturePlayback() {
270    fOpData->unref();
271
272    SkSafeUnref(fBitmaps);
273    SkSafeUnref(fPaints);
274    SkSafeUnref(fBoundingHierarchy);
275    SkSafeUnref(fStateTree);
276
277    for (int i = 0; i < fPictureCount; i++) {
278        fPictureRefs[i]->unref();
279    }
280    SkDELETE_ARRAY(fPictureRefs);
281
282    SkDELETE(fFactoryPlayback);
283}
284
285void SkPicturePlayback::dumpSize() const {
286    SkDebugf("--- picture size: ops=%d bitmaps=%d [%d] paints=%d [%d] paths=%d\n",
287             fOpData->size(),
288             SafeCount(fBitmaps), SafeCount(fBitmaps) * sizeof(SkBitmap),
289             SafeCount(fPaints), SafeCount(fPaints) * sizeof(SkPaint),
290             SafeCount(fPathHeap.get()));
291}
292
293bool SkPicturePlayback::containsBitmaps() const {
294    if (fBitmaps && fBitmaps->count() > 0) {
295        return true;
296    }
297    for (int i = 0; i < fPictureCount; ++i) {
298        if (fPictureRefs[i]->willPlayBackBitmaps()) {
299            return true;
300        }
301    }
302    return false;
303}
304
305///////////////////////////////////////////////////////////////////////////////
306///////////////////////////////////////////////////////////////////////////////
307
308#include "SkStream.h"
309
310static void write_tag_size(SkWriteBuffer& buffer, uint32_t tag, uint32_t size) {
311    buffer.writeUInt(tag);
312    buffer.writeUInt(size);
313}
314
315static void write_tag_size(SkWStream* stream, uint32_t tag,  uint32_t size) {
316    stream->write32(tag);
317    stream->write32(size);
318}
319
320static size_t compute_chunk_size(SkFlattenable::Factory* array, int count) {
321    size_t size = 4;  // for 'count'
322
323    for (int i = 0; i < count; i++) {
324        const char* name = SkFlattenable::FactoryToName(array[i]);
325        if (NULL == name || 0 == *name) {
326            size += SkWStream::SizeOfPackedUInt(0);
327        } else {
328            size_t len = strlen(name);
329            size += SkWStream::SizeOfPackedUInt(len);
330            size += len;
331        }
332    }
333
334    return size;
335}
336
337static void write_factories(SkWStream* stream, const SkFactorySet& rec) {
338    int count = rec.count();
339
340    SkAutoSTMalloc<16, SkFlattenable::Factory> storage(count);
341    SkFlattenable::Factory* array = (SkFlattenable::Factory*)storage.get();
342    rec.copyToArray(array);
343
344    size_t size = compute_chunk_size(array, count);
345
346    // TODO: write_tag_size should really take a size_t
347    write_tag_size(stream, SK_PICT_FACTORY_TAG, (uint32_t) size);
348    SkDEBUGCODE(size_t start = stream->bytesWritten());
349    stream->write32(count);
350
351    for (int i = 0; i < count; i++) {
352        const char* name = SkFlattenable::FactoryToName(array[i]);
353//        SkDebugf("---- write factories [%d] %p <%s>\n", i, array[i], name);
354        if (NULL == name || 0 == *name) {
355            stream->writePackedUInt(0);
356        } else {
357            uint32_t len = strlen(name);
358            stream->writePackedUInt(len);
359            stream->write(name, len);
360        }
361    }
362
363    SkASSERT(size == (stream->bytesWritten() - start));
364}
365
366static void write_typefaces(SkWStream* stream, const SkRefCntSet& rec) {
367    int count = rec.count();
368
369    write_tag_size(stream, SK_PICT_TYPEFACE_TAG, count);
370
371    SkAutoSTMalloc<16, SkTypeface*> storage(count);
372    SkTypeface** array = (SkTypeface**)storage.get();
373    rec.copyToArray((SkRefCnt**)array);
374
375    for (int i = 0; i < count; i++) {
376        array[i]->serialize(stream);
377    }
378}
379
380void SkPicturePlayback::flattenToBuffer(SkWriteBuffer& buffer) const {
381    int i, n;
382
383    if ((n = SafeCount(fBitmaps)) > 0) {
384        write_tag_size(buffer, SK_PICT_BITMAP_BUFFER_TAG, n);
385        for (i = 0; i < n; i++) {
386            buffer.writeBitmap((*fBitmaps)[i]);
387        }
388    }
389
390    if ((n = SafeCount(fPaints)) > 0) {
391        write_tag_size(buffer, SK_PICT_PAINT_BUFFER_TAG, n);
392        for (i = 0; i < n; i++) {
393            buffer.writePaint((*fPaints)[i]);
394        }
395    }
396
397    if ((n = SafeCount(fPathHeap.get())) > 0) {
398        write_tag_size(buffer, SK_PICT_PATH_BUFFER_TAG, n);
399        fPathHeap->flatten(buffer);
400    }
401}
402
403void SkPicturePlayback::serialize(SkWStream* stream,
404                                  SkPicture::EncodeBitmap encoder) const {
405    write_tag_size(stream, SK_PICT_READER_TAG, fOpData->size());
406    stream->write(fOpData->bytes(), fOpData->size());
407
408    if (fPictureCount > 0) {
409        write_tag_size(stream, SK_PICT_PICTURE_TAG, fPictureCount);
410        for (int i = 0; i < fPictureCount; i++) {
411            fPictureRefs[i]->serialize(stream, encoder);
412        }
413    }
414
415    // Write some of our data into a writebuffer, and then serialize that
416    // into our stream
417    {
418        SkRefCntSet  typefaceSet;
419        SkFactorySet factSet;
420
421        SkWriteBuffer buffer(SkWriteBuffer::kCrossProcess_Flag);
422        buffer.setTypefaceRecorder(&typefaceSet);
423        buffer.setFactoryRecorder(&factSet);
424        buffer.setBitmapEncoder(encoder);
425
426        this->flattenToBuffer(buffer);
427
428        // We have to write these two sets into the stream *before* we write
429        // the buffer, since parsing that buffer will require that we already
430        // have these sets available to use.
431        write_factories(stream, factSet);
432        write_typefaces(stream, typefaceSet);
433
434        write_tag_size(stream, SK_PICT_BUFFER_SIZE_TAG, buffer.bytesWritten());
435        buffer.writeToStream(stream);
436    }
437
438    stream->write32(SK_PICT_EOF_TAG);
439}
440
441void SkPicturePlayback::flatten(SkWriteBuffer& buffer) const {
442    write_tag_size(buffer, SK_PICT_READER_TAG, fOpData->size());
443    buffer.writeByteArray(fOpData->bytes(), fOpData->size());
444
445    if (fPictureCount > 0) {
446        write_tag_size(buffer, SK_PICT_PICTURE_TAG, fPictureCount);
447        for (int i = 0; i < fPictureCount; i++) {
448            fPictureRefs[i]->flatten(buffer);
449        }
450    }
451
452    // Write this picture playback's data into a writebuffer
453    this->flattenToBuffer(buffer);
454    buffer.write32(SK_PICT_EOF_TAG);
455}
456
457///////////////////////////////////////////////////////////////////////////////
458
459/**
460 *  Return the corresponding SkReadBuffer flags, given a set of
461 *  SkPictInfo flags.
462 */
463static uint32_t pictInfoFlagsToReadBufferFlags(uint32_t pictInfoFlags) {
464    static const struct {
465        uint32_t    fSrc;
466        uint32_t    fDst;
467    } gSD[] = {
468        { SkPictInfo::kCrossProcess_Flag,   SkReadBuffer::kCrossProcess_Flag },
469        { SkPictInfo::kScalarIsFloat_Flag,  SkReadBuffer::kScalarIsFloat_Flag },
470        { SkPictInfo::kPtrIs64Bit_Flag,     SkReadBuffer::kPtrIs64Bit_Flag },
471    };
472
473    uint32_t rbMask = 0;
474    for (size_t i = 0; i < SK_ARRAY_COUNT(gSD); ++i) {
475        if (pictInfoFlags & gSD[i].fSrc) {
476            rbMask |= gSD[i].fDst;
477        }
478    }
479    return rbMask;
480}
481
482bool SkPicturePlayback::parseStreamTag(SkStream* stream, const SkPictInfo& info, uint32_t tag,
483                                       size_t size, SkPicture::InstallPixelRefProc proc) {
484    /*
485     *  By the time we encounter BUFFER_SIZE_TAG, we need to have already seen
486     *  its dependents: FACTORY_TAG and TYPEFACE_TAG. These two are not required
487     *  but if they are present, they need to have been seen before the buffer.
488     *
489     *  We assert that if/when we see either of these, that we have not yet seen
490     *  the buffer tag, because if we have, then its too-late to deal with the
491     *  factories or typefaces.
492     */
493    SkDEBUGCODE(bool haveBuffer = false;)
494
495    switch (tag) {
496        case SK_PICT_READER_TAG: {
497            SkAutoMalloc storage(size);
498            if (stream->read(storage.get(), size) != size) {
499                return false;
500            }
501            SkASSERT(NULL == fOpData);
502            fOpData = SkData::NewFromMalloc(storage.detach(), size);
503        } break;
504        case SK_PICT_FACTORY_TAG: {
505            SkASSERT(!haveBuffer);
506        // Remove this code when v21 and below are no longer supported. At the
507        // same time add a new 'count' variable and use it rather then reusing 'size'.
508#ifndef DISABLE_V21_COMPATIBILITY_CODE
509            if (info.fVersion >= 22) {
510                // in v22 this tag's size represents the size of the chunk in bytes
511                // and the number of factory strings is written out separately
512#endif
513                size = stream->readU32();
514#ifndef DISABLE_V21_COMPATIBILITY_CODE
515            }
516#endif
517            fFactoryPlayback = SkNEW_ARGS(SkFactoryPlayback, (size));
518            for (size_t i = 0; i < size; i++) {
519                SkString str;
520                const size_t len = stream->readPackedUInt();
521                str.resize(len);
522                if (stream->read(str.writable_str(), len) != len) {
523                    return false;
524                }
525                fFactoryPlayback->base()[i] = SkFlattenable::NameToFactory(str.c_str());
526            }
527        } break;
528        case SK_PICT_TYPEFACE_TAG: {
529            SkASSERT(!haveBuffer);
530            fTFPlayback.setCount(size);
531            for (size_t i = 0; i < size; i++) {
532                SkAutoTUnref<SkTypeface> tf(SkTypeface::Deserialize(stream));
533                if (!tf.get()) {    // failed to deserialize
534                    // fTFPlayback asserts it never has a null, so we plop in
535                    // the default here.
536                    tf.reset(SkTypeface::RefDefault());
537                }
538                fTFPlayback.set(i, tf);
539            }
540        } break;
541        case SK_PICT_PICTURE_TAG: {
542            fPictureCount = size;
543            fPictureRefs = SkNEW_ARRAY(SkPicture*, fPictureCount);
544            bool success = true;
545            int i = 0;
546            for ( ; i < fPictureCount; i++) {
547                fPictureRefs[i] = SkPicture::CreateFromStream(stream, proc);
548                if (NULL == fPictureRefs[i]) {
549                    success = false;
550                    break;
551                }
552            }
553            if (!success) {
554                // Delete all of the pictures that were already created (up to but excluding i):
555                for (int j = 0; j < i; j++) {
556                    fPictureRefs[j]->unref();
557                }
558                // Delete the array
559                SkDELETE_ARRAY(fPictureRefs);
560                fPictureCount = 0;
561                return false;
562            }
563        } break;
564        case SK_PICT_BUFFER_SIZE_TAG: {
565            SkAutoMalloc storage(size);
566            if (stream->read(storage.get(), size) != size) {
567                return false;
568            }
569
570            SkReadBuffer buffer(storage.get(), size);
571            buffer.setFlags(pictInfoFlagsToReadBufferFlags(info.fFlags));
572
573            fFactoryPlayback->setupBuffer(buffer);
574            fTFPlayback.setupBuffer(buffer);
575            buffer.setBitmapDecoder(proc);
576
577            while (!buffer.eof()) {
578                tag = buffer.readUInt();
579                size = buffer.readUInt();
580                if (!this->parseBufferTag(buffer, tag, size)) {
581                    return false;
582                }
583            }
584            SkDEBUGCODE(haveBuffer = true;)
585        } break;
586    }
587    return true;    // success
588}
589
590bool SkPicturePlayback::parseBufferTag(SkReadBuffer& buffer,
591                                       uint32_t tag, size_t size) {
592    switch (tag) {
593        case SK_PICT_BITMAP_BUFFER_TAG: {
594            fBitmaps = SkTRefArray<SkBitmap>::Create(size);
595            for (size_t i = 0; i < size; ++i) {
596                SkBitmap* bm = &fBitmaps->writableAt(i);
597                buffer.readBitmap(bm);
598                bm->setImmutable();
599            }
600        } break;
601        case SK_PICT_PAINT_BUFFER_TAG: {
602            fPaints = SkTRefArray<SkPaint>::Create(size);
603            for (size_t i = 0; i < size; ++i) {
604                buffer.readPaint(&fPaints->writableAt(i));
605            }
606        } break;
607        case SK_PICT_PATH_BUFFER_TAG:
608            if (size > 0) {
609                fPathHeap.reset(SkNEW_ARGS(SkPathHeap, (buffer)));
610            }
611            break;
612        default:
613            // The tag was invalid.
614            return false;
615    }
616    return true;    // success
617}
618
619SkPicturePlayback* SkPicturePlayback::CreateFromStream(SkStream* stream,
620                                                       const SkPictInfo& info,
621                                                       SkPicture::InstallPixelRefProc proc) {
622    SkAutoTDelete<SkPicturePlayback> playback(SkNEW(SkPicturePlayback));
623
624    if (!playback->parseStream(stream, info, proc)) {
625        return NULL;
626    }
627    return playback.detach();
628}
629
630SkPicturePlayback* SkPicturePlayback::CreateFromBuffer(SkReadBuffer& buffer) {
631    SkAutoTDelete<SkPicturePlayback> playback(SkNEW(SkPicturePlayback));
632
633    if (!playback->parseBuffer(buffer)) {
634        return NULL;
635    }
636    return playback.detach();
637}
638
639bool SkPicturePlayback::parseStream(SkStream* stream, const SkPictInfo& info,
640                                    SkPicture::InstallPixelRefProc proc) {
641    for (;;) {
642        uint32_t tag = stream->readU32();
643        if (SK_PICT_EOF_TAG == tag) {
644            break;
645        }
646
647        uint32_t size = stream->readU32();
648        if (!this->parseStreamTag(stream, info, tag, size, proc)) {
649            return false; // we're invalid
650        }
651    }
652    return true;
653}
654
655bool SkPicturePlayback::parseBuffer(SkReadBuffer& buffer) {
656    for (;;) {
657        uint32_t tag = buffer.readUInt();
658        if (SK_PICT_EOF_TAG == tag) {
659            break;
660        }
661
662        uint32_t size = buffer.readUInt();
663        if (!this->parseBufferTag(buffer, tag, size)) {
664            return false; // we're invalid
665        }
666    }
667    return true;
668}
669
670///////////////////////////////////////////////////////////////////////////////
671///////////////////////////////////////////////////////////////////////////////
672
673#ifdef SPEW_CLIP_SKIPPING
674struct SkipClipRec {
675    int     fCount;
676    size_t  fSize;
677
678    SkipClipRec() {
679        fCount = 0;
680        fSize = 0;
681    }
682
683    void recordSkip(size_t bytes) {
684        fCount += 1;
685        fSize += bytes;
686    }
687};
688#endif
689
690#ifdef SK_DEVELOPER
691bool SkPicturePlayback::preDraw(int opIndex, int type) {
692    return false;
693}
694
695void SkPicturePlayback::postDraw(int opIndex) {
696}
697#endif
698
699/*
700 * Read the next op code and chunk size from 'reader'. The returned size
701 * is the entire size of the chunk (including the opcode). Thus, the
702 * offset just prior to calling read_op_and_size + 'size' is the offset
703 * to the next chunk's op code. This also means that the size of a chunk
704 * with no arguments (just an opcode) will be 4.
705 */
706static DrawType read_op_and_size(SkReader32* reader, uint32_t* size) {
707    uint32_t temp = reader->readInt();
708    uint32_t op;
709    if (((uint8_t) temp) == temp) {
710        // old skp file - no size information
711        op = temp;
712        *size = 0;
713    } else {
714        UNPACK_8_24(temp, op, *size);
715        if (MASK_24 == *size) {
716            *size = reader->readInt();
717        }
718    }
719    return (DrawType) op;
720}
721
722void SkPicturePlayback::draw(SkCanvas& canvas, SkDrawPictureCallback* callback) {
723#ifdef ENABLE_TIME_DRAW
724    SkAutoTime  at("SkPicture::draw", 50);
725#endif
726
727#ifdef SPEW_CLIP_SKIPPING
728    SkipClipRec skipRect, skipRRect, skipRegion, skipPath, skipCull;
729    int opCount = 0;
730#endif
731
732#ifdef SK_BUILD_FOR_ANDROID
733    SkAutoMutexAcquire autoMutex(fDrawMutex);
734#endif
735
736    // kDrawComplete will be the signal that we have reached the end of
737    // the command stream
738    static const uint32_t kDrawComplete = SK_MaxU32;
739
740    SkReader32 reader(fOpData->bytes(), fOpData->size());
741    TextContainer text;
742    SkTDArray<void*> results;
743
744    if (NULL != fStateTree && NULL != fBoundingHierarchy) {
745        SkRect clipBounds;
746        if (canvas.getClipBounds(&clipBounds)) {
747            SkIRect query;
748            clipBounds.roundOut(&query);
749            fBoundingHierarchy->search(query, &results);
750            if (results.count() == 0) {
751                return;
752            }
753            SkTQSort<SkPictureStateTree::Draw>(
754                reinterpret_cast<SkPictureStateTree::Draw**>(results.begin()),
755                reinterpret_cast<SkPictureStateTree::Draw**>(results.end()-1));
756        }
757    }
758
759    SkPictureStateTree::Iterator it = (NULL == fStateTree) ?
760        SkPictureStateTree::Iterator() :
761        fStateTree->getIterator(results, &canvas);
762
763    if (it.isValid()) {
764        uint32_t skipTo = it.draw();
765        if (kDrawComplete == skipTo) {
766            return;
767        }
768        reader.setOffset(skipTo);
769    }
770
771    // Record this, so we can concat w/ it if we encounter a setMatrix()
772    SkMatrix initialMatrix = canvas.getTotalMatrix();
773    int originalSaveCount = canvas.getSaveCount();
774
775#ifdef SK_BUILD_FOR_ANDROID
776    fAbortCurrentPlayback = false;
777#endif
778
779#ifdef SK_DEVELOPER
780    int opIndex = -1;
781#endif
782
783    while (!reader.eof()) {
784        if (callback && callback->abortDrawing()) {
785            canvas.restoreToCount(originalSaveCount);
786            return;
787        }
788#ifdef SK_BUILD_FOR_ANDROID
789        if (fAbortCurrentPlayback) {
790            return;
791        }
792#endif
793
794#ifdef SPEW_CLIP_SKIPPING
795        opCount++;
796#endif
797
798        size_t curOffset = reader.offset();
799        uint32_t size;
800        DrawType op = read_op_and_size(&reader, &size);
801        size_t skipTo = 0;
802        if (NOOP == op) {
803            // NOOPs are to be ignored - do not propagate them any further
804            skipTo = curOffset + size;
805#ifdef SK_DEVELOPER
806        } else {
807            opIndex++;
808            if (this->preDraw(opIndex, op)) {
809                skipTo = curOffset + size;
810            }
811#endif
812        }
813
814        if (0 != skipTo) {
815            if (it.isValid()) {
816                // If using a bounding box hierarchy, advance the state tree
817                // iterator until at or after skipTo
818                uint32_t adjustedSkipTo;
819                do {
820                    adjustedSkipTo = it.draw();
821                } while (adjustedSkipTo < skipTo);
822                skipTo = adjustedSkipTo;
823            }
824            if (kDrawComplete == skipTo) {
825                break;
826            }
827            reader.setOffset(skipTo);
828            continue;
829        }
830
831        switch (op) {
832            case CLIP_PATH: {
833                const SkPath& path = getPath(reader);
834                uint32_t packed = reader.readInt();
835                SkRegion::Op regionOp = ClipParams_unpackRegionOp(packed);
836                bool doAA = ClipParams_unpackDoAA(packed);
837                size_t offsetToRestore = reader.readInt();
838                SkASSERT(!offsetToRestore || \
839                    offsetToRestore >= reader.offset());
840                canvas.clipPath(path, regionOp, doAA);
841                if (canvas.isClipEmpty() && offsetToRestore) {
842#ifdef SPEW_CLIP_SKIPPING
843                    skipPath.recordSkip(offsetToRestore - reader.offset());
844#endif
845                    reader.setOffset(offsetToRestore);
846                }
847            } break;
848            case CLIP_REGION: {
849                SkRegion region;
850                this->getRegion(reader, &region);
851                uint32_t packed = reader.readInt();
852                SkRegion::Op regionOp = ClipParams_unpackRegionOp(packed);
853                size_t offsetToRestore = reader.readInt();
854                SkASSERT(!offsetToRestore || \
855                    offsetToRestore >= reader.offset());
856                canvas.clipRegion(region, regionOp);
857                if (canvas.isClipEmpty() && offsetToRestore) {
858#ifdef SPEW_CLIP_SKIPPING
859                    skipRegion.recordSkip(offsetToRestore - reader.offset());
860#endif
861                    reader.setOffset(offsetToRestore);
862                }
863            } break;
864            case CLIP_RECT: {
865                const SkRect& rect = reader.skipT<SkRect>();
866                uint32_t packed = reader.readInt();
867                SkRegion::Op regionOp = ClipParams_unpackRegionOp(packed);
868                bool doAA = ClipParams_unpackDoAA(packed);
869                size_t offsetToRestore = reader.readInt();
870                SkASSERT(!offsetToRestore || \
871                         offsetToRestore >= reader.offset());
872                canvas.clipRect(rect, regionOp, doAA);
873                if (canvas.isClipEmpty() && offsetToRestore) {
874#ifdef SPEW_CLIP_SKIPPING
875                    skipRect.recordSkip(offsetToRestore - reader.offset());
876#endif
877                    reader.setOffset(offsetToRestore);
878                }
879            } break;
880            case CLIP_RRECT: {
881                SkRRect rrect;
882                reader.readRRect(&rrect);
883                uint32_t packed = reader.readInt();
884                SkRegion::Op regionOp = ClipParams_unpackRegionOp(packed);
885                bool doAA = ClipParams_unpackDoAA(packed);
886                size_t offsetToRestore = reader.readInt();
887                SkASSERT(!offsetToRestore || \
888                         offsetToRestore >= reader.offset());
889                canvas.clipRRect(rrect, regionOp, doAA);
890                if (canvas.isClipEmpty() && offsetToRestore) {
891#ifdef SPEW_CLIP_SKIPPING
892                    skipRRect.recordSkip(offsetToRestore - reader.offset());
893#endif
894                    reader.setOffset(offsetToRestore);
895                }
896            } break;
897            case PUSH_CULL: {
898                const SkRect& cullRect = reader.skipT<SkRect>();
899                size_t offsetToRestore = reader.readInt();
900                if (offsetToRestore && canvas.quickReject(cullRect)) {
901#ifdef SPEW_CLIP_SKIPPING
902                    skipCull.recordSkip(offsetToRestore - reader.offset());
903#endif
904                    reader.setOffset(offsetToRestore);
905                } else {
906                    canvas.pushCull(cullRect);
907                }
908            } break;
909            case POP_CULL:
910                canvas.popCull();
911                break;
912            case CONCAT: {
913                SkMatrix matrix;
914                this->getMatrix(reader, &matrix);
915                canvas.concat(matrix);
916                break;
917            }
918            case DRAW_BITMAP: {
919                const SkPaint* paint = getPaint(reader);
920                const SkBitmap& bitmap = getBitmap(reader);
921                const SkPoint& loc = reader.skipT<SkPoint>();
922                canvas.drawBitmap(bitmap, loc.fX, loc.fY, paint);
923            } break;
924            case DRAW_BITMAP_RECT_TO_RECT: {
925                const SkPaint* paint = getPaint(reader);
926                const SkBitmap& bitmap = getBitmap(reader);
927                const SkRect* src = this->getRectPtr(reader);   // may be null
928                const SkRect& dst = reader.skipT<SkRect>();     // required
929                SkCanvas::DrawBitmapRectFlags flags;
930                flags = (SkCanvas::DrawBitmapRectFlags) reader.readInt();
931                canvas.drawBitmapRectToRect(bitmap, src, dst, paint, flags);
932            } break;
933            case DRAW_BITMAP_MATRIX: {
934                const SkPaint* paint = getPaint(reader);
935                const SkBitmap& bitmap = getBitmap(reader);
936                SkMatrix matrix;
937                this->getMatrix(reader, &matrix);
938                canvas.drawBitmapMatrix(bitmap, matrix, paint);
939            } break;
940            case DRAW_BITMAP_NINE: {
941                const SkPaint* paint = getPaint(reader);
942                const SkBitmap& bitmap = getBitmap(reader);
943                const SkIRect& src = reader.skipT<SkIRect>();
944                const SkRect& dst = reader.skipT<SkRect>();
945                canvas.drawBitmapNine(bitmap, src, dst, paint);
946            } break;
947            case DRAW_CLEAR:
948                canvas.clear(reader.readInt());
949                break;
950            case DRAW_DATA: {
951                size_t length = reader.readInt();
952                canvas.drawData(reader.skip(length), length);
953                // skip handles padding the read out to a multiple of 4
954            } break;
955            case DRAW_DRRECT: {
956                const SkPaint& paint = *getPaint(reader);
957                SkRRect outer, inner;
958                reader.readRRect(&outer);
959                reader.readRRect(&inner);
960                canvas.drawDRRect(outer, inner, paint);
961            } break;
962            case BEGIN_COMMENT_GROUP: {
963                const char* desc = reader.readString();
964                canvas.beginCommentGroup(desc);
965            } break;
966            case COMMENT: {
967                const char* kywd = reader.readString();
968                const char* value = reader.readString();
969                canvas.addComment(kywd, value);
970            } break;
971            case END_COMMENT_GROUP: {
972                canvas.endCommentGroup();
973            } break;
974            case DRAW_OVAL: {
975                const SkPaint& paint = *getPaint(reader);
976                canvas.drawOval(reader.skipT<SkRect>(), paint);
977            } break;
978            case DRAW_PAINT:
979                canvas.drawPaint(*getPaint(reader));
980                break;
981            case DRAW_PATH: {
982                const SkPaint& paint = *getPaint(reader);
983                canvas.drawPath(getPath(reader), paint);
984            } break;
985            case DRAW_PICTURE:
986                canvas.drawPicture(getPicture(reader));
987                break;
988            case DRAW_POINTS: {
989                const SkPaint& paint = *getPaint(reader);
990                SkCanvas::PointMode mode = (SkCanvas::PointMode)reader.readInt();
991                size_t count = reader.readInt();
992                const SkPoint* pts = (const SkPoint*)reader.skip(sizeof(SkPoint) * count);
993                canvas.drawPoints(mode, count, pts, paint);
994            } break;
995            case DRAW_POS_TEXT: {
996                const SkPaint& paint = *getPaint(reader);
997                getText(reader, &text);
998                size_t points = reader.readInt();
999                const SkPoint* pos = (const SkPoint*)reader.skip(points * sizeof(SkPoint));
1000                canvas.drawPosText(text.text(), text.length(), pos, paint);
1001            } break;
1002            case DRAW_POS_TEXT_TOP_BOTTOM: {
1003                const SkPaint& paint = *getPaint(reader);
1004                getText(reader, &text);
1005                size_t points = reader.readInt();
1006                const SkPoint* pos = (const SkPoint*)reader.skip(points * sizeof(SkPoint));
1007                const SkScalar top = reader.readScalar();
1008                const SkScalar bottom = reader.readScalar();
1009                if (!canvas.quickRejectY(top, bottom)) {
1010                    canvas.drawPosText(text.text(), text.length(), pos, paint);
1011                }
1012            } break;
1013            case DRAW_POS_TEXT_H: {
1014                const SkPaint& paint = *getPaint(reader);
1015                getText(reader, &text);
1016                size_t xCount = reader.readInt();
1017                const SkScalar constY = reader.readScalar();
1018                const SkScalar* xpos = (const SkScalar*)reader.skip(xCount * sizeof(SkScalar));
1019                canvas.drawPosTextH(text.text(), text.length(), xpos, constY,
1020                                    paint);
1021            } break;
1022            case DRAW_POS_TEXT_H_TOP_BOTTOM: {
1023                const SkPaint& paint = *getPaint(reader);
1024                getText(reader, &text);
1025                size_t xCount = reader.readInt();
1026                const SkScalar* xpos = (const SkScalar*)reader.skip((3 + xCount) * sizeof(SkScalar));
1027                const SkScalar top = *xpos++;
1028                const SkScalar bottom = *xpos++;
1029                const SkScalar constY = *xpos++;
1030                if (!canvas.quickRejectY(top, bottom)) {
1031                    canvas.drawPosTextH(text.text(), text.length(), xpos,
1032                                        constY, paint);
1033                }
1034            } break;
1035            case DRAW_RECT: {
1036                const SkPaint& paint = *getPaint(reader);
1037                canvas.drawRect(reader.skipT<SkRect>(), paint);
1038            } break;
1039            case DRAW_RRECT: {
1040                const SkPaint& paint = *getPaint(reader);
1041                SkRRect rrect;
1042                reader.readRRect(&rrect);
1043                canvas.drawRRect(rrect, paint);
1044            } break;
1045            case DRAW_SPRITE: {
1046                const SkPaint* paint = getPaint(reader);
1047                const SkBitmap& bitmap = getBitmap(reader);
1048                int left = reader.readInt();
1049                int top = reader.readInt();
1050                canvas.drawSprite(bitmap, left, top, paint);
1051            } break;
1052            case DRAW_TEXT: {
1053                const SkPaint& paint = *getPaint(reader);
1054                getText(reader, &text);
1055                SkScalar x = reader.readScalar();
1056                SkScalar y = reader.readScalar();
1057                canvas.drawText(text.text(), text.length(), x, y, paint);
1058            } break;
1059            case DRAW_TEXT_TOP_BOTTOM: {
1060                const SkPaint& paint = *getPaint(reader);
1061                getText(reader, &text);
1062                const SkScalar* ptr = (const SkScalar*)reader.skip(4 * sizeof(SkScalar));
1063                // ptr[0] == x
1064                // ptr[1] == y
1065                // ptr[2] == top
1066                // ptr[3] == bottom
1067                if (!canvas.quickRejectY(ptr[2], ptr[3])) {
1068                    canvas.drawText(text.text(), text.length(), ptr[0], ptr[1],
1069                                    paint);
1070                }
1071            } break;
1072            case DRAW_TEXT_ON_PATH: {
1073                const SkPaint& paint = *getPaint(reader);
1074                getText(reader, &text);
1075                const SkPath& path = getPath(reader);
1076                SkMatrix matrix;
1077                this->getMatrix(reader, &matrix);
1078                canvas.drawTextOnPath(text.text(), text.length(), path, &matrix, paint);
1079            } break;
1080            case DRAW_VERTICES: {
1081                SkAutoTUnref<SkXfermode> xfer;
1082                const SkPaint& paint = *getPaint(reader);
1083                DrawVertexFlags flags = (DrawVertexFlags)reader.readInt();
1084                SkCanvas::VertexMode vmode = (SkCanvas::VertexMode)reader.readInt();
1085                int vCount = reader.readInt();
1086                const SkPoint* verts = (const SkPoint*)reader.skip(
1087                                                    vCount * sizeof(SkPoint));
1088                const SkPoint* texs = NULL;
1089                const SkColor* colors = NULL;
1090                const uint16_t* indices = NULL;
1091                int iCount = 0;
1092                if (flags & DRAW_VERTICES_HAS_TEXS) {
1093                    texs = (const SkPoint*)reader.skip(
1094                                                    vCount * sizeof(SkPoint));
1095                }
1096                if (flags & DRAW_VERTICES_HAS_COLORS) {
1097                    colors = (const SkColor*)reader.skip(
1098                                                    vCount * sizeof(SkColor));
1099                }
1100                if (flags & DRAW_VERTICES_HAS_INDICES) {
1101                    iCount = reader.readInt();
1102                    indices = (const uint16_t*)reader.skip(
1103                                                    iCount * sizeof(uint16_t));
1104                }
1105                if (flags & DRAW_VERTICES_HAS_XFER) {
1106                    int mode = reader.readInt();
1107                    if (mode < 0 || mode > SkXfermode::kLastMode) {
1108                        mode = SkXfermode::kModulate_Mode;
1109                    }
1110                    xfer.reset(SkXfermode::Create((SkXfermode::Mode)mode));
1111                }
1112                canvas.drawVertices(vmode, vCount, verts, texs, colors, xfer,
1113                                    indices, iCount, paint);
1114            } break;
1115            case RESTORE:
1116                canvas.restore();
1117                break;
1118            case ROTATE:
1119                canvas.rotate(reader.readScalar());
1120                break;
1121            case SAVE:
1122                canvas.save((SkCanvas::SaveFlags) reader.readInt());
1123                break;
1124            case SAVE_LAYER: {
1125                const SkRect* boundsPtr = getRectPtr(reader);
1126                const SkPaint* paint = getPaint(reader);
1127                canvas.saveLayer(boundsPtr, paint, (SkCanvas::SaveFlags) reader.readInt());
1128                } break;
1129            case SCALE: {
1130                SkScalar sx = reader.readScalar();
1131                SkScalar sy = reader.readScalar();
1132                canvas.scale(sx, sy);
1133            } break;
1134            case SET_MATRIX: {
1135                SkMatrix matrix;
1136                this->getMatrix(reader, &matrix);
1137                matrix.postConcat(initialMatrix);
1138                canvas.setMatrix(matrix);
1139            } break;
1140            case SKEW: {
1141                SkScalar sx = reader.readScalar();
1142                SkScalar sy = reader.readScalar();
1143                canvas.skew(sx, sy);
1144            } break;
1145            case TRANSLATE: {
1146                SkScalar dx = reader.readScalar();
1147                SkScalar dy = reader.readScalar();
1148                canvas.translate(dx, dy);
1149            } break;
1150            default:
1151                SkASSERT(0);
1152        }
1153
1154#ifdef SK_DEVELOPER
1155        this->postDraw(opIndex);
1156#endif
1157
1158        if (it.isValid()) {
1159            uint32_t skipTo = it.draw();
1160            if (kDrawComplete == skipTo) {
1161                break;
1162            }
1163            reader.setOffset(skipTo);
1164        }
1165    }
1166
1167#ifdef SPEW_CLIP_SKIPPING
1168    {
1169        size_t size =  skipRect.fSize + skipRRect.fSize + skipPath.fSize + skipRegion.fSize +
1170                skipCull.fSize;
1171        SkDebugf("--- Clip skips %d%% rect:%d rrect:%d path:%d rgn:%d cull:%d\n",
1172             size * 100 / reader.offset(), skipRect.fCount, skipRRect.fCount,
1173                 skipPath.fCount, skipRegion.fCount, skipCull.fCount);
1174        SkDebugf("--- Total ops: %d\n", opCount);
1175    }
1176#endif
1177//    this->dumpSize();
1178}
1179
1180///////////////////////////////////////////////////////////////////////////////
1181
1182#ifdef SK_DEBUG_SIZE
1183int SkPicturePlayback::size(size_t* sizePtr) {
1184    int objects = bitmaps(sizePtr);
1185    objects += paints(sizePtr);
1186    objects += paths(sizePtr);
1187    objects += pictures(sizePtr);
1188    objects += regions(sizePtr);
1189    *sizePtr = fOpData.size();
1190    return objects;
1191}
1192
1193int SkPicturePlayback::bitmaps(size_t* size) {
1194    size_t result = 0;
1195    for (int index = 0; index < fBitmapCount; index++) {
1196     //   const SkBitmap& bitmap = fBitmaps[index];
1197        result += sizeof(SkBitmap); // bitmap->size();
1198    }
1199    *size = result;
1200    return fBitmapCount;
1201}
1202
1203int SkPicturePlayback::paints(size_t* size) {
1204    size_t result = 0;
1205    for (int index = 0; index < fPaintCount; index++) {
1206    //    const SkPaint& paint = fPaints[index];
1207        result += sizeof(SkPaint); // paint->size();
1208    }
1209    *size = result;
1210    return fPaintCount;
1211}
1212
1213int SkPicturePlayback::paths(size_t* size) {
1214    size_t result = 0;
1215    for (int index = 0; index < fPathCount; index++) {
1216        const SkPath& path = fPaths[index];
1217        result += path.flatten(NULL);
1218    }
1219    *size = result;
1220    return fPathCount;
1221}
1222#endif
1223
1224#ifdef SK_DEBUG_DUMP
1225void SkPicturePlayback::dumpBitmap(const SkBitmap& bitmap) const {
1226    char pBuffer[DUMP_BUFFER_SIZE];
1227    char* bufferPtr = pBuffer;
1228    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1229        "BitmapData bitmap%p = {", &bitmap);
1230    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1231        "{kWidth, %d}, ", bitmap.width());
1232    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1233        "{kHeight, %d}, ", bitmap.height());
1234    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1235        "{kRowBytes, %d}, ", bitmap.rowBytes());
1236//        start here;
1237    SkDebugf("%s{0}};\n", pBuffer);
1238}
1239
1240void dumpMatrix(const SkMatrix& matrix) const {
1241    SkMatrix defaultMatrix;
1242    defaultMatrix.reset();
1243    char pBuffer[DUMP_BUFFER_SIZE];
1244    char* bufferPtr = pBuffer;
1245    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1246        "MatrixData matrix%p = {", &matrix);
1247    SkScalar scaleX = matrix.getScaleX();
1248    if (scaleX != defaultMatrix.getScaleX())
1249        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1250            "{kScaleX, %g}, ", SkScalarToFloat(scaleX));
1251    SkScalar scaleY = matrix.getScaleY();
1252    if (scaleY != defaultMatrix.getScaleY())
1253        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1254            "{kScaleY, %g}, ", SkScalarToFloat(scaleY));
1255    SkScalar skewX = matrix.getSkewX();
1256    if (skewX != defaultMatrix.getSkewX())
1257        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1258            "{kSkewX, %g}, ", SkScalarToFloat(skewX));
1259    SkScalar skewY = matrix.getSkewY();
1260    if (skewY != defaultMatrix.getSkewY())
1261        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1262            "{kSkewY, %g}, ", SkScalarToFloat(skewY));
1263    SkScalar translateX = matrix.getTranslateX();
1264    if (translateX != defaultMatrix.getTranslateX())
1265        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1266            "{kTranslateX, %g}, ", SkScalarToFloat(translateX));
1267    SkScalar translateY = matrix.getTranslateY();
1268    if (translateY != defaultMatrix.getTranslateY())
1269        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1270            "{kTranslateY, %g}, ", SkScalarToFloat(translateY));
1271    SkScalar perspX = matrix.getPerspX();
1272    if (perspX != defaultMatrix.getPerspX())
1273        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1274            "{kPerspX, %g}, ", perspX);
1275    SkScalar perspY = matrix.getPerspY();
1276    if (perspY != defaultMatrix.getPerspY())
1277        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1278            "{kPerspY, %g}, ", perspY);
1279    SkDebugf("%s{0}};\n", pBuffer);
1280}
1281
1282void dumpPaint(const SkPaint& paint) const {
1283    SkPaint defaultPaint;
1284    char pBuffer[DUMP_BUFFER_SIZE];
1285    char* bufferPtr = pBuffer;
1286    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1287        "PaintPointers paintPtrs%p = {", &paint);
1288    const SkTypeface* typeface = paint.getTypeface();
1289    if (typeface != defaultPaint.getTypeface())
1290        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1291            "{kTypeface, %p}, ", typeface);
1292    const SkPathEffect* pathEffect = paint.getPathEffect();
1293    if (pathEffect != defaultPaint.getPathEffect())
1294        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1295            "{kPathEffect, %p}, ", pathEffect);
1296    const SkShader* shader = paint.getShader();
1297    if (shader != defaultPaint.getShader())
1298        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1299            "{kShader, %p}, ", shader);
1300    const SkXfermode* xfermode = paint.getXfermode();
1301    if (xfermode != defaultPaint.getXfermode())
1302        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1303            "{kXfermode, %p}, ", xfermode);
1304    const SkMaskFilter* maskFilter = paint.getMaskFilter();
1305    if (maskFilter != defaultPaint.getMaskFilter())
1306        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1307            "{kMaskFilter, %p}, ", maskFilter);
1308    const SkColorFilter* colorFilter = paint.getColorFilter();
1309    if (colorFilter != defaultPaint.getColorFilter())
1310        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1311            "{kColorFilter, %p}, ", colorFilter);
1312    const SkRasterizer* rasterizer = paint.getRasterizer();
1313    if (rasterizer != defaultPaint.getRasterizer())
1314        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1315            "{kRasterizer, %p}, ", rasterizer);
1316    const SkDrawLooper* drawLooper = paint.getLooper();
1317    if (drawLooper != defaultPaint.getLooper())
1318        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1319            "{kDrawLooper, %p}, ", drawLooper);
1320    SkDebugf("%s{0}};\n", pBuffer);
1321    bufferPtr = pBuffer;
1322    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1323        "PaintScalars paintScalars%p = {", &paint);
1324    SkScalar textSize = paint.getTextSize();
1325    if (textSize != defaultPaint.getTextSize())
1326        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1327            "{kTextSize, %g}, ", SkScalarToFloat(textSize));
1328    SkScalar textScaleX = paint.getTextScaleX();
1329    if (textScaleX != defaultPaint.getTextScaleX())
1330        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1331            "{kTextScaleX, %g}, ", SkScalarToFloat(textScaleX));
1332    SkScalar textSkewX = paint.getTextSkewX();
1333    if (textSkewX != defaultPaint.getTextSkewX())
1334        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1335            "{kTextSkewX, %g}, ", SkScalarToFloat(textSkewX));
1336    SkScalar strokeWidth = paint.getStrokeWidth();
1337    if (strokeWidth != defaultPaint.getStrokeWidth())
1338        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1339            "{kStrokeWidth, %g}, ", SkScalarToFloat(strokeWidth));
1340    SkScalar strokeMiter = paint.getStrokeMiter();
1341    if (strokeMiter != defaultPaint.getStrokeMiter())
1342        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1343            "{kStrokeMiter, %g}, ", SkScalarToFloat(strokeMiter));
1344    SkDebugf("%s{0}};\n", pBuffer);
1345    bufferPtr = pBuffer;
1346    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1347        "PaintInts = paintInts%p = {", &paint);
1348    unsigned color = paint.getColor();
1349    if (color != defaultPaint.getColor())
1350        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1351            "{kColor, 0x%x}, ", color);
1352    unsigned flags = paint.getFlags();
1353    if (flags != defaultPaint.getFlags())
1354        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1355            "{kFlags, 0x%x}, ", flags);
1356    int align = paint.getTextAlign();
1357    if (align != defaultPaint.getTextAlign())
1358        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1359            "{kAlign, 0x%x}, ", align);
1360    int strokeCap = paint.getStrokeCap();
1361    if (strokeCap != defaultPaint.getStrokeCap())
1362        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1363            "{kStrokeCap, 0x%x}, ", strokeCap);
1364    int strokeJoin = paint.getStrokeJoin();
1365    if (strokeJoin != defaultPaint.getStrokeJoin())
1366        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1367            "{kAlign, 0x%x}, ", strokeJoin);
1368    int style = paint.getStyle();
1369    if (style != defaultPaint.getStyle())
1370        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1371            "{kStyle, 0x%x}, ", style);
1372    int textEncoding = paint.getTextEncoding();
1373    if (textEncoding != defaultPaint.getTextEncoding())
1374        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1375            "{kTextEncoding, 0x%x}, ", textEncoding);
1376    SkDebugf("%s{0}};\n", pBuffer);
1377
1378    SkDebugf("PaintData paint%p = {paintPtrs%p, paintScalars%p, paintInts%p};\n",
1379        &paint, &paint, &paint, &paint);
1380}
1381
1382void SkPicturePlayback::dumpPath(const SkPath& path) const {
1383    SkDebugf("path dump unimplemented\n");
1384}
1385
1386void SkPicturePlayback::dumpPicture(const SkPicture& picture) const {
1387    SkDebugf("picture dump unimplemented\n");
1388}
1389
1390void SkPicturePlayback::dumpRegion(const SkRegion& region) const {
1391    SkDebugf("region dump unimplemented\n");
1392}
1393
1394int SkPicturePlayback::dumpDrawType(char* bufferPtr, char* buffer, DrawType drawType) {
1395    return snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1396        "k%s, ", DrawTypeToString(drawType));
1397}
1398
1399int SkPicturePlayback::dumpInt(char* bufferPtr, char* buffer, char* name) {
1400    return snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1401        "%s:%d, ", name, getInt());
1402}
1403
1404int SkPicturePlayback::dumpRect(char* bufferPtr, char* buffer, char* name) {
1405    const SkRect* rect = fReader.skipRect();
1406    return snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1407        "%s:{l:%g t:%g r:%g b:%g}, ", name, SkScalarToFloat(rect.fLeft),
1408        SkScalarToFloat(rect.fTop),
1409        SkScalarToFloat(rect.fRight), SkScalarToFloat(rect.fBottom));
1410}
1411
1412int SkPicturePlayback::dumpPoint(char* bufferPtr, char* buffer, char* name) {
1413    SkPoint pt;
1414    getPoint(&pt);
1415    return snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1416        "%s:{x:%g y:%g}, ", name, SkScalarToFloat(pt.fX),
1417        SkScalarToFloat(pt.fY));
1418}
1419
1420void SkPicturePlayback::dumpPointArray(char** bufferPtrPtr, char* buffer, int count) {
1421    char* bufferPtr = *bufferPtrPtr;
1422    const SkPoint* pts = (const SkPoint*)fReadStream.getAtPos();
1423    fReadStream.skip(sizeof(SkPoint) * count);
1424    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1425        "count:%d {", count);
1426    for (int index = 0; index < count; index++)
1427        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1428        "{x:%g y:%g}, ", SkScalarToFloat(pts[index].fX),
1429        SkScalarToFloat(pts[index].fY));
1430    bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1431        "} ");
1432    *bufferPtrPtr = bufferPtr;
1433}
1434
1435int SkPicturePlayback::dumpPtr(char* bufferPtr, char* buffer, char* name, void* ptr) {
1436    return snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1437        "%s:%p, ", name, ptr);
1438}
1439
1440int SkPicturePlayback::dumpRectPtr(char* bufferPtr, char* buffer, char* name) {
1441    char result;
1442    fReadStream.read(&result, sizeof(result));
1443    if (result)
1444        return dumpRect(bufferPtr, buffer, name);
1445    else
1446        return snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1447            "%s:NULL, ", name);
1448}
1449
1450int SkPicturePlayback::dumpScalar(char* bufferPtr, char* buffer, char* name) {
1451    return snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - buffer),
1452        "%s:%d, ", name, getScalar());
1453}
1454
1455void SkPicturePlayback::dumpText(char** bufferPtrPtr, char* buffer) {
1456    char* bufferPtr = *bufferPtrPtr;
1457    int length = getInt();
1458    bufferPtr += dumpDrawType(bufferPtr, buffer);
1459    fReadStream.skipToAlign4();
1460    char* text = (char*) fReadStream.getAtPos();
1461    fReadStream.skip(length);
1462    bufferPtr += dumpInt(bufferPtr, buffer, "length");
1463    int limit = DUMP_BUFFER_SIZE - (bufferPtr - buffer) - 2;
1464    length >>= 1;
1465    if (limit > length)
1466        limit = length;
1467    if (limit > 0) {
1468        *bufferPtr++ = '"';
1469        for (int index = 0; index < limit; index++) {
1470            *bufferPtr++ = *(unsigned short*) text;
1471            text += sizeof(unsigned short);
1472        }
1473        *bufferPtr++ = '"';
1474    }
1475    *bufferPtrPtr = bufferPtr;
1476}
1477
1478#define DUMP_DRAWTYPE(drawType) \
1479    bufferPtr += dumpDrawType(bufferPtr, buffer, drawType)
1480
1481#define DUMP_INT(name) \
1482    bufferPtr += dumpInt(bufferPtr, buffer, #name)
1483
1484#define DUMP_RECT_PTR(name) \
1485    bufferPtr += dumpRectPtr(bufferPtr, buffer, #name)
1486
1487#define DUMP_POINT(name) \
1488    bufferPtr += dumpRect(bufferPtr, buffer, #name)
1489
1490#define DUMP_RECT(name) \
1491    bufferPtr += dumpRect(bufferPtr, buffer, #name)
1492
1493#define DUMP_POINT_ARRAY(count) \
1494    dumpPointArray(&bufferPtr, buffer, count)
1495
1496#define DUMP_PTR(name, ptr) \
1497    bufferPtr += dumpPtr(bufferPtr, buffer, #name, (void*) ptr)
1498
1499#define DUMP_SCALAR(name) \
1500    bufferPtr += dumpScalar(bufferPtr, buffer, #name)
1501
1502#define DUMP_TEXT() \
1503    dumpText(&bufferPtr, buffer)
1504
1505void SkPicturePlayback::dumpStream() {
1506    SkDebugf("RecordStream stream = {\n");
1507    DrawType drawType;
1508    TextContainer text;
1509    fReadStream.rewind();
1510    char buffer[DUMP_BUFFER_SIZE], * bufferPtr;
1511    while (fReadStream.read(&drawType, sizeof(drawType))) {
1512        bufferPtr = buffer;
1513        DUMP_DRAWTYPE(drawType);
1514        switch (drawType) {
1515            case CLIP_PATH: {
1516                DUMP_PTR(SkPath, &getPath());
1517                DUMP_INT(SkRegion::Op);
1518                DUMP_INT(offsetToRestore);
1519                } break;
1520            case CLIP_REGION: {
1521                DUMP_INT(SkRegion::Op);
1522                DUMP_INT(offsetToRestore);
1523            } break;
1524            case CLIP_RECT: {
1525                DUMP_RECT(rect);
1526                DUMP_INT(SkRegion::Op);
1527                DUMP_INT(offsetToRestore);
1528                } break;
1529            case CONCAT:
1530                break;
1531            case DRAW_BITMAP: {
1532                DUMP_PTR(SkPaint, getPaint());
1533                DUMP_PTR(SkBitmap, &getBitmap());
1534                DUMP_SCALAR(left);
1535                DUMP_SCALAR(top);
1536                } break;
1537            case DRAW_PAINT:
1538                DUMP_PTR(SkPaint, getPaint());
1539                break;
1540            case DRAW_PATH: {
1541                DUMP_PTR(SkPaint, getPaint());
1542                DUMP_PTR(SkPath, &getPath());
1543                } break;
1544            case DRAW_PICTURE: {
1545                DUMP_PTR(SkPicture, &getPicture());
1546                } break;
1547            case DRAW_POINTS: {
1548                DUMP_PTR(SkPaint, getPaint());
1549                (void)getInt(); // PointMode
1550                size_t count = getInt();
1551                fReadStream.skipToAlign4();
1552                DUMP_POINT_ARRAY(count);
1553                } break;
1554            case DRAW_POS_TEXT: {
1555                DUMP_PTR(SkPaint, getPaint());
1556                DUMP_TEXT();
1557                size_t points = getInt();
1558                fReadStream.skipToAlign4();
1559                DUMP_POINT_ARRAY(points);
1560                } break;
1561            case DRAW_POS_TEXT_H: {
1562                DUMP_PTR(SkPaint, getPaint());
1563                DUMP_TEXT();
1564                size_t points = getInt();
1565                fReadStream.skipToAlign4();
1566                DUMP_SCALAR(top);
1567                DUMP_SCALAR(bottom);
1568                DUMP_SCALAR(constY);
1569                DUMP_POINT_ARRAY(points);
1570                } break;
1571            case DRAW_RECT: {
1572                DUMP_PTR(SkPaint, getPaint());
1573                DUMP_RECT(rect);
1574                } break;
1575            case DRAW_SPRITE: {
1576                DUMP_PTR(SkPaint, getPaint());
1577                DUMP_PTR(SkBitmap, &getBitmap());
1578                DUMP_SCALAR(left);
1579                DUMP_SCALAR(top);
1580                } break;
1581            case DRAW_TEXT: {
1582                DUMP_PTR(SkPaint, getPaint());
1583                DUMP_TEXT();
1584                DUMP_SCALAR(x);
1585                DUMP_SCALAR(y);
1586                } break;
1587            case DRAW_TEXT_ON_PATH: {
1588                DUMP_PTR(SkPaint, getPaint());
1589                DUMP_TEXT();
1590                DUMP_PTR(SkPath, &getPath());
1591                } break;
1592            case RESTORE:
1593                break;
1594            case ROTATE:
1595                DUMP_SCALAR(rotate);
1596                break;
1597            case SAVE:
1598                DUMP_INT(SkCanvas::SaveFlags);
1599                break;
1600            case SAVE_LAYER: {
1601                DUMP_RECT_PTR(layer);
1602                DUMP_PTR(SkPaint, getPaint());
1603                DUMP_INT(SkCanvas::SaveFlags);
1604                } break;
1605            case SCALE: {
1606                DUMP_SCALAR(sx);
1607                DUMP_SCALAR(sy);
1608                } break;
1609            case SKEW: {
1610                DUMP_SCALAR(sx);
1611                DUMP_SCALAR(sy);
1612                } break;
1613            case TRANSLATE: {
1614                DUMP_SCALAR(dx);
1615                DUMP_SCALAR(dy);
1616                } break;
1617            default:
1618                SkASSERT(0);
1619        }
1620        SkDebugf("%s\n", buffer);
1621    }
1622}
1623
1624void SkPicturePlayback::dump() const {
1625    char pBuffer[DUMP_BUFFER_SIZE];
1626    char* bufferPtr = pBuffer;
1627    int index;
1628    if (fBitmapCount > 0)
1629        SkDebugf("// bitmaps (%d)\n", fBitmapCount);
1630    for (index = 0; index < fBitmapCount; index++) {
1631        const SkBitmap& bitmap = fBitmaps[index];
1632        dumpBitmap(bitmap);
1633    }
1634    if (fBitmapCount > 0)
1635        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1636            "Bitmaps bitmaps = {");
1637    for (index = 0; index < fBitmapCount; index++)
1638        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1639            "bitmap%p, ", &fBitmaps[index]);
1640    if (fBitmapCount > 0)
1641        SkDebugf("%s0};\n", pBuffer);
1642
1643
1644    if (fPaintCount > 0)
1645        SkDebugf("// paints (%d)\n", fPaintCount);
1646    for (index = 0; index < fPaintCount; index++) {
1647        const SkPaint& paint = fPaints[index];
1648        dumpPaint(paint);
1649    }
1650    bufferPtr = pBuffer;
1651    if (fPaintCount > 0)
1652        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1653            "Paints paints = {");
1654    for (index = 0; index < fPaintCount; index++)
1655        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1656            "paint%p, ", &fPaints[index]);
1657    if (fPaintCount > 0)
1658        SkDebugf("%s0};\n", pBuffer);
1659
1660    for (index = 0; index < fPathCount; index++) {
1661        const SkPath& path = fPaths[index];
1662        dumpPath(path);
1663    }
1664    bufferPtr = pBuffer;
1665    if (fPathCount > 0)
1666        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1667            "Paths paths = {");
1668    for (index = 0; index < fPathCount; index++)
1669        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1670            "path%p, ", &fPaths[index]);
1671    if (fPathCount > 0)
1672        SkDebugf("%s0};\n", pBuffer);
1673
1674    for (index = 0; index < fPictureCount; index++) {
1675        dumpPicture(*fPictureRefs[index]);
1676    }
1677    bufferPtr = pBuffer;
1678    if (fPictureCount > 0)
1679        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1680            "Pictures pictures = {");
1681    for (index = 0; index < fPictureCount; index++)
1682        bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer),
1683            "picture%p, ", fPictureRefs[index]);
1684    if (fPictureCount > 0)
1685        SkDebugf("%s0};\n", pBuffer);
1686
1687    const_cast<SkPicturePlayback*>(this)->dumpStream();
1688}
1689
1690#endif
1691