• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "include/core/SkCanvas.h"
9 #include "include/core/SkImage.h"
10 #include "include/core/SkMallocPixelRef.h"
11 #include "include/core/SkPictureRecorder.h"
12 #include "include/core/SkTextBlob.h"
13 #include "include/core/SkTypeface.h"
14 #include "include/effects/SkDashPathEffect.h"
15 #include "include/effects/SkImageFilters.h"
16 #include "include/effects/SkTableColorFilter.h"
17 #include "include/private/SkFixed.h"
18 #include "include/private/SkTemplates.h"
19 #include "src/core/SkAnnotationKeys.h"
20 #include "src/core/SkFontDescriptor.h"
21 #include "src/core/SkMatrixPriv.h"
22 #include "src/core/SkNormalSource.h"
23 #include "src/core/SkOSFile.h"
24 #include "src/core/SkPicturePriv.h"
25 #include "src/core/SkReadBuffer.h"
26 #include "src/core/SkWriteBuffer.h"
27 #include "src/shaders/SkLightingShader.h"
28 #include "src/shaders/SkShaderBase.h"
29 #include "tests/Test.h"
30 #include "tools/Resources.h"
31 #include "tools/ToolUtils.h"
32 
33 static const uint32_t kArraySize = 64;
34 static const int kBitmapSize = 256;
35 
36 class SerializationTest {
37 public:
38 
39 template<typename T>
TestAlignment(T * testObj,skiatest::Reporter * reporter)40 static void TestAlignment(T* testObj, skiatest::Reporter* reporter) {
41     // Test memory read/write functions directly
42     unsigned char dataWritten[1024];
43     size_t bytesWrittenToMemory = testObj->writeToMemory(dataWritten);
44     REPORTER_ASSERT(reporter, SkAlign4(bytesWrittenToMemory) == bytesWrittenToMemory);
45     size_t bytesReadFromMemory = testObj->readFromMemory(dataWritten, bytesWrittenToMemory);
46     REPORTER_ASSERT(reporter, SkAlign4(bytesReadFromMemory) == bytesReadFromMemory);
47 }
48 };
49 
50 template<typename T> struct SerializationUtils {
51     // Generic case for flattenables
WriteSerializationUtils52     static void Write(SkWriteBuffer& writer, const T* flattenable) {
53         writer.writeFlattenable(flattenable);
54     }
ReadSerializationUtils55     static void Read(SkReadBuffer& reader, T** flattenable) {
56         *flattenable = (T*)reader.readFlattenable(T::GetFlattenableType());
57     }
58 };
59 
60 template<> struct SerializationUtils<SkMatrix> {
WriteSerializationUtils61     static void Write(SkWriteBuffer& writer, const SkMatrix* matrix) {
62         writer.writeMatrix(*matrix);
63     }
ReadSerializationUtils64     static void Read(SkReadBuffer& reader, SkMatrix* matrix) {
65         reader.readMatrix(matrix);
66     }
67 };
68 
69 template<> struct SerializationUtils<SkPath> {
WriteSerializationUtils70     static void Write(SkWriteBuffer& writer, const SkPath* path) {
71         writer.writePath(*path);
72     }
ReadSerializationUtils73     static void Read(SkReadBuffer& reader, SkPath* path) {
74         reader.readPath(path);
75     }
76 };
77 
78 template<> struct SerializationUtils<SkRegion> {
WriteSerializationUtils79     static void Write(SkWriteBuffer& writer, const SkRegion* region) {
80         writer.writeRegion(*region);
81     }
ReadSerializationUtils82     static void Read(SkReadBuffer& reader, SkRegion* region) {
83         reader.readRegion(region);
84     }
85 };
86 
87 template<> struct SerializationUtils<SkString> {
WriteSerializationUtils88     static void Write(SkWriteBuffer& writer, const SkString* string) {
89         writer.writeString(string->c_str());
90     }
ReadSerializationUtils91     static void Read(SkReadBuffer& reader, SkString* string) {
92         reader.readString(string);
93     }
94 };
95 
96 template<> struct SerializationUtils<unsigned char> {
WriteSerializationUtils97     static void Write(SkWriteBuffer& writer, unsigned char* data, uint32_t arraySize) {
98         writer.writeByteArray(data, arraySize);
99     }
ReadSerializationUtils100     static bool Read(SkReadBuffer& reader, unsigned char* data, uint32_t arraySize) {
101         return reader.readByteArray(data, arraySize);
102     }
103 };
104 
105 template<> struct SerializationUtils<SkColor> {
WriteSerializationUtils106     static void Write(SkWriteBuffer& writer, SkColor* data, uint32_t arraySize) {
107         writer.writeColorArray(data, arraySize);
108     }
ReadSerializationUtils109     static bool Read(SkReadBuffer& reader, SkColor* data, uint32_t arraySize) {
110         return reader.readColorArray(data, arraySize);
111     }
112 };
113 
114 template<> struct SerializationUtils<SkColor4f> {
WriteSerializationUtils115     static void Write(SkWriteBuffer& writer, SkColor4f* data, uint32_t arraySize) {
116         writer.writeColor4fArray(data, arraySize);
117     }
ReadSerializationUtils118     static bool Read(SkReadBuffer& reader, SkColor4f* data, uint32_t arraySize) {
119         return reader.readColor4fArray(data, arraySize);
120     }
121 };
122 
123 template<> struct SerializationUtils<int32_t> {
WriteSerializationUtils124     static void Write(SkWriteBuffer& writer, int32_t* data, uint32_t arraySize) {
125         writer.writeIntArray(data, arraySize);
126     }
ReadSerializationUtils127     static bool Read(SkReadBuffer& reader, int32_t* data, uint32_t arraySize) {
128         return reader.readIntArray(data, arraySize);
129     }
130 };
131 
132 template<> struct SerializationUtils<SkPoint> {
WriteSerializationUtils133     static void Write(SkWriteBuffer& writer, SkPoint* data, uint32_t arraySize) {
134         writer.writePointArray(data, arraySize);
135     }
ReadSerializationUtils136     static bool Read(SkReadBuffer& reader, SkPoint* data, uint32_t arraySize) {
137         return reader.readPointArray(data, arraySize);
138     }
139 };
140 
141 template<> struct SerializationUtils<SkPoint3> {
WriteSerializationUtils142     static void Write(SkWriteBuffer& writer, const SkPoint3* data) {
143         writer.writePoint3(*data);
144     }
ReadSerializationUtils145     static void Read(SkReadBuffer& reader, SkPoint3* data) {
146         reader.readPoint3(data);
147     }
148 };
149 
150 template<> struct SerializationUtils<SkScalar> {
WriteSerializationUtils151     static void Write(SkWriteBuffer& writer, SkScalar* data, uint32_t arraySize) {
152         writer.writeScalarArray(data, arraySize);
153     }
ReadSerializationUtils154     static bool Read(SkReadBuffer& reader, SkScalar* data, uint32_t arraySize) {
155         return reader.readScalarArray(data, arraySize);
156     }
157 };
158 
159 template<typename T, bool testInvalid> struct SerializationTestUtils {
InvalidateDataSerializationTestUtils160     static void InvalidateData(unsigned char* data) {}
161 };
162 
163 template<> struct SerializationTestUtils<SkString, true> {
InvalidateDataSerializationTestUtils164     static void InvalidateData(unsigned char* data) {
165         data[3] |= 0x80; // Reverse sign of 1st integer
166     }
167 };
168 
169 template<typename T, bool testInvalid>
TestObjectSerializationNoAlign(T * testObj,skiatest::Reporter * reporter)170 static void TestObjectSerializationNoAlign(T* testObj, skiatest::Reporter* reporter) {
171     SkBinaryWriteBuffer writer;
172     SerializationUtils<T>::Write(writer, testObj);
173     size_t bytesWritten = writer.bytesWritten();
174     REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
175 
176     unsigned char dataWritten[1024];
177     writer.writeToMemory(dataWritten);
178 
179     SerializationTestUtils<T, testInvalid>::InvalidateData(dataWritten);
180 
181     // Make sure this fails when it should (test with smaller size, but still multiple of 4)
182     SkReadBuffer buffer(dataWritten, bytesWritten - 4);
183     T obj;
184     SerializationUtils<T>::Read(buffer, &obj);
185     REPORTER_ASSERT(reporter, !buffer.isValid());
186 
187     // Make sure this succeeds when it should
188     SkReadBuffer buffer2(dataWritten, bytesWritten);
189     size_t offsetBefore = buffer2.offset();
190     T obj2;
191     SerializationUtils<T>::Read(buffer2, &obj2);
192     size_t offsetAfter = buffer2.offset();
193     // This should have succeeded, since there are enough bytes to read this
194     REPORTER_ASSERT(reporter, buffer2.isValid() == !testInvalid);
195     // Note: This following test should always succeed, regardless of whether the buffer is valid,
196     // since if it is invalid, it will simply skip to the end, as if it had read the whole buffer.
197     REPORTER_ASSERT(reporter, offsetAfter - offsetBefore == bytesWritten);
198 }
199 
200 template<typename T>
TestObjectSerialization(T * testObj,skiatest::Reporter * reporter)201 static void TestObjectSerialization(T* testObj, skiatest::Reporter* reporter) {
202     TestObjectSerializationNoAlign<T, false>(testObj, reporter);
203     SerializationTest::TestAlignment(testObj, reporter);
204 }
205 
206 template<typename T>
TestFlattenableSerialization(T * testObj,bool shouldSucceed,skiatest::Reporter * reporter)207 static T* TestFlattenableSerialization(T* testObj, bool shouldSucceed,
208                                        skiatest::Reporter* reporter) {
209     SkBinaryWriteBuffer writer;
210     SerializationUtils<T>::Write(writer, testObj);
211     size_t bytesWritten = writer.bytesWritten();
212     REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
213 
214     SkASSERT(bytesWritten <= 4096);
215     unsigned char dataWritten[4096];
216     writer.writeToMemory(dataWritten);
217 
218     // Make sure this fails when it should (test with smaller size, but still multiple of 4)
219     SkReadBuffer buffer(dataWritten, bytesWritten - 4);
220     T* obj = nullptr;
221     SerializationUtils<T>::Read(buffer, &obj);
222     REPORTER_ASSERT(reporter, !buffer.isValid());
223     REPORTER_ASSERT(reporter, nullptr == obj);
224 
225     // Make sure this succeeds when it should
226     SkReadBuffer buffer2(dataWritten, bytesWritten);
227     const unsigned char* peekBefore = static_cast<const unsigned char*>(buffer2.skip(0));
228     T* obj2 = nullptr;
229     SerializationUtils<T>::Read(buffer2, &obj2);
230     const unsigned char* peekAfter = static_cast<const unsigned char*>(buffer2.skip(0));
231     if (shouldSucceed) {
232         // This should have succeeded, since there are enough bytes to read this
233         REPORTER_ASSERT(reporter, buffer2.isValid());
234         REPORTER_ASSERT(reporter, static_cast<size_t>(peekAfter - peekBefore) == bytesWritten);
235         REPORTER_ASSERT(reporter, obj2);
236     } else {
237         // If the deserialization was supposed to fail, make sure it did
238         REPORTER_ASSERT(reporter, !buffer.isValid());
239         REPORTER_ASSERT(reporter, nullptr == obj2);
240     }
241 
242     return obj2; // Return object to perform further validity tests on it
243 }
244 
245 template<typename T>
TestArraySerialization(T * data,skiatest::Reporter * reporter)246 static void TestArraySerialization(T* data, skiatest::Reporter* reporter) {
247     SkBinaryWriteBuffer writer;
248     SerializationUtils<T>::Write(writer, data, kArraySize);
249     size_t bytesWritten = writer.bytesWritten();
250     // This should write the length (in 4 bytes) and the array
251     REPORTER_ASSERT(reporter, (4 + kArraySize * sizeof(T)) == bytesWritten);
252 
253     unsigned char dataWritten[2048];
254     writer.writeToMemory(dataWritten);
255 
256     // Make sure this fails when it should
257     SkReadBuffer buffer(dataWritten, bytesWritten);
258     T dataRead[kArraySize];
259     bool success = SerializationUtils<T>::Read(buffer, dataRead, kArraySize / 2);
260     // This should have failed, since the provided size was too small
261     REPORTER_ASSERT(reporter, !success);
262 
263     // Make sure this succeeds when it should
264     SkReadBuffer buffer2(dataWritten, bytesWritten);
265     success = SerializationUtils<T>::Read(buffer2, dataRead, kArraySize);
266     // This should have succeeded, since there are enough bytes to read this
267     REPORTER_ASSERT(reporter, success);
268 }
269 
TestBitmapSerialization(const SkBitmap & validBitmap,const SkBitmap & invalidBitmap,bool shouldSucceed,skiatest::Reporter * reporter)270 static void TestBitmapSerialization(const SkBitmap& validBitmap,
271                                     const SkBitmap& invalidBitmap,
272                                     bool shouldSucceed,
273                                     skiatest::Reporter* reporter) {
274     sk_sp<SkImage> validImage(SkImage::MakeFromBitmap(validBitmap));
275     sk_sp<SkImageFilter> validBitmapSource(SkImageFilters::Image(std::move(validImage)));
276     sk_sp<SkImage> invalidImage(SkImage::MakeFromBitmap(invalidBitmap));
277     sk_sp<SkImageFilter> invalidBitmapSource(SkImageFilters::Image(std::move(invalidImage)));
278     sk_sp<SkImageFilter> xfermodeImageFilter(
279         SkImageFilters::Xfermode(SkBlendMode::kSrcOver,
280                                  std::move(invalidBitmapSource),
281                                  std::move(validBitmapSource), nullptr));
282 
283     sk_sp<SkImageFilter> deserializedFilter(
284         TestFlattenableSerialization<SkImageFilter>(
285             xfermodeImageFilter.get(), shouldSucceed, reporter));
286 
287     // Try to render a small bitmap using the invalid deserialized filter
288     // to make sure we don't crash while trying to render it
289     if (shouldSucceed) {
290         SkBitmap bitmap;
291         bitmap.allocN32Pixels(24, 24);
292         SkCanvas canvas(bitmap);
293         canvas.clear(0x00000000);
294         SkPaint paint;
295         paint.setImageFilter(deserializedFilter);
296         canvas.clipRect(SkRect::MakeXYWH(0, 0, SkIntToScalar(24), SkIntToScalar(24)));
297         canvas.drawBitmap(bitmap, 0, 0, &paint);
298     }
299 }
300 
TestColorFilterSerialization(skiatest::Reporter * reporter)301 static void TestColorFilterSerialization(skiatest::Reporter* reporter) {
302     uint8_t table[256];
303     for (int i = 0; i < 256; ++i) {
304         table[i] = (i * 41) % 256;
305     }
306     auto colorFilter(SkTableColorFilter::Make(table));
307     sk_sp<SkColorFilter> copy(
308         TestFlattenableSerialization<SkColorFilter>(colorFilter.get(), true, reporter));
309 }
310 
draw_picture(SkPicture & picture)311 static SkBitmap draw_picture(SkPicture& picture) {
312      SkBitmap bitmap;
313      bitmap.allocN32Pixels(SkScalarCeilToInt(picture.cullRect().width()),
314                            SkScalarCeilToInt(picture.cullRect().height()));
315      SkCanvas canvas(bitmap);
316      picture.playback(&canvas);
317      return bitmap;
318 }
319 
compare_bitmaps(skiatest::Reporter * reporter,const SkBitmap & b1,const SkBitmap & b2)320 static void compare_bitmaps(skiatest::Reporter* reporter,
321                             const SkBitmap& b1, const SkBitmap& b2) {
322     REPORTER_ASSERT(reporter, b1.width() == b2.width());
323     REPORTER_ASSERT(reporter, b1.height() == b2.height());
324 
325     if ((b1.width() != b2.width()) ||
326         (b1.height() != b2.height())) {
327         return;
328     }
329 
330     int pixelErrors = 0;
331     for (int y = 0; y < b2.height(); ++y) {
332         for (int x = 0; x < b2.width(); ++x) {
333             if (b1.getColor(x, y) != b2.getColor(x, y))
334                 ++pixelErrors;
335         }
336     }
337     REPORTER_ASSERT(reporter, 0 == pixelErrors);
338 }
serialize_and_compare_typeface(sk_sp<SkTypeface> typeface,const char * text,skiatest::Reporter * reporter)339 static void serialize_and_compare_typeface(sk_sp<SkTypeface> typeface, const char* text,
340                                            skiatest::Reporter* reporter)
341 {
342     // Create a font with the typeface.
343     SkPaint paint;
344     paint.setColor(SK_ColorGRAY);
345     SkFont font(std::move(typeface), 30);
346 
347     // Paint some text.
348     SkPictureRecorder recorder;
349     SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
350     SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
351                                                SkIntToScalar(canvasRect.height()),
352                                                nullptr, 0);
353     canvas->drawColor(SK_ColorWHITE);
354     canvas->drawString(text, 24, 32, font, paint);
355     sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
356 
357     // Serlialize picture and create its clone from stream.
358     SkDynamicMemoryWStream stream;
359     picture->serialize(&stream);
360     std::unique_ptr<SkStream> inputStream(stream.detachAsStream());
361     sk_sp<SkPicture> loadedPicture(SkPicture::MakeFromStream(inputStream.get()));
362 
363     // Draw both original and clone picture and compare bitmaps -- they should be identical.
364     SkBitmap origBitmap = draw_picture(*picture);
365     SkBitmap destBitmap = draw_picture(*loadedPicture);
366     compare_bitmaps(reporter, origBitmap, destBitmap);
367 }
368 
TestPictureTypefaceSerialization(skiatest::Reporter * reporter)369 static void TestPictureTypefaceSerialization(skiatest::Reporter* reporter) {
370     {
371         // Load typeface from file to test CreateFromFile with index.
372         auto typeface = MakeResourceAsTypeface("fonts/test.ttc", 1);
373         if (!typeface) {
374             INFOF(reporter, "Could not run fontstream test because test.ttc not found.");
375         } else {
376             serialize_and_compare_typeface(std::move(typeface), "A!", reporter);
377         }
378     }
379 
380     {
381         // Load typeface as stream to create with axis settings.
382         std::unique_ptr<SkStreamAsset> distortable(GetResourceAsStream("fonts/Distortable.ttf"));
383         if (!distortable) {
384             INFOF(reporter, "Could not run fontstream test because Distortable.ttf not found.");
385         } else {
386             SkFixed axis = SK_FixedSqrt2;
387             sk_sp<SkTypeface> typeface(SkTypeface::MakeFromFontData(
388                 std::make_unique<SkFontData>(std::move(distortable), 0, &axis, 1)));
389             if (!typeface) {
390                 INFOF(reporter, "Could not run fontstream test because Distortable.ttf not created.");
391             } else {
392                 serialize_and_compare_typeface(std::move(typeface), "ab", reporter);
393             }
394         }
395     }
396 }
397 
setup_bitmap_for_canvas(SkBitmap * bitmap)398 static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
399     bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
400 }
401 
make_checkerboard_bitmap(SkBitmap & bitmap)402 static void make_checkerboard_bitmap(SkBitmap& bitmap) {
403     setup_bitmap_for_canvas(&bitmap);
404 
405     SkCanvas canvas(bitmap);
406     canvas.clear(0x00000000);
407     SkPaint darkPaint;
408     darkPaint.setColor(0xFF804020);
409     SkPaint lightPaint;
410     lightPaint.setColor(0xFF244484);
411     const int i = kBitmapSize / 8;
412     const SkScalar f = SkIntToScalar(i);
413     for (int y = 0; y < kBitmapSize; y += i) {
414         for (int x = 0; x < kBitmapSize; x += i) {
415             canvas.save();
416             canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
417             canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
418             canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
419             canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
420             canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
421             canvas.restore();
422         }
423     }
424 }
425 
draw_something(SkCanvas * canvas)426 static void draw_something(SkCanvas* canvas) {
427     SkPaint paint;
428     SkBitmap bitmap;
429     make_checkerboard_bitmap(bitmap);
430 
431     canvas->save();
432     canvas->scale(0.5f, 0.5f);
433     canvas->drawBitmap(bitmap, 0, 0, nullptr);
434     canvas->restore();
435 
436     paint.setAntiAlias(true);
437 
438     paint.setColor(SK_ColorRED);
439     canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
440     paint.setColor(SK_ColorBLACK);
441 
442     SkFont font;
443     font.setSize(kBitmapSize/3);
444     canvas->drawString("Picture", SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), font, paint);
445 }
446 
render(const SkPicture & p)447 static sk_sp<SkImage> render(const SkPicture& p) {
448     auto surf = SkSurface::MakeRasterN32Premul(SkScalarRoundToInt(p.cullRect().width()),
449                                                SkScalarRoundToInt(p.cullRect().height()));
450     if (!surf) {
451         return nullptr; // bounds are empty?
452     }
453     surf->getCanvas()->clear(SK_ColorWHITE);
454     p.playback(surf->getCanvas());
455     return surf->makeImageSnapshot();
456 }
457 
DEF_TEST(Serialization,reporter)458 DEF_TEST(Serialization, reporter) {
459     // Test matrix serialization
460     {
461         SkMatrix matrix = SkMatrix::I();
462         TestObjectSerialization(&matrix, reporter);
463     }
464 
465     // Test point3 serialization
466     {
467         SkPoint3 point;
468         TestObjectSerializationNoAlign<SkPoint3, false>(&point, reporter);
469     }
470 
471     // Test path serialization
472     {
473         SkPath path;
474         TestObjectSerialization(&path, reporter);
475     }
476 
477     // Test region serialization
478     {
479         SkRegion region;
480         TestObjectSerialization(&region, reporter);
481     }
482 
483     // Test color filter serialization
484     {
485         TestColorFilterSerialization(reporter);
486     }
487 
488     // Test string serialization
489     {
490         SkString string("string");
491         TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
492         TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
493     }
494 
495     // Test rrect serialization
496     {
497         // SkRRect does not initialize anything.
498         // An uninitialized SkRRect can be serialized,
499         // but will branch on uninitialized data when deserialized.
500         SkRRect rrect;
501         SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
502         SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
503         rrect.setRectRadii(rect, corners);
504         SerializationTest::TestAlignment(&rrect, reporter);
505     }
506 
507     // Test readByteArray
508     {
509         unsigned char data[kArraySize] = { 1, 2, 3 };
510         TestArraySerialization(data, reporter);
511     }
512 
513     // Test readColorArray
514     {
515         SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
516         TestArraySerialization(data, reporter);
517     }
518 
519     // Test readColor4fArray
520     {
521         SkColor4f data[kArraySize] = {
522             SkColor4f::FromColor(SK_ColorBLACK),
523             SkColor4f::FromColor(SK_ColorWHITE),
524             SkColor4f::FromColor(SK_ColorRED),
525             { 1.f, 2.f, 4.f, 8.f }
526         };
527         TestArraySerialization(data, reporter);
528     }
529 
530     // Test readIntArray
531     {
532         int32_t data[kArraySize] = { 1, 2, 4, 8 };
533         TestArraySerialization(data, reporter);
534     }
535 
536     // Test readPointArray
537     {
538         SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
539         TestArraySerialization(data, reporter);
540     }
541 
542     // Test readScalarArray
543     {
544         SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
545         TestArraySerialization(data, reporter);
546     }
547 
548     // Test invalid deserializations
549     {
550         SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
551 
552         SkBitmap validBitmap;
553         validBitmap.setInfo(info);
554 
555         // Create a bitmap with a really large height
556         SkBitmap invalidBitmap;
557         invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
558 
559         // The deserialization should succeed, and the rendering shouldn't crash,
560         // even when the device fails to initialize, due to its size
561         TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
562     }
563 
564     // Test simple SkPicture serialization
565     {
566         SkPictureRecorder recorder;
567         draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
568                                                SkIntToScalar(kBitmapSize),
569                                                nullptr, 0));
570         sk_sp<SkPicture> pict(recorder.finishRecordingAsPicture());
571 
572         // Serialize picture
573         SkBinaryWriteBuffer writer;
574         SkPicturePriv::Flatten(pict, writer);
575         size_t size = writer.bytesWritten();
576         SkAutoTMalloc<unsigned char> data(size);
577         writer.writeToMemory(static_cast<void*>(data.get()));
578 
579         // Deserialize picture
580         SkReadBuffer reader(static_cast<void*>(data.get()), size);
581         sk_sp<SkPicture> readPict(SkPicturePriv::MakeFromBuffer(reader));
582         REPORTER_ASSERT(reporter, reader.isValid());
583         REPORTER_ASSERT(reporter, readPict.get());
584         sk_sp<SkImage> img0 = render(*pict);
585         sk_sp<SkImage> img1 = render(*readPict);
586         if (img0 && img1) {
587             REPORTER_ASSERT(reporter, ToolUtils::equal_pixels(img0.get(), img1.get()));
588         }
589     }
590 
591     TestPictureTypefaceSerialization(reporter);
592 
593     // Test SkLightingShader/NormalMapSource serialization
594     {
595         const int kTexSize = 2;
596 
597         SkLights::Builder builder;
598 
599         builder.add(SkLights::Light::MakeDirectional(SkColor3f::Make(1.0f, 1.0f, 1.0f),
600                                                      SkVector3::Make(1.0f, 0.0f, 0.0f)));
601         builder.setAmbientLightColor(SkColor3f::Make(0.2f, 0.2f, 0.2f));
602 
603         sk_sp<SkLights> fLights = builder.finish();
604 
605         SkBitmap diffuse = ToolUtils::create_checkerboard_bitmap(
606                 kTexSize, kTexSize, 0x00000000, ToolUtils::color_to_565(0xFF804020), 8);
607 
608         SkRect bitmapBounds = SkRect::MakeIWH(diffuse.width(), diffuse.height());
609 
610         SkMatrix matrix;
611         SkRect r = SkRect::MakeWH(SkIntToScalar(kTexSize), SkIntToScalar(kTexSize));
612         matrix.setRectToRect(bitmapBounds, r, SkMatrix::kFill_ScaleToFit);
613 
614         SkMatrix ctm;
615         ctm.setRotate(45);
616         SkBitmap normals;
617         normals.allocN32Pixels(kTexSize, kTexSize);
618 
619         ToolUtils::create_frustum_normal_map(&normals, SkIRect::MakeWH(kTexSize, kTexSize));
620         sk_sp<SkShader> normalMap = normals.makeShader(&matrix);
621         sk_sp<SkNormalSource> normalSource = SkNormalSource::MakeFromNormalMap(std::move(normalMap),
622                                                                                ctm);
623         sk_sp<SkShader> diffuseShader = diffuse.makeShader(&matrix);
624 
625         sk_sp<SkShader> lightingShader = SkLightingShader::Make(diffuseShader,
626                                                                 normalSource,
627                                                                 fLights);
628         sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
629 
630         lightingShader = SkLightingShader::Make(std::move(diffuseShader),
631                                                 nullptr,
632                                                 fLights);
633         sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
634 
635         lightingShader = SkLightingShader::Make(nullptr,
636                                                 std::move(normalSource),
637                                                 fLights);
638         sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
639 
640         lightingShader = SkLightingShader::Make(nullptr,
641                                                 nullptr,
642                                                 fLights);
643         sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
644     }
645 }
646 
647 ///////////////////////////////////////////////////////////////////////////////////////////////////
648 #include "include/core/SkAnnotation.h"
649 
copy_picture_via_serialization(SkPicture * src)650 static sk_sp<SkPicture> copy_picture_via_serialization(SkPicture* src) {
651     SkDynamicMemoryWStream wstream;
652     src->serialize(&wstream);
653     std::unique_ptr<SkStreamAsset> rstream(wstream.detachAsStream());
654     return SkPicture::MakeFromStream(rstream.get());
655 }
656 
657 struct AnnotationRec {
658     const SkRect    fRect;
659     const char*     fKey;
660     sk_sp<SkData>   fValue;
661 };
662 
663 class TestAnnotationCanvas : public SkCanvas {
664     skiatest::Reporter*     fReporter;
665     const AnnotationRec*    fRec;
666     int                     fCount;
667     int                     fCurrIndex;
668 
669 public:
TestAnnotationCanvas(skiatest::Reporter * reporter,const AnnotationRec rec[],int count)670     TestAnnotationCanvas(skiatest::Reporter* reporter, const AnnotationRec rec[], int count)
671         : SkCanvas(100, 100)
672         , fReporter(reporter)
673         , fRec(rec)
674         , fCount(count)
675         , fCurrIndex(0)
676     {}
677 
~TestAnnotationCanvas()678     ~TestAnnotationCanvas() {
679         REPORTER_ASSERT(fReporter, fCount == fCurrIndex);
680     }
681 
682 protected:
onDrawAnnotation(const SkRect & rect,const char key[],SkData * value)683     void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) {
684         REPORTER_ASSERT(fReporter, fCurrIndex < fCount);
685         REPORTER_ASSERT(fReporter, rect == fRec[fCurrIndex].fRect);
686         REPORTER_ASSERT(fReporter, !strcmp(key, fRec[fCurrIndex].fKey));
687         REPORTER_ASSERT(fReporter, value->equals(fRec[fCurrIndex].fValue.get()));
688         fCurrIndex += 1;
689     }
690 };
691 
692 /*
693  *  Test the 3 annotation types by recording them into a picture, serializing, and then playing
694  *  them back into another canvas.
695  */
DEF_TEST(Annotations,reporter)696 DEF_TEST(Annotations, reporter) {
697     SkPictureRecorder recorder;
698     SkCanvas* recordingCanvas = recorder.beginRecording(SkRect::MakeWH(100, 100));
699 
700     const char* str0 = "rect-with-url";
701     const SkRect r0 = SkRect::MakeWH(10, 10);
702     sk_sp<SkData> d0(SkData::MakeWithCString(str0));
703     SkAnnotateRectWithURL(recordingCanvas, r0, d0.get());
704 
705     const char* str1 = "named-destination";
706     const SkRect r1 = SkRect::MakeXYWH(5, 5, 0, 0); // collapsed to a point
707     sk_sp<SkData> d1(SkData::MakeWithCString(str1));
708     SkAnnotateNamedDestination(recordingCanvas, {r1.x(), r1.y()}, d1.get());
709 
710     const char* str2 = "link-to-destination";
711     const SkRect r2 = SkRect::MakeXYWH(20, 20, 5, 6);
712     sk_sp<SkData> d2(SkData::MakeWithCString(str2));
713     SkAnnotateLinkToDestination(recordingCanvas, r2, d2.get());
714 
715     const AnnotationRec recs[] = {
716         { r0, SkAnnotationKeys::URL_Key(),                  std::move(d0) },
717         { r1, SkAnnotationKeys::Define_Named_Dest_Key(),    std::move(d1) },
718         { r2, SkAnnotationKeys::Link_Named_Dest_Key(),      std::move(d2) },
719     };
720 
721     sk_sp<SkPicture> pict0(recorder.finishRecordingAsPicture());
722     sk_sp<SkPicture> pict1(copy_picture_via_serialization(pict0.get()));
723 
724     TestAnnotationCanvas canvas(reporter, recs, SK_ARRAY_COUNT(recs));
725     canvas.drawPicture(pict1);
726 }
727 
DEF_TEST(WriteBuffer_storage,reporter)728 DEF_TEST(WriteBuffer_storage, reporter) {
729     enum {
730         kSize = 32
731     };
732     int32_t storage[kSize/4];
733     char src[kSize];
734     sk_bzero(src, kSize);
735 
736     SkBinaryWriteBuffer writer(storage, kSize);
737     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
738     REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
739     writer.write(src, kSize - 4);
740     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
741     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
742     writer.writeInt(0);
743     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
744     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
745 
746     writer.reset(storage, kSize-4);
747     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
748     REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
749     writer.write(src, kSize - 4);
750     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
751     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
752     writer.writeInt(0);
753     REPORTER_ASSERT(reporter, !writer.usingInitialStorage());   // this is the change
754     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
755 }
756 
DEF_TEST(WriteBuffer_external_memory_textblob,reporter)757 DEF_TEST(WriteBuffer_external_memory_textblob, reporter) {
758     SkFont font;
759     font.setTypeface(SkTypeface::MakeDefault());
760 
761     SkTextBlobBuilder builder;
762     int glyph_count = 5;
763     const auto& run = builder.allocRun(font, glyph_count, 1.2f, 2.3f);
764     // allocRun() allocates only the glyph buffer.
765     std::fill(run.glyphs, run.glyphs + glyph_count, 0);
766     auto blob = builder.make();
767     SkSerialProcs procs;
768     SkAutoTMalloc<uint8_t> storage;
769     size_t blob_size = 0u;
770     size_t storage_size = 0u;
771 
772     blob_size = SkAlign4(blob->serialize(procs)->size());
773     REPORTER_ASSERT(reporter, blob_size > 4u);
774     storage_size = blob_size - 4;
775     storage.realloc(storage_size);
776     REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) == 0u);
777     storage_size = blob_size;
778     storage.realloc(storage_size);
779     REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) != 0u);
780 }
781 
DEF_TEST(WriteBuffer_external_memory_flattenable,reporter)782 DEF_TEST(WriteBuffer_external_memory_flattenable, reporter) {
783     SkScalar intervals[] = {1.f, 1.f};
784     auto path_effect = SkDashPathEffect::Make(intervals, 2, 0);
785     size_t path_size = SkAlign4(path_effect->serialize()->size());
786     REPORTER_ASSERT(reporter, path_size > 4u);
787     SkAutoTMalloc<uint8_t> storage;
788 
789     size_t storage_size = path_size - 4;
790     storage.realloc(storage_size);
791     REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) == 0u);
792 
793     storage_size = path_size;
794     storage.realloc(storage_size);
795     REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) != 0u);
796 }
797 
798 #include "src/core/SkAutoMalloc.h"
799 
DEF_TEST(ReadBuffer_empty,reporter)800 DEF_TEST(ReadBuffer_empty, reporter) {
801     SkBinaryWriteBuffer writer;
802     writer.writeInt(123);
803     writer.writeDataAsByteArray(SkData::MakeEmpty().get());
804     writer.writeInt(321);
805 
806     size_t size = writer.bytesWritten();
807     SkAutoMalloc storage(size);
808     writer.writeToMemory(storage.get());
809 
810     SkReadBuffer reader(storage.get(), size);
811     REPORTER_ASSERT(reporter, reader.readInt() == 123);
812     auto data = reader.readByteArrayAsData();
813     REPORTER_ASSERT(reporter, data->size() == 0);
814     REPORTER_ASSERT(reporter, reader.readInt() == 321);
815 }
816