1 /*
2 * Copyright 2013 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 "Resources.h"
9 #include "SkAnnotationKeys.h"
10 #include "SkCanvas.h"
11 #include "SkFixed.h"
12 #include "SkFontDescriptor.h"
13 #include "SkImage.h"
14 #include "SkImageSource.h"
15 #include "SkLightingShader.h"
16 #include "SkMakeUnique.h"
17 #include "SkMallocPixelRef.h"
18 #include "SkNormalSource.h"
19 #include "SkOSFile.h"
20 #include "SkPictureRecorder.h"
21 #include "SkShaderBase.h"
22 #include "SkTableColorFilter.h"
23 #include "SkTemplates.h"
24 #include "SkTypeface.h"
25 #include "SkWriteBuffer.h"
26 #include "SkValidatingReadBuffer.h"
27 #include "SkXfermodeImageFilter.h"
28 #include "sk_tool_utils.h"
29 #include "Test.h"
30
31 static const uint32_t kArraySize = 64;
32 static const int kBitmapSize = 256;
33
34 template<typename T>
TestAlignment(T * testObj,skiatest::Reporter * reporter)35 static void TestAlignment(T* testObj, skiatest::Reporter* reporter) {
36 // Test memory read/write functions directly
37 unsigned char dataWritten[1024];
38 size_t bytesWrittenToMemory = testObj->writeToMemory(dataWritten);
39 REPORTER_ASSERT(reporter, SkAlign4(bytesWrittenToMemory) == bytesWrittenToMemory);
40 size_t bytesReadFromMemory = testObj->readFromMemory(dataWritten, bytesWrittenToMemory);
41 REPORTER_ASSERT(reporter, SkAlign4(bytesReadFromMemory) == bytesReadFromMemory);
42 }
43
44 template<typename T> struct SerializationUtils {
45 // Generic case for flattenables
WriteSerializationUtils46 static void Write(SkWriteBuffer& writer, const T* flattenable) {
47 writer.writeFlattenable(flattenable);
48 }
ReadSerializationUtils49 static void Read(SkValidatingReadBuffer& reader, T** flattenable) {
50 *flattenable = (T*)reader.readFlattenable(T::GetFlattenableType());
51 }
52 };
53
54 template<> struct SerializationUtils<SkMatrix> {
WriteSerializationUtils55 static void Write(SkWriteBuffer& writer, const SkMatrix* matrix) {
56 writer.writeMatrix(*matrix);
57 }
ReadSerializationUtils58 static void Read(SkValidatingReadBuffer& reader, SkMatrix* matrix) {
59 reader.readMatrix(matrix);
60 }
61 };
62
63 template<> struct SerializationUtils<SkPath> {
WriteSerializationUtils64 static void Write(SkWriteBuffer& writer, const SkPath* path) {
65 writer.writePath(*path);
66 }
ReadSerializationUtils67 static void Read(SkValidatingReadBuffer& reader, SkPath* path) {
68 reader.readPath(path);
69 }
70 };
71
72 template<> struct SerializationUtils<SkRegion> {
WriteSerializationUtils73 static void Write(SkWriteBuffer& writer, const SkRegion* region) {
74 writer.writeRegion(*region);
75 }
ReadSerializationUtils76 static void Read(SkValidatingReadBuffer& reader, SkRegion* region) {
77 reader.readRegion(region);
78 }
79 };
80
81 template<> struct SerializationUtils<SkString> {
WriteSerializationUtils82 static void Write(SkWriteBuffer& writer, const SkString* string) {
83 writer.writeString(string->c_str());
84 }
ReadSerializationUtils85 static void Read(SkValidatingReadBuffer& reader, SkString* string) {
86 reader.readString(string);
87 }
88 };
89
90 template<> struct SerializationUtils<unsigned char> {
WriteSerializationUtils91 static void Write(SkWriteBuffer& writer, unsigned char* data, uint32_t arraySize) {
92 writer.writeByteArray(data, arraySize);
93 }
ReadSerializationUtils94 static bool Read(SkValidatingReadBuffer& reader, unsigned char* data, uint32_t arraySize) {
95 return reader.readByteArray(data, arraySize);
96 }
97 };
98
99 template<> struct SerializationUtils<SkColor> {
WriteSerializationUtils100 static void Write(SkWriteBuffer& writer, SkColor* data, uint32_t arraySize) {
101 writer.writeColorArray(data, arraySize);
102 }
ReadSerializationUtils103 static bool Read(SkValidatingReadBuffer& reader, SkColor* data, uint32_t arraySize) {
104 return reader.readColorArray(data, arraySize);
105 }
106 };
107
108 template<> struct SerializationUtils<SkColor4f> {
WriteSerializationUtils109 static void Write(SkWriteBuffer& writer, SkColor4f* data, uint32_t arraySize) {
110 writer.writeColor4fArray(data, arraySize);
111 }
ReadSerializationUtils112 static bool Read(SkValidatingReadBuffer& reader, SkColor4f* data, uint32_t arraySize) {
113 return reader.readColor4fArray(data, arraySize);
114 }
115 };
116
117 template<> struct SerializationUtils<int32_t> {
WriteSerializationUtils118 static void Write(SkWriteBuffer& writer, int32_t* data, uint32_t arraySize) {
119 writer.writeIntArray(data, arraySize);
120 }
ReadSerializationUtils121 static bool Read(SkValidatingReadBuffer& reader, int32_t* data, uint32_t arraySize) {
122 return reader.readIntArray(data, arraySize);
123 }
124 };
125
126 template<> struct SerializationUtils<SkPoint> {
WriteSerializationUtils127 static void Write(SkWriteBuffer& writer, SkPoint* data, uint32_t arraySize) {
128 writer.writePointArray(data, arraySize);
129 }
ReadSerializationUtils130 static bool Read(SkValidatingReadBuffer& reader, SkPoint* data, uint32_t arraySize) {
131 return reader.readPointArray(data, arraySize);
132 }
133 };
134
135 template<> struct SerializationUtils<SkScalar> {
WriteSerializationUtils136 static void Write(SkWriteBuffer& writer, SkScalar* data, uint32_t arraySize) {
137 writer.writeScalarArray(data, arraySize);
138 }
ReadSerializationUtils139 static bool Read(SkValidatingReadBuffer& reader, SkScalar* data, uint32_t arraySize) {
140 return reader.readScalarArray(data, arraySize);
141 }
142 };
143
144 template<typename T, bool testInvalid> struct SerializationTestUtils {
InvalidateDataSerializationTestUtils145 static void InvalidateData(unsigned char* data) {}
146 };
147
148 template<> struct SerializationTestUtils<SkString, true> {
InvalidateDataSerializationTestUtils149 static void InvalidateData(unsigned char* data) {
150 data[3] |= 0x80; // Reverse sign of 1st integer
151 }
152 };
153
154 template<typename T, bool testInvalid>
TestObjectSerializationNoAlign(T * testObj,skiatest::Reporter * reporter)155 static void TestObjectSerializationNoAlign(T* testObj, skiatest::Reporter* reporter) {
156 SkBinaryWriteBuffer writer;
157 SerializationUtils<T>::Write(writer, testObj);
158 size_t bytesWritten = writer.bytesWritten();
159 REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
160
161 unsigned char dataWritten[1024];
162 writer.writeToMemory(dataWritten);
163
164 SerializationTestUtils<T, testInvalid>::InvalidateData(dataWritten);
165
166 // Make sure this fails when it should (test with smaller size, but still multiple of 4)
167 SkValidatingReadBuffer buffer(dataWritten, bytesWritten - 4);
168 T obj;
169 SerializationUtils<T>::Read(buffer, &obj);
170 REPORTER_ASSERT(reporter, !buffer.isValid());
171
172 // Make sure this succeeds when it should
173 SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
174 size_t offsetBefore = buffer2.offset();
175 T obj2;
176 SerializationUtils<T>::Read(buffer2, &obj2);
177 size_t offsetAfter = buffer2.offset();
178 // This should have succeeded, since there are enough bytes to read this
179 REPORTER_ASSERT(reporter, buffer2.isValid() == !testInvalid);
180 // Note: This following test should always succeed, regardless of whether the buffer is valid,
181 // since if it is invalid, it will simply skip to the end, as if it had read the whole buffer.
182 REPORTER_ASSERT(reporter, offsetAfter - offsetBefore == bytesWritten);
183 }
184
185 template<typename T>
TestObjectSerialization(T * testObj,skiatest::Reporter * reporter)186 static void TestObjectSerialization(T* testObj, skiatest::Reporter* reporter) {
187 TestObjectSerializationNoAlign<T, false>(testObj, reporter);
188 TestAlignment(testObj, reporter);
189 }
190
191 template<typename T>
TestFlattenableSerialization(T * testObj,bool shouldSucceed,skiatest::Reporter * reporter)192 static T* TestFlattenableSerialization(T* testObj, bool shouldSucceed,
193 skiatest::Reporter* reporter) {
194 SkBinaryWriteBuffer writer;
195 SerializationUtils<T>::Write(writer, testObj);
196 size_t bytesWritten = writer.bytesWritten();
197 REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
198
199 SkASSERT(bytesWritten <= 4096);
200 unsigned char dataWritten[4096];
201 writer.writeToMemory(dataWritten);
202
203 // Make sure this fails when it should (test with smaller size, but still multiple of 4)
204 SkValidatingReadBuffer buffer(dataWritten, bytesWritten - 4);
205 T* obj = nullptr;
206 SerializationUtils<T>::Read(buffer, &obj);
207 REPORTER_ASSERT(reporter, !buffer.isValid());
208 REPORTER_ASSERT(reporter, nullptr == obj);
209
210 // Make sure this succeeds when it should
211 SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
212 const unsigned char* peekBefore = static_cast<const unsigned char*>(buffer2.skip(0));
213 T* obj2 = nullptr;
214 SerializationUtils<T>::Read(buffer2, &obj2);
215 const unsigned char* peekAfter = static_cast<const unsigned char*>(buffer2.skip(0));
216 if (shouldSucceed) {
217 // This should have succeeded, since there are enough bytes to read this
218 REPORTER_ASSERT(reporter, buffer2.isValid());
219 REPORTER_ASSERT(reporter, static_cast<size_t>(peekAfter - peekBefore) == bytesWritten);
220 REPORTER_ASSERT(reporter, obj2);
221 } else {
222 // If the deserialization was supposed to fail, make sure it did
223 REPORTER_ASSERT(reporter, !buffer.isValid());
224 REPORTER_ASSERT(reporter, nullptr == obj2);
225 }
226
227 return obj2; // Return object to perform further validity tests on it
228 }
229
230 template<typename T>
TestArraySerialization(T * data,skiatest::Reporter * reporter)231 static void TestArraySerialization(T* data, skiatest::Reporter* reporter) {
232 SkBinaryWriteBuffer writer;
233 SerializationUtils<T>::Write(writer, data, kArraySize);
234 size_t bytesWritten = writer.bytesWritten();
235 // This should write the length (in 4 bytes) and the array
236 REPORTER_ASSERT(reporter, (4 + kArraySize * sizeof(T)) == bytesWritten);
237
238 unsigned char dataWritten[2048];
239 writer.writeToMemory(dataWritten);
240
241 // Make sure this fails when it should
242 SkValidatingReadBuffer buffer(dataWritten, bytesWritten);
243 T dataRead[kArraySize];
244 bool success = SerializationUtils<T>::Read(buffer, dataRead, kArraySize / 2);
245 // This should have failed, since the provided size was too small
246 REPORTER_ASSERT(reporter, !success);
247
248 // Make sure this succeeds when it should
249 SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
250 success = SerializationUtils<T>::Read(buffer2, dataRead, kArraySize);
251 // This should have succeeded, since there are enough bytes to read this
252 REPORTER_ASSERT(reporter, success);
253 }
254
TestBitmapSerialization(const SkBitmap & validBitmap,const SkBitmap & invalidBitmap,bool shouldSucceed,skiatest::Reporter * reporter)255 static void TestBitmapSerialization(const SkBitmap& validBitmap,
256 const SkBitmap& invalidBitmap,
257 bool shouldSucceed,
258 skiatest::Reporter* reporter) {
259 sk_sp<SkImage> validImage(SkImage::MakeFromBitmap(validBitmap));
260 sk_sp<SkImageFilter> validBitmapSource(SkImageSource::Make(std::move(validImage)));
261 sk_sp<SkImage> invalidImage(SkImage::MakeFromBitmap(invalidBitmap));
262 sk_sp<SkImageFilter> invalidBitmapSource(SkImageSource::Make(std::move(invalidImage)));
263 sk_sp<SkImageFilter> xfermodeImageFilter(
264 SkXfermodeImageFilter::Make(SkBlendMode::kSrcOver,
265 std::move(invalidBitmapSource),
266 std::move(validBitmapSource), nullptr));
267
268 sk_sp<SkImageFilter> deserializedFilter(
269 TestFlattenableSerialization<SkImageFilter>(
270 xfermodeImageFilter.get(), shouldSucceed, reporter));
271
272 // Try to render a small bitmap using the invalid deserialized filter
273 // to make sure we don't crash while trying to render it
274 if (shouldSucceed) {
275 SkBitmap bitmap;
276 bitmap.allocN32Pixels(24, 24);
277 SkCanvas canvas(bitmap);
278 canvas.clear(0x00000000);
279 SkPaint paint;
280 paint.setImageFilter(deserializedFilter);
281 canvas.clipRect(SkRect::MakeXYWH(0, 0, SkIntToScalar(24), SkIntToScalar(24)));
282 canvas.drawBitmap(bitmap, 0, 0, &paint);
283 }
284 }
285
TestColorFilterSerialization(skiatest::Reporter * reporter)286 static void TestColorFilterSerialization(skiatest::Reporter* reporter) {
287 uint8_t table[256];
288 for (int i = 0; i < 256; ++i) {
289 table[i] = (i * 41) % 256;
290 }
291 auto colorFilter(SkTableColorFilter::Make(table));
292 sk_sp<SkColorFilter> copy(
293 TestFlattenableSerialization<SkColorFilter>(colorFilter.get(), true, reporter));
294 }
295
draw_picture(SkPicture & picture)296 static SkBitmap draw_picture(SkPicture& picture) {
297 SkBitmap bitmap;
298 bitmap.allocN32Pixels(SkScalarCeilToInt(picture.cullRect().width()),
299 SkScalarCeilToInt(picture.cullRect().height()));
300 SkCanvas canvas(bitmap);
301 picture.playback(&canvas);
302 return bitmap;
303 }
304
compare_bitmaps(skiatest::Reporter * reporter,const SkBitmap & b1,const SkBitmap & b2)305 static void compare_bitmaps(skiatest::Reporter* reporter,
306 const SkBitmap& b1, const SkBitmap& b2) {
307 REPORTER_ASSERT(reporter, b1.width() == b2.width());
308 REPORTER_ASSERT(reporter, b1.height() == b2.height());
309
310 if ((b1.width() != b2.width()) ||
311 (b1.height() != b2.height())) {
312 return;
313 }
314
315 int pixelErrors = 0;
316 for (int y = 0; y < b2.height(); ++y) {
317 for (int x = 0; x < b2.width(); ++x) {
318 if (b1.getColor(x, y) != b2.getColor(x, y))
319 ++pixelErrors;
320 }
321 }
322 REPORTER_ASSERT(reporter, 0 == pixelErrors);
323 }
serialize_and_compare_typeface(sk_sp<SkTypeface> typeface,const char * text,skiatest::Reporter * reporter)324 static void serialize_and_compare_typeface(sk_sp<SkTypeface> typeface, const char* text,
325 skiatest::Reporter* reporter)
326 {
327 // Create a paint with the typeface.
328 SkPaint paint;
329 paint.setColor(SK_ColorGRAY);
330 paint.setTextSize(SkIntToScalar(30));
331 paint.setTypeface(std::move(typeface));
332
333 // Paint some text.
334 SkPictureRecorder recorder;
335 SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
336 SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
337 SkIntToScalar(canvasRect.height()),
338 nullptr, 0);
339 canvas->drawColor(SK_ColorWHITE);
340 canvas->drawText(text, 2, 24, 32, paint);
341 sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
342
343 // Serlialize picture and create its clone from stream.
344 SkDynamicMemoryWStream stream;
345 picture->serialize(&stream);
346 std::unique_ptr<SkStream> inputStream(stream.detachAsStream());
347 sk_sp<SkPicture> loadedPicture(SkPicture::MakeFromStream(inputStream.get()));
348
349 // Draw both original and clone picture and compare bitmaps -- they should be identical.
350 SkBitmap origBitmap = draw_picture(*picture);
351 SkBitmap destBitmap = draw_picture(*loadedPicture);
352 compare_bitmaps(reporter, origBitmap, destBitmap);
353 }
354
TestPictureTypefaceSerialization(skiatest::Reporter * reporter)355 static void TestPictureTypefaceSerialization(skiatest::Reporter* reporter) {
356 {
357 // Load typeface from file to test CreateFromFile with index.
358 SkString filename = GetResourcePath("/fonts/test.ttc");
359 sk_sp<SkTypeface> typeface(SkTypeface::MakeFromFile(filename.c_str(), 1));
360 if (!typeface) {
361 INFOF(reporter, "Could not run fontstream test because test.ttc not found.");
362 } else {
363 serialize_and_compare_typeface(std::move(typeface), "A!", reporter);
364 }
365 }
366
367 {
368 // Load typeface as stream to create with axis settings.
369 std::unique_ptr<SkStreamAsset> distortable(GetResourceAsStream("/fonts/Distortable.ttf"));
370 if (!distortable) {
371 INFOF(reporter, "Could not run fontstream test because Distortable.ttf not found.");
372 } else {
373 SkFixed axis = SK_FixedSqrt2;
374 sk_sp<SkTypeface> typeface(SkTypeface::MakeFromFontData(
375 skstd::make_unique<SkFontData>(std::move(distortable), 0, &axis, 1)));
376 if (!typeface) {
377 INFOF(reporter, "Could not run fontstream test because Distortable.ttf not created.");
378 } else {
379 serialize_and_compare_typeface(std::move(typeface), "abc", reporter);
380 }
381 }
382 }
383 }
384
setup_bitmap_for_canvas(SkBitmap * bitmap)385 static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
386 bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
387 }
388
make_checkerboard_bitmap(SkBitmap & bitmap)389 static void make_checkerboard_bitmap(SkBitmap& bitmap) {
390 setup_bitmap_for_canvas(&bitmap);
391
392 SkCanvas canvas(bitmap);
393 canvas.clear(0x00000000);
394 SkPaint darkPaint;
395 darkPaint.setColor(0xFF804020);
396 SkPaint lightPaint;
397 lightPaint.setColor(0xFF244484);
398 const int i = kBitmapSize / 8;
399 const SkScalar f = SkIntToScalar(i);
400 for (int y = 0; y < kBitmapSize; y += i) {
401 for (int x = 0; x < kBitmapSize; x += i) {
402 canvas.save();
403 canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
404 canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
405 canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
406 canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
407 canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
408 canvas.restore();
409 }
410 }
411 }
412
draw_something(SkCanvas * canvas)413 static void draw_something(SkCanvas* canvas) {
414 SkPaint paint;
415 SkBitmap bitmap;
416 make_checkerboard_bitmap(bitmap);
417
418 canvas->save();
419 canvas->scale(0.5f, 0.5f);
420 canvas->drawBitmap(bitmap, 0, 0, nullptr);
421 canvas->restore();
422
423 paint.setAntiAlias(true);
424
425 paint.setColor(SK_ColorRED);
426 canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
427 paint.setColor(SK_ColorBLACK);
428 paint.setTextSize(SkIntToScalar(kBitmapSize/3));
429 canvas->drawString("Picture", SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), paint);
430 }
431
DEF_TEST(Serialization,reporter)432 DEF_TEST(Serialization, reporter) {
433 // Test matrix serialization
434 {
435 SkMatrix matrix = SkMatrix::I();
436 TestObjectSerialization(&matrix, reporter);
437 }
438
439 // Test path serialization
440 {
441 SkPath path;
442 TestObjectSerialization(&path, reporter);
443 }
444
445 // Test region serialization
446 {
447 SkRegion region;
448 TestObjectSerialization(®ion, reporter);
449 }
450
451 // Test color filter serialization
452 {
453 TestColorFilterSerialization(reporter);
454 }
455
456 // Test string serialization
457 {
458 SkString string("string");
459 TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
460 TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
461 }
462
463 // Test rrect serialization
464 {
465 // SkRRect does not initialize anything.
466 // An uninitialized SkRRect can be serialized,
467 // but will branch on uninitialized data when deserialized.
468 SkRRect rrect;
469 SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
470 SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
471 rrect.setRectRadii(rect, corners);
472 TestAlignment(&rrect, reporter);
473 }
474
475 // Test readByteArray
476 {
477 unsigned char data[kArraySize] = { 1, 2, 3 };
478 TestArraySerialization(data, reporter);
479 }
480
481 // Test readColorArray
482 {
483 SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
484 TestArraySerialization(data, reporter);
485 }
486
487 // Test readColor4fArray
488 {
489 SkColor4f data[kArraySize] = {
490 SkColor4f::FromColor(SK_ColorBLACK),
491 SkColor4f::FromColor(SK_ColorWHITE),
492 SkColor4f::FromColor(SK_ColorRED),
493 { 1.f, 2.f, 4.f, 8.f }
494 };
495 TestArraySerialization(data, reporter);
496 }
497
498 // Test readIntArray
499 {
500 int32_t data[kArraySize] = { 1, 2, 4, 8 };
501 TestArraySerialization(data, reporter);
502 }
503
504 // Test readPointArray
505 {
506 SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
507 TestArraySerialization(data, reporter);
508 }
509
510 // Test readScalarArray
511 {
512 SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
513 TestArraySerialization(data, reporter);
514 }
515
516 // Test invalid deserializations
517 {
518 SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
519
520 SkBitmap validBitmap;
521 validBitmap.setInfo(info);
522
523 // Create a bitmap with a really large height
524 SkBitmap invalidBitmap;
525 invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
526
527 // The deserialization should succeed, and the rendering shouldn't crash,
528 // even when the device fails to initialize, due to its size
529 TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
530 }
531
532 // Test simple SkPicture serialization
533 {
534 SkPictureRecorder recorder;
535 draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
536 SkIntToScalar(kBitmapSize),
537 nullptr, 0));
538 sk_sp<SkPicture> pict(recorder.finishRecordingAsPicture());
539
540 // Serialize picture
541 SkBinaryWriteBuffer writer;
542 pict->flatten(writer);
543 size_t size = writer.bytesWritten();
544 SkAutoTMalloc<unsigned char> data(size);
545 writer.writeToMemory(static_cast<void*>(data.get()));
546
547 // Deserialize picture
548 SkValidatingReadBuffer reader(static_cast<void*>(data.get()), size);
549 sk_sp<SkPicture> readPict(SkPicture::MakeFromBuffer(reader));
550 REPORTER_ASSERT(reporter, reader.isValid());
551 REPORTER_ASSERT(reporter, readPict.get());
552 }
553
554 TestPictureTypefaceSerialization(reporter);
555
556 // Test SkLightingShader/NormalMapSource serialization
557 {
558 const int kTexSize = 2;
559
560 SkLights::Builder builder;
561
562 builder.add(SkLights::Light::MakeDirectional(SkColor3f::Make(1.0f, 1.0f, 1.0f),
563 SkVector3::Make(1.0f, 0.0f, 0.0f)));
564 builder.setAmbientLightColor(SkColor3f::Make(0.2f, 0.2f, 0.2f));
565
566 sk_sp<SkLights> fLights = builder.finish();
567
568 SkBitmap diffuse = sk_tool_utils::create_checkerboard_bitmap(
569 kTexSize, kTexSize,
570 sk_tool_utils::color_to_565(0x0),
571 sk_tool_utils::color_to_565(0xFF804020),
572 8);
573
574 SkRect bitmapBounds = SkRect::MakeIWH(diffuse.width(), diffuse.height());
575
576 SkMatrix matrix;
577 SkRect r = SkRect::MakeWH(SkIntToScalar(kTexSize), SkIntToScalar(kTexSize));
578 matrix.setRectToRect(bitmapBounds, r, SkMatrix::kFill_ScaleToFit);
579
580 SkMatrix ctm;
581 ctm.setRotate(45);
582 SkBitmap normals;
583 normals.allocN32Pixels(kTexSize, kTexSize);
584
585 sk_tool_utils::create_frustum_normal_map(&normals, SkIRect::MakeWH(kTexSize, kTexSize));
586 sk_sp<SkShader> normalMap = SkShader::MakeBitmapShader(normals, SkShader::kClamp_TileMode,
587 SkShader::kClamp_TileMode, &matrix);
588 sk_sp<SkNormalSource> normalSource = SkNormalSource::MakeFromNormalMap(std::move(normalMap),
589 ctm);
590 sk_sp<SkShader> diffuseShader = SkShader::MakeBitmapShader(diffuse,
591 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode, &matrix);
592
593 sk_sp<SkShader> lightingShader = SkLightingShader::Make(diffuseShader,
594 normalSource,
595 fLights);
596 sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
597
598 lightingShader = SkLightingShader::Make(std::move(diffuseShader),
599 nullptr,
600 fLights);
601 sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
602
603 lightingShader = SkLightingShader::Make(nullptr,
604 std::move(normalSource),
605 fLights);
606 sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
607
608 lightingShader = SkLightingShader::Make(nullptr,
609 nullptr,
610 fLights);
611 sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
612 }
613 }
614
615 ///////////////////////////////////////////////////////////////////////////////////////////////////
616 #include "SkAnnotation.h"
617
copy_picture_via_serialization(SkPicture * src)618 static sk_sp<SkPicture> copy_picture_via_serialization(SkPicture* src) {
619 SkDynamicMemoryWStream wstream;
620 src->serialize(&wstream);
621 std::unique_ptr<SkStreamAsset> rstream(wstream.detachAsStream());
622 return SkPicture::MakeFromStream(rstream.get());
623 }
624
625 struct AnnotationRec {
626 const SkRect fRect;
627 const char* fKey;
628 sk_sp<SkData> fValue;
629 };
630
631 class TestAnnotationCanvas : public SkCanvas {
632 skiatest::Reporter* fReporter;
633 const AnnotationRec* fRec;
634 int fCount;
635 int fCurrIndex;
636
637 public:
TestAnnotationCanvas(skiatest::Reporter * reporter,const AnnotationRec rec[],int count)638 TestAnnotationCanvas(skiatest::Reporter* reporter, const AnnotationRec rec[], int count)
639 : SkCanvas(100, 100)
640 , fReporter(reporter)
641 , fRec(rec)
642 , fCount(count)
643 , fCurrIndex(0)
644 {}
645
~TestAnnotationCanvas()646 ~TestAnnotationCanvas() {
647 REPORTER_ASSERT(fReporter, fCount == fCurrIndex);
648 }
649
650 protected:
onDrawAnnotation(const SkRect & rect,const char key[],SkData * value)651 void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) {
652 REPORTER_ASSERT(fReporter, fCurrIndex < fCount);
653 REPORTER_ASSERT(fReporter, rect == fRec[fCurrIndex].fRect);
654 REPORTER_ASSERT(fReporter, !strcmp(key, fRec[fCurrIndex].fKey));
655 REPORTER_ASSERT(fReporter, value->equals(fRec[fCurrIndex].fValue.get()));
656 fCurrIndex += 1;
657 }
658 };
659
660 /*
661 * Test the 3 annotation types by recording them into a picture, serializing, and then playing
662 * them back into another canvas.
663 */
DEF_TEST(Annotations,reporter)664 DEF_TEST(Annotations, reporter) {
665 SkPictureRecorder recorder;
666 SkCanvas* recordingCanvas = recorder.beginRecording(SkRect::MakeWH(100, 100));
667
668 const char* str0 = "rect-with-url";
669 const SkRect r0 = SkRect::MakeWH(10, 10);
670 sk_sp<SkData> d0(SkData::MakeWithCString(str0));
671 SkAnnotateRectWithURL(recordingCanvas, r0, d0.get());
672
673 const char* str1 = "named-destination";
674 const SkRect r1 = SkRect::MakeXYWH(5, 5, 0, 0); // collapsed to a point
675 sk_sp<SkData> d1(SkData::MakeWithCString(str1));
676 SkAnnotateNamedDestination(recordingCanvas, {r1.x(), r1.y()}, d1.get());
677
678 const char* str2 = "link-to-destination";
679 const SkRect r2 = SkRect::MakeXYWH(20, 20, 5, 6);
680 sk_sp<SkData> d2(SkData::MakeWithCString(str2));
681 SkAnnotateLinkToDestination(recordingCanvas, r2, d2.get());
682
683 const AnnotationRec recs[] = {
684 { r0, SkAnnotationKeys::URL_Key(), std::move(d0) },
685 { r1, SkAnnotationKeys::Define_Named_Dest_Key(), std::move(d1) },
686 { r2, SkAnnotationKeys::Link_Named_Dest_Key(), std::move(d2) },
687 };
688
689 sk_sp<SkPicture> pict0(recorder.finishRecordingAsPicture());
690 sk_sp<SkPicture> pict1(copy_picture_via_serialization(pict0.get()));
691
692 TestAnnotationCanvas canvas(reporter, recs, SK_ARRAY_COUNT(recs));
693 canvas.drawPicture(pict1);
694 }
695