1 /*
2 * Copyright 2010 The Android Open Source Project
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 "tests/Test.h"
9
10 #ifdef SK_SUPPORT_PDF
11
12 #include "include/core/SkBitmap.h"
13 #include "include/core/SkCanvas.h"
14 #include "include/core/SkData.h"
15 #include "include/core/SkImageEncoder.h"
16 #include "include/core/SkMatrix.h"
17 #include "include/core/SkScalar.h"
18 #include "include/core/SkStream.h"
19 #include "include/core/SkTypes.h"
20 #include "include/effects/SkImageFilters.h"
21 #include "include/effects/SkPerlinNoiseShader.h"
22 #include "include/private/SkTo.h"
23 #include "src/core/SkGlyphRun.h"
24 #include "src/core/SkImageFilter_Base.h"
25 #include "src/core/SkReadBuffer.h"
26 #include "src/core/SkSpecialImage.h"
27 #include "src/pdf/SkClusterator.h"
28 #include "src/pdf/SkDeflate.h"
29 #include "src/pdf/SkPDFDevice.h"
30 #include "src/pdf/SkPDFDocumentPriv.h"
31 #include "src/pdf/SkPDFFont.h"
32 #include "src/pdf/SkPDFTypes.h"
33 #include "src/pdf/SkPDFUnion.h"
34 #include "src/pdf/SkPDFUtils.h"
35 #include "tools/Resources.h"
36 #include "tools/ToolUtils.h"
37
38 #include <cstdlib>
39 #include <cmath>
40 #include <memory>
41
42 template <typename T>
emit_to_string(T & obj)43 static SkString emit_to_string(T& obj) {
44 SkDynamicMemoryWStream buffer;
45 obj.emitObject(&buffer);
46 SkString tmp(buffer.bytesWritten());
47 buffer.copyTo(tmp.writable_str());
48 return tmp;
49 }
50
eq(const SkString & str,const char * strPtr,size_t len)51 static bool eq(const SkString& str, const char* strPtr, size_t len) {
52 return len == str.size() && 0 == memcmp(str.c_str(), strPtr, len);
53 }
54
assert_eql(skiatest::Reporter * reporter,const SkString & skString,const char * str,size_t len)55 static void assert_eql(skiatest::Reporter* reporter,
56 const SkString& skString,
57 const char* str,
58 size_t len) {
59 if (!eq(skString, str, len)) {
60 REPORT_FAILURE(reporter, "", SkStringPrintf(
61 "'%*s' != '%s'", (int)len, str, skString.c_str()));
62 }
63 }
64
assert_eq(skiatest::Reporter * reporter,const SkString & skString,const char * str)65 static void assert_eq(skiatest::Reporter* reporter,
66 const SkString& skString,
67 const char* str) {
68 assert_eql(reporter, skString, str, strlen(str));
69 }
70
71
72 template <typename T>
assert_emit_eq(skiatest::Reporter * reporter,T & object,const char * string)73 static void assert_emit_eq(skiatest::Reporter* reporter,
74 T& object,
75 const char* string) {
76 SkString result = emit_to_string(object);
77 assert_eq(reporter, result, string);
78 }
79
80 // This test used to assert without the fix submitted for
81 // http://code.google.com/p/skia/issues/detail?id=1083.
82 // SKP files might have invalid glyph ids. This test ensures they are ignored,
83 // and there is no assert on input data in Debug mode.
test_issue1083()84 static void test_issue1083() {
85 SkDynamicMemoryWStream outStream;
86 auto doc = SkPDF::MakeDocument(&outStream);
87 SkCanvas* canvas = doc->beginPage(100.0f, 100.0f);
88
89 uint16_t glyphID = 65000;
90 canvas->drawSimpleText(&glyphID, 2, SkTextEncoding::kGlyphID, 0, 0, SkFont(), SkPaint());
91
92 doc->close();
93 }
94
assert_emit_eq_number(skiatest::Reporter * reporter,float number)95 static void assert_emit_eq_number(skiatest::Reporter* reporter, float number) {
96 SkPDFUnion pdfUnion = SkPDFUnion::Scalar(number);
97 SkString result = emit_to_string(pdfUnion);
98 float value = static_cast<float>(std::atof(result.c_str()));
99 if (value != number) {
100 ERRORF(reporter, "%.9g != %s", number, result.c_str());
101 }
102 }
103
104
TestPDFUnion(skiatest::Reporter * reporter)105 static void TestPDFUnion(skiatest::Reporter* reporter) {
106 SkPDFUnion boolTrue = SkPDFUnion::Bool(true);
107 assert_emit_eq(reporter, boolTrue, "true");
108
109 SkPDFUnion boolFalse = SkPDFUnion::Bool(false);
110 assert_emit_eq(reporter, boolFalse, "false");
111
112 SkPDFUnion int42 = SkPDFUnion::Int(42);
113 assert_emit_eq(reporter, int42, "42");
114
115 assert_emit_eq_number(reporter, SK_ScalarHalf);
116 assert_emit_eq_number(reporter, 110999.75f); // bigScalar
117 assert_emit_eq_number(reporter, 50000000.1f); // biggerScalar
118 assert_emit_eq_number(reporter, 1.0f / 65536); // smallScalar
119
120 SkPDFUnion stringSimple = SkPDFUnion::String("test ) string ( foo");
121 assert_emit_eq(reporter, stringSimple, "(test \\) string \\( foo)");
122
123 SkString stringComplexInput("\ttest ) string ( foo");
124 SkPDFUnion stringComplex = SkPDFUnion::String(stringComplexInput);
125 assert_emit_eq(reporter, stringComplex, "(\\011test \\) string \\( foo)");
126
127 SkString binaryStringInput("\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20");
128 SkPDFUnion binaryString = SkPDFUnion::String(binaryStringInput);
129 assert_emit_eq(reporter, binaryString, "<0102030405060708090A0B0C0D0E0F10>");
130
131 SkString nameInput("Test name\twith#tab");
132 SkPDFUnion name = SkPDFUnion::Name(nameInput);
133 assert_emit_eq(reporter, name, "/Test#20name#09with#23tab");
134
135 SkString nameInput2("A#/%()<>[]{}B");
136 SkPDFUnion name2 = SkPDFUnion::Name(nameInput2);
137 assert_emit_eq(reporter, name2, "/A#23#2F#25#28#29#3C#3E#5B#5D#7B#7DB");
138
139 SkPDFUnion name3 = SkPDFUnion::Name("SimpleNameWithOnlyPrintableASCII");
140 assert_emit_eq(reporter, name3, "/SimpleNameWithOnlyPrintableASCII");
141
142 // Test that we correctly handle characters with the high-bit set.
143 SkString highBitString("\xDE\xAD" "be\xEF");
144 SkPDFUnion highBitName = SkPDFUnion::Name(highBitString);
145 assert_emit_eq(reporter, highBitName, "/#DE#ADbe#EF");
146
147 // https://bugs.skia.org/9508
148 // https://crbug.com/494913
149 // Trailing '\0' characters must be removed.
150 const char nameInput4[] = "Test name with nil\0";
151 SkPDFUnion name4 = SkPDFUnion::Name(SkString(nameInput4, strlen(nameInput4) + 1));
152 assert_emit_eq(reporter, name4, "/Test#20name#20with#20nil");
153 }
154
TestPDFArray(skiatest::Reporter * reporter)155 static void TestPDFArray(skiatest::Reporter* reporter) {
156 std::unique_ptr<SkPDFArray> array(new SkPDFArray);
157 assert_emit_eq(reporter, *array, "[]");
158
159 array->appendInt(42);
160 assert_emit_eq(reporter, *array, "[42]");
161
162 array->appendScalar(SK_ScalarHalf);
163 assert_emit_eq(reporter, *array, "[42 .5]");
164
165 array->appendInt(0);
166 assert_emit_eq(reporter, *array, "[42 .5 0]");
167
168 array->appendBool(true);
169 assert_emit_eq(reporter, *array, "[42 .5 0 true]");
170
171 array->appendName("ThisName");
172 assert_emit_eq(reporter, *array, "[42 .5 0 true /ThisName]");
173
174 array->appendName(SkString("AnotherName"));
175 assert_emit_eq(reporter, *array, "[42 .5 0 true /ThisName /AnotherName]");
176
177 array->appendString("This String");
178 assert_emit_eq(reporter, *array,
179 "[42 .5 0 true /ThisName /AnotherName (This String)]");
180
181 array->appendString(SkString("Another String"));
182 assert_emit_eq(reporter, *array,
183 "[42 .5 0 true /ThisName /AnotherName (This String) "
184 "(Another String)]");
185
186 std::unique_ptr<SkPDFArray> innerArray(new SkPDFArray);
187 innerArray->appendInt(-1);
188 array->appendObject(std::move(innerArray));
189 assert_emit_eq(reporter, *array,
190 "[42 .5 0 true /ThisName /AnotherName (This String) "
191 "(Another String) [-1]]");
192 }
193
TestPDFDict(skiatest::Reporter * reporter)194 static void TestPDFDict(skiatest::Reporter* reporter) {
195 std::unique_ptr<SkPDFDict> dict(new SkPDFDict);
196 assert_emit_eq(reporter, *dict, "<<>>");
197
198 dict->insertInt("n1", SkToSizeT(42));
199 assert_emit_eq(reporter, *dict, "<</n1 42>>");
200
201 dict = std::make_unique<SkPDFDict>();
202 assert_emit_eq(reporter, *dict, "<<>>");
203
204 dict->insertInt("n1", 42);
205 assert_emit_eq(reporter, *dict, "<</n1 42>>");
206
207 dict->insertScalar("n2", SK_ScalarHalf);
208
209 SkString n3("n3");
210 std::unique_ptr<SkPDFArray> innerArray(new SkPDFArray);
211 innerArray->appendInt(-100);
212 dict->insertObject(n3, std::move(innerArray));
213 assert_emit_eq(reporter, *dict, "<</n1 42\n/n2 .5\n/n3 [-100]>>");
214
215 dict = std::make_unique<SkPDFDict>();
216 assert_emit_eq(reporter, *dict, "<<>>");
217
218 dict->insertInt("n1", 24);
219 assert_emit_eq(reporter, *dict, "<</n1 24>>");
220
221 dict->insertInt("n2", SkToSizeT(99));
222 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99>>");
223
224 dict->insertScalar("n3", SK_ScalarHalf);
225 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5>>");
226
227 dict->insertName("n4", "AName");
228 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5\n/n4 /AName>>");
229
230 dict->insertName("n5", SkString("AnotherName"));
231 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5\n/n4 /AName\n"
232 "/n5 /AnotherName>>");
233
234 dict->insertString("n6", "A String");
235 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5\n/n4 /AName\n"
236 "/n5 /AnotherName\n/n6 (A String)>>");
237
238 dict->insertString("n7", SkString("Another String"));
239 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5\n/n4 /AName\n"
240 "/n5 /AnotherName\n/n6 (A String)\n/n7 (Another String)>>");
241
242 dict = std::make_unique<SkPDFDict>("DType");
243 assert_emit_eq(reporter, *dict, "<</Type /DType>>");
244 }
245
DEF_TEST(SkPDF_Primitives,reporter)246 DEF_TEST(SkPDF_Primitives, reporter) {
247 TestPDFUnion(reporter);
248 TestPDFArray(reporter);
249 TestPDFDict(reporter);
250 test_issue1083();
251 }
252
253 namespace {
254
255 class TestImageFilter : public SkImageFilter_Base {
256 public:
Make(bool visited=false)257 static sk_sp<TestImageFilter> Make(bool visited = false) {
258 return sk_sp<TestImageFilter>(new TestImageFilter(visited));
259 }
260
visited() const261 bool visited() const { return fVisited; }
262
263 protected:
onFilterImage(const Context & ctx,SkIPoint * offset) const264 sk_sp<SkSpecialImage> onFilterImage(const Context& ctx, SkIPoint* offset) const override {
265 fVisited = true;
266 offset->fX = offset->fY = 0;
267 return sk_ref_sp<SkSpecialImage>(ctx.sourceImage());
268 }
269
270 private:
271 SK_FLATTENABLE_HOOKS(TestImageFilter)
TestImageFilter(bool visited)272 TestImageFilter(bool visited) : INHERITED(nullptr, 0, nullptr), fVisited(visited) {}
273
274 mutable bool fVisited;
275
276 using INHERITED = SkImageFilter_Base;
277 };
278
CreateProc(SkReadBuffer & buffer)279 sk_sp<SkFlattenable> TestImageFilter::CreateProc(SkReadBuffer& buffer) {
280 SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 0);
281 bool visited = buffer.readBool();
282 return TestImageFilter::Make(visited);
283 }
284
285 } // namespace
286
287 // Check that PDF rendering of image filters successfully falls back to
288 // CPU rasterization.
DEF_TEST(SkPDF_ImageFilter,reporter)289 DEF_TEST(SkPDF_ImageFilter, reporter) {
290 REQUIRE_PDF_DOCUMENT(SkPDF_ImageFilter, reporter);
291 SkDynamicMemoryWStream stream;
292 auto doc = SkPDF::MakeDocument(&stream);
293 SkCanvas* canvas = doc->beginPage(100.0f, 100.0f);
294
295 sk_sp<TestImageFilter> filter(TestImageFilter::Make());
296
297 // Filter just created; should be unvisited.
298 REPORTER_ASSERT(reporter, !filter->visited());
299 SkPaint paint;
300 paint.setImageFilter(filter);
301 canvas->drawRect(SkRect::MakeWH(100, 100), paint);
302 doc->close();
303
304 // Filter was used in rendering; should be visited.
305 REPORTER_ASSERT(reporter, filter->visited());
306 }
307
308 // Check that PDF rendering of image filters successfully falls back to
309 // CPU rasterization.
DEF_TEST(SkPDF_FontCanEmbedTypeface,reporter)310 DEF_TEST(SkPDF_FontCanEmbedTypeface, reporter) {
311 SkNullWStream nullWStream;
312 SkPDFDocument doc(&nullWStream, SkPDF::Metadata());
313
314 const char resource[] = "fonts/Roboto2-Regular_NoEmbed.ttf";
315 sk_sp<SkTypeface> noEmbedTypeface(MakeResourceAsTypeface(resource));
316 if (noEmbedTypeface) {
317 REPORTER_ASSERT(reporter,
318 !SkPDFFont::CanEmbedTypeface(noEmbedTypeface.get(), &doc));
319 }
320 sk_sp<SkTypeface> portableTypeface(ToolUtils::create_portable_typeface(nullptr, SkFontStyle()));
321 REPORTER_ASSERT(reporter,
322 SkPDFFont::CanEmbedTypeface(portableTypeface.get(), &doc));
323 }
324
325
326 // test to see that all finite scalars round trip via scanf().
check_pdf_scalar_serialization(skiatest::Reporter * reporter,float inputFloat)327 static void check_pdf_scalar_serialization(
328 skiatest::Reporter* reporter, float inputFloat) {
329 char floatString[kMaximumSkFloatToDecimalLength];
330 size_t len = SkFloatToDecimal(inputFloat, floatString);
331 if (len >= sizeof(floatString)) {
332 ERRORF(reporter, "string too long: %u", (unsigned)len);
333 return;
334 }
335 if (floatString[len] != '\0' || strlen(floatString) != len) {
336 ERRORF(reporter, "terminator misplaced.");
337 return; // The terminator is needed for sscanf().
338 }
339 if (reporter->verbose()) {
340 SkDebugf("%15.9g = \"%s\"\n", inputFloat, floatString);
341 }
342 float roundTripFloat;
343 if (1 != sscanf(floatString, "%f", &roundTripFloat)) {
344 ERRORF(reporter, "unscannable result: %s", floatString);
345 return;
346 }
347 if (std::isfinite(inputFloat) && roundTripFloat != inputFloat) {
348 ERRORF(reporter, "roundTripFloat (%.9g) != inputFloat (%.9g)",
349 roundTripFloat, inputFloat);
350 }
351 }
352
353 // Test SkPDFUtils::AppendScalar for accuracy.
DEF_TEST(SkPDF_Primitives_Scalar,reporter)354 DEF_TEST(SkPDF_Primitives_Scalar, reporter) {
355 SkRandom random(0x5EED);
356 int iterationCount = 512;
357 while (iterationCount-- > 0) {
358 union { uint32_t u; float f; };
359 u = random.nextU();
360 static_assert(sizeof(float) == sizeof(uint32_t), "");
361 check_pdf_scalar_serialization(reporter, f);
362 }
363 float alwaysCheck[] = {
364 0.0f, -0.0f, 1.0f, -1.0f, SK_ScalarPI, 0.1f, FLT_MIN, FLT_MAX,
365 -FLT_MIN, -FLT_MAX, FLT_MIN / 16.0f, -FLT_MIN / 16.0f,
366 SK_FloatNaN, SK_FloatInfinity, SK_FloatNegativeInfinity,
367 -FLT_MIN / 8388608.0
368 };
369 for (float inputFloat: alwaysCheck) {
370 check_pdf_scalar_serialization(reporter, inputFloat);
371 }
372 }
373
374 // Test SkPDFUtils:: for accuracy.
DEF_TEST(SkPDF_Primitives_Color,reporter)375 DEF_TEST(SkPDF_Primitives_Color, reporter) {
376 char buffer[5];
377 for (int i = 0; i < 256; ++i) {
378 size_t len = SkPDFUtils::ColorToDecimal(i, buffer);
379 REPORTER_ASSERT(reporter, len == strlen(buffer));
380 float f;
381 REPORTER_ASSERT(reporter, 1 == sscanf(buffer, "%f", &f));
382 int roundTrip = (int)(0.5 + f * 255);
383 REPORTER_ASSERT(reporter, roundTrip == i);
384 }
385 }
386
make_run(size_t len,const SkGlyphID * glyphs,SkPoint * pos,const SkFont & font,const uint32_t * clusters,size_t utf8TextByteLength,const char * utf8Text)387 static SkGlyphRun make_run(size_t len, const SkGlyphID* glyphs, SkPoint* pos,
388 const SkFont& font, const uint32_t* clusters,
389 size_t utf8TextByteLength, const char* utf8Text) {
390 return SkGlyphRun(font,
391 SkSpan<const SkPoint>{pos, len},
392 SkSpan<const SkGlyphID>{glyphs, len},
393 SkSpan<const char>{utf8Text, utf8TextByteLength},
394 SkSpan<const uint32_t>{clusters, len},
395 SkSpan<const SkVector>{});
396 }
397
DEF_TEST(SkPDF_Clusterator,reporter)398 DEF_TEST(SkPDF_Clusterator, reporter) {
399 SkFont font;
400 {
401 constexpr unsigned len = 11;
402 const uint32_t clusters[len] = { 3, 2, 2, 1, 0, 4, 4, 7, 6, 6, 5 };
403 const SkGlyphID glyphs[len] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
404 SkPoint pos[len] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
405 {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}};
406 const char text[] = "abcdefgh";
407 SkGlyphRun run = make_run(len, glyphs, pos, font, clusters, strlen(text), text);
408 SkClusterator clusterator(run);
409 SkClusterator::Cluster expectations[] = {
410 {&text[3], 1, 0, 1},
411 {&text[2], 1, 1, 2},
412 {&text[1], 1, 3, 1},
413 {&text[0], 1, 4, 1},
414 {&text[4], 1, 5, 2},
415 {&text[7], 1, 7, 1},
416 {&text[6], 1, 8, 2},
417 {&text[5], 1, 10, 1},
418 {nullptr, 0, 0, 0},
419 };
420 for (const auto& expectation : expectations) {
421 REPORTER_ASSERT(reporter, clusterator.next() == expectation);
422 }
423 }
424 {
425 constexpr unsigned len = 5;
426 const uint32_t clusters[len] = { 0, 1, 4, 5, 6 };
427 const SkGlyphID glyphs[len] = { 43, 167, 79, 79, 82, };
428 SkPoint pos[len] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}};
429 const char text[] = "Ha\xCC\x8A" "llo";
430 SkGlyphRun run = make_run(len, glyphs, pos, font, clusters, strlen(text), text);
431 SkClusterator clusterator(run);
432 SkClusterator::Cluster expectations[] = {
433 {&text[0], 1, 0, 1},
434 {&text[1], 3, 1, 1},
435 {&text[4], 1, 2, 1},
436 {&text[5], 1, 3, 1},
437 {&text[6], 1, 4, 1},
438 {nullptr, 0, 0, 0},
439 };
440 for (const auto& expectation : expectations) {
441 REPORTER_ASSERT(reporter, clusterator.next() == expectation);
442 }
443 }
444 }
445
DEF_TEST(fuzz875632f0,reporter)446 DEF_TEST(fuzz875632f0, reporter) {
447 SkNullWStream stream;
448 auto doc = SkPDF::MakeDocument(&stream);
449 REPORTER_ASSERT(reporter, doc);
450 SkCanvas* canvas = doc->beginPage(128, 160);
451
452 SkAutoCanvasRestore autoCanvasRestore(canvas, false);
453
454 SkPaint layerPaint({0, 0, 0, 0});
455 layerPaint.setImageFilter(SkImageFilters::Dilate(536870912, 0, nullptr, nullptr));
456 layerPaint.setBlendMode(SkBlendMode::kClear);
457
458 canvas->saveLayer(nullptr, &layerPaint);
459 canvas->saveLayer(nullptr, nullptr);
460
461 SkPaint paint;
462 paint.setBlendMode(SkBlendMode::kDarken);
463 paint.setShader(SkPerlinNoiseShader::MakeFractalNoise(0, 0, 2, 0, nullptr));
464 paint.setColor4f(SkColor4f{0, 0, 0 ,0});
465
466 canvas->drawPath(SkPath(), paint);
467 }
468 #endif
469