1/*
2 * Copyright 2013 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "Resources.h"
9#include "SkCanvas.h"
10#include "SkFixed.h"
11#include "SkFontDescriptor.h"
12#include "SkImage.h"
13#include "SkImageSource.h"
14#include "SkMallocPixelRef.h"
15#include "SkOSFile.h"
16#include "SkPictureRecorder.h"
17#include "SkTableColorFilter.h"
18#include "SkTemplates.h"
19#include "SkTypeface.h"
20#include "SkWriteBuffer.h"
21#include "SkValidatingReadBuffer.h"
22#include "SkXfermodeImageFilter.h"
23#include "Test.h"
24
25static const uint32_t kArraySize = 64;
26static const int kBitmapSize = 256;
27
28template<typename T>
29static void TestAlignment(T* testObj, skiatest::Reporter* reporter) {
30    // Test memory read/write functions directly
31    unsigned char dataWritten[1024];
32    size_t bytesWrittenToMemory = testObj->writeToMemory(dataWritten);
33    REPORTER_ASSERT(reporter, SkAlign4(bytesWrittenToMemory) == bytesWrittenToMemory);
34    size_t bytesReadFromMemory = testObj->readFromMemory(dataWritten, bytesWrittenToMemory);
35    REPORTER_ASSERT(reporter, SkAlign4(bytesReadFromMemory) == bytesReadFromMemory);
36}
37
38template<typename T> struct SerializationUtils {
39    // Generic case for flattenables
40    static void Write(SkWriteBuffer& writer, const T* flattenable) {
41        writer.writeFlattenable(flattenable);
42    }
43    static void Read(SkValidatingReadBuffer& reader, T** flattenable) {
44        *flattenable = (T*)reader.readFlattenable(T::GetFlattenableType());
45    }
46};
47
48template<> struct SerializationUtils<SkMatrix> {
49    static void Write(SkWriteBuffer& writer, const SkMatrix* matrix) {
50        writer.writeMatrix(*matrix);
51    }
52    static void Read(SkValidatingReadBuffer& reader, SkMatrix* matrix) {
53        reader.readMatrix(matrix);
54    }
55};
56
57template<> struct SerializationUtils<SkPath> {
58    static void Write(SkWriteBuffer& writer, const SkPath* path) {
59        writer.writePath(*path);
60    }
61    static void Read(SkValidatingReadBuffer& reader, SkPath* path) {
62        reader.readPath(path);
63    }
64};
65
66template<> struct SerializationUtils<SkRegion> {
67    static void Write(SkWriteBuffer& writer, const SkRegion* region) {
68        writer.writeRegion(*region);
69    }
70    static void Read(SkValidatingReadBuffer& reader, SkRegion* region) {
71        reader.readRegion(region);
72    }
73};
74
75template<> struct SerializationUtils<SkString> {
76    static void Write(SkWriteBuffer& writer, const SkString* string) {
77        writer.writeString(string->c_str());
78    }
79    static void Read(SkValidatingReadBuffer& reader, SkString* string) {
80        reader.readString(string);
81    }
82};
83
84template<> struct SerializationUtils<unsigned char> {
85    static void Write(SkWriteBuffer& writer, unsigned char* data, uint32_t arraySize) {
86        writer.writeByteArray(data, arraySize);
87    }
88    static bool Read(SkValidatingReadBuffer& reader, unsigned char* data, uint32_t arraySize) {
89        return reader.readByteArray(data, arraySize);
90    }
91};
92
93template<> struct SerializationUtils<SkColor> {
94    static void Write(SkWriteBuffer& writer, SkColor* data, uint32_t arraySize) {
95        writer.writeColorArray(data, arraySize);
96    }
97    static bool Read(SkValidatingReadBuffer& reader, SkColor* data, uint32_t arraySize) {
98        return reader.readColorArray(data, arraySize);
99    }
100};
101
102template<> struct SerializationUtils<int32_t> {
103    static void Write(SkWriteBuffer& writer, int32_t* data, uint32_t arraySize) {
104        writer.writeIntArray(data, arraySize);
105    }
106    static bool Read(SkValidatingReadBuffer& reader, int32_t* data, uint32_t arraySize) {
107        return reader.readIntArray(data, arraySize);
108    }
109};
110
111template<> struct SerializationUtils<SkPoint> {
112    static void Write(SkWriteBuffer& writer, SkPoint* data, uint32_t arraySize) {
113        writer.writePointArray(data, arraySize);
114    }
115    static bool Read(SkValidatingReadBuffer& reader, SkPoint* data, uint32_t arraySize) {
116        return reader.readPointArray(data, arraySize);
117    }
118};
119
120template<> struct SerializationUtils<SkScalar> {
121    static void Write(SkWriteBuffer& writer, SkScalar* data, uint32_t arraySize) {
122        writer.writeScalarArray(data, arraySize);
123    }
124    static bool Read(SkValidatingReadBuffer& reader, SkScalar* data, uint32_t arraySize) {
125        return reader.readScalarArray(data, arraySize);
126    }
127};
128
129template<typename T, bool testInvalid> struct SerializationTestUtils {
130    static void InvalidateData(unsigned char* data) {}
131};
132
133template<> struct SerializationTestUtils<SkString, true> {
134    static void InvalidateData(unsigned char* data) {
135        data[3] |= 0x80; // Reverse sign of 1st integer
136    }
137};
138
139template<typename T, bool testInvalid>
140static void TestObjectSerializationNoAlign(T* testObj, skiatest::Reporter* reporter) {
141    SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
142    SerializationUtils<T>::Write(writer, testObj);
143    size_t bytesWritten = writer.bytesWritten();
144    REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
145
146    unsigned char dataWritten[1024];
147    writer.writeToMemory(dataWritten);
148
149    SerializationTestUtils<T, testInvalid>::InvalidateData(dataWritten);
150
151    // Make sure this fails when it should (test with smaller size, but still multiple of 4)
152    SkValidatingReadBuffer buffer(dataWritten, bytesWritten - 4);
153    T obj;
154    SerializationUtils<T>::Read(buffer, &obj);
155    REPORTER_ASSERT(reporter, !buffer.isValid());
156
157    // Make sure this succeeds when it should
158    SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
159    const unsigned char* peekBefore = static_cast<const unsigned char*>(buffer2.skip(0));
160    T obj2;
161    SerializationUtils<T>::Read(buffer2, &obj2);
162    const unsigned char* peekAfter = static_cast<const unsigned char*>(buffer2.skip(0));
163    // This should have succeeded, since there are enough bytes to read this
164    REPORTER_ASSERT(reporter, buffer2.isValid() == !testInvalid);
165    // Note: This following test should always succeed, regardless of whether the buffer is valid,
166    // since if it is invalid, it will simply skip to the end, as if it had read the whole buffer.
167    REPORTER_ASSERT(reporter, static_cast<size_t>(peekAfter - peekBefore) == bytesWritten);
168}
169
170template<typename T>
171static void TestObjectSerialization(T* testObj, skiatest::Reporter* reporter) {
172    TestObjectSerializationNoAlign<T, false>(testObj, reporter);
173    TestAlignment(testObj, reporter);
174}
175
176template<typename T>
177static T* TestFlattenableSerialization(T* testObj, bool shouldSucceed,
178                                       skiatest::Reporter* reporter) {
179    SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
180    SerializationUtils<T>::Write(writer, testObj);
181    size_t bytesWritten = writer.bytesWritten();
182    REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
183
184    unsigned char dataWritten[4096];
185    SkASSERT(bytesWritten <= sizeof(dataWritten));
186    writer.writeToMemory(dataWritten);
187
188    // Make sure this fails when it should (test with smaller size, but still multiple of 4)
189    SkValidatingReadBuffer buffer(dataWritten, bytesWritten - 4);
190    T* obj = nullptr;
191    SerializationUtils<T>::Read(buffer, &obj);
192    REPORTER_ASSERT(reporter, !buffer.isValid());
193    REPORTER_ASSERT(reporter, nullptr == obj);
194
195    // Make sure this succeeds when it should
196    SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
197    const unsigned char* peekBefore = static_cast<const unsigned char*>(buffer2.skip(0));
198    T* obj2 = nullptr;
199    SerializationUtils<T>::Read(buffer2, &obj2);
200    const unsigned char* peekAfter = static_cast<const unsigned char*>(buffer2.skip(0));
201    if (shouldSucceed) {
202        // This should have succeeded, since there are enough bytes to read this
203        REPORTER_ASSERT(reporter, buffer2.isValid());
204        REPORTER_ASSERT(reporter, static_cast<size_t>(peekAfter - peekBefore) == bytesWritten);
205        REPORTER_ASSERT(reporter, obj2);
206    } else {
207        // If the deserialization was supposed to fail, make sure it did
208        REPORTER_ASSERT(reporter, !buffer.isValid());
209        REPORTER_ASSERT(reporter, nullptr == obj2);
210    }
211
212    return obj2; // Return object to perform further validity tests on it
213}
214
215template<typename T>
216static void TestArraySerialization(T* data, skiatest::Reporter* reporter) {
217    SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
218    SerializationUtils<T>::Write(writer, data, kArraySize);
219    size_t bytesWritten = writer.bytesWritten();
220    // This should write the length (in 4 bytes) and the array
221    REPORTER_ASSERT(reporter, (4 + kArraySize * sizeof(T)) == bytesWritten);
222
223    unsigned char dataWritten[1024];
224    writer.writeToMemory(dataWritten);
225
226    // Make sure this fails when it should
227    SkValidatingReadBuffer buffer(dataWritten, bytesWritten);
228    T dataRead[kArraySize];
229    bool success = SerializationUtils<T>::Read(buffer, dataRead, kArraySize / 2);
230    // This should have failed, since the provided size was too small
231    REPORTER_ASSERT(reporter, !success);
232
233    // Make sure this succeeds when it should
234    SkValidatingReadBuffer buffer2(dataWritten, bytesWritten);
235    success = SerializationUtils<T>::Read(buffer2, dataRead, kArraySize);
236    // This should have succeeded, since there are enough bytes to read this
237    REPORTER_ASSERT(reporter, success);
238}
239
240static void TestBitmapSerialization(const SkBitmap& validBitmap,
241                                    const SkBitmap& invalidBitmap,
242                                    bool shouldSucceed,
243                                    skiatest::Reporter* reporter) {
244    SkAutoTUnref<SkImage> validImage(SkImage::NewFromBitmap(validBitmap));
245    SkAutoTUnref<SkImageFilter> validBitmapSource(SkImageSource::Create(validImage));
246    SkAutoTUnref<SkImage> invalidImage(SkImage::NewFromBitmap(invalidBitmap));
247    SkAutoTUnref<SkImageFilter> invalidBitmapSource(SkImageSource::Create(invalidImage));
248    SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(SkXfermode::kSrcOver_Mode));
249    SkAutoTUnref<SkImageFilter> xfermodeImageFilter(
250        SkXfermodeImageFilter::Create(mode, invalidBitmapSource, validBitmapSource));
251
252    SkAutoTUnref<SkImageFilter> deserializedFilter(
253        TestFlattenableSerialization<SkImageFilter>(
254            xfermodeImageFilter, shouldSucceed, reporter));
255
256    // Try to render a small bitmap using the invalid deserialized filter
257    // to make sure we don't crash while trying to render it
258    if (shouldSucceed) {
259        SkBitmap bitmap;
260        bitmap.allocN32Pixels(24, 24);
261        SkCanvas canvas(bitmap);
262        canvas.clear(0x00000000);
263        SkPaint paint;
264        paint.setImageFilter(deserializedFilter);
265        canvas.clipRect(SkRect::MakeXYWH(0, 0, SkIntToScalar(24), SkIntToScalar(24)));
266        canvas.drawBitmap(bitmap, 0, 0, &paint);
267    }
268}
269
270static void TestXfermodeSerialization(skiatest::Reporter* reporter) {
271    for (size_t i = 0; i <= SkXfermode::kLastMode; ++i) {
272        if (i == SkXfermode::kSrcOver_Mode) {
273            // skip SrcOver, as it is allowed to return nullptr from Create()
274            continue;
275        }
276        SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(static_cast<SkXfermode::Mode>(i)));
277        REPORTER_ASSERT(reporter, mode.get());
278        SkAutoTUnref<SkXfermode> copy(
279            TestFlattenableSerialization<SkXfermode>(mode.get(), true, reporter));
280    }
281}
282
283static void TestColorFilterSerialization(skiatest::Reporter* reporter) {
284    uint8_t table[256];
285    for (int i = 0; i < 256; ++i) {
286        table[i] = (i * 41) % 256;
287    }
288    SkAutoTUnref<SkColorFilter> colorFilter(SkTableColorFilter::Create(table));
289    SkAutoTUnref<SkColorFilter> copy(
290        TestFlattenableSerialization<SkColorFilter>(colorFilter.get(), true, reporter));
291}
292
293static SkBitmap draw_picture(SkPicture& picture) {
294     SkBitmap bitmap;
295     bitmap.allocN32Pixels(SkScalarCeilToInt(picture.cullRect().width()),
296                           SkScalarCeilToInt(picture.cullRect().height()));
297     SkCanvas canvas(bitmap);
298     picture.playback(&canvas);
299     return bitmap;
300}
301
302static void compare_bitmaps(skiatest::Reporter* reporter,
303                            const SkBitmap& b1, const SkBitmap& b2) {
304    REPORTER_ASSERT(reporter, b1.width() == b2.width());
305    REPORTER_ASSERT(reporter, b1.height() == b2.height());
306    SkAutoLockPixels autoLockPixels1(b1);
307    SkAutoLockPixels autoLockPixels2(b2);
308
309    if ((b1.width() != b2.width()) ||
310        (b1.height() != b2.height())) {
311        return;
312    }
313
314    int pixelErrors = 0;
315    for (int y = 0; y < b2.height(); ++y) {
316        for (int x = 0; x < b2.width(); ++x) {
317            if (b1.getColor(x, y) != b2.getColor(x, y))
318                ++pixelErrors;
319        }
320    }
321    REPORTER_ASSERT(reporter, 0 == pixelErrors);
322}
323static void serialize_and_compare_typeface(SkTypeface* typeface, const char* text,
324                                           skiatest::Reporter* reporter)
325{
326    // Create a paint with the typeface.
327    SkPaint paint;
328    paint.setColor(SK_ColorGRAY);
329    paint.setTextSize(SkIntToScalar(30));
330    paint.setTypeface(typeface);
331
332    // Paint some text.
333    SkPictureRecorder recorder;
334    SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
335    SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
336                                               SkIntToScalar(canvasRect.height()),
337                                               nullptr, 0);
338    canvas->drawColor(SK_ColorWHITE);
339    canvas->drawText(text, 2, 24, 32, paint);
340    SkAutoTUnref<SkPicture> picture(recorder.endRecording());
341
342    // Serlialize picture and create its clone from stream.
343    SkDynamicMemoryWStream stream;
344    picture->serialize(&stream);
345    SkAutoTDelete<SkStream> inputStream(stream.detachAsStream());
346    SkAutoTUnref<SkPicture> loadedPicture(SkPicture::CreateFromStream(inputStream.get()));
347
348    // Draw both original and clone picture and compare bitmaps -- they should be identical.
349    SkBitmap origBitmap = draw_picture(*picture);
350    SkBitmap destBitmap = draw_picture(*loadedPicture);
351    compare_bitmaps(reporter, origBitmap, destBitmap);
352}
353
354static void TestPictureTypefaceSerialization(skiatest::Reporter* reporter) {
355    {
356        // Load typeface from file to test CreateFromFile with index.
357        SkString filename = GetResourcePath("/fonts/test.ttc");
358        SkAutoTUnref<SkTypeface> typeface(SkTypeface::CreateFromFile(filename.c_str(), 1));
359        if (!typeface) {
360            INFOF(reporter, "Could not run fontstream test because test.ttc not found.");
361        } else {
362            serialize_and_compare_typeface(typeface, "A!", reporter);
363        }
364    }
365
366    {
367        // Load typeface as stream to create with axis settings.
368        SkAutoTDelete<SkStreamAsset> distortable(GetResourceAsStream("/fonts/Distortable.ttf"));
369        if (!distortable) {
370            INFOF(reporter, "Could not run fontstream test because Distortable.ttf not found.");
371        } else {
372            SkFixed axis = SK_FixedSqrt2;
373            SkAutoTUnref<SkTypeface> typeface(SkTypeface::CreateFromFontData(
374                new SkFontData(distortable.detach(), 0, &axis, 1)));
375            if (!typeface) {
376                INFOF(reporter, "Could not run fontstream test because Distortable.ttf not created.");
377            } else {
378                serialize_and_compare_typeface(typeface, "abc", reporter);
379            }
380        }
381    }
382}
383
384static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
385    bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
386}
387
388static void make_checkerboard_bitmap(SkBitmap& bitmap) {
389    setup_bitmap_for_canvas(&bitmap);
390
391    SkCanvas canvas(bitmap);
392    canvas.clear(0x00000000);
393    SkPaint darkPaint;
394    darkPaint.setColor(0xFF804020);
395    SkPaint lightPaint;
396    lightPaint.setColor(0xFF244484);
397    const int i = kBitmapSize / 8;
398    const SkScalar f = SkIntToScalar(i);
399    for (int y = 0; y < kBitmapSize; y += i) {
400        for (int x = 0; x < kBitmapSize; x += i) {
401            canvas.save();
402            canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
403            canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
404            canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
405            canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
406            canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
407            canvas.restore();
408        }
409    }
410}
411
412static void draw_something(SkCanvas* canvas) {
413    SkPaint paint;
414    SkBitmap bitmap;
415    make_checkerboard_bitmap(bitmap);
416
417    canvas->save();
418    canvas->scale(0.5f, 0.5f);
419    canvas->drawBitmap(bitmap, 0, 0, nullptr);
420    canvas->restore();
421
422    paint.setAntiAlias(true);
423
424    paint.setColor(SK_ColorRED);
425    canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
426    paint.setColor(SK_ColorBLACK);
427    paint.setTextSize(SkIntToScalar(kBitmapSize/3));
428    canvas->drawText("Picture", 7, SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), paint);
429}
430
431DEF_TEST(Serialization, reporter) {
432    // Test matrix serialization
433    {
434        SkMatrix matrix = SkMatrix::I();
435        TestObjectSerialization(&matrix, reporter);
436    }
437
438    // Test path serialization
439    {
440        SkPath path;
441        TestObjectSerialization(&path, reporter);
442    }
443
444    // Test region serialization
445    {
446        SkRegion region;
447        TestObjectSerialization(&region, reporter);
448    }
449
450    // Test xfermode serialization
451    {
452        TestXfermodeSerialization(reporter);
453    }
454
455    // Test color filter serialization
456    {
457        TestColorFilterSerialization(reporter);
458    }
459
460    // Test string serialization
461    {
462        SkString string("string");
463        TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
464        TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
465    }
466
467    // Test rrect serialization
468    {
469        // SkRRect does not initialize anything.
470        // An uninitialized SkRRect can be serialized,
471        // but will branch on uninitialized data when deserialized.
472        SkRRect rrect;
473        SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
474        SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
475        rrect.setRectRadii(rect, corners);
476        TestAlignment(&rrect, reporter);
477    }
478
479    // Test readByteArray
480    {
481        unsigned char data[kArraySize] = { 1, 2, 3 };
482        TestArraySerialization(data, reporter);
483    }
484
485    // Test readColorArray
486    {
487        SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
488        TestArraySerialization(data, reporter);
489    }
490
491    // Test readIntArray
492    {
493        int32_t data[kArraySize] = { 1, 2, 4, 8 };
494        TestArraySerialization(data, reporter);
495    }
496
497    // Test readPointArray
498    {
499        SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
500        TestArraySerialization(data, reporter);
501    }
502
503    // Test readScalarArray
504    {
505        SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
506        TestArraySerialization(data, reporter);
507    }
508
509    // Test invalid deserializations
510    {
511        SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
512
513        SkBitmap validBitmap;
514        validBitmap.setInfo(info);
515
516        // Create a bitmap with a really large height
517        SkBitmap invalidBitmap;
518        invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
519
520        // The deserialization should succeed, and the rendering shouldn't crash,
521        // even when the device fails to initialize, due to its size
522        TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
523    }
524
525    // Test simple SkPicture serialization
526    {
527        SkPictureRecorder recorder;
528        draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
529                                               SkIntToScalar(kBitmapSize),
530                                               nullptr, 0));
531        SkAutoTUnref<SkPicture> pict(recorder.endRecording());
532
533        // Serialize picture
534        SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
535        pict->flatten(writer);
536        size_t size = writer.bytesWritten();
537        SkAutoTMalloc<unsigned char> data(size);
538        writer.writeToMemory(static_cast<void*>(data.get()));
539
540        // Deserialize picture
541        SkValidatingReadBuffer reader(static_cast<void*>(data.get()), size);
542        SkAutoTUnref<SkPicture> readPict(
543            SkPicture::CreateFromBuffer(reader));
544        REPORTER_ASSERT(reporter, readPict.get());
545    }
546
547    TestPictureTypefaceSerialization(reporter);
548}
549