• 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/SkAnnotation.h"
9 #include "include/core/SkBitmap.h"
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkColorFilter.h"
14 #include "include/core/SkData.h"
15 #include "include/core/SkFont.h"
16 #include "include/core/SkFontArguments.h"
17 #include "include/core/SkFontMetrics.h"
18 #include "include/core/SkFontMgr.h"
19 #include "include/core/SkFontStyle.h"
20 #include "include/core/SkImage.h"
21 #include "include/core/SkImageFilter.h"
22 #include "include/core/SkImageInfo.h"
23 #include "include/core/SkMatrix.h"
24 #include "include/core/SkPaint.h"
25 #include "include/core/SkPath.h"
26 #include "include/core/SkPathEffect.h"
27 #include "include/core/SkPicture.h"
28 #include "include/core/SkPictureRecorder.h"
29 #include "include/core/SkPoint.h"
30 #include "include/core/SkPoint3.h"
31 #include "include/core/SkRRect.h"
32 #include "include/core/SkRect.h"
33 #include "include/core/SkRefCnt.h"
34 #include "include/core/SkRegion.h"
35 #include "include/core/SkSamplingOptions.h"
36 #include "include/core/SkScalar.h"
37 #include "include/core/SkSerialProcs.h"
38 #include "include/core/SkStream.h"
39 #include "include/core/SkString.h"
40 #include "include/core/SkSurface.h"
41 #include "include/core/SkTextBlob.h"
42 #include "include/core/SkTypeface.h"
43 #include "include/core/SkTypes.h"
44 #include "include/effects/SkDashPathEffect.h"
45 #include "include/effects/SkImageFilters.h"
46 #include "include/private/base/SkAlign.h"
47 #include "include/private/base/SkTemplates.h"
48 #include "include/private/base/SkMalloc.h"
49 #include "src/base/SkAutoMalloc.h"
50 #include "src/core/SkAnnotationKeys.h"
51 #include "src/core/SkColorFilterBase.h"
52 #include "src/core/SkImageFilter_Base.h"
53 #include "src/core/SkPicturePriv.h"
54 #include "src/core/SkReadBuffer.h"
55 #include "src/core/SkWriteBuffer.h"
56 #include "tests/Test.h"
57 #include "tools/Resources.h"
58 #include "tools/ToolUtils.h"
59 
60 #include <algorithm>
61 #include <array>
62 #include <cstdint>
63 #include <cstring>
64 #include <memory>
65 #include <utility>
66 
67 using namespace skia_private;
68 
69 static const uint32_t kArraySize = 64;
70 static const int kBitmapSize = 256;
71 
72 class SerializationTest {
73 public:
74 
75 template<typename T>
TestAlignment(T * testObj,skiatest::Reporter * reporter)76 static void TestAlignment(T* testObj, skiatest::Reporter* reporter) {
77     // Test memory read/write functions directly
78     unsigned char dataWritten[1024];
79     size_t bytesWrittenToMemory = testObj->writeToMemory(dataWritten);
80     REPORTER_ASSERT(reporter, SkAlign4(bytesWrittenToMemory) == bytesWrittenToMemory);
81     size_t bytesReadFromMemory = testObj->readFromMemory(dataWritten, bytesWrittenToMemory);
82     REPORTER_ASSERT(reporter, SkAlign4(bytesReadFromMemory) == bytesReadFromMemory);
83 }
84 };
85 
86 template<typename T> struct SerializationUtils {
87     // Generic case for flattenables
WriteSerializationUtils88     static void Write(SkWriteBuffer& writer, const T* flattenable) {
89         writer.writeFlattenable(flattenable);
90     }
ReadSerializationUtils91     static void Read(SkReadBuffer& reader, T** flattenable) {
92         *flattenable = (T*)reader.readFlattenable(T::GetFlattenableType());
93     }
94 };
95 
96 template<> struct SerializationUtils<SkMatrix> {
WriteSerializationUtils97     static void Write(SkWriteBuffer& writer, const SkMatrix* matrix) {
98         writer.writeMatrix(*matrix);
99     }
ReadSerializationUtils100     static void Read(SkReadBuffer& reader, SkMatrix* matrix) {
101         reader.readMatrix(matrix);
102     }
103 };
104 
105 template<> struct SerializationUtils<SkPath> {
WriteSerializationUtils106     static void Write(SkWriteBuffer& writer, const SkPath* path) {
107         writer.writePath(*path);
108     }
ReadSerializationUtils109     static void Read(SkReadBuffer& reader, SkPath* path) {
110         reader.readPath(path);
111     }
112 };
113 
114 template<> struct SerializationUtils<SkRegion> {
WriteSerializationUtils115     static void Write(SkWriteBuffer& writer, const SkRegion* region) {
116         writer.writeRegion(*region);
117     }
ReadSerializationUtils118     static void Read(SkReadBuffer& reader, SkRegion* region) {
119         reader.readRegion(region);
120     }
121 };
122 
123 template<> struct SerializationUtils<SkString> {
WriteSerializationUtils124     static void Write(SkWriteBuffer& writer, const SkString* string) {
125         writer.writeString(string->c_str());
126     }
ReadSerializationUtils127     static void Read(SkReadBuffer& reader, SkString* string) {
128         reader.readString(string);
129     }
130 };
131 
132 template<> struct SerializationUtils<unsigned char> {
WriteSerializationUtils133     static void Write(SkWriteBuffer& writer, unsigned char* data, uint32_t arraySize) {
134         writer.writeByteArray(data, arraySize);
135     }
ReadSerializationUtils136     static bool Read(SkReadBuffer& reader, unsigned char* data, uint32_t arraySize) {
137         return reader.readByteArray(data, arraySize);
138     }
139 };
140 
141 template<> struct SerializationUtils<SkColor> {
WriteSerializationUtils142     static void Write(SkWriteBuffer& writer, SkColor* data, uint32_t arraySize) {
143         writer.writeColorArray(data, arraySize);
144     }
ReadSerializationUtils145     static bool Read(SkReadBuffer& reader, SkColor* data, uint32_t arraySize) {
146         return reader.readColorArray(data, arraySize);
147     }
148 };
149 
150 template<> struct SerializationUtils<SkColor4f> {
WriteSerializationUtils151     static void Write(SkWriteBuffer& writer, SkColor4f* data, uint32_t arraySize) {
152         writer.writeColor4fArray(data, arraySize);
153     }
ReadSerializationUtils154     static bool Read(SkReadBuffer& reader, SkColor4f* data, uint32_t arraySize) {
155         return reader.readColor4fArray(data, arraySize);
156     }
157 };
158 
159 template<> struct SerializationUtils<int32_t> {
WriteSerializationUtils160     static void Write(SkWriteBuffer& writer, int32_t* data, uint32_t arraySize) {
161         writer.writeIntArray(data, arraySize);
162     }
ReadSerializationUtils163     static bool Read(SkReadBuffer& reader, int32_t* data, uint32_t arraySize) {
164         return reader.readIntArray(data, arraySize);
165     }
166 };
167 
168 template<> struct SerializationUtils<SkPoint> {
WriteSerializationUtils169     static void Write(SkWriteBuffer& writer, SkPoint* data, uint32_t arraySize) {
170         writer.writePointArray(data, arraySize);
171     }
ReadSerializationUtils172     static bool Read(SkReadBuffer& reader, SkPoint* data, uint32_t arraySize) {
173         return reader.readPointArray(data, arraySize);
174     }
175 };
176 
177 template<> struct SerializationUtils<SkPoint3> {
WriteSerializationUtils178     static void Write(SkWriteBuffer& writer, const SkPoint3* data) {
179         writer.writePoint3(*data);
180     }
ReadSerializationUtils181     static void Read(SkReadBuffer& reader, SkPoint3* data) {
182         reader.readPoint3(data);
183     }
184 };
185 
186 template<> struct SerializationUtils<SkScalar> {
WriteSerializationUtils187     static void Write(SkWriteBuffer& writer, SkScalar* data, uint32_t arraySize) {
188         writer.writeScalarArray(data, arraySize);
189     }
ReadSerializationUtils190     static bool Read(SkReadBuffer& reader, SkScalar* data, uint32_t arraySize) {
191         return reader.readScalarArray(data, arraySize);
192     }
193 };
194 
195 template<typename T, bool testInvalid> struct SerializationTestUtils {
InvalidateDataSerializationTestUtils196     static void InvalidateData(unsigned char* data) {}
197 };
198 
199 template<> struct SerializationTestUtils<SkString, true> {
InvalidateDataSerializationTestUtils200     static void InvalidateData(unsigned char* data) {
201         data[3] |= 0x80; // Reverse sign of 1st integer
202     }
203 };
204 
205 template<typename T, bool testInvalid>
TestObjectSerializationNoAlign(T * testObj,skiatest::Reporter * reporter)206 static void TestObjectSerializationNoAlign(T* testObj, skiatest::Reporter* reporter) {
207     SkBinaryWriteBuffer writer;
208     SerializationUtils<T>::Write(writer, testObj);
209     size_t bytesWritten = writer.bytesWritten();
210     REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
211 
212     unsigned char dataWritten[1024];
213     writer.writeToMemory(dataWritten);
214 
215     SerializationTestUtils<T, testInvalid>::InvalidateData(dataWritten);
216 
217     // Make sure this fails when it should (test with smaller size, but still multiple of 4)
218     SkReadBuffer buffer(dataWritten, bytesWritten - 4);
219     T obj;
220     SerializationUtils<T>::Read(buffer, &obj);
221     REPORTER_ASSERT(reporter, !buffer.isValid());
222 
223     // Make sure this succeeds when it should
224     SkReadBuffer buffer2(dataWritten, bytesWritten);
225     size_t offsetBefore = buffer2.offset();
226     T obj2;
227     SerializationUtils<T>::Read(buffer2, &obj2);
228     size_t offsetAfter = buffer2.offset();
229     // This should have succeeded, since there are enough bytes to read this
230     REPORTER_ASSERT(reporter, buffer2.isValid() == !testInvalid);
231     // Note: This following test should always succeed, regardless of whether the buffer is valid,
232     // since if it is invalid, it will simply skip to the end, as if it had read the whole buffer.
233     REPORTER_ASSERT(reporter, offsetAfter - offsetBefore == bytesWritten);
234 }
235 
236 template<typename T>
TestObjectSerialization(T * testObj,skiatest::Reporter * reporter)237 static void TestObjectSerialization(T* testObj, skiatest::Reporter* reporter) {
238     TestObjectSerializationNoAlign<T, false>(testObj, reporter);
239     SerializationTest::TestAlignment(testObj, reporter);
240 }
241 
242 template<typename T>
TestFlattenableSerialization(T * testObj,bool shouldSucceed,skiatest::Reporter * reporter)243 static T* TestFlattenableSerialization(T* testObj, bool shouldSucceed,
244                                        skiatest::Reporter* reporter) {
245     SkBinaryWriteBuffer writer;
246     SerializationUtils<T>::Write(writer, testObj);
247     size_t bytesWritten = writer.bytesWritten();
248     REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
249 
250     SkASSERT(bytesWritten <= 4096);
251     unsigned char dataWritten[4096];
252     writer.writeToMemory(dataWritten);
253 
254     // Make sure this fails when it should (test with smaller size, but still multiple of 4)
255     SkReadBuffer buffer(dataWritten, bytesWritten - 4);
256     T* obj = nullptr;
257     SerializationUtils<T>::Read(buffer, &obj);
258     REPORTER_ASSERT(reporter, !buffer.isValid());
259     REPORTER_ASSERT(reporter, nullptr == obj);
260 
261     // Make sure this succeeds when it should
262     SkReadBuffer buffer2(dataWritten, bytesWritten);
263     const unsigned char* peekBefore = static_cast<const unsigned char*>(buffer2.skip(0));
264     T* obj2 = nullptr;
265     SerializationUtils<T>::Read(buffer2, &obj2);
266     const unsigned char* peekAfter = static_cast<const unsigned char*>(buffer2.skip(0));
267     if (shouldSucceed) {
268         // This should have succeeded, since there are enough bytes to read this
269         REPORTER_ASSERT(reporter, buffer2.isValid());
270         REPORTER_ASSERT(reporter, static_cast<size_t>(peekAfter - peekBefore) == bytesWritten);
271         REPORTER_ASSERT(reporter, obj2);
272     } else {
273         // If the deserialization was supposed to fail, make sure it did
274         REPORTER_ASSERT(reporter, !buffer.isValid());
275         REPORTER_ASSERT(reporter, nullptr == obj2);
276     }
277 
278     return obj2; // Return object to perform further validity tests on it
279 }
280 
281 template<typename T>
TestArraySerialization(T * data,skiatest::Reporter * reporter)282 static void TestArraySerialization(T* data, skiatest::Reporter* reporter) {
283     SkBinaryWriteBuffer writer;
284     SerializationUtils<T>::Write(writer, data, kArraySize);
285     size_t bytesWritten = writer.bytesWritten();
286     // This should write the length (in 4 bytes) and the array
287     REPORTER_ASSERT(reporter, (4 + kArraySize * sizeof(T)) == bytesWritten);
288 
289     unsigned char dataWritten[2048];
290     writer.writeToMemory(dataWritten);
291 
292     // Make sure this fails when it should
293     SkReadBuffer buffer(dataWritten, bytesWritten);
294     T dataRead[kArraySize];
295     bool success = SerializationUtils<T>::Read(buffer, dataRead, kArraySize / 2);
296     // This should have failed, since the provided size was too small
297     REPORTER_ASSERT(reporter, !success);
298 
299     // Make sure this succeeds when it should
300     SkReadBuffer buffer2(dataWritten, bytesWritten);
301     success = SerializationUtils<T>::Read(buffer2, dataRead, kArraySize);
302     // This should have succeeded, since there are enough bytes to read this
303     REPORTER_ASSERT(reporter, success);
304 }
305 
TestBitmapSerialization(const SkBitmap & validBitmap,const SkBitmap & invalidBitmap,bool shouldSucceed,skiatest::Reporter * reporter)306 static void TestBitmapSerialization(const SkBitmap& validBitmap,
307                                     const SkBitmap& invalidBitmap,
308                                     bool shouldSucceed,
309                                     skiatest::Reporter* reporter) {
310     sk_sp<SkImage> validImage(validBitmap.asImage());
311     sk_sp<SkImageFilter> validBitmapSource(SkImageFilters::Image(std::move(validImage)));
312     sk_sp<SkImage> invalidImage(invalidBitmap.asImage());
313     sk_sp<SkImageFilter> invalidBitmapSource(SkImageFilters::Image(std::move(invalidImage)));
314     sk_sp<SkImageFilter> xfermodeImageFilter(
315         SkImageFilters::Blend(SkBlendMode::kSrcOver,
316                               std::move(invalidBitmapSource),
317                               std::move(validBitmapSource), nullptr));
318 
319     sk_sp<SkImageFilter> deserializedFilter(
320         TestFlattenableSerialization<SkImageFilter_Base>(
321             (SkImageFilter_Base*)xfermodeImageFilter.get(), shouldSucceed, reporter));
322 
323     // Try to render a small bitmap using the invalid deserialized filter
324     // to make sure we don't crash while trying to render it
325     if (shouldSucceed) {
326         SkBitmap bitmap;
327         bitmap.allocN32Pixels(24, 24);
328         SkCanvas canvas(bitmap);
329         canvas.clear(0x00000000);
330         SkPaint paint;
331         paint.setImageFilter(deserializedFilter);
332         canvas.clipRect(SkRect::MakeXYWH(0, 0, SkIntToScalar(24), SkIntToScalar(24)));
333         canvas.drawImage(bitmap.asImage(), 0, 0, SkSamplingOptions(), &paint);
334     }
335 }
336 
TestColorFilterSerialization(skiatest::Reporter * reporter)337 static void TestColorFilterSerialization(skiatest::Reporter* reporter) {
338     uint8_t table[256];
339     for (int i = 0; i < 256; ++i) {
340         table[i] = (i * 41) % 256;
341     }
342     auto filter = SkColorFilters::Table(table);
343     sk_sp<SkColorFilter> copy(
344         TestFlattenableSerialization(as_CFB(filter.get()), true, reporter));
345 }
346 
draw_picture(SkPicture & picture)347 static SkBitmap draw_picture(SkPicture& picture) {
348      SkBitmap bitmap;
349      bitmap.allocN32Pixels(SkScalarCeilToInt(picture.cullRect().width()),
350                            SkScalarCeilToInt(picture.cullRect().height()));
351      SkCanvas canvas(bitmap);
352      picture.playback(&canvas);
353      return bitmap;
354 }
355 
compare_bitmaps(skiatest::Reporter * reporter,const SkBitmap & b1,const SkBitmap & b2)356 static void compare_bitmaps(skiatest::Reporter* reporter,
357                             const SkBitmap& b1, const SkBitmap& b2) {
358     REPORTER_ASSERT(reporter, b1.width() == b2.width());
359     REPORTER_ASSERT(reporter, b1.height() == b2.height());
360 
361     if ((b1.width() != b2.width()) ||
362         (b1.height() != b2.height())) {
363         return;
364     }
365 
366     int pixelErrors = 0;
367     for (int y = 0; y < b2.height(); ++y) {
368         for (int x = 0; x < b2.width(); ++x) {
369             if (b1.getColor(x, y) != b2.getColor(x, y))
370                 ++pixelErrors;
371         }
372     }
373     REPORTER_ASSERT(reporter, 0 == pixelErrors);
374 }
375 
serialize_typeface_proc(SkTypeface * typeface,void * ctx)376 static sk_sp<SkData> serialize_typeface_proc(SkTypeface* typeface, void* ctx) {
377     // Write out typeface ID followed by entire typeface.
378     SkDynamicMemoryWStream stream;
379     sk_sp<SkData> data(typeface->serialize(SkTypeface::SerializeBehavior::kDoIncludeData));
380     uint32_t typeface_id = typeface->uniqueID();
381     stream.write(&typeface_id, sizeof(typeface_id));
382     stream.write(data->data(), data->size());
383     return stream.detachAsData();
384 }
385 
deserialize_typeface_proc(const void * data,size_t length,void * ctx)386 static sk_sp<SkTypeface> deserialize_typeface_proc(const void* data, size_t length, void* ctx) {
387     SkStream* stream;
388     if (length < sizeof(stream)) {
389         return nullptr;
390     }
391     memcpy(&stream, data, sizeof(stream));
392 
393     SkTypefaceID id;
394     if (!stream->read(&id, sizeof(id))) {
395         return nullptr;
396     }
397 
398     sk_sp<SkTypeface> typeface = SkTypeface::MakeDeserialize(stream);
399     return typeface;
400 }
401 
serialize_and_compare_typeface(sk_sp<SkTypeface> typeface,const char * text,const SkSerialProcs * serial_procs,const SkDeserialProcs * deserial_procs,skiatest::Reporter * reporter)402 static void serialize_and_compare_typeface(sk_sp<SkTypeface> typeface,
403                                            const char* text,
404                                            const SkSerialProcs* serial_procs,
405                                            const SkDeserialProcs* deserial_procs,
406                                            skiatest::Reporter* reporter) {
407     // Create a font with the typeface.
408     SkPaint paint;
409     paint.setColor(SK_ColorGRAY);
410     SkFont font(std::move(typeface), 30);
411 
412     // Paint some text.
413     SkPictureRecorder recorder;
414     SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
415     SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
416                                                SkIntToScalar(canvasRect.height()));
417     canvas->drawColor(SK_ColorWHITE);
418     canvas->drawString(text, 24, 32, font, paint);
419     sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
420 
421     // Serlialize picture and create its clone from stream.
422     SkDynamicMemoryWStream stream;
423     picture->serialize(&stream, serial_procs);
424     std::unique_ptr<SkStream> inputStream(stream.detachAsStream());
425     sk_sp<SkPicture> loadedPicture(SkPicture::MakeFromStream(inputStream.get(), deserial_procs));
426 
427     // Draw both original and clone picture and compare bitmaps -- they should be identical.
428     SkBitmap origBitmap = draw_picture(*picture);
429     SkBitmap destBitmap = draw_picture(*loadedPicture);
430     compare_bitmaps(reporter, origBitmap, destBitmap);
431 }
432 
makeDistortableWithNonDefaultAxes(skiatest::Reporter * reporter)433 static sk_sp<SkTypeface> makeDistortableWithNonDefaultAxes(skiatest::Reporter* reporter) {
434     std::unique_ptr<SkStreamAsset> distortable(GetResourceAsStream("fonts/Distortable.ttf"));
435     if (!distortable) {
436         REPORT_FAILURE(reporter, "distortable", SkString());
437         return nullptr;
438     }
439 
440     const SkFontArguments::VariationPosition::Coordinate position[] = {
441         { SkSetFourByteTag('w','g','h','t'), SK_ScalarSqrt2 },
442     };
443     SkFontArguments params;
444     params.setVariationDesignPosition({position, std::size(position)});
445 
446     sk_sp<SkFontMgr> fm = SkFontMgr::RefDefault();
447 
448     sk_sp<SkTypeface> typeface = fm->makeFromStream(std::move(distortable), params);
449     if (!typeface) {
450         return nullptr;  // Not all SkFontMgr can makeFromStream().
451     }
452 
453     int count = typeface->getVariationDesignPosition(nullptr, 0);
454     if (count == -1) {
455         return nullptr;  // The number of axes is unknown.
456     }
457 
458     return typeface;
459 }
460 
TestPictureTypefaceSerialization(const SkSerialProcs * serial_procs,const SkDeserialProcs * deserial_procs,skiatest::Reporter * reporter)461 static void TestPictureTypefaceSerialization(const SkSerialProcs* serial_procs,
462                                              const SkDeserialProcs* deserial_procs,
463                                              skiatest::Reporter* reporter) {
464     {
465         // Load typeface from file to test CreateFromFile with index.
466         auto typeface = MakeResourceAsTypeface("fonts/test.ttc", 1);
467         if (!typeface) {
468             INFOF(reporter, "Could not run fontstream test because test.ttc not found.");
469         } else {
470             serialize_and_compare_typeface(std::move(typeface), "A!", serial_procs, deserial_procs,
471                                            reporter);
472         }
473     }
474 
475     {
476         // Load typeface as stream to create with axis settings.
477         auto typeface = makeDistortableWithNonDefaultAxes(reporter);
478         if (!typeface) {
479             INFOF(reporter, "Could not run fontstream test because Distortable.ttf not created.");
480         } else {
481             serialize_and_compare_typeface(std::move(typeface), "ab", serial_procs,
482                                             deserial_procs, reporter);
483         }
484     }
485 }
486 
DumpTypeface(const SkTypeface & typeface)487 SkString DumpTypeface(const SkTypeface& typeface) {
488     int index;
489     std::unique_ptr<SkStreamAsset> typefaceStream = typeface.openStream(&index);
490     if (!typefaceStream) {
491         return SkString("No Stream");
492     }
493     size_t length = typefaceStream->getLength();
494 
495     SkString s;
496     s.appendf("Index: %d\n", index);
497     s.appendf("Length: %zu\n", length);
498     return s;
499 }
DumpFontMetrics(const SkFontMetrics & metrics)500 SkString DumpFontMetrics(const SkFontMetrics& metrics) {
501     SkString m("Flags:\n");
502 
503     if (metrics.fFlags == 0) {
504         m += "  No flags\n";
505     } else {
506         if (metrics.fFlags & SkFontMetrics::kUnderlineThicknessIsValid_Flag) {
507             m += "  UnderlineThicknessIsValid\n";
508         }
509         if (metrics.fFlags & SkFontMetrics::kUnderlinePositionIsValid_Flag) {
510             m += "  kUnderlinePositionIsValid\n";
511         }
512         if (metrics.fFlags & SkFontMetrics::kStrikeoutThicknessIsValid_Flag) {
513             m += "  kStrikeoutThicknessIsValid\n";
514         }
515         if (metrics.fFlags & SkFontMetrics::kStrikeoutPositionIsValid_Flag) {
516             m += "  kStrikeoutPositionIsValid\n";
517         }
518         if (metrics.fFlags & SkFontMetrics::kBoundsInvalid_Flag) {
519             m += "  kBoundsInvalid\n";
520         }
521     }
522 
523     m.appendf("Top: %f\n", metrics.fTop);
524     m.appendf("Ascent: %f\n", metrics.fAscent);
525     m.appendf("Descent: %f\n", metrics.fDescent);
526     m.appendf("Bottom: %f\n", metrics.fBottom);
527     m.appendf("Leading: %f\n", metrics.fLeading);
528     m.appendf("AvgCharWidth: %f\n", metrics.fAvgCharWidth);
529     m.appendf("MaxCharWidth: %f\n", metrics.fMaxCharWidth);
530     m.appendf("XMin: %f\n", metrics.fXMin);
531     m.appendf("XMax: %f\n", metrics.fXMax);
532     m.appendf("XHeight: %f\n", metrics.fXHeight);
533     m.appendf("CapHeight: %f\n", metrics.fCapHeight);
534     m.appendf("UnderlineThickness: %f\n", metrics.fUnderlineThickness);
535     m.appendf("UnderlinePosition: %f\n", metrics.fUnderlinePosition);
536     m.appendf("StrikeoutThickness: %f\n", metrics.fStrikeoutThickness);
537     m.appendf("StrikeoutPosition: %f\n", metrics.fStrikeoutPosition);
538     return m;
539 }
TestTypefaceSerialization(skiatest::Reporter * reporter,sk_sp<SkTypeface> typeface)540 static void TestTypefaceSerialization(skiatest::Reporter* reporter, sk_sp<SkTypeface> typeface) {
541     SkDynamicMemoryWStream typefaceWStream;
542     typeface->serialize(&typefaceWStream);
543 
544     std::unique_ptr<SkStream> typefaceStream = typefaceWStream.detachAsStream();
545     sk_sp<SkTypeface> cloneTypeface = SkTypeface::MakeDeserialize(typefaceStream.get());
546     SkASSERT(cloneTypeface);
547 
548     SkString name, cloneName;
549     typeface->getFamilyName(&name);
550     cloneTypeface->getFamilyName(&cloneName);
551 
552     REPORTER_ASSERT(reporter, typeface->countGlyphs() == cloneTypeface->countGlyphs(),
553         "Typeface: \"%s\" CloneTypeface: \"%s\"", name.c_str(), cloneName.c_str());
554     REPORTER_ASSERT(reporter, typeface->fontStyle() == cloneTypeface->fontStyle(),
555         "Typeface: \"%s\" CloneTypeface: \"%s\"", name.c_str(), cloneName.c_str());
556 
557     SkFont font(typeface, 12);
558     SkFont clone(cloneTypeface, 12);
559     SkFontMetrics fontMetrics, cloneMetrics;
560     font.getMetrics(&fontMetrics);
561     clone.getMetrics(&cloneMetrics);
562     REPORTER_ASSERT(reporter, fontMetrics == cloneMetrics,
563         "Typeface: \"%s\"\n-Metrics---\n%s-Data---\n%s\n\n"
564         "CloneTypeface: \"%s\"\n-Metrics---\n%s-Data---\n%s",
565         name.c_str(),
566         DumpFontMetrics(fontMetrics).c_str(),
567         DumpTypeface(*typeface).c_str(),
568         cloneName.c_str(),
569         DumpFontMetrics(cloneMetrics).c_str(),
570         DumpTypeface(*cloneTypeface).c_str());
571 }
DEF_TEST(Serialization_Typeface,reporter)572 DEF_TEST(Serialization_Typeface, reporter) {
573     SkFont font;
574     TestTypefaceSerialization(reporter, font.refTypefaceOrDefault());
575     TestTypefaceSerialization(reporter, ToolUtils::sample_user_typeface());
576 }
577 
setup_bitmap_for_canvas(SkBitmap * bitmap)578 static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
579     bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
580 }
581 
make_checkerboard_image()582 static sk_sp<SkImage> make_checkerboard_image() {
583     SkBitmap bitmap;
584     setup_bitmap_for_canvas(&bitmap);
585 
586     SkCanvas canvas(bitmap);
587     canvas.clear(0x00000000);
588     SkPaint darkPaint;
589     darkPaint.setColor(0xFF804020);
590     SkPaint lightPaint;
591     lightPaint.setColor(0xFF244484);
592     const int i = kBitmapSize / 8;
593     const SkScalar f = SkIntToScalar(i);
594     for (int y = 0; y < kBitmapSize; y += i) {
595         for (int x = 0; x < kBitmapSize; x += i) {
596             canvas.save();
597             canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
598             canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
599             canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
600             canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
601             canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
602             canvas.restore();
603         }
604     }
605     return bitmap.asImage();
606 }
607 
draw_something(SkCanvas * canvas)608 static void draw_something(SkCanvas* canvas) {
609     canvas->save();
610     canvas->scale(0.5f, 0.5f);
611     canvas->drawImage(make_checkerboard_image(), 0, 0);
612     canvas->restore();
613 
614     SkPaint paint;
615     paint.setAntiAlias(true);
616     paint.setColor(SK_ColorRED);
617     canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
618     paint.setColor(SK_ColorBLACK);
619 
620     SkFont font;
621     font.setSize(kBitmapSize/3);
622     canvas->drawString("Picture", SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), font, paint);
623 }
624 
render(const SkPicture & p)625 static sk_sp<SkImage> render(const SkPicture& p) {
626     auto surf = SkSurface::MakeRasterN32Premul(SkScalarRoundToInt(p.cullRect().width()),
627                                                SkScalarRoundToInt(p.cullRect().height()));
628     if (!surf) {
629         return nullptr; // bounds are empty?
630     }
631     surf->getCanvas()->clear(SK_ColorWHITE);
632     p.playback(surf->getCanvas());
633     return surf->makeImageSnapshot();
634 }
635 
DEF_TEST(Serialization,reporter)636 DEF_TEST(Serialization, reporter) {
637     // Test matrix serialization
638     {
639         SkMatrix matrix = SkMatrix::I();
640         TestObjectSerialization(&matrix, reporter);
641     }
642 
643     // Test point3 serialization
644     {
645         SkPoint3 point;
646         TestObjectSerializationNoAlign<SkPoint3, false>(&point, reporter);
647     }
648 
649     // Test path serialization
650     {
651         SkPath path;
652         TestObjectSerialization(&path, reporter);
653     }
654 
655     // Test region serialization
656     {
657         SkRegion region;
658         TestObjectSerialization(&region, reporter);
659     }
660 
661     // Test color filter serialization
662     {
663         TestColorFilterSerialization(reporter);
664     }
665 
666     // Test string serialization
667     {
668         SkString string("string");
669         TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
670         TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
671     }
672 
673     // Test rrect serialization
674     {
675         // SkRRect does not initialize anything.
676         // An uninitialized SkRRect can be serialized,
677         // but will branch on uninitialized data when deserialized.
678         SkRRect rrect;
679         SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
680         SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
681         rrect.setRectRadii(rect, corners);
682         SerializationTest::TestAlignment(&rrect, reporter);
683     }
684 
685     // Test readByteArray
686     {
687         unsigned char data[kArraySize] = { 1, 2, 3 };
688         TestArraySerialization(data, reporter);
689     }
690 
691     // Test readColorArray
692     {
693         SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
694         TestArraySerialization(data, reporter);
695     }
696 
697     // Test readColor4fArray
698     {
699         SkColor4f data[kArraySize] = {
700             SkColor4f::FromColor(SK_ColorBLACK),
701             SkColor4f::FromColor(SK_ColorWHITE),
702             SkColor4f::FromColor(SK_ColorRED),
703             { 1.f, 2.f, 4.f, 8.f }
704         };
705         TestArraySerialization(data, reporter);
706     }
707 
708     // Test readIntArray
709     {
710         int32_t data[kArraySize] = { 1, 2, 4, 8 };
711         TestArraySerialization(data, reporter);
712     }
713 
714     // Test readPointArray
715     {
716         SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
717         TestArraySerialization(data, reporter);
718     }
719 
720     // Test readScalarArray
721     {
722         SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
723         TestArraySerialization(data, reporter);
724     }
725 
726     // Test skipByteArray
727     {
728         // Valid case with non-empty array:
729         {
730             unsigned char data[kArraySize] = { 1, 2, 3 };
731             SkBinaryWriteBuffer writer;
732             writer.writeByteArray(data, kArraySize);
733             SkAutoMalloc buf(writer.bytesWritten());
734             writer.writeToMemory(buf.get());
735 
736             SkReadBuffer reader(buf.get(), writer.bytesWritten());
737             size_t len = ~0;
738             const void* arr = reader.skipByteArray(&len);
739             REPORTER_ASSERT(reporter, arr);
740             REPORTER_ASSERT(reporter, len == kArraySize);
741             REPORTER_ASSERT(reporter, memcmp(arr, data, len) == 0);
742         }
743 
744         // Writing a zero length array (can be detected as valid by non-nullptr return):
745         {
746             SkBinaryWriteBuffer writer;
747             writer.writeByteArray(nullptr, 0);
748             SkAutoMalloc buf(writer.bytesWritten());
749             writer.writeToMemory(buf.get());
750 
751             SkReadBuffer reader(buf.get(), writer.bytesWritten());
752             size_t len = ~0;
753             const void* arr = reader.skipByteArray(&len);
754             REPORTER_ASSERT(reporter, arr);
755             REPORTER_ASSERT(reporter, len == 0);
756         }
757 
758         // If the array can't be safely read, should return nullptr:
759         {
760             SkBinaryWriteBuffer writer;
761             writer.writeUInt(kArraySize);
762             SkAutoMalloc buf(writer.bytesWritten());
763             writer.writeToMemory(buf.get());
764 
765             SkReadBuffer reader(buf.get(), writer.bytesWritten());
766             size_t len = ~0;
767             const void* arr = reader.skipByteArray(&len);
768             REPORTER_ASSERT(reporter, !arr);
769             REPORTER_ASSERT(reporter, len == 0);
770         }
771     }
772 
773     // Test invalid deserializations
774     {
775         SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
776 
777         SkBitmap validBitmap;
778         validBitmap.setInfo(info);
779 
780         // Create a bitmap with a really large height
781         SkBitmap invalidBitmap;
782         invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
783 
784         // The deserialization should succeed, and the rendering shouldn't crash,
785         // even when the device fails to initialize, due to its size
786         TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
787     }
788 
789     // Test simple SkPicture serialization
790     {
791         SkPictureRecorder recorder;
792         draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
793                                                SkIntToScalar(kBitmapSize)));
794         sk_sp<SkPicture> pict(recorder.finishRecordingAsPicture());
795 
796         // Serialize picture
797         SkBinaryWriteBuffer writer;
798         SkPicturePriv::Flatten(pict, writer);
799         size_t size = writer.bytesWritten();
800         AutoTMalloc<unsigned char> data(size);
801         writer.writeToMemory(static_cast<void*>(data.get()));
802 
803         // Deserialize picture
804         SkReadBuffer reader(static_cast<void*>(data.get()), size);
805         sk_sp<SkPicture> readPict(SkPicturePriv::MakeFromBuffer(reader));
806         REPORTER_ASSERT(reporter, reader.isValid());
807         REPORTER_ASSERT(reporter, readPict.get());
808         sk_sp<SkImage> img0 = render(*pict);
809         sk_sp<SkImage> img1 = render(*readPict);
810         if (img0 && img1) {
811             REPORTER_ASSERT(reporter, ToolUtils::equal_pixels(img0.get(), img1.get()));
812         }
813     }
814 
815     TestPictureTypefaceSerialization(nullptr, nullptr, reporter);
816 
817     SkSerialProcs serial_procs;
818     serial_procs.fTypefaceProc = serialize_typeface_proc;
819     SkDeserialProcs deserial_procs;
820     deserial_procs.fTypefaceProc = deserialize_typeface_proc;
821     TestPictureTypefaceSerialization(&serial_procs, &deserial_procs, reporter);
822 }
823 
824 ///////////////////////////////////////////////////////////////////////////////////////////////////
825 
copy_picture_via_serialization(SkPicture * src)826 static sk_sp<SkPicture> copy_picture_via_serialization(SkPicture* src) {
827     SkDynamicMemoryWStream wstream;
828     src->serialize(&wstream);
829     std::unique_ptr<SkStreamAsset> rstream(wstream.detachAsStream());
830     return SkPicture::MakeFromStream(rstream.get());
831 }
832 
833 struct AnnotationRec {
834     const SkRect    fRect;
835     const char*     fKey;
836     sk_sp<SkData>   fValue;
837 };
838 
839 class TestAnnotationCanvas : public SkCanvas {
840     skiatest::Reporter*     fReporter;
841     const AnnotationRec*    fRec;
842     int                     fCount;
843     int                     fCurrIndex;
844 
845 public:
TestAnnotationCanvas(skiatest::Reporter * reporter,const AnnotationRec rec[],int count)846     TestAnnotationCanvas(skiatest::Reporter* reporter, const AnnotationRec rec[], int count)
847         : SkCanvas(100, 100)
848         , fReporter(reporter)
849         , fRec(rec)
850         , fCount(count)
851         , fCurrIndex(0)
852     {}
853 
~TestAnnotationCanvas()854     ~TestAnnotationCanvas() override {
855         REPORTER_ASSERT(fReporter, fCount == fCurrIndex);
856     }
857 
858 protected:
onDrawAnnotation(const SkRect & rect,const char key[],SkData * value)859     void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) override {
860         REPORTER_ASSERT(fReporter, fCurrIndex < fCount);
861         REPORTER_ASSERT(fReporter, rect == fRec[fCurrIndex].fRect);
862         REPORTER_ASSERT(fReporter, !strcmp(key, fRec[fCurrIndex].fKey));
863         REPORTER_ASSERT(fReporter, value->equals(fRec[fCurrIndex].fValue.get()));
864         fCurrIndex += 1;
865     }
866 };
867 
868 /*
869  *  Test the 3 annotation types by recording them into a picture, serializing, and then playing
870  *  them back into another canvas.
871  */
DEF_TEST(Annotations,reporter)872 DEF_TEST(Annotations, reporter) {
873     SkPictureRecorder recorder;
874     SkCanvas* recordingCanvas = recorder.beginRecording(SkRect::MakeWH(100, 100));
875 
876     const char* str0 = "rect-with-url";
877     const SkRect r0 = SkRect::MakeWH(10, 10);
878     sk_sp<SkData> d0(SkData::MakeWithCString(str0));
879     SkAnnotateRectWithURL(recordingCanvas, r0, d0.get());
880 
881     const char* str1 = "named-destination";
882     const SkRect r1 = SkRect::MakeXYWH(5, 5, 0, 0); // collapsed to a point
883     sk_sp<SkData> d1(SkData::MakeWithCString(str1));
884     SkAnnotateNamedDestination(recordingCanvas, {r1.x(), r1.y()}, d1.get());
885 
886     const char* str2 = "link-to-destination";
887     const SkRect r2 = SkRect::MakeXYWH(20, 20, 5, 6);
888     sk_sp<SkData> d2(SkData::MakeWithCString(str2));
889     SkAnnotateLinkToDestination(recordingCanvas, r2, d2.get());
890 
891     const AnnotationRec recs[] = {
892         { r0, SkAnnotationKeys::URL_Key(),                  std::move(d0) },
893         { r1, SkAnnotationKeys::Define_Named_Dest_Key(),    std::move(d1) },
894         { r2, SkAnnotationKeys::Link_Named_Dest_Key(),      std::move(d2) },
895     };
896 
897     sk_sp<SkPicture> pict0(recorder.finishRecordingAsPicture());
898     sk_sp<SkPicture> pict1(copy_picture_via_serialization(pict0.get()));
899 
900     TestAnnotationCanvas canvas(reporter, recs, std::size(recs));
901     canvas.drawPicture(pict1);
902 }
903 
DEF_TEST(WriteBuffer_storage,reporter)904 DEF_TEST(WriteBuffer_storage, reporter) {
905     enum {
906         kSize = 32
907     };
908     int32_t storage[kSize/4];
909     char src[kSize];
910     sk_bzero(src, kSize);
911 
912     SkBinaryWriteBuffer writer(storage, kSize);
913     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
914     REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
915     writer.write(src, kSize - 4);
916     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
917     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
918     writer.writeInt(0);
919     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
920     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
921 
922     writer.reset(storage, kSize-4);
923     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
924     REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
925     writer.write(src, kSize - 4);
926     REPORTER_ASSERT(reporter, writer.usingInitialStorage());
927     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
928     writer.writeInt(0);
929     REPORTER_ASSERT(reporter, !writer.usingInitialStorage());   // this is the change
930     REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
931 }
932 
DEF_TEST(WriteBuffer_external_memory_textblob,reporter)933 DEF_TEST(WriteBuffer_external_memory_textblob, reporter) {
934     SkFont font;
935     font.setTypeface(SkTypeface::MakeDefault());
936 
937     SkTextBlobBuilder builder;
938     int glyph_count = 5;
939     const auto& run = builder.allocRun(font, glyph_count, 1.2f, 2.3f);
940     // allocRun() allocates only the glyph buffer.
941     std::fill(run.glyphs, run.glyphs + glyph_count, 0);
942     auto blob = builder.make();
943     SkSerialProcs procs;
944     AutoTMalloc<uint8_t> storage;
945     size_t blob_size = 0u;
946     size_t storage_size = 0u;
947 
948     blob_size = SkAlign4(blob->serialize(procs)->size());
949     REPORTER_ASSERT(reporter, blob_size > 4u);
950     storage_size = blob_size - 4;
951     storage.realloc(storage_size);
952     REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) == 0u);
953     storage_size = blob_size;
954     storage.realloc(storage_size);
955     REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) != 0u);
956 }
957 
DEF_TEST(WriteBuffer_external_memory_flattenable,reporter)958 DEF_TEST(WriteBuffer_external_memory_flattenable, reporter) {
959     SkScalar intervals[] = {1.f, 1.f};
960     auto path_effect = SkDashPathEffect::Make(intervals, 2, 0);
961     size_t path_size = SkAlign4(path_effect->serialize()->size());
962     REPORTER_ASSERT(reporter, path_size > 4u);
963     AutoTMalloc<uint8_t> storage;
964 
965     size_t storage_size = path_size - 4;
966     storage.realloc(storage_size);
967     REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) == 0u);
968 
969     storage_size = path_size;
970     storage.realloc(storage_size);
971     REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) != 0u);
972 }
973 
DEF_TEST(ReadBuffer_empty,reporter)974 DEF_TEST(ReadBuffer_empty, reporter) {
975     SkBinaryWriteBuffer writer;
976     writer.writeInt(123);
977     writer.writeDataAsByteArray(SkData::MakeEmpty().get());
978     writer.writeInt(321);
979 
980     size_t size = writer.bytesWritten();
981     SkAutoMalloc storage(size);
982     writer.writeToMemory(storage.get());
983 
984     SkReadBuffer reader(storage.get(), size);
985     REPORTER_ASSERT(reporter, reader.readInt() == 123);
986     auto data = reader.readByteArrayAsData();
987     REPORTER_ASSERT(reporter, data->size() == 0);
988     REPORTER_ASSERT(reporter, reader.readInt() == 321);
989 }
990