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 "Test.h"
9
10 #ifdef SK_SUPPORT_PDF
11
12 #include "Resources.h"
13 #include "SkBitmap.h"
14 #include "SkCanvas.h"
15 #include "SkClusterator.h"
16 #include "SkData.h"
17 #include "SkDeflate.h"
18 #include "SkGlyphRun.h"
19 #include "SkImageEncoder.h"
20 #include "SkImageFilterPriv.h"
21 #include "SkMakeUnique.h"
22 #include "SkMatrix.h"
23 #include "SkPDFDevice.h"
24 #include "SkPDFDocumentPriv.h"
25 #include "SkPDFFont.h"
26 #include "SkPDFTypes.h"
27 #include "SkPDFUnion.h"
28 #include "SkPDFUtils.h"
29 #include "SkReadBuffer.h"
30 #include "SkScalar.h"
31 #include "SkSpecialImage.h"
32 #include "SkStream.h"
33 #include "SkTo.h"
34 #include "SkTypes.h"
35 #include "sk_tool_utils.h"
36
37 #include <cstdlib>
38 #include <cmath>
39
40 #define DUMMY_TEXT "DCT compessed stream."
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'", 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, kGlyphID_SkTextEncoding, 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
TestPDFArray(skiatest::Reporter * reporter)148 static void TestPDFArray(skiatest::Reporter* reporter) {
149 std::unique_ptr<SkPDFArray> array(new SkPDFArray);
150 assert_emit_eq(reporter, *array, "[]");
151
152 array->appendInt(42);
153 assert_emit_eq(reporter, *array, "[42]");
154
155 array->appendScalar(SK_ScalarHalf);
156 assert_emit_eq(reporter, *array, "[42 .5]");
157
158 array->appendInt(0);
159 assert_emit_eq(reporter, *array, "[42 .5 0]");
160
161 array->appendBool(true);
162 assert_emit_eq(reporter, *array, "[42 .5 0 true]");
163
164 array->appendName("ThisName");
165 assert_emit_eq(reporter, *array, "[42 .5 0 true /ThisName]");
166
167 array->appendName(SkString("AnotherName"));
168 assert_emit_eq(reporter, *array, "[42 .5 0 true /ThisName /AnotherName]");
169
170 array->appendString("This String");
171 assert_emit_eq(reporter, *array,
172 "[42 .5 0 true /ThisName /AnotherName (This String)]");
173
174 array->appendString(SkString("Another String"));
175 assert_emit_eq(reporter, *array,
176 "[42 .5 0 true /ThisName /AnotherName (This String) "
177 "(Another String)]");
178
179 std::unique_ptr<SkPDFArray> innerArray(new SkPDFArray);
180 innerArray->appendInt(-1);
181 array->appendObject(std::move(innerArray));
182 assert_emit_eq(reporter, *array,
183 "[42 .5 0 true /ThisName /AnotherName (This String) "
184 "(Another String) [-1]]");
185 }
186
TestPDFDict(skiatest::Reporter * reporter)187 static void TestPDFDict(skiatest::Reporter* reporter) {
188 std::unique_ptr<SkPDFDict> dict(new SkPDFDict);
189 assert_emit_eq(reporter, *dict, "<<>>");
190
191 dict->insertInt("n1", SkToSizeT(42));
192 assert_emit_eq(reporter, *dict, "<</n1 42>>");
193
194 dict.reset(new SkPDFDict);
195 assert_emit_eq(reporter, *dict, "<<>>");
196
197 dict->insertInt("n1", 42);
198 assert_emit_eq(reporter, *dict, "<</n1 42>>");
199
200 dict->insertScalar("n2", SK_ScalarHalf);
201
202 SkString n3("n3");
203 std::unique_ptr<SkPDFArray> innerArray(new SkPDFArray);
204 innerArray->appendInt(-100);
205 dict->insertObject(n3, std::move(innerArray));
206 assert_emit_eq(reporter, *dict, "<</n1 42\n/n2 .5\n/n3 [-100]>>");
207
208 dict.reset(new SkPDFDict);
209 assert_emit_eq(reporter, *dict, "<<>>");
210
211 dict->insertInt("n1", 24);
212 assert_emit_eq(reporter, *dict, "<</n1 24>>");
213
214 dict->insertInt("n2", SkToSizeT(99));
215 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99>>");
216
217 dict->insertScalar("n3", SK_ScalarHalf);
218 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5>>");
219
220 dict->insertName("n4", "AName");
221 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5\n/n4 /AName>>");
222
223 dict->insertName("n5", SkString("AnotherName"));
224 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5\n/n4 /AName\n"
225 "/n5 /AnotherName>>");
226
227 dict->insertString("n6", "A String");
228 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5\n/n4 /AName\n"
229 "/n5 /AnotherName\n/n6 (A String)>>");
230
231 dict->insertString("n7", SkString("Another String"));
232 assert_emit_eq(reporter, *dict, "<</n1 24\n/n2 99\n/n3 .5\n/n4 /AName\n"
233 "/n5 /AnotherName\n/n6 (A String)\n/n7 (Another String)>>");
234
235 dict.reset(new SkPDFDict("DType"));
236 assert_emit_eq(reporter, *dict, "<</Type /DType>>");
237 }
238
DEF_TEST(SkPDF_Primitives,reporter)239 DEF_TEST(SkPDF_Primitives, reporter) {
240 TestPDFUnion(reporter);
241 TestPDFArray(reporter);
242 TestPDFDict(reporter);
243 test_issue1083();
244 }
245
246 namespace {
247
248 class DummyImageFilter : public SkImageFilter {
249 public:
Make(bool visited=false)250 static sk_sp<DummyImageFilter> Make(bool visited = false) {
251 return sk_sp<DummyImageFilter>(new DummyImageFilter(visited));
252 }
253
visited() const254 bool visited() const { return fVisited; }
255
256 protected:
onFilterImage(SkSpecialImage * source,const Context &,SkIPoint * offset) const257 sk_sp<SkSpecialImage> onFilterImage(SkSpecialImage* source, const Context&,
258 SkIPoint* offset) const override {
259 fVisited = true;
260 offset->fX = offset->fY = 0;
261 return sk_ref_sp<SkSpecialImage>(source);
262 }
onMakeColorSpace(SkColorSpaceXformer *) const263 sk_sp<SkImageFilter> onMakeColorSpace(SkColorSpaceXformer*) const override {
264 return sk_ref_sp(const_cast<DummyImageFilter*>(this));
265 }
266
267 private:
268 SK_FLATTENABLE_HOOKS(DummyImageFilter)
DummyImageFilter(bool visited)269 DummyImageFilter(bool visited) : INHERITED(nullptr, 0, nullptr), fVisited(visited) {}
270
271 mutable bool fVisited;
272
273 typedef SkImageFilter INHERITED;
274 };
275
CreateProc(SkReadBuffer & buffer)276 sk_sp<SkFlattenable> DummyImageFilter::CreateProc(SkReadBuffer& buffer) {
277 SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 0);
278 bool visited = buffer.readBool();
279 return DummyImageFilter::Make(visited);
280 }
281
282 };
283
284 // Check that PDF rendering of image filters successfully falls back to
285 // CPU rasterization.
DEF_TEST(SkPDF_ImageFilter,reporter)286 DEF_TEST(SkPDF_ImageFilter, reporter) {
287 REQUIRE_PDF_DOCUMENT(SkPDF_ImageFilter, reporter);
288 SkDynamicMemoryWStream stream;
289 auto doc = SkPDF::MakeDocument(&stream);
290 SkCanvas* canvas = doc->beginPage(100.0f, 100.0f);
291
292 sk_sp<DummyImageFilter> filter(DummyImageFilter::Make());
293
294 // Filter just created; should be unvisited.
295 REPORTER_ASSERT(reporter, !filter->visited());
296 SkPaint paint;
297 paint.setImageFilter(filter);
298 canvas->drawRect(SkRect::MakeWH(100, 100), paint);
299 doc->close();
300
301 // Filter was used in rendering; should be visited.
302 REPORTER_ASSERT(reporter, filter->visited());
303 }
304
305 // Check that PDF rendering of image filters successfully falls back to
306 // CPU rasterization.
DEF_TEST(SkPDF_FontCanEmbedTypeface,reporter)307 DEF_TEST(SkPDF_FontCanEmbedTypeface, reporter) {
308 SkNullWStream nullWStream;
309 SkPDFDocument doc(&nullWStream, SkPDF::Metadata());
310
311 const char resource[] = "fonts/Roboto2-Regular_NoEmbed.ttf";
312 sk_sp<SkTypeface> noEmbedTypeface(MakeResourceAsTypeface(resource));
313 if (noEmbedTypeface) {
314 REPORTER_ASSERT(reporter,
315 !SkPDFFont::CanEmbedTypeface(noEmbedTypeface.get(), &doc));
316 }
317 sk_sp<SkTypeface> portableTypeface(
318 sk_tool_utils::create_portable_typeface(nullptr, SkFontStyle()));
319 REPORTER_ASSERT(reporter,
320 SkPDFFont::CanEmbedTypeface(portableTypeface.get(), &doc));
321 }
322
323
324 // test to see that all finite scalars round trip via scanf().
check_pdf_scalar_serialization(skiatest::Reporter * reporter,float inputFloat)325 static void check_pdf_scalar_serialization(
326 skiatest::Reporter* reporter, float inputFloat) {
327 char floatString[kMaximumSkFloatToDecimalLength];
328 size_t len = SkFloatToDecimal(inputFloat, floatString);
329 if (len >= sizeof(floatString)) {
330 ERRORF(reporter, "string too long: %u", (unsigned)len);
331 return;
332 }
333 if (floatString[len] != '\0' || strlen(floatString) != len) {
334 ERRORF(reporter, "terminator misplaced.");
335 return; // The terminator is needed for sscanf().
336 }
337 if (reporter->verbose()) {
338 SkDebugf("%15.9g = \"%s\"\n", inputFloat, floatString);
339 }
340 float roundTripFloat;
341 if (1 != sscanf(floatString, "%f", &roundTripFloat)) {
342 ERRORF(reporter, "unscannable result: %s", floatString);
343 return;
344 }
345 if (std::isfinite(inputFloat) && roundTripFloat != inputFloat) {
346 ERRORF(reporter, "roundTripFloat (%.9g) != inputFloat (%.9g)",
347 roundTripFloat, inputFloat);
348 }
349 }
350
351 // Test SkPDFUtils::AppendScalar for accuracy.
DEF_TEST(SkPDF_Primitives_Scalar,reporter)352 DEF_TEST(SkPDF_Primitives_Scalar, reporter) {
353 SkRandom random(0x5EED);
354 int iterationCount = 512;
355 while (iterationCount-- > 0) {
356 union { uint32_t u; float f; };
357 u = random.nextU();
358 static_assert(sizeof(float) == sizeof(uint32_t), "");
359 check_pdf_scalar_serialization(reporter, f);
360 }
361 float alwaysCheck[] = {
362 0.0f, -0.0f, 1.0f, -1.0f, SK_ScalarPI, 0.1f, FLT_MIN, FLT_MAX,
363 -FLT_MIN, -FLT_MAX, FLT_MIN / 16.0f, -FLT_MIN / 16.0f,
364 SK_FloatNaN, SK_FloatInfinity, SK_FloatNegativeInfinity,
365 -FLT_MIN / 8388608.0
366 };
367 for (float inputFloat: alwaysCheck) {
368 check_pdf_scalar_serialization(reporter, inputFloat);
369 }
370 }
371
372 // Test SkPDFUtils:: for accuracy.
DEF_TEST(SkPDF_Primitives_Color,reporter)373 DEF_TEST(SkPDF_Primitives_Color, reporter) {
374 char buffer[5];
375 for (int i = 0; i < 256; ++i) {
376 size_t len = SkPDFUtils::ColorToDecimal(i, buffer);
377 REPORTER_ASSERT(reporter, len == strlen(buffer));
378 float f;
379 REPORTER_ASSERT(reporter, 1 == sscanf(buffer, "%f", &f));
380 int roundTrip = (int)(0.5 + f * 255);
381 REPORTER_ASSERT(reporter, roundTrip == i);
382 }
383 }
384
make_run(size_t len,const SkGlyphID * glyphs,SkPoint * pos,const SkFont & font,const uint32_t * clusters,size_t utf8TextByteLength,const char * utf8Text)385 static SkGlyphRun make_run(size_t len, const SkGlyphID* glyphs, SkPoint* pos,
386 const SkFont& font, const uint32_t* clusters,
387 size_t utf8TextByteLength, const char* utf8Text) {
388 return SkGlyphRun(font,
389 SkSpan<const SkPoint>{pos, len},
390 SkSpan<const SkGlyphID>{glyphs, len},
391 SkSpan<const char>{utf8Text, utf8TextByteLength},
392 SkSpan<const uint32_t>{clusters, len});
393 }
394
DEF_TEST(SkPDF_Clusterator,reporter)395 DEF_TEST(SkPDF_Clusterator, reporter) {
396 SkFont font;
397 {
398 constexpr unsigned len = 11;
399 const uint32_t clusters[len] = { 3, 2, 2, 1, 0, 4, 4, 7, 6, 6, 5 };
400 const SkGlyphID glyphs[len] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
401 SkPoint pos[len] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
402 {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}};
403 const char text[] = "abcdefgh";
404 SkGlyphRun run = make_run(len, glyphs, pos, font, clusters, strlen(text), text);
405 SkClusterator clusterator(run);
406 SkClusterator::Cluster expectations[] = {
407 {&text[3], 1, 0, 1},
408 {&text[2], 1, 1, 2},
409 {&text[1], 1, 3, 1},
410 {&text[0], 1, 4, 1},
411 {&text[4], 1, 5, 2},
412 {&text[7], 1, 7, 1},
413 {&text[6], 1, 8, 2},
414 {&text[5], 1, 10, 1},
415 {nullptr, 0, 0, 0},
416 };
417 for (const auto& expectation : expectations) {
418 REPORTER_ASSERT(reporter, clusterator.next() == expectation);
419 }
420 }
421 {
422 constexpr unsigned len = 5;
423 const uint32_t clusters[len] = { 0, 1, 4, 5, 6 };
424 const SkGlyphID glyphs[len] = { 43, 167, 79, 79, 82, };
425 SkPoint pos[len] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}};
426 const char text[] = "Ha\xCC\x8A" "llo";
427 SkGlyphRun run = make_run(len, glyphs, pos, font, clusters, strlen(text), text);
428 SkClusterator clusterator(run);
429 SkClusterator::Cluster expectations[] = {
430 {&text[0], 1, 0, 1},
431 {&text[1], 3, 1, 1},
432 {&text[4], 1, 2, 1},
433 {&text[5], 1, 3, 1},
434 {&text[6], 1, 4, 1},
435 {nullptr, 0, 0, 0},
436 };
437 for (const auto& expectation : expectations) {
438 REPORTER_ASSERT(reporter, clusterator.next() == expectation);
439 }
440 }
441 }
442
443 #endif
444