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 /* Description:
9 * This test defines a series of elementatry test steps that perform
10 * a single or a small group of canvas API calls. Each test step is
11 * used in several test cases that verify that different types of SkCanvas
12 * flavors and derivatives pass it and yield consistent behavior. The
13 * test cases analyse results that are queryable through the API. They do
14 * not look at rendering results.
15 *
16 * Adding test stepss:
17 * The general pattern for creating a new test step is to write a test
18 * function of the form:
19 *
20 * static void MyTestStepFunction(SkCanvas* canvas,
21 * const TestData& d,
22 * skiatest::Reporter* reporter,
23 * CanvasTestStep* testStep)
24 * {
25 * canvas->someCanvasAPImethod();
26 * (...)
27 * REPORTER_ASSERT(reporter, (...), \
28 * testStep->assertMessage());
29 * }
30 *
31 * The definition of the test step function should be followed by an
32 * invocation of the TEST_STEP macro, which generates a class and
33 * instance for the test step:
34 *
35 * TEST_STEP(MyTestStep, MyTestStepFunction)
36 *
37 * There are also short hand macros for defining simple test steps
38 * in a single line of code. A simple test step is a one that is made
39 * of a single canvas API call.
40 *
41 * SIMPLE_TEST_STEP(MytestStep, someCanvasAPIMethod());
42 *
43 * There is another macro called SIMPLE_TEST_STEP_WITH_ASSERT that
44 * works the same way as SIMPLE_TEST_STEP, and additionally verifies
45 * that the invoked method returns a non-zero value.
46 */
47
48 #include "SkBitmap.h"
49 #include "SkBlendMode.h"
50 #include "SkCanvas.h"
51 #include "SkCanvasStack.h"
52 #include "SkClipOp.h"
53 #include "SkClipOpPriv.h"
54 #include "SkColor.h"
55 #include "SkImageFilter.h"
56 #include "SkImageInfo.h"
57 #include "SkMalloc.h"
58 #include "SkMatrix.h"
59 #include "SkNWayCanvas.h"
60 #include "SkPDFDocument.h"
61 #include "SkPaint.h"
62 #include "SkPaintFilterCanvas.h"
63 #include "SkPath.h"
64 #include "SkPictureRecorder.h"
65 #include "SkPixmap.h"
66 #include "SkPoint.h"
67 #include "SkRect.h"
68 #include "SkRefCnt.h"
69 #include "SkRegion.h"
70 #include "SkScalar.h"
71 #include "SkShader.h"
72 #include "SkSize.h"
73 #include "SkSpecialImage.h"
74 #include "SkStream.h"
75 #include "SkString.h"
76 #include "SkSurface.h"
77 #include "SkTDArray.h"
78 #include "SkTemplates.h"
79 #include "SkTypes.h"
80 #include "SkVertices.h"
81 #include "Test.h"
82
83 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
84 #include "SkColorData.h"
85 #include "SkColorSpace.h"
86 #endif
87
88 #include <memory>
89 #include <utility>
90
91 class SkColorSpaceXformer;
92 class SkReadBuffer;
93 template <typename T> class SkTCopyOnFirstWrite;
94
DEF_TEST(canvas_clipbounds,reporter)95 DEF_TEST(canvas_clipbounds, reporter) {
96 SkCanvas canvas(10, 10);
97 SkIRect irect, irect2;
98 SkRect rect, rect2;
99
100 irect = canvas.getDeviceClipBounds();
101 REPORTER_ASSERT(reporter, irect == SkIRect::MakeWH(10, 10));
102 REPORTER_ASSERT(reporter, canvas.getDeviceClipBounds(&irect2));
103 REPORTER_ASSERT(reporter, irect == irect2);
104
105 // local bounds are always too big today -- can we trim them?
106 rect = canvas.getLocalClipBounds();
107 REPORTER_ASSERT(reporter, rect.contains(SkRect::MakeWH(10, 10)));
108 REPORTER_ASSERT(reporter, canvas.getLocalClipBounds(&rect2));
109 REPORTER_ASSERT(reporter, rect == rect2);
110
111 canvas.clipRect(SkRect::MakeEmpty());
112
113 irect = canvas.getDeviceClipBounds();
114 REPORTER_ASSERT(reporter, irect == SkIRect::MakeEmpty());
115 REPORTER_ASSERT(reporter, !canvas.getDeviceClipBounds(&irect2));
116 REPORTER_ASSERT(reporter, irect == irect2);
117
118 rect = canvas.getLocalClipBounds();
119 REPORTER_ASSERT(reporter, rect == SkRect::MakeEmpty());
120 REPORTER_ASSERT(reporter, !canvas.getLocalClipBounds(&rect2));
121 REPORTER_ASSERT(reporter, rect == rect2);
122
123 // Test for wacky sizes that we (historically) have guarded against
124 {
125 SkCanvas c(-10, -20);
126 REPORTER_ASSERT(reporter, c.getBaseLayerSize() == SkISize::MakeEmpty());
127
128 SkPictureRecorder().beginRecording({ 5, 5, 4, 4 });
129 }
130 }
131
132 // Will call proc with multiple styles of canvas (recording, raster, pdf)
multi_canvas_driver(int w,int h,F proc)133 template <typename F> static void multi_canvas_driver(int w, int h, F proc) {
134 proc(SkPictureRecorder().beginRecording(SkRect::MakeIWH(w, h)));
135
136 SkNullWStream stream;
137 if (auto doc = SkPDF::MakeDocument(&stream)) {
138 proc(doc->beginPage(SkIntToScalar(w), SkIntToScalar(h)));
139 }
140
141 proc(SkSurface::MakeRasterN32Premul(w, h, nullptr)->getCanvas());
142 }
143
144 const SkIRect gBaseRestrictedR = { 0, 0, 10, 10 };
145
test_restriction(skiatest::Reporter * reporter,SkCanvas * canvas)146 static void test_restriction(skiatest::Reporter* reporter, SkCanvas* canvas) {
147 REPORTER_ASSERT(reporter, canvas->getDeviceClipBounds() == gBaseRestrictedR);
148
149 const SkIRect restrictionR = { 2, 2, 8, 8 };
150 canvas->androidFramework_setDeviceClipRestriction(restrictionR);
151 REPORTER_ASSERT(reporter, canvas->getDeviceClipBounds() == restrictionR);
152
153 const SkIRect clipR = { 4, 4, 6, 6 };
154 canvas->clipRect(SkRect::Make(clipR), SkClipOp::kIntersect);
155 REPORTER_ASSERT(reporter, canvas->getDeviceClipBounds() == clipR);
156
157 #ifdef SK_SUPPORT_DEPRECATED_CLIPOPS
158 // now test that expanding clipops can't exceed the restriction
159 const SkClipOp expanders[] = {
160 SkClipOp::kUnion_deprecated,
161 SkClipOp::kXOR_deprecated,
162 SkClipOp::kReverseDifference_deprecated,
163 SkClipOp::kReplace_deprecated,
164 };
165
166 const SkRect expandR = { 0, 0, 5, 9 };
167 SkASSERT(!SkRect::Make(restrictionR).contains(expandR));
168
169 for (SkClipOp op : expanders) {
170 canvas->save();
171 canvas->clipRect(expandR, op);
172 REPORTER_ASSERT(reporter, gBaseRestrictedR.contains(canvas->getDeviceClipBounds()));
173 canvas->restore();
174 }
175 #endif
176 }
177
178 /**
179 * Clip restriction logic exists in the canvas itself, and in various kinds of devices.
180 *
181 * This test explicitly tries to exercise that variety:
182 * - picture : empty device but exercises canvas itself
183 * - pdf : uses SkClipStack in its device (as does SVG and GPU)
184 * - raster : uses SkRasterClip in its device
185 */
DEF_TEST(canvas_clip_restriction,reporter)186 DEF_TEST(canvas_clip_restriction, reporter) {
187 multi_canvas_driver(gBaseRestrictedR.width(), gBaseRestrictedR.height(),
188 [reporter](SkCanvas* canvas) { test_restriction(reporter, canvas); });
189 }
190
DEF_TEST(canvas_empty_clip,reporter)191 DEF_TEST(canvas_empty_clip, reporter) {
192 multi_canvas_driver(50, 50, [reporter](SkCanvas* canvas) {
193 canvas->save();
194 canvas->clipRect({0, 0, 20, 40 });
195 REPORTER_ASSERT(reporter, !canvas->isClipEmpty());
196 canvas->clipRect({30, 0, 50, 40 });
197 REPORTER_ASSERT(reporter, canvas->isClipEmpty());
198 });
199 }
200
201 static const int kWidth = 2, kHeight = 2;
202
createBitmap(SkBitmap * bm,SkColor color)203 static void createBitmap(SkBitmap* bm, SkColor color) {
204 bm->allocN32Pixels(kWidth, kHeight);
205 bm->eraseColor(color);
206 }
207
208 ///////////////////////////////////////////////////////////////////////////////
209 // Constants used by test steps
210 const SkPoint kTestPoints[] = {
211 {SkIntToScalar(0), SkIntToScalar(0)},
212 {SkIntToScalar(2), SkIntToScalar(1)},
213 {SkIntToScalar(0), SkIntToScalar(2)}
214 };
215 const SkPoint kTestPoints2[] = {
216 { SkIntToScalar(0), SkIntToScalar(1) },
217 { SkIntToScalar(1), SkIntToScalar(1) },
218 { SkIntToScalar(2), SkIntToScalar(1) },
219 { SkIntToScalar(3), SkIntToScalar(1) },
220 { SkIntToScalar(4), SkIntToScalar(1) },
221 { SkIntToScalar(5), SkIntToScalar(1) },
222 { SkIntToScalar(6), SkIntToScalar(1) },
223 { SkIntToScalar(7), SkIntToScalar(1) },
224 { SkIntToScalar(8), SkIntToScalar(1) },
225 { SkIntToScalar(9), SkIntToScalar(1) },
226 { SkIntToScalar(10), SkIntToScalar(1) }
227 };
228
229 struct TestData {
230 public:
TestDataTestData231 TestData()
232 : fRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
233 SkIntToScalar(2), SkIntToScalar(1)))
234 , fMatrix(TestMatrix())
235 , fPath(TestPath())
236 , fNearlyZeroLengthPath(TestNearlyZeroLengthPath())
237 , fIRect(SkIRect::MakeXYWH(0, 0, 2, 1))
238 , fRegion(TestRegion())
239 , fColor(0x01020304)
240 , fPoints(kTestPoints)
241 , fPointCount(3)
242 , fWidth(2)
243 , fHeight(2)
244 , fText("Hello World")
245 , fPoints2(kTestPoints2)
246 , fBitmap(TestBitmap())
247 { }
248
249 SkRect fRect;
250 SkMatrix fMatrix;
251 SkPath fPath;
252 SkPath fNearlyZeroLengthPath;
253 SkIRect fIRect;
254 SkRegion fRegion;
255 SkColor fColor;
256 SkPaint fPaint;
257 const SkPoint* fPoints;
258 size_t fPointCount;
259 int fWidth;
260 int fHeight;
261 SkString fText;
262 const SkPoint* fPoints2;
263 SkBitmap fBitmap;
264
265 private:
TestMatrixTestData266 static SkMatrix TestMatrix() {
267 SkMatrix matrix;
268 matrix.reset();
269 matrix.setScale(SkIntToScalar(2), SkIntToScalar(3));
270
271 return matrix;
272 }
TestPathTestData273 static SkPath TestPath() {
274 SkPath path;
275 path.addRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
276 SkIntToScalar(2), SkIntToScalar(1)));
277 return path;
278 }
TestNearlyZeroLengthPathTestData279 static SkPath TestNearlyZeroLengthPath() {
280 SkPath path;
281 SkPoint pt1 = { 0, 0 };
282 SkPoint pt2 = { 0, SK_ScalarNearlyZero };
283 SkPoint pt3 = { SkIntToScalar(1), 0 };
284 SkPoint pt4 = { SkIntToScalar(1), SK_ScalarNearlyZero/2 };
285 path.moveTo(pt1);
286 path.lineTo(pt2);
287 path.lineTo(pt3);
288 path.lineTo(pt4);
289 return path;
290 }
TestRegionTestData291 static SkRegion TestRegion() {
292 SkRegion region;
293 SkIRect rect = SkIRect::MakeXYWH(0, 0, 2, 1);
294 region.setRect(rect);
295 return region;
296 }
TestBitmapTestData297 static SkBitmap TestBitmap() {
298 SkBitmap bitmap;
299 createBitmap(&bitmap, 0x05060708);
300 return bitmap;
301 }
302 };
303
304 // Format strings that describe the test context. The %s token is where
305 // the name of the test step is inserted. The context is required for
306 // disambiguating the error in the case of failures that are reported in
307 // functions that are called multiple times in different contexts (test
308 // cases and test steps).
309 static const char* const kDefaultAssertMessageFormat = "%s";
310 static const char* const kCanvasDrawAssertMessageFormat =
311 "Drawing test step %s with SkCanvas";
312 static const char* const kPdfAssertMessageFormat =
313 "PDF sanity check failed %s";
314
315 class CanvasTestStep;
testStepArray()316 static SkTDArray<CanvasTestStep*>& testStepArray() {
317 static SkTDArray<CanvasTestStep*> theTests;
318 return theTests;
319 }
320
321 class CanvasTestStep {
322 public:
CanvasTestStep(bool fEnablePdfTesting=true)323 CanvasTestStep(bool fEnablePdfTesting = true) {
324 *testStepArray().append() = this;
325 fAssertMessageFormat = kDefaultAssertMessageFormat;
326 this->fEnablePdfTesting = fEnablePdfTesting;
327 }
~CanvasTestStep()328 virtual ~CanvasTestStep() { }
329
330 virtual void draw(SkCanvas*, const TestData&, skiatest::Reporter*) = 0;
331 virtual const char* name() const = 0;
332
assertMessage()333 const char* assertMessage() {
334 fAssertMessage.printf(fAssertMessageFormat, name());
335 return fAssertMessage.c_str();
336 }
337
setAssertMessageFormat(const char * format)338 void setAssertMessageFormat(const char* format) {
339 fAssertMessageFormat = format;
340 }
341
enablePdfTesting()342 bool enablePdfTesting() { return fEnablePdfTesting; }
343
344 private:
345 SkString fAssertMessage;
346 const char* fAssertMessageFormat;
347 bool fEnablePdfTesting;
348 };
349
350 ///////////////////////////////////////////////////////////////////////////////
351 // Macros for defining test steps
352
353 #define TEST_STEP(NAME, FUNCTION) \
354 class NAME##_TestStep : public CanvasTestStep{ \
355 public: \
356 virtual void draw(SkCanvas* canvas, const TestData& d, \
357 skiatest::Reporter* reporter) { \
358 FUNCTION (canvas, d, reporter, this); \
359 } \
360 virtual const char* name() const {return #NAME ;} \
361 }; \
362 static NAME##_TestStep NAME##_TestStepInstance;
363
364 #define TEST_STEP_NO_PDF(NAME, FUNCTION) \
365 class NAME##_TestStep : public CanvasTestStep{ \
366 public: \
367 NAME##_TestStep() : CanvasTestStep(false) {} \
368 virtual void draw(SkCanvas* canvas, const TestData& d, \
369 skiatest::Reporter* reporter) { \
370 FUNCTION (canvas, d, reporter, this); \
371 } \
372 virtual const char* name() const {return #NAME ;} \
373 }; \
374 static NAME##_TestStep NAME##_TestStepInstance;
375
376 #define SIMPLE_TEST_STEP(NAME, CALL) \
377 static void NAME##TestStep(SkCanvas* canvas, const TestData& d, \
378 skiatest::Reporter*, CanvasTestStep*) { \
379 canvas-> CALL ; \
380 } \
381 TEST_STEP(NAME, NAME##TestStep )
382
383 #define SIMPLE_TEST_STEP_WITH_ASSERT(NAME, CALL) \
384 static void NAME##TestStep(SkCanvas* canvas, const TestData& d, skiatest::Reporter*, \
385 CanvasTestStep* testStep) { \
386 REPORTER_ASSERT(reporter, canvas->CALL, testStep->assertMessage()); \
387 } \
388 TEST_STEP(NAME, NAME##TestStep)
389
390 ///////////////////////////////////////////////////////////////////////////////
391 // Basic test steps for most virtual methods in SkCanvas that draw or affect
392 // the state of the canvas.
393
394 SIMPLE_TEST_STEP(Translate, translate(SkIntToScalar(1), SkIntToScalar(2)));
395 SIMPLE_TEST_STEP(Scale, scale(SkIntToScalar(1), SkIntToScalar(2)));
396 SIMPLE_TEST_STEP(Rotate, rotate(SkIntToScalar(1)));
397 SIMPLE_TEST_STEP(Skew, skew(SkIntToScalar(1), SkIntToScalar(2)));
398 SIMPLE_TEST_STEP(Concat, concat(d.fMatrix));
399 SIMPLE_TEST_STEP(SetMatrix, setMatrix(d.fMatrix));
400 SIMPLE_TEST_STEP(ClipRect, clipRect(d.fRect));
401 SIMPLE_TEST_STEP(ClipPath, clipPath(d.fPath));
402 SIMPLE_TEST_STEP(ClipRegion, clipRegion(d.fRegion, kReplace_SkClipOp));
403 SIMPLE_TEST_STEP(Clear, clear(d.fColor));
404
405 ///////////////////////////////////////////////////////////////////////////////
406 // Complex test steps
407
SaveMatrixClipStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter * reporter,CanvasTestStep * testStep)408 static void SaveMatrixClipStep(SkCanvas* canvas, const TestData& d,
409 skiatest::Reporter* reporter, CanvasTestStep* testStep) {
410 int saveCount = canvas->getSaveCount();
411 canvas->save();
412 canvas->translate(SkIntToScalar(1), SkIntToScalar(2));
413 canvas->clipRegion(d.fRegion);
414 canvas->restore();
415 REPORTER_ASSERT(reporter, canvas->getSaveCount() == saveCount, testStep->assertMessage());
416 REPORTER_ASSERT(reporter, canvas->getTotalMatrix().isIdentity(), testStep->assertMessage());
417 // REPORTER_ASSERT(reporter, canvas->getTotalClip() != kTestRegion,
418 // testStep->assertMessage());
419 }
420 TEST_STEP(SaveMatrixClip, SaveMatrixClipStep);
421
SaveLayerStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter * reporter,CanvasTestStep * testStep)422 static void SaveLayerStep(SkCanvas* canvas, const TestData& d,
423 skiatest::Reporter* reporter, CanvasTestStep* testStep) {
424 int saveCount = canvas->getSaveCount();
425 canvas->saveLayer(nullptr, nullptr);
426 canvas->restore();
427 REPORTER_ASSERT(reporter, canvas->getSaveCount() == saveCount, testStep->assertMessage());
428 }
429 TEST_STEP(SaveLayer, SaveLayerStep);
430
BoundedSaveLayerStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter * reporter,CanvasTestStep * testStep)431 static void BoundedSaveLayerStep(SkCanvas* canvas, const TestData& d,
432 skiatest::Reporter* reporter, CanvasTestStep* testStep) {
433 int saveCount = canvas->getSaveCount();
434 canvas->saveLayer(&d.fRect, nullptr);
435 canvas->restore();
436 REPORTER_ASSERT(reporter, canvas->getSaveCount() == saveCount, testStep->assertMessage());
437 }
438 TEST_STEP(BoundedSaveLayer, BoundedSaveLayerStep);
439
PaintSaveLayerStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter * reporter,CanvasTestStep * testStep)440 static void PaintSaveLayerStep(SkCanvas* canvas, const TestData& d,
441 skiatest::Reporter* reporter, CanvasTestStep* testStep) {
442 int saveCount = canvas->getSaveCount();
443 canvas->saveLayer(nullptr, &d.fPaint);
444 canvas->restore();
445 REPORTER_ASSERT(reporter, canvas->getSaveCount() == saveCount, testStep->assertMessage());
446 }
447 TEST_STEP(PaintSaveLayer, PaintSaveLayerStep);
448
TwoClipOpsStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter *,CanvasTestStep *)449 static void TwoClipOpsStep(SkCanvas* canvas, const TestData& d,
450 skiatest::Reporter*, CanvasTestStep*) {
451 // This test exercises a functionality in SkPicture that leads to the
452 // recording of restore offset placeholders. This test will trigger an
453 // assertion at playback time if the placeholders are not properly
454 // filled when the recording ends.
455 canvas->clipRect(d.fRect);
456 canvas->clipRegion(d.fRegion);
457 }
458 TEST_STEP(TwoClipOps, TwoClipOpsStep);
459
460 // exercise fix for http://code.google.com/p/skia/issues/detail?id=560
461 // ('SkPathStroker::lineTo() fails for line with length SK_ScalarNearlyZero')
DrawNearlyZeroLengthPathTestStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter *,CanvasTestStep *)462 static void DrawNearlyZeroLengthPathTestStep(SkCanvas* canvas, const TestData& d,
463 skiatest::Reporter*, CanvasTestStep*) {
464 SkPaint paint;
465 paint.setStrokeWidth(SkIntToScalar(1));
466 paint.setStyle(SkPaint::kStroke_Style);
467
468 canvas->drawPath(d.fNearlyZeroLengthPath, paint);
469 }
470 TEST_STEP(DrawNearlyZeroLengthPath, DrawNearlyZeroLengthPathTestStep);
471
DrawVerticesShaderTestStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter *,CanvasTestStep *)472 static void DrawVerticesShaderTestStep(SkCanvas* canvas, const TestData& d,
473 skiatest::Reporter*, CanvasTestStep*) {
474 SkPoint pts[4];
475 pts[0].set(0, 0);
476 pts[1].set(SkIntToScalar(d.fWidth), 0);
477 pts[2].set(SkIntToScalar(d.fWidth), SkIntToScalar(d.fHeight));
478 pts[3].set(0, SkIntToScalar(d.fHeight));
479 SkPaint paint;
480 paint.setShader(SkShader::MakeBitmapShader(d.fBitmap, SkShader::kClamp_TileMode,
481 SkShader::kClamp_TileMode));
482 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangleFan_VertexMode, 4, pts, pts,
483 nullptr),
484 SkBlendMode::kModulate, paint);
485 }
486 // NYI: issue 240.
487 TEST_STEP_NO_PDF(DrawVerticesShader, DrawVerticesShaderTestStep);
488
DrawPictureTestStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter *,CanvasTestStep *)489 static void DrawPictureTestStep(SkCanvas* canvas, const TestData& d,
490 skiatest::Reporter*, CanvasTestStep*) {
491 SkPictureRecorder recorder;
492 SkCanvas* testCanvas = recorder.beginRecording(SkIntToScalar(d.fWidth), SkIntToScalar(d.fHeight),
493 nullptr, 0);
494 testCanvas->scale(SkIntToScalar(2), SkIntToScalar(1));
495 testCanvas->clipRect(d.fRect);
496 testCanvas->drawRect(d.fRect, d.fPaint);
497
498 canvas->drawPicture(recorder.finishRecordingAsPicture());
499 }
500 TEST_STEP(DrawPicture, DrawPictureTestStep);
501
SaveRestoreTestStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter * reporter,CanvasTestStep * testStep)502 static void SaveRestoreTestStep(SkCanvas* canvas, const TestData& d,
503 skiatest::Reporter* reporter, CanvasTestStep* testStep) {
504 int baseSaveCount = canvas->getSaveCount();
505 int n = canvas->save();
506 REPORTER_ASSERT(reporter, baseSaveCount == n, testStep->assertMessage());
507 REPORTER_ASSERT(reporter, baseSaveCount + 1 == canvas->getSaveCount(),
508 testStep->assertMessage());
509 canvas->save();
510 canvas->save();
511 REPORTER_ASSERT(reporter, baseSaveCount + 3 == canvas->getSaveCount(),
512 testStep->assertMessage());
513 canvas->restoreToCount(baseSaveCount + 1);
514 REPORTER_ASSERT(reporter, baseSaveCount + 1 == canvas->getSaveCount(),
515 testStep->assertMessage());
516
517 // should this pin to 1, or be a no-op, or crash?
518 canvas->restoreToCount(0);
519 REPORTER_ASSERT(reporter, 1 == canvas->getSaveCount(), testStep->assertMessage());
520 }
521 TEST_STEP(SaveRestore, SaveRestoreTestStep);
522
NestedSaveRestoreWithSolidPaintTestStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter *,CanvasTestStep *)523 static void NestedSaveRestoreWithSolidPaintTestStep(SkCanvas* canvas, const TestData& d,
524 skiatest::Reporter*, CanvasTestStep*) {
525 // This test step challenges the TestDeferredCanvasStateConsistency
526 // test cases because the opaque paint can trigger an optimization
527 // that discards previously recorded commands. The challenge is to maintain
528 // correct clip and matrix stack state.
529 canvas->resetMatrix();
530 canvas->rotate(SkIntToScalar(30));
531 canvas->save();
532 canvas->translate(SkIntToScalar(2), SkIntToScalar(1));
533 canvas->save();
534 canvas->scale(SkIntToScalar(3), SkIntToScalar(3));
535 SkPaint paint;
536 paint.setColor(0xFFFFFFFF);
537 canvas->drawPaint(paint);
538 canvas->restore();
539 canvas->restore();
540 }
541 TEST_STEP(NestedSaveRestoreWithSolidPaint, \
542 NestedSaveRestoreWithSolidPaintTestStep);
543
NestedSaveRestoreWithFlushTestStep(SkCanvas * canvas,const TestData & d,skiatest::Reporter *,CanvasTestStep *)544 static void NestedSaveRestoreWithFlushTestStep(SkCanvas* canvas, const TestData& d,
545 skiatest::Reporter*, CanvasTestStep*) {
546 // This test step challenges the TestDeferredCanvasStateConsistency
547 // test case because the canvas flush on a deferred canvas will
548 // reset the recording session. The challenge is to maintain correct
549 // clip and matrix stack state on the playback canvas.
550 canvas->resetMatrix();
551 canvas->rotate(SkIntToScalar(30));
552 canvas->save();
553 canvas->translate(SkIntToScalar(2), SkIntToScalar(1));
554 canvas->save();
555 canvas->scale(SkIntToScalar(3), SkIntToScalar(3));
556 canvas->drawRect(d.fRect,d.fPaint);
557 canvas->flush();
558 canvas->restore();
559 canvas->restore();
560 }
561 TEST_STEP(NestedSaveRestoreWithFlush, NestedSaveRestoreWithFlushTestStep);
562
TestPdfDevice(skiatest::Reporter * reporter,const TestData & d,CanvasTestStep * step)563 static void TestPdfDevice(skiatest::Reporter* reporter, const TestData& d, CanvasTestStep* step) {
564 SkDynamicMemoryWStream outStream;
565 auto doc = SkPDF::MakeDocument(&outStream);
566 if (!doc) {
567 INFOF(reporter, "PDF disabled; TestPdfDevice test skipped.");
568 return;
569 }
570 SkCanvas* canvas = doc->beginPage(SkIntToScalar(d.fWidth),
571 SkIntToScalar(d.fHeight));
572 REPORTER_ASSERT(reporter, canvas);
573 step->setAssertMessageFormat(kPdfAssertMessageFormat);
574 step->draw(canvas, d, reporter);
575 }
576
577 /*
578 * This sub-test verifies that the test step passes when executed
579 * with SkCanvas and with classes derrived from SkCanvas. It also verifies
580 * that the all canvas derivatives report the same state as an SkCanvas
581 * after having executed the test step.
582 */
TestOverrideStateConsistency(skiatest::Reporter * reporter,const TestData & d,CanvasTestStep * testStep)583 static void TestOverrideStateConsistency(skiatest::Reporter* reporter, const TestData& d,
584 CanvasTestStep* testStep) {
585 SkBitmap referenceStore;
586 createBitmap(&referenceStore, 0xFFFFFFFF);
587 SkCanvas referenceCanvas(referenceStore);
588 testStep->setAssertMessageFormat(kCanvasDrawAssertMessageFormat);
589 testStep->draw(&referenceCanvas, d, reporter);
590 }
591
test_newraster(skiatest::Reporter * reporter)592 static void test_newraster(skiatest::Reporter* reporter) {
593 SkImageInfo info = SkImageInfo::MakeN32Premul(10, 10);
594 const size_t minRowBytes = info.minRowBytes();
595 const size_t size = info.computeByteSize(minRowBytes);
596 SkAutoTMalloc<SkPMColor> storage(size);
597 SkPMColor* baseAddr = storage.get();
598 sk_bzero(baseAddr, size);
599
600 std::unique_ptr<SkCanvas> canvas = SkCanvas::MakeRasterDirect(info, baseAddr, minRowBytes);
601 REPORTER_ASSERT(reporter, canvas);
602
603 SkPixmap pmap;
604 const SkPMColor* addr = canvas->peekPixels(&pmap) ? pmap.addr32() : nullptr;
605 REPORTER_ASSERT(reporter, addr);
606 REPORTER_ASSERT(reporter, info == pmap.info());
607 REPORTER_ASSERT(reporter, minRowBytes == pmap.rowBytes());
608 for (int y = 0; y < info.height(); ++y) {
609 for (int x = 0; x < info.width(); ++x) {
610 REPORTER_ASSERT(reporter, 0 == addr[x]);
611 }
612 addr = (const SkPMColor*)((const char*)addr + pmap.rowBytes());
613 }
614
615 // now try a deliberately bad info
616 info = info.makeWH(-1, info.height());
617 REPORTER_ASSERT(reporter, nullptr == SkCanvas::MakeRasterDirect(info, baseAddr, minRowBytes));
618
619 // too big
620 info = info.makeWH(1 << 30, 1 << 30);
621 REPORTER_ASSERT(reporter, nullptr == SkCanvas::MakeRasterDirect(info, baseAddr, minRowBytes));
622
623 // not a valid pixel type
624 info = SkImageInfo::Make(10, 10, kUnknown_SkColorType, info.alphaType());
625 REPORTER_ASSERT(reporter, nullptr == SkCanvas::MakeRasterDirect(info, baseAddr, minRowBytes));
626
627 // We should not succeed with a zero-sized valid info
628 info = SkImageInfo::MakeN32Premul(0, 0);
629 canvas = SkCanvas::MakeRasterDirect(info, baseAddr, minRowBytes);
630 REPORTER_ASSERT(reporter, nullptr == canvas);
631 }
632
DEF_TEST(Canvas,reporter)633 DEF_TEST(Canvas, reporter) {
634 TestData d;
635
636 for (int testStep = 0; testStep < testStepArray().count(); testStep++) {
637 TestOverrideStateConsistency(reporter, d, testStepArray()[testStep]);
638 if (testStepArray()[testStep]->enablePdfTesting()) {
639 TestPdfDevice(reporter, d, testStepArray()[testStep]);
640 }
641 }
642
643 test_newraster(reporter);
644 }
645
DEF_TEST(Canvas_SaveState,reporter)646 DEF_TEST(Canvas_SaveState, reporter) {
647 SkCanvas canvas(10, 10);
648 REPORTER_ASSERT(reporter, 1 == canvas.getSaveCount());
649
650 int n = canvas.save();
651 REPORTER_ASSERT(reporter, 1 == n);
652 REPORTER_ASSERT(reporter, 2 == canvas.getSaveCount());
653
654 n = canvas.saveLayer(nullptr, nullptr);
655 REPORTER_ASSERT(reporter, 2 == n);
656 REPORTER_ASSERT(reporter, 3 == canvas.getSaveCount());
657
658 canvas.restore();
659 REPORTER_ASSERT(reporter, 2 == canvas.getSaveCount());
660 canvas.restore();
661 REPORTER_ASSERT(reporter, 1 == canvas.getSaveCount());
662 }
663
DEF_TEST(Canvas_ClipEmptyPath,reporter)664 DEF_TEST(Canvas_ClipEmptyPath, reporter) {
665 SkCanvas canvas(10, 10);
666 canvas.save();
667 SkPath path;
668 canvas.clipPath(path);
669 canvas.restore();
670 canvas.save();
671 path.moveTo(5, 5);
672 canvas.clipPath(path);
673 canvas.restore();
674 canvas.save();
675 path.moveTo(7, 7);
676 canvas.clipPath(path); // should not assert here
677 canvas.restore();
678 }
679
680 namespace {
681
682 class MockFilterCanvas : public SkPaintFilterCanvas {
683 public:
MockFilterCanvas(SkCanvas * canvas)684 MockFilterCanvas(SkCanvas* canvas) : INHERITED(canvas) { }
685
686 protected:
onFilter(SkTCopyOnFirstWrite<SkPaint> *,Type) const687 bool onFilter(SkTCopyOnFirstWrite<SkPaint>*, Type) const override { return true; }
688
689 private:
690 typedef SkPaintFilterCanvas INHERITED;
691 };
692
693 } // anonymous namespace
694
695 // SkPaintFilterCanvas should inherit the initial target canvas state.
DEF_TEST(PaintFilterCanvas_ConsistentState,reporter)696 DEF_TEST(PaintFilterCanvas_ConsistentState, reporter) {
697 SkCanvas canvas(100, 100);
698 canvas.clipRect(SkRect::MakeXYWH(12.7f, 12.7f, 75, 75));
699 canvas.scale(0.5f, 0.75f);
700
701 MockFilterCanvas filterCanvas(&canvas);
702 REPORTER_ASSERT(reporter, canvas.getTotalMatrix() == filterCanvas.getTotalMatrix());
703 REPORTER_ASSERT(reporter, canvas.getLocalClipBounds() == filterCanvas.getLocalClipBounds());
704
705 filterCanvas.clipRect(SkRect::MakeXYWH(30.5f, 30.7f, 100, 100));
706 filterCanvas.scale(0.75f, 0.5f);
707 REPORTER_ASSERT(reporter, canvas.getTotalMatrix() == filterCanvas.getTotalMatrix());
708 REPORTER_ASSERT(reporter, filterCanvas.getLocalClipBounds().contains(canvas.getLocalClipBounds()));
709 }
710
711 ///////////////////////////////////////////////////////////////////////////////////////////////////
712
713 // Subclass that takes a bool*, which it updates in its construct (true) and destructor (false)
714 // to allow the caller to know how long the object is alive.
715 class LifeLineCanvas : public SkCanvas {
716 bool* fLifeLine;
717 public:
LifeLineCanvas(int w,int h,bool * lifeline)718 LifeLineCanvas(int w, int h, bool* lifeline) : SkCanvas(w, h), fLifeLine(lifeline) {
719 *fLifeLine = true;
720 }
~LifeLineCanvas()721 ~LifeLineCanvas() {
722 *fLifeLine = false;
723 }
724 };
725
726 // Check that NWayCanvas does NOT try to manage the lifetime of its sub-canvases
DEF_TEST(NWayCanvas,r)727 DEF_TEST(NWayCanvas, r) {
728 const int w = 10;
729 const int h = 10;
730 bool life[2];
731 {
732 LifeLineCanvas c0(w, h, &life[0]);
733 REPORTER_ASSERT(r, life[0]);
734 }
735 REPORTER_ASSERT(r, !life[0]);
736
737
738 std::unique_ptr<SkCanvas> c0 = std::unique_ptr<SkCanvas>(new LifeLineCanvas(w, h, &life[0]));
739 std::unique_ptr<SkCanvas> c1 = std::unique_ptr<SkCanvas>(new LifeLineCanvas(w, h, &life[1]));
740 REPORTER_ASSERT(r, life[0]);
741 REPORTER_ASSERT(r, life[1]);
742
743 {
744 SkNWayCanvas nway(w, h);
745 nway.addCanvas(c0.get());
746 nway.addCanvas(c1.get());
747 REPORTER_ASSERT(r, life[0]);
748 REPORTER_ASSERT(r, life[1]);
749 }
750 // Now assert that the death of the nway has NOT also killed the sub-canvases
751 REPORTER_ASSERT(r, life[0]);
752 REPORTER_ASSERT(r, life[1]);
753 }
754
755 // Check that CanvasStack DOES manage the lifetime of its sub-canvases
DEF_TEST(CanvasStack,r)756 DEF_TEST(CanvasStack, r) {
757 const int w = 10;
758 const int h = 10;
759 bool life[2];
760 std::unique_ptr<SkCanvas> c0 = std::unique_ptr<SkCanvas>(new LifeLineCanvas(w, h, &life[0]));
761 std::unique_ptr<SkCanvas> c1 = std::unique_ptr<SkCanvas>(new LifeLineCanvas(w, h, &life[1]));
762 REPORTER_ASSERT(r, life[0]);
763 REPORTER_ASSERT(r, life[1]);
764
765 {
766 SkCanvasStack stack(w, h);
767 stack.pushCanvas(std::move(c0), {0,0});
768 stack.pushCanvas(std::move(c1), {0,0});
769 REPORTER_ASSERT(r, life[0]);
770 REPORTER_ASSERT(r, life[1]);
771 }
772 // Now assert that the death of the canvasstack has also killed the sub-canvases
773 REPORTER_ASSERT(r, !life[0]);
774 REPORTER_ASSERT(r, !life[1]);
775 }
776
test_cliptype(SkCanvas * canvas,skiatest::Reporter * r)777 static void test_cliptype(SkCanvas* canvas, skiatest::Reporter* r) {
778 REPORTER_ASSERT(r, !canvas->isClipEmpty());
779 REPORTER_ASSERT(r, canvas->isClipRect());
780
781 canvas->save();
782 canvas->clipRect({0, 0, 0, 0});
783 REPORTER_ASSERT(r, canvas->isClipEmpty());
784 REPORTER_ASSERT(r, !canvas->isClipRect());
785 canvas->restore();
786
787 canvas->save();
788 canvas->clipRect({2, 2, 6, 6});
789 REPORTER_ASSERT(r, !canvas->isClipEmpty());
790 REPORTER_ASSERT(r, canvas->isClipRect());
791 canvas->restore();
792
793 canvas->save();
794 canvas->clipRect({2, 2, 6, 6}, SkClipOp::kDifference); // punch a hole in the clip
795 REPORTER_ASSERT(r, !canvas->isClipEmpty());
796 REPORTER_ASSERT(r, !canvas->isClipRect());
797 canvas->restore();
798
799 REPORTER_ASSERT(r, !canvas->isClipEmpty());
800 REPORTER_ASSERT(r, canvas->isClipRect());
801 }
802
DEF_TEST(CanvasClipType,r)803 DEF_TEST(CanvasClipType, r) {
804 // test rasterclip backend
805 test_cliptype(SkSurface::MakeRasterN32Premul(10, 10)->getCanvas(), r);
806
807 // test clipstack backend
808 SkDynamicMemoryWStream stream;
809 if (auto doc = SkPDF::MakeDocument(&stream)) {
810 test_cliptype(doc->beginPage(100, 100), r);
811 }
812 }
813
814 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
DEF_TEST(Canvas_LegacyColorBehavior,r)815 DEF_TEST(Canvas_LegacyColorBehavior, r) {
816 sk_sp<SkColorSpace> cs = SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB,
817 SkNamedGamut::kAdobeRGB);
818
819 // Make a Adobe RGB bitmap.
820 SkBitmap bitmap;
821 bitmap.allocPixels(SkImageInfo::MakeN32(1, 1, kOpaque_SkAlphaType, cs));
822 bitmap.eraseColor(0xFF000000);
823
824 // Wrap it in a legacy canvas. Test that the canvas behaves like a legacy canvas.
825 SkCanvas canvas(bitmap, SkCanvas::ColorBehavior::kLegacy);
826 REPORTER_ASSERT(r, !canvas.imageInfo().colorSpace());
827 SkPaint p;
828 p.setColor(SK_ColorRED);
829 canvas.drawIRect(SkIRect::MakeWH(1, 1), p);
830 REPORTER_ASSERT(r, SK_ColorRED == SkSwizzle_BGRA_to_PMColor(*bitmap.getAddr32(0, 0)));
831 }
832 #endif
833
834 namespace {
835
836 class ZeroBoundsImageFilter : public SkImageFilter {
837 public:
Make()838 static sk_sp<SkImageFilter> Make() { return sk_sp<SkImageFilter>(new ZeroBoundsImageFilter); }
839
840 protected:
onFilterImage(SkSpecialImage *,const Context &,SkIPoint *) const841 sk_sp<SkSpecialImage> onFilterImage(SkSpecialImage*, const Context&, SkIPoint*) const override {
842 return nullptr;
843 }
onMakeColorSpace(SkColorSpaceXformer *) const844 sk_sp<SkImageFilter> onMakeColorSpace(SkColorSpaceXformer*) const override { return nullptr; }
onFilterNodeBounds(const SkIRect &,const SkMatrix &,MapDirection,const SkIRect * inputRect) const845 SkIRect onFilterNodeBounds(const SkIRect&, const SkMatrix&,
846 MapDirection, const SkIRect* inputRect) const override {
847 return SkIRect::MakeEmpty();
848 }
849
850 private:
851 SK_FLATTENABLE_HOOKS(ZeroBoundsImageFilter)
852
ZeroBoundsImageFilter()853 ZeroBoundsImageFilter() : INHERITED(nullptr, 0, nullptr) {}
854
855 typedef SkImageFilter INHERITED;
856 };
857
CreateProc(SkReadBuffer & buffer)858 sk_sp<SkFlattenable> ZeroBoundsImageFilter::CreateProc(SkReadBuffer& buffer) {
859 SkDEBUGFAIL("Should never get here");
860 return nullptr;
861 }
862
863 } // anonymous namespace
864
DEF_TEST(Canvas_SaveLayerWithNullBoundsAndZeroBoundsImageFilter,r)865 DEF_TEST(Canvas_SaveLayerWithNullBoundsAndZeroBoundsImageFilter, r) {
866 SkCanvas canvas(10, 10);
867 SkPaint p;
868 p.setImageFilter(ZeroBoundsImageFilter::Make());
869 // This should not fail any assert.
870 canvas.saveLayer(nullptr, &p);
871 REPORTER_ASSERT(r, canvas.getDeviceClipBounds().isEmpty());
872 canvas.restore();
873 }
874
875 #include "SkPaintImageFilter.h"
876
877 // Test that we don't crash/assert when building a canvas with degenerate coordintes
878 // (esp. big ones, that might invoke tiling).
DEF_TEST(Canvas_degenerate_dimension,reporter)879 DEF_TEST(Canvas_degenerate_dimension, reporter) {
880 // Need a paint that will sneak us past the quickReject in SkCanvas, so we can test the
881 // raster code further downstream.
882 SkPaint paint;
883 paint.setImageFilter(SkPaintImageFilter::Make(SkPaint(), nullptr));
884 REPORTER_ASSERT(reporter, !paint.canComputeFastBounds());
885
886 const int big = 100 * 1024; // big enough to definitely trigger tiling
887 const SkISize sizes[] {SkISize{0, big}, {big, 0}, {0, 0}};
888 for (SkISize size : sizes) {
889 SkBitmap bm;
890 bm.setInfo(SkImageInfo::MakeN32Premul(size.width(), size.height()));
891 SkCanvas canvas(bm);
892 canvas.drawRect({0, 0, 100, 90*1024}, paint);
893 }
894 }
895
896 #include "SkBlurImageFilter.h"
897
DEF_TEST(Canvas_ClippedOutImageFilter,reporter)898 DEF_TEST(Canvas_ClippedOutImageFilter, reporter) {
899 SkCanvas canvas(100, 100);
900
901 SkPaint p;
902 p.setColor(SK_ColorGREEN);
903 p.setImageFilter(SkBlurImageFilter::Make(3.0f, 3.0f, nullptr, nullptr));
904
905 SkRect blurredRect = SkRect::MakeXYWH(60, 10, 30, 30);
906
907 SkMatrix invM;
908 invM.setRotate(-45);
909 invM.mapRect(&blurredRect);
910
911 const SkRect clipRect = SkRect::MakeXYWH(0, 50, 50, 50);
912
913 canvas.clipRect(clipRect);
914
915 canvas.rotate(45);
916 const SkMatrix preCTM = canvas.getTotalMatrix();
917 canvas.drawRect(blurredRect, p);
918 const SkMatrix postCTM = canvas.getTotalMatrix();
919 REPORTER_ASSERT(reporter, preCTM == postCTM);
920 }
921
922