• 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/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>
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(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 
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 filter = SkTableColorFilter::Make(table);
307     sk_sp<SkColorFilter> copy(
308         TestFlattenableSerialization(as_CFB(filter.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 }
339 
serialize_typeface_proc(SkTypeface * typeface,void * ctx)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 
deserialize_typeface_proc(const void * data,size_t length,void * ctx)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     SkFontID 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 
serialize_and_compare_typeface(sk_sp<SkTypeface> typeface,const char * text,const SkSerialProcs * serial_procs,const SkDeserialProcs * deserial_procs,skiatest::Reporter * reporter)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 
makeDistortableWithNonDefaultAxes(skiatest::Reporter * reporter)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 
TestPictureTypefaceSerialization(const SkSerialProcs * serial_procs,const SkDeserialProcs * deserial_procs,skiatest::Reporter * reporter)425 static void TestPictureTypefaceSerialization(const SkSerialProcs* serial_procs,
426                                              const SkDeserialProcs* deserial_procs,
427                                              skiatest::Reporter* reporter) {
428     if (serial_procs != nullptr) {
429         {
430             // Load typeface from file to test CreateFromFile with index.
431             auto typeface = MakeResourceAsTypeface("fonts/test.ttc", 1);
432             if (!typeface) {
433                 INFOF(reporter, "Could not run fontstream test because test.ttc not found.");
434             } else {
435                 serialize_and_compare_typeface(std::move(typeface), "A!", serial_procs, deserial_procs,
436                     reporter);
437             }
438         }
439 
440         {
441             // Load typeface as stream to create with axis settings.
442             auto typeface = makeDistortableWithNonDefaultAxes(reporter);
443             if (!typeface) {
444                 INFOF(reporter, "Could not run fontstream test because Distortable.ttf not created.");
445             } else {
446                 serialize_and_compare_typeface(std::move(typeface), "ab", serial_procs,
447                     deserial_procs, reporter);
448             }
449         }
450     }
451 }
452 
TestTypefaceSerialization(skiatest::Reporter * reporter,sk_sp<SkTypeface> typeface)453 static void TestTypefaceSerialization(skiatest::Reporter* reporter, sk_sp<SkTypeface> typeface) {
454     SkDynamicMemoryWStream typefaceWStream;
455     typeface->serialize(&typefaceWStream);
456 
457     std::unique_ptr<SkStream> typefaceStream = typefaceWStream.detachAsStream();
458     sk_sp<SkTypeface> cloneTypeface = SkTypeface::MakeDeserialize(typefaceStream.get());
459     SkASSERT(cloneTypeface);
460 
461     SkString name, cloneName;
462     typeface->getFamilyName(&name);
463     cloneTypeface->getFamilyName(&cloneName);
464 
465     REPORTER_ASSERT(reporter, typeface->countGlyphs() == cloneTypeface->countGlyphs(),
466         "Typeface: \"%s\" CloneTypeface: \"%s\"", name.c_str(), cloneName.c_str());
467     REPORTER_ASSERT(reporter, typeface->fontStyle() == cloneTypeface->fontStyle(),
468         "Typeface: \"%s\" CloneTypeface: \"%s\"", name.c_str(), cloneName.c_str());
469 
470     SkFont font(typeface, 12);
471     SkFont clone(cloneTypeface, 12);
472     SkFontMetrics fontMetrics, cloneMetrics;
473     font.getMetrics(&fontMetrics);
474     clone.getMetrics(&cloneMetrics);
475     REPORTER_ASSERT(reporter, fontMetrics == cloneMetrics,
476         "Typeface: \"%s\" CloneTypeface: \"%s\"", name.c_str(), cloneName.c_str());
477 }
478 
479 #ifdef SKIA_COMPILE_DM_ALL
DEF_TEST(Serialization_Typeface,reporter)480 DEF_TEST(Serialization_Typeface, reporter) {
481     SkFont font;
482     TestTypefaceSerialization(reporter, font.refTypefaceOrDefault());
483     TestTypefaceSerialization(reporter, ToolUtils::sample_user_typeface());
484 }
485 #endif
486 
setup_bitmap_for_canvas(SkBitmap * bitmap)487 static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
488     bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
489 }
490 
make_checkerboard_image()491 static sk_sp<SkImage> make_checkerboard_image() {
492     SkBitmap bitmap;
493     setup_bitmap_for_canvas(&bitmap);
494 
495     SkCanvas canvas(bitmap);
496     canvas.clear(0x00000000);
497     SkPaint darkPaint;
498     darkPaint.setColor(0xFF804020);
499     SkPaint lightPaint;
500     lightPaint.setColor(0xFF244484);
501     const int i = kBitmapSize / 8;
502     const SkScalar f = SkIntToScalar(i);
503     for (int y = 0; y < kBitmapSize; y += i) {
504         for (int x = 0; x < kBitmapSize; x += i) {
505             canvas.save();
506             canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
507             canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
508             canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
509             canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
510             canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
511             canvas.restore();
512         }
513     }
514     return bitmap.asImage();
515 }
516 
draw_something(SkCanvas * canvas)517 static void draw_something(SkCanvas* canvas) {
518     canvas->save();
519     canvas->scale(0.5f, 0.5f);
520     canvas->drawImage(make_checkerboard_image(), 0, 0);
521     canvas->restore();
522 
523     SkPaint paint;
524     paint.setAntiAlias(true);
525     paint.setColor(SK_ColorRED);
526     canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
527     paint.setColor(SK_ColorBLACK);
528 
529     SkFont font;
530     font.setSize(kBitmapSize/3);
531     canvas->drawString("Picture", SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), font, paint);
532 }
533 
render(const SkPicture & p)534 static sk_sp<SkImage> render(const SkPicture& p) {
535     auto surf = SkSurface::MakeRasterN32Premul(SkScalarRoundToInt(p.cullRect().width()),
536                                                SkScalarRoundToInt(p.cullRect().height()));
537     if (!surf) {
538         return nullptr; // bounds are empty?
539     }
540     surf->getCanvas()->clear(SK_ColorWHITE);
541     p.playback(surf->getCanvas());
542     return surf->makeImageSnapshot();
543 }
544 
DEF_TEST(Serialization,reporter)545 DEF_TEST(Serialization, reporter) {
546     // Test matrix serialization
547     {
548         SkMatrix matrix = SkMatrix::I();
549         TestObjectSerialization(&matrix, reporter);
550     }
551 
552     // Test point3 serialization
553     {
554         SkPoint3 point;
555         TestObjectSerializationNoAlign<SkPoint3, false>(&point, reporter);
556     }
557 
558     // Test path serialization
559     {
560         SkPath path;
561         TestObjectSerialization(&path, reporter);
562     }
563 
564     // Test region serialization
565     {
566         SkRegion region;
567         TestObjectSerialization(&region, reporter);
568     }
569 
570     // Test color filter serialization
571     {
572         TestColorFilterSerialization(reporter);
573     }
574 
575     // Test string serialization
576     {
577         SkString string("string");
578         TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
579         TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
580     }
581 
582     // Test rrect serialization
583     {
584         // SkRRect does not initialize anything.
585         // An uninitialized SkRRect can be serialized,
586         // but will branch on uninitialized data when deserialized.
587         SkRRect rrect;
588         SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
589         SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
590         rrect.setRectRadii(rect, corners);
591         SerializationTest::TestAlignment(&rrect, reporter);
592     }
593 
594     // Test readByteArray
595     {
596         unsigned char data[kArraySize] = { 1, 2, 3 };
597         TestArraySerialization(data, reporter);
598     }
599 
600     // Test readColorArray
601     {
602         SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
603         TestArraySerialization(data, reporter);
604     }
605 
606     // Test readColor4fArray
607     {
608         SkColor4f data[kArraySize] = {
609             SkColor4f::FromColor(SK_ColorBLACK),
610             SkColor4f::FromColor(SK_ColorWHITE),
611             SkColor4f::FromColor(SK_ColorRED),
612             { 1.f, 2.f, 4.f, 8.f }
613         };
614         TestArraySerialization(data, reporter);
615     }
616 
617     // Test readIntArray
618     {
619         int32_t data[kArraySize] = { 1, 2, 4, 8 };
620         TestArraySerialization(data, reporter);
621     }
622 
623     // Test readPointArray
624     {
625         SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
626         TestArraySerialization(data, reporter);
627     }
628 
629     // Test readScalarArray
630     {
631         SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
632         TestArraySerialization(data, reporter);
633     }
634 
635     // Test skipByteArray
636     {
637         // Valid case with non-empty array:
638         {
639             unsigned char data[kArraySize] = { 1, 2, 3 };
640             SkBinaryWriteBuffer writer;
641             writer.writeByteArray(data, kArraySize);
642             SkAutoMalloc buf(writer.bytesWritten());
643             writer.writeToMemory(buf.get());
644 
645             SkReadBuffer reader(buf.get(), writer.bytesWritten());
646             size_t len = ~0;
647             const void* arr = reader.skipByteArray(&len);
648             REPORTER_ASSERT(reporter, arr);
649             REPORTER_ASSERT(reporter, len == kArraySize);
650             REPORTER_ASSERT(reporter, memcmp(arr, data, len) == 0);
651         }
652 
653         // Writing a zero length array (can be detected as valid by non-nullptr return):
654         {
655             SkBinaryWriteBuffer writer;
656             writer.writeByteArray(nullptr, 0);
657             SkAutoMalloc buf(writer.bytesWritten());
658             writer.writeToMemory(buf.get());
659 
660             SkReadBuffer reader(buf.get(), writer.bytesWritten());
661             size_t len = ~0;
662             const void* arr = reader.skipByteArray(&len);
663             REPORTER_ASSERT(reporter, arr);
664             REPORTER_ASSERT(reporter, len == 0);
665         }
666 
667         // If the array can't be safely read, should return nullptr:
668         {
669             SkBinaryWriteBuffer writer;
670             writer.writeUInt(kArraySize);
671             SkAutoMalloc buf(writer.bytesWritten());
672             writer.writeToMemory(buf.get());
673 
674             SkReadBuffer reader(buf.get(), writer.bytesWritten());
675             size_t len = ~0;
676             const void* arr = reader.skipByteArray(&len);
677             REPORTER_ASSERT(reporter, !arr);
678             REPORTER_ASSERT(reporter, len == 0);
679         }
680     }
681 
682     // Test invalid deserializations
683     {
684         SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
685 
686         SkBitmap validBitmap;
687         validBitmap.setInfo(info);
688 
689         // Create a bitmap with a really large height
690         SkBitmap invalidBitmap;
691         invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
692 
693         // The deserialization should succeed, and the rendering shouldn't crash,
694         // even when the device fails to initialize, due to its size
695         TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
696     }
697 
698     // Test simple SkPicture serialization
699     {
700         SkPictureRecorder recorder;
701         draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
702                                                SkIntToScalar(kBitmapSize)));
703         sk_sp<SkPicture> pict(recorder.finishRecordingAsPicture());
704 
705         // Serialize picture
706         SkBinaryWriteBuffer writer;
707         SkPicturePriv::Flatten(pict, writer);
708         size_t size = writer.bytesWritten();
709         SkAutoTMalloc<unsigned char> data(size);
710         writer.writeToMemory(static_cast<void*>(data.get()));
711 
712         // Deserialize picture
713         SkReadBuffer reader(static_cast<void*>(data.get()), size);
714         sk_sp<SkPicture> readPict(SkPicturePriv::MakeFromBuffer(reader));
715         REPORTER_ASSERT(reporter, reader.isValid());
716         REPORTER_ASSERT(reporter, readPict.get());
717         sk_sp<SkImage> img0 = render(*pict);
718         sk_sp<SkImage> img1 = render(*readPict);
719         if (img0 && img1) {
720             REPORTER_ASSERT(reporter, ToolUtils::equal_pixels(img0.get(), img1.get()));
721         }
722     }
723 
724     TestPictureTypefaceSerialization(nullptr, nullptr, reporter);
725 
726     SkSerialProcs serial_procs;
727     serial_procs.fTypefaceProc = serialize_typeface_proc;
728     SkDeserialProcs deserial_procs;
729     deserial_procs.fTypefaceProc = deserialize_typeface_proc;
730     TestPictureTypefaceSerialization(&serial_procs, &deserial_procs, reporter);
731 }
732 
733 ///////////////////////////////////////////////////////////////////////////////////////////////////
734 #include "include/core/SkAnnotation.h"
735 
copy_picture_via_serialization(SkPicture * src)736 static sk_sp<SkPicture> copy_picture_via_serialization(SkPicture* src) {
737     SkDynamicMemoryWStream wstream;
738     src->serialize(&wstream);
739     std::unique_ptr<SkStreamAsset> rstream(wstream.detachAsStream());
740     return SkPicture::MakeFromStream(rstream.get());
741 }
742 
743 struct AnnotationRec {
744     const SkRect    fRect;
745     const char*     fKey;
746     sk_sp<SkData>   fValue;
747 };
748 
749 class TestAnnotationCanvas : public SkCanvas {
750     skiatest::Reporter*     fReporter;
751     const AnnotationRec*    fRec;
752     int                     fCount;
753     int                     fCurrIndex;
754 
755 public:
TestAnnotationCanvas(skiatest::Reporter * reporter,const AnnotationRec rec[],int count)756     TestAnnotationCanvas(skiatest::Reporter* reporter, const AnnotationRec rec[], int count)
757         : SkCanvas(100, 100)
758         , fReporter(reporter)
759         , fRec(rec)
760         , fCount(count)
761         , fCurrIndex(0)
762     {}
763 
~TestAnnotationCanvas()764     ~TestAnnotationCanvas() override {
765         REPORTER_ASSERT(fReporter, fCount == fCurrIndex);
766     }
767 
768 protected:
onDrawAnnotation(const SkRect & rect,const char key[],SkData * value)769     void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) override {
770         REPORTER_ASSERT(fReporter, fCurrIndex < fCount);
771         REPORTER_ASSERT(fReporter, rect == fRec[fCurrIndex].fRect);
772         REPORTER_ASSERT(fReporter, !strcmp(key, fRec[fCurrIndex].fKey));
773         REPORTER_ASSERT(fReporter, value->equals(fRec[fCurrIndex].fValue.get()));
774         fCurrIndex += 1;
775     }
776 };
777 
778 /*
779  *  Test the 3 annotation types by recording them into a picture, serializing, and then playing
780  *  them back into another canvas.
781  */
DEF_TEST(Annotations,reporter)782 DEF_TEST(Annotations, reporter) {
783     SkPictureRecorder recorder;
784     SkCanvas* recordingCanvas = recorder.beginRecording(SkRect::MakeWH(100, 100));
785 
786     const char* str0 = "rect-with-url";
787     const SkRect r0 = SkRect::MakeWH(10, 10);
788     sk_sp<SkData> d0(SkData::MakeWithCString(str0));
789     SkAnnotateRectWithURL(recordingCanvas, r0, d0.get());
790 
791     const char* str1 = "named-destination";
792     const SkRect r1 = SkRect::MakeXYWH(5, 5, 0, 0); // collapsed to a point
793     sk_sp<SkData> d1(SkData::MakeWithCString(str1));
794     SkAnnotateNamedDestination(recordingCanvas, {r1.x(), r1.y()}, d1.get());
795 
796     const char* str2 = "link-to-destination";
797     const SkRect r2 = SkRect::MakeXYWH(20, 20, 5, 6);
798     sk_sp<SkData> d2(SkData::MakeWithCString(str2));
799     SkAnnotateLinkToDestination(recordingCanvas, r2, d2.get());
800 
801     const AnnotationRec recs[] = {
802         { r0, SkAnnotationKeys::URL_Key(),                  std::move(d0) },
803         { r1, SkAnnotationKeys::Define_Named_Dest_Key(),    std::move(d1) },
804         { r2, SkAnnotationKeys::Link_Named_Dest_Key(),      std::move(d2) },
805     };
806 
807     sk_sp<SkPicture> pict0(recorder.finishRecordingAsPicture());
808     sk_sp<SkPicture> pict1(copy_picture_via_serialization(pict0.get()));
809 
810     TestAnnotationCanvas canvas(reporter, recs, SK_ARRAY_COUNT(recs));
811     canvas.drawPicture(pict1);
812 }
813 
DEF_TEST(WriteBuffer_storage,reporter)814 DEF_TEST(WriteBuffer_storage, reporter) {
815     enum {
816         kSize = 32
817     };
818     int32_t storage[kSize/4];
819     char src[kSize];
820     sk_bzero(src, kSize);
821 
822     SkBinaryWriteBuffer writer(storage, kSize);
823     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
824     REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
825     writer.write(src, kSize - 4);
826     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
827     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
828     writer.writeInt(0);
829     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
830     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
831 
832     writer.reset(storage, kSize-4);
833     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
834     REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
835     writer.write(src, kSize - 4);
836     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
837     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
838     writer.writeInt(0);
839     REPORTER_ASSERT(reporter, !writer.usingInitialStorage());   // this is the change
840     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
841 }
842 
DEF_TEST(WriteBuffer_external_memory_textblob,reporter)843 DEF_TEST(WriteBuffer_external_memory_textblob, reporter) {
844     SkFont font;
845     font.setTypeface(SkTypeface::MakeDefault());
846 
847     SkTextBlobBuilder builder;
848     int glyph_count = 5;
849     const auto& run = builder.allocRun(font, glyph_count, 1.2f, 2.3f);
850     // allocRun() allocates only the glyph buffer.
851     std::fill(run.glyphs, run.glyphs + glyph_count, 0);
852     auto blob = builder.make();
853     SkSerialProcs procs;
854     SkAutoTMalloc<uint8_t> storage;
855     size_t blob_size = 0u;
856     size_t storage_size = 0u;
857 
858     blob_size = SkAlign4(blob->serialize(procs)->size());
859     REPORTER_ASSERT(reporter, blob_size > 4u);
860     storage_size = blob_size - 4;
861     storage.realloc(storage_size);
862     REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) == 0u);
863     storage_size = blob_size;
864     storage.realloc(storage_size);
865     REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) != 0u);
866 }
867 
DEF_TEST(WriteBuffer_external_memory_flattenable,reporter)868 DEF_TEST(WriteBuffer_external_memory_flattenable, reporter) {
869     SkScalar intervals[] = {1.f, 1.f};
870     auto path_effect = SkDashPathEffect::Make(intervals, 2, 0);
871     size_t path_size = SkAlign4(path_effect->serialize()->size());
872     REPORTER_ASSERT(reporter, path_size > 4u);
873     SkAutoTMalloc<uint8_t> storage;
874 
875     size_t storage_size = path_size - 4;
876     storage.realloc(storage_size);
877     REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) == 0u);
878 
879     storage_size = path_size;
880     storage.realloc(storage_size);
881     REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) != 0u);
882 }
883 
DEF_TEST(ReadBuffer_empty,reporter)884 DEF_TEST(ReadBuffer_empty, reporter) {
885     SkBinaryWriteBuffer writer;
886     writer.writeInt(123);
887     writer.writeDataAsByteArray(SkData::MakeEmpty().get());
888     writer.writeInt(321);
889 
890     size_t size = writer.bytesWritten();
891     SkAutoMalloc storage(size);
892     writer.writeToMemory(storage.get());
893 
894     SkReadBuffer reader(storage.get(), size);
895     REPORTER_ASSERT(reporter, reader.readInt() == 123);
896     auto data = reader.readByteArrayAsData();
897     REPORTER_ASSERT(reporter, data->size() == 0);
898     REPORTER_ASSERT(reporter, reader.readInt() == 321);
899 }
900