Home | History | Annotate | Download | only in tests
      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 
     22 static const uint32_t kArraySize = 64;
     23 static const int kBitmapSize = 256;
     24 
     25 template<typename T>
     26 static 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 
     35 template<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 
     45 template<> 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 
     54 template<> 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 
     63 template<> 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 
     72 template<> 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 
     81 template<> 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 
     90 template<> 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 
     99 template<> 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 
    108 template<> 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 
    117 template<> 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 
    126 template<typename T, bool testInvalid> struct SerializationTestUtils {
    127     static void InvalidateData(unsigned char* data) {}
    128 };
    129 
    130 template<> struct SerializationTestUtils<SkString, true> {
    131     static void InvalidateData(unsigned char* data) {
    132         data[3] |= 0x80; // Reverse sign of 1st integer
    133     }
    134 };
    135 
    136 template<typename T, bool testInvalid>
    137 static 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 
    167 template<typename T>
    168 static void TestObjectSerialization(T* testObj, skiatest::Reporter* reporter) {
    169     TestObjectSerializationNoAlign<T, false>(testObj, reporter);
    170     TestAlignment(testObj, reporter);
    171 }
    172 
    173 template<typename T>
    174 static 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 
    212 template<typename T>
    213 static 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 
    237 static 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 
    265 static 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 
    278 static 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 
    288 static 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 
    297 static 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 
    319 static void TestPictureTypefaceSerialization(skiatest::Reporter* reporter) {
    320     // Load typeface form file.
    321     // This test cannot run if there is no resource path.
    322     SkString resourcePath = GetResourcePath();
    323     if (resourcePath.isEmpty()) {
    324         SkDebugf("Could not run fontstream test because resourcePath not specified.");
    325         return;
    326     }
    327     SkString filename = SkOSPath::Join(resourcePath.c_str(), "test.ttc");
    328     SkTypeface* typeface = SkTypeface::CreateFromFile(filename.c_str(), 1);
    329     if (!typeface) {
    330         SkDebugf("Could not run fontstream test because test.ttc not found.");
    331         return;
    332     }
    333 
    334     // Create a paint with the typeface we loaded.
    335     SkPaint paint;
    336     paint.setColor(SK_ColorGRAY);
    337     paint.setTextSize(SkIntToScalar(30));
    338     SkSafeUnref(paint.setTypeface(typeface));
    339 
    340     // Paint some text.
    341     SkPictureRecorder recorder;
    342     SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
    343     SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
    344                                                SkIntToScalar(canvasRect.height()),
    345                                                NULL, 0);
    346     canvas->drawColor(SK_ColorWHITE);
    347     canvas->drawText("A!", 2, 24, 32, paint);
    348     SkAutoTUnref<SkPicture> picture(recorder.endRecording());
    349 
    350     // Serlialize picture and create its clone from stream.
    351     SkDynamicMemoryWStream stream;
    352     picture->serialize(&stream);
    353     SkAutoTUnref<SkStream> inputStream(stream.detachAsStream());
    354     SkAutoTUnref<SkPicture> loadedPicture(SkPicture::CreateFromStream(inputStream.get()));
    355 
    356     // Draw both original and clone picture and compare bitmaps -- they should be identical.
    357     SkBitmap origBitmap = draw_picture(*picture);
    358     SkBitmap destBitmap = draw_picture(*loadedPicture);
    359     compare_bitmaps(reporter, origBitmap, destBitmap);
    360 }
    361 
    362 static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
    363     bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
    364 }
    365 
    366 static void make_checkerboard_bitmap(SkBitmap& bitmap) {
    367     setup_bitmap_for_canvas(&bitmap);
    368 
    369     SkCanvas canvas(bitmap);
    370     canvas.clear(0x00000000);
    371     SkPaint darkPaint;
    372     darkPaint.setColor(0xFF804020);
    373     SkPaint lightPaint;
    374     lightPaint.setColor(0xFF244484);
    375     const int i = kBitmapSize / 8;
    376     const SkScalar f = SkIntToScalar(i);
    377     for (int y = 0; y < kBitmapSize; y += i) {
    378         for (int x = 0; x < kBitmapSize; x += i) {
    379             canvas.save();
    380             canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
    381             canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
    382             canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
    383             canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
    384             canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
    385             canvas.restore();
    386         }
    387     }
    388 }
    389 
    390 static void draw_something(SkCanvas* canvas) {
    391     SkPaint paint;
    392     SkBitmap bitmap;
    393     make_checkerboard_bitmap(bitmap);
    394 
    395     canvas->save();
    396     canvas->scale(0.5f, 0.5f);
    397     canvas->drawBitmap(bitmap, 0, 0, NULL);
    398     canvas->restore();
    399 
    400     const char beforeStr[] = "before circle";
    401     const char afterStr[] = "after circle";
    402 
    403     paint.setAntiAlias(true);
    404 
    405     paint.setColor(SK_ColorRED);
    406     canvas->drawData(beforeStr, sizeof(beforeStr));
    407     canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
    408     canvas->drawData(afterStr, sizeof(afterStr));
    409     paint.setColor(SK_ColorBLACK);
    410     paint.setTextSize(SkIntToScalar(kBitmapSize/3));
    411     canvas->drawText("Picture", 7, SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), paint);
    412 }
    413 
    414 DEF_TEST(Serialization, reporter) {
    415     // Test matrix serialization
    416     {
    417         SkMatrix matrix = SkMatrix::I();
    418         TestObjectSerialization(&matrix, reporter);
    419     }
    420 
    421     // Test path serialization
    422     {
    423         SkPath path;
    424         TestObjectSerialization(&path, reporter);
    425     }
    426 
    427     // Test region serialization
    428     {
    429         SkRegion region;
    430         TestObjectSerialization(&region, reporter);
    431     }
    432 
    433     // Test xfermode serialization
    434     {
    435         TestXfermodeSerialization(reporter);
    436     }
    437 
    438     // Test color filter serialization
    439     {
    440         TestColorFilterSerialization(reporter);
    441     }
    442 
    443     // Test string serialization
    444     {
    445         SkString string("string");
    446         TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
    447         TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
    448     }
    449 
    450     // Test rrect serialization
    451     {
    452         // SkRRect does not initialize anything.
    453         // An uninitialized SkRRect can be serialized,
    454         // but will branch on uninitialized data when deserialized.
    455         SkRRect rrect;
    456         SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
    457         SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
    458         rrect.setRectRadii(rect, corners);
    459         TestAlignment(&rrect, reporter);
    460     }
    461 
    462     // Test readByteArray
    463     {
    464         unsigned char data[kArraySize] = { 1, 2, 3 };
    465         TestArraySerialization(data, reporter);
    466     }
    467 
    468     // Test readColorArray
    469     {
    470         SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
    471         TestArraySerialization(data, reporter);
    472     }
    473 
    474     // Test readIntArray
    475     {
    476         int32_t data[kArraySize] = { 1, 2, 4, 8 };
    477         TestArraySerialization(data, reporter);
    478     }
    479 
    480     // Test readPointArray
    481     {
    482         SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
    483         TestArraySerialization(data, reporter);
    484     }
    485 
    486     // Test readScalarArray
    487     {
    488         SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
    489         TestArraySerialization(data, reporter);
    490     }
    491 
    492     // Test invalid deserializations
    493     {
    494         SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
    495 
    496         SkBitmap validBitmap;
    497         validBitmap.setInfo(info);
    498 
    499         // Create a bitmap with a really large height
    500         SkBitmap invalidBitmap;
    501         invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
    502 
    503         // The deserialization should succeed, and the rendering shouldn't crash,
    504         // even when the device fails to initialize, due to its size
    505         TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
    506     }
    507 
    508     // Test simple SkPicture serialization
    509     {
    510         SkPictureRecorder recorder;
    511         draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
    512                                                SkIntToScalar(kBitmapSize),
    513                                                NULL, 0));
    514         SkAutoTUnref<SkPicture> pict(recorder.endRecording());
    515 
    516         // Serialize picture
    517         SkWriteBuffer writer(SkWriteBuffer::kValidation_Flag);
    518         pict->flatten(writer);
    519         size_t size = writer.bytesWritten();
    520         SkAutoTMalloc<unsigned char> data(size);
    521         writer.writeToMemory(static_cast<void*>(data.get()));
    522 
    523         // Deserialize picture
    524         SkValidatingReadBuffer reader(static_cast<void*>(data.get()), size);
    525         SkAutoTUnref<SkPicture> readPict(
    526             SkPicture::CreateFromBuffer(reader));
    527         REPORTER_ASSERT(reporter, readPict.get());
    528     }
    529 
    530     TestPictureTypefaceSerialization(reporter);
    531 }
    532