Line data Source code
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 :
20 0 : sk_sp<SkPDFArray> SkPDFUtils::RectToArray(const SkRect& rect) {
21 0 : auto result = sk_make_sp<SkPDFArray>();
22 0 : result->reserve(4);
23 0 : result->appendScalar(rect.fLeft);
24 0 : result->appendScalar(rect.fTop);
25 0 : result->appendScalar(rect.fRight);
26 0 : result->appendScalar(rect.fBottom);
27 0 : return result;
28 : }
29 :
30 0 : sk_sp<SkPDFArray> SkPDFUtils::MatrixToArray(const SkMatrix& matrix) {
31 : SkScalar values[6];
32 0 : if (!matrix.asAffine(values)) {
33 0 : SkMatrix::SetAffineIdentity(values);
34 : }
35 :
36 0 : auto result = sk_make_sp<SkPDFArray>();
37 0 : result->reserve(6);
38 0 : for (size_t i = 0; i < SK_ARRAY_COUNT(values); i++) {
39 0 : result->appendScalar(values[i]);
40 : }
41 0 : return result;
42 : }
43 :
44 : // static
45 0 : void SkPDFUtils::AppendTransform(const SkMatrix& matrix, SkWStream* content) {
46 : SkScalar values[6];
47 0 : if (!matrix.asAffine(values)) {
48 0 : SkMatrix::SetAffineIdentity(values);
49 : }
50 0 : for (size_t i = 0; i < SK_ARRAY_COUNT(values); i++) {
51 0 : SkPDFUtils::AppendScalar(values[i], content);
52 0 : content->writeText(" ");
53 : }
54 0 : content->writeText("cm\n");
55 0 : }
56 :
57 : // static
58 0 : void SkPDFUtils::MoveTo(SkScalar x, SkScalar y, SkWStream* content) {
59 0 : SkPDFUtils::AppendScalar(x, content);
60 0 : content->writeText(" ");
61 0 : SkPDFUtils::AppendScalar(y, content);
62 0 : content->writeText(" m\n");
63 0 : }
64 :
65 : // static
66 0 : void SkPDFUtils::AppendLine(SkScalar x, SkScalar y, SkWStream* content) {
67 0 : SkPDFUtils::AppendScalar(x, content);
68 0 : content->writeText(" ");
69 0 : SkPDFUtils::AppendScalar(y, content);
70 0 : content->writeText(" l\n");
71 0 : }
72 :
73 : // static
74 0 : void SkPDFUtils::AppendCubic(SkScalar ctl1X, SkScalar ctl1Y,
75 : SkScalar ctl2X, SkScalar ctl2Y,
76 : SkScalar dstX, SkScalar dstY, SkWStream* content) {
77 0 : SkString cmd("y\n");
78 0 : SkPDFUtils::AppendScalar(ctl1X, content);
79 0 : content->writeText(" ");
80 0 : SkPDFUtils::AppendScalar(ctl1Y, content);
81 0 : content->writeText(" ");
82 0 : if (ctl2X != dstX || ctl2Y != dstY) {
83 0 : cmd.set("c\n");
84 0 : SkPDFUtils::AppendScalar(ctl2X, content);
85 0 : content->writeText(" ");
86 0 : SkPDFUtils::AppendScalar(ctl2Y, content);
87 0 : content->writeText(" ");
88 : }
89 0 : SkPDFUtils::AppendScalar(dstX, content);
90 0 : content->writeText(" ");
91 0 : SkPDFUtils::AppendScalar(dstY, content);
92 0 : content->writeText(" ");
93 0 : content->writeText(cmd.c_str());
94 0 : }
95 :
96 0 : static void append_quad(const SkPoint quad[], SkWStream* content) {
97 : SkPoint cubic[4];
98 0 : SkConvertQuadToCubic(quad, cubic);
99 0 : SkPDFUtils::AppendCubic(cubic[1].fX, cubic[1].fY, cubic[2].fX, cubic[2].fY,
100 0 : cubic[3].fX, cubic[3].fY, content);
101 0 : }
102 :
103 : // static
104 0 : 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 0 : SkScalar bottom = SkMinScalar(rect.fBottom, rect.fTop);
107 :
108 0 : SkPDFUtils::AppendScalar(rect.fLeft, content);
109 0 : content->writeText(" ");
110 0 : SkPDFUtils::AppendScalar(bottom, content);
111 0 : content->writeText(" ");
112 0 : SkPDFUtils::AppendScalar(rect.width(), content);
113 0 : content->writeText(" ");
114 0 : SkPDFUtils::AppendScalar(rect.height(), content);
115 0 : content->writeText(" re\n");
116 0 : }
117 :
118 : // static
119 0 : 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 0 : if (path.isRect(&rect, &isClosed, &direction) &&
131 0 : isClosed && SkPath::kCW_Direction == direction)
132 : {
133 0 : SkPDFUtils::AppendRectangle(rect, content);
134 0 : return;
135 : }
136 :
137 : enum SkipFillState {
138 : kEmpty_SkipFillState,
139 : kSingleLine_SkipFillState,
140 : kNonSingleLine_SkipFillState,
141 : };
142 0 : SkipFillState fillState = kEmpty_SkipFillState;
143 : //if (paintStyle != SkPaint::kFill_Style) {
144 : // fillState = kNonSingleLine_SkipFillState;
145 : //}
146 0 : SkPoint lastMovePt = SkPoint::Make(0,0);
147 0 : SkDynamicMemoryWStream currentSegment;
148 : SkPoint args[4];
149 0 : SkPath::Iter iter(path, false);
150 0 : for (SkPath::Verb verb = iter.next(args, doConsumeDegerates);
151 0 : verb != SkPath::kDone_Verb;
152 0 : verb = iter.next(args, doConsumeDegerates)) {
153 : // args gets all the points, even the implicit first point.
154 0 : switch (verb) {
155 : case SkPath::kMove_Verb:
156 0 : MoveTo(args[0].fX, args[0].fY, ¤tSegment);
157 0 : lastMovePt = args[0];
158 0 : fillState = kEmpty_SkipFillState;
159 0 : break;
160 : case SkPath::kLine_Verb:
161 0 : AppendLine(args[1].fX, args[1].fY, ¤tSegment);
162 0 : if ((fillState == kEmpty_SkipFillState) && (args[0] != lastMovePt)) {
163 0 : fillState = kSingleLine_SkipFillState;
164 0 : break;
165 : }
166 0 : fillState = kNonSingleLine_SkipFillState;
167 0 : break;
168 : case SkPath::kQuad_Verb:
169 0 : append_quad(args, ¤tSegment);
170 0 : fillState = kNonSingleLine_SkipFillState;
171 0 : break;
172 : case SkPath::kConic_Verb: {
173 0 : SkAutoConicToQuads converter;
174 0 : const SkPoint* quads = converter.computeQuads(args, iter.conicWeight(), tolerance);
175 0 : for (int i = 0; i < converter.countQuads(); ++i) {
176 0 : append_quad(&quads[i * 2], ¤tSegment);
177 : }
178 0 : fillState = kNonSingleLine_SkipFillState;
179 0 : } break;
180 : case SkPath::kCubic_Verb:
181 0 : AppendCubic(args[1].fX, args[1].fY, args[2].fX, args[2].fY,
182 0 : args[3].fX, args[3].fY, ¤tSegment);
183 0 : fillState = kNonSingleLine_SkipFillState;
184 0 : break;
185 : case SkPath::kClose_Verb:
186 0 : ClosePath(¤tSegment);
187 0 : currentSegment.writeToStream(content);
188 0 : currentSegment.reset();
189 0 : break;
190 : default:
191 0 : SkASSERT(false);
192 0 : break;
193 : }
194 : }
195 0 : if (currentSegment.bytesWritten() > 0) {
196 0 : currentSegment.writeToStream(content);
197 : }
198 : }
199 :
200 : // static
201 0 : void SkPDFUtils::ClosePath(SkWStream* content) {
202 0 : content->writeText("h\n");
203 0 : }
204 :
205 : // static
206 0 : void SkPDFUtils::PaintPath(SkPaint::Style style, SkPath::FillType fill,
207 : SkWStream* content) {
208 0 : if (style == SkPaint::kFill_Style) {
209 0 : content->writeText("f");
210 0 : } else if (style == SkPaint::kStrokeAndFill_Style) {
211 0 : content->writeText("B");
212 0 : } else if (style == SkPaint::kStroke_Style) {
213 0 : content->writeText("S");
214 : }
215 :
216 0 : if (style != SkPaint::kStroke_Style) {
217 : NOT_IMPLEMENTED(fill == SkPath::kInverseEvenOdd_FillType, false);
218 : NOT_IMPLEMENTED(fill == SkPath::kInverseWinding_FillType, false);
219 0 : if (fill == SkPath::kEvenOdd_FillType) {
220 0 : content->writeText("*");
221 : }
222 : }
223 0 : content->writeText("\n");
224 0 : }
225 :
226 : // static
227 0 : void SkPDFUtils::StrokePath(SkWStream* content) {
228 : SkPDFUtils::PaintPath(
229 0 : SkPaint::kStroke_Style, SkPath::kWinding_FillType, content);
230 0 : }
231 :
232 : // static
233 0 : void SkPDFUtils::DrawFormXObject(int objectIndex, SkWStream* content) {
234 0 : content->writeText("/");
235 0 : content->writeText(SkPDFResourceDict::getResourceName(
236 : SkPDFResourceDict::kXObject_ResourceType,
237 0 : objectIndex).c_str());
238 0 : content->writeText(" Do\n");
239 0 : }
240 :
241 : // static
242 0 : void SkPDFUtils::ApplyGraphicState(int objectIndex, SkWStream* content) {
243 0 : content->writeText("/");
244 0 : content->writeText(SkPDFResourceDict::getResourceName(
245 : SkPDFResourceDict::kExtGState_ResourceType,
246 0 : objectIndex).c_str());
247 0 : content->writeText(" gs\n");
248 0 : }
249 :
250 : // static
251 0 : 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 0 : objectIndex);
257 0 : content->writeText("/Pattern CS/Pattern cs/");
258 0 : content->writeText(resourceName.c_str());
259 0 : content->writeText(" SCN/");
260 0 : content->writeText(resourceName.c_str());
261 0 : content->writeText(" scn\n");
262 0 : }
263 :
264 0 : size_t SkPDFUtils::ColorToDecimal(uint8_t value, char result[5]) {
265 0 : if (value == 255 || value == 0) {
266 0 : result[0] = value ? '1' : '0';
267 0 : result[1] = '\0';
268 0 : return 1;
269 : }
270 : // int x = 0.5 + (1000.0 / 255.0) * value;
271 0 : int x = SkFixedRoundToInt((SK_Fixed1 * 1000 / 255) * value);
272 0 : result[0] = '.';
273 0 : for (int i = 3; i > 0; --i) {
274 0 : result[i] = '0' + x % 10;
275 0 : x /= 10;
276 : }
277 : int j;
278 0 : for (j = 3; j > 1; --j) {
279 0 : if (result[j] != '0') {
280 0 : break;
281 : }
282 : }
283 0 : result[j + 1] = '\0';
284 0 : return j + 1;
285 : }
286 :
287 0 : void SkPDFUtils::AppendScalar(SkScalar value, SkWStream* stream) {
288 : char result[kMaximumFloatDecimalLength];
289 0 : size_t len = SkPDFUtils::FloatToDecimal(SkScalarToFloat(value), result);
290 0 : SkASSERT(len < kMaximumFloatDecimalLength);
291 0 : stream->write(result, len);
292 0 : }
293 :
294 : // Return pow(10.0, e), optimized for common cases.
295 0 : inline double pow10(int e) {
296 0 : switch (e) {
297 0 : case 0: return 1.0; // common cases
298 0 : case 1: return 10.0;
299 0 : case 2: return 100.0;
300 0 : case 3: return 1e+03;
301 0 : case 4: return 1e+04;
302 0 : case 5: return 1e+05;
303 0 : case 6: return 1e+06;
304 0 : case 7: return 1e+07;
305 0 : case 8: return 1e+08;
306 0 : case 9: return 1e+09;
307 0 : case 10: return 1e+10;
308 0 : case 11: return 1e+11;
309 0 : case 12: return 1e+12;
310 0 : case 13: return 1e+13;
311 0 : case 14: return 1e+14;
312 0 : case 15: return 1e+15;
313 : default:
314 0 : if (e > 15) {
315 0 : double value = 1e+15;
316 0 : while (e-- > 15) { value *= 10.0; }
317 0 : return value;
318 : } else {
319 0 : SkASSERT(e < 0);
320 0 : double value = 1.0;
321 0 : while (e++ < 0) { value /= 10.0; }
322 0 : 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. */
336 0 : 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 0 : char* output = &result[0];
352 0 : 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 0 : if (value == SK_FloatInfinity) {
360 0 : value = FLT_MAX; // nearest finite float.
361 : }
362 0 : if (value == SK_FloatNegativeInfinity) {
363 0 : value = -FLT_MAX; // nearest finite float.
364 : }
365 0 : 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 0 : *output++ = '0';
369 0 : *output = '\0';
370 0 : return output - result;
371 : }
372 0 : if (value < 0.0) {
373 0 : *output++ = '-';
374 0 : value = -value;
375 : }
376 0 : SkASSERT(value >= 0.0f);
377 :
378 : int binaryExponent;
379 0 : (void)std::frexp(value, &binaryExponent);
380 : static const double kLog2 = 0.3010299956639812; // log10(2.0);
381 0 : int decimalExponent = static_cast<int>(std::floor(kLog2 * binaryExponent));
382 0 : int decimalShift = decimalExponent - 8;
383 0 : double power = pow10(-decimalShift);
384 0 : int32_t d = static_cast<int32_t>(value * power + 0.5);
385 : // SkASSERT(value == (float)(d * pow(10.0, decimalShift)));
386 0 : SkASSERT(d <= 999999999);
387 0 : if (d > 167772159) { // floor(pow(10,1+log10(1<<24)))
388 : // need one fewer decimal digits for 24-bit precision.
389 0 : decimalShift = decimalExponent - 7;
390 : // SkASSERT(power * 0.1 = pow10(-decimalShift));
391 : // recalculate to get rounding right.
392 0 : d = static_cast<int32_t>(value * (power * 0.1) + 0.5);
393 0 : SkASSERT(d <= 99999999);
394 : }
395 0 : while (d % 10 == 0) {
396 0 : d /= 10;
397 0 : ++decimalShift;
398 : }
399 0 : SkASSERT(d > 0);
400 : // SkASSERT(value == (float)(d * pow(10.0, decimalShift)));
401 : uint8_t buffer[9]; // decimal value buffer.
402 0 : int bufferIndex = 0;
403 0 : do {
404 0 : buffer[bufferIndex++] = d % 10;
405 0 : d /= 10;
406 0 : } while (d != 0);
407 0 : SkASSERT(bufferIndex <= (int)sizeof(buffer) && bufferIndex > 0);
408 0 : if (decimalShift >= 0) {
409 0 : do {
410 0 : --bufferIndex;
411 0 : *output++ = '0' + buffer[bufferIndex];
412 0 : } while (bufferIndex);
413 0 : for (int i = 0; i < decimalShift; ++i) {
414 0 : *output++ = '0';
415 : }
416 : } else {
417 0 : int placesBeforeDecimal = bufferIndex + decimalShift;
418 0 : if (placesBeforeDecimal > 0) {
419 0 : while (placesBeforeDecimal-- > 0) {
420 0 : --bufferIndex;
421 0 : *output++ = '0' + buffer[bufferIndex];
422 : }
423 0 : *output++ = '.';
424 : } else {
425 0 : *output++ = '.';
426 0 : int placesAfterDecimal = -placesBeforeDecimal;
427 0 : while (placesAfterDecimal-- > 0) {
428 0 : *output++ = '0';
429 : }
430 : }
431 0 : while (bufferIndex > 0) {
432 0 : --bufferIndex;
433 0 : *output++ = '0' + buffer[bufferIndex];
434 0 : if (output == end) {
435 0 : 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 0 : SkASSERT(output <= end);
442 0 : *output = '\0';
443 0 : return output - result;
444 : }
445 :
446 0 : void SkPDFUtils::WriteString(SkWStream* wStream, const char* cin, size_t len) {
447 : SkDEBUGCODE(static const size_t kMaxLen = 65535;)
448 0 : SkASSERT(len <= kMaxLen);
449 :
450 0 : size_t extraCharacterCount = 0;
451 0 : for (size_t i = 0; i < len; i++) {
452 0 : if (cin[i] > '~' || cin[i] < ' ') {
453 0 : extraCharacterCount += 3;
454 : }
455 0 : if (cin[i] == '\\' || cin[i] == '(' || cin[i] == ')') {
456 0 : ++extraCharacterCount;
457 : }
458 : }
459 0 : if (extraCharacterCount <= len) {
460 0 : wStream->writeText("(");
461 0 : for (size_t i = 0; i < len; i++) {
462 0 : if (cin[i] > '~' || cin[i] < ' ') {
463 0 : uint8_t c = static_cast<uint8_t>(cin[i]);
464 : uint8_t octal[4];
465 0 : octal[0] = '\\';
466 0 : octal[1] = '0' + ( c >> 6 );
467 0 : octal[2] = '0' + ((c >> 3) & 0x07);
468 0 : octal[3] = '0' + ( c & 0x07);
469 0 : wStream->write(octal, 4);
470 : } else {
471 0 : if (cin[i] == '\\' || cin[i] == '(' || cin[i] == ')') {
472 0 : wStream->writeText("\\");
473 : }
474 0 : wStream->write(&cin[i], 1);
475 : }
476 : }
477 0 : wStream->writeText(")");
478 : } else {
479 0 : wStream->writeText("<");
480 0 : for (size_t i = 0; i < len; i++) {
481 0 : uint8_t c = static_cast<uint8_t>(cin[i]);
482 : static const char gHex[] = "0123456789ABCDEF";
483 : char hexValue[2];
484 0 : hexValue[0] = gHex[(c >> 4) & 0xF];
485 0 : hexValue[1] = gHex[ c & 0xF];
486 0 : wStream->write(hexValue, 2);
487 : }
488 0 : wStream->writeText(">");
489 : }
490 0 : }
|