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#include "src/pdf/SkPDFUtils.h"
9
10#include "include/core/SkData.h"
11#include "include/core/SkStream.h"
12#include "include/core/SkString.h"
13#include "include/private/SkFixed.h"
14#include "src/core/SkGeometry.h"
15#include "src/core/SkPathPriv.h"
16#include "src/image/SkImage_Base.h"
17#include "src/pdf/SkPDFResourceDict.h"
18#include "src/pdf/SkPDFTypes.h"
19
20#include <cmath>
21
22const char* SkPDFUtils::BlendModeName(SkBlendMode mode) {
23 // PDF32000.book section 11.3.5 "Blend Mode"
24 switch (mode) {
25 case SkBlendMode::kSrcOver: return "Normal";
26 case SkBlendMode::kXor: return "Normal"; // (unsupported mode)
27 case SkBlendMode::kPlus: return "Normal"; // (unsupported mode)
28 case SkBlendMode::kScreen: return "Screen";
29 case SkBlendMode::kOverlay: return "Overlay";
30 case SkBlendMode::kDarken: return "Darken";
31 case SkBlendMode::kLighten: return "Lighten";
32 case SkBlendMode::kColorDodge: return "ColorDodge";
33 case SkBlendMode::kColorBurn: return "ColorBurn";
34 case SkBlendMode::kHardLight: return "HardLight";
35 case SkBlendMode::kSoftLight: return "SoftLight";
36 case SkBlendMode::kDifference: return "Difference";
37 case SkBlendMode::kExclusion: return "Exclusion";
38 case SkBlendMode::kMultiply: return "Multiply";
39 case SkBlendMode::kHue: return "Hue";
40 case SkBlendMode::kSaturation: return "Saturation";
41 case SkBlendMode::kColor: return "Color";
42 case SkBlendMode::kLuminosity: return "Luminosity";
43 // Other blendmodes are handled in SkPDFDevice::setUpContentEntry.
44 default: return nullptr;
45 }
46}
47
48std::unique_ptr<SkPDFArray> SkPDFUtils::RectToArray(const SkRect& r) {
49 return SkPDFMakeArray(r.left(), r.top(), r.right(), r.bottom());
50}
51
52std::unique_ptr<SkPDFArray> SkPDFUtils::MatrixToArray(const SkMatrix& matrix) {
53 SkScalar a[6];
54 if (!matrix.asAffine(a)) {
55 SkMatrix::SetAffineIdentity(a);
56 }
57 return SkPDFMakeArray(a[0], a[1], a[2], a[3], a[4], a[5]);
58}
59
60void SkPDFUtils::MoveTo(SkScalar x, SkScalar y, SkWStream* content) {
61 SkPDFUtils::AppendScalar(x, content);
62 content->writeText(" ");
63 SkPDFUtils::AppendScalar(y, content);
64 content->writeText(" m\n");
65}
66
67void SkPDFUtils::AppendLine(SkScalar x, SkScalar y, SkWStream* content) {
68 SkPDFUtils::AppendScalar(x, content);
69 content->writeText(" ");
70 SkPDFUtils::AppendScalar(y, content);
71 content->writeText(" l\n");
72}
73
74static void append_cubic(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
96static void append_quad(const SkPoint quad[], SkWStream* content) {
97 SkPoint cubic[4];
98 SkConvertQuadToCubic(quad, cubic);
99 append_cubic(cubic[1].fX, cubic[1].fY, cubic[2].fX, cubic[2].fY,
100 cubic[3].fX, cubic[3].fY, content);
101}
102
103void SkPDFUtils::AppendRectangle(const SkRect& rect, SkWStream* content) {
104 // Skia has 0,0 at top left, pdf at bottom left. Do the right thing.
105 SkScalar bottom = std::min(rect.fBottom, rect.fTop);
106
107 SkPDFUtils::AppendScalar(rect.fLeft, content);
108 content->writeText(" ");
109 SkPDFUtils::AppendScalar(bottom, content);
110 content->writeText(" ");
111 SkPDFUtils::AppendScalar(rect.width(), content);
112 content->writeText(" ");
113 SkPDFUtils::AppendScalar(rect.height(), content);
114 content->writeText(" re\n");
115}
116
117void SkPDFUtils::EmitPath(const SkPath& path, SkPaint::Style paintStyle,
118 bool doConsumeDegerates, SkWStream* content,
119 SkScalar tolerance) {
120 if (path.isEmpty() && SkPaint::kFill_Style == paintStyle) {
121 SkPDFUtils::AppendRectangle({0, 0, 0, 0}, content);
122 return;
123 }
124 // Filling a path with no area results in a drawing in PDF renderers but
125 // Chrome expects to be able to draw some such entities with no visible
126 // result, so we detect those cases and discard the drawing for them.
127 // Specifically: moveTo(X), lineTo(Y) and moveTo(X), lineTo(X), lineTo(Y).
128
129 SkRect rect;
130 bool isClosed; // Both closure and direction need to be checked.
131 SkPathDirection direction;
132 if (path.isRect(&rect, &isClosed, &direction) &&
133 isClosed &&
134 (SkPathDirection::kCW == direction ||
135 SkPathFillType::kEvenOdd == path.getFillType()))
136 {
137 SkPDFUtils::AppendRectangle(rect, content);
138 return;
139 }
140
141 enum SkipFillState {
142 kEmpty_SkipFillState,
143 kSingleLine_SkipFillState,
144 kNonSingleLine_SkipFillState,
145 };
146 SkipFillState fillState = kEmpty_SkipFillState;
147 //if (paintStyle != SkPaint::kFill_Style) {
148 // fillState = kNonSingleLine_SkipFillState;
149 //}
150 SkPoint lastMovePt = SkPoint::Make(0,0);
151 SkDynamicMemoryWStream currentSegment;
152 SkPoint args[4];
153 SkPath::Iter iter(path, false);
154 for (SkPath::Verb verb = iter.next(args);
155 verb != SkPath::kDone_Verb;
156 verb = iter.next(args)) {
157 // args gets all the points, even the implicit first point.
158 switch (verb) {
159 case SkPath::kMove_Verb:
160 MoveTo(args[0].fX, args[0].fY, &currentSegment);
161 lastMovePt = args[0];
162 fillState = kEmpty_SkipFillState;
163 break;
164 case SkPath::kLine_Verb:
165 if (!doConsumeDegerates || !SkPathPriv::AllPointsEq(args, 2)) {
166 AppendLine(args[1].fX, args[1].fY, &currentSegment);
167 if ((fillState == kEmpty_SkipFillState) && (args[0] != lastMovePt)) {
168 fillState = kSingleLine_SkipFillState;
169 break;
170 }
171 fillState = kNonSingleLine_SkipFillState;
172 }
173 break;
174 case SkPath::kQuad_Verb:
175 if (!doConsumeDegerates || !SkPathPriv::AllPointsEq(args, 3)) {
176 append_quad(args, &currentSegment);
177 fillState = kNonSingleLine_SkipFillState;
178 }
179 break;
180 case SkPath::kConic_Verb:
181 if (!doConsumeDegerates || !SkPathPriv::AllPointsEq(args, 3)) {
182 SkAutoConicToQuads converter;
183 const SkPoint* quads = converter.computeQuads(args, iter.conicWeight(), tolerance);
184 for (int i = 0; i < converter.countQuads(); ++i) {
185 append_quad(&quads[i * 2], &currentSegment);
186 }
187 fillState = kNonSingleLine_SkipFillState;
188 }
189 break;
190 case SkPath::kCubic_Verb:
191 if (!doConsumeDegerates || !SkPathPriv::AllPointsEq(args, 4)) {
192 append_cubic(args[1].fX, args[1].fY, args[2].fX, args[2].fY,
193 args[3].fX, args[3].fY, &currentSegment);
194 fillState = kNonSingleLine_SkipFillState;
195 }
196 break;
197 case SkPath::kClose_Verb:
198 ClosePath(&currentSegment);
199 currentSegment.writeToStream(content);
200 currentSegment.reset();
201 break;
202 default:
203 SkASSERT(false);
204 break;
205 }
206 }
207 if (currentSegment.bytesWritten() > 0) {
208 currentSegment.writeToStream(content);
209 }
210}
211
212void SkPDFUtils::ClosePath(SkWStream* content) {
213 content->writeText("h\n");
214}
215
216void SkPDFUtils::PaintPath(SkPaint::Style style, SkPathFillType fill, SkWStream* content) {
217 if (style == SkPaint::kFill_Style) {
218 content->writeText("f");
219 } else if (style == SkPaint::kStrokeAndFill_Style) {
220 content->writeText("B");
221 } else if (style == SkPaint::kStroke_Style) {
222 content->writeText("S");
223 }
224
225 if (style != SkPaint::kStroke_Style) {
226 NOT_IMPLEMENTED(fill == SkPathFillType::kInverseEvenOdd, false);
227 NOT_IMPLEMENTED(fill == SkPathFillType::kInverseWinding, false);
228 if (fill == SkPathFillType::kEvenOdd) {
229 content->writeText("*");
230 }
231 }
232 content->writeText("\n");
233}
234
235void SkPDFUtils::StrokePath(SkWStream* content) {
236 SkPDFUtils::PaintPath(SkPaint::kStroke_Style, SkPathFillType::kWinding, content);
237}
238
239void SkPDFUtils::ApplyGraphicState(int objectIndex, SkWStream* content) {
240 SkPDFWriteResourceName(content, SkPDFResourceType::kExtGState, objectIndex);
241 content->writeText(" gs\n");
242}
243
244void SkPDFUtils::ApplyPattern(int objectIndex, SkWStream* content) {
245 // Select Pattern color space (CS, cs) and set pattern object as current
246 // color (SCN, scn)
247 content->writeText("/Pattern CS/Pattern cs");
248 SkPDFWriteResourceName(content, SkPDFResourceType::kPattern, objectIndex);
249 content->writeText(" SCN");
250 SkPDFWriteResourceName(content, SkPDFResourceType::kPattern, objectIndex);
251 content->writeText(" scn\n");
252}
253
254// return "x/pow(10, places)", given 0<x<pow(10, places)
255// result points to places+2 chars.
256static size_t print_permil_as_decimal(int x, char* result, unsigned places) {
257 result[0] = '.';
258 for (int i = places; i > 0; --i) {
259 result[i] = '0' + x % 10;
260 x /= 10;
261 }
262 int j;
263 for (j = places; j > 1; --j) {
264 if (result[j] != '0') {
265 break;
266 }
267 }
268 result[j + 1] = '\0';
269 return j + 1;
270}
271
272
273static constexpr int int_pow(int base, unsigned exp, int acc = 1) {
274 return exp < 1 ? acc
275 : int_pow(base * base,
276 exp / 2,
277 (exp % 2) ? acc * base : acc);
278}
279
280
281size_t SkPDFUtils::ColorToDecimalF(float value, char result[kFloatColorDecimalCount + 2]) {
282 static constexpr int kFactor = int_pow(10, kFloatColorDecimalCount);
283 int x = sk_float_round2int(value * kFactor);
284 if (x >= kFactor || x <= 0) { // clamp to 0-1
285 result[0] = x > 0 ? '1' : '0';
286 result[1] = '\0';
287 return 1;
288 }
289 return print_permil_as_decimal(x, result, kFloatColorDecimalCount);
290}
291
292size_t SkPDFUtils::ColorToDecimal(uint8_t value, char result[5]) {
293 if (value == 255 || value == 0) {
294 result[0] = value ? '1' : '0';
295 result[1] = '\0';
296 return 1;
297 }
298 // int x = 0.5 + (1000.0 / 255.0) * value;
299 int x = SkFixedRoundToInt((SK_Fixed1 * 1000 / 255) * value);
300 return print_permil_as_decimal(x, result, 3);
301}
302
303bool SkPDFUtils::InverseTransformBBox(const SkMatrix& matrix, SkRect* bbox) {
304 SkMatrix inverse;
305 if (!matrix.invert(&inverse)) {
306 return false;
307 }
308 inverse.mapRect(bbox);
309 return true;
310}
311
312void SkPDFUtils::PopulateTilingPatternDict(SkPDFDict* pattern,
313 SkRect& bbox,
314 std::unique_ptr<SkPDFDict> resources,
315 const SkMatrix& matrix) {
316 const int kTiling_PatternType = 1;
317 const int kColoredTilingPattern_PaintType = 1;
318 const int kConstantSpacing_TilingType = 1;
319
320 pattern->insertName("Type", "Pattern");
321 pattern->insertInt("PatternType", kTiling_PatternType);
322 pattern->insertInt("PaintType", kColoredTilingPattern_PaintType);
323 pattern->insertInt("TilingType", kConstantSpacing_TilingType);
324 pattern->insertObject("BBox", SkPDFUtils::RectToArray(bbox));
325 pattern->insertScalar("XStep", bbox.width());
326 pattern->insertScalar("YStep", bbox.height());
327 pattern->insertObject("Resources", std::move(resources));
328 if (!matrix.isIdentity()) {
329 pattern->insertObject("Matrix", SkPDFUtils::MatrixToArray(matrix));
330 }
331}
332
333bool SkPDFUtils::ToBitmap(const SkImage* img, SkBitmap* dst) {
334 SkASSERT(img);
335 SkASSERT(dst);
336 SkBitmap bitmap;
337 if(as_IB(img)->getROPixels(&bitmap)) {
338 SkASSERT(bitmap.dimensions() == img->dimensions());
339 SkASSERT(!bitmap.drawsNothing());
340 *dst = std::move(bitmap);
341 return true;
342 }
343 return false;
344}
345
346#ifdef SK_PDF_BASE85_BINARY
347void SkPDFUtils::Base85Encode(std::unique_ptr<SkStreamAsset> stream, SkDynamicMemoryWStream* dst) {
348 SkASSERT(dst);
349 SkASSERT(stream);
350 dst->writeText("\n");
351 int column = 0;
352 while (true) {
353 uint8_t src[4] = {0, 0, 0, 0};
354 size_t count = stream->read(src, 4);
355 SkASSERT(count < 5);
356 if (0 == count) {
357 dst->writeText("~>\n");
358 return;
359 }
360 uint32_t v = ((uint32_t)src[0] << 24) | ((uint32_t)src[1] << 16) |
361 ((uint32_t)src[2] << 8) | src[3];
362 if (v == 0 && count == 4) {
363 dst->writeText("z");
364 column += 1;
365 } else {
366 char buffer[5];
367 for (int n = 4; n > 0; --n) {
368 buffer[n] = (v % 85) + '!';
369 v /= 85;
370 }
371 buffer[0] = v + '!';
372 dst->write(buffer, count + 1);
373 column += count + 1;
374 }
375 if (column > 74) {
376 dst->writeText("\n");
377 column = 0;
378 }
379 }
380}
381#endif // SK_PDF_BASE85_BINARY
382
383void SkPDFUtils::AppendTransform(const SkMatrix& matrix, SkWStream* content) {
384 SkScalar values[6];
385 if (!matrix.asAffine(values)) {
386 SkMatrix::SetAffineIdentity(values);
387 }
388 for (SkScalar v : values) {
389 SkPDFUtils::AppendScalar(v, content);
390 content->writeText(" ");
391 }
392 content->writeText("cm\n");
393}
394