SerializationTest.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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. #include "include/core/SkCanvas.h"
  8. #include "include/core/SkImage.h"
  9. #include "include/core/SkMallocPixelRef.h"
  10. #include "include/core/SkPictureRecorder.h"
  11. #include "include/core/SkTextBlob.h"
  12. #include "include/core/SkTypeface.h"
  13. #include "include/effects/SkDashPathEffect.h"
  14. #include "include/effects/SkImageSource.h"
  15. #include "include/effects/SkTableColorFilter.h"
  16. #include "include/effects/SkXfermodeImageFilter.h"
  17. #include "include/private/SkFixed.h"
  18. #include "include/private/SkTemplates.h"
  19. #include "src/core/SkAnnotationKeys.h"
  20. #include "src/core/SkFontDescriptor.h"
  21. #include "src/core/SkMakeUnique.h"
  22. #include "src/core/SkMatrixPriv.h"
  23. #include "src/core/SkNormalSource.h"
  24. #include "src/core/SkOSFile.h"
  25. #include "src/core/SkPicturePriv.h"
  26. #include "src/core/SkReadBuffer.h"
  27. #include "src/core/SkWriteBuffer.h"
  28. #include "src/shaders/SkLightingShader.h"
  29. #include "src/shaders/SkShaderBase.h"
  30. #include "tests/Test.h"
  31. #include "tools/Resources.h"
  32. #include "tools/ToolUtils.h"
  33. static const uint32_t kArraySize = 64;
  34. static const int kBitmapSize = 256;
  35. class SerializationTest {
  36. public:
  37. template<typename T>
  38. static void TestAlignment(T* testObj, skiatest::Reporter* reporter) {
  39. // Test memory read/write functions directly
  40. unsigned char dataWritten[1024];
  41. size_t bytesWrittenToMemory = testObj->writeToMemory(dataWritten);
  42. REPORTER_ASSERT(reporter, SkAlign4(bytesWrittenToMemory) == bytesWrittenToMemory);
  43. size_t bytesReadFromMemory = testObj->readFromMemory(dataWritten, bytesWrittenToMemory);
  44. REPORTER_ASSERT(reporter, SkAlign4(bytesReadFromMemory) == bytesReadFromMemory);
  45. }
  46. };
  47. template<typename T> struct SerializationUtils {
  48. // Generic case for flattenables
  49. static void Write(SkWriteBuffer& writer, const T* flattenable) {
  50. writer.writeFlattenable(flattenable);
  51. }
  52. static void Read(SkReadBuffer& reader, T** flattenable) {
  53. *flattenable = (T*)reader.readFlattenable(T::GetFlattenableType());
  54. }
  55. };
  56. template<> struct SerializationUtils<SkMatrix> {
  57. static void Write(SkWriteBuffer& writer, const SkMatrix* matrix) {
  58. writer.writeMatrix(*matrix);
  59. }
  60. static void Read(SkReadBuffer& reader, SkMatrix* matrix) {
  61. reader.readMatrix(matrix);
  62. }
  63. };
  64. template<> struct SerializationUtils<SkPath> {
  65. static void Write(SkWriteBuffer& writer, const SkPath* path) {
  66. writer.writePath(*path);
  67. }
  68. static void Read(SkReadBuffer& reader, SkPath* path) {
  69. reader.readPath(path);
  70. }
  71. };
  72. template<> struct SerializationUtils<SkRegion> {
  73. static void Write(SkWriteBuffer& writer, const SkRegion* region) {
  74. writer.writeRegion(*region);
  75. }
  76. static void Read(SkReadBuffer& reader, SkRegion* region) {
  77. reader.readRegion(region);
  78. }
  79. };
  80. template<> struct SerializationUtils<SkString> {
  81. static void Write(SkWriteBuffer& writer, const SkString* string) {
  82. writer.writeString(string->c_str());
  83. }
  84. static void Read(SkReadBuffer& reader, SkString* string) {
  85. reader.readString(string);
  86. }
  87. };
  88. template<> struct SerializationUtils<unsigned char> {
  89. static void Write(SkWriteBuffer& writer, unsigned char* data, uint32_t arraySize) {
  90. writer.writeByteArray(data, arraySize);
  91. }
  92. static bool Read(SkReadBuffer& reader, unsigned char* data, uint32_t arraySize) {
  93. return reader.readByteArray(data, arraySize);
  94. }
  95. };
  96. template<> struct SerializationUtils<SkColor> {
  97. static void Write(SkWriteBuffer& writer, SkColor* data, uint32_t arraySize) {
  98. writer.writeColorArray(data, arraySize);
  99. }
  100. static bool Read(SkReadBuffer& reader, SkColor* data, uint32_t arraySize) {
  101. return reader.readColorArray(data, arraySize);
  102. }
  103. };
  104. template<> struct SerializationUtils<SkColor4f> {
  105. static void Write(SkWriteBuffer& writer, SkColor4f* data, uint32_t arraySize) {
  106. writer.writeColor4fArray(data, arraySize);
  107. }
  108. static bool Read(SkReadBuffer& reader, SkColor4f* data, uint32_t arraySize) {
  109. return reader.readColor4fArray(data, arraySize);
  110. }
  111. };
  112. template<> struct SerializationUtils<int32_t> {
  113. static void Write(SkWriteBuffer& writer, int32_t* data, uint32_t arraySize) {
  114. writer.writeIntArray(data, arraySize);
  115. }
  116. static bool Read(SkReadBuffer& reader, int32_t* data, uint32_t arraySize) {
  117. return reader.readIntArray(data, arraySize);
  118. }
  119. };
  120. template<> struct SerializationUtils<SkPoint> {
  121. static void Write(SkWriteBuffer& writer, SkPoint* data, uint32_t arraySize) {
  122. writer.writePointArray(data, arraySize);
  123. }
  124. static bool Read(SkReadBuffer& reader, SkPoint* data, uint32_t arraySize) {
  125. return reader.readPointArray(data, arraySize);
  126. }
  127. };
  128. template<> struct SerializationUtils<SkPoint3> {
  129. static void Write(SkWriteBuffer& writer, const SkPoint3* data) {
  130. writer.writePoint3(*data);
  131. }
  132. static void Read(SkReadBuffer& reader, SkPoint3* data) {
  133. reader.readPoint3(data);
  134. }
  135. };
  136. template<> struct SerializationUtils<SkScalar> {
  137. static void Write(SkWriteBuffer& writer, SkScalar* data, uint32_t arraySize) {
  138. writer.writeScalarArray(data, arraySize);
  139. }
  140. static bool Read(SkReadBuffer& reader, SkScalar* data, uint32_t arraySize) {
  141. return reader.readScalarArray(data, arraySize);
  142. }
  143. };
  144. template<typename T, bool testInvalid> struct SerializationTestUtils {
  145. static void InvalidateData(unsigned char* data) {}
  146. };
  147. template<> struct SerializationTestUtils<SkString, true> {
  148. static void InvalidateData(unsigned char* data) {
  149. data[3] |= 0x80; // Reverse sign of 1st integer
  150. }
  151. };
  152. template<typename T, bool testInvalid>
  153. static void TestObjectSerializationNoAlign(T* testObj, skiatest::Reporter* reporter) {
  154. SkBinaryWriteBuffer writer;
  155. SerializationUtils<T>::Write(writer, testObj);
  156. size_t bytesWritten = writer.bytesWritten();
  157. REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
  158. unsigned char dataWritten[1024];
  159. writer.writeToMemory(dataWritten);
  160. SerializationTestUtils<T, testInvalid>::InvalidateData(dataWritten);
  161. // Make sure this fails when it should (test with smaller size, but still multiple of 4)
  162. SkReadBuffer buffer(dataWritten, bytesWritten - 4);
  163. T obj;
  164. SerializationUtils<T>::Read(buffer, &obj);
  165. REPORTER_ASSERT(reporter, !buffer.isValid());
  166. // Make sure this succeeds when it should
  167. SkReadBuffer buffer2(dataWritten, bytesWritten);
  168. size_t offsetBefore = buffer2.offset();
  169. T obj2;
  170. SerializationUtils<T>::Read(buffer2, &obj2);
  171. size_t offsetAfter = buffer2.offset();
  172. // This should have succeeded, since there are enough bytes to read this
  173. REPORTER_ASSERT(reporter, buffer2.isValid() == !testInvalid);
  174. // Note: This following test should always succeed, regardless of whether the buffer is valid,
  175. // since if it is invalid, it will simply skip to the end, as if it had read the whole buffer.
  176. REPORTER_ASSERT(reporter, offsetAfter - offsetBefore == bytesWritten);
  177. }
  178. template<typename T>
  179. static void TestObjectSerialization(T* testObj, skiatest::Reporter* reporter) {
  180. TestObjectSerializationNoAlign<T, false>(testObj, reporter);
  181. SerializationTest::TestAlignment(testObj, reporter);
  182. }
  183. template<typename T>
  184. static T* TestFlattenableSerialization(T* testObj, bool shouldSucceed,
  185. skiatest::Reporter* reporter) {
  186. SkBinaryWriteBuffer writer;
  187. SerializationUtils<T>::Write(writer, testObj);
  188. size_t bytesWritten = writer.bytesWritten();
  189. REPORTER_ASSERT(reporter, SkAlign4(bytesWritten) == bytesWritten);
  190. SkASSERT(bytesWritten <= 4096);
  191. unsigned char dataWritten[4096];
  192. writer.writeToMemory(dataWritten);
  193. // Make sure this fails when it should (test with smaller size, but still multiple of 4)
  194. SkReadBuffer buffer(dataWritten, bytesWritten - 4);
  195. T* obj = nullptr;
  196. SerializationUtils<T>::Read(buffer, &obj);
  197. REPORTER_ASSERT(reporter, !buffer.isValid());
  198. REPORTER_ASSERT(reporter, nullptr == obj);
  199. // Make sure this succeeds when it should
  200. SkReadBuffer buffer2(dataWritten, bytesWritten);
  201. const unsigned char* peekBefore = static_cast<const unsigned char*>(buffer2.skip(0));
  202. T* obj2 = nullptr;
  203. SerializationUtils<T>::Read(buffer2, &obj2);
  204. const unsigned char* peekAfter = static_cast<const unsigned char*>(buffer2.skip(0));
  205. if (shouldSucceed) {
  206. // This should have succeeded, since there are enough bytes to read this
  207. REPORTER_ASSERT(reporter, buffer2.isValid());
  208. REPORTER_ASSERT(reporter, static_cast<size_t>(peekAfter - peekBefore) == bytesWritten);
  209. REPORTER_ASSERT(reporter, obj2);
  210. } else {
  211. // If the deserialization was supposed to fail, make sure it did
  212. REPORTER_ASSERT(reporter, !buffer.isValid());
  213. REPORTER_ASSERT(reporter, nullptr == obj2);
  214. }
  215. return obj2; // Return object to perform further validity tests on it
  216. }
  217. template<typename T>
  218. static void TestArraySerialization(T* data, skiatest::Reporter* reporter) {
  219. SkBinaryWriteBuffer writer;
  220. SerializationUtils<T>::Write(writer, data, kArraySize);
  221. size_t bytesWritten = writer.bytesWritten();
  222. // This should write the length (in 4 bytes) and the array
  223. REPORTER_ASSERT(reporter, (4 + kArraySize * sizeof(T)) == bytesWritten);
  224. unsigned char dataWritten[2048];
  225. writer.writeToMemory(dataWritten);
  226. // Make sure this fails when it should
  227. SkReadBuffer 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. // Make sure this succeeds when it should
  233. SkReadBuffer buffer2(dataWritten, bytesWritten);
  234. success = SerializationUtils<T>::Read(buffer2, dataRead, kArraySize);
  235. // This should have succeeded, since there are enough bytes to read this
  236. REPORTER_ASSERT(reporter, success);
  237. }
  238. static void TestBitmapSerialization(const SkBitmap& validBitmap,
  239. const SkBitmap& invalidBitmap,
  240. bool shouldSucceed,
  241. skiatest::Reporter* reporter) {
  242. sk_sp<SkImage> validImage(SkImage::MakeFromBitmap(validBitmap));
  243. sk_sp<SkImageFilter> validBitmapSource(SkImageSource::Make(std::move(validImage)));
  244. sk_sp<SkImage> invalidImage(SkImage::MakeFromBitmap(invalidBitmap));
  245. sk_sp<SkImageFilter> invalidBitmapSource(SkImageSource::Make(std::move(invalidImage)));
  246. sk_sp<SkImageFilter> xfermodeImageFilter(
  247. SkXfermodeImageFilter::Make(SkBlendMode::kSrcOver,
  248. std::move(invalidBitmapSource),
  249. std::move(validBitmapSource), nullptr));
  250. sk_sp<SkImageFilter> deserializedFilter(
  251. TestFlattenableSerialization<SkImageFilter>(
  252. xfermodeImageFilter.get(), shouldSucceed, reporter));
  253. // Try to render a small bitmap using the invalid deserialized filter
  254. // to make sure we don't crash while trying to render it
  255. if (shouldSucceed) {
  256. SkBitmap bitmap;
  257. bitmap.allocN32Pixels(24, 24);
  258. SkCanvas canvas(bitmap);
  259. canvas.clear(0x00000000);
  260. SkPaint paint;
  261. paint.setImageFilter(deserializedFilter);
  262. canvas.clipRect(SkRect::MakeXYWH(0, 0, SkIntToScalar(24), SkIntToScalar(24)));
  263. canvas.drawBitmap(bitmap, 0, 0, &paint);
  264. }
  265. }
  266. static void TestColorFilterSerialization(skiatest::Reporter* reporter) {
  267. uint8_t table[256];
  268. for (int i = 0; i < 256; ++i) {
  269. table[i] = (i * 41) % 256;
  270. }
  271. auto colorFilter(SkTableColorFilter::Make(table));
  272. sk_sp<SkColorFilter> copy(
  273. TestFlattenableSerialization<SkColorFilter>(colorFilter.get(), true, reporter));
  274. }
  275. static SkBitmap draw_picture(SkPicture& picture) {
  276. SkBitmap bitmap;
  277. bitmap.allocN32Pixels(SkScalarCeilToInt(picture.cullRect().width()),
  278. SkScalarCeilToInt(picture.cullRect().height()));
  279. SkCanvas canvas(bitmap);
  280. picture.playback(&canvas);
  281. return bitmap;
  282. }
  283. static void compare_bitmaps(skiatest::Reporter* reporter,
  284. const SkBitmap& b1, const SkBitmap& b2) {
  285. REPORTER_ASSERT(reporter, b1.width() == b2.width());
  286. REPORTER_ASSERT(reporter, b1.height() == b2.height());
  287. if ((b1.width() != b2.width()) ||
  288. (b1.height() != b2.height())) {
  289. return;
  290. }
  291. int pixelErrors = 0;
  292. for (int y = 0; y < b2.height(); ++y) {
  293. for (int x = 0; x < b2.width(); ++x) {
  294. if (b1.getColor(x, y) != b2.getColor(x, y))
  295. ++pixelErrors;
  296. }
  297. }
  298. REPORTER_ASSERT(reporter, 0 == pixelErrors);
  299. }
  300. static void serialize_and_compare_typeface(sk_sp<SkTypeface> typeface, const char* text,
  301. skiatest::Reporter* reporter)
  302. {
  303. // Create a font with the typeface.
  304. SkPaint paint;
  305. paint.setColor(SK_ColorGRAY);
  306. SkFont font(std::move(typeface), 30);
  307. // Paint some text.
  308. SkPictureRecorder recorder;
  309. SkIRect canvasRect = SkIRect::MakeWH(kBitmapSize, kBitmapSize);
  310. SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(canvasRect.width()),
  311. SkIntToScalar(canvasRect.height()),
  312. nullptr, 0);
  313. canvas->drawColor(SK_ColorWHITE);
  314. canvas->drawString(text, 24, 32, font, paint);
  315. sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
  316. // Serlialize picture and create its clone from stream.
  317. SkDynamicMemoryWStream stream;
  318. picture->serialize(&stream);
  319. std::unique_ptr<SkStream> inputStream(stream.detachAsStream());
  320. sk_sp<SkPicture> loadedPicture(SkPicture::MakeFromStream(inputStream.get()));
  321. // Draw both original and clone picture and compare bitmaps -- they should be identical.
  322. SkBitmap origBitmap = draw_picture(*picture);
  323. SkBitmap destBitmap = draw_picture(*loadedPicture);
  324. compare_bitmaps(reporter, origBitmap, destBitmap);
  325. }
  326. static void TestPictureTypefaceSerialization(skiatest::Reporter* reporter) {
  327. {
  328. // Load typeface from file to test CreateFromFile with index.
  329. auto typeface = MakeResourceAsTypeface("fonts/test.ttc", 1);
  330. if (!typeface) {
  331. INFOF(reporter, "Could not run fontstream test because test.ttc not found.");
  332. } else {
  333. serialize_and_compare_typeface(std::move(typeface), "A!", reporter);
  334. }
  335. }
  336. {
  337. // Load typeface as stream to create with axis settings.
  338. std::unique_ptr<SkStreamAsset> distortable(GetResourceAsStream("fonts/Distortable.ttf"));
  339. if (!distortable) {
  340. INFOF(reporter, "Could not run fontstream test because Distortable.ttf not found.");
  341. } else {
  342. SkFixed axis = SK_FixedSqrt2;
  343. sk_sp<SkTypeface> typeface(SkTypeface::MakeFromFontData(
  344. skstd::make_unique<SkFontData>(std::move(distortable), 0, &axis, 1)));
  345. if (!typeface) {
  346. INFOF(reporter, "Could not run fontstream test because Distortable.ttf not created.");
  347. } else {
  348. serialize_and_compare_typeface(std::move(typeface), "ab", reporter);
  349. }
  350. }
  351. }
  352. }
  353. static void setup_bitmap_for_canvas(SkBitmap* bitmap) {
  354. bitmap->allocN32Pixels(kBitmapSize, kBitmapSize);
  355. }
  356. static void make_checkerboard_bitmap(SkBitmap& bitmap) {
  357. setup_bitmap_for_canvas(&bitmap);
  358. SkCanvas canvas(bitmap);
  359. canvas.clear(0x00000000);
  360. SkPaint darkPaint;
  361. darkPaint.setColor(0xFF804020);
  362. SkPaint lightPaint;
  363. lightPaint.setColor(0xFF244484);
  364. const int i = kBitmapSize / 8;
  365. const SkScalar f = SkIntToScalar(i);
  366. for (int y = 0; y < kBitmapSize; y += i) {
  367. for (int x = 0; x < kBitmapSize; x += i) {
  368. canvas.save();
  369. canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
  370. canvas.drawRect(SkRect::MakeXYWH(0, 0, f, f), darkPaint);
  371. canvas.drawRect(SkRect::MakeXYWH(f, 0, f, f), lightPaint);
  372. canvas.drawRect(SkRect::MakeXYWH(0, f, f, f), lightPaint);
  373. canvas.drawRect(SkRect::MakeXYWH(f, f, f, f), darkPaint);
  374. canvas.restore();
  375. }
  376. }
  377. }
  378. static void draw_something(SkCanvas* canvas) {
  379. SkPaint paint;
  380. SkBitmap bitmap;
  381. make_checkerboard_bitmap(bitmap);
  382. canvas->save();
  383. canvas->scale(0.5f, 0.5f);
  384. canvas->drawBitmap(bitmap, 0, 0, nullptr);
  385. canvas->restore();
  386. paint.setAntiAlias(true);
  387. paint.setColor(SK_ColorRED);
  388. canvas->drawCircle(SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/3), paint);
  389. paint.setColor(SK_ColorBLACK);
  390. SkFont font;
  391. font.setSize(kBitmapSize/3);
  392. canvas->drawString("Picture", SkIntToScalar(kBitmapSize/2), SkIntToScalar(kBitmapSize/4), font, paint);
  393. }
  394. static sk_sp<SkImage> render(const SkPicture& p) {
  395. auto surf = SkSurface::MakeRasterN32Premul(SkScalarRoundToInt(p.cullRect().width()),
  396. SkScalarRoundToInt(p.cullRect().height()));
  397. if (!surf) {
  398. return nullptr; // bounds are empty?
  399. }
  400. surf->getCanvas()->clear(SK_ColorWHITE);
  401. p.playback(surf->getCanvas());
  402. return surf->makeImageSnapshot();
  403. }
  404. DEF_TEST(Serialization, reporter) {
  405. // Test matrix serialization
  406. {
  407. SkMatrix matrix = SkMatrix::I();
  408. TestObjectSerialization(&matrix, reporter);
  409. }
  410. // Test point3 serialization
  411. {
  412. SkPoint3 point;
  413. TestObjectSerializationNoAlign<SkPoint3, false>(&point, reporter);
  414. }
  415. // Test path serialization
  416. {
  417. SkPath path;
  418. TestObjectSerialization(&path, reporter);
  419. }
  420. // Test region serialization
  421. {
  422. SkRegion region;
  423. TestObjectSerialization(&region, reporter);
  424. }
  425. // Test color filter serialization
  426. {
  427. TestColorFilterSerialization(reporter);
  428. }
  429. // Test string serialization
  430. {
  431. SkString string("string");
  432. TestObjectSerializationNoAlign<SkString, false>(&string, reporter);
  433. TestObjectSerializationNoAlign<SkString, true>(&string, reporter);
  434. }
  435. // Test rrect serialization
  436. {
  437. // SkRRect does not initialize anything.
  438. // An uninitialized SkRRect can be serialized,
  439. // but will branch on uninitialized data when deserialized.
  440. SkRRect rrect;
  441. SkRect rect = SkRect::MakeXYWH(1, 2, 20, 30);
  442. SkVector corners[4] = { {1, 2}, {2, 3}, {3,4}, {4,5} };
  443. rrect.setRectRadii(rect, corners);
  444. SerializationTest::TestAlignment(&rrect, reporter);
  445. }
  446. // Test readByteArray
  447. {
  448. unsigned char data[kArraySize] = { 1, 2, 3 };
  449. TestArraySerialization(data, reporter);
  450. }
  451. // Test readColorArray
  452. {
  453. SkColor data[kArraySize] = { SK_ColorBLACK, SK_ColorWHITE, SK_ColorRED };
  454. TestArraySerialization(data, reporter);
  455. }
  456. // Test readColor4fArray
  457. {
  458. SkColor4f data[kArraySize] = {
  459. SkColor4f::FromColor(SK_ColorBLACK),
  460. SkColor4f::FromColor(SK_ColorWHITE),
  461. SkColor4f::FromColor(SK_ColorRED),
  462. { 1.f, 2.f, 4.f, 8.f }
  463. };
  464. TestArraySerialization(data, reporter);
  465. }
  466. // Test readIntArray
  467. {
  468. int32_t data[kArraySize] = { 1, 2, 4, 8 };
  469. TestArraySerialization(data, reporter);
  470. }
  471. // Test readPointArray
  472. {
  473. SkPoint data[kArraySize] = { {6, 7}, {42, 128} };
  474. TestArraySerialization(data, reporter);
  475. }
  476. // Test readScalarArray
  477. {
  478. SkScalar data[kArraySize] = { SK_Scalar1, SK_ScalarHalf, SK_ScalarMax };
  479. TestArraySerialization(data, reporter);
  480. }
  481. // Test invalid deserializations
  482. {
  483. SkImageInfo info = SkImageInfo::MakeN32Premul(kBitmapSize, kBitmapSize);
  484. SkBitmap validBitmap;
  485. validBitmap.setInfo(info);
  486. // Create a bitmap with a really large height
  487. SkBitmap invalidBitmap;
  488. invalidBitmap.setInfo(info.makeWH(info.width(), 1000000000));
  489. // The deserialization should succeed, and the rendering shouldn't crash,
  490. // even when the device fails to initialize, due to its size
  491. TestBitmapSerialization(validBitmap, invalidBitmap, true, reporter);
  492. }
  493. // Test simple SkPicture serialization
  494. {
  495. SkPictureRecorder recorder;
  496. draw_something(recorder.beginRecording(SkIntToScalar(kBitmapSize),
  497. SkIntToScalar(kBitmapSize),
  498. nullptr, 0));
  499. sk_sp<SkPicture> pict(recorder.finishRecordingAsPicture());
  500. // Serialize picture
  501. SkBinaryWriteBuffer writer;
  502. SkPicturePriv::Flatten(pict, writer);
  503. size_t size = writer.bytesWritten();
  504. SkAutoTMalloc<unsigned char> data(size);
  505. writer.writeToMemory(static_cast<void*>(data.get()));
  506. // Deserialize picture
  507. SkReadBuffer reader(static_cast<void*>(data.get()), size);
  508. sk_sp<SkPicture> readPict(SkPicturePriv::MakeFromBuffer(reader));
  509. REPORTER_ASSERT(reporter, reader.isValid());
  510. REPORTER_ASSERT(reporter, readPict.get());
  511. sk_sp<SkImage> img0 = render(*pict);
  512. sk_sp<SkImage> img1 = render(*readPict);
  513. if (img0 && img1) {
  514. REPORTER_ASSERT(reporter, ToolUtils::equal_pixels(img0.get(), img1.get()));
  515. }
  516. }
  517. TestPictureTypefaceSerialization(reporter);
  518. // Test SkLightingShader/NormalMapSource serialization
  519. {
  520. const int kTexSize = 2;
  521. SkLights::Builder builder;
  522. builder.add(SkLights::Light::MakeDirectional(SkColor3f::Make(1.0f, 1.0f, 1.0f),
  523. SkVector3::Make(1.0f, 0.0f, 0.0f)));
  524. builder.setAmbientLightColor(SkColor3f::Make(0.2f, 0.2f, 0.2f));
  525. sk_sp<SkLights> fLights = builder.finish();
  526. SkBitmap diffuse = ToolUtils::create_checkerboard_bitmap(
  527. kTexSize, kTexSize, 0x00000000, ToolUtils::color_to_565(0xFF804020), 8);
  528. SkRect bitmapBounds = SkRect::MakeIWH(diffuse.width(), diffuse.height());
  529. SkMatrix matrix;
  530. SkRect r = SkRect::MakeWH(SkIntToScalar(kTexSize), SkIntToScalar(kTexSize));
  531. matrix.setRectToRect(bitmapBounds, r, SkMatrix::kFill_ScaleToFit);
  532. SkMatrix ctm;
  533. ctm.setRotate(45);
  534. SkBitmap normals;
  535. normals.allocN32Pixels(kTexSize, kTexSize);
  536. ToolUtils::create_frustum_normal_map(&normals, SkIRect::MakeWH(kTexSize, kTexSize));
  537. sk_sp<SkShader> normalMap = normals.makeShader(&matrix);
  538. sk_sp<SkNormalSource> normalSource = SkNormalSource::MakeFromNormalMap(std::move(normalMap),
  539. ctm);
  540. sk_sp<SkShader> diffuseShader = diffuse.makeShader(&matrix);
  541. sk_sp<SkShader> lightingShader = SkLightingShader::Make(diffuseShader,
  542. normalSource,
  543. fLights);
  544. sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
  545. lightingShader = SkLightingShader::Make(std::move(diffuseShader),
  546. nullptr,
  547. fLights);
  548. sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
  549. lightingShader = SkLightingShader::Make(nullptr,
  550. std::move(normalSource),
  551. fLights);
  552. sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
  553. lightingShader = SkLightingShader::Make(nullptr,
  554. nullptr,
  555. fLights);
  556. sk_sp<SkShader>(TestFlattenableSerialization(as_SB(lightingShader.get()), true, reporter));
  557. }
  558. }
  559. ///////////////////////////////////////////////////////////////////////////////////////////////////
  560. #include "include/core/SkAnnotation.h"
  561. static sk_sp<SkPicture> copy_picture_via_serialization(SkPicture* src) {
  562. SkDynamicMemoryWStream wstream;
  563. src->serialize(&wstream);
  564. std::unique_ptr<SkStreamAsset> rstream(wstream.detachAsStream());
  565. return SkPicture::MakeFromStream(rstream.get());
  566. }
  567. struct AnnotationRec {
  568. const SkRect fRect;
  569. const char* fKey;
  570. sk_sp<SkData> fValue;
  571. };
  572. class TestAnnotationCanvas : public SkCanvas {
  573. skiatest::Reporter* fReporter;
  574. const AnnotationRec* fRec;
  575. int fCount;
  576. int fCurrIndex;
  577. public:
  578. TestAnnotationCanvas(skiatest::Reporter* reporter, const AnnotationRec rec[], int count)
  579. : SkCanvas(100, 100)
  580. , fReporter(reporter)
  581. , fRec(rec)
  582. , fCount(count)
  583. , fCurrIndex(0)
  584. {}
  585. ~TestAnnotationCanvas() {
  586. REPORTER_ASSERT(fReporter, fCount == fCurrIndex);
  587. }
  588. protected:
  589. void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) {
  590. REPORTER_ASSERT(fReporter, fCurrIndex < fCount);
  591. REPORTER_ASSERT(fReporter, rect == fRec[fCurrIndex].fRect);
  592. REPORTER_ASSERT(fReporter, !strcmp(key, fRec[fCurrIndex].fKey));
  593. REPORTER_ASSERT(fReporter, value->equals(fRec[fCurrIndex].fValue.get()));
  594. fCurrIndex += 1;
  595. }
  596. };
  597. /*
  598. * Test the 3 annotation types by recording them into a picture, serializing, and then playing
  599. * them back into another canvas.
  600. */
  601. DEF_TEST(Annotations, reporter) {
  602. SkPictureRecorder recorder;
  603. SkCanvas* recordingCanvas = recorder.beginRecording(SkRect::MakeWH(100, 100));
  604. const char* str0 = "rect-with-url";
  605. const SkRect r0 = SkRect::MakeWH(10, 10);
  606. sk_sp<SkData> d0(SkData::MakeWithCString(str0));
  607. SkAnnotateRectWithURL(recordingCanvas, r0, d0.get());
  608. const char* str1 = "named-destination";
  609. const SkRect r1 = SkRect::MakeXYWH(5, 5, 0, 0); // collapsed to a point
  610. sk_sp<SkData> d1(SkData::MakeWithCString(str1));
  611. SkAnnotateNamedDestination(recordingCanvas, {r1.x(), r1.y()}, d1.get());
  612. const char* str2 = "link-to-destination";
  613. const SkRect r2 = SkRect::MakeXYWH(20, 20, 5, 6);
  614. sk_sp<SkData> d2(SkData::MakeWithCString(str2));
  615. SkAnnotateLinkToDestination(recordingCanvas, r2, d2.get());
  616. const AnnotationRec recs[] = {
  617. { r0, SkAnnotationKeys::URL_Key(), std::move(d0) },
  618. { r1, SkAnnotationKeys::Define_Named_Dest_Key(), std::move(d1) },
  619. { r2, SkAnnotationKeys::Link_Named_Dest_Key(), std::move(d2) },
  620. };
  621. sk_sp<SkPicture> pict0(recorder.finishRecordingAsPicture());
  622. sk_sp<SkPicture> pict1(copy_picture_via_serialization(pict0.get()));
  623. TestAnnotationCanvas canvas(reporter, recs, SK_ARRAY_COUNT(recs));
  624. canvas.drawPicture(pict1);
  625. }
  626. DEF_TEST(WriteBuffer_storage, reporter) {
  627. enum {
  628. kSize = 32
  629. };
  630. int32_t storage[kSize/4];
  631. char src[kSize];
  632. sk_bzero(src, kSize);
  633. SkBinaryWriteBuffer writer(storage, kSize);
  634. REPORTER_ASSERT(reporter, writer.usingInitialStorage());
  635. REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
  636. writer.write(src, kSize - 4);
  637. REPORTER_ASSERT(reporter, writer.usingInitialStorage());
  638. REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
  639. writer.writeInt(0);
  640. REPORTER_ASSERT(reporter, writer.usingInitialStorage());
  641. REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
  642. writer.reset(storage, kSize-4);
  643. REPORTER_ASSERT(reporter, writer.usingInitialStorage());
  644. REPORTER_ASSERT(reporter, writer.bytesWritten() == 0);
  645. writer.write(src, kSize - 4);
  646. REPORTER_ASSERT(reporter, writer.usingInitialStorage());
  647. REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize - 4);
  648. writer.writeInt(0);
  649. REPORTER_ASSERT(reporter, !writer.usingInitialStorage()); // this is the change
  650. REPORTER_ASSERT(reporter, writer.bytesWritten() == kSize);
  651. }
  652. DEF_TEST(WriteBuffer_external_memory_textblob, reporter) {
  653. SkFont font;
  654. font.setTypeface(SkTypeface::MakeDefault());
  655. SkTextBlobBuilder builder;
  656. int glyph_count = 5;
  657. const auto& run = builder.allocRun(font, glyph_count, 1.2f, 2.3f);
  658. // allocRun() allocates only the glyph buffer.
  659. std::fill(run.glyphs, run.glyphs + glyph_count, 0);
  660. auto blob = builder.make();
  661. SkSerialProcs procs;
  662. SkAutoTMalloc<uint8_t> storage;
  663. size_t blob_size = 0u;
  664. size_t storage_size = 0u;
  665. blob_size = SkAlign4(blob->serialize(procs)->size());
  666. REPORTER_ASSERT(reporter, blob_size > 4u);
  667. storage_size = blob_size - 4;
  668. storage.realloc(storage_size);
  669. REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) == 0u);
  670. storage_size = blob_size;
  671. storage.realloc(storage_size);
  672. REPORTER_ASSERT(reporter, blob->serialize(procs, storage.get(), storage_size) != 0u);
  673. }
  674. DEF_TEST(WriteBuffer_external_memory_flattenable, reporter) {
  675. SkScalar intervals[] = {1.f, 1.f};
  676. auto path_effect = SkDashPathEffect::Make(intervals, 2, 0);
  677. size_t path_size = SkAlign4(path_effect->serialize()->size());
  678. REPORTER_ASSERT(reporter, path_size > 4u);
  679. SkAutoTMalloc<uint8_t> storage;
  680. size_t storage_size = path_size - 4;
  681. storage.realloc(storage_size);
  682. REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) == 0u);
  683. storage_size = path_size;
  684. storage.realloc(storage_size);
  685. REPORTER_ASSERT(reporter, path_effect->serialize(storage.get(), storage_size) != 0u);
  686. }