Update rive-cpp to 2.0 version
[platform/core/uifw/rive-tizen.git] / submodule / skia / tests / SerializationTest.cpp
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/SkFontMetrics.h"
10 #include "include/core/SkFontMgr.h"
11 #include "include/core/SkImage.h"
12 #include "include/core/SkMallocPixelRef.h"
13 #include "include/core/SkPictureRecorder.h"
14 #include "include/core/SkTextBlob.h"
15 #include "include/core/SkTypeface.h"
16 #include "include/effects/SkDashPathEffect.h"
17 #include "include/effects/SkImageFilters.h"
18 #include "include/effects/SkTableColorFilter.h"
19 #include "include/private/SkFixed.h"
20 #include "include/private/SkTemplates.h"
21 #include "src/core/SkAnnotationKeys.h"
22 #include "src/core/SkAutoMalloc.h"
23 #include "src/core/SkMatrixPriv.h"
24 #include "src/core/SkOSFile.h"
25 #include "src/core/SkPicturePriv.h"
26 #include "src/core/SkReadBuffer.h"
27 #include "src/core/SkWriteBuffer.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>
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
52     static void Write(SkWriteBuffer& writer, const T* flattenable) {
53         writer.writeFlattenable(flattenable);
54     }
55     static void Read(SkReadBuffer& reader, T** flattenable) {
56         *flattenable = (T*)reader.readFlattenable(T::GetFlattenableType());
57     }
58 };
59
60 template<> struct SerializationUtils<SkMatrix> {
61     static void Write(SkWriteBuffer& writer, const SkMatrix* matrix) {
62         writer.writeMatrix(*matrix);
63     }
64     static void Read(SkReadBuffer& reader, SkMatrix* matrix) {
65         reader.readMatrix(matrix);
66     }
67 };
68
69 template<> struct SerializationUtils<SkPath> {
70     static void Write(SkWriteBuffer& writer, const SkPath* path) {
71         writer.writePath(*path);
72     }
73     static void Read(SkReadBuffer& reader, SkPath* path) {
74         reader.readPath(path);
75     }
76 };
77
78 template<> struct SerializationUtils<SkRegion> {
79     static void Write(SkWriteBuffer& writer, const SkRegion* region) {
80         writer.writeRegion(*region);
81     }
82     static void Read(SkReadBuffer& reader, SkRegion* region) {
83         reader.readRegion(region);
84     }
85 };
86
87 template<> struct SerializationUtils<SkString> {
88     static void Write(SkWriteBuffer& writer, const SkString* string) {
89         writer.writeString(string->c_str());
90     }
91     static void Read(SkReadBuffer& reader, SkString* string) {
92         reader.readString(string);
93     }
94 };
95
96 template<> struct SerializationUtils<unsigned char> {
97     static void Write(SkWriteBuffer& writer, unsigned char* data, uint32_t arraySize) {
98         writer.writeByteArray(data, arraySize);
99     }
100     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> {
106     static void Write(SkWriteBuffer& writer, SkColor* data, uint32_t arraySize) {
107         writer.writeColorArray(data, arraySize);
108     }
109     static bool Read(SkReadBuffer& reader, SkColor* data, uint32_t arraySize) {
110         return reader.readColorArray(data, arraySize);
111     }
112 };
113
114 template<> struct SerializationUtils<SkColor4f> {
115     static void Write(SkWriteBuffer& writer, SkColor4f* data, uint32_t arraySize) {
116         writer.writeColor4fArray(data, arraySize);
117     }
118     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> {
124     static void Write(SkWriteBuffer& writer, int32_t* data, uint32_t arraySize) {
125         writer.writeIntArray(data, arraySize);
126     }
127     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> {
133     static void Write(SkWriteBuffer& writer, SkPoint* data, uint32_t arraySize) {
134         writer.writePointArray(data, arraySize);
135     }
136     static bool Read(SkReadBuffer& reader, SkPoint* data, uint32_t arraySize) {
137         return reader.readPointArray(data, arraySize);
138     }
139 };
140
141 template<> struct SerializationUtils<SkPoint3> {
142     static void Write(SkWriteBuffer& writer, const SkPoint3* data) {
143         writer.writePoint3(*data);
144     }
145     static void Read(SkReadBuffer& reader, SkPoint3* data) {
146         reader.readPoint3(data);
147     }
148 };
149
150 template<> struct SerializationUtils<SkScalar> {
151     static void Write(SkWriteBuffer& writer, SkScalar* data, uint32_t arraySize) {
152         writer.writeScalarArray(data, arraySize);
153     }
154     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 {
160     static void InvalidateData(unsigned char* data) {}
161 };
162
163 template<> struct SerializationTestUtils<SkString, true> {
164     static void InvalidateData(unsigned char* data) {
165         data[3] |= 0x80; // Reverse sign of 1st integer
166     }
167 };
168
169 template<typename T, bool testInvalid>
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>
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>
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>
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
270 static void TestBitmapSerialization(const SkBitmap& validBitmap,
271                                     const SkBitmap& invalidBitmap,
272                                     bool shouldSucceed,
273                                     skiatest::Reporter* reporter) {
274     sk_sp<SkImage> validImage(validBitmap.asImage());
275     sk_sp<SkImageFilter> validBitmapSource(SkImageFilters::Image(std::move(validImage)));
276     sk_sp<SkImage> invalidImage(invalidBitmap.asImage());
277     sk_sp<SkImageFilter> invalidBitmapSource(SkImageFilters::Image(std::move(invalidImage)));
278     sk_sp<SkImageFilter> xfermodeImageFilter(
279         SkImageFilters::Blend(SkBlendMode::kSrcOver,
280                               std::move(invalidBitmapSource),
281                               std::move(validBitmapSource), nullptr));
282
283     sk_sp<SkImageFilter> deserializedFilter(
284         TestFlattenableSerialization<SkImageFilter_Base>(
285             (SkImageFilter_Base*)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.drawImage(bitmap.asImage(), 0, 0, SkSamplingOptions(), &paint);
298     }
299 }
300
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 filter = SkTableColorFilter::Make(table);
307     sk_sp<SkColorFilter> copy(
308         TestFlattenableSerialization(as_CFB(filter.get()), true, reporter));
309 }
310
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
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 }
339
340 static sk_sp<SkData> serialize_typeface_proc(SkTypeface* typeface, void* ctx) {
341     // Write out typeface ID followed by entire typeface.
342     SkDynamicMemoryWStream stream;
343     sk_sp<SkData> data(typeface->serialize(SkTypeface::SerializeBehavior::kDoIncludeData));
344     uint32_t typeface_id = typeface->uniqueID();
345     stream.write(&typeface_id, sizeof(typeface_id));
346     stream.write(data->data(), data->size());
347     return stream.detachAsData();
348 }
349
350 static sk_sp<SkTypeface> deserialize_typeface_proc(const void* data, size_t length, void* ctx) {
351     SkStream* stream;
352     if (length < sizeof(stream)) {
353         return nullptr;
354     }
355     memcpy(&stream, data, sizeof(stream));
356
357     SkTypefaceID id;
358     if (!stream->read(&id, sizeof(id))) {
359         return nullptr;
360     }
361
362     sk_sp<SkTypeface> typeface = SkTypeface::MakeDeserialize(stream);
363     return typeface;
364 }
365
366 static void serialize_and_compare_typeface(sk_sp<SkTypeface> typeface,
367                                            const char* text,
368                                            const SkSerialProcs* serial_procs,
369                                            const SkDeserialProcs* deserial_procs,
370                                            skiatest::Reporter* reporter) {
371     // Create a font with the typeface.
372     SkPaint paint;
373     paint.setColor(SK_ColorGRAY);
374     SkFont font(std::move(typeface), 30);
375
376     // Paint some text.
377     SkPictureRecorder recorder;
378     SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
379     SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
380                                                SkIntToScalar(canvasRect.height()));
381     canvas->drawColor(SK_ColorWHITE);
382     canvas->drawString(text, 24, 32, font, paint);
383     sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
384
385     // Serlialize picture and create its clone from stream.
386     SkDynamicMemoryWStream stream;
387     picture->serialize(&stream, serial_procs);
388     std::unique_ptr<SkStream> inputStream(stream.detachAsStream());
389     sk_sp<SkPicture> loadedPicture(SkPicture::MakeFromStream(inputStream.get(), deserial_procs));
390
391     // Draw both original and clone picture and compare bitmaps -- they should be identical.
392     SkBitmap origBitmap = draw_picture(*picture);
393     SkBitmap destBitmap = draw_picture(*loadedPicture);
394     compare_bitmaps(reporter, origBitmap, destBitmap);
395 }
396
397 static sk_sp<SkTypeface> makeDistortableWithNonDefaultAxes(skiatest::Reporter* reporter) {
398     std::unique_ptr<SkStreamAsset> distortable(GetResourceAsStream("fonts/Distortable.ttf"));
399     if (!distortable) {
400         REPORT_FAILURE(reporter, "distortable", SkString());
401         return nullptr;
402     }
403
404     const SkFontArguments::VariationPosition::Coordinate position[] = {
405         { SkSetFourByteTag('w','g','h','t'), SK_ScalarSqrt2 },
406     };
407     SkFontArguments params;
408     params.setVariationDesignPosition({position, SK_ARRAY_COUNT(position)});
409
410     sk_sp<SkFontMgr> fm = SkFontMgr::RefDefault();
411
412     sk_sp<SkTypeface> typeface = fm->makeFromStream(std::move(distortable), params);
413     if (!typeface) {
414         return nullptr;  // Not all SkFontMgr can makeFromStream().
415     }
416
417     int count = typeface->getVariationDesignPosition(nullptr, 0);
418     if (count == -1) {
419         return nullptr;  // The number of axes is unknown.
420     }
421
422     return typeface;
423 }
424
425 static void TestPictureTypefaceSerialization(const SkSerialProcs* serial_procs,
426                                              const SkDeserialProcs* deserial_procs,
427                                              skiatest::Reporter* reporter) {
428     {
429         // Load typeface from file to test CreateFromFile with index.
430         auto typeface = MakeResourceAsTypeface("fonts/test.ttc", 1);
431         if (!typeface) {
432             INFOF(reporter, "Could not run fontstream test because test.ttc not found.");
433         } else {
434             serialize_and_compare_typeface(std::move(typeface), "A!", serial_procs, deserial_procs,
435                                            reporter);
436         }
437     }
438
439     {
440         // Load typeface as stream to create with axis settings.
441         auto typeface = makeDistortableWithNonDefaultAxes(reporter);
442         if (!typeface) {
443             INFOF(reporter, "Could not run fontstream test because Distortable.ttf not created.");
444         } else {
445             serialize_and_compare_typeface(std::move(typeface), "ab", serial_procs,
446                                             deserial_procs, reporter);
447         }
448     }
449 }
450
451 static void TestTypefaceSerialization(skiatest::Reporter* reporter, sk_sp<SkTypeface> typeface) {
452     SkDynamicMemoryWStream typefaceWStream;
453     typeface->serialize(&typefaceWStream);
454
455     std::unique_ptr<SkStream> typefaceStream = typefaceWStream.detachAsStream();
456     sk_sp<SkTypeface> cloneTypeface = SkTypeface::MakeDeserialize(typefaceStream.get());
457     SkASSERT(cloneTypeface);
458
459     SkString name, cloneName;
460     typeface->getFamilyName(&name);
461     cloneTypeface->getFamilyName(&cloneName);
462
463     REPORTER_ASSERT(reporter, typeface->countGlyphs() == cloneTypeface->countGlyphs(),
464         "Typeface: \"%s\" CloneTypeface: \"%s\"", name.c_str(), cloneName.c_str());
465     REPORTER_ASSERT(reporter, typeface->fontStyle() == cloneTypeface->fontStyle(),
466         "Typeface: \"%s\" CloneTypeface: \"%s\"", name.c_str(), cloneName.c_str());
467
468     SkFont font(typeface, 12);
469     SkFont clone(cloneTypeface, 12);
470     SkFontMetrics fontMetrics, cloneMetrics;
471     font.getMetrics(&fontMetrics);
472     clone.getMetrics(&cloneMetrics);
473     REPORTER_ASSERT(reporter, fontMetrics == cloneMetrics,
474         "Typeface: \"%s\" CloneTypeface: \"%s\"", name.c_str(), cloneName.c_str());
475 }
476 DEF_TEST(Serialization_Typeface, reporter) {
477     SkFont font;
478     TestTypefaceSerialization(reporter, font.refTypefaceOrDefault());
479     TestTypefaceSerialization(reporter, ToolUtils::sample_user_typeface());
480 }
481
482 static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
483     bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
484 }
485
486 static sk_sp<SkImage> make_checkerboard_image() {
487     SkBitmap bitmap;
488     setup_bitmap_for_canvas(&bitmap);
489
490     SkCanvas canvas(bitmap);
491     canvas.clear(0x00000000);
492     SkPaint darkPaint;
493     darkPaint.setColor(0xFF804020);
494     SkPaint lightPaint;
495     lightPaint.setColor(0xFF244484);
496     const int i = kBitmapSize / 8;
497     const SkScalar f = SkIntToScalar(i);
498     for (int y = 0; y < kBitmapSize; y += i) {
499         for (int x = 0; x < kBitmapSize; x += i) {
500             canvas.save();
501             canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
502             canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
503             canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
504             canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
505             canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
506             canvas.restore();
507         }
508     }
509     return bitmap.asImage();
510 }
511
512 static void draw_something(SkCanvas* canvas) {
513     canvas->save();
514     canvas->scale(0.5f, 0.5f);
515     canvas->drawImage(make_checkerboard_image(), 0, 0);
516     canvas->restore();
517
518     SkPaint paint;
519     paint.setAntiAlias(true);
520     paint.setColor(SK_ColorRED);
521     canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
522     paint.setColor(SK_ColorBLACK);
523
524     SkFont font;
525     font.setSize(kBitmapSize/3);
526     canvas->drawString("Picture", SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), font, paint);
527 }
528
529 static sk_sp<SkImage> render(const SkPicture& p) {
530     auto surf = SkSurface::MakeRasterN32Premul(SkScalarRoundToInt(p.cullRect().width()),
531                                                SkScalarRoundToInt(p.cullRect().height()));
532     if (!surf) {
533         return nullptr; // bounds are empty?
534     }
535     surf->getCanvas()->clear(SK_ColorWHITE);
536     p.playback(surf->getCanvas());
537     return surf->makeImageSnapshot();
538 }
539
540 DEF_TEST(Serialization, reporter) {
541     // Test matrix serialization
542     {
543         SkMatrix matrix = SkMatrix::I();
544         TestObjectSerialization(&matrix, reporter);
545     }
546
547     // Test point3 serialization
548     {
549         SkPoint3 point;
550         TestObjectSerializationNoAlign<SkPoint3, false>(&point, reporter);
551     }
552
553     // Test path serialization
554     {
555         SkPath path;
556         TestObjectSerialization(&path, reporter);
557     }
558
559     // Test region serialization
560     {
561         SkRegion region;
562         TestObjectSerialization(&region, reporter);
563     }
564
565     // Test color filter serialization
566     {
567         TestColorFilterSerialization(reporter);
568     }
569
570     // Test string serialization
571     {
572         SkString string("string");
573         TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
574         TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
575     }
576
577     // Test rrect serialization
578     {
579         // SkRRect does not initialize anything.
580         // An uninitialized SkRRect can be serialized,
581         // but will branch on uninitialized data when deserialized.
582         SkRRect rrect;
583         SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
584         SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
585         rrect.setRectRadii(rect, corners);
586         SerializationTest::TestAlignment(&rrect, reporter);
587     }
588
589     // Test readByteArray
590     {
591         unsigned char data[kArraySize] = { 1, 2, 3 };
592         TestArraySerialization(data, reporter);
593     }
594
595     // Test readColorArray
596     {
597         SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
598         TestArraySerialization(data, reporter);
599     }
600
601     // Test readColor4fArray
602     {
603         SkColor4f data[kArraySize] = {
604             SkColor4f::FromColor(SK_ColorBLACK),
605             SkColor4f::FromColor(SK_ColorWHITE),
606             SkColor4f::FromColor(SK_ColorRED),
607             { 1.f, 2.f, 4.f, 8.f }
608         };
609         TestArraySerialization(data, reporter);
610     }
611
612     // Test readIntArray
613     {
614         int32_t data[kArraySize] = { 1, 2, 4, 8 };
615         TestArraySerialization(data, reporter);
616     }
617
618     // Test readPointArray
619     {
620         SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
621         TestArraySerialization(data, reporter);
622     }
623
624     // Test readScalarArray
625     {
626         SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
627         TestArraySerialization(data, reporter);
628     }
629
630     // Test skipByteArray
631     {
632         // Valid case with non-empty array:
633         {
634             unsigned char data[kArraySize] = { 1, 2, 3 };
635             SkBinaryWriteBuffer writer;
636             writer.writeByteArray(data, kArraySize);
637             SkAutoMalloc buf(writer.bytesWritten());
638             writer.writeToMemory(buf.get());
639
640             SkReadBuffer reader(buf.get(), writer.bytesWritten());
641             size_t len = ~0;
642             const void* arr = reader.skipByteArray(&len);
643             REPORTER_ASSERT(reporter, arr);
644             REPORTER_ASSERT(reporter, len == kArraySize);
645             REPORTER_ASSERT(reporter, memcmp(arr, data, len) == 0);
646         }
647
648         // Writing a zero length array (can be detected as valid by non-nullptr return):
649         {
650             SkBinaryWriteBuffer writer;
651             writer.writeByteArray(nullptr, 0);
652             SkAutoMalloc buf(writer.bytesWritten());
653             writer.writeToMemory(buf.get());
654
655             SkReadBuffer reader(buf.get(), writer.bytesWritten());
656             size_t len = ~0;
657             const void* arr = reader.skipByteArray(&len);
658             REPORTER_ASSERT(reporter, arr);
659             REPORTER_ASSERT(reporter, len == 0);
660         }
661
662         // If the array can't be safely read, should return nullptr:
663         {
664             SkBinaryWriteBuffer writer;
665             writer.writeUInt(kArraySize);
666             SkAutoMalloc buf(writer.bytesWritten());
667             writer.writeToMemory(buf.get());
668
669             SkReadBuffer reader(buf.get(), writer.bytesWritten());
670             size_t len = ~0;
671             const void* arr = reader.skipByteArray(&len);
672             REPORTER_ASSERT(reporter, !arr);
673             REPORTER_ASSERT(reporter, len == 0);
674         }
675     }
676
677     // Test invalid deserializations
678     {
679         SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
680
681         SkBitmap validBitmap;
682         validBitmap.setInfo(info);
683
684         // Create a bitmap with a really large height
685         SkBitmap invalidBitmap;
686         invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
687
688         // The deserialization should succeed, and the rendering shouldn't crash,
689         // even when the device fails to initialize, due to its size
690         TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
691     }
692
693     // Test simple SkPicture serialization
694     {
695         SkPictureRecorder recorder;
696         draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
697                                                SkIntToScalar(kBitmapSize)));
698         sk_sp<SkPicture> pict(recorder.finishRecordingAsPicture());
699
700         // Serialize picture
701         SkBinaryWriteBuffer writer;
702         SkPicturePriv::Flatten(pict, writer);
703         size_t size = writer.bytesWritten();
704         SkAutoTMalloc<unsigned char> data(size);
705         writer.writeToMemory(static_cast<void*>(data.get()));
706
707         // Deserialize picture
708         SkReadBuffer reader(static_cast<void*>(data.get()), size);
709         sk_sp<SkPicture> readPict(SkPicturePriv::MakeFromBuffer(reader));
710         REPORTER_ASSERT(reporter, reader.isValid());
711         REPORTER_ASSERT(reporter, readPict.get());
712         sk_sp<SkImage> img0 = render(*pict);
713         sk_sp<SkImage> img1 = render(*readPict);
714         if (img0 && img1) {
715             REPORTER_ASSERT(reporter, ToolUtils::equal_pixels(img0.get(), img1.get()));
716         }
717     }
718
719     TestPictureTypefaceSerialization(nullptr, nullptr, reporter);
720
721     SkSerialProcs serial_procs;
722     serial_procs.fTypefaceProc = serialize_typeface_proc;
723     SkDeserialProcs deserial_procs;
724     deserial_procs.fTypefaceProc = deserialize_typeface_proc;
725     TestPictureTypefaceSerialization(&serial_procs, &deserial_procs, reporter);
726 }
727
728 ///////////////////////////////////////////////////////////////////////////////////////////////////
729 #include "include/core/SkAnnotation.h"
730
731 static sk_sp<SkPicture> copy_picture_via_serialization(SkPicture* src) {
732     SkDynamicMemoryWStream wstream;
733     src->serialize(&wstream);
734     std::unique_ptr<SkStreamAsset> rstream(wstream.detachAsStream());
735     return SkPicture::MakeFromStream(rstream.get());
736 }
737
738 struct AnnotationRec {
739     const SkRect    fRect;
740     const char*     fKey;
741     sk_sp<SkData>   fValue;
742 };
743
744 class TestAnnotationCanvas : public SkCanvas {
745     skiatest::Reporter*     fReporter;
746     const AnnotationRec*    fRec;
747     int                     fCount;
748     int                     fCurrIndex;
749
750 public:
751     TestAnnotationCanvas(skiatest::Reporter* reporter, const AnnotationRec rec[], int count)
752         : SkCanvas(100, 100)
753         , fReporter(reporter)
754         , fRec(rec)
755         , fCount(count)
756         , fCurrIndex(0)
757     {}
758
759     ~TestAnnotationCanvas() override {
760         REPORTER_ASSERT(fReporter, fCount == fCurrIndex);
761     }
762
763 protected:
764     void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) override {
765         REPORTER_ASSERT(fReporter, fCurrIndex < fCount);
766         REPORTER_ASSERT(fReporter, rect == fRec[fCurrIndex].fRect);
767         REPORTER_ASSERT(fReporter, !strcmp(key, fRec[fCurrIndex].fKey));
768         REPORTER_ASSERT(fReporter, value->equals(fRec[fCurrIndex].fValue.get()));
769         fCurrIndex += 1;
770     }
771 };
772
773 /*
774  *  Test the 3 annotation types by recording them into a picture, serializing, and then playing
775  *  them back into another canvas.
776  */
777 DEF_TEST(Annotations, reporter) {
778     SkPictureRecorder recorder;
779     SkCanvas* recordingCanvas = recorder.beginRecording(SkRect::MakeWH(100, 100));
780
781     const char* str0 = "rect-with-url";
782     const SkRect r0 = SkRect::MakeWH(10, 10);
783     sk_sp<SkData> d0(SkData::MakeWithCString(str0));
784     SkAnnotateRectWithURL(recordingCanvas, r0, d0.get());
785
786     const char* str1 = "named-destination";
787     const SkRect r1 = SkRect::MakeXYWH(5, 5, 0, 0); // collapsed to a point
788     sk_sp<SkData> d1(SkData::MakeWithCString(str1));
789     SkAnnotateNamedDestination(recordingCanvas, {r1.x(), r1.y()}, d1.get());
790
791     const char* str2 = "link-to-destination";
792     const SkRect r2 = SkRect::MakeXYWH(20, 20, 5, 6);
793     sk_sp<SkData> d2(SkData::MakeWithCString(str2));
794     SkAnnotateLinkToDestination(recordingCanvas, r2, d2.get());
795
796     const AnnotationRec recs[] = {
797         { r0, SkAnnotationKeys::URL_Key(),                  std::move(d0) },
798         { r1, SkAnnotationKeys::Define_Named_Dest_Key(),    std::move(d1) },
799         { r2, SkAnnotationKeys::Link_Named_Dest_Key(),      std::move(d2) },
800     };
801
802     sk_sp<SkPicture> pict0(recorder.finishRecordingAsPicture());
803     sk_sp<SkPicture> pict1(copy_picture_via_serialization(pict0.get()));
804
805     TestAnnotationCanvas canvas(reporter, recs, SK_ARRAY_COUNT(recs));
806     canvas.drawPicture(pict1);
807 }
808
809 DEF_TEST(WriteBuffer_storage, reporter) {
810     enum {
811         kSize = 32
812     };
813     int32_t storage[kSize/4];
814     char src[kSize];
815     sk_bzero(src, kSize);
816
817     SkBinaryWriteBuffer writer(storage, kSize);
818     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
819     REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
820     writer.write(src, kSize - 4);
821     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
822     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
823     writer.writeInt(0);
824     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
825     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
826
827     writer.reset(storage, kSize-4);
828     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
829     REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
830     writer.write(src, kSize - 4);
831     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
832     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
833     writer.writeInt(0);
834     REPORTER_ASSERT(reporter, !writer.usingInitialStorage());   // this is the change
835     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
836 }
837
838 DEF_TEST(WriteBuffer_external_memory_textblob, reporter) {
839     SkFont font;
840     font.setTypeface(SkTypeface::MakeDefault());
841
842     SkTextBlobBuilder builder;
843     int glyph_count = 5;
844     const auto& run = builder.allocRun(font, glyph_count, 1.2f, 2.3f);
845     // allocRun() allocates only the glyph buffer.
846     std::fill(run.glyphs, run.glyphs + glyph_count, 0);
847     auto blob = builder.make();
848     SkSerialProcs procs;
849     SkAutoTMalloc<uint8_t> storage;
850     size_t blob_size = 0u;
851     size_t storage_size = 0u;
852
853     blob_size = SkAlign4(blob->serialize(procs)->size());
854     REPORTER_ASSERT(reporter, blob_size > 4u);
855     storage_size = blob_size - 4;
856     storage.realloc(storage_size);
857     REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) == 0u);
858     storage_size = blob_size;
859     storage.realloc(storage_size);
860     REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) != 0u);
861 }
862
863 DEF_TEST(WriteBuffer_external_memory_flattenable, reporter) {
864     SkScalar intervals[] = {1.f, 1.f};
865     auto path_effect = SkDashPathEffect::Make(intervals, 2, 0);
866     size_t path_size = SkAlign4(path_effect->serialize()->size());
867     REPORTER_ASSERT(reporter, path_size > 4u);
868     SkAutoTMalloc<uint8_t> storage;
869
870     size_t storage_size = path_size - 4;
871     storage.realloc(storage_size);
872     REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) == 0u);
873
874     storage_size = path_size;
875     storage.realloc(storage_size);
876     REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) != 0u);
877 }
878
879 DEF_TEST(ReadBuffer_empty, reporter) {
880     SkBinaryWriteBuffer writer;
881     writer.writeInt(123);
882     writer.writeDataAsByteArray(SkData::MakeEmpty().get());
883     writer.writeInt(321);
884
885     size_t size = writer.bytesWritten();
886     SkAutoMalloc storage(size);
887     writer.writeToMemory(storage.get());
888
889     SkReadBuffer reader(storage.get(), size);
890     REPORTER_ASSERT(reporter, reader.readInt() == 123);
891     auto data = reader.readByteArrayAsData();
892     REPORTER_ASSERT(reporter, data->size() == 0);
893     REPORTER_ASSERT(reporter, reader.readInt() == 321);
894 }