1 /*
2  * Copyright 2011 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 
8 
9 #include "SkData.h"
10 #include "SkFixed.h"
11 #include "SkGeometry.h"
12 #include "SkPDFResourceDict.h"
13 #include "SkPDFUtils.h"
14 #include "SkStream.h"
15 #include "SkString.h"
16 #include "SkPDFTypes.h"
17 
18 #include <cmath>
19 
RectToArray(const SkRect & rect)20 sk_sp<SkPDFArray> SkPDFUtils::RectToArray(const SkRect& rect) {
21     auto result = sk_make_sp<SkPDFArray>();
22     result->reserve(4);
23     result->appendScalar(rect.fLeft);
24     result->appendScalar(rect.fTop);
25     result->appendScalar(rect.fRight);
26     result->appendScalar(rect.fBottom);
27     return result;
28 }
29 
MatrixToArray(const SkMatrix & matrix)30 sk_sp<SkPDFArray> SkPDFUtils::MatrixToArray(const SkMatrix& matrix) {
31     SkScalar values[6];
32     if (!matrix.asAffine(values)) {
33         SkMatrix::SetAffineIdentity(values);
34     }
35 
36     auto result = sk_make_sp<SkPDFArray>();
37     result->reserve(6);
38     for (size_t i = 0; i < SK_ARRAY_COUNT(values); i++) {
39         result->appendScalar(values[i]);
40     }
41     return result;
42 }
43 
44 // static
AppendTransform(const SkMatrix & matrix,SkWStream * content)45 void SkPDFUtils::AppendTransform(const SkMatrix& matrix, SkWStream* content) {
46     SkScalar values[6];
47     if (!matrix.asAffine(values)) {
48         SkMatrix::SetAffineIdentity(values);
49     }
50     for (size_t i = 0; i < SK_ARRAY_COUNT(values); i++) {
51         SkPDFUtils::AppendScalar(values[i], content);
52         content->writeText(" ");
53     }
54     content->writeText("cm\n");
55 }
56 
57 // static
MoveTo(SkScalar x,SkScalar y,SkWStream * content)58 void SkPDFUtils::MoveTo(SkScalar x, SkScalar y, SkWStream* content) {
59     SkPDFUtils::AppendScalar(x, content);
60     content->writeText(" ");
61     SkPDFUtils::AppendScalar(y, content);
62     content->writeText(" m\n");
63 }
64 
65 // static
AppendLine(SkScalar x,SkScalar y,SkWStream * content)66 void SkPDFUtils::AppendLine(SkScalar x, SkScalar y, SkWStream* content) {
67     SkPDFUtils::AppendScalar(x, content);
68     content->writeText(" ");
69     SkPDFUtils::AppendScalar(y, content);
70     content->writeText(" l\n");
71 }
72 
73 // static
AppendCubic(SkScalar ctl1X,SkScalar ctl1Y,SkScalar ctl2X,SkScalar ctl2Y,SkScalar dstX,SkScalar dstY,SkWStream * content)74 void SkPDFUtils::AppendCubic(SkScalar ctl1X, SkScalar ctl1Y,
75                              SkScalar ctl2X, SkScalar ctl2Y,
76                              SkScalar dstX, SkScalar dstY, SkWStream* content) {
77     SkString cmd("y\n");
78     SkPDFUtils::AppendScalar(ctl1X, content);
79     content->writeText(" ");
80     SkPDFUtils::AppendScalar(ctl1Y, content);
81     content->writeText(" ");
82     if (ctl2X != dstX || ctl2Y != dstY) {
83         cmd.set("c\n");
84         SkPDFUtils::AppendScalar(ctl2X, content);
85         content->writeText(" ");
86         SkPDFUtils::AppendScalar(ctl2Y, content);
87         content->writeText(" ");
88     }
89     SkPDFUtils::AppendScalar(dstX, content);
90     content->writeText(" ");
91     SkPDFUtils::AppendScalar(dstY, content);
92     content->writeText(" ");
93     content->writeText(cmd.c_str());
94 }
95 
append_quad(const SkPoint quad[],SkWStream * content)96 static void append_quad(const SkPoint quad[], SkWStream* content) {
97     SkPoint cubic[4];
98     SkConvertQuadToCubic(quad, cubic);
99     SkPDFUtils::AppendCubic(cubic[1].fX, cubic[1].fY, cubic[2].fX, cubic[2].fY,
100                             cubic[3].fX, cubic[3].fY, content);
101 }
102 
103 // static
AppendRectangle(const SkRect & rect,SkWStream * content)104 void SkPDFUtils::AppendRectangle(const SkRect& rect, SkWStream* content) {
105     // Skia has 0,0 at top left, pdf at bottom left.  Do the right thing.
106     SkScalar bottom = SkMinScalar(rect.fBottom, rect.fTop);
107 
108     SkPDFUtils::AppendScalar(rect.fLeft, content);
109     content->writeText(" ");
110     SkPDFUtils::AppendScalar(bottom, content);
111     content->writeText(" ");
112     SkPDFUtils::AppendScalar(rect.width(), content);
113     content->writeText(" ");
114     SkPDFUtils::AppendScalar(rect.height(), content);
115     content->writeText(" re\n");
116 }
117 
118 // static
EmitPath(const SkPath & path,SkPaint::Style paintStyle,bool doConsumeDegerates,SkWStream * content,SkScalar tolerance)119 void SkPDFUtils::EmitPath(const SkPath& path, SkPaint::Style paintStyle,
120                           bool doConsumeDegerates, SkWStream* content,
121                           SkScalar tolerance) {
122     // Filling a path with no area results in a drawing in PDF renderers but
123     // Chrome expects to be able to draw some such entities with no visible
124     // result, so we detect those cases and discard the drawing for them.
125     // Specifically: moveTo(X), lineTo(Y) and moveTo(X), lineTo(X), lineTo(Y).
126 
127     SkRect rect;
128     bool isClosed; // Both closure and direction need to be checked.
129     SkPath::Direction direction;
130     if (path.isRect(&rect, &isClosed, &direction) &&
131         isClosed && SkPath::kCW_Direction == direction)
132     {
133         SkPDFUtils::AppendRectangle(rect, content);
134         return;
135     }
136 
137     enum SkipFillState {
138         kEmpty_SkipFillState,
139         kSingleLine_SkipFillState,
140         kNonSingleLine_SkipFillState,
141     };
142     SkipFillState fillState = kEmpty_SkipFillState;
143     //if (paintStyle != SkPaint::kFill_Style) {
144     //    fillState = kNonSingleLine_SkipFillState;
145     //}
146     SkPoint lastMovePt = SkPoint::Make(0,0);
147     SkDynamicMemoryWStream currentSegment;
148     SkPoint args[4];
149     SkPath::Iter iter(path, false);
150     for (SkPath::Verb verb = iter.next(args, doConsumeDegerates);
151          verb != SkPath::kDone_Verb;
152          verb = iter.next(args, doConsumeDegerates)) {
153         // args gets all the points, even the implicit first point.
154         switch (verb) {
155             case SkPath::kMove_Verb:
156                 MoveTo(args[0].fX, args[0].fY, &currentSegment);
157                 lastMovePt = args[0];
158                 fillState = kEmpty_SkipFillState;
159                 break;
160             case SkPath::kLine_Verb:
161                 AppendLine(args[1].fX, args[1].fY, &currentSegment);
162                 if ((fillState == kEmpty_SkipFillState) && (args[0] != lastMovePt)) {
163                     fillState = kSingleLine_SkipFillState;
164                     break;
165                 }
166                 fillState = kNonSingleLine_SkipFillState;
167                 break;
168             case SkPath::kQuad_Verb:
169                 append_quad(args, &currentSegment);
170                 fillState = kNonSingleLine_SkipFillState;
171                 break;
172             case SkPath::kConic_Verb: {
173                 SkAutoConicToQuads converter;
174                 const SkPoint* quads = converter.computeQuads(args, iter.conicWeight(), tolerance);
175                 for (int i = 0; i < converter.countQuads(); ++i) {
176                     append_quad(&quads[i * 2], &currentSegment);
177                 }
178                 fillState = kNonSingleLine_SkipFillState;
179             } break;
180             case SkPath::kCubic_Verb:
181                 AppendCubic(args[1].fX, args[1].fY, args[2].fX, args[2].fY,
182                             args[3].fX, args[3].fY, &currentSegment);
183                 fillState = kNonSingleLine_SkipFillState;
184                 break;
185             case SkPath::kClose_Verb:
186                 ClosePath(&currentSegment);
187                 currentSegment.writeToStream(content);
188                 currentSegment.reset();
189                 break;
190             default:
191                 SkASSERT(false);
192                 break;
193         }
194     }
195     if (currentSegment.bytesWritten() > 0) {
196         currentSegment.writeToStream(content);
197     }
198 }
199 
200 // static
ClosePath(SkWStream * content)201 void SkPDFUtils::ClosePath(SkWStream* content) {
202     content->writeText("h\n");
203 }
204 
205 // static
PaintPath(SkPaint::Style style,SkPath::FillType fill,SkWStream * content)206 void SkPDFUtils::PaintPath(SkPaint::Style style, SkPath::FillType fill,
207                            SkWStream* content) {
208     if (style == SkPaint::kFill_Style) {
209         content->writeText("f");
210     } else if (style == SkPaint::kStrokeAndFill_Style) {
211         content->writeText("B");
212     } else if (style == SkPaint::kStroke_Style) {
213         content->writeText("S");
214     }
215 
216     if (style != SkPaint::kStroke_Style) {
217         NOT_IMPLEMENTED(fill == SkPath::kInverseEvenOdd_FillType, false);
218         NOT_IMPLEMENTED(fill == SkPath::kInverseWinding_FillType, false);
219         if (fill == SkPath::kEvenOdd_FillType) {
220             content->writeText("*");
221         }
222     }
223     content->writeText("\n");
224 }
225 
226 // static
StrokePath(SkWStream * content)227 void SkPDFUtils::StrokePath(SkWStream* content) {
228     SkPDFUtils::PaintPath(
229         SkPaint::kStroke_Style, SkPath::kWinding_FillType, content);
230 }
231 
232 // static
DrawFormXObject(int objectIndex,SkWStream * content)233 void SkPDFUtils::DrawFormXObject(int objectIndex, SkWStream* content) {
234     content->writeText("/");
235     content->writeText(SkPDFResourceDict::getResourceName(
236             SkPDFResourceDict::kXObject_ResourceType,
237             objectIndex).c_str());
238     content->writeText(" Do\n");
239 }
240 
241 // static
ApplyGraphicState(int objectIndex,SkWStream * content)242 void SkPDFUtils::ApplyGraphicState(int objectIndex, SkWStream* content) {
243     content->writeText("/");
244     content->writeText(SkPDFResourceDict::getResourceName(
245             SkPDFResourceDict::kExtGState_ResourceType,
246             objectIndex).c_str());
247     content->writeText(" gs\n");
248 }
249 
250 // static
ApplyPattern(int objectIndex,SkWStream * content)251 void SkPDFUtils::ApplyPattern(int objectIndex, SkWStream* content) {
252     // Select Pattern color space (CS, cs) and set pattern object as current
253     // color (SCN, scn)
254     SkString resourceName = SkPDFResourceDict::getResourceName(
255             SkPDFResourceDict::kPattern_ResourceType,
256             objectIndex);
257     content->writeText("/Pattern CS/Pattern cs/");
258     content->writeText(resourceName.c_str());
259     content->writeText(" SCN/");
260     content->writeText(resourceName.c_str());
261     content->writeText(" scn\n");
262 }
263 
ColorToDecimal(uint8_t value,char result[5])264 size_t SkPDFUtils::ColorToDecimal(uint8_t value, char result[5]) {
265     if (value == 255 || value == 0) {
266         result[0] = value ? '1' : '0';
267         result[1] = '\0';
268         return 1;
269     }
270     // int x = 0.5 + (1000.0 / 255.0) * value;
271     int x = SkFixedRoundToInt((SK_Fixed1 * 1000 / 255) * value);
272     result[0] = '.';
273     for (int i = 3; i > 0; --i) {
274         result[i] = '0' + x % 10;
275         x /= 10;
276     }
277     int j;
278     for (j = 3; j > 1; --j) {
279         if (result[j] != '0') {
280             break;
281         }
282     }
283     result[j + 1] = '\0';
284     return j + 1;
285 }
286 
AppendScalar(SkScalar value,SkWStream * stream)287 void SkPDFUtils::AppendScalar(SkScalar value, SkWStream* stream) {
288     char result[kMaximumFloatDecimalLength];
289     size_t len = SkPDFUtils::FloatToDecimal(SkScalarToFloat(value), result);
290     SkASSERT(len < kMaximumFloatDecimalLength);
291     stream->write(result, len);
292 }
293 
294 // Return pow(10.0, e), optimized for common cases.
pow10(int e)295 inline double pow10(int e) {
296     switch (e) {
297         case 0:  return 1.0;  // common cases
298         case 1:  return 10.0;
299         case 2:  return 100.0;
300         case 3:  return 1e+03;
301         case 4:  return 1e+04;
302         case 5:  return 1e+05;
303         case 6:  return 1e+06;
304         case 7:  return 1e+07;
305         case 8:  return 1e+08;
306         case 9:  return 1e+09;
307         case 10: return 1e+10;
308         case 11: return 1e+11;
309         case 12: return 1e+12;
310         case 13: return 1e+13;
311         case 14: return 1e+14;
312         case 15: return 1e+15;
313         default:
314             if (e > 15) {
315                 double value = 1e+15;
316                 while (e-- > 15) { value *= 10.0; }
317                 return value;
318             } else {
319                 SkASSERT(e < 0);
320                 double value = 1.0;
321                 while (e++ < 0) { value /= 10.0; }
322                 return value;
323             }
324     }
325 }
326 
327 /** Write a string into result, includeing a terminating '\0' (for
328     unit testing).  Return strlen(result) (for SkWStream::write) The
329     resulting string will be in the form /[-]?([0-9]*.)?[0-9]+/ and
330     sscanf(result, "%f", &x) will return the original value iff the
331     value is finite. This function accepts all possible input values.
332 
333     Motivation: "PDF does not support [numbers] in exponential format
334     (such as 6.02e23)."  Otherwise, this function would rely on a
335     sprintf-type function from the standard library. */
FloatToDecimal(float value,char result[kMaximumFloatDecimalLength])336 size_t SkPDFUtils::FloatToDecimal(float value,
337                                   char result[kMaximumFloatDecimalLength]) {
338     /* The longest result is -FLT_MIN.
339        We serialize it as "-.0000000000000000000000000000000000000117549435"
340        which has 48 characters plus a terminating '\0'. */
341 
342     /* section C.1 of the PDF1.4 spec (http://goo.gl/0SCswJ) says that
343        most PDF rasterizers will use fixed-point scalars that lack the
344        dynamic range of floats.  Even if this is the case, I want to
345        serialize these (uncommon) very small and very large scalar
346        values with enough precision to allow a floating-point
347        rasterizer to read them in with perfect accuracy.
348        Experimentally, rasterizers such as pdfium do seem to benefit
349        from this.  Rasterizers that rely on fixed-point scalars should
350        gracefully ignore these values that they can not parse. */
351     char* output = &result[0];
352     const char* const end = &result[kMaximumFloatDecimalLength - 1];
353     // subtract one to leave space for '\0'.
354 
355     /* This function is written to accept any possible input value,
356        including non-finite values such as INF and NAN.  In that case,
357        we ignore value-correctness and and output a syntacticly-valid
358        number. */
359     if (value == SK_FloatInfinity) {
360         value = FLT_MAX;  // nearest finite float.
361     }
362     if (value == SK_FloatNegativeInfinity) {
363         value = -FLT_MAX;  // nearest finite float.
364     }
365     if (!std::isfinite(value) || value == 0.0f) {
366         // NAN is unsupported in PDF.  Always output a valid number.
367         // Also catch zero here, as a special case.
368         *output++ = '0';
369         *output = '\0';
370         return output - result;
371     }
372     if (value < 0.0) {
373         *output++ = '-';
374         value = -value;
375     }
376     SkASSERT(value >= 0.0f);
377 
378     int binaryExponent;
379     (void)std::frexp(value, &binaryExponent);
380     static const double kLog2 = 0.3010299956639812;  // log10(2.0);
381     int decimalExponent = static_cast<int>(std::floor(kLog2 * binaryExponent));
382     int decimalShift = decimalExponent - 8;
383     double power = pow10(-decimalShift);
384     int32_t d = static_cast<int32_t>(value * power + 0.5);
385     // SkASSERT(value == (float)(d * pow(10.0, decimalShift)));
386     SkASSERT(d <= 999999999);
387     if (d > 167772159) {  // floor(pow(10,1+log10(1<<24)))
388        // need one fewer decimal digits for 24-bit precision.
389        decimalShift = decimalExponent - 7;
390        // SkASSERT(power * 0.1 = pow10(-decimalShift));
391        // recalculate to get rounding right.
392        d = static_cast<int32_t>(value * (power * 0.1) + 0.5);
393        SkASSERT(d <= 99999999);
394     }
395     while (d % 10 == 0) {
396         d /= 10;
397         ++decimalShift;
398     }
399     SkASSERT(d > 0);
400     // SkASSERT(value == (float)(d * pow(10.0, decimalShift)));
401     uint8_t buffer[9]; // decimal value buffer.
402     int bufferIndex = 0;
403     do {
404         buffer[bufferIndex++] = d % 10;
405         d /= 10;
406     } while (d != 0);
407     SkASSERT(bufferIndex <= (int)sizeof(buffer) && bufferIndex > 0);
408     if (decimalShift >= 0) {
409         do {
410             --bufferIndex;
411             *output++ = '0' + buffer[bufferIndex];
412         } while (bufferIndex);
413         for (int i = 0; i < decimalShift; ++i) {
414             *output++ = '0';
415         }
416     } else {
417         int placesBeforeDecimal = bufferIndex + decimalShift;
418         if (placesBeforeDecimal > 0) {
419             while (placesBeforeDecimal-- > 0) {
420                 --bufferIndex;
421                 *output++ = '0' + buffer[bufferIndex];
422             }
423             *output++ = '.';
424         } else {
425             *output++ = '.';
426             int placesAfterDecimal = -placesBeforeDecimal;
427             while (placesAfterDecimal-- > 0) {
428                 *output++ = '0';
429             }
430         }
431         while (bufferIndex > 0) {
432             --bufferIndex;
433             *output++ = '0' + buffer[bufferIndex];
434             if (output == end) {
435                 break;  // denormalized: don't need extra precision.
436                 // Note: denormalized numbers will not have the same number of
437                 // significantDigits, but do not need them to round-trip.
438             }
439         }
440     }
441     SkASSERT(output <= end);
442     *output = '\0';
443     return output - result;
444 }
445 
WriteString(SkWStream * wStream,const char * cin,size_t len)446 void SkPDFUtils::WriteString(SkWStream* wStream, const char* cin, size_t len) {
447     SkDEBUGCODE(static const size_t kMaxLen = 65535;)
448     SkASSERT(len <= kMaxLen);
449 
450     size_t extraCharacterCount = 0;
451     for (size_t i = 0; i < len; i++) {
452         if (cin[i] > '~' || cin[i] < ' ') {
453             extraCharacterCount += 3;
454         }
455         if (cin[i] == '\\' || cin[i] == '(' || cin[i] == ')') {
456             ++extraCharacterCount;
457         }
458     }
459     if (extraCharacterCount <= len) {
460         wStream->writeText("(");
461         for (size_t i = 0; i < len; i++) {
462             if (cin[i] > '~' || cin[i] < ' ') {
463                 uint8_t c = static_cast<uint8_t>(cin[i]);
464                 uint8_t octal[4];
465                 octal[0] = '\\';
466                 octal[1] = '0' + ( c >> 6        );
467                 octal[2] = '0' + ((c >> 3) & 0x07);
468                 octal[3] = '0' + ( c       & 0x07);
469                 wStream->write(octal, 4);
470             } else {
471                 if (cin[i] == '\\' || cin[i] == '(' || cin[i] == ')') {
472                     wStream->writeText("\\");
473                 }
474                 wStream->write(&cin[i], 1);
475             }
476         }
477         wStream->writeText(")");
478     } else {
479         wStream->writeText("<");
480         for (size_t i = 0; i < len; i++) {
481             uint8_t c = static_cast<uint8_t>(cin[i]);
482             static const char gHex[] = "0123456789ABCDEF";
483             char hexValue[2];
484             hexValue[0] = gHex[(c >> 4) & 0xF];
485             hexValue[1] = gHex[ c       & 0xF];
486             wStream->write(hexValue, 2);
487         }
488         wStream->writeText(">");
489     }
490 }
491