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