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