PictureTest.cpp revision b950c6fd7188d625ed64ee6a3ea4f66d6d52e10c
1/*
2 * Copyright 2012 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkBitmapDevice.h"
9#include "SkCanvas.h"
10#include "SkColorPriv.h"
11#include "SkDashPathEffect.h"
12#include "SkData.h"
13#include "SkDecodingImageGenerator.h"
14#include "SkError.h"
15#include "SkImageEncoder.h"
16#include "SkImageGenerator.h"
17#include "SkPaint.h"
18#include "SkPicture.h"
19#include "SkPictureRecorder.h"
20#include "SkPictureUtils.h"
21#include "SkRRect.h"
22#include "SkRandom.h"
23#include "SkShader.h"
24#include "SkStream.h"
25#include "Test.h"
26
27static const int gColorScale = 30;
28static const int gColorOffset = 60;
29
30static void make_bm(SkBitmap* bm, int w, int h, SkColor color, bool immutable) {
31    bm->allocN32Pixels(w, h);
32    bm->eraseColor(color);
33    if (immutable) {
34        bm->setImmutable();
35    }
36}
37
38static void make_checkerboard(SkBitmap* bm, int w, int h, bool immutable) {
39    SkASSERT(w % 2 == 0);
40    SkASSERT(h % 2 == 0);
41    bm->allocPixels(SkImageInfo::Make(w, h, kAlpha_8_SkColorType,
42                                      kPremul_SkAlphaType));
43    SkAutoLockPixels lock(*bm);
44    for (int y = 0; y < h; y += 2) {
45        uint8_t* s = bm->getAddr8(0, y);
46        for (int x = 0; x < w; x += 2) {
47            *s++ = 0xFF;
48            *s++ = 0x00;
49        }
50        s = bm->getAddr8(0, y + 1);
51        for (int x = 0; x < w; x += 2) {
52            *s++ = 0x00;
53            *s++ = 0xFF;
54        }
55    }
56    if (immutable) {
57        bm->setImmutable();
58    }
59}
60
61static void init_paint(SkPaint* paint, const SkBitmap &bm) {
62    SkShader* shader = SkShader::CreateBitmapShader(bm,
63                                                    SkShader::kClamp_TileMode,
64                                                    SkShader::kClamp_TileMode);
65    paint->setShader(shader)->unref();
66}
67
68typedef void (*DrawBitmapProc)(SkCanvas*, const SkBitmap&,
69                               const SkBitmap&, const SkPoint&,
70                               SkTDArray<SkPixelRef*>* usedPixRefs);
71
72static void drawpaint_proc(SkCanvas* canvas, const SkBitmap& bm,
73                           const SkBitmap& altBM, const SkPoint& pos,
74                           SkTDArray<SkPixelRef*>* usedPixRefs) {
75    SkPaint paint;
76    init_paint(&paint, bm);
77
78    canvas->drawPaint(paint);
79    *usedPixRefs->append() = bm.pixelRef();
80}
81
82static void drawpoints_proc(SkCanvas* canvas, const SkBitmap& bm,
83                            const SkBitmap& altBM, const SkPoint& pos,
84                            SkTDArray<SkPixelRef*>* usedPixRefs) {
85    SkPaint paint;
86    init_paint(&paint, bm);
87
88    // draw a rect
89    SkPoint points[5] = {
90        { pos.fX, pos.fY },
91        { pos.fX + bm.width() - 1, pos.fY },
92        { pos.fX + bm.width() - 1, pos.fY + bm.height() - 1 },
93        { pos.fX, pos.fY + bm.height() - 1 },
94        { pos.fX, pos.fY },
95    };
96
97    canvas->drawPoints(SkCanvas::kPolygon_PointMode, 5, points, paint);
98    *usedPixRefs->append() = bm.pixelRef();
99}
100
101static void drawrect_proc(SkCanvas* canvas, const SkBitmap& bm,
102                          const SkBitmap& altBM, const SkPoint& pos,
103                          SkTDArray<SkPixelRef*>* usedPixRefs) {
104    SkPaint paint;
105    init_paint(&paint, bm);
106
107    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
108    r.offset(pos.fX, pos.fY);
109
110    canvas->drawRect(r, paint);
111    *usedPixRefs->append() = bm.pixelRef();
112}
113
114static void drawoval_proc(SkCanvas* canvas, const SkBitmap& bm,
115                          const SkBitmap& altBM, const SkPoint& pos,
116                          SkTDArray<SkPixelRef*>* usedPixRefs) {
117    SkPaint paint;
118    init_paint(&paint, bm);
119
120    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
121    r.offset(pos.fX, pos.fY);
122
123    canvas->drawOval(r, paint);
124    *usedPixRefs->append() = bm.pixelRef();
125}
126
127static void drawrrect_proc(SkCanvas* canvas, const SkBitmap& bm,
128                           const SkBitmap& altBM, const SkPoint& pos,
129                           SkTDArray<SkPixelRef*>* usedPixRefs) {
130    SkPaint paint;
131    init_paint(&paint, bm);
132
133    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
134    r.offset(pos.fX, pos.fY);
135
136    SkRRect rr;
137    rr.setRectXY(r, SkIntToScalar(bm.width())/4, SkIntToScalar(bm.height())/4);
138    canvas->drawRRect(rr, paint);
139    *usedPixRefs->append() = bm.pixelRef();
140}
141
142static void drawpath_proc(SkCanvas* canvas, const SkBitmap& bm,
143                          const SkBitmap& altBM, const SkPoint& pos,
144                          SkTDArray<SkPixelRef*>* usedPixRefs) {
145    SkPaint paint;
146    init_paint(&paint, bm);
147
148    SkPath path;
149    path.lineTo(bm.width()/2.0f, SkIntToScalar(bm.height()));
150    path.lineTo(SkIntToScalar(bm.width()), 0);
151    path.close();
152    path.offset(pos.fX, pos.fY);
153
154    canvas->drawPath(path, paint);
155    *usedPixRefs->append() = bm.pixelRef();
156}
157
158static void drawbitmap_proc(SkCanvas* canvas, const SkBitmap& bm,
159                            const SkBitmap& altBM, const SkPoint& pos,
160                            SkTDArray<SkPixelRef*>* usedPixRefs) {
161    canvas->drawBitmap(bm, pos.fX, pos.fY, NULL);
162    *usedPixRefs->append() = bm.pixelRef();
163}
164
165static void drawbitmap_withshader_proc(SkCanvas* canvas, const SkBitmap& bm,
166                                       const SkBitmap& altBM, const SkPoint& pos,
167                                       SkTDArray<SkPixelRef*>* usedPixRefs) {
168    SkPaint paint;
169    init_paint(&paint, bm);
170
171    // The bitmap in the paint is ignored unless we're drawing an A8 bitmap
172    canvas->drawBitmap(altBM, pos.fX, pos.fY, &paint);
173    *usedPixRefs->append() = bm.pixelRef();
174    *usedPixRefs->append() = altBM.pixelRef();
175}
176
177static void drawsprite_proc(SkCanvas* canvas, const SkBitmap& bm,
178                            const SkBitmap& altBM, const SkPoint& pos,
179                            SkTDArray<SkPixelRef*>* usedPixRefs) {
180    const SkMatrix& ctm = canvas->getTotalMatrix();
181
182    SkPoint p(pos);
183    ctm.mapPoints(&p, 1);
184
185    canvas->drawSprite(bm, (int)p.fX, (int)p.fY, NULL);
186    *usedPixRefs->append() = bm.pixelRef();
187}
188
189#if 0
190// Although specifiable, this case doesn't seem to make sense (i.e., the
191// bitmap in the shader is never used).
192static void drawsprite_withshader_proc(SkCanvas* canvas, const SkBitmap& bm,
193                                       const SkBitmap& altBM, const SkPoint& pos,
194                                       SkTDArray<SkPixelRef*>* usedPixRefs) {
195    SkPaint paint;
196    init_paint(&paint, bm);
197
198    const SkMatrix& ctm = canvas->getTotalMatrix();
199
200    SkPoint p(pos);
201    ctm.mapPoints(&p, 1);
202
203    canvas->drawSprite(altBM, (int)p.fX, (int)p.fY, &paint);
204    *usedPixRefs->append() = bm.pixelRef();
205    *usedPixRefs->append() = altBM.pixelRef();
206}
207#endif
208
209static void drawbitmaprect_proc(SkCanvas* canvas, const SkBitmap& bm,
210                                const SkBitmap& altBM, const SkPoint& pos,
211                                SkTDArray<SkPixelRef*>* usedPixRefs) {
212    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
213
214    r.offset(pos.fX, pos.fY);
215    canvas->drawBitmapRectToRect(bm, NULL, r, NULL);
216    *usedPixRefs->append() = bm.pixelRef();
217}
218
219static void drawbitmaprect_withshader_proc(SkCanvas* canvas,
220                                           const SkBitmap& bm,
221                                           const SkBitmap& altBM,
222                                           const SkPoint& pos,
223                                           SkTDArray<SkPixelRef*>* usedPixRefs) {
224    SkPaint paint;
225    init_paint(&paint, bm);
226
227    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
228    r.offset(pos.fX, pos.fY);
229
230    // The bitmap in the paint is ignored unless we're drawing an A8 bitmap
231    canvas->drawBitmapRectToRect(altBM, NULL, r, &paint);
232    *usedPixRefs->append() = bm.pixelRef();
233    *usedPixRefs->append() = altBM.pixelRef();
234}
235
236static void drawtext_proc(SkCanvas* canvas, const SkBitmap& bm,
237                          const SkBitmap& altBM, const SkPoint& pos,
238                          SkTDArray<SkPixelRef*>* usedPixRefs) {
239    SkPaint paint;
240    init_paint(&paint, bm);
241    paint.setTextSize(SkIntToScalar(1.5*bm.width()));
242
243    canvas->drawText("0", 1, pos.fX, pos.fY+bm.width(), paint);
244    *usedPixRefs->append() = bm.pixelRef();
245}
246
247static void drawpostext_proc(SkCanvas* canvas, const SkBitmap& bm,
248                             const SkBitmap& altBM, const SkPoint& pos,
249                             SkTDArray<SkPixelRef*>* usedPixRefs) {
250    SkPaint paint;
251    init_paint(&paint, bm);
252    paint.setTextSize(SkIntToScalar(1.5*bm.width()));
253
254    SkPoint point = { pos.fX, pos.fY + bm.height() };
255    canvas->drawPosText("O", 1, &point, paint);
256    *usedPixRefs->append() = bm.pixelRef();
257}
258
259static void drawtextonpath_proc(SkCanvas* canvas, const SkBitmap& bm,
260                                const SkBitmap& altBM, const SkPoint& pos,
261                                SkTDArray<SkPixelRef*>* usedPixRefs) {
262    SkPaint paint;
263
264    init_paint(&paint, bm);
265    paint.setTextSize(SkIntToScalar(1.5*bm.width()));
266
267    SkPath path;
268    path.lineTo(SkIntToScalar(bm.width()), 0);
269    path.offset(pos.fX, pos.fY+bm.height());
270
271    canvas->drawTextOnPath("O", 1, path, NULL, paint);
272    *usedPixRefs->append() = bm.pixelRef();
273}
274
275static void drawverts_proc(SkCanvas* canvas, const SkBitmap& bm,
276                           const SkBitmap& altBM, const SkPoint& pos,
277                           SkTDArray<SkPixelRef*>* usedPixRefs) {
278    SkPaint paint;
279    init_paint(&paint, bm);
280
281    SkPoint verts[4] = {
282        { pos.fX, pos.fY },
283        { pos.fX + bm.width(), pos.fY },
284        { pos.fX + bm.width(), pos.fY + bm.height() },
285        { pos.fX, pos.fY + bm.height() }
286    };
287    SkPoint texs[4] = { { 0, 0 },
288                        { SkIntToScalar(bm.width()), 0 },
289                        { SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) },
290                        { 0, SkIntToScalar(bm.height()) } };
291    uint16_t indices[6] = { 0, 1, 2, 0, 2, 3 };
292
293    canvas->drawVertices(SkCanvas::kTriangles_VertexMode, 4, verts, texs, NULL, NULL,
294                         indices, 6, paint);
295    *usedPixRefs->append() = bm.pixelRef();
296}
297
298// Return a picture with the bitmaps drawn at the specified positions.
299static SkPicture* record_bitmaps(const SkBitmap bm[],
300                                 const SkPoint pos[],
301                                 SkTDArray<SkPixelRef*> analytic[],
302                                 int count,
303                                 DrawBitmapProc proc) {
304    SkPictureRecorder recorder;
305    SkCanvas* canvas = recorder.beginRecording(1000, 1000, NULL, 0);
306    for (int i = 0; i < count; ++i) {
307        analytic[i].rewind();
308        canvas->save();
309        SkRect clipRect = SkRect::MakeXYWH(pos[i].fX, pos[i].fY,
310                                           SkIntToScalar(bm[i].width()),
311                                           SkIntToScalar(bm[i].height()));
312        canvas->clipRect(clipRect, SkRegion::kIntersect_Op);
313        proc(canvas, bm[i], bm[count+i], pos[i], &analytic[i]);
314        canvas->restore();
315    }
316    return recorder.endRecording();
317}
318
319static void rand_rect(SkRect* rect, SkRandom& rand, SkScalar W, SkScalar H) {
320    rect->fLeft   = rand.nextRangeScalar(-W, 2*W);
321    rect->fTop    = rand.nextRangeScalar(-H, 2*H);
322    rect->fRight  = rect->fLeft + rand.nextRangeScalar(0, W);
323    rect->fBottom = rect->fTop + rand.nextRangeScalar(0, H);
324
325    // we integralize rect to make our tests more predictable, since Gather is
326    // a little sloppy.
327    SkIRect ir;
328    rect->round(&ir);
329    rect->set(ir);
330}
331
332static void draw(SkPicture* pic, int width, int height, SkBitmap* result) {
333    make_bm(result, width, height, SK_ColorBLACK, false);
334
335    SkCanvas canvas(*result);
336    canvas.drawPicture(*pic);
337}
338
339template <typename T> int find_index(const T* array, T elem, int count) {
340    for (int i = 0; i < count; ++i) {
341        if (array[i] == elem) {
342            return i;
343        }
344    }
345    return -1;
346}
347
348// Return true if 'ref' is found in array[]
349static bool find(SkPixelRef const * const * array, SkPixelRef const * ref, int count) {
350    return find_index<const SkPixelRef*>(array, ref, count) >= 0;
351}
352
353// Look at each pixel that is inside 'subset', and if its color appears in
354// colors[], find the corresponding value in refs[] and append that ref into
355// array, skipping duplicates of the same value.
356// Note that gathering pixelRefs from rendered colors suffers from the problem
357// that multiple simultaneous textures (e.g., A8 for alpha and 8888 for color)
358// isn't easy to reconstruct.
359static void gather_from_image(const SkBitmap& bm, SkPixelRef* const refs[],
360                              int count, SkTDArray<SkPixelRef*>* array,
361                              const SkRect& subset) {
362    SkIRect ir;
363    subset.roundOut(&ir);
364
365    if (!ir.intersect(0, 0, bm.width()-1, bm.height()-1)) {
366        return;
367    }
368
369    // Since we only want to return unique values in array, when we scan we just
370    // set a bit for each index'd color found. In practice we only have a few
371    // distinct colors, so we just use an int's bits as our array. Hence the
372    // assert that count <= number-of-bits-in-our-int.
373    SkASSERT((unsigned)count <= 32);
374    uint32_t bitarray = 0;
375
376    SkAutoLockPixels alp(bm);
377
378    for (int y = ir.fTop; y < ir.fBottom; ++y) {
379        for (int x = ir.fLeft; x < ir.fRight; ++x) {
380            SkPMColor pmc = *bm.getAddr32(x, y);
381            // the only good case where the color is not found would be if
382            // the color is transparent, meaning no bitmap was drawn in that
383            // pixel.
384            if (pmc) {
385                uint32_t index = SkGetPackedR32(pmc);
386                SkASSERT(SkGetPackedG32(pmc) == index);
387                SkASSERT(SkGetPackedB32(pmc) == index);
388                if (0 == index) {
389                    continue;           // background color
390                }
391                SkASSERT(0 == (index - gColorOffset) % gColorScale);
392                index = (index - gColorOffset) / gColorScale;
393                SkASSERT(static_cast<int>(index) < count);
394                bitarray |= 1 << index;
395            }
396        }
397    }
398
399    for (int i = 0; i < count; ++i) {
400        if (bitarray & (1 << i)) {
401            *array->append() = refs[i];
402        }
403    }
404}
405
406static void gather_from_analytic(const SkPoint pos[], SkScalar w, SkScalar h,
407                                 const SkTDArray<SkPixelRef*> analytic[],
408                                 int count,
409                                 SkTDArray<SkPixelRef*>* result,
410                                 const SkRect& subset) {
411    for (int i = 0; i < count; ++i) {
412        SkRect rect = SkRect::MakeXYWH(pos[i].fX, pos[i].fY, w, h);
413
414        if (SkRect::Intersects(subset, rect)) {
415            result->append(analytic[i].count(), analytic[i].begin());
416        }
417    }
418}
419
420
421static const struct {
422    const DrawBitmapProc proc;
423    const char* const desc;
424} gProcs[] = {
425    {drawpaint_proc, "drawpaint"},
426    {drawpoints_proc, "drawpoints"},
427    {drawrect_proc, "drawrect"},
428    {drawoval_proc, "drawoval"},
429    {drawrrect_proc, "drawrrect"},
430    {drawpath_proc, "drawpath"},
431    {drawbitmap_proc, "drawbitmap"},
432    {drawbitmap_withshader_proc, "drawbitmap_withshader"},
433    {drawsprite_proc, "drawsprite"},
434#if 0
435    {drawsprite_withshader_proc, "drawsprite_withshader"},
436#endif
437    {drawbitmaprect_proc, "drawbitmaprect"},
438    {drawbitmaprect_withshader_proc, "drawbitmaprect_withshader"},
439    {drawtext_proc, "drawtext"},
440    {drawpostext_proc, "drawpostext"},
441    {drawtextonpath_proc, "drawtextonpath"},
442    {drawverts_proc, "drawverts"},
443};
444
445static void create_textures(SkBitmap* bm, SkPixelRef** refs, int num, int w, int h) {
446    // Our convention is that the color components contain an encoding of
447    // the index of their corresponding bitmap/pixelref. (0,0,0,0) is
448    // reserved for the background
449    for (int i = 0; i < num; ++i) {
450        make_bm(&bm[i], w, h,
451                SkColorSetARGB(0xFF,
452                               gColorScale*i+gColorOffset,
453                               gColorScale*i+gColorOffset,
454                               gColorScale*i+gColorOffset),
455                true);
456        refs[i] = bm[i].pixelRef();
457    }
458
459    // The A8 alternate bitmaps are all BW checkerboards
460    for (int i = 0; i < num; ++i) {
461        make_checkerboard(&bm[num+i], w, h, true);
462        refs[num+i] = bm[num+i].pixelRef();
463    }
464}
465
466static void test_gatherpixelrefs(skiatest::Reporter* reporter) {
467    const int IW = 32;
468    const int IH = IW;
469    const SkScalar W = SkIntToScalar(IW);
470    const SkScalar H = W;
471
472    static const int N = 4;
473    SkBitmap bm[2*N];
474    SkPixelRef* refs[2*N];
475    SkTDArray<SkPixelRef*> analytic[N];
476
477    const SkPoint pos[N] = {
478        { 0, 0 }, { W, 0 }, { 0, H }, { W, H }
479    };
480
481    create_textures(bm, refs, N, IW, IH);
482
483    SkRandom rand;
484    for (size_t k = 0; k < SK_ARRAY_COUNT(gProcs); ++k) {
485        SkAutoTUnref<SkPicture> pic(
486            record_bitmaps(bm, pos, analytic, N, gProcs[k].proc));
487
488        REPORTER_ASSERT(reporter, pic->willPlayBackBitmaps() || N == 0);
489        // quick check for a small piece of each quadrant, which should just
490        // contain 1 or 2 bitmaps.
491        for (size_t  i = 0; i < SK_ARRAY_COUNT(pos); ++i) {
492            SkRect r;
493            r.set(2, 2, W - 2, H - 2);
494            r.offset(pos[i].fX, pos[i].fY);
495            SkAutoDataUnref data(SkPictureUtils::GatherPixelRefs(pic, r));
496            if (!data) {
497                ERRORF(reporter, "SkPictureUtils::GatherPixelRefs returned "
498                       "NULL for %s.", gProcs[k].desc);
499                continue;
500            }
501            SkPixelRef** gatheredRefs = (SkPixelRef**)data->data();
502            int count = static_cast<int>(data->size() / sizeof(SkPixelRef*));
503            REPORTER_ASSERT(reporter, 1 == count || 2 == count);
504            if (1 == count) {
505                REPORTER_ASSERT(reporter, gatheredRefs[0] == refs[i]);
506            } else if (2 == count) {
507                REPORTER_ASSERT(reporter,
508                    (gatheredRefs[0] == refs[i] && gatheredRefs[1] == refs[i+N]) ||
509                    (gatheredRefs[1] == refs[i] && gatheredRefs[0] == refs[i+N]));
510            }
511        }
512
513        SkBitmap image;
514        draw(pic, 2*IW, 2*IH, &image);
515
516        // Test a bunch of random (mostly) rects, and compare the gather results
517        // with a deduced list of refs by looking at the colors drawn.
518        for (int j = 0; j < 100; ++j) {
519            SkRect r;
520            rand_rect(&r, rand, 2*W, 2*H);
521
522            SkTDArray<SkPixelRef*> fromImage;
523            gather_from_image(image, refs, N, &fromImage, r);
524
525            SkTDArray<SkPixelRef*> fromAnalytic;
526            gather_from_analytic(pos, W, H, analytic, N, &fromAnalytic, r);
527
528            SkData* data = SkPictureUtils::GatherPixelRefs(pic, r);
529            size_t dataSize = data ? data->size() : 0;
530            int gatherCount = static_cast<int>(dataSize / sizeof(SkPixelRef*));
531            SkASSERT(gatherCount * sizeof(SkPixelRef*) == dataSize);
532            SkPixelRef** gatherRefs = data ? (SkPixelRef**)(data->data()) : NULL;
533            SkAutoDataUnref adu(data);
534
535            // Everything that we saw drawn should appear in the analytic list
536            // but the analytic list may contain some pixelRefs that were not
537            // seen in the image (e.g., A8 textures used as masks)
538            for (int i = 0; i < fromImage.count(); ++i) {
539                if (-1 == fromAnalytic.find(fromImage[i])) {
540                    ERRORF(reporter, "PixelRef missing %d %s",
541                           i, gProcs[k].desc);
542                }
543            }
544
545            /*
546             *  GatherPixelRefs is conservative, so it can return more bitmaps
547             *  than are strictly required. Thus our check here is only that
548             *  Gather didn't miss any that we actually needed. Even that isn't
549             *  a strict requirement on Gather, which is meant to be quick and
550             *  only mostly-correct, but at the moment this test should work.
551             */
552            for (int i = 0; i < fromAnalytic.count(); ++i) {
553                bool found = find(gatherRefs, fromAnalytic[i], gatherCount);
554                if (!found) {
555                    ERRORF(reporter, "PixelRef missing %d %s",
556                           i, gProcs[k].desc);
557                }
558#if 0
559                // enable this block of code to debug failures, as it will rerun
560                // the case that failed.
561                if (!found) {
562                    SkData* data = SkPictureUtils::GatherPixelRefs(pic, r);
563                    size_t dataSize = data ? data->size() : 0;
564                }
565#endif
566            }
567        }
568    }
569}
570
571static void test_gatherpixelrefsandrects(skiatest::Reporter* reporter) {
572    const int IW = 32;
573    const int IH = IW;
574    const SkScalar W = SkIntToScalar(IW);
575    const SkScalar H = W;
576
577    static const int N = 4;
578    SkBitmap bm[2*N];
579    SkPixelRef* refs[2*N];
580    SkTDArray<SkPixelRef*> analytic[N];
581
582    const SkPoint pos[N] = {
583        { 0, 0 }, { W, 0 }, { 0, H }, { W, H }
584    };
585
586    create_textures(bm, refs, N, IW, IH);
587
588    SkRandom rand;
589    for (size_t k = 0; k < SK_ARRAY_COUNT(gProcs); ++k) {
590        SkAutoTUnref<SkPicture> pic(
591            record_bitmaps(bm, pos, analytic, N, gProcs[k].proc));
592
593        REPORTER_ASSERT(reporter, pic->willPlayBackBitmaps() || N == 0);
594
595        SkAutoTUnref<SkPictureUtils::SkPixelRefContainer> prCont(
596                                new SkPictureUtils::SkPixelRefsAndRectsList);
597
598        SkPictureUtils::GatherPixelRefsAndRects(pic, prCont);
599
600        // quick check for a small piece of each quadrant, which should just
601        // contain 1 or 2 bitmaps.
602        for (size_t  i = 0; i < SK_ARRAY_COUNT(pos); ++i) {
603            SkRect r;
604            r.set(2, 2, W - 2, H - 2);
605            r.offset(pos[i].fX, pos[i].fY);
606
607            SkTDArray<SkPixelRef*> gatheredRefs;
608            prCont->query(r, &gatheredRefs);
609
610            int count = gatheredRefs.count();
611            REPORTER_ASSERT(reporter, 1 == count || 2 == count);
612            if (1 == count) {
613                REPORTER_ASSERT(reporter, gatheredRefs[0] == refs[i]);
614            } else if (2 == count) {
615                REPORTER_ASSERT(reporter,
616                    (gatheredRefs[0] == refs[i] && gatheredRefs[1] == refs[i+N]) ||
617                    (gatheredRefs[1] == refs[i] && gatheredRefs[0] == refs[i+N]));
618            }
619        }
620
621        SkBitmap image;
622        draw(pic, 2*IW, 2*IH, &image);
623
624        // Test a bunch of random (mostly) rects, and compare the gather results
625        // with the analytic results and the pixel refs seen in a rendering.
626        for (int j = 0; j < 100; ++j) {
627            SkRect r;
628            rand_rect(&r, rand, 2*W, 2*H);
629
630            SkTDArray<SkPixelRef*> fromImage;
631            gather_from_image(image, refs, N, &fromImage, r);
632
633            SkTDArray<SkPixelRef*> fromAnalytic;
634            gather_from_analytic(pos, W, H, analytic, N, &fromAnalytic, r);
635
636            SkTDArray<SkPixelRef*> gatheredRefs;
637            prCont->query(r, &gatheredRefs);
638
639            // Everything that we saw drawn should appear in the analytic list
640            // but the analytic list may contain some pixelRefs that were not
641            // seen in the image (e.g., A8 textures used as masks)
642            for (int i = 0; i < fromImage.count(); ++i) {
643                REPORTER_ASSERT(reporter, -1 != fromAnalytic.find(fromImage[i]));
644            }
645
646            // Everything in the analytic list should appear in the gathered
647            // list.
648            for (int i = 0; i < fromAnalytic.count(); ++i) {
649                REPORTER_ASSERT(reporter, -1 != gatheredRefs.find(fromAnalytic[i]));
650            }
651        }
652    }
653}
654
655#ifdef SK_DEBUG
656// Ensure that deleting SkPicturePlayback does not assert. Asserts only fire in debug mode, so only
657// run in debug mode.
658static void test_deleting_empty_playback() {
659    SkPictureRecorder recorder;
660    // Creates an SkPictureRecord
661    recorder.beginRecording(0, 0, NULL, 0);
662    // Turns that into an SkPicturePlayback
663    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
664    // Deletes the old SkPicturePlayback, and creates a new SkPictureRecord
665    recorder.beginRecording(0, 0, NULL, 0);
666}
667
668// Ensure that serializing an empty picture does not assert. Likewise only runs in debug mode.
669static void test_serializing_empty_picture() {
670    SkPictureRecorder recorder;
671    recorder.beginRecording(0, 0, NULL, 0);
672    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
673    SkDynamicMemoryWStream stream;
674    picture->serialize(&stream);
675}
676#endif
677
678static void rand_op(SkCanvas* canvas, SkRandom& rand) {
679    SkPaint paint;
680    SkRect rect = SkRect::MakeWH(50, 50);
681
682    SkScalar unit = rand.nextUScalar1();
683    if (unit <= 0.3) {
684//        SkDebugf("save\n");
685        canvas->save();
686    } else if (unit <= 0.6) {
687//        SkDebugf("restore\n");
688        canvas->restore();
689    } else if (unit <= 0.9) {
690//        SkDebugf("clip\n");
691        canvas->clipRect(rect);
692    } else {
693//        SkDebugf("draw\n");
694        canvas->drawPaint(paint);
695    }
696}
697
698#if SK_SUPPORT_GPU
699static void test_gpu_veto(skiatest::Reporter* reporter) {
700
701    SkPictureRecorder recorder;
702
703    SkCanvas* canvas = recorder.beginRecording(100, 100, NULL, 0);
704    {
705        SkPath path;
706        path.moveTo(0, 0);
707        path.lineTo(50, 50);
708
709        SkScalar intervals[] = { 1.0f, 1.0f };
710        SkAutoTUnref<SkDashPathEffect> dash(SkDashPathEffect::Create(intervals, 2, 0));
711
712        SkPaint paint;
713        paint.setStyle(SkPaint::kStroke_Style);
714        paint.setPathEffect(dash);
715
716        canvas->drawPath(path, paint);
717    }
718    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
719    // path effects currently render an SkPicture undesireable for GPU rendering
720    REPORTER_ASSERT(reporter, !picture->suitableForGpuRasterization(NULL));
721
722    canvas = recorder.beginRecording(100, 100, NULL, 0);
723    {
724        SkPath path;
725
726        path.moveTo(0, 0);
727        path.lineTo(0, 50);
728        path.lineTo(25, 25);
729        path.lineTo(50, 50);
730        path.lineTo(50, 0);
731        path.close();
732        REPORTER_ASSERT(reporter, !path.isConvex());
733
734        SkPaint paint;
735        paint.setAntiAlias(true);
736        for (int i = 0; i < 50; ++i) {
737            canvas->drawPath(path, paint);
738        }
739    }
740    picture.reset(recorder.endRecording());
741    // A lot of AA concave paths currently render an SkPicture undesireable for GPU rendering
742    REPORTER_ASSERT(reporter, !picture->suitableForGpuRasterization(NULL));
743
744    canvas = recorder.beginRecording(100, 100, NULL, 0);
745    {
746        SkPath path;
747
748        path.moveTo(0, 0);
749        path.lineTo(0, 50);
750        path.lineTo(25, 25);
751        path.lineTo(50, 50);
752        path.lineTo(50, 0);
753        path.close();
754        REPORTER_ASSERT(reporter, !path.isConvex());
755
756        SkPaint paint;
757        paint.setAntiAlias(true);
758        paint.setStyle(SkPaint::kStroke_Style);
759        paint.setStrokeWidth(0);
760        for (int i = 0; i < 50; ++i) {
761            canvas->drawPath(path, paint);
762        }
763    }
764    picture.reset(recorder.endRecording());
765    // hairline stroked AA concave paths are fine for GPU rendering
766    REPORTER_ASSERT(reporter, picture->suitableForGpuRasterization(NULL));
767}
768#endif
769
770static void set_canvas_to_save_count_4(SkCanvas* canvas) {
771    canvas->restoreToCount(1);
772    canvas->save();
773    canvas->save();
774    canvas->save();
775}
776
777static void test_unbalanced_save_restores(skiatest::Reporter* reporter) {
778    SkCanvas testCanvas(100, 100);
779    set_canvas_to_save_count_4(&testCanvas);
780
781    REPORTER_ASSERT(reporter, 4 == testCanvas.getSaveCount());
782
783    SkPaint paint;
784    SkRect rect = SkRect::MakeLTRB(-10000000, -10000000, 10000000, 10000000);
785
786    SkPictureRecorder recorder;
787
788    {
789        // Create picture with 2 unbalanced saves
790        SkCanvas* canvas = recorder.beginRecording(100, 100, NULL, 0);
791        canvas->save();
792        canvas->translate(10, 10);
793        canvas->drawRect(rect, paint);
794        canvas->save();
795        canvas->translate(10, 10);
796        canvas->drawRect(rect, paint);
797        SkAutoTUnref<SkPicture> extraSavePicture(recorder.endRecording());
798
799        testCanvas.drawPicture(*extraSavePicture);
800        REPORTER_ASSERT(reporter, 4 == testCanvas.getSaveCount());
801    }
802
803    set_canvas_to_save_count_4(&testCanvas);
804
805    {
806        // Create picture with 2 unbalanced restores
807        SkCanvas* canvas = recorder.beginRecording(100, 100, NULL, 0);
808        canvas->save();
809        canvas->translate(10, 10);
810        canvas->drawRect(rect, paint);
811        canvas->save();
812        canvas->translate(10, 10);
813        canvas->drawRect(rect, paint);
814        canvas->restore();
815        canvas->restore();
816        canvas->restore();
817        canvas->restore();
818        SkAutoTUnref<SkPicture> extraRestorePicture(recorder.endRecording());
819
820        testCanvas.drawPicture(*extraRestorePicture);
821        REPORTER_ASSERT(reporter, 4 == testCanvas.getSaveCount());
822    }
823
824    set_canvas_to_save_count_4(&testCanvas);
825
826    {
827        SkCanvas* canvas = recorder.beginRecording(100, 100, NULL, 0);
828        canvas->translate(10, 10);
829        canvas->drawRect(rect, paint);
830        SkAutoTUnref<SkPicture> noSavePicture(recorder.endRecording());
831
832        testCanvas.drawPicture(*noSavePicture);
833        REPORTER_ASSERT(reporter, 4 == testCanvas.getSaveCount());
834        REPORTER_ASSERT(reporter, testCanvas.getTotalMatrix().isIdentity());
835    }
836}
837
838static void test_peephole() {
839    SkRandom rand;
840
841    SkPictureRecorder recorder;
842
843    for (int j = 0; j < 100; j++) {
844        SkRandom rand2(rand); // remember the seed
845
846        SkCanvas* canvas = recorder.beginRecording(100, 100, NULL, 0);
847
848        for (int i = 0; i < 1000; ++i) {
849            rand_op(canvas, rand);
850        }
851        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
852
853        rand = rand2;
854    }
855
856    {
857        SkCanvas* canvas = recorder.beginRecording(100, 100, NULL, 0);
858        SkRect rect = SkRect::MakeWH(50, 50);
859
860        for (int i = 0; i < 100; ++i) {
861            canvas->save();
862        }
863        while (canvas->getSaveCount() > 1) {
864            canvas->clipRect(rect);
865            canvas->restore();
866        }
867        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
868    }
869}
870
871#ifndef SK_DEBUG
872// Only test this is in release mode. We deliberately crash in debug mode, since a valid caller
873// should never do this.
874static void test_bad_bitmap() {
875    // This bitmap has a width and height but no pixels. As a result, attempting to record it will
876    // fail.
877    SkBitmap bm;
878    bm.setConfig(SkImageInfo::MakeN32Premul(100, 100));
879    SkPictureRecorder recorder;
880    SkCanvas* recordingCanvas = recorder.beginRecording(100, 100, NULL, 0);
881    recordingCanvas->drawBitmap(bm, 0, 0);
882    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
883
884    SkCanvas canvas;
885    canvas.drawPicture(*picture);
886}
887#endif
888
889static SkData* encode_bitmap_to_data(size_t*, const SkBitmap& bm) {
890    return SkImageEncoder::EncodeData(bm, SkImageEncoder::kPNG_Type, 100);
891}
892
893static SkData* serialized_picture_from_bitmap(const SkBitmap& bitmap) {
894    SkPictureRecorder recorder;
895    SkCanvas* canvas = recorder.beginRecording(bitmap.width(), bitmap.height(), NULL, 0);
896    canvas->drawBitmap(bitmap, 0, 0);
897    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
898
899    SkDynamicMemoryWStream wStream;
900    picture->serialize(&wStream, &encode_bitmap_to_data);
901    return wStream.copyToData();
902}
903
904struct ErrorContext {
905    int fErrors;
906    skiatest::Reporter* fReporter;
907};
908
909static void assert_one_parse_error_cb(SkError error, void* context) {
910    ErrorContext* errorContext = static_cast<ErrorContext*>(context);
911    errorContext->fErrors++;
912    // This test only expects one error, and that is a kParseError. If there are others,
913    // there is some unknown problem.
914    REPORTER_ASSERT_MESSAGE(errorContext->fReporter, 1 == errorContext->fErrors,
915                            "This threw more errors than expected.");
916    REPORTER_ASSERT_MESSAGE(errorContext->fReporter, kParseError_SkError == error,
917                            SkGetLastErrorString());
918}
919
920static void test_bitmap_with_encoded_data(skiatest::Reporter* reporter) {
921    // Create a bitmap that will be encoded.
922    SkBitmap original;
923    make_bm(&original, 100, 100, SK_ColorBLUE, true);
924    SkDynamicMemoryWStream wStream;
925    if (!SkImageEncoder::EncodeStream(&wStream, original, SkImageEncoder::kPNG_Type, 100)) {
926        return;
927    }
928    SkAutoDataUnref data(wStream.copyToData());
929
930    SkBitmap bm;
931    bool installSuccess = SkInstallDiscardablePixelRef(
932         SkDecodingImageGenerator::Create(data, SkDecodingImageGenerator::Options()), &bm, NULL);
933    REPORTER_ASSERT(reporter, installSuccess);
934
935    // Write both bitmaps to pictures, and ensure that the resulting data streams are the same.
936    // Flattening original will follow the old path of performing an encode, while flattening bm
937    // will use the already encoded data.
938    SkAutoDataUnref picture1(serialized_picture_from_bitmap(original));
939    SkAutoDataUnref picture2(serialized_picture_from_bitmap(bm));
940    REPORTER_ASSERT(reporter, picture1->equals(picture2));
941    // Now test that a parse error was generated when trying to create a new SkPicture without
942    // providing a function to decode the bitmap.
943    ErrorContext context;
944    context.fErrors = 0;
945    context.fReporter = reporter;
946    SkSetErrorCallback(assert_one_parse_error_cb, &context);
947    SkMemoryStream pictureStream(picture1);
948    SkClearLastError();
949    SkAutoUnref pictureFromStream(SkPicture::CreateFromStream(&pictureStream, NULL));
950    REPORTER_ASSERT(reporter, pictureFromStream.get() != NULL);
951    SkClearLastError();
952    SkSetErrorCallback(NULL, NULL);
953}
954
955static void test_clone_empty(skiatest::Reporter* reporter) {
956    // This is a regression test for crbug.com/172062
957    // Before the fix, we used to crash accessing a null pointer when we
958    // had a picture with no paints. This test passes by not crashing.
959    {
960        SkPictureRecorder recorder;
961        recorder.beginRecording(1, 1, NULL, 0);
962        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
963        SkAutoTUnref<SkPicture> destPicture(picture->clone());
964        REPORTER_ASSERT(reporter, NULL != destPicture);
965    }
966}
967
968static void test_draw_empty(skiatest::Reporter* reporter) {
969    SkBitmap result;
970    make_bm(&result, 2, 2, SK_ColorBLACK, false);
971
972    SkCanvas canvas(result);
973
974    {
975        // stock SkPicture
976        SkPictureRecorder recorder;
977        recorder.beginRecording(1, 1, NULL, 0);
978        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
979
980        canvas.drawPicture(*picture);
981    }
982
983    {
984        // tile grid
985        SkTileGridFactory::TileGridInfo gridInfo;
986        gridInfo.fMargin.setEmpty();
987        gridInfo.fOffset.setZero();
988        gridInfo.fTileInterval.set(1, 1);
989
990        SkTileGridFactory factory(gridInfo);
991        SkPictureRecorder recorder;
992        recorder.beginRecording(1, 1, &factory, 0);
993        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
994
995        canvas.drawPicture(*picture);
996    }
997
998    {
999        // RTree
1000        SkRTreeFactory factory;
1001        SkPictureRecorder recorder;
1002        recorder.beginRecording(1, 1, &factory, 0);
1003        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1004
1005        canvas.drawPicture(*picture);
1006    }
1007
1008    {
1009        // quad tree
1010        SkQuadTreeFactory factory;
1011        SkPictureRecorder recorder;
1012        recorder.beginRecording(1, 1, &factory, 0);
1013        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1014
1015        canvas.drawPicture(*picture);
1016    }
1017}
1018
1019static void test_clip_bound_opt(skiatest::Reporter* reporter) {
1020    // Test for crbug.com/229011
1021    SkRect rect1 = SkRect::MakeXYWH(SkIntToScalar(4), SkIntToScalar(4),
1022                                    SkIntToScalar(2), SkIntToScalar(2));
1023    SkRect rect2 = SkRect::MakeXYWH(SkIntToScalar(7), SkIntToScalar(7),
1024                                    SkIntToScalar(1), SkIntToScalar(1));
1025    SkRect rect3 = SkRect::MakeXYWH(SkIntToScalar(6), SkIntToScalar(6),
1026                                    SkIntToScalar(1), SkIntToScalar(1));
1027
1028    SkPath invPath;
1029    invPath.addOval(rect1);
1030    invPath.setFillType(SkPath::kInverseEvenOdd_FillType);
1031    SkPath path;
1032    path.addOval(rect2);
1033    SkPath path2;
1034    path2.addOval(rect3);
1035    SkIRect clipBounds;
1036    SkPictureRecorder recorder;
1037    // Minimalist test set for 100% code coverage of
1038    // SkPictureRecord::updateClipConservativelyUsingBounds
1039    {
1040        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL,
1041            SkPicture::kUsePathBoundsForClip_RecordingFlag);
1042        canvas->clipPath(invPath, SkRegion::kIntersect_Op);
1043        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1044        REPORTER_ASSERT(reporter, true == nonEmpty);
1045        REPORTER_ASSERT(reporter, 0 == clipBounds.fLeft);
1046        REPORTER_ASSERT(reporter, 0 == clipBounds.fTop);
1047        REPORTER_ASSERT(reporter, 10 == clipBounds.fBottom);
1048        REPORTER_ASSERT(reporter, 10 == clipBounds.fRight);
1049    }
1050    {
1051        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL,
1052            SkPicture::kUsePathBoundsForClip_RecordingFlag);
1053        canvas->clipPath(path, SkRegion::kIntersect_Op);
1054        canvas->clipPath(invPath, SkRegion::kIntersect_Op);
1055        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1056        REPORTER_ASSERT(reporter, true == nonEmpty);
1057        REPORTER_ASSERT(reporter, 7 == clipBounds.fLeft);
1058        REPORTER_ASSERT(reporter, 7 == clipBounds.fTop);
1059        REPORTER_ASSERT(reporter, 8 == clipBounds.fBottom);
1060        REPORTER_ASSERT(reporter, 8 == clipBounds.fRight);
1061    }
1062    {
1063        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL,
1064            SkPicture::kUsePathBoundsForClip_RecordingFlag);
1065        canvas->clipPath(path, SkRegion::kIntersect_Op);
1066        canvas->clipPath(invPath, SkRegion::kUnion_Op);
1067        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1068        REPORTER_ASSERT(reporter, true == nonEmpty);
1069        REPORTER_ASSERT(reporter, 0 == clipBounds.fLeft);
1070        REPORTER_ASSERT(reporter, 0 == clipBounds.fTop);
1071        REPORTER_ASSERT(reporter, 10 == clipBounds.fBottom);
1072        REPORTER_ASSERT(reporter, 10 == clipBounds.fRight);
1073    }
1074    {
1075        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL,
1076            SkPicture::kUsePathBoundsForClip_RecordingFlag);
1077        canvas->clipPath(path, SkRegion::kDifference_Op);
1078        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1079        REPORTER_ASSERT(reporter, true == nonEmpty);
1080        REPORTER_ASSERT(reporter, 0 == clipBounds.fLeft);
1081        REPORTER_ASSERT(reporter, 0 == clipBounds.fTop);
1082        REPORTER_ASSERT(reporter, 10 == clipBounds.fBottom);
1083        REPORTER_ASSERT(reporter, 10 == clipBounds.fRight);
1084    }
1085    {
1086        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL,
1087            SkPicture::kUsePathBoundsForClip_RecordingFlag);
1088        canvas->clipPath(path, SkRegion::kReverseDifference_Op);
1089        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1090        // True clip is actually empty in this case, but the best
1091        // determination we can make using only bounds as input is that the
1092        // clip is included in the bounds of 'path'.
1093        REPORTER_ASSERT(reporter, true == nonEmpty);
1094        REPORTER_ASSERT(reporter, 7 == clipBounds.fLeft);
1095        REPORTER_ASSERT(reporter, 7 == clipBounds.fTop);
1096        REPORTER_ASSERT(reporter, 8 == clipBounds.fBottom);
1097        REPORTER_ASSERT(reporter, 8 == clipBounds.fRight);
1098    }
1099    {
1100        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL,
1101            SkPicture::kUsePathBoundsForClip_RecordingFlag);
1102        canvas->clipPath(path, SkRegion::kIntersect_Op);
1103        canvas->clipPath(path2, SkRegion::kXOR_Op);
1104        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1105        REPORTER_ASSERT(reporter, true == nonEmpty);
1106        REPORTER_ASSERT(reporter, 6 == clipBounds.fLeft);
1107        REPORTER_ASSERT(reporter, 6 == clipBounds.fTop);
1108        REPORTER_ASSERT(reporter, 8 == clipBounds.fBottom);
1109        REPORTER_ASSERT(reporter, 8 == clipBounds.fRight);
1110    }
1111}
1112
1113/**
1114 * A canvas that records the number of clip commands.
1115 */
1116class ClipCountingCanvas : public SkCanvas {
1117public:
1118    explicit ClipCountingCanvas(int width, int height)
1119        : INHERITED(width, height)
1120        , fClipCount(0){
1121    }
1122
1123    virtual void onClipRect(const SkRect& r,
1124                            SkRegion::Op op,
1125                            ClipEdgeStyle edgeStyle) SK_OVERRIDE {
1126        fClipCount += 1;
1127        this->INHERITED::onClipRect(r, op, edgeStyle);
1128    }
1129
1130    virtual void onClipRRect(const SkRRect& rrect,
1131                             SkRegion::Op op,
1132                             ClipEdgeStyle edgeStyle)SK_OVERRIDE {
1133        fClipCount += 1;
1134        this->INHERITED::onClipRRect(rrect, op, edgeStyle);
1135    }
1136
1137    virtual void onClipPath(const SkPath& path,
1138                            SkRegion::Op op,
1139                            ClipEdgeStyle edgeStyle) SK_OVERRIDE {
1140        fClipCount += 1;
1141        this->INHERITED::onClipPath(path, op, edgeStyle);
1142    }
1143
1144    virtual void onClipRegion(const SkRegion& deviceRgn, SkRegion::Op op) SK_OVERRIDE {
1145        fClipCount += 1;
1146        this->INHERITED::onClipRegion(deviceRgn, op);
1147    }
1148
1149    unsigned getClipCount() const { return fClipCount; }
1150
1151private:
1152    unsigned fClipCount;
1153
1154    typedef SkCanvas INHERITED;
1155};
1156
1157static void test_clip_expansion(skiatest::Reporter* reporter) {
1158    SkPictureRecorder recorder;
1159    SkCanvas* canvas = recorder.beginRecording(10, 10, NULL, 0);
1160
1161    canvas->clipRect(SkRect::MakeEmpty(), SkRegion::kReplace_Op);
1162    // The following expanding clip should not be skipped.
1163    canvas->clipRect(SkRect::MakeXYWH(4, 4, 3, 3), SkRegion::kUnion_Op);
1164    // Draw something so the optimizer doesn't just fold the world.
1165    SkPaint p;
1166    p.setColor(SK_ColorBLUE);
1167    canvas->drawPaint(p);
1168    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1169
1170    ClipCountingCanvas testCanvas(10, 10);
1171    picture->draw(&testCanvas);
1172
1173    // Both clips should be present on playback.
1174    REPORTER_ASSERT(reporter, testCanvas.getClipCount() == 2);
1175}
1176
1177static void test_hierarchical(skiatest::Reporter* reporter) {
1178    SkBitmap bm;
1179    make_bm(&bm, 10, 10, SK_ColorRED, true);
1180
1181    SkPictureRecorder recorder;
1182
1183    recorder.beginRecording(10, 10, NULL, 0);
1184    SkAutoTUnref<SkPicture> childPlain(recorder.endRecording());
1185    REPORTER_ASSERT(reporter, !childPlain->willPlayBackBitmaps()); // 0
1186
1187    recorder.beginRecording(10, 10, NULL, 0)->drawBitmap(bm, 0, 0);
1188    SkAutoTUnref<SkPicture> childWithBitmap(recorder.endRecording());
1189    REPORTER_ASSERT(reporter, childWithBitmap->willPlayBackBitmaps()); // 1
1190
1191    {
1192        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL, 0);
1193        canvas->drawPicture(*childPlain);
1194        SkAutoTUnref<SkPicture> parentPP(recorder.endRecording());
1195        REPORTER_ASSERT(reporter, !parentPP->willPlayBackBitmaps()); // 0
1196    }
1197    {
1198        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL, 0);
1199        canvas->drawPicture(*childWithBitmap);
1200        SkAutoTUnref<SkPicture> parentPWB(recorder.endRecording());
1201        REPORTER_ASSERT(reporter, parentPWB->willPlayBackBitmaps()); // 1
1202    }
1203    {
1204        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL, 0);
1205        canvas->drawBitmap(bm, 0, 0);
1206        canvas->drawPicture(*childPlain);
1207        SkAutoTUnref<SkPicture> parentWBP(recorder.endRecording());
1208        REPORTER_ASSERT(reporter, parentWBP->willPlayBackBitmaps()); // 1
1209    }
1210    {
1211        SkCanvas* canvas = recorder.beginRecording(10, 10, NULL, 0);
1212        canvas->drawBitmap(bm, 0, 0);
1213        canvas->drawPicture(*childWithBitmap);
1214        SkAutoTUnref<SkPicture> parentWBWB(recorder.endRecording());
1215        REPORTER_ASSERT(reporter, parentWBWB->willPlayBackBitmaps()); // 2
1216    }
1217}
1218
1219static void test_gen_id(skiatest::Reporter* reporter) {
1220
1221    SkPicture empty;
1222
1223    // Empty pictures should still have a valid ID
1224    REPORTER_ASSERT(reporter, empty.uniqueID() != SK_InvalidGenID);
1225
1226    SkPictureRecorder recorder;
1227
1228    SkCanvas* canvas = recorder.beginRecording(1, 1, NULL, 0);
1229    canvas->drawARGB(255, 255, 255, 255);
1230    SkAutoTUnref<SkPicture> hasData(recorder.endRecording());
1231    // picture should have a non-zero id after recording
1232    REPORTER_ASSERT(reporter, hasData->uniqueID() != SK_InvalidGenID);
1233
1234    // both pictures should have different ids
1235    REPORTER_ASSERT(reporter, hasData->uniqueID() != empty.uniqueID());
1236
1237    // test out copy constructor
1238    SkPicture copyWithData(*hasData);
1239    REPORTER_ASSERT(reporter, hasData->uniqueID() == copyWithData.uniqueID());
1240
1241    SkPicture emptyCopy(empty);
1242    REPORTER_ASSERT(reporter, empty.uniqueID() != emptyCopy.uniqueID());
1243
1244    // test out swap
1245    {
1246        SkPicture swapWithData;
1247        uint32_t beforeID1 = swapWithData.uniqueID();
1248        uint32_t beforeID2 = copyWithData.uniqueID();
1249        swapWithData.swap(copyWithData);
1250        REPORTER_ASSERT(reporter, copyWithData.uniqueID() == beforeID1);
1251        REPORTER_ASSERT(reporter, swapWithData.uniqueID() == beforeID2);
1252    }
1253
1254    // test out clone
1255    {
1256        SkAutoTUnref<SkPicture> cloneWithData(hasData->clone());
1257        REPORTER_ASSERT(reporter, hasData->uniqueID() == cloneWithData->uniqueID());
1258
1259        SkAutoTUnref<SkPicture> emptyClone(empty.clone());
1260        REPORTER_ASSERT(reporter, empty.uniqueID() != emptyClone->uniqueID());
1261    }
1262}
1263
1264DEF_TEST(Picture, reporter) {
1265#ifdef SK_DEBUG
1266    test_deleting_empty_playback();
1267    test_serializing_empty_picture();
1268#else
1269    test_bad_bitmap();
1270#endif
1271    test_unbalanced_save_restores(reporter);
1272    test_peephole();
1273#if SK_SUPPORT_GPU
1274    test_gpu_veto(reporter);
1275#endif
1276    test_gatherpixelrefs(reporter);
1277    test_gatherpixelrefsandrects(reporter);
1278    test_bitmap_with_encoded_data(reporter);
1279    test_clone_empty(reporter);
1280    test_draw_empty(reporter);
1281    test_clip_bound_opt(reporter);
1282    test_clip_expansion(reporter);
1283    test_hierarchical(reporter);
1284    test_gen_id(reporter);
1285}
1286
1287static void draw_bitmaps(const SkBitmap bitmap, SkCanvas* canvas) {
1288    const SkPaint paint;
1289    const SkRect rect = { 5.0f, 5.0f, 8.0f, 8.0f };
1290    const SkIRect irect =  { 2, 2, 3, 3 };
1291
1292    // Don't care what these record, as long as they're legal.
1293    canvas->drawBitmap(bitmap, 0.0f, 0.0f, &paint);
1294    canvas->drawBitmapRectToRect(bitmap, &rect, rect, &paint, SkCanvas::kNone_DrawBitmapRectFlag);
1295    canvas->drawBitmapMatrix(bitmap, SkMatrix::I(), &paint);
1296    canvas->drawBitmapNine(bitmap, irect, rect, &paint);
1297    canvas->drawSprite(bitmap, 1, 1);
1298}
1299
1300static void test_draw_bitmaps(SkCanvas* canvas) {
1301    SkBitmap empty;
1302    draw_bitmaps(empty, canvas);
1303    empty.setConfig(SkImageInfo::MakeN32Premul(10, 10));
1304    draw_bitmaps(empty, canvas);
1305}
1306
1307DEF_TEST(Picture_EmptyBitmap, r) {
1308    SkPictureRecorder recorder;
1309    test_draw_bitmaps(recorder.beginRecording(10, 10, NULL, 0));
1310    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1311}
1312
1313DEF_TEST(Canvas_EmptyBitmap, r) {
1314    SkBitmap dst;
1315    dst.allocN32Pixels(10, 10);
1316    SkCanvas canvas(dst);
1317
1318    test_draw_bitmaps(&canvas);
1319}
1320