PictureTest.cpp revision 87c4138fae37ba6b7e4de7acc3fce19524d726ea
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 "SkBBoxHierarchy.h"
9#include "SkBlurImageFilter.h"
10#include "SkCanvas.h"
11#include "SkColorPriv.h"
12#include "SkDashPathEffect.h"
13#include "SkData.h"
14#include "SkDecodingImageGenerator.h"
15#include "SkError.h"
16#include "SkImageEncoder.h"
17#include "SkImageGenerator.h"
18#include "SkPaint.h"
19#include "SkPicture.h"
20#include "SkPictureRecorder.h"
21#include "SkPictureUtils.h"
22#include "SkPixelRef.h"
23#include "SkRRect.h"
24#include "SkRandom.h"
25#include "SkShader.h"
26#include "SkStream.h"
27
28#if SK_SUPPORT_GPU
29#include "SkSurface.h"
30#include "GrContextFactory.h"
31#include "GrPictureUtils.h"
32#endif
33#include "Test.h"
34
35#include "SkLumaColorFilter.h"
36#include "SkColorFilterImageFilter.h"
37
38static const int gColorScale = 30;
39static const int gColorOffset = 60;
40
41static void make_bm(SkBitmap* bm, int w, int h, SkColor color, bool immutable) {
42    bm->allocN32Pixels(w, h);
43    bm->eraseColor(color);
44    if (immutable) {
45        bm->setImmutable();
46    }
47}
48
49static void make_checkerboard(SkBitmap* bm, int w, int h, bool immutable) {
50    SkASSERT(w % 2 == 0);
51    SkASSERT(h % 2 == 0);
52    bm->allocPixels(SkImageInfo::Make(w, h, kAlpha_8_SkColorType,
53                                      kPremul_SkAlphaType));
54    SkAutoLockPixels lock(*bm);
55    for (int y = 0; y < h; y += 2) {
56        uint8_t* s = bm->getAddr8(0, y);
57        for (int x = 0; x < w; x += 2) {
58            *s++ = 0xFF;
59            *s++ = 0x00;
60        }
61        s = bm->getAddr8(0, y + 1);
62        for (int x = 0; x < w; x += 2) {
63            *s++ = 0x00;
64            *s++ = 0xFF;
65        }
66    }
67    if (immutable) {
68        bm->setImmutable();
69    }
70}
71
72static void init_paint(SkPaint* paint, const SkBitmap &bm) {
73    SkShader* shader = SkShader::CreateBitmapShader(bm,
74                                                    SkShader::kClamp_TileMode,
75                                                    SkShader::kClamp_TileMode);
76    paint->setShader(shader)->unref();
77}
78
79typedef void (*DrawBitmapProc)(SkCanvas*, const SkBitmap&,
80                               const SkBitmap&, const SkPoint&,
81                               SkTDArray<SkPixelRef*>* usedPixRefs);
82
83static void drawpaint_proc(SkCanvas* canvas, const SkBitmap& bm,
84                           const SkBitmap& altBM, const SkPoint& pos,
85                           SkTDArray<SkPixelRef*>* usedPixRefs) {
86    SkPaint paint;
87    init_paint(&paint, bm);
88
89    canvas->drawPaint(paint);
90    *usedPixRefs->append() = bm.pixelRef();
91}
92
93static void drawpoints_proc(SkCanvas* canvas, const SkBitmap& bm,
94                            const SkBitmap& altBM, const SkPoint& pos,
95                            SkTDArray<SkPixelRef*>* usedPixRefs) {
96    SkPaint paint;
97    init_paint(&paint, bm);
98
99    // draw a rect
100    SkPoint points[5] = {
101        { pos.fX, pos.fY },
102        { pos.fX + bm.width() - 1, pos.fY },
103        { pos.fX + bm.width() - 1, pos.fY + bm.height() - 1 },
104        { pos.fX, pos.fY + bm.height() - 1 },
105        { pos.fX, pos.fY },
106    };
107
108    canvas->drawPoints(SkCanvas::kPolygon_PointMode, 5, points, paint);
109    *usedPixRefs->append() = bm.pixelRef();
110}
111
112static void drawrect_proc(SkCanvas* canvas, const SkBitmap& bm,
113                          const SkBitmap& altBM, const SkPoint& pos,
114                          SkTDArray<SkPixelRef*>* usedPixRefs) {
115    SkPaint paint;
116    init_paint(&paint, bm);
117
118    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
119    r.offset(pos.fX, pos.fY);
120
121    canvas->drawRect(r, paint);
122    *usedPixRefs->append() = bm.pixelRef();
123}
124
125static void drawoval_proc(SkCanvas* canvas, const SkBitmap& bm,
126                          const SkBitmap& altBM, const SkPoint& pos,
127                          SkTDArray<SkPixelRef*>* usedPixRefs) {
128    SkPaint paint;
129    init_paint(&paint, bm);
130
131    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
132    r.offset(pos.fX, pos.fY);
133
134    canvas->drawOval(r, paint);
135    *usedPixRefs->append() = bm.pixelRef();
136}
137
138static void drawrrect_proc(SkCanvas* canvas, const SkBitmap& bm,
139                           const SkBitmap& altBM, const SkPoint& pos,
140                           SkTDArray<SkPixelRef*>* usedPixRefs) {
141    SkPaint paint;
142    init_paint(&paint, bm);
143
144    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
145    r.offset(pos.fX, pos.fY);
146
147    SkRRect rr;
148    rr.setRectXY(r, SkIntToScalar(bm.width())/4, SkIntToScalar(bm.height())/4);
149    canvas->drawRRect(rr, paint);
150    *usedPixRefs->append() = bm.pixelRef();
151}
152
153static void drawpath_proc(SkCanvas* canvas, const SkBitmap& bm,
154                          const SkBitmap& altBM, const SkPoint& pos,
155                          SkTDArray<SkPixelRef*>* usedPixRefs) {
156    SkPaint paint;
157    init_paint(&paint, bm);
158
159    SkPath path;
160    path.lineTo(bm.width()/2.0f, SkIntToScalar(bm.height()));
161    path.lineTo(SkIntToScalar(bm.width()), 0);
162    path.close();
163    path.offset(pos.fX, pos.fY);
164
165    canvas->drawPath(path, paint);
166    *usedPixRefs->append() = bm.pixelRef();
167}
168
169static void drawbitmap_proc(SkCanvas* canvas, const SkBitmap& bm,
170                            const SkBitmap& altBM, const SkPoint& pos,
171                            SkTDArray<SkPixelRef*>* usedPixRefs) {
172    canvas->drawBitmap(bm, pos.fX, pos.fY, NULL);
173    *usedPixRefs->append() = bm.pixelRef();
174}
175
176static void drawbitmap_withshader_proc(SkCanvas* canvas, const SkBitmap& bm,
177                                       const SkBitmap& altBM, const SkPoint& pos,
178                                       SkTDArray<SkPixelRef*>* usedPixRefs) {
179    SkPaint paint;
180    init_paint(&paint, bm);
181
182    // The bitmap in the paint is ignored unless we're drawing an A8 bitmap
183    canvas->drawBitmap(altBM, pos.fX, pos.fY, &paint);
184    *usedPixRefs->append() = bm.pixelRef();
185    *usedPixRefs->append() = altBM.pixelRef();
186}
187
188static void drawsprite_proc(SkCanvas* canvas, const SkBitmap& bm,
189                            const SkBitmap& altBM, const SkPoint& pos,
190                            SkTDArray<SkPixelRef*>* usedPixRefs) {
191    const SkMatrix& ctm = canvas->getTotalMatrix();
192
193    SkPoint p(pos);
194    ctm.mapPoints(&p, 1);
195
196    canvas->drawSprite(bm, (int)p.fX, (int)p.fY, NULL);
197    *usedPixRefs->append() = bm.pixelRef();
198}
199
200#if 0
201// Although specifiable, this case doesn't seem to make sense (i.e., the
202// bitmap in the shader is never used).
203static void drawsprite_withshader_proc(SkCanvas* canvas, const SkBitmap& bm,
204                                       const SkBitmap& altBM, const SkPoint& pos,
205                                       SkTDArray<SkPixelRef*>* usedPixRefs) {
206    SkPaint paint;
207    init_paint(&paint, bm);
208
209    const SkMatrix& ctm = canvas->getTotalMatrix();
210
211    SkPoint p(pos);
212    ctm.mapPoints(&p, 1);
213
214    canvas->drawSprite(altBM, (int)p.fX, (int)p.fY, &paint);
215    *usedPixRefs->append() = bm.pixelRef();
216    *usedPixRefs->append() = altBM.pixelRef();
217}
218#endif
219
220static void drawbitmaprect_proc(SkCanvas* canvas, const SkBitmap& bm,
221                                const SkBitmap& altBM, const SkPoint& pos,
222                                SkTDArray<SkPixelRef*>* usedPixRefs) {
223    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
224
225    r.offset(pos.fX, pos.fY);
226    canvas->drawBitmapRectToRect(bm, NULL, r, NULL);
227    *usedPixRefs->append() = bm.pixelRef();
228}
229
230static void drawbitmaprect_withshader_proc(SkCanvas* canvas,
231                                           const SkBitmap& bm,
232                                           const SkBitmap& altBM,
233                                           const SkPoint& pos,
234                                           SkTDArray<SkPixelRef*>* usedPixRefs) {
235    SkPaint paint;
236    init_paint(&paint, bm);
237
238    SkRect r = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
239    r.offset(pos.fX, pos.fY);
240
241    // The bitmap in the paint is ignored unless we're drawing an A8 bitmap
242    canvas->drawBitmapRectToRect(altBM, NULL, r, &paint);
243    *usedPixRefs->append() = bm.pixelRef();
244    *usedPixRefs->append() = altBM.pixelRef();
245}
246
247static void drawtext_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    canvas->drawText("0", 1, pos.fX, pos.fY+bm.width(), paint);
255    *usedPixRefs->append() = bm.pixelRef();
256}
257
258static void drawpostext_proc(SkCanvas* canvas, const SkBitmap& bm,
259                             const SkBitmap& altBM, const SkPoint& pos,
260                             SkTDArray<SkPixelRef*>* usedPixRefs) {
261    SkPaint paint;
262    init_paint(&paint, bm);
263    paint.setTextSize(SkIntToScalar(1.5*bm.width()));
264
265    SkPoint point = { pos.fX, pos.fY + bm.height() };
266    canvas->drawPosText("O", 1, &point, paint);
267    *usedPixRefs->append() = bm.pixelRef();
268}
269
270static void drawtextonpath_proc(SkCanvas* canvas, const SkBitmap& bm,
271                                const SkBitmap& altBM, const SkPoint& pos,
272                                SkTDArray<SkPixelRef*>* usedPixRefs) {
273    SkPaint paint;
274
275    init_paint(&paint, bm);
276    paint.setTextSize(SkIntToScalar(1.5*bm.width()));
277
278    SkPath path;
279    path.lineTo(SkIntToScalar(bm.width()), 0);
280    path.offset(pos.fX, pos.fY+bm.height());
281
282    canvas->drawTextOnPath("O", 1, path, NULL, paint);
283    *usedPixRefs->append() = bm.pixelRef();
284}
285
286static void drawverts_proc(SkCanvas* canvas, const SkBitmap& bm,
287                           const SkBitmap& altBM, const SkPoint& pos,
288                           SkTDArray<SkPixelRef*>* usedPixRefs) {
289    SkPaint paint;
290    init_paint(&paint, bm);
291
292    SkPoint verts[4] = {
293        { pos.fX, pos.fY },
294        { pos.fX + bm.width(), pos.fY },
295        { pos.fX + bm.width(), pos.fY + bm.height() },
296        { pos.fX, pos.fY + bm.height() }
297    };
298    SkPoint texs[4] = { { 0, 0 },
299                        { SkIntToScalar(bm.width()), 0 },
300                        { SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) },
301                        { 0, SkIntToScalar(bm.height()) } };
302    uint16_t indices[6] = { 0, 1, 2, 0, 2, 3 };
303
304    canvas->drawVertices(SkCanvas::kTriangles_VertexMode, 4, verts, texs, NULL, NULL,
305                         indices, 6, paint);
306    *usedPixRefs->append() = bm.pixelRef();
307}
308
309// Return a picture with the bitmaps drawn at the specified positions.
310static SkPicture* record_bitmaps(const SkBitmap bm[],
311                                 const SkPoint pos[],
312                                 SkTDArray<SkPixelRef*> analytic[],
313                                 int count,
314                                 DrawBitmapProc proc) {
315    SkPictureRecorder recorder;
316    SkCanvas* canvas = recorder.beginRecording(1000, 1000);
317    for (int i = 0; i < count; ++i) {
318        analytic[i].rewind();
319        canvas->save();
320        SkRect clipRect = SkRect::MakeXYWH(pos[i].fX, pos[i].fY,
321                                           SkIntToScalar(bm[i].width()),
322                                           SkIntToScalar(bm[i].height()));
323        canvas->clipRect(clipRect, SkRegion::kIntersect_Op);
324        proc(canvas, bm[i], bm[count+i], pos[i], &analytic[i]);
325        canvas->restore();
326    }
327    return recorder.endRecording();
328}
329
330static void rand_rect(SkRect* rect, SkRandom& rand, SkScalar W, SkScalar H) {
331    rect->fLeft   = rand.nextRangeScalar(-W, 2*W);
332    rect->fTop    = rand.nextRangeScalar(-H, 2*H);
333    rect->fRight  = rect->fLeft + rand.nextRangeScalar(0, W);
334    rect->fBottom = rect->fTop + rand.nextRangeScalar(0, H);
335
336    // we integralize rect to make our tests more predictable, since Gather is
337    // a little sloppy.
338    SkIRect ir;
339    rect->round(&ir);
340    rect->set(ir);
341}
342
343static void draw(SkPicture* pic, int width, int height, SkBitmap* result) {
344    make_bm(result, width, height, SK_ColorBLACK, false);
345
346    SkCanvas canvas(*result);
347    canvas.drawPicture(pic);
348}
349
350template <typename T> int find_index(const T* array, T elem, int count) {
351    for (int i = 0; i < count; ++i) {
352        if (array[i] == elem) {
353            return i;
354        }
355    }
356    return -1;
357}
358
359// Return true if 'ref' is found in array[]
360static bool find(SkPixelRef const * const * array, SkPixelRef const * ref, int count) {
361    return find_index<const SkPixelRef*>(array, ref, count) >= 0;
362}
363
364// Look at each pixel that is inside 'subset', and if its color appears in
365// colors[], find the corresponding value in refs[] and append that ref into
366// array, skipping duplicates of the same value.
367// Note that gathering pixelRefs from rendered colors suffers from the problem
368// that multiple simultaneous textures (e.g., A8 for alpha and 8888 for color)
369// isn't easy to reconstruct.
370static void gather_from_image(const SkBitmap& bm, SkPixelRef* const refs[],
371                              int count, SkTDArray<SkPixelRef*>* array,
372                              const SkRect& subset) {
373    SkIRect ir;
374    subset.roundOut(&ir);
375
376    if (!ir.intersect(0, 0, bm.width()-1, bm.height()-1)) {
377        return;
378    }
379
380    // Since we only want to return unique values in array, when we scan we just
381    // set a bit for each index'd color found. In practice we only have a few
382    // distinct colors, so we just use an int's bits as our array. Hence the
383    // assert that count <= number-of-bits-in-our-int.
384    SkASSERT((unsigned)count <= 32);
385    uint32_t bitarray = 0;
386
387    SkAutoLockPixels alp(bm);
388
389    for (int y = ir.fTop; y < ir.fBottom; ++y) {
390        for (int x = ir.fLeft; x < ir.fRight; ++x) {
391            SkPMColor pmc = *bm.getAddr32(x, y);
392            // the only good case where the color is not found would be if
393            // the color is transparent, meaning no bitmap was drawn in that
394            // pixel.
395            if (pmc) {
396                uint32_t index = SkGetPackedR32(pmc);
397                SkASSERT(SkGetPackedG32(pmc) == index);
398                SkASSERT(SkGetPackedB32(pmc) == index);
399                if (0 == index) {
400                    continue;           // background color
401                }
402                SkASSERT(0 == (index - gColorOffset) % gColorScale);
403                index = (index - gColorOffset) / gColorScale;
404                SkASSERT(static_cast<int>(index) < count);
405                bitarray |= 1 << index;
406            }
407        }
408    }
409
410    for (int i = 0; i < count; ++i) {
411        if (bitarray & (1 << i)) {
412            *array->append() = refs[i];
413        }
414    }
415}
416
417static void gather_from_analytic(const SkPoint pos[], SkScalar w, SkScalar h,
418                                 const SkTDArray<SkPixelRef*> analytic[],
419                                 int count,
420                                 SkTDArray<SkPixelRef*>* result,
421                                 const SkRect& subset) {
422    for (int i = 0; i < count; ++i) {
423        SkRect rect = SkRect::MakeXYWH(pos[i].fX, pos[i].fY, w, h);
424
425        if (SkRect::Intersects(subset, rect)) {
426            result->append(analytic[i].count(), analytic[i].begin());
427        }
428    }
429}
430
431
432static const struct {
433    const DrawBitmapProc proc;
434    const char* const desc;
435} gProcs[] = {
436    {drawpaint_proc, "drawpaint"},
437    {drawpoints_proc, "drawpoints"},
438    {drawrect_proc, "drawrect"},
439    {drawoval_proc, "drawoval"},
440    {drawrrect_proc, "drawrrect"},
441    {drawpath_proc, "drawpath"},
442    {drawbitmap_proc, "drawbitmap"},
443    {drawbitmap_withshader_proc, "drawbitmap_withshader"},
444    {drawsprite_proc, "drawsprite"},
445#if 0
446    {drawsprite_withshader_proc, "drawsprite_withshader"},
447#endif
448    {drawbitmaprect_proc, "drawbitmaprect"},
449    {drawbitmaprect_withshader_proc, "drawbitmaprect_withshader"},
450    {drawtext_proc, "drawtext"},
451    {drawpostext_proc, "drawpostext"},
452    {drawtextonpath_proc, "drawtextonpath"},
453    {drawverts_proc, "drawverts"},
454};
455
456static void create_textures(SkBitmap* bm, SkPixelRef** refs, int num, int w, int h) {
457    // Our convention is that the color components contain an encoding of
458    // the index of their corresponding bitmap/pixelref. (0,0,0,0) is
459    // reserved for the background
460    for (int i = 0; i < num; ++i) {
461        make_bm(&bm[i], w, h,
462                SkColorSetARGB(0xFF,
463                               gColorScale*i+gColorOffset,
464                               gColorScale*i+gColorOffset,
465                               gColorScale*i+gColorOffset),
466                true);
467        refs[i] = bm[i].pixelRef();
468    }
469
470    // The A8 alternate bitmaps are all BW checkerboards
471    for (int i = 0; i < num; ++i) {
472        make_checkerboard(&bm[num+i], w, h, true);
473        refs[num+i] = bm[num+i].pixelRef();
474    }
475}
476
477static void test_gatherpixelrefs(skiatest::Reporter* reporter) {
478    const int IW = 32;
479    const int IH = IW;
480    const SkScalar W = SkIntToScalar(IW);
481    const SkScalar H = W;
482
483    static const int N = 4;
484    SkBitmap bm[2*N];
485    SkPixelRef* refs[2*N];
486    SkTDArray<SkPixelRef*> analytic[N];
487
488    const SkPoint pos[N] = {
489        { 0, 0 }, { W, 0 }, { 0, H }, { W, H }
490    };
491
492    create_textures(bm, refs, N, IW, IH);
493
494    SkRandom rand;
495    for (size_t k = 0; k < SK_ARRAY_COUNT(gProcs); ++k) {
496        SkAutoTUnref<SkPicture> pic(
497            record_bitmaps(bm, pos, analytic, N, gProcs[k].proc));
498
499        REPORTER_ASSERT(reporter, pic->willPlayBackBitmaps() || N == 0);
500        // quick check for a small piece of each quadrant, which should just
501        // contain 1 or 2 bitmaps.
502        for (size_t  i = 0; i < SK_ARRAY_COUNT(pos); ++i) {
503            SkRect r;
504            r.set(2, 2, W - 2, H - 2);
505            r.offset(pos[i].fX, pos[i].fY);
506            SkAutoDataUnref data(SkPictureUtils::GatherPixelRefs(pic, r));
507            if (!data) {
508                ERRORF(reporter, "SkPictureUtils::GatherPixelRefs returned "
509                       "NULL for %s.", gProcs[k].desc);
510                continue;
511            }
512            SkPixelRef** gatheredRefs = (SkPixelRef**)data->data();
513            int count = static_cast<int>(data->size() / sizeof(SkPixelRef*));
514            REPORTER_ASSERT(reporter, 1 == count || 2 == count);
515            if (1 == count) {
516                REPORTER_ASSERT(reporter, gatheredRefs[0] == refs[i]);
517            } else if (2 == count) {
518                REPORTER_ASSERT(reporter,
519                    (gatheredRefs[0] == refs[i] && gatheredRefs[1] == refs[i+N]) ||
520                    (gatheredRefs[1] == refs[i] && gatheredRefs[0] == refs[i+N]));
521            }
522        }
523
524        SkBitmap image;
525        draw(pic, 2*IW, 2*IH, &image);
526
527        // Test a bunch of random (mostly) rects, and compare the gather results
528        // with a deduced list of refs by looking at the colors drawn.
529        for (int j = 0; j < 100; ++j) {
530            SkRect r;
531            rand_rect(&r, rand, 2*W, 2*H);
532
533            SkTDArray<SkPixelRef*> fromImage;
534            gather_from_image(image, refs, N, &fromImage, r);
535
536            SkTDArray<SkPixelRef*> fromAnalytic;
537            gather_from_analytic(pos, W, H, analytic, N, &fromAnalytic, r);
538
539            SkData* data = SkPictureUtils::GatherPixelRefs(pic, r);
540            size_t dataSize = data ? data->size() : 0;
541            int gatherCount = static_cast<int>(dataSize / sizeof(SkPixelRef*));
542            SkASSERT(gatherCount * sizeof(SkPixelRef*) == dataSize);
543            SkPixelRef** gatherRefs = data ? (SkPixelRef**)(data->data()) : NULL;
544            SkAutoDataUnref adu(data);
545
546            // Everything that we saw drawn should appear in the analytic list
547            // but the analytic list may contain some pixelRefs that were not
548            // seen in the image (e.g., A8 textures used as masks)
549            for (int i = 0; i < fromImage.count(); ++i) {
550                if (-1 == fromAnalytic.find(fromImage[i])) {
551                    ERRORF(reporter, "PixelRef missing %d %s",
552                           i, gProcs[k].desc);
553                }
554            }
555
556            /*
557             *  GatherPixelRefs is conservative, so it can return more bitmaps
558             *  than are strictly required. Thus our check here is only that
559             *  Gather didn't miss any that we actually needed. Even that isn't
560             *  a strict requirement on Gather, which is meant to be quick and
561             *  only mostly-correct, but at the moment this test should work.
562             */
563            for (int i = 0; i < fromAnalytic.count(); ++i) {
564                bool found = find(gatherRefs, fromAnalytic[i], gatherCount);
565                if (!found) {
566                    ERRORF(reporter, "PixelRef missing %d %s",
567                           i, gProcs[k].desc);
568                }
569#if 0
570                // enable this block of code to debug failures, as it will rerun
571                // the case that failed.
572                if (!found) {
573                    SkData* data = SkPictureUtils::GatherPixelRefs(pic, r);
574                    size_t dataSize = data ? data->size() : 0;
575                }
576#endif
577            }
578        }
579    }
580}
581
582#define GENERATE_CANVAS(recorder, x) \
583    (x) ? recorder.EXPERIMENTAL_beginRecording(100, 100) \
584        : recorder.  DEPRECATED_beginRecording(100,100);
585
586/* Hit a few SkPicture::Analysis cases not handled elsewhere. */
587static void test_analysis(skiatest::Reporter* reporter, bool useNewPath) {
588    SkPictureRecorder recorder;
589
590    SkCanvas* canvas = GENERATE_CANVAS(recorder, useNewPath);
591    {
592        canvas->drawRect(SkRect::MakeWH(10, 10), SkPaint ());
593    }
594    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
595    REPORTER_ASSERT(reporter, !picture->willPlayBackBitmaps());
596
597    canvas = GENERATE_CANVAS(recorder, useNewPath);
598    {
599        SkPaint paint;
600        // CreateBitmapShader is too smart for us; an empty (or 1x1) bitmap shader
601        // gets optimized into a non-bitmap form, so we create a 2x2 bitmap here.
602        SkBitmap bitmap;
603        bitmap.allocPixels(SkImageInfo::MakeN32Premul(2, 2));
604        bitmap.eraseColor(SK_ColorBLUE);
605        *(bitmap.getAddr32(0, 0)) = SK_ColorGREEN;
606        SkShader* shader = SkShader::CreateBitmapShader(bitmap, SkShader::kClamp_TileMode,
607                                                        SkShader::kClamp_TileMode);
608        paint.setShader(shader)->unref();
609        REPORTER_ASSERT(reporter,
610                        shader->asABitmap(NULL, NULL, NULL) == SkShader::kDefault_BitmapType);
611
612        canvas->drawRect(SkRect::MakeWH(10, 10), paint);
613    }
614    picture.reset(recorder.endRecording());
615    REPORTER_ASSERT(reporter, picture->willPlayBackBitmaps());
616}
617
618
619static void test_gatherpixelrefsandrects(skiatest::Reporter* reporter) {
620    const int IW = 32;
621    const int IH = IW;
622    const SkScalar W = SkIntToScalar(IW);
623    const SkScalar H = W;
624
625    static const int N = 4;
626    SkBitmap bm[2*N];
627    SkPixelRef* refs[2*N];
628    SkTDArray<SkPixelRef*> analytic[N];
629
630    const SkPoint pos[N] = {
631        { 0, 0 }, { W, 0 }, { 0, H }, { W, H }
632    };
633
634    create_textures(bm, refs, N, IW, IH);
635
636    SkRandom rand;
637    for (size_t k = 0; k < SK_ARRAY_COUNT(gProcs); ++k) {
638        SkAutoTUnref<SkPicture> pic(
639            record_bitmaps(bm, pos, analytic, N, gProcs[k].proc));
640
641        REPORTER_ASSERT(reporter, pic->willPlayBackBitmaps() || N == 0);
642
643        SkAutoTUnref<SkPictureUtils::SkPixelRefContainer> prCont(
644                                new SkPictureUtils::SkPixelRefsAndRectsList);
645
646        SkPictureUtils::GatherPixelRefsAndRects(pic, prCont);
647
648        // quick check for a small piece of each quadrant, which should just
649        // contain 1 or 2 bitmaps.
650        for (size_t  i = 0; i < SK_ARRAY_COUNT(pos); ++i) {
651            SkRect r;
652            r.set(2, 2, W - 2, H - 2);
653            r.offset(pos[i].fX, pos[i].fY);
654
655            SkTDArray<SkPixelRef*> gatheredRefs;
656            prCont->query(r, &gatheredRefs);
657
658            int count = gatheredRefs.count();
659            REPORTER_ASSERT(reporter, 1 == count || 2 == count);
660            if (1 == count) {
661                REPORTER_ASSERT(reporter, gatheredRefs[0] == refs[i]);
662            } else if (2 == count) {
663                REPORTER_ASSERT(reporter,
664                    (gatheredRefs[0] == refs[i] && gatheredRefs[1] == refs[i+N]) ||
665                    (gatheredRefs[1] == refs[i] && gatheredRefs[0] == refs[i+N]));
666            }
667        }
668
669        SkBitmap image;
670        draw(pic, 2*IW, 2*IH, &image);
671
672        // Test a bunch of random (mostly) rects, and compare the gather results
673        // with the analytic results and the pixel refs seen in a rendering.
674        for (int j = 0; j < 100; ++j) {
675            SkRect r;
676            rand_rect(&r, rand, 2*W, 2*H);
677
678            SkTDArray<SkPixelRef*> fromImage;
679            gather_from_image(image, refs, N, &fromImage, r);
680
681            SkTDArray<SkPixelRef*> fromAnalytic;
682            gather_from_analytic(pos, W, H, analytic, N, &fromAnalytic, r);
683
684            SkTDArray<SkPixelRef*> gatheredRefs;
685            prCont->query(r, &gatheredRefs);
686
687            // Everything that we saw drawn should appear in the analytic list
688            // but the analytic list may contain some pixelRefs that were not
689            // seen in the image (e.g., A8 textures used as masks)
690            for (int i = 0; i < fromImage.count(); ++i) {
691                REPORTER_ASSERT(reporter, -1 != fromAnalytic.find(fromImage[i]));
692            }
693
694            // Everything in the analytic list should appear in the gathered
695            // list.
696            for (int i = 0; i < fromAnalytic.count(); ++i) {
697                REPORTER_ASSERT(reporter, -1 != gatheredRefs.find(fromAnalytic[i]));
698            }
699        }
700    }
701}
702
703#ifdef SK_DEBUG
704// Ensure that deleting an empty SkPicture does not assert. Asserts only fire
705// in debug mode, so only run in debug mode.
706static void test_deleting_empty_picture() {
707    SkPictureRecorder recorder;
708    // Creates an SkPictureRecord
709    recorder.beginRecording(0, 0);
710    // Turns that into an SkPicture
711    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
712    // Ceates a new SkPictureRecord
713    recorder.beginRecording(0, 0);
714}
715
716// Ensure that serializing an empty picture does not assert. Likewise only runs in debug mode.
717static void test_serializing_empty_picture() {
718    SkPictureRecorder recorder;
719    recorder.beginRecording(0, 0);
720    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
721    SkDynamicMemoryWStream stream;
722    picture->serialize(&stream);
723}
724#endif
725
726static void rand_op(SkCanvas* canvas, SkRandom& rand) {
727    SkPaint paint;
728    SkRect rect = SkRect::MakeWH(50, 50);
729
730    SkScalar unit = rand.nextUScalar1();
731    if (unit <= 0.3) {
732//        SkDebugf("save\n");
733        canvas->save();
734    } else if (unit <= 0.6) {
735//        SkDebugf("restore\n");
736        canvas->restore();
737    } else if (unit <= 0.9) {
738//        SkDebugf("clip\n");
739        canvas->clipRect(rect);
740    } else {
741//        SkDebugf("draw\n");
742        canvas->drawPaint(paint);
743    }
744}
745
746#if SK_SUPPORT_GPU
747
748static void test_gpu_veto(skiatest::Reporter* reporter,
749                          bool useNewPath) {
750
751    SkPictureRecorder recorder;
752
753    SkCanvas* canvas = GENERATE_CANVAS(recorder, useNewPath);
754    {
755        SkPath path;
756        path.moveTo(0, 0);
757        path.lineTo(50, 50);
758
759        SkScalar intervals[] = { 1.0f, 1.0f };
760        SkAutoTUnref<SkDashPathEffect> dash(SkDashPathEffect::Create(intervals, 2, 0));
761
762        SkPaint paint;
763        paint.setStyle(SkPaint::kStroke_Style);
764        paint.setPathEffect(dash);
765
766        canvas->drawPath(path, paint);
767    }
768    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
769    // path effects currently render an SkPicture undesireable for GPU rendering
770
771    const char *reason = NULL;
772    REPORTER_ASSERT(reporter, !picture->suitableForGpuRasterization(NULL, &reason));
773    REPORTER_ASSERT(reporter, reason);
774
775    canvas = GENERATE_CANVAS(recorder, useNewPath);
776    {
777        SkPath path;
778
779        path.moveTo(0, 0);
780        path.lineTo(0, 50);
781        path.lineTo(25, 25);
782        path.lineTo(50, 50);
783        path.lineTo(50, 0);
784        path.close();
785        REPORTER_ASSERT(reporter, !path.isConvex());
786
787        SkPaint paint;
788        paint.setAntiAlias(true);
789        for (int i = 0; i < 50; ++i) {
790            canvas->drawPath(path, paint);
791        }
792    }
793    picture.reset(recorder.endRecording());
794    // A lot of AA concave paths currently render an SkPicture undesireable for GPU rendering
795    REPORTER_ASSERT(reporter, !picture->suitableForGpuRasterization(NULL));
796
797    canvas = GENERATE_CANVAS(recorder, useNewPath);
798    {
799        SkPath path;
800
801        path.moveTo(0, 0);
802        path.lineTo(0, 50);
803        path.lineTo(25, 25);
804        path.lineTo(50, 50);
805        path.lineTo(50, 0);
806        path.close();
807        REPORTER_ASSERT(reporter, !path.isConvex());
808
809        SkPaint paint;
810        paint.setAntiAlias(true);
811        paint.setStyle(SkPaint::kStroke_Style);
812        paint.setStrokeWidth(0);
813        for (int i = 0; i < 50; ++i) {
814            canvas->drawPath(path, paint);
815        }
816    }
817    picture.reset(recorder.endRecording());
818    // hairline stroked AA concave paths are fine for GPU rendering
819    REPORTER_ASSERT(reporter, picture->suitableForGpuRasterization(NULL));
820
821    canvas = GENERATE_CANVAS(recorder, useNewPath);
822    {
823        SkPaint paint;
824        SkScalar intervals [] = { 10, 20 };
825        SkPathEffect* pe = SkDashPathEffect::Create(intervals, 2, 25);
826        paint.setPathEffect(pe)->unref();
827
828        SkPoint points [2] = { { 0, 0 }, { 100, 0 } };
829        canvas->drawPoints(SkCanvas::kLines_PointMode, 2, points, paint);
830    }
831    picture.reset(recorder.endRecording());
832    // fast-path dashed effects are fine for GPU rendering ...
833    REPORTER_ASSERT(reporter, picture->suitableForGpuRasterization(NULL));
834
835    canvas = GENERATE_CANVAS(recorder, useNewPath);
836    {
837        SkPaint paint;
838        SkScalar intervals [] = { 10, 20 };
839        SkPathEffect* pe = SkDashPathEffect::Create(intervals, 2, 25);
840        paint.setPathEffect(pe)->unref();
841
842        canvas->drawRect(SkRect::MakeWH(10, 10), paint);
843    }
844    picture.reset(recorder.endRecording());
845    // ... but only when applied to drawPoint() calls
846    REPORTER_ASSERT(reporter, !picture->suitableForGpuRasterization(NULL));
847
848    // Nest the previous picture inside a new one.
849    // This doesn't work in the old backend.
850    if (useNewPath) {
851        canvas = GENERATE_CANVAS(recorder, useNewPath);
852        {
853            canvas->drawPicture(picture.get());
854        }
855        picture.reset(recorder.endRecording());
856        REPORTER_ASSERT(reporter, !picture->suitableForGpuRasterization(NULL));
857    }
858}
859
860#undef GENERATE_CANVAS
861
862static void test_gpu_picture_optimization(skiatest::Reporter* reporter,
863                                          GrContextFactory* factory) {
864    for (int i= 0; i < GrContextFactory::kGLContextTypeCnt; ++i) {
865        GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType) i;
866
867        if (!GrContextFactory::IsRenderingGLContext(glCtxType)) {
868            continue;
869        }
870
871        GrContext* context = factory->get(glCtxType);
872
873        if (NULL == context) {
874            continue;
875        }
876
877        static const int kWidth = 100;
878        static const int kHeight = 100;
879
880        SkAutoTUnref<SkPicture> pict, child;
881
882        {
883            SkPictureRecorder recorder;
884
885            SkCanvas* c = recorder.beginRecording(SkIntToScalar(kWidth), SkIntToScalar(kHeight));
886
887            c->saveLayer(NULL, NULL);
888            c->restore();
889
890            child.reset(recorder.endRecording());
891        }
892
893        // create a picture with the structure:
894        // 1)
895        //      SaveLayer
896        //      Restore
897        // 2)
898        //      SaveLayer
899        //          Translate
900        //          SaveLayer w/ bound
901        //          Restore
902        //      Restore
903        // 3)
904        //      SaveLayer w/ copyable paint
905        //      Restore
906        // 4)
907        //      SaveLayer
908        //          DrawPicture (which has a SaveLayer/Restore pair)
909        //      Restore
910        // 5)
911        //      SaveLayer
912        //          DrawPicture with Matrix & Paint (with SaveLayer/Restore pair)
913        //      Restore
914        {
915            SkPictureRecorder recorder;
916
917            SkCanvas* c = recorder.beginRecording(SkIntToScalar(kWidth),
918                                                  SkIntToScalar(kHeight));
919            // 1)
920            c->saveLayer(NULL, NULL); // layer #0
921            c->restore();
922
923            // 2)
924            c->saveLayer(NULL, NULL); // layer #1
925                c->translate(kWidth/2.0f, kHeight/2.0f);
926                SkRect r = SkRect::MakeXYWH(0, 0, kWidth/2, kHeight/2);
927                c->saveLayer(&r, NULL); // layer #2
928                c->restore();
929            c->restore();
930
931            // 3)
932            {
933                SkPaint p;
934                p.setColor(SK_ColorRED);
935                c->saveLayer(NULL, &p); // layer #3
936                c->restore();
937            }
938            // 4)
939            {
940                c->saveLayer(NULL, NULL);  // layer #4
941                    c->drawPicture(child);  // layer #5 inside picture
942                c->restore();
943            }
944            // 5
945            {
946                SkPaint p;
947                SkMatrix trans;
948                trans.setTranslate(10, 10);
949
950                c->saveLayer(NULL, NULL);  // layer #6
951                    c->drawPicture(child, &trans, &p); // layer #7 inside picture
952                c->restore();
953            }
954
955            pict.reset(recorder.endRecording());
956        }
957
958        // Now test out the SaveLayer extraction
959        {
960            SkImageInfo info = SkImageInfo::MakeN32Premul(kWidth, kHeight);
961
962            SkAutoTUnref<SkSurface> surface(SkSurface::NewScratchRenderTarget(context, info));
963
964            SkCanvas* canvas = surface->getCanvas();
965
966            canvas->EXPERIMENTAL_optimize(pict);
967
968            SkPicture::AccelData::Key key = GrAccelData::ComputeAccelDataKey();
969
970            const SkPicture::AccelData* data = pict->EXPERIMENTAL_getAccelData(key);
971            REPORTER_ASSERT(reporter, data);
972
973            const GrAccelData *gpuData = static_cast<const GrAccelData*>(data);
974            REPORTER_ASSERT(reporter, 8 == gpuData->numSaveLayers());
975
976            const GrAccelData::SaveLayerInfo& info0 = gpuData->saveLayerInfo(0);
977            // The parent/child layers appear in reverse order
978            const GrAccelData::SaveLayerInfo& info1 = gpuData->saveLayerInfo(2);
979            const GrAccelData::SaveLayerInfo& info2 = gpuData->saveLayerInfo(1);
980
981            const GrAccelData::SaveLayerInfo& info3 = gpuData->saveLayerInfo(3);
982
983            // The parent/child layers appear in reverse order
984            const GrAccelData::SaveLayerInfo& info4 = gpuData->saveLayerInfo(5);
985            const GrAccelData::SaveLayerInfo& info5 = gpuData->saveLayerInfo(4);
986
987            // The parent/child layers appear in reverse order
988            const GrAccelData::SaveLayerInfo& info6 = gpuData->saveLayerInfo(7);
989            const GrAccelData::SaveLayerInfo& info7 = gpuData->saveLayerInfo(6);
990
991            REPORTER_ASSERT(reporter, info0.fValid);
992            REPORTER_ASSERT(reporter, pict->uniqueID() == info0.fPictureID);
993            REPORTER_ASSERT(reporter, kWidth == info0.fSize.fWidth &&
994                                      kHeight == info0.fSize.fHeight);
995            REPORTER_ASSERT(reporter, info0.fOriginXform.isIdentity());
996            REPORTER_ASSERT(reporter, 0 == info0.fOffset.fX && 0 == info0.fOffset.fY);
997            REPORTER_ASSERT(reporter, NULL == info0.fPaint);
998            REPORTER_ASSERT(reporter, !info0.fIsNested && !info0.fHasNestedLayers);
999
1000            REPORTER_ASSERT(reporter, info1.fValid);
1001            REPORTER_ASSERT(reporter, pict->uniqueID() == info1.fPictureID);
1002            REPORTER_ASSERT(reporter, kWidth == info1.fSize.fWidth &&
1003                                      kHeight == info1.fSize.fHeight);
1004            REPORTER_ASSERT(reporter, info1.fOriginXform.isIdentity());
1005            REPORTER_ASSERT(reporter, 0 == info1.fOffset.fX && 0 == info1.fOffset.fY);
1006            REPORTER_ASSERT(reporter, NULL == info1.fPaint);
1007            REPORTER_ASSERT(reporter, !info1.fIsNested &&
1008                                      info1.fHasNestedLayers); // has a nested SL
1009
1010            REPORTER_ASSERT(reporter, info2.fValid);
1011            REPORTER_ASSERT(reporter, pict->uniqueID() == info2.fPictureID);
1012            REPORTER_ASSERT(reporter, kWidth / 2 == info2.fSize.fWidth &&
1013                                      kHeight/2 == info2.fSize.fHeight); // bound reduces size
1014            REPORTER_ASSERT(reporter, info2.fOriginXform.isIdentity());
1015            REPORTER_ASSERT(reporter, kWidth/2 == info2.fOffset.fX &&   // translated
1016                                      kHeight/2 == info2.fOffset.fY);
1017            REPORTER_ASSERT(reporter, NULL == info1.fPaint);
1018            REPORTER_ASSERT(reporter, info2.fIsNested && !info2.fHasNestedLayers); // is nested
1019
1020            REPORTER_ASSERT(reporter, info3.fValid);
1021            REPORTER_ASSERT(reporter, pict->uniqueID() == info3.fPictureID);
1022            REPORTER_ASSERT(reporter, kWidth == info3.fSize.fWidth &&
1023                                      kHeight == info3.fSize.fHeight);
1024            REPORTER_ASSERT(reporter, info3.fOriginXform.isIdentity());
1025            REPORTER_ASSERT(reporter, 0 == info3.fOffset.fX && 0 == info3.fOffset.fY);
1026            REPORTER_ASSERT(reporter, info3.fPaint);
1027            REPORTER_ASSERT(reporter, !info3.fIsNested && !info3.fHasNestedLayers);
1028
1029            REPORTER_ASSERT(reporter, info4.fValid);
1030            REPORTER_ASSERT(reporter, pict->uniqueID() == info4.fPictureID);
1031            REPORTER_ASSERT(reporter, kWidth == info4.fSize.fWidth &&
1032                                      kHeight == info4.fSize.fHeight);
1033            REPORTER_ASSERT(reporter, 0 == info4.fOffset.fX && 0 == info4.fOffset.fY);
1034            REPORTER_ASSERT(reporter, info4.fOriginXform.isIdentity());
1035            REPORTER_ASSERT(reporter, NULL == info4.fPaint);
1036            REPORTER_ASSERT(reporter, !info4.fIsNested &&
1037                                      info4.fHasNestedLayers); // has a nested SL
1038
1039            REPORTER_ASSERT(reporter, info5.fValid);
1040            REPORTER_ASSERT(reporter, child->uniqueID() == info5.fPictureID); // in a child picture
1041            REPORTER_ASSERT(reporter, kWidth == info5.fSize.fWidth &&
1042                                      kHeight == info5.fSize.fHeight);
1043            REPORTER_ASSERT(reporter, 0 == info5.fOffset.fX && 0 == info5.fOffset.fY);
1044            REPORTER_ASSERT(reporter, info5.fOriginXform.isIdentity());
1045            REPORTER_ASSERT(reporter, NULL == info5.fPaint);
1046            REPORTER_ASSERT(reporter, info5.fIsNested && !info5.fHasNestedLayers); // is nested
1047
1048            REPORTER_ASSERT(reporter, info6.fValid);
1049            REPORTER_ASSERT(reporter, pict->uniqueID() == info6.fPictureID);
1050            REPORTER_ASSERT(reporter, kWidth == info6.fSize.fWidth &&
1051                                      kHeight == info6.fSize.fHeight);
1052            REPORTER_ASSERT(reporter, 0 == info6.fOffset.fX && 0 == info6.fOffset.fY);
1053            REPORTER_ASSERT(reporter, info6.fOriginXform.isIdentity());
1054            REPORTER_ASSERT(reporter, NULL == info6.fPaint);
1055            REPORTER_ASSERT(reporter, !info6.fIsNested &&
1056                                      info6.fHasNestedLayers); // has a nested SL
1057
1058            REPORTER_ASSERT(reporter, info7.fValid);
1059            REPORTER_ASSERT(reporter, child->uniqueID() == info7.fPictureID); // in a child picture
1060            REPORTER_ASSERT(reporter, kWidth == info7.fSize.fWidth &&
1061                                      kHeight == info7.fSize.fHeight);
1062            REPORTER_ASSERT(reporter, 0 == info7.fOffset.fX && 0 == info7.fOffset.fY);
1063            REPORTER_ASSERT(reporter, info7.fOriginXform.isIdentity());
1064            REPORTER_ASSERT(reporter, NULL == info7.fPaint);
1065            REPORTER_ASSERT(reporter, info7.fIsNested && !info7.fHasNestedLayers); // is nested
1066        }
1067    }
1068}
1069
1070#endif
1071
1072static void test_has_text(skiatest::Reporter* reporter, bool useNewPath) {
1073    SkPictureRecorder recorder;
1074#define BEGIN_RECORDING useNewPath ? recorder.EXPERIMENTAL_beginRecording(100, 100) \
1075                                   : recorder.  DEPRECATED_beginRecording(100, 100)
1076
1077    SkCanvas* canvas = BEGIN_RECORDING;
1078    {
1079        canvas->drawRect(SkRect::MakeWH(20, 20), SkPaint());
1080    }
1081    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1082    REPORTER_ASSERT(reporter, !picture->hasText());
1083
1084    SkPoint point = SkPoint::Make(10, 10);
1085    canvas = BEGIN_RECORDING;
1086    {
1087        canvas->drawText("Q", 1, point.fX, point.fY, SkPaint());
1088    }
1089    picture.reset(recorder.endRecording());
1090    REPORTER_ASSERT(reporter, picture->hasText());
1091
1092    canvas = BEGIN_RECORDING;
1093    {
1094        canvas->drawPosText("Q", 1, &point, SkPaint());
1095    }
1096    picture.reset(recorder.endRecording());
1097    REPORTER_ASSERT(reporter, picture->hasText());
1098
1099    canvas = BEGIN_RECORDING;
1100    {
1101        canvas->drawPosTextH("Q", 1, &point.fX, point.fY, SkPaint());
1102    }
1103    picture.reset(recorder.endRecording());
1104    REPORTER_ASSERT(reporter, picture->hasText());
1105
1106    canvas = BEGIN_RECORDING;
1107    {
1108        SkPath path;
1109        path.moveTo(0, 0);
1110        path.lineTo(50, 50);
1111
1112        canvas->drawTextOnPathHV("Q", 1, path, point.fX, point.fY, SkPaint());
1113    }
1114    picture.reset(recorder.endRecording());
1115    REPORTER_ASSERT(reporter, picture->hasText());
1116
1117    canvas = BEGIN_RECORDING;
1118    {
1119        SkPath path;
1120        path.moveTo(0, 0);
1121        path.lineTo(50, 50);
1122
1123        canvas->drawTextOnPath("Q", 1, path, NULL, SkPaint());
1124    }
1125    picture.reset(recorder.endRecording());
1126    REPORTER_ASSERT(reporter, picture->hasText());
1127
1128    // Nest the previous picture inside a new one.
1129    // This doesn't work in the old backend.
1130    if (useNewPath) {
1131        canvas = BEGIN_RECORDING;
1132        {
1133            canvas->drawPicture(picture.get());
1134        }
1135        picture.reset(recorder.endRecording());
1136        REPORTER_ASSERT(reporter, picture->hasText());
1137    }
1138#undef BEGIN_RECORDING
1139}
1140
1141static void set_canvas_to_save_count_4(SkCanvas* canvas) {
1142    canvas->restoreToCount(1);
1143    canvas->save();
1144    canvas->save();
1145    canvas->save();
1146}
1147
1148/**
1149 * A canvas that records the number of saves, saveLayers and restores.
1150 */
1151class SaveCountingCanvas : public SkCanvas {
1152public:
1153    SaveCountingCanvas(int width, int height)
1154        : INHERITED(width, height)
1155        , fSaveCount(0)
1156        , fSaveLayerCount(0)
1157        , fRestoreCount(0){
1158    }
1159
1160    virtual SaveLayerStrategy willSaveLayer(const SkRect* bounds, const SkPaint* paint,
1161                                            SaveFlags flags) SK_OVERRIDE {
1162        ++fSaveLayerCount;
1163        return this->INHERITED::willSaveLayer(bounds, paint, flags);
1164    }
1165
1166    virtual void willSave() SK_OVERRIDE {
1167        ++fSaveCount;
1168        this->INHERITED::willSave();
1169    }
1170
1171    virtual void willRestore() SK_OVERRIDE {
1172        ++fRestoreCount;
1173        this->INHERITED::willRestore();
1174    }
1175
1176    unsigned int getSaveCount() const { return fSaveCount; }
1177    unsigned int getSaveLayerCount() const { return fSaveLayerCount; }
1178    unsigned int getRestoreCount() const { return fRestoreCount; }
1179
1180private:
1181    unsigned int fSaveCount;
1182    unsigned int fSaveLayerCount;
1183    unsigned int fRestoreCount;
1184
1185    typedef SkCanvas INHERITED;
1186};
1187
1188void check_save_state(skiatest::Reporter* reporter, SkPicture* picture,
1189                      unsigned int numSaves, unsigned int numSaveLayers,
1190                      unsigned int numRestores) {
1191    SaveCountingCanvas canvas(SkScalarCeilToInt(picture->cullRect().width()),
1192                              SkScalarCeilToInt(picture->cullRect().height()));
1193
1194    picture->playback(&canvas);
1195
1196    // Optimizations may have removed these,
1197    // so expect to have seen no more than num{Saves,SaveLayers,Restores}.
1198    REPORTER_ASSERT(reporter, numSaves >= canvas.getSaveCount());
1199    REPORTER_ASSERT(reporter, numSaveLayers >= canvas.getSaveLayerCount());
1200    REPORTER_ASSERT(reporter, numRestores >= canvas.getRestoreCount());
1201}
1202
1203// This class exists so SkPicture can friend it and give it access to
1204// the 'partialReplay' method.
1205class SkPictureRecorderReplayTester {
1206public:
1207    static SkPicture* Copy(SkPictureRecorder* recorder) {
1208        SkPictureRecorder recorder2;
1209
1210        SkCanvas* canvas = recorder2.beginRecording(10, 10);
1211
1212        recorder->partialReplay(canvas);
1213
1214        return recorder2.endRecording();
1215    }
1216};
1217
1218static void create_imbalance(SkCanvas* canvas) {
1219    SkRect clipRect = SkRect::MakeWH(2, 2);
1220    SkRect drawRect = SkRect::MakeWH(10, 10);
1221    canvas->save();
1222        canvas->clipRect(clipRect, SkRegion::kReplace_Op);
1223        canvas->translate(1.0f, 1.0f);
1224        SkPaint p;
1225        p.setColor(SK_ColorGREEN);
1226        canvas->drawRect(drawRect, p);
1227    // no restore
1228}
1229
1230// This tests that replaying a potentially unbalanced picture into a canvas
1231// doesn't affect the canvas' save count or matrix/clip state.
1232static void check_balance(skiatest::Reporter* reporter, SkPicture* picture) {
1233    SkBitmap bm;
1234    bm.allocN32Pixels(4, 3);
1235    SkCanvas canvas(bm);
1236
1237    int beforeSaveCount = canvas.getSaveCount();
1238
1239    SkMatrix beforeMatrix = canvas.getTotalMatrix();
1240
1241    SkRect beforeClip;
1242
1243    canvas.getClipBounds(&beforeClip);
1244
1245    canvas.drawPicture(picture);
1246
1247    REPORTER_ASSERT(reporter, beforeSaveCount == canvas.getSaveCount());
1248    REPORTER_ASSERT(reporter, beforeMatrix == canvas.getTotalMatrix());
1249
1250    SkRect afterClip;
1251
1252    canvas.getClipBounds(&afterClip);
1253
1254    REPORTER_ASSERT(reporter, afterClip == beforeClip);
1255}
1256
1257// Test out SkPictureRecorder::partialReplay
1258DEF_TEST(PictureRecorder_replay, reporter) {
1259    // check save/saveLayer state
1260    {
1261        SkPictureRecorder recorder;
1262
1263        SkCanvas* canvas = recorder.beginRecording(10, 10);
1264
1265        canvas->saveLayer(NULL, NULL);
1266
1267        SkAutoTUnref<SkPicture> copy(SkPictureRecorderReplayTester::Copy(&recorder));
1268
1269        // The extra save and restore comes from the Copy process.
1270        check_save_state(reporter, copy, 2, 1, 3);
1271
1272        canvas->saveLayer(NULL, NULL);
1273
1274        SkAutoTUnref<SkPicture> final(recorder.endRecording());
1275
1276        check_save_state(reporter, final, 1, 2, 3);
1277
1278        // The copy shouldn't pick up any operations added after it was made
1279        check_save_state(reporter, copy, 2, 1, 3);
1280    }
1281
1282    // (partially) check leakage of draw ops
1283    {
1284        SkPictureRecorder recorder;
1285
1286        SkCanvas* canvas = recorder.beginRecording(10, 10);
1287
1288        SkRect r = SkRect::MakeWH(5, 5);
1289        SkPaint p;
1290
1291        canvas->drawRect(r, p);
1292
1293        SkAutoTUnref<SkPicture> copy(SkPictureRecorderReplayTester::Copy(&recorder));
1294
1295        REPORTER_ASSERT(reporter, !copy->willPlayBackBitmaps());
1296
1297        SkBitmap bm;
1298        make_bm(&bm, 10, 10, SK_ColorRED, true);
1299
1300        r.offset(5.0f, 5.0f);
1301        canvas->drawBitmapRectToRect(bm, NULL, r);
1302
1303        SkAutoTUnref<SkPicture> final(recorder.endRecording());
1304        REPORTER_ASSERT(reporter, final->willPlayBackBitmaps());
1305
1306        REPORTER_ASSERT(reporter, copy->uniqueID() != final->uniqueID());
1307
1308        // The snapshot shouldn't pick up any operations added after it was made
1309        REPORTER_ASSERT(reporter, !copy->willPlayBackBitmaps());
1310    }
1311
1312    // Recreate the Android partialReplay test case
1313    {
1314        SkPictureRecorder recorder;
1315
1316        SkCanvas* canvas = recorder.beginRecording(4, 3, NULL, 0);
1317        create_imbalance(canvas);
1318
1319        int expectedSaveCount = canvas->getSaveCount();
1320
1321        SkAutoTUnref<SkPicture> copy(SkPictureRecorderReplayTester::Copy(&recorder));
1322        check_balance(reporter, copy);
1323
1324        REPORTER_ASSERT(reporter, expectedSaveCount = canvas->getSaveCount());
1325
1326        // End the recording of source to test the picture finalization
1327        // process isn't complicated by the partialReplay step
1328        SkAutoTUnref<SkPicture> final(recorder.endRecording());
1329    }
1330}
1331
1332static void test_unbalanced_save_restores(skiatest::Reporter* reporter) {
1333    SkCanvas testCanvas(100, 100);
1334    set_canvas_to_save_count_4(&testCanvas);
1335
1336    REPORTER_ASSERT(reporter, 4 == testCanvas.getSaveCount());
1337
1338    SkPaint paint;
1339    SkRect rect = SkRect::MakeLTRB(-10000000, -10000000, 10000000, 10000000);
1340
1341    SkPictureRecorder recorder;
1342
1343    {
1344        // Create picture with 2 unbalanced saves
1345        SkCanvas* canvas = recorder.beginRecording(100, 100);
1346        canvas->save();
1347        canvas->translate(10, 10);
1348        canvas->drawRect(rect, paint);
1349        canvas->save();
1350        canvas->translate(10, 10);
1351        canvas->drawRect(rect, paint);
1352        SkAutoTUnref<SkPicture> extraSavePicture(recorder.endRecording());
1353
1354        testCanvas.drawPicture(extraSavePicture);
1355        REPORTER_ASSERT(reporter, 4 == testCanvas.getSaveCount());
1356    }
1357
1358    set_canvas_to_save_count_4(&testCanvas);
1359
1360    {
1361        // Create picture with 2 unbalanced restores
1362        SkCanvas* canvas = recorder.beginRecording(100, 100);
1363        canvas->save();
1364        canvas->translate(10, 10);
1365        canvas->drawRect(rect, paint);
1366        canvas->save();
1367        canvas->translate(10, 10);
1368        canvas->drawRect(rect, paint);
1369        canvas->restore();
1370        canvas->restore();
1371        canvas->restore();
1372        canvas->restore();
1373        SkAutoTUnref<SkPicture> extraRestorePicture(recorder.endRecording());
1374
1375        testCanvas.drawPicture(extraRestorePicture);
1376        REPORTER_ASSERT(reporter, 4 == testCanvas.getSaveCount());
1377    }
1378
1379    set_canvas_to_save_count_4(&testCanvas);
1380
1381    {
1382        SkCanvas* canvas = recorder.beginRecording(100, 100);
1383        canvas->translate(10, 10);
1384        canvas->drawRect(rect, paint);
1385        SkAutoTUnref<SkPicture> noSavePicture(recorder.endRecording());
1386
1387        testCanvas.drawPicture(noSavePicture);
1388        REPORTER_ASSERT(reporter, 4 == testCanvas.getSaveCount());
1389        REPORTER_ASSERT(reporter, testCanvas.getTotalMatrix().isIdentity());
1390    }
1391}
1392
1393static void test_peephole() {
1394    SkRandom rand;
1395
1396    SkPictureRecorder recorder;
1397
1398    for (int j = 0; j < 100; j++) {
1399        SkRandom rand2(rand); // remember the seed
1400
1401        SkCanvas* canvas = recorder.beginRecording(100, 100);
1402
1403        for (int i = 0; i < 1000; ++i) {
1404            rand_op(canvas, rand);
1405        }
1406        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1407
1408        rand = rand2;
1409    }
1410
1411    {
1412        SkCanvas* canvas = recorder.beginRecording(100, 100);
1413        SkRect rect = SkRect::MakeWH(50, 50);
1414
1415        for (int i = 0; i < 100; ++i) {
1416            canvas->save();
1417        }
1418        while (canvas->getSaveCount() > 1) {
1419            canvas->clipRect(rect);
1420            canvas->restore();
1421        }
1422        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1423    }
1424}
1425
1426#ifndef SK_DEBUG
1427// Only test this is in release mode. We deliberately crash in debug mode, since a valid caller
1428// should never do this.
1429static void test_bad_bitmap() {
1430    // This bitmap has a width and height but no pixels. As a result, attempting to record it will
1431    // fail.
1432    SkBitmap bm;
1433    bm.setInfo(SkImageInfo::MakeN32Premul(100, 100));
1434    SkPictureRecorder recorder;
1435    SkCanvas* recordingCanvas = recorder.beginRecording(100, 100);
1436    recordingCanvas->drawBitmap(bm, 0, 0);
1437    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1438
1439    SkCanvas canvas;
1440    canvas.drawPicture(picture);
1441}
1442#endif
1443
1444static SkData* encode_bitmap_to_data(size_t*, const SkBitmap& bm) {
1445    return SkImageEncoder::EncodeData(bm, SkImageEncoder::kPNG_Type, 100);
1446}
1447
1448static SkData* serialized_picture_from_bitmap(const SkBitmap& bitmap) {
1449    SkPictureRecorder recorder;
1450    SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(bitmap.width()),
1451                                               SkIntToScalar(bitmap.height()));
1452    canvas->drawBitmap(bitmap, 0, 0);
1453    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1454
1455    SkDynamicMemoryWStream wStream;
1456    picture->serialize(&wStream, &encode_bitmap_to_data);
1457    return wStream.copyToData();
1458}
1459
1460struct ErrorContext {
1461    int fErrors;
1462    skiatest::Reporter* fReporter;
1463};
1464
1465static void assert_one_parse_error_cb(SkError error, void* context) {
1466    ErrorContext* errorContext = static_cast<ErrorContext*>(context);
1467    errorContext->fErrors++;
1468    // This test only expects one error, and that is a kParseError. If there are others,
1469    // there is some unknown problem.
1470    REPORTER_ASSERT_MESSAGE(errorContext->fReporter, 1 == errorContext->fErrors,
1471                            "This threw more errors than expected.");
1472    REPORTER_ASSERT_MESSAGE(errorContext->fReporter, kParseError_SkError == error,
1473                            SkGetLastErrorString());
1474}
1475
1476static void test_bitmap_with_encoded_data(skiatest::Reporter* reporter) {
1477    // Create a bitmap that will be encoded.
1478    SkBitmap original;
1479    make_bm(&original, 100, 100, SK_ColorBLUE, true);
1480    SkDynamicMemoryWStream wStream;
1481    if (!SkImageEncoder::EncodeStream(&wStream, original, SkImageEncoder::kPNG_Type, 100)) {
1482        return;
1483    }
1484    SkAutoDataUnref data(wStream.copyToData());
1485
1486    SkBitmap bm;
1487    bool installSuccess = SkInstallDiscardablePixelRef(
1488         SkDecodingImageGenerator::Create(data, SkDecodingImageGenerator::Options()), &bm);
1489    REPORTER_ASSERT(reporter, installSuccess);
1490
1491    // Write both bitmaps to pictures, and ensure that the resulting data streams are the same.
1492    // Flattening original will follow the old path of performing an encode, while flattening bm
1493    // will use the already encoded data.
1494    SkAutoDataUnref picture1(serialized_picture_from_bitmap(original));
1495    SkAutoDataUnref picture2(serialized_picture_from_bitmap(bm));
1496    REPORTER_ASSERT(reporter, picture1->equals(picture2));
1497    // Now test that a parse error was generated when trying to create a new SkPicture without
1498    // providing a function to decode the bitmap.
1499    ErrorContext context;
1500    context.fErrors = 0;
1501    context.fReporter = reporter;
1502    SkSetErrorCallback(assert_one_parse_error_cb, &context);
1503    SkMemoryStream pictureStream(picture1);
1504    SkClearLastError();
1505    SkAutoUnref pictureFromStream(SkPicture::CreateFromStream(&pictureStream, NULL));
1506    REPORTER_ASSERT(reporter, pictureFromStream.get() != NULL);
1507    SkClearLastError();
1508    SkSetErrorCallback(NULL, NULL);
1509}
1510
1511static void test_draw_empty(skiatest::Reporter* reporter) {
1512    SkBitmap result;
1513    make_bm(&result, 2, 2, SK_ColorBLACK, false);
1514
1515    SkCanvas canvas(result);
1516
1517    {
1518        // stock SkPicture
1519        SkPictureRecorder recorder;
1520        recorder.beginRecording(1, 1);
1521        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1522
1523        canvas.drawPicture(picture);
1524    }
1525
1526    {
1527        // tile grid
1528        SkTileGridFactory::TileGridInfo gridInfo;
1529        gridInfo.fMargin.setEmpty();
1530        gridInfo.fOffset.setZero();
1531        gridInfo.fTileInterval.set(1, 1);
1532
1533        SkTileGridFactory factory(gridInfo);
1534        SkPictureRecorder recorder;
1535        recorder.beginRecording(1, 1, &factory);
1536        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1537
1538        canvas.drawPicture(picture);
1539    }
1540
1541    {
1542        // RTree
1543        SkRTreeFactory factory;
1544        SkPictureRecorder recorder;
1545        recorder.beginRecording(1, 1, &factory);
1546        SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1547
1548        canvas.drawPicture(picture);
1549    }
1550}
1551
1552static void test_clip_bound_opt(skiatest::Reporter* reporter) {
1553    // Test for crbug.com/229011
1554    SkRect rect1 = SkRect::MakeXYWH(SkIntToScalar(4), SkIntToScalar(4),
1555                                    SkIntToScalar(2), SkIntToScalar(2));
1556    SkRect rect2 = SkRect::MakeXYWH(SkIntToScalar(7), SkIntToScalar(7),
1557                                    SkIntToScalar(1), SkIntToScalar(1));
1558    SkRect rect3 = SkRect::MakeXYWH(SkIntToScalar(6), SkIntToScalar(6),
1559                                    SkIntToScalar(1), SkIntToScalar(1));
1560
1561    SkPath invPath;
1562    invPath.addOval(rect1);
1563    invPath.setFillType(SkPath::kInverseEvenOdd_FillType);
1564    SkPath path;
1565    path.addOval(rect2);
1566    SkPath path2;
1567    path2.addOval(rect3);
1568    SkIRect clipBounds;
1569    SkPictureRecorder recorder;
1570    // Minimalist test set for 100% code coverage of
1571    // SkPictureRecord::updateClipConservativelyUsingBounds
1572    {
1573        SkCanvas* canvas = recorder.beginRecording(10, 10);
1574        canvas->clipPath(invPath, SkRegion::kIntersect_Op);
1575        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1576        REPORTER_ASSERT(reporter, true == nonEmpty);
1577        REPORTER_ASSERT(reporter, 0 == clipBounds.fLeft);
1578        REPORTER_ASSERT(reporter, 0 == clipBounds.fTop);
1579        REPORTER_ASSERT(reporter, 10 == clipBounds.fBottom);
1580        REPORTER_ASSERT(reporter, 10 == clipBounds.fRight);
1581    }
1582    {
1583        SkCanvas* canvas = recorder.beginRecording(10, 10);
1584        canvas->clipPath(path, SkRegion::kIntersect_Op);
1585        canvas->clipPath(invPath, SkRegion::kIntersect_Op);
1586        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1587        REPORTER_ASSERT(reporter, true == nonEmpty);
1588        REPORTER_ASSERT(reporter, 7 == clipBounds.fLeft);
1589        REPORTER_ASSERT(reporter, 7 == clipBounds.fTop);
1590        REPORTER_ASSERT(reporter, 8 == clipBounds.fBottom);
1591        REPORTER_ASSERT(reporter, 8 == clipBounds.fRight);
1592    }
1593    {
1594        SkCanvas* canvas = recorder.beginRecording(10, 10);
1595        canvas->clipPath(path, SkRegion::kIntersect_Op);
1596        canvas->clipPath(invPath, SkRegion::kUnion_Op);
1597        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1598        REPORTER_ASSERT(reporter, true == nonEmpty);
1599        REPORTER_ASSERT(reporter, 0 == clipBounds.fLeft);
1600        REPORTER_ASSERT(reporter, 0 == clipBounds.fTop);
1601        REPORTER_ASSERT(reporter, 10 == clipBounds.fBottom);
1602        REPORTER_ASSERT(reporter, 10 == clipBounds.fRight);
1603    }
1604    {
1605        SkCanvas* canvas = recorder.beginRecording(10, 10);
1606        canvas->clipPath(path, SkRegion::kDifference_Op);
1607        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1608        REPORTER_ASSERT(reporter, true == nonEmpty);
1609        REPORTER_ASSERT(reporter, 0 == clipBounds.fLeft);
1610        REPORTER_ASSERT(reporter, 0 == clipBounds.fTop);
1611        REPORTER_ASSERT(reporter, 10 == clipBounds.fBottom);
1612        REPORTER_ASSERT(reporter, 10 == clipBounds.fRight);
1613    }
1614    {
1615        SkCanvas* canvas = recorder.beginRecording(10, 10);
1616        canvas->clipPath(path, SkRegion::kReverseDifference_Op);
1617        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1618        // True clip is actually empty in this case, but the best
1619        // determination we can make using only bounds as input is that the
1620        // clip is included in the bounds of 'path'.
1621        REPORTER_ASSERT(reporter, true == nonEmpty);
1622        REPORTER_ASSERT(reporter, 7 == clipBounds.fLeft);
1623        REPORTER_ASSERT(reporter, 7 == clipBounds.fTop);
1624        REPORTER_ASSERT(reporter, 8 == clipBounds.fBottom);
1625        REPORTER_ASSERT(reporter, 8 == clipBounds.fRight);
1626    }
1627    {
1628        SkCanvas* canvas = recorder.beginRecording(10, 10);
1629        canvas->clipPath(path, SkRegion::kIntersect_Op);
1630        canvas->clipPath(path2, SkRegion::kXOR_Op);
1631        bool nonEmpty = canvas->getClipDeviceBounds(&clipBounds);
1632        REPORTER_ASSERT(reporter, true == nonEmpty);
1633        REPORTER_ASSERT(reporter, 6 == clipBounds.fLeft);
1634        REPORTER_ASSERT(reporter, 6 == clipBounds.fTop);
1635        REPORTER_ASSERT(reporter, 8 == clipBounds.fBottom);
1636        REPORTER_ASSERT(reporter, 8 == clipBounds.fRight);
1637    }
1638}
1639
1640/**
1641 * A canvas that records the number of clip commands.
1642 */
1643class ClipCountingCanvas : public SkCanvas {
1644public:
1645    ClipCountingCanvas(int width, int height)
1646        : INHERITED(width, height)
1647        , fClipCount(0){
1648    }
1649
1650    virtual void onClipRect(const SkRect& r,
1651                            SkRegion::Op op,
1652                            ClipEdgeStyle edgeStyle) SK_OVERRIDE {
1653        fClipCount += 1;
1654        this->INHERITED::onClipRect(r, op, edgeStyle);
1655    }
1656
1657    virtual void onClipRRect(const SkRRect& rrect,
1658                             SkRegion::Op op,
1659                             ClipEdgeStyle edgeStyle)SK_OVERRIDE {
1660        fClipCount += 1;
1661        this->INHERITED::onClipRRect(rrect, op, edgeStyle);
1662    }
1663
1664    virtual void onClipPath(const SkPath& path,
1665                            SkRegion::Op op,
1666                            ClipEdgeStyle edgeStyle) SK_OVERRIDE {
1667        fClipCount += 1;
1668        this->INHERITED::onClipPath(path, op, edgeStyle);
1669    }
1670
1671    virtual void onClipRegion(const SkRegion& deviceRgn, SkRegion::Op op) SK_OVERRIDE {
1672        fClipCount += 1;
1673        this->INHERITED::onClipRegion(deviceRgn, op);
1674    }
1675
1676    unsigned getClipCount() const { return fClipCount; }
1677
1678private:
1679    unsigned fClipCount;
1680
1681    typedef SkCanvas INHERITED;
1682};
1683
1684static void test_clip_expansion(skiatest::Reporter* reporter) {
1685    SkPictureRecorder recorder;
1686    SkCanvas* canvas = recorder.beginRecording(10, 10);
1687
1688    canvas->clipRect(SkRect::MakeEmpty(), SkRegion::kReplace_Op);
1689    // The following expanding clip should not be skipped.
1690    canvas->clipRect(SkRect::MakeXYWH(4, 4, 3, 3), SkRegion::kUnion_Op);
1691    // Draw something so the optimizer doesn't just fold the world.
1692    SkPaint p;
1693    p.setColor(SK_ColorBLUE);
1694    canvas->drawPaint(p);
1695    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1696
1697    ClipCountingCanvas testCanvas(10, 10);
1698    picture->playback(&testCanvas);
1699
1700    // Both clips should be present on playback.
1701    REPORTER_ASSERT(reporter, testCanvas.getClipCount() == 2);
1702}
1703
1704static void test_hierarchical(skiatest::Reporter* reporter) {
1705    SkBitmap bm;
1706    make_bm(&bm, 10, 10, SK_ColorRED, true);
1707
1708    SkPictureRecorder recorder;
1709
1710    recorder.beginRecording(10, 10);
1711    SkAutoTUnref<SkPicture> childPlain(recorder.endRecording());
1712    REPORTER_ASSERT(reporter, !childPlain->willPlayBackBitmaps()); // 0
1713
1714    recorder.beginRecording(10, 10)->drawBitmap(bm, 0, 0);
1715    SkAutoTUnref<SkPicture> childWithBitmap(recorder.endRecording());
1716    REPORTER_ASSERT(reporter, childWithBitmap->willPlayBackBitmaps()); // 1
1717
1718    {
1719        SkCanvas* canvas = recorder.beginRecording(10, 10);
1720        canvas->drawPicture(childPlain);
1721        SkAutoTUnref<SkPicture> parentPP(recorder.endRecording());
1722        REPORTER_ASSERT(reporter, !parentPP->willPlayBackBitmaps()); // 0
1723    }
1724    {
1725        SkCanvas* canvas = recorder.beginRecording(10, 10);
1726        canvas->drawPicture(childWithBitmap);
1727        SkAutoTUnref<SkPicture> parentPWB(recorder.endRecording());
1728        REPORTER_ASSERT(reporter, parentPWB->willPlayBackBitmaps()); // 1
1729    }
1730    {
1731        SkCanvas* canvas = recorder.beginRecording(10, 10);
1732        canvas->drawBitmap(bm, 0, 0);
1733        canvas->drawPicture(childPlain);
1734        SkAutoTUnref<SkPicture> parentWBP(recorder.endRecording());
1735        REPORTER_ASSERT(reporter, parentWBP->willPlayBackBitmaps()); // 1
1736    }
1737    {
1738        SkCanvas* canvas = recorder.beginRecording(10, 10);
1739        canvas->drawBitmap(bm, 0, 0);
1740        canvas->drawPicture(childWithBitmap);
1741        SkAutoTUnref<SkPicture> parentWBWB(recorder.endRecording());
1742        REPORTER_ASSERT(reporter, parentWBWB->willPlayBackBitmaps()); // 2
1743    }
1744}
1745
1746static void test_gen_id(skiatest::Reporter* reporter) {
1747
1748    SkPictureRecorder recorder;
1749    recorder.beginRecording(0, 0);
1750    SkAutoTUnref<SkPicture> empty(recorder.endRecording());
1751
1752    // Empty pictures should still have a valid ID
1753    REPORTER_ASSERT(reporter, empty->uniqueID() != SK_InvalidGenID);
1754
1755    SkCanvas* canvas = recorder.beginRecording(1, 1);
1756    canvas->drawARGB(255, 255, 255, 255);
1757    SkAutoTUnref<SkPicture> hasData(recorder.endRecording());
1758    // picture should have a non-zero id after recording
1759    REPORTER_ASSERT(reporter, hasData->uniqueID() != SK_InvalidGenID);
1760
1761    // both pictures should have different ids
1762    REPORTER_ASSERT(reporter, hasData->uniqueID() != empty->uniqueID());
1763}
1764
1765DEF_TEST(Picture, reporter) {
1766#ifdef SK_DEBUG
1767    test_deleting_empty_picture();
1768    test_serializing_empty_picture();
1769#else
1770    test_bad_bitmap();
1771#endif
1772    test_unbalanced_save_restores(reporter);
1773    test_peephole();
1774#if SK_SUPPORT_GPU
1775    test_gpu_veto(reporter, false);
1776    test_gpu_veto(reporter, true);
1777#endif
1778    test_has_text(reporter, false);
1779    test_has_text(reporter, true);
1780    test_analysis(reporter, false);
1781    test_analysis(reporter, true);
1782    test_gatherpixelrefs(reporter);
1783    test_gatherpixelrefsandrects(reporter);
1784    test_bitmap_with_encoded_data(reporter);
1785    test_draw_empty(reporter);
1786    test_clip_bound_opt(reporter);
1787    test_clip_expansion(reporter);
1788    test_hierarchical(reporter);
1789    test_gen_id(reporter);
1790}
1791
1792#if SK_SUPPORT_GPU
1793DEF_GPUTEST(GPUPicture, reporter, factory) {
1794    test_gpu_picture_optimization(reporter, factory);
1795}
1796#endif
1797
1798static void draw_bitmaps(const SkBitmap bitmap, SkCanvas* canvas) {
1799    const SkPaint paint;
1800    const SkRect rect = { 5.0f, 5.0f, 8.0f, 8.0f };
1801    const SkIRect irect =  { 2, 2, 3, 3 };
1802
1803    // Don't care what these record, as long as they're legal.
1804    canvas->drawBitmap(bitmap, 0.0f, 0.0f, &paint);
1805    canvas->drawBitmapRectToRect(bitmap, &rect, rect, &paint, SkCanvas::kNone_DrawBitmapRectFlag);
1806    canvas->drawBitmapMatrix(bitmap, SkMatrix::I(), &paint);
1807    canvas->drawBitmapNine(bitmap, irect, rect, &paint);
1808    canvas->drawSprite(bitmap, 1, 1);
1809}
1810
1811static void test_draw_bitmaps(SkCanvas* canvas) {
1812    SkBitmap empty;
1813    draw_bitmaps(empty, canvas);
1814    empty.setInfo(SkImageInfo::MakeN32Premul(10, 10));
1815    draw_bitmaps(empty, canvas);
1816}
1817
1818DEF_TEST(Picture_EmptyBitmap, r) {
1819    SkPictureRecorder recorder;
1820    test_draw_bitmaps(recorder.beginRecording(10, 10));
1821    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1822}
1823
1824DEF_TEST(Canvas_EmptyBitmap, r) {
1825    SkBitmap dst;
1826    dst.allocN32Pixels(10, 10);
1827    SkCanvas canvas(dst);
1828
1829    test_draw_bitmaps(&canvas);
1830}
1831
1832DEF_TEST(DontOptimizeSaveLayerDrawDrawRestore, reporter) {
1833    // This test is from crbug.com/344987.
1834    // The commands are:
1835    //   saveLayer with paint that modifies alpha
1836    //     drawBitmapRectToRect
1837    //     drawBitmapRectToRect
1838    //   restore
1839    // The bug was that this structure was modified so that:
1840    //  - The saveLayer and restore were eliminated
1841    //  - The alpha was only applied to the first drawBitmapRectToRect
1842
1843    // This test draws blue and red squares inside a 50% transparent
1844    // layer.  Both colours should show up muted.
1845    // When the bug is present, the red square (the second bitmap)
1846    // shows upwith full opacity.
1847
1848    SkBitmap blueBM;
1849    make_bm(&blueBM, 100, 100, SkColorSetARGB(255, 0, 0, 255), true);
1850    SkBitmap redBM;
1851    make_bm(&redBM, 100, 100, SkColorSetARGB(255, 255, 0, 0), true);
1852    SkPaint semiTransparent;
1853    semiTransparent.setAlpha(0x80);
1854
1855    SkPictureRecorder recorder;
1856    SkCanvas* canvas = recorder.beginRecording(100, 100);
1857    canvas->drawARGB(0, 0, 0, 0);
1858
1859    canvas->saveLayer(0, &semiTransparent);
1860    canvas->drawBitmap(blueBM, 25, 25);
1861    canvas->drawBitmap(redBM, 50, 50);
1862    canvas->restore();
1863
1864    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
1865
1866    // Now replay the picture back on another canvas
1867    // and check a couple of its pixels.
1868    SkBitmap replayBM;
1869    make_bm(&replayBM, 100, 100, SK_ColorBLACK, false);
1870    SkCanvas replayCanvas(replayBM);
1871    picture->playback(&replayCanvas);
1872    replayCanvas.flush();
1873
1874    // With the bug present, at (55, 55) we would get a fully opaque red
1875    // intead of a dark red.
1876    REPORTER_ASSERT(reporter, replayBM.getColor(30, 30) == 0xff000080);
1877    REPORTER_ASSERT(reporter, replayBM.getColor(55, 55) == 0xff800000);
1878}
1879
1880struct CountingBBH : public SkBBoxHierarchy {
1881    mutable int searchCalls;
1882
1883    CountingBBH() : searchCalls(0) {}
1884
1885    virtual void search(const SkRect& query, SkTDArray<void*>* results) const {
1886        this->searchCalls++;
1887    }
1888
1889    // All other methods unimplemented.
1890    virtual void insert(void* data, const SkRect& bounds, bool defer) {}
1891    virtual void flushDeferredInserts() {}
1892    virtual void clear() {}
1893    virtual int getCount() const { return 0; }
1894    virtual int getDepth() const { return 0; }
1895    virtual void rewindInserts() {}
1896};
1897
1898class SpoonFedBBHFactory : public SkBBHFactory {
1899public:
1900    explicit SpoonFedBBHFactory(SkBBoxHierarchy* bbh) : fBBH(bbh) {}
1901    virtual SkBBoxHierarchy* operator()(int width, int height) const {
1902        return SkRef(fBBH);
1903    }
1904private:
1905    SkBBoxHierarchy* fBBH;
1906};
1907
1908// When the canvas clip covers the full picture, we don't need to call the BBH.
1909DEF_TEST(Picture_SkipBBH, r) {
1910    CountingBBH bbh;
1911    SpoonFedBBHFactory factory(&bbh);
1912
1913    SkPictureRecorder recorder;
1914    recorder.beginRecording(320, 240, &factory);
1915    SkAutoTUnref<const SkPicture> picture(recorder.endRecording());
1916
1917    SkCanvas big(640, 480), small(300, 200);
1918
1919    picture->playback(&big);
1920    REPORTER_ASSERT(r, bbh.searchCalls == 0);
1921
1922    picture->playback(&small);
1923    REPORTER_ASSERT(r, bbh.searchCalls == 1);
1924}
1925
1926DEF_TEST(Picture_BitmapLeak, r) {
1927    SkBitmap mut, immut;
1928    mut.allocN32Pixels(300, 200);
1929    immut.allocN32Pixels(300, 200);
1930    immut.setImmutable();
1931    SkASSERT(!mut.isImmutable());
1932    SkASSERT(immut.isImmutable());
1933
1934    // No one can hold a ref on our pixels yet.
1935    REPORTER_ASSERT(r, mut.pixelRef()->unique());
1936    REPORTER_ASSERT(r, immut.pixelRef()->unique());
1937
1938    SkPictureRecorder rec;
1939    SkCanvas* canvas = rec.beginRecording(1920, 1200);
1940        canvas->drawBitmap(mut, 0, 0);
1941        canvas->drawBitmap(immut, 800, 600);
1942    SkAutoTDelete<const SkPicture> pic(rec.endRecording());
1943
1944    // The picture shares the immutable pixels but copies the mutable ones.
1945    REPORTER_ASSERT(r, mut.pixelRef()->unique());
1946    REPORTER_ASSERT(r, !immut.pixelRef()->unique());
1947
1948    // When the picture goes away, it's just our bitmaps holding the refs.
1949    pic.reset(NULL);
1950    REPORTER_ASSERT(r, mut.pixelRef()->unique());
1951    REPORTER_ASSERT(r, immut.pixelRef()->unique());
1952}
1953