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