blob: 99136226ec9bf927f6169420dafc0a17aa142f20 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
halcanarye06ca962016-09-09 05:34:55 -07009
halcanaryf59d18a2016-09-16 14:44:57 -070010#include "SkAdvancedTypefaceMetrics.h"
reedf70b5312016-03-04 16:36:20 -080011#include "SkAnnotationKeys.h"
Mike Reed986480a2017-01-13 22:43:16 +000012#include "SkBitmapDevice.h"
martina.kollarovab8d6af12016-06-29 05:12:31 -070013#include "SkBitmapKey.h"
Hal Canary7cbf5e32017-07-12 13:10:23 -040014#include "SkCanvas.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040015#include "SkClipOpPriv.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000016#include "SkColor.h"
halcanary287d22d2015-09-24 10:20:05 -070017#include "SkColorFilter.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000018#include "SkDraw.h"
halcanarye06ca962016-09-09 05:34:55 -070019#include "SkDrawFilter.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkGlyphCache.h"
brianosman04a44d02016-09-21 09:46:57 -070021#include "SkImageFilterCache.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040022#include "SkJpegEncoder.h"
halcanary022c2bd2016-09-02 11:29:46 -070023#include "SkMakeUnique.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040024#include "SkMaskFilter.h"
halcanarydb0dcc72015-03-20 12:31:52 -070025#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070026#include "SkPDFCanon.h"
halcanary989da4a2016-03-21 14:33:17 -070027#include "SkPDFDocument.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000028#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000029#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000030#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000031#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000032#include "SkPDFShader.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000033#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000034#include "SkPDFUtils.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040035#include "SkPath.h"
36#include "SkPathEffect.h"
37#include "SkPathOps.h"
Hal Canaryf50ff392016-09-30 10:25:39 -040038#include "SkPixelRef.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000039#include "SkRRect.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040040#include "SkRasterClip.h"
halcanary4871f222016-08-26 13:17:44 -070041#include "SkScopeExit.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000042#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070043#include "SkSurface.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000044#include "SkTemplates.h"
halcanarye06ca962016-09-09 05:34:55 -070045#include "SkTextBlobRunIterator.h"
46#include "SkTextFormatParams.h"
halcanaryf59d18a2016-09-16 14:44:57 -070047#include "SkUtils.h"
halcanarya6814332015-05-27 08:53:36 -070048#include "SkXfermodeInterpretation.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040049
50#ifndef SK_PDF_MASK_QUALITY
51 // If MASK_QUALITY is in [0,100], will be used for JpegEncoder.
52 // Otherwise, just encode masks losslessly.
53 #define SK_PDF_MASK_QUALITY 50
54 // Since these masks are used for blurry shadows, we shouldn't need
55 // high quality. Raise this value if your shadows have visible JPEG
56 // artifacts.
57 // If SkJpegEncoder::Encode fails, we will fall back to the lossless
58 // encoding.
59#endif
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000060
61// Utility functions
62
Hal Canary51329c92017-06-27 14:28:37 -040063// This function destroys the mask and either frees or takes the pixels.
64sk_sp<SkImage> mask_to_greyscale_image(SkMask* mask) {
65 sk_sp<SkImage> img;
66 SkPixmap pm(SkImageInfo::Make(mask->fBounds.width(), mask->fBounds.height(),
67 kGray_8_SkColorType, kOpaque_SkAlphaType),
68 mask->fImage, mask->fRowBytes);
69 const int imgQuality = SK_PDF_MASK_QUALITY;
70 if (imgQuality <= 100 && imgQuality >= 0) {
71 SkDynamicMemoryWStream buffer;
72 SkJpegEncoder::Options jpegOptions;
73 jpegOptions.fQuality = imgQuality;
74 if (SkJpegEncoder::Encode(&buffer, pm, jpegOptions)) {
75 img = SkImage::MakeFromEncoded(buffer.detachAsData());
76 SkASSERT(img);
77 if (img) {
78 SkMask::FreeImage(mask->fImage);
79 }
80 }
81 }
82 if (!img) {
83 img = SkImage::MakeFromRaster(pm, [](const void* p, void*) { SkMask::FreeImage((void*)p); },
84 nullptr);
85 }
86 *mask = SkMask(); // destructive;
87 return img;
88}
89
Hal Canaryd425a1d2017-07-12 13:13:51 -040090sk_sp<SkImage> alpha_image_to_greyscale_image(const SkImage* mask) {
91 int w = mask->width(), h = mask->height();
92 SkBitmap greyBitmap;
93 greyBitmap.allocPixels(SkImageInfo::Make(w, h, kGray_8_SkColorType, kOpaque_SkAlphaType));
94 if (!mask->readPixels(SkImageInfo::MakeA8(w, h),
95 greyBitmap.getPixels(), greyBitmap.rowBytes(), 0, 0)) {
96 return nullptr;
97 }
98 return SkImage::MakeFromBitmap(greyBitmap);
99}
100
Mike Reeda1361362017-03-07 09:37:29 -0500101static void draw_points(SkCanvas::PointMode mode,
102 size_t count,
103 const SkPoint* points,
104 const SkPaint& paint,
105 const SkIRect& bounds,
106 const SkMatrix& ctm,
107 SkBaseDevice* device) {
108 SkRasterClip rc(bounds);
109 SkDraw draw;
110 draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(bounds.right(), bounds.bottom()), nullptr, 0);
111 draw.fMatrix = &ctm;
112 draw.fRC = &rc;
113 draw.drawPoints(mode, count, points, paint, device);
114}
115
116static SkIRect size(const SkBaseDevice& dev) { return {0, 0, dev.width(), dev.height()}; }
117
reed374772b2016-10-05 17:33:02 -0700118// If the paint will definitely draw opaquely, replace kSrc with
119// kSrcOver. http://crbug.com/473572
halcanarya6814332015-05-27 08:53:36 -0700120static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
reed374772b2016-10-05 17:33:02 -0700121 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
122 paint->setBlendMode(SkBlendMode::kSrcOver);
halcanarya6814332015-05-27 08:53:36 -0700123 }
124}
125
Hal Canaryd12a6762017-05-26 17:01:16 -0400126// A shader's matrix is: CTMM x LocalMatrix x WrappingLocalMatrix. We want to
127// switch to device space, where CTM = I, while keeping the original behavior.
128//
129// I * LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
130// LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
131// InvLocalMatrix * LocalMatrix * NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
132// NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
133//
134static void transform_shader(SkPaint* paint, const SkMatrix& ctm) {
135 SkMatrix lm = SkPDFUtils::GetShaderLocalMatrix(paint->getShader());
136 SkMatrix lmInv;
137 if (lm.invert(&lmInv)) {
138 SkMatrix m = SkMatrix::Concat(SkMatrix::Concat(lmInv, ctm), lm);
139 paint->setShader(paint->getShader()->makeWithLocalMatrix(m));
140 }
141}
142
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000143static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000144 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -0700145 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000146 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700147 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000148 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700149 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000150 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000151}
152
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000153static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000154 SkPaint result = paint;
155 if (result.isFakeBoldText()) {
156 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
157 kStdFakeBoldInterpKeys,
158 kStdFakeBoldInterpValues,
159 kStdFakeBoldInterpLength);
Mike Reed8be952a2017-02-13 20:44:33 -0500160 SkScalar width = result.getTextSize() * fakeBoldScale;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000161 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000162 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000163 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000164 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000165 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000166 result.setStrokeWidth(width);
167 }
168 return result;
169}
170
Hal Canaryf50ff392016-09-30 10:25:39 -0400171
Hal Canaryd12a6762017-05-26 17:01:16 -0400172// If the paint has a color filter, apply the color filter to the shader or the
173// paint color. Remove the color filter.
174void remove_color_filter(SkPaint* paint) {
175 if (SkColorFilter* cf = paint->getColorFilter()) {
176 if (SkShader* shader = paint->getShader()) {
177 paint->setShader(shader->makeWithColorFilter(paint->refColorFilter()));
178 } else {
179 paint->setColor(cf->filterColor(paint->getColor()));
180 }
181 paint->setColorFilter(nullptr);
182 }
183}
184
halcanary2be7e012016-03-28 11:58:08 -0700185SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
186 : fColor(SK_ColorBLACK)
187 , fTextScaleX(SK_Scalar1)
188 , fTextFill(SkPaint::kFill_Style)
189 , fShaderIndex(-1)
halcanaryc2f9ec12016-09-12 08:55:29 -0700190 , fGraphicStateIndex(-1) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000191 fMatrix.reset();
192}
193
halcanary2be7e012016-03-28 11:58:08 -0700194bool SkPDFDevice::GraphicStateEntry::compareInitialState(
195 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000196 return fColor == cur.fColor &&
197 fShaderIndex == cur.fShaderIndex &&
198 fGraphicStateIndex == cur.fGraphicStateIndex &&
199 fMatrix == cur.fMatrix &&
200 fClipStack == cur.fClipStack &&
201 (fTextScaleX == 0 ||
202 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000203}
204
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000205class GraphicStackState {
206public:
207 GraphicStackState(const SkClipStack& existingClipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000208 SkWStream* contentStream)
209 : fStackDepth(0),
210 fContentStream(contentStream) {
211 fEntries[0].fClipStack = existingClipStack;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000212 }
213
Hal Canary6d673962017-02-22 17:16:59 -0500214 void updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500215 const SkPoint& translation, const SkRect& bounds);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000216 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700217 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000218
219 void drainStack();
220
221private:
222 void push();
223 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700224 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000225
226 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
227 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700228 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000229 int fStackDepth;
230 SkWStream* fContentStream;
231};
232
233void GraphicStackState::drainStack() {
234 while (fStackDepth) {
235 pop();
236 }
237}
238
239void GraphicStackState::push() {
240 SkASSERT(fStackDepth < kMaxStackDepth);
241 fContentStream->writeText("q\n");
242 fStackDepth++;
243 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
244}
245
246void GraphicStackState::pop() {
247 SkASSERT(fStackDepth > 0);
248 fContentStream->writeText("Q\n");
249 fStackDepth--;
250}
251
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000252/* Calculate an inverted path's equivalent non-inverted path, given the
253 * canvas bounds.
254 * outPath may alias with invPath (since this is supported by PathOps).
255 */
256static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
257 SkPath* outPath) {
258 SkASSERT(invPath.isInverseFillType());
259
260 SkPath clipPath;
261 clipPath.addRect(bounds);
262
reedcdb42bb2015-06-26 10:23:07 -0700263 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000264}
265
Hal Canary44a97d52017-02-22 10:45:25 -0500266bool apply_clip(SkClipOp op, const SkPath& u, const SkPath& v, SkPath* r) {
267 switch (op) {
268 case SkClipOp::kDifference:
269 return Op(u, v, kDifference_SkPathOp, r);
270 case SkClipOp::kIntersect:
271 return Op(u, v, kIntersect_SkPathOp, r);
Mike Reed14113bc2017-05-10 14:13:20 -0400272#ifdef SK_SUPPORT_DEPRECATED_CLIPOPS
Hal Canary44a97d52017-02-22 10:45:25 -0500273 case SkClipOp::kUnion_deprecated:
274 return Op(u, v, kUnion_SkPathOp, r);
275 case SkClipOp::kXOR_deprecated:
276 return Op(u, v, kXOR_SkPathOp, r);
277 case SkClipOp::kReverseDifference_deprecated:
278 return Op(u, v, kReverseDifference_SkPathOp, r);
279 case SkClipOp::kReplace_deprecated:
280 *r = v;
281 return true;
Mike Reed14113bc2017-05-10 14:13:20 -0400282#endif
Hal Canary44a97d52017-02-22 10:45:25 -0500283 default:
284 return false;
285 }
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000286}
287
288/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
289 * Returns true if successful, or false if not successful.
290 * If successful, the resulting clip is stored in outClipPath.
291 * If not successful, outClipPath is undefined, and a fallback method
292 * should be used.
293 */
294static bool get_clip_stack_path(const SkMatrix& transform,
295 const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500296 const SkRect& bounds,
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000297 SkPath* outClipPath) {
298 outClipPath->reset();
299 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
300
301 const SkClipStack::Element* clipEntry;
302 SkClipStack::Iter iter;
303 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
304 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
305 SkPath entryPath;
306 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
307 outClipPath->reset();
308 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
309 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000310 } else {
311 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000312 }
313 entryPath.transform(transform);
Hal Canary44a97d52017-02-22 10:45:25 -0500314 if (!apply_clip(clipEntry->getOp(), *outClipPath, entryPath, outClipPath)) {
315 return false;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000316 }
317 }
318
319 if (outClipPath->isInverseFillType()) {
320 // The bounds are slightly outset to ensure this is correct in the
321 // face of floating-point accuracy and possible SkRegion bitmap
322 // approximations.
Hal Canary44a97d52017-02-22 10:45:25 -0500323 SkRect clipBounds = bounds;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000324 clipBounds.outset(SK_Scalar1, SK_Scalar1);
325 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
326 return false;
327 }
328 }
329 return true;
330}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000331
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000332// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000333// graphic state stack, and the fact that we can know all the clips used
334// on the page to optimize this.
335void GraphicStackState::updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500336 const SkPoint& translation,
337 const SkRect& bounds) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000338 if (clipStack == currentEntry()->fClipStack) {
339 return;
340 }
341
342 while (fStackDepth > 0) {
343 pop();
344 if (clipStack == currentEntry()->fClipStack) {
345 return;
346 }
347 }
348 push();
349
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000350 currentEntry()->fClipStack = clipStack;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000351
352 SkMatrix transform;
353 transform.setTranslate(translation.fX, translation.fY);
354
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000355 SkPath clipPath;
Hal Canary44a97d52017-02-22 10:45:25 -0500356 if (get_clip_stack_path(transform, clipStack, bounds, &clipPath)) {
halcanary5edf2902016-09-07 09:05:25 -0700357 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
358 SkPath::FillType clipFill = clipPath.getFillType();
359 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
360 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
361 if (clipFill == SkPath::kEvenOdd_FillType) {
362 fContentStream->writeText("W* n\n");
363 } else {
364 fContentStream->writeText("W n\n");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000365 }
366 }
halcanary5edf2902016-09-07 09:05:25 -0700367 // If Op() fails (pathological case; e.g. input values are
368 // extremely large or NaN), emit no clip at all.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000369}
370
371void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
372 if (matrix == currentEntry()->fMatrix) {
373 return;
374 }
375
376 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
377 SkASSERT(fStackDepth > 0);
378 SkASSERT(fEntries[fStackDepth].fClipStack ==
379 fEntries[fStackDepth -1].fClipStack);
380 pop();
381
382 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
383 }
384 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
385 return;
386 }
387
388 push();
389 SkPDFUtils::AppendTransform(matrix, fContentStream);
390 currentEntry()->fMatrix = matrix;
391}
392
halcanary2be7e012016-03-28 11:58:08 -0700393void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000394 // PDF treats a shader as a color, so we only set one or the other.
395 if (state.fShaderIndex >= 0) {
396 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000397 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000398 currentEntry()->fShaderIndex = state.fShaderIndex;
399 }
400 } else {
401 if (state.fColor != currentEntry()->fColor ||
402 currentEntry()->fShaderIndex >= 0) {
403 emit_pdf_color(state.fColor, fContentStream);
404 fContentStream->writeText("RG ");
405 emit_pdf_color(state.fColor, fContentStream);
406 fContentStream->writeText("rg\n");
407 currentEntry()->fColor = state.fColor;
408 currentEntry()->fShaderIndex = -1;
409 }
410 }
411
412 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000413 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000414 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
415 }
416
417 if (state.fTextScaleX) {
418 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
Mike Reed8be952a2017-02-13 20:44:33 -0500419 SkScalar pdfScale = state.fTextScaleX * 1000;
halcanarybc4696b2015-05-06 10:56:04 -0700420 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000421 fContentStream->writeText(" Tz\n");
422 currentEntry()->fTextScaleX = state.fTextScaleX;
423 }
424 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700425 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
426 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
427 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000428 fContentStream->writeDecAsText(state.fTextFill);
429 fContentStream->writeText(" Tr\n");
430 currentEntry()->fTextFill = state.fTextFill;
431 }
432 }
433}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000434
reed76033be2015-03-14 10:54:31 -0700435static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700436 // PDF does not support image filters, so render them on CPU.
437 // Note that this rendering is done at "screen" resolution (100dpi), not
438 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700439 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800440 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700441
442 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700443 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700444}
445
446SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700447 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700448 // need to return a raster device, which we will detect in drawDevice()
449 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700450 }
fmalita6987dca2014-11-13 08:33:37 -0800451 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
Hal Canarya0622582017-06-29 18:51:35 -0400452 return new SkPDFDevice(size, fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000453}
454
halcanary989da4a2016-03-21 14:33:17 -0700455SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
456
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000457// A helper class to automatically finish a ContentEntry at the end of a
458// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000459class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000460public:
Mike Reeda1361362017-03-07 09:37:29 -0500461 ScopedContentEntry(SkPDFDevice* device,
462 const SkClipStack& clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000463 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500464 const SkPaint& paint,
465 bool hasText = false)
466 : fDevice(device)
467 , fContentEntry(nullptr)
468 , fBlendMode(SkBlendMode::kSrcOver)
469 , fDstFormXObject(nullptr)
470 {
471 if (matrix.hasPerspective()) {
472 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
473 return;
474 }
475 fBlendMode = paint.getBlendMode();
476 fContentEntry =
477 fDevice->setUpContentEntry(clipStack, matrix, paint, hasText, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000478 }
Mike Reeda1361362017-03-07 09:37:29 -0500479 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, bool hasText = false)
480 : ScopedContentEntry(dev, dev->cs(), dev->ctm(), paint, hasText) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000481
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000482 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000483 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000484 SkPath* shape = &fShape;
485 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700486 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000487 }
reed374772b2016-10-05 17:33:02 -0700488 fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000489 }
490 }
491
halcanary2be7e012016-03-28 11:58:08 -0700492 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
Hal Canary51329c92017-06-27 14:28:37 -0400493 SkDynamicMemoryWStream* stream() { return &fContentEntry->fContent; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000494
495 /* Returns true when we explicitly need the shape of the drawing. */
496 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700497 switch (fBlendMode) {
498 case SkBlendMode::kClear:
499 case SkBlendMode::kSrc:
500 case SkBlendMode::kSrcIn:
501 case SkBlendMode::kSrcOut:
502 case SkBlendMode::kDstIn:
503 case SkBlendMode::kDstOut:
504 case SkBlendMode::kSrcATop:
505 case SkBlendMode::kDstATop:
506 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000507 return true;
508 default:
509 return false;
510 }
511 }
512
513 /* Returns true unless we only need the shape of the drawing. */
514 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700515 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000516 return false;
517 }
518 return true;
519 }
520
521 /* If the shape is different than the alpha component of the content, then
522 * setShape should be called with the shape. In particular, images and
523 * devices have rectangular shape.
524 */
525 void setShape(const SkPath& shape) {
526 fShape = shape;
527 }
528
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000529private:
530 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700531 SkPDFDevice::ContentEntry* fContentEntry;
reed374772b2016-10-05 17:33:02 -0700532 SkBlendMode fBlendMode;
halcanarydabd4f02016-08-03 11:16:56 -0700533 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000534 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000535};
536
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000537////////////////////////////////////////////////////////////////////////////////
538
Hal Canarya0622582017-06-29 18:51:35 -0400539SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc)
reed589a39e2016-08-20 07:59:19 -0700540 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
541 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700542 , fPageSize(pageSize)
Hal Canarya0622582017-06-29 18:51:35 -0400543 , fInitialTransform(SkMatrix::I())
544 , fDocument(doc)
545{
halcanarya1f1ee92015-02-20 06:17:26 -0800546 SkASSERT(pageSize.width() > 0);
547 SkASSERT(pageSize.height() > 0);
Hal Canarya0622582017-06-29 18:51:35 -0400548}
robertphillips1f3923e2016-07-21 07:17:54 -0700549
Hal Canarya0622582017-06-29 18:51:35 -0400550void SkPDFDevice::setFlip() {
551 // Skia generally uses the top left as the origin but PDF
552 // natively has the origin at the bottom left. This matrix
553 // corrects for that. But that only needs to be done once, we
554 // don't do it when layering.
555 fInitialTransform.setTranslate(0, SkIntToScalar(fPageSize.fHeight));
556 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000557}
558
559SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700560 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000561}
562
563void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700564 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000565}
566
halcanary3c35fb32016-06-30 11:55:07 -0700567void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000568 fGraphicStateResources.unrefAll();
569 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000570 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000571 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000572}
573
Mike Reeda1361362017-03-07 09:37:29 -0500574void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500575 if (!value) {
576 return;
577 }
578 if (rect.isEmpty()) {
Mike Reeda1361362017-03-07 09:37:29 -0500579 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
580 SkPoint transformedPoint;
581 this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
Hal Canary5c1b3602017-04-17 16:30:06 -0400582 fNamedDestinations.emplace_back(NamedDestination{sk_ref_sp(value), transformedPoint});
Mike Reeda1361362017-03-07 09:37:29 -0500583 }
584 return;
585 }
586 // Convert to path to handle non-90-degree rotations.
587 SkPath path;
588 path.addRect(rect);
589 path.transform(this->ctm(), &path);
590 SkPath clip;
591 (void)this->cs().asPath(&clip);
592 Op(clip, path, kIntersect_SkPathOp, &path);
593 // PDF wants a rectangle only.
594 SkRect transformedRect = path.getBounds();
595 if (transformedRect.isEmpty()) {
596 return;
597 }
598 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400599 fLinkToURLs.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
Mike Reeda1361362017-03-07 09:37:29 -0500600 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400601 fLinkToDestinations.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
reedf70b5312016-03-04 16:36:20 -0800602 }
603}
604
Hal Canaryd12a6762017-05-26 17:01:16 -0400605void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
606 SkPaint newPaint = srcPaint;
607 remove_color_filter(&newPaint);
halcanarya6814332015-05-27 08:53:36 -0700608 replace_srcmode_on_opaque_paint(&newPaint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000609 newPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryd12a6762017-05-26 17:01:16 -0400610
611 SkMatrix ctm = this->ctm();
612 if (ctm.getType() & SkMatrix::kPerspective_Mask) {
613 if (newPaint.getShader()) {
614 transform_shader(&newPaint, ctm);
615 }
616 ctm = SkMatrix::I();
617 }
618 ScopedContentEntry content(this, this->cs(), ctm, newPaint);
Mike Reeda1361362017-03-07 09:37:29 -0500619 this->internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000620}
621
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000622void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700623 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000624 if (!contentEntry) {
625 return;
626 }
Hal Canaryd425a1d2017-07-12 13:13:51 -0400627 SkRect bbox = SkRect::Make(fPageSize);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000628 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000629 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000630 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000631 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000632 inverse.mapRect(&bbox);
633
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000634 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000635 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000636 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000637}
638
Mike Reeda1361362017-03-07 09:37:29 -0500639void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700640 size_t count,
641 const SkPoint* points,
642 const SkPaint& srcPaint) {
643 SkPaint passedPaint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400644 remove_color_filter(&passedPaint);
halcanarya6814332015-05-27 08:53:36 -0700645 replace_srcmode_on_opaque_paint(&passedPaint);
Hal Canary80fa7ce2017-06-28 16:04:20 -0400646 if (SkCanvas::kPoints_PointMode != mode) {
647 passedPaint.setStyle(SkPaint::kStroke_Style);
648 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000649 if (count == 0) {
650 return;
651 }
652
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000653 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
654 // We only use this when there's a path effect because of the overhead
655 // of multiple calls to setUpContentEntry it causes.
656 if (passedPaint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500657 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000658 return;
659 }
Mike Reeda1361362017-03-07 09:37:29 -0500660 draw_points(mode, count, points, passedPaint,
661 this->devClipBounds(), this->ctm(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000662 return;
663 }
664
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000665 const SkPaint* paint = &passedPaint;
666 SkPaint modifiedPaint;
667
668 if (mode == SkCanvas::kPoints_PointMode &&
669 paint->getStrokeCap() != SkPaint::kRound_Cap) {
670 modifiedPaint = *paint;
671 paint = &modifiedPaint;
672 if (paint->getStrokeWidth()) {
673 // PDF won't draw a single point with square/butt caps because the
674 // orientation is ambiguous. Draw a rectangle instead.
675 modifiedPaint.setStyle(SkPaint::kFill_Style);
676 SkScalar strokeWidth = paint->getStrokeWidth();
677 SkScalar halfStroke = SkScalarHalf(strokeWidth);
678 for (size_t i = 0; i < count; i++) {
679 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
680 r.inset(-halfStroke, -halfStroke);
Mike Reeda1361362017-03-07 09:37:29 -0500681 this->drawRect(r, modifiedPaint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000682 }
683 return;
684 } else {
685 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
686 }
687 }
688
Mike Reeda1361362017-03-07 09:37:29 -0500689 ScopedContentEntry content(this, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000690 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000691 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000692 }
Hal Canary51329c92017-06-27 14:28:37 -0400693 SkDynamicMemoryWStream* contentStream = content.stream();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000694 switch (mode) {
695 case SkCanvas::kPolygon_PointMode:
Hal Canary51329c92017-06-27 14:28:37 -0400696 SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000697 for (size_t i = 1; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400698 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000699 }
Hal Canary51329c92017-06-27 14:28:37 -0400700 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000701 break;
702 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000703 for (size_t i = 0; i < count/2; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400704 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
705 SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
706 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000707 }
708 break;
709 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000710 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
711 for (size_t i = 0; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400712 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
713 SkPDFUtils::ClosePath(contentStream);
714 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000715 }
716 break;
717 default:
718 SkASSERT(false);
719 }
720}
721
halcanary8103a342016-03-08 15:10:16 -0800722static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800723 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700724 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700725 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700726
halcanaryece83922016-03-08 08:32:12 -0800727 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700728 border->reserve(3);
729 border->appendInt(0); // Horizontal corner radius.
730 border->appendInt(0); // Vertical corner radius.
731 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800732 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700733
halcanaryece83922016-03-08 08:32:12 -0800734 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700735 rect->reserve(4);
736 rect->appendScalar(translatedRect.fLeft);
737 rect->appendScalar(translatedRect.fTop);
738 rect->appendScalar(translatedRect.fRight);
739 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800740 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700741
halcanary8103a342016-03-08 15:10:16 -0800742 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700743}
744
halcanary8103a342016-03-08 15:10:16 -0800745static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700746 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700747 SkString url(static_cast<const char *>(urlData->data()),
748 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800749 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700750 action->insertName("S", "URI");
751 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800752 annotation->insertObject("A", std::move(action));
753 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700754}
755
halcanary8103a342016-03-08 15:10:16 -0800756static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
757 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700758 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700759 SkString name(static_cast<const char *>(nameData->data()),
760 nameData->size() - 1);
761 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800762 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700763}
764
Mike Reeda1361362017-03-07 09:37:29 -0500765void SkPDFDevice::drawRect(const SkRect& rect,
halcanarya6814332015-05-27 08:53:36 -0700766 const SkPaint& srcPaint) {
767 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400768 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700769 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000770 SkRect r = rect;
771 r.sort();
772
Hal Canaryd12a6762017-05-26 17:01:16 -0400773 if (paint.getPathEffect() || paint.getMaskFilter()) {
Mike Reeda1361362017-03-07 09:37:29 -0500774 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000775 return;
776 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000777 SkPath path;
778 path.addRect(r);
Mike Reeda1361362017-03-07 09:37:29 -0500779 this->drawPath(path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000780 return;
781 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000782
Mike Reeda1361362017-03-07 09:37:29 -0500783 ScopedContentEntry content(this, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000784 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000785 return;
786 }
Hal Canary51329c92017-06-27 14:28:37 -0400787 SkPDFUtils::AppendRectangle(r, content.stream());
788 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000789}
790
Mike Reeda1361362017-03-07 09:37:29 -0500791void SkPDFDevice::drawRRect(const SkRRect& rrect,
halcanarya6814332015-05-27 08:53:36 -0700792 const SkPaint& srcPaint) {
793 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400794 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700795 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000796 SkPath path;
797 path.addRRect(rrect);
Mike Reeda1361362017-03-07 09:37:29 -0500798 this->drawPath(path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000799}
800
Mike Reeda1361362017-03-07 09:37:29 -0500801void SkPDFDevice::drawOval(const SkRect& oval,
halcanarya6814332015-05-27 08:53:36 -0700802 const SkPaint& srcPaint) {
803 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400804 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700805 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700806 SkPath path;
807 path.addOval(oval);
Mike Reeda1361362017-03-07 09:37:29 -0500808 this->drawPath(path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700809}
810
Mike Reeda1361362017-03-07 09:37:29 -0500811void SkPDFDevice::drawPath(const SkPath& origPath,
halcanarya6814332015-05-27 08:53:36 -0700812 const SkPaint& srcPaint,
813 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000814 bool pathIsMutable) {
Mike Reeda1361362017-03-07 09:37:29 -0500815 this->internalDrawPath(
816 this->cs(), this->ctm(), origPath, srcPaint, prePathMatrix, pathIsMutable);
817}
818
Hal Canaryd12a6762017-05-26 17:01:16 -0400819void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
820 const SkMatrix& ctm,
821 const SkPath& origPath,
822 const SkPaint& origPaint,
823 const SkMatrix* prePathMatrix) {
824 SkASSERT(origPaint.getMaskFilter());
825 SkPath path(origPath);
826 SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
827 if (prePathMatrix) {
828 path.transform(*prePathMatrix, &path);
829 }
830 SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
831 ? SkStrokeRec::kFill_InitStyle
832 : SkStrokeRec::kHairline_InitStyle;
833 path.transform(ctm, &path);
834
Hal Canarya0622582017-06-29 18:51:35 -0400835 // TODO(halcanary): respect fDocument->rasterDpi().
836 // SkScalar rasterScale = (float)rasterDpi / SkPDFUtils::kDpiForRasterScaleOne;
Hal Canaryd12a6762017-05-26 17:01:16 -0400837 // Would it be easier to just change the device size (and pre-scale the canvas)?
838 SkIRect bounds = clipStack.bounds(size(*this)).roundOut();
839 SkMask sourceMask;
840 if (!SkDraw::DrawToMask(path, &bounds, paint->getMaskFilter(), &SkMatrix::I(),
841 &sourceMask, SkMask::kComputeBoundsAndRenderImage_CreateMode,
842 initStyle)) {
843 return;
844 }
845 SkAutoMaskFreeImage srcAutoMaskFreeImage(sourceMask.fImage);
846 SkMask dstMask;
847 SkIPoint margin;
848 if (!paint->getMaskFilter()->filterMask(&dstMask, sourceMask, ctm, &margin)) {
849 return;
850 }
Hal Canary51329c92017-06-27 14:28:37 -0400851 SkIRect dstMaskBounds = dstMask.fBounds;
852 sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
Hal Canaryd12a6762017-05-26 17:01:16 -0400853 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
854 // Must mask with a Form XObject.
Hal Canary51329c92017-06-27 14:28:37 -0400855 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
Hal Canaryd12a6762017-05-26 17:01:16 -0400856 {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400857 SkCanvas canvas(maskDevice.get());
Hal Canary51329c92017-06-27 14:28:37 -0400858 canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
Hal Canaryd12a6762017-05-26 17:01:16 -0400859 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400860 if (!ctm.isIdentity() && paint->getShader()) {
861 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
862 }
863 ScopedContentEntry content(this, clipStack, SkMatrix::I(), *paint);
864 if (!content.entry()) {
865 return;
866 }
Hal Canary51329c92017-06-27 14:28:37 -0400867 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
868 SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
869 SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
870 this->clearMaskOnGraphicState(content.stream());
871}
Hal Canaryd12a6762017-05-26 17:01:16 -0400872
Hal Canary51329c92017-06-27 14:28:37 -0400873void SkPDFDevice::addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,
874 SkDynamicMemoryWStream* contentStream) {
875 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
876 maskDevice->makeFormXObjectFromDevice(), false,
877 SkPDFGraphicState::kLuminosity_SMaskMode, this->getCanon());
878 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(sMaskGS.get()), contentStream);
879}
Hal Canaryd12a6762017-05-26 17:01:16 -0400880
Hal Canary51329c92017-06-27 14:28:37 -0400881void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400882 // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
Hal Canaryc02de0b2017-06-28 13:14:03 -0400883 sk_sp<SkPDFDict>& noSMaskGS = this->getCanon()->fNoSmaskGraphicState;
884 if (!noSMaskGS) {
885 noSMaskGS = sk_make_sp<SkPDFDict>("ExtGState");
886 noSMaskGS->insertName("SMask", "None");
887 }
Hal Canary51329c92017-06-27 14:28:37 -0400888 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(noSMaskGS.get()), contentStream);
Hal Canaryd12a6762017-05-26 17:01:16 -0400889}
890
Mike Reeda1361362017-03-07 09:37:29 -0500891void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
892 const SkMatrix& ctm,
893 const SkPath& origPath,
894 const SkPaint& srcPaint,
895 const SkMatrix* prePathMatrix,
896 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700897 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400898 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700899 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800900 SkPath modifiedPath;
901 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000902
Hal Canaryd12a6762017-05-26 17:01:16 -0400903 if (paint.getMaskFilter()) {
904 this->internalDrawPathWithFilter(clipStack, ctm, origPath, paint, prePathMatrix);
905 return;
906 }
907
Mike Reeda1361362017-03-07 09:37:29 -0500908 SkMatrix matrix = ctm;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000909 if (prePathMatrix) {
910 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800911 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000912 pathPtr = &modifiedPath;
913 pathIsMutable = true;
914 }
halcanary682ee012016-01-28 10:59:34 -0800915 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000916 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000917 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000918 }
919 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000920
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000921 if (paint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500922 if (clipStack.isEmpty(size(*this))) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000923 return;
924 }
halcanary682ee012016-01-28 10:59:34 -0800925 if (!pathIsMutable) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400926 modifiedPath = origPath;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000927 pathPtr = &modifiedPath;
928 pathIsMutable = true;
929 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400930 if (paint.getFillPath(*pathPtr, pathPtr)) {
931 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000932 } else {
Hal Canaryd12a6762017-05-26 17:01:16 -0400933 paint.setStyle(SkPaint::kStroke_Style);
934 paint.setStrokeWidth(0);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000935 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400936 paint.setPathEffect(nullptr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000937 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000938
Hal Canaryd12a6762017-05-26 17:01:16 -0400939 if (this->handleInversePath(*pathPtr, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000940 return;
941 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400942 if (matrix.getType() & SkMatrix::kPerspective_Mask) {
943 if (!pathIsMutable) {
944 modifiedPath = origPath;
945 pathPtr = &modifiedPath;
946 pathIsMutable = true;
947 }
948 pathPtr->transform(matrix);
949 if (paint.getShader()) {
950 transform_shader(&paint, matrix);
951 }
952 matrix = SkMatrix::I();
953 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000954
Mike Reeda1361362017-03-07 09:37:29 -0500955 ScopedContentEntry content(this, clipStack, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000956 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000957 return;
958 }
Hal Canary385468f2017-02-13 11:03:23 -0500959 SkScalar matrixScale = matrix.mapRadius(1.0f);
960 SkScalar tolerance = matrixScale > 0.0f ? 0.25f / matrixScale : 0.25f;
halcanary8b2bc252015-10-06 09:41:47 -0700961 bool consumeDegeratePathSegments =
962 paint.getStyle() == SkPaint::kFill_Style ||
963 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
964 paint.getStrokeCap() != SkPaint::kSquare_Cap);
Hal Canary51329c92017-06-27 14:28:37 -0400965 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(), consumeDegeratePathSegments, content.stream(),
Hal Canary385468f2017-02-13 11:03:23 -0500966 tolerance);
Hal Canary51329c92017-06-27 14:28:37 -0400967 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000968}
969
Hal Canary7cbf5e32017-07-12 13:10:23 -0400970////////////////////////////////////////////////////////////////////////////////
Hal Canaryf50ff392016-09-30 10:25:39 -0400971
Mike Reeda1361362017-03-07 09:37:29 -0500972void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400973 const SkRect* src,
974 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400975 const SkPaint& paint,
Hal Canaryf50ff392016-09-30 10:25:39 -0400976 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400977 SkASSERT(image);
978 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
979 src, dst, paint, this->ctm());
Hal Canaryf50ff392016-09-30 10:25:39 -0400980}
981
Hal Canary7cbf5e32017-07-12 13:10:23 -0400982void SkPDFDevice::drawBitmapRect(const SkBitmap& bm,
halcanary7a14b312015-10-01 07:28:13 -0700983 const SkRect* src,
984 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400985 const SkPaint& paint,
Mike Reeda1361362017-03-07 09:37:29 -0500986 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400987 SkASSERT(!bm.drawsNothing());
988 this->internalDrawImageRect(SkKeyedImage(bm), src, dst, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700989}
990
Hal Canary7cbf5e32017-07-12 13:10:23 -0400991void SkPDFDevice::drawBitmap(const SkBitmap& bm, SkScalar x, SkScalar y, const SkPaint& paint) {
992 SkASSERT(!bm.drawsNothing());
993 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
994 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700995}
996
Hal Canary7cbf5e32017-07-12 13:10:23 -0400997void SkPDFDevice::drawSprite(const SkBitmap& bm, int x, int y, const SkPaint& paint) {
998 SkASSERT(!bm.drawsNothing());
999 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
1000 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, SkMatrix::I());
halcanary7a14b312015-10-01 07:28:13 -07001001}
1002
Hal Canary7cbf5e32017-07-12 13:10:23 -04001003void SkPDFDevice::drawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint& paint) {
1004 SkASSERT(image);
1005 auto r = SkRect::MakeXYWH(x, y, image->width(), image->height());
1006 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
1007 nullptr, r, paint, this->ctm());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001008}
1009
Hal Canary7cbf5e32017-07-12 13:10:23 -04001010////////////////////////////////////////////////////////////////////////////////
1011
halcanaryf0c30f52016-07-15 13:35:45 -07001012namespace {
1013class GlyphPositioner {
1014public:
1015 GlyphPositioner(SkDynamicMemoryWStream* content,
1016 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -07001017 bool wideChars,
1018 bool defaultPositioning,
1019 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -07001020 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -07001021 , fCurrentMatrixOrigin(origin)
1022 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -07001023 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -07001024 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -07001025 }
halcanary4871f222016-08-26 13:17:44 -07001026 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -07001027 void flush() {
1028 if (fInText) {
1029 fContent->writeText("> Tj\n");
1030 fInText = false;
1031 }
1032 }
halcanary4871f222016-08-26 13:17:44 -07001033 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -07001034 SkScalar advanceWidth,
1035 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -07001036 if (!fInitialized) {
1037 // Flip the text about the x-axis to account for origin swap and include
1038 // the passed parameters.
1039 fContent->writeText("1 0 ");
1040 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
1041 fContent->writeText(" -1 ");
1042 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
1043 fContent->writeText(" ");
1044 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
1045 fContent->writeText(" Tm\n");
1046 fCurrentMatrixOrigin.set(0.0f, 0.0f);
1047 fInitialized = true;
1048 }
halcanary4ed2f012016-08-15 18:40:07 -07001049 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -07001050 SkPoint position = xy - fCurrentMatrixOrigin;
Hal Canary197ca9b2017-05-15 10:29:44 -04001051 if (position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -07001052 this->flush();
halcanary4871f222016-08-26 13:17:44 -07001053 SkPDFUtils::AppendScalar(position.x(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001054 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -07001055 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001056 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -07001057 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -07001058 fXAdvance = 0;
1059 }
1060 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -07001061 }
1062 if (!fInText) {
1063 fContent->writeText("<");
1064 fInText = true;
1065 }
1066 if (fWideChars) {
1067 SkPDFUtils::WriteUInt16BE(fContent, glyph);
1068 } else {
1069 SkASSERT(0 == glyph >> 8);
1070 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1071 }
halcanaryf0c30f52016-07-15 13:35:45 -07001072 }
1073
1074private:
1075 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -07001076 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001077 SkScalar fXAdvance = 0.0f;
1078 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001079 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001080 bool fInText = false;
1081 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -07001082 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001083};
halcanaryf59d18a2016-09-16 14:44:57 -07001084
1085/** Given the m-to-n glyph-to-character mapping data (as returned by
1086 harfbuzz), iterate over the clusters. */
1087class Clusterator {
1088public:
1089 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1090 explicit Clusterator(uint32_t glyphCount)
1091 : fClusters(nullptr)
1092 , fUtf8Text(nullptr)
1093 , fGlyphCount(glyphCount)
1094 , fTextByteLength(0) {}
1095 // The clusters[] array is an array of offsets into utf8Text[],
1096 // one offset for each glyph. See SkTextBlobBuilder for more info.
1097 Clusterator(const uint32_t* clusters,
1098 const char* utf8Text,
1099 uint32_t glyphCount,
1100 uint32_t textByteLength)
1101 : fClusters(clusters)
1102 , fUtf8Text(utf8Text)
1103 , fGlyphCount(glyphCount)
1104 , fTextByteLength(textByteLength) {
1105 // This is a cheap heuristic for /ReversedChars which seems to
1106 // work for clusters produced by HarfBuzz, which either
1107 // increase from zero (LTR) or decrease to zero (RTL).
1108 // "ReversedChars" is how PDF deals with RTL text.
1109 fReversedChars =
1110 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1111 }
1112 struct Cluster {
1113 const char* fUtf8Text;
1114 uint32_t fTextByteLength;
1115 uint32_t fGlyphIndex;
1116 uint32_t fGlyphCount;
1117 explicit operator bool() const { return fGlyphCount != 0; }
1118 };
1119 // True if this looks like right-to-left text.
1120 bool reversedChars() const { return fReversedChars; }
1121 Cluster next() {
1122 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1123 // These glyphs have no text. Treat as one "cluster".
1124 uint32_t glyphCount = fGlyphCount;
1125 fGlyphCount = 0;
1126 return Cluster{nullptr, 0, 0, glyphCount};
1127 }
1128 if (fGlyphCount == 0 || fTextByteLength == 0) {
1129 return Cluster{nullptr, 0, 0, 0}; // empty
1130 }
1131 SkASSERT(fUtf8Text);
1132 SkASSERT(fClusters);
1133 uint32_t cluster = fClusters[0];
1134 if (cluster >= fTextByteLength) {
1135 return Cluster{nullptr, 0, 0, 0}; // bad input.
1136 }
1137 uint32_t glyphsInCluster = 1;
1138 while (glyphsInCluster < fGlyphCount &&
1139 fClusters[glyphsInCluster] == cluster) {
1140 ++glyphsInCluster;
1141 }
1142 SkASSERT(glyphsInCluster <= fGlyphCount);
1143 uint32_t textLength = 0;
1144 if (glyphsInCluster == fGlyphCount) {
1145 // consumes rest of glyphs and rest of text
1146 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1147 textLength = fTextByteLength - cluster;
1148 } else { // RTL text; last cluster.
1149 SkASSERT(fPreviousCluster < fTextByteLength);
1150 if (fPreviousCluster <= cluster) { // bad input.
1151 return Cluster{nullptr, 0, 0, 0};
1152 }
1153 textLength = fPreviousCluster - cluster;
1154 }
1155 fGlyphCount = 0;
1156 return Cluster{fUtf8Text + cluster,
1157 textLength,
1158 fGlyphIndex,
1159 glyphsInCluster};
1160 }
1161 SkASSERT(glyphsInCluster < fGlyphCount);
1162 uint32_t nextCluster = fClusters[glyphsInCluster];
1163 if (nextCluster >= fTextByteLength) {
1164 return Cluster{nullptr, 0, 0, 0}; // bad input.
1165 }
1166 if (nextCluster > cluster) { // LTR text
1167 if (kInvalidCluster != fPreviousCluster) {
1168 return Cluster{nullptr, 0, 0, 0}; // bad input.
1169 }
1170 textLength = nextCluster - cluster;
1171 } else { // RTL text
1172 SkASSERT(nextCluster < cluster);
1173 if (kInvalidCluster == fPreviousCluster) { // first cluster
1174 textLength = fTextByteLength - cluster;
1175 } else { // later cluster
1176 if (fPreviousCluster <= cluster) {
1177 return Cluster{nullptr, 0, 0, 0}; // bad input.
1178 }
1179 textLength = fPreviousCluster - cluster;
1180 }
1181 fPreviousCluster = cluster;
1182 }
1183 uint32_t glyphIndex = fGlyphIndex;
1184 fGlyphCount -= glyphsInCluster;
1185 fGlyphIndex += glyphsInCluster;
1186 fClusters += glyphsInCluster;
1187 return Cluster{fUtf8Text + cluster,
1188 textLength,
1189 glyphIndex,
1190 glyphsInCluster};
1191 }
1192
1193private:
1194 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1195 const uint32_t* fClusters;
1196 const char* fUtf8Text;
1197 uint32_t fGlyphCount;
1198 uint32_t fTextByteLength;
1199 uint32_t fGlyphIndex = 0;
1200 uint32_t fPreviousCluster = kInvalidCluster;
1201 bool fReversedChars = false;
1202};
1203
1204struct TextStorage {
1205 SkAutoTMalloc<char> fUtf8textStorage;
1206 SkAutoTMalloc<uint32_t> fClusterStorage;
1207 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1208};
halcanaryf0c30f52016-07-15 13:35:45 -07001209} // namespace
1210
halcanaryf59d18a2016-09-16 14:44:57 -07001211/** Given some unicode text (as passed to drawText(), convert to
1212 glyphs (via primitive shaping), while preserving
1213 glyph-to-character mapping information. */
1214static Clusterator make_clusterator(
1215 const void* sourceText,
1216 size_t sourceByteCount,
1217 const SkPaint& paint,
1218 TextStorage* storage,
1219 int glyphCount) {
1220 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1221 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1222 SkASSERT(glyphCount > 0);
1223 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1224 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1225 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1226 uint32_t* clusters = storage->fClusterStorage.get();
1227 uint32_t utf8ByteCount = 0;
1228 const char* utf8Text = nullptr;
1229 switch (paint.getTextEncoding()) {
1230 case SkPaint::kUTF8_TextEncoding: {
1231 const char* txtPtr = (const char*)sourceText;
1232 for (int i = 0; i < glyphCount; ++i) {
1233 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1234 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1235 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1236 }
1237 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1238 utf8ByteCount = SkToU32(sourceByteCount);
1239 utf8Text = (const char*)sourceText;
1240 break;
1241 }
1242 case SkPaint::kUTF16_TextEncoding: {
1243 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1244 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1245 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1246 storage->fUtf8textStorage.reset(utf8ByteCount);
1247 char* txtPtr = storage->fUtf8textStorage.get();
1248 utf8Text = txtPtr;
1249 int clusterIndex = 0;
1250 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1251 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1252 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1253 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1254 }
1255 SkASSERT(clusterIndex == glyphCount);
1256 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1257 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1258 break;
1259 }
1260 case SkPaint::kUTF32_TextEncoding: {
1261 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1262 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1263 SkASSERT(glyphCount == utf32count);
1264 for (int i = 0; i < utf32count; ++i) {
1265 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1266 }
1267 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1268 char* txtPtr = storage->fUtf8textStorage.get();
1269 utf8Text = txtPtr;
1270 for (int i = 0; i < utf32count; ++i) {
1271 clusters[i] = SkToU32(txtPtr - utf8Text);
1272 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1273 }
1274 break;
1275 }
1276 default:
1277 SkDEBUGFAIL("");
1278 break;
1279 }
1280 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1281}
1282
halcanaryf59d18a2016-09-16 14:44:57 -07001283static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1284 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1285}
1286
halcanaryc2f9ec12016-09-12 08:55:29 -07001287static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1288 wStream->writeText("/");
1289 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1290 wStream->write(&prefix, 1);
1291 wStream->writeDecAsText(fontIndex);
1292 wStream->writeText(" ");
1293 SkPDFUtils::AppendScalar(textSize, wStream);
1294 wStream->writeText(" Tf\n");
1295}
1296
Hal Canaryd12a6762017-05-26 17:01:16 -04001297static SkPath draw_text_as_path(const void* sourceText, size_t sourceByteCount,
1298 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
1299 SkPoint offset, const SkPaint& srcPaint) {
1300 SkPath path;
1301 int glyphCount;
1302 SkAutoTMalloc<SkPoint> tmpPoints;
1303 switch (positioning) {
1304 case SkTextBlob::kDefault_Positioning:
1305 srcPaint.getTextPath(sourceText, sourceByteCount, offset.x(), offset.y(), &path);
1306 break;
1307 case SkTextBlob::kHorizontal_Positioning:
1308 glyphCount = srcPaint.countText(sourceText, sourceByteCount);
1309 tmpPoints.realloc(glyphCount);
1310 for (int i = 0; i < glyphCount; ++i) {
1311 tmpPoints[i] = {pos[i] + offset.x(), offset.y()};
1312 }
1313 srcPaint.getPosTextPath(sourceText, sourceByteCount, tmpPoints.get(), &path);
1314 break;
1315 case SkTextBlob::kFull_Positioning:
1316 srcPaint.getPosTextPath(sourceText, sourceByteCount, (const SkPoint*)pos, &path);
1317 path.offset(offset.x(), offset.y());
1318 break;
1319 }
1320 return path;
1321}
1322
Hal Canary9b9510a2017-07-18 09:39:00 -04001323static bool has_outline_glyph(SkGlyphID gid, SkGlyphCache* cache) {
1324 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1325 const SkPath* path = cache->findPath(glyph);
1326 return (path && !path->isEmpty()) || (glyph.fWidth == 0 && glyph.fHeight == 0);
1327}
1328
Hal Canary699b8732017-06-13 12:13:29 -04001329static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkGlyphCache* cache,
1330 SkScalar xScale, SkScalar yScale,
1331 SkPoint xy, const SkMatrix& ctm) {
1332 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1333 SkRect glyphBounds = {glyph.fLeft * xScale,
1334 glyph.fTop * yScale,
1335 (glyph.fLeft + glyph.fWidth) * xScale,
1336 (glyph.fTop + glyph.fHeight) * yScale};
1337 glyphBounds.offset(xy);
1338 ctm.mapRect(&glyphBounds); // now in dev space.
1339 return glyphBounds;
1340}
1341
1342static bool contains(const SkRect& r, SkPoint p) {
1343 return r.left() <= p.x() && p.x() <= r.right() &&
1344 r.top() <= p.y() && p.y() <= r.bottom();
1345}
1346
Hal Canary9b9510a2017-07-18 09:39:00 -04001347static sk_sp<SkImage> image_from_mask(const SkMask& mask) {
1348 if (!mask.fImage) {
1349 return nullptr;
1350 }
1351 SkIRect bounds = mask.fBounds;
1352 SkBitmap bm;
1353 switch (mask.fFormat) {
1354 case SkMask::kBW_Format:
1355 bm.allocPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()));
1356 for (int y = 0; y < bm.height(); ++y) {
1357 for (int x8 = 0; x8 < bm.width(); x8 += 8) {
1358 uint8_t v = *mask.getAddr1(x8 + bounds.x(), y + bounds.y());
1359 int e = SkTMin(x8 + 8, bm.width());
1360 for (int x = x8; x < e; ++x) {
1361 *bm.getAddr8(x, y) = (v >> (x & 0x7)) & 0x1 ? 0xFF : 0x00;
1362 }
1363 }
1364 }
1365 bm.setImmutable();
1366 return SkImage::MakeFromBitmap(bm);
1367 case SkMask::kA8_Format:
1368 bm.installPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()),
1369 mask.fImage, mask.fRowBytes);
1370 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1371 case SkMask::kARGB32_Format:
1372 bm.installPixels(SkImageInfo::MakeN32Premul(bounds.width(), bounds.height()),
1373 mask.fImage, mask.fRowBytes);
1374 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1375 case SkMask::k3D_Format:
1376 SkASSERT(false);
1377 return nullptr;
1378 case SkMask::kLCD16_Format:
1379 SkASSERT(false);
1380 return nullptr;
1381 default:
1382 SkASSERT(false);
1383 return nullptr;
1384 }
1385}
1386
halcanary4ed2f012016-08-15 18:40:07 -07001387void SkPDFDevice::internalDrawText(
Mike Reeda1361362017-03-07 09:37:29 -05001388 const void* sourceText, size_t sourceByteCount,
halcanary4ed2f012016-08-15 18:40:07 -07001389 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001390 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1391 uint32_t textByteLength, const char* utf8Text) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001392 if (0 == sourceByteCount || !sourceText) {
1393 return;
1394 }
1395 if (this->cs().isEmpty(size(*this))) {
halcanary4ed2f012016-08-15 18:40:07 -07001396 return;
1397 }
halcanaryea17dfe2016-08-24 09:20:57 -07001398 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1399 if (srcPaint.isVerticalText()) {
1400 // Don't pretend we support drawing vertical text. It is not
1401 // clear to me how to switch to "vertical writing" mode in PDF.
1402 // Currently neither Chromium or Android set this flag.
1403 // https://bug.skia.org/5665
halcanaryea17dfe2016-08-24 09:20:57 -07001404 }
Hal Canaryd12a6762017-05-26 17:01:16 -04001405 if (srcPaint.getPathEffect()
1406 || srcPaint.getMaskFilter()
1407 || SkPaint::kFill_Style != srcPaint.getStyle()) {
1408 // Stroked Text doesn't work well with Type3 fonts.
1409 SkPath path = draw_text_as_path(sourceText, sourceByteCount, pos,
1410 positioning, offset, srcPaint);
1411 this->drawPath(path, srcPaint, nullptr, true);
halcanaryf59d18a2016-09-16 14:44:57 -07001412 return;
halcanarye06ca962016-09-09 05:34:55 -07001413 }
halcanary4ed2f012016-08-15 18:40:07 -07001414 SkPaint paint = calculate_text_paint(srcPaint);
Hal Canaryd12a6762017-05-26 17:01:16 -04001415 remove_color_filter(&paint);
halcanary4ed2f012016-08-15 18:40:07 -07001416 replace_srcmode_on_opaque_paint(&paint);
1417 if (!paint.getTypeface()) {
1418 paint.setTypeface(SkTypeface::MakeDefault());
1419 }
1420 SkTypeface* typeface = paint.getTypeface();
1421 if (!typeface) {
1422 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1423 return;
1424 }
halcanary4871f222016-08-26 13:17:44 -07001425
1426 const SkAdvancedTypefaceMetrics* metrics =
1427 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1428 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001429 return;
1430 }
halcanary2bd295e2016-09-16 08:15:56 -07001431 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1432 if (glyphCount <= 0) {
1433 return;
1434 }
halcanary3b294d52016-09-16 13:21:08 -07001435
halcanaryf59d18a2016-09-16 14:44:57 -07001436 // These three heap buffers are only used in the case where no glyphs
1437 // are passed to drawText() (most clients pass glyphs or a textblob).
1438 TextStorage storage;
1439 const SkGlyphID* glyphs = nullptr;
1440 Clusterator clusterator;
1441 if (textByteLength > 0) {
1442 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1443 glyphs = (const SkGlyphID*)sourceText;
1444 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1445 SkASSERT(clusters);
1446 SkASSERT(utf8Text);
1447 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1448 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1449 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1450 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1451 glyphs = (const SkGlyphID*)sourceText;
1452 clusterator = Clusterator(SkToU32(glyphCount));
1453 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1454 SkASSERT(nullptr == clusters);
1455 SkASSERT(nullptr == utf8Text);
1456 } else {
1457 SkASSERT(nullptr == clusters);
1458 SkASSERT(nullptr == utf8Text);
1459 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1460 &storage, glyphCount);
1461 glyphs = storage.fGlyphStorage;
1462 }
halcanary4ed2f012016-08-15 18:40:07 -07001463 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001464 paint.setHinting(SkPaint::kNo_Hinting);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001465
1466 int emSize;
1467 SkAutoGlyphCache glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
1468
1469 SkScalar textSize = paint.getTextSize();
1470 SkScalar advanceScale = textSize * paint.getTextScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001471
Hal Canary699b8732017-06-13 12:13:29 -04001472 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1473 SkScalar textScaleY = textSize / emSize;
1474 SkScalar textScaleX = advanceScale + paint.getTextSkewX() * textScaleY;
1475
halcanary4ed2f012016-08-15 18:40:07 -07001476 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001477 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1478 SkPaint::kCenter_Align == alignment ? -0.5f :
1479 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001480 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001481 SkScalar advance = 0;
halcanary4ed2f012016-08-15 18:40:07 -07001482 for (int i = 0; i < glyphCount; ++i) {
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001483 advance += advanceScale * glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
halcanary4ed2f012016-08-15 18:40:07 -07001484 }
halcanary4871f222016-08-26 13:17:44 -07001485 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001486 }
Hal Canary699b8732017-06-13 12:13:29 -04001487 SkRect clipStackBounds = this->cs().bounds(size(*this));
Hal Canary9b9510a2017-07-18 09:39:00 -04001488 struct PositionedGlyph {
1489 SkPoint fPos;
1490 SkGlyphID fGlyph;
1491 };
1492 SkTArray<PositionedGlyph> fMissingGlyphs;
1493 {
1494 ScopedContentEntry content(this, paint, true);
1495 if (!content.entry()) {
1496 return;
robertphillips5ba165e2016-08-15 15:36:58 -07001497 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001498 SkDynamicMemoryWStream* out = content.stream();
1499 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
1500
1501 out->writeText("BT\n");
1502 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1503
1504 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
1505
1506 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
1507 if (clusterator.reversedChars()) {
1508 out->writeText("/ReversedChars BMC\n");
1509 }
1510 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1511 GlyphPositioner glyphPositioner(out,
1512 paint.getTextSkewX(),
1513 multiByteGlyphs,
1514 defaultPositioning,
1515 offset);
1516 SkPDFFont* font = nullptr;
1517
1518 while (Clusterator::Cluster c = clusterator.next()) {
1519 int index = c.fGlyphIndex;
1520 int glyphLimit = index + c.fGlyphCount;
1521
1522 bool actualText = false;
1523 SK_AT_SCOPE_EXIT(if (actualText) {
1524 glyphPositioner.flush();
1525 out->writeText("EMC\n");
1526 });
1527 if (c.fUtf8Text) { // real cluster
1528 // Check if `/ActualText` needed.
1529 const char* textPtr = c.fUtf8Text;
1530 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1531 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1532 if (unichar < 0) {
halcanaryf59d18a2016-09-16 14:44:57 -07001533 return;
1534 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001535 if (textPtr < textEnd || // more characters left
1536 glyphLimit > index + 1 || // toUnicode wouldn't work
1537 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1538 {
1539 glyphPositioner.flush();
1540 out->writeText("/Span<</ActualText <");
1541 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1542 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1543 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1544 while (textPtr < textEnd) {
1545 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1546 if (unichar < 0) {
1547 break;
1548 }
1549 SkPDFUtils::WriteUTF16beHex(out, unichar);
1550 }
1551 out->writeText("> >> BDC\n"); // begin marked-content sequence
1552 // with an associated property list.
1553 actualText = true;
halcanaryf59d18a2016-09-16 14:44:57 -07001554 }
halcanaryf59d18a2016-09-16 14:44:57 -07001555 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001556 for (; index < glyphLimit; ++index) {
1557 SkGlyphID gid = glyphs[index];
1558 if (gid > maxGlyphID) {
1559 continue;
halcanaryf59d18a2016-09-16 14:44:57 -07001560 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001561 if (!font || !font->hasGlyph(gid)) {
1562 // Not yet specified font or need to switch font.
1563 int fontIndex = this->getFontResourceIndex(typeface, gid);
1564 // All preconditions for SkPDFFont::GetFontResource are met.
1565 SkASSERT(fontIndex >= 0);
1566 if (fontIndex < 0) {
1567 return;
1568 }
1569 glyphPositioner.flush();
1570 update_font(out, fontIndex, textSize);
1571 font = fFontResources[fontIndex];
1572 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1573 if (!font) {
1574 return;
1575 }
1576 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1577 }
1578 SkPoint xy = {0, 0};
1579 SkScalar advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1580 if (!defaultPositioning) {
1581 xy = SkTextBlob::kFull_Positioning == positioning
1582 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1583 : SkPoint{pos[index], 0};
1584 if (alignment != SkPaint::kLeft_Align) {
1585 xy.offset(alignmentFactor * advance, 0);
1586 }
1587 // Do a glyph-by-glyph bounds-reject if positions are absolute.
1588 SkRect glyphBounds = get_glyph_bounds_device_space(
1589 gid, glyphCache.get(), textScaleX, textScaleY,
1590 xy + offset, this->ctm());
1591 if (glyphBounds.isEmpty()) {
1592 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
1593 continue;
1594 }
1595 } else {
1596 if (!clipStackBounds.intersects(glyphBounds)) {
1597 continue; // reject glyphs as out of bounds
1598 }
1599 }
1600 if (!has_outline_glyph(gid, glyphCache.get())) {
Hal Canary10ccb022017-07-19 10:12:11 -04001601 fMissingGlyphs.push_back({xy + offset, gid});
Hal Canary699b8732017-06-13 12:13:29 -04001602 }
1603 } else {
Hal Canary9b9510a2017-07-18 09:39:00 -04001604 if (!has_outline_glyph(gid, glyphCache.get())) {
1605 fMissingGlyphs.push_back({offset, gid});
Hal Canary699b8732017-06-13 12:13:29 -04001606 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001607 offset += SkPoint{advance, 0};
Hal Canary699b8732017-06-13 12:13:29 -04001608 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001609 font->noteGlyphUsage(gid);
1610
1611 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1612 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
halcanaryf59d18a2016-09-16 14:44:57 -07001613 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001614 }
1615 }
1616 if (fMissingGlyphs.count() > 0) {
1617 // Fall back on images.
1618 SkPaint scaledGlyphCachePaint;
1619 scaledGlyphCachePaint.setTextSize(paint.getTextSize());
1620 scaledGlyphCachePaint.setTextScaleX(paint.getTextScaleX());
1621 scaledGlyphCachePaint.setTextSkewX(paint.getTextSkewX());
1622 scaledGlyphCachePaint.setTypeface(sk_ref_sp(typeface));
1623 SkAutoGlyphCache scaledGlyphCache(scaledGlyphCachePaint, nullptr, nullptr);
1624 SkTHashMap<SkPDFCanon::BitmapGlyphKey, SkPDFCanon::BitmapGlyph>* map =
1625 &this->getCanon()->fBitmapGlyphImages;
1626 for (PositionedGlyph positionedGlyph : fMissingGlyphs) {
1627 SkPDFCanon::BitmapGlyphKey key = {typeface->uniqueID(),
1628 paint.getTextSize(),
1629 paint.getTextScaleX(),
1630 paint.getTextSkewX(),
1631 positionedGlyph.fGlyph,
1632 0};
1633 SkImage* img = nullptr;
1634 SkIPoint imgOffset = {0, 0};
1635 if (SkPDFCanon::BitmapGlyph* ptr = map->find(key)) {
1636 img = ptr->fImage.get();
1637 imgOffset = ptr->fOffset;
1638 } else {
1639 (void)scaledGlyphCache->findImage(
1640 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph));
1641 SkMask mask;
1642 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph).toMask(&mask);
1643 imgOffset = {mask.fBounds.x(), mask.fBounds.y()};
1644 img = map->set(key, {image_from_mask(mask), imgOffset})->fImage.get();
1645 }
1646 if (img) {
1647 SkPoint pt = positionedGlyph.fPos +
1648 SkPoint{(SkScalar)imgOffset.x(), (SkScalar)imgOffset.y()};
1649 this->drawImage(img, pt.x(), pt.y(), srcPaint);
1650 }
halcanaryf59d18a2016-09-16 14:44:57 -07001651 }
robertphillips5ba165e2016-08-15 15:36:58 -07001652 }
halcanary4ed2f012016-08-15 18:40:07 -07001653}
1654
Mike Reeda1361362017-03-07 09:37:29 -05001655void SkPDFDevice::drawText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001656 SkScalar x, SkScalar y, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001657 this->internalDrawText(text, len, nullptr, SkTextBlob::kDefault_Positioning,
halcanarye06ca962016-09-09 05:34:55 -07001658 SkPoint{x, y}, paint, nullptr, 0, nullptr);
halcanary4ed2f012016-08-15 18:40:07 -07001659}
1660
Mike Reeda1361362017-03-07 09:37:29 -05001661void SkPDFDevice::drawPosText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001662 const SkScalar pos[], int scalarsPerPos,
1663 const SkPoint& offset, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001664 this->internalDrawText(text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001665 offset, paint, nullptr, 0, nullptr);
1666}
1667
Mike Reeda1361362017-03-07 09:37:29 -05001668void SkPDFDevice::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
halcanarye06ca962016-09-09 05:34:55 -07001669 const SkPaint &paint, SkDrawFilter* drawFilter) {
1670 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1671 SkPaint runPaint(paint);
1672 it.applyFontToPaint(&runPaint);
1673 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1674 continue;
1675 }
1676 runPaint.setFlags(this->filterTextFlags(runPaint));
1677 SkPoint offset = it.offset() + SkPoint{x, y};
Mike Reeda1361362017-03-07 09:37:29 -05001678 this->internalDrawText(it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
halcanarye06ca962016-09-09 05:34:55 -07001679 it.pos(), it.positioning(), offset, runPaint,
1680 it.clusters(), it.textSize(), it.text());
1681 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001682}
1683
Mike Reed2f6b5a42017-03-19 15:04:17 -04001684void SkPDFDevice::drawVertices(const SkVertices*, SkBlendMode, const SkPaint&) {
Mike Reeda1361362017-03-07 09:37:29 -05001685 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001686 return;
1687 }
reed@google.com85e143c2013-12-30 15:51:25 +00001688 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001689}
1690
Mike Reeda1361362017-03-07 09:37:29 -05001691void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001692 SkASSERT(!paint.getImageFilter());
1693
reed7503d602016-07-15 14:23:29 -07001694 // Check if the source device is really a bitmapdevice (because that's what we returned
1695 // from createDevice (likely due to an imagefilter)
1696 SkPixmap pmap;
1697 if (device->peekPixels(&pmap)) {
1698 SkBitmap bitmap;
1699 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001700 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001701 return;
1702 }
1703
fmalita6987dca2014-11-13 08:33:37 -08001704 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001705 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001706
1707 SkScalar scalarX = SkIntToScalar(x);
1708 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001709 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1710 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001711 fLinkToURLs.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001712 }
halcanary91fcb3e2016-03-04 13:53:22 -08001713 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1714 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001715 fLinkToDestinations.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001716 }
halcanary91fcb3e2016-03-04 13:53:22 -08001717 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1718 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001719 fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001720 }
1721
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001722 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001723 return;
1724 }
1725
Mike Reeda1361362017-03-07 09:37:29 -05001726 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
1727 ScopedContentEntry content(this, this->cs(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001728 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001729 return;
1730 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001731 if (content.needShape()) {
1732 SkPath shape;
1733 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001734 SkIntToScalar(device->width()),
1735 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001736 content.setShape(shape);
1737 }
1738 if (!content.needSource()) {
1739 return;
1740 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001741
halcanary4b1e17e2016-07-27 14:49:46 -07001742 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
Hal Canary51329c92017-06-27 14:28:37 -04001743 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001744}
1745
reede8f30622016-03-23 18:59:25 -07001746sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1747 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001748}
1749
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001750
halcanary8103a342016-03-08 15:10:16 -08001751sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001752 SkTDArray<SkPDFObject*> fonts;
1753 fonts.setReserve(fFontResources.count());
1754 for (SkPDFFont* font : fFontResources) {
1755 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001756 }
halcanary8103a342016-03-08 15:10:16 -08001757 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001758 &fGraphicStateResources,
1759 &fShaderResources,
1760 &fXObjectResources,
1761 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001762}
1763
halcanary8103a342016-03-08 15:10:16 -08001764sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001765 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001766 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001767 mediaBox->appendInt(0);
1768 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001769 mediaBox->appendInt(fPageSize.width());
1770 mediaBox->appendInt(fPageSize.height());
1771 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001772}
1773
mtklein5f939ab2016-03-16 10:28:35 -07001774std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001775 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001776 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001777 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001778 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001779
Hal Canary6d673962017-02-22 17:16:59 -05001780 GraphicStackState gsState(fExistingClipStack, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001781 for (const auto& entry : fContentEntries) {
Hal Canary6d673962017-02-22 17:16:59 -05001782 gsState.updateClip(entry.fState.fClipStack,
Mike Reeda1361362017-03-07 09:37:29 -05001783 {0, 0}, SkRect::Make(size(*this)));
halcanary2be7e012016-03-28 11:58:08 -07001784 gsState.updateMatrix(entry.fState.fMatrix);
1785 gsState.updateDrawingState(entry.fState);
1786
halcanaryafdc1772016-08-23 09:02:12 -07001787 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001788 }
1789 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001790 if (buffer.bytesWritten() > 0) {
1791 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1792 } else {
1793 return skstd::make_unique<SkMemoryStream>();
1794 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001795}
1796
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001797/* Draws an inverse filled path by using Path Ops to compute the positive
1798 * inverse using the current clip as the inverse bounds.
1799 * Return true if this was an inverse path and was properly handled,
1800 * otherwise returns false and the normal drawing routine should continue,
1801 * either as a (incorrect) fallback or because the path was not inverse
1802 * in the first place.
1803 */
Mike Reeda1361362017-03-07 09:37:29 -05001804bool SkPDFDevice::handleInversePath(const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001805 const SkPaint& paint, bool pathIsMutable,
1806 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001807 if (!origPath.isInverseFillType()) {
1808 return false;
1809 }
1810
Mike Reeda1361362017-03-07 09:37:29 -05001811 if (this->cs().isEmpty(size(*this))) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001812 return false;
1813 }
1814
1815 SkPath modifiedPath;
1816 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1817 SkPaint noInversePaint(paint);
1818
1819 // Merge stroking operations into final path.
1820 if (SkPaint::kStroke_Style == paint.getStyle() ||
1821 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1822 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1823 if (doFillPath) {
1824 noInversePaint.setStyle(SkPaint::kFill_Style);
1825 noInversePaint.setStrokeWidth(0);
1826 pathPtr = &modifiedPath;
1827 } else {
1828 // To be consistent with the raster output, hairline strokes
1829 // are rendered as non-inverted.
1830 modifiedPath.toggleInverseFillType();
Mike Reeda1361362017-03-07 09:37:29 -05001831 this->drawPath(modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001832 return true;
1833 }
1834 }
1835
1836 // Get bounds of clip in current transform space
1837 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001838 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001839 SkMatrix totalMatrix = this->ctm();
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001840 if (prePathMatrix) {
1841 totalMatrix.preConcat(*prePathMatrix);
1842 }
1843 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001844 return false;
1845 }
Mike Reeda1361362017-03-07 09:37:29 -05001846 SkRect bounds = this->cs().bounds(size(*this));
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001847 transformInverse.mapRect(&bounds);
1848
1849 // Extend the bounds by the line width (plus some padding)
1850 // so the edge doesn't cause a visible stroke.
1851 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1852 paint.getStrokeWidth() + SK_Scalar1);
1853
1854 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1855 return false;
1856 }
1857
Mike Reeda1361362017-03-07 09:37:29 -05001858 this->drawPath(modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001859 return true;
1860}
1861
wangxianzhuef6c50a2015-09-17 20:38:02 -07001862void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1863 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001864 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001865 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001866 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001867 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001868 }
halcanary91fcb3e2016-03-04 13:53:22 -08001869 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001870 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001871 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001872 array->appendObject(
1873 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001874 }
1875}
epoger@google.comb58772f2013-03-08 09:09:10 +00001876
halcanary6d622702015-03-25 08:45:42 -07001877void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001878 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001879 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001880 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001881 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001882 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001883 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001884 pdfDest->appendScalar(p.x());
1885 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001886 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001887 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001888 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001889 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001890}
1891
halcanary4b1e17e2016-07-27 14:49:46 -07001892sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
halcanary5abbb442016-07-29 08:41:33 -07001893 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001894 if (!fInitialTransform.isIdentity()) {
1895 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001896 SkDEBUGFAIL("Layer initial transform should be invertible.");
1897 inverseTransform.reset();
1898 }
1899 }
halcanary4b1e17e2016-07-27 14:49:46 -07001900 sk_sp<SkPDFObject> xobject =
1901 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
halcanary5abbb442016-07-29 08:41:33 -07001902 this->makeResourceDict(), inverseTransform, nullptr);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001903 // We always draw the form xobjects that we create back into the device, so
1904 // we simply preserve the font usage instead of pulling it out and merging
1905 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001906 this->cleanUp(); // Reset this device to have no content.
1907 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001908 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001909}
1910
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001911void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001912 sk_sp<SkPDFObject> mask,
Mike Reeda1361362017-03-07 09:37:29 -05001913 const SkClipStack& clipStack,
reed374772b2016-10-05 17:33:02 -07001914 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001915 bool invertClip) {
Mike Reeda1361362017-03-07 09:37:29 -05001916 if (!invertClip && clipStack.isEmpty(size(*this))) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001917 return;
1918 }
1919
halcanary4b1e17e2016-07-27 14:49:46 -07001920 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001921 std::move(mask), invertClip,
1922 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001923
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001924 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001925 paint.setBlendMode(mode);
Mike Reeda1361362017-03-07 09:37:29 -05001926 ScopedContentEntry content(this, clipStack, SkMatrix::I(), paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001927 if (!content.entry()) {
1928 return;
1929 }
Hal Canary51329c92017-06-27 14:28:37 -04001930 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()), content.stream());
1931 SkPDFUtils::DrawFormXObject(xObjectIndex, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001932 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001933}
1934
Mike Reeda1361362017-03-07 09:37:29 -05001935SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack& clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001936 const SkMatrix& matrix,
1937 const SkPaint& paint,
1938 bool hasText,
1939 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001940 *dst = nullptr;
reed374772b2016-10-05 17:33:02 -07001941 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001942
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001943 // For the following modes, we want to handle source and destination
1944 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001945 if (blendMode == SkBlendMode::kClear ||
1946 blendMode == SkBlendMode::kSrc ||
1947 blendMode == SkBlendMode::kSrcIn ||
1948 blendMode == SkBlendMode::kDstIn ||
1949 blendMode == SkBlendMode::kSrcOut ||
1950 blendMode == SkBlendMode::kDstOut ||
1951 blendMode == SkBlendMode::kSrcATop ||
1952 blendMode == SkBlendMode::kDstATop ||
1953 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001954 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001955 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001956 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001957 } else if (blendMode != SkBlendMode::kSrc &&
1958 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001959 // Except for Src and SrcOut, if there isn't anything already there,
1960 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001961 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001962 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001963 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001964 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001965 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001966
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001967 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001968 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001969 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001970 }
1971
halcanary2be7e012016-03-28 11:58:08 -07001972 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001973 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001974 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001975 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001976 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001977 } else {
halcanary2be7e012016-03-28 11:58:08 -07001978 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001979 }
Mike Reeda1361362017-03-07 09:37:29 -05001980 populateGraphicStateEntryFromPaint(matrix, clipStack, paint, hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001981 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001982}
1983
reed374772b2016-10-05 17:33:02 -07001984void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001985 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001986 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001987 if (blendMode != SkBlendMode::kClear &&
1988 blendMode != SkBlendMode::kSrc &&
1989 blendMode != SkBlendMode::kDstOver &&
1990 blendMode != SkBlendMode::kSrcIn &&
1991 blendMode != SkBlendMode::kDstIn &&
1992 blendMode != SkBlendMode::kSrcOut &&
1993 blendMode != SkBlendMode::kDstOut &&
1994 blendMode != SkBlendMode::kSrcATop &&
1995 blendMode != SkBlendMode::kDstATop &&
1996 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001997 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001998 return;
1999 }
reed374772b2016-10-05 17:33:02 -07002000 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002001 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00002002 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002003 // For DstOver, an empty content entry was inserted before the rest
2004 // of the content entries. If nothing was drawn, it needs to be
2005 // removed.
halcanary2be7e012016-03-28 11:58:08 -07002006 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002007 }
2008 return;
2009 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002010 if (!dst) {
reed374772b2016-10-05 17:33:02 -07002011 SkASSERT(blendMode == SkBlendMode::kSrc ||
2012 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002013 return;
2014 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002015
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002016 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07002017 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002018 // Changing the current content into a form-xobject will destroy the clip
2019 // objects which is fine since the xobject will already be clipped. However
2020 // if source has shape, we need to clip it too, so a copy of the clip is
2021 // saved.
halcanary2be7e012016-03-28 11:58:08 -07002022
2023 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002024
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002025 SkPaint stockPaint;
2026
halcanary4b1e17e2016-07-27 14:49:46 -07002027 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002028 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002029 // If nothing was drawn and there's no shape, then the draw was a
2030 // no-op, but dst needs to be restored for that to be true.
2031 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
2032 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
2033 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07002034 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
2035 blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002036 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07002037 // TODO: addXObjectResource take sk_sp
Hal Canary51329c92017-06-27 14:28:37 -04002038 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002039 return;
2040 } else {
reed374772b2016-10-05 17:33:02 -07002041 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002042 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002043 } else {
halcanary2be7e012016-03-28 11:58:08 -07002044 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07002045 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002046 }
2047
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002048 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
2049 // without alpha.
reed374772b2016-10-05 17:33:02 -07002050 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002051 // TODO(vandebo): In order to properly support SrcATop we have to track
2052 // the shape of what's been drawn at all times. It's the intersection of
2053 // the non-transparent parts of the device and the outlines (shape) of
2054 // all images and devices drawn.
2055 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
Mike Reeda1361362017-03-07 09:37:29 -05002056 fExistingClipStack, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002057 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07002058 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002059 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002060 SkPaint filledPaint;
2061 filledPaint.setColor(SK_ColorBLACK);
2062 filledPaint.setStyle(SkPaint::kFill_Style);
Mike Reeda1361362017-03-07 09:37:29 -05002063 this->internalDrawPath(clipStack, SkMatrix::I(), *shape, filledPaint, nullptr, true);
2064 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
2065 this->makeFormXObjectFromDevice(),
2066 fExistingClipStack,
2067 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07002068 } else {
Mike Reeda1361362017-03-07 09:37:29 -05002069 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
2070 srcFormXObject,
2071 fExistingClipStack,
2072 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002073 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002074 }
2075
reed374772b2016-10-05 17:33:02 -07002076 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002077 return;
reed374772b2016-10-05 17:33:02 -07002078 } else if (blendMode == SkBlendMode::kSrc ||
2079 blendMode == SkBlendMode::kDstATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002080 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002081 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04002082 SkPDFUtils::DrawFormXObject(this->addXObjectResource(srcFormXObject.get()),
2083 content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002084 }
reed374772b2016-10-05 17:33:02 -07002085 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002086 return;
2087 }
reed374772b2016-10-05 17:33:02 -07002088 } else if (blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002089 ScopedContentEntry content(this, fExistingClipStack,
2090 SkMatrix::I(), stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002091 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04002092 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002093 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002094 }
2095
reed374772b2016-10-05 17:33:02 -07002096 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
2097 blendMode == SkBlendMode::kDstIn ||
2098 blendMode == SkBlendMode::kSrcOut ||
2099 blendMode == SkBlendMode::kDstOut ||
2100 blendMode == SkBlendMode::kSrcATop ||
2101 blendMode == SkBlendMode::kDstATop ||
2102 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002103
reed374772b2016-10-05 17:33:02 -07002104 if (blendMode == SkBlendMode::kSrcIn ||
2105 blendMode == SkBlendMode::kSrcOut ||
2106 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07002107 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
2108 std::move(dst),
Mike Reeda1361362017-03-07 09:37:29 -05002109 fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07002110 SkBlendMode::kSrcOver,
2111 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07002112 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002113 } else {
reed374772b2016-10-05 17:33:02 -07002114 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07002115 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07002116 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002117 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
Mike Reeda1361362017-03-07 09:37:29 -05002118 std::move(dst), fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07002119 SkBlendMode::kSrcOver, false);
2120 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002121 }
halcanarydabd4f02016-08-03 11:16:56 -07002122 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
Mike Reeda1361362017-03-07 09:37:29 -05002123 fExistingClipStack, mode,
reed374772b2016-10-05 17:33:02 -07002124 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07002125 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002126 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002127}
2128
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002129bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00002130 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07002131 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002132 return true;
2133 }
2134 return false;
2135}
2136
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002137void SkPDFDevice::populateGraphicStateEntryFromPaint(
2138 const SkMatrix& matrix,
2139 const SkClipStack& clipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002140 const SkPaint& paint,
2141 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07002142 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07002143 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
2144 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
2145 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002146
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002147 entry->fMatrix = matrix;
2148 entry->fClipStack = clipStack;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002149 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2150 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002151
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002152 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08002153 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07002154 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002155 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002156 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05002157 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
2158 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002159 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05002160 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002161 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07002162 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002163 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05002164 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
2165 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2166 color = gradientColor;
2167 } else {
2168 // PDF positions patterns relative to the initial transform, so
2169 // we need to apply the current transform to the shader parameters.
2170 SkMatrix transform = matrix;
2171 transform.postConcat(fInitialTransform);
2172
2173 // PDF doesn't support kClamp_TileMode, so we simulate it by making
2174 // a pattern the size of the current clip.
Mike Reeda1361362017-03-07 09:37:29 -05002175 SkRect clipStackBounds = clipStack.bounds(size(*this));
Hal Canaryc8f91802017-02-12 20:29:12 -05002176
2177 // We need to apply the initial transform to bounds in order to get
2178 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05002179 fInitialTransform.mapRect(&clipStackBounds);
2180 SkIRect bounds;
2181 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05002182
Hal Canary7e872ca2017-07-19 15:51:18 -04002183 pdfShader = SkPDFMakeShader(fDocument, shader, transform, bounds, paint.getColor());
Hal Canaryc8f91802017-02-12 20:29:12 -05002184
2185 if (pdfShader.get()) {
2186 // pdfShader has been canonicalized so we can directly compare
2187 // pointers.
2188 int resourceIndex = fShaderResources.find(pdfShader.get());
2189 if (resourceIndex < 0) {
2190 resourceIndex = fShaderResources.count();
2191 fShaderResources.push(pdfShader.get());
2192 pdfShader.get()->ref();
2193 }
2194 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002195 }
2196 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002197 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002198
Hal Canary80fa7ce2017-06-28 16:04:20 -04002199 sk_sp<SkPDFDict> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002200 if (color == paint.getColor()) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002201 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002202 } else {
2203 SkPaint newPaint = paint;
2204 newPaint.setColor(color);
Hal Canary5c1b3602017-04-17 16:30:06 -04002205 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002206 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002207 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002208 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002209
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002210 if (hasText) {
2211 entry->fTextScaleX = paint.getTextScaleX();
2212 entry->fTextFill = paint.getStyle();
2213 } else {
2214 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002215 }
2216}
2217
halcanarybe27a112015-04-01 13:31:19 -07002218int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002219 // Assumes that gs has been canonicalized (so we can directly compare
2220 // pointers).
2221 int result = fGraphicStateResources.find(gs);
2222 if (result < 0) {
2223 result = fGraphicStateResources.count();
2224 fGraphicStateResources.push(gs);
2225 gs->ref();
2226 }
2227 return result;
2228}
2229
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002230int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002231 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002232 // Assumes that xobject has been canonicalized (so we can directly compare
2233 // pointers).
2234 int result = fXObjectResources.find(xObject);
2235 if (result < 0) {
2236 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002237 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002238 }
2239 return result;
2240}
2241
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002242int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002243 sk_sp<SkPDFFont> newFont = SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID);
halcanary7e8d5d32016-08-12 07:59:38 -07002244 if (!newFont) {
2245 return -1;
2246 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002247 int resourceIndex = fFontResources.find(newFont.get());
2248 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002249 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002250 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002251 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002252 }
2253 return resourceIndex;
2254}
2255
Hal Canaryfafe1352017-04-11 12:12:02 -04002256static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07002257
Hal Canary7cbf5e32017-07-12 13:10:23 -04002258static sk_sp<SkImage> color_filter(const SkImage* image,
halcanarya50151d2016-03-25 11:57:49 -07002259 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002260 auto surface =
Hal Canary7cbf5e32017-07-12 13:10:23 -04002261 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07002262 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002263 SkCanvas* canvas = surface->getCanvas();
2264 canvas->clear(SK_ColorTRANSPARENT);
2265 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002266 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canary7cbf5e32017-07-12 13:10:23 -04002267 canvas->drawImage(image, 0, 0, &paint);
halcanarya50151d2016-03-25 11:57:49 -07002268 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002269}
2270
2271////////////////////////////////////////////////////////////////////////////////
Hal Canary7cbf5e32017-07-12 13:10:23 -04002272
2273static bool is_integer(SkScalar x) {
2274 return x == SkScalarTruncToScalar(x);
2275}
2276
2277static bool is_integral(const SkRect& r) {
2278 return is_integer(r.left()) &&
2279 is_integer(r.top()) &&
2280 is_integer(r.right()) &&
2281 is_integer(r.bottom());
2282}
2283
2284void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
2285 const SkRect* src,
2286 const SkRect& dst,
2287 const SkPaint& srcPaint,
2288 const SkMatrix& ctm) {
2289 if (!imageSubset) {
halcanarya50151d2016-03-25 11:57:49 -07002290 return;
2291 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002292
2293 SkIRect bounds = imageSubset.image()->bounds();
2294 SkPaint paint = srcPaint;
2295 if (imageSubset.image()->isOpaque()) {
2296 replace_srcmode_on_opaque_paint(&paint);
2297 }
2298 SkRect srcRect = src ? *src : SkRect::Make(bounds);
2299 SkMatrix transform;
2300 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
2301 if (src && *src != SkRect::Make(bounds)) {
2302 if (!srcRect.intersect(SkRect::Make(bounds))) {
2303 return;
2304 }
2305 srcRect.roundOut(&bounds);
2306 transform.preTranslate(SkIntToScalar(bounds.x()),
2307 SkIntToScalar(bounds.y()));
2308 if (bounds != imageSubset.image()->bounds()) {
2309 imageSubset = imageSubset.subset(bounds);
2310 }
2311 if (!imageSubset) {
2312 return;
2313 }
2314 }
2315
Hal Canaryd425a1d2017-07-12 13:13:51 -04002316 // TODO(halcanary) support isAlphaOnly & getMaskFilter.
2317 bool imageAlphaOnly = imageSubset.image()->isAlphaOnly() && !paint.getMaskFilter();
2318 if (imageAlphaOnly) {
2319 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
2320 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2321 paint.setColorFilter(nullptr);
2322 imageSubset = SkKeyedImage(std::move(img));
2323 if (!imageSubset) {
2324 return;
2325 }
2326 imageAlphaOnly = imageSubset.image()->isAlphaOnly();
2327 // The colorfilter can make a alphonly image no longer be alphaonly.
2328 }
2329 }
2330 if (imageAlphaOnly) {
2331 sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
2332 if (!mask) {
2333 return;
2334 }
2335 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
2336 // Must mask with a Form XObject.
2337 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
2338 {
2339 SkCanvas canvas(maskDevice.get());
2340 canvas.concat(transform);
2341 canvas.concat(ctm);
2342 // TODO(halcanary): investigate sub-pixel clipping.
2343 canvas.drawImage(mask, 0, 0);
2344 }
2345 remove_color_filter(&paint);
2346 if (!ctm.isIdentity() && paint.getShader()) {
2347 transform_shader(&paint, ctm); // Since we are using identity matrix.
2348 }
2349 ScopedContentEntry content(this, this->cs(), SkMatrix::I(), paint);
2350 if (!content.entry()) {
2351 return;
2352 }
2353 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
2354 SkPDFUtils::AppendRectangle(SkRect::Make(fPageSize), content.stream());
2355 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kWinding_FillType, content.stream());
2356 this->clearMaskOnGraphicState(content.stream());
2357 return;
2358 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002359 if (paint.getMaskFilter()) {
2360 paint.setShader(imageSubset.image()->makeShader(&transform));
2361 SkPath path;
2362 path.addRect(SkRect::Make(imageSubset.image()->bounds()));
2363 this->internalDrawPath(this->cs(), this->ctm(), path, paint, &transform, true);
2364 return;
2365 }
2366 transform.postConcat(ctm);
2367
2368 bool needToRestore = false;
2369 if (src && !is_integral(*src)) {
2370 // Need sub-pixel clipping to fix https://bug.skia.org/4374
2371 this->cs().save();
2372 this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
2373 needToRestore = true;
2374 }
2375 SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
2376
halcanary7a14b312015-10-01 07:28:13 -07002377 #ifdef SK_PDF_IMAGE_STATS
2378 gDrawImageCalls.fetch_add(1);
2379 #endif
Hal Canary7cbf5e32017-07-12 13:10:23 -04002380 SkMatrix matrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002381
2382 // Rasterize the bitmap using perspective in a new bitmap.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002383 if (transform.hasPerspective()) {
Hal Canarya0622582017-06-29 18:51:35 -04002384 SkASSERT(fDocument->rasterDpi() > 0);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002385 // Transform the bitmap in the new space, without taking into
2386 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002387 SkPath perspectiveOutline;
Hal Canary7cbf5e32017-07-12 13:10:23 -04002388 SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
halcanary7a14b312015-10-01 07:28:13 -07002389 perspectiveOutline.addRect(imageBounds);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002390 perspectiveOutline.transform(transform);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002391
2392 // TODO(edisonn): perf - use current clip too.
2393 // Retrieve the bounds of the new shape.
2394 SkRect bounds = perspectiveOutline.getBounds();
2395
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002396 // Transform the bitmap in the new space, taking into
2397 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002398 SkMatrix total = transform;
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002399 total.postConcat(fInitialTransform);
Hal Canarya0622582017-06-29 18:51:35 -04002400 SkScalar dpiScale = SkIntToScalar(fDocument->rasterDpi()) /
2401 SkIntToScalar(SkPDFUtils::kDpiForRasterScaleOne);
halcanary7a14b312015-10-01 07:28:13 -07002402 total.postScale(dpiScale, dpiScale);
2403
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002404 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002405 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002406 physicalPerspectiveOutline.transform(total);
2407
halcanary7a14b312015-10-01 07:28:13 -07002408 SkRect physicalPerspectiveBounds =
2409 physicalPerspectiveOutline.getBounds();
2410 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2411 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002412
2413 // TODO(edisonn): A better approach would be to use a bitmap shader
2414 // (in clamp mode) and draw a rect over the entire bounding box. Then
2415 // intersect perspectiveOutline to the clip. That will avoid introducing
2416 // alpha to the image while still giving good behavior at the edge of
2417 // the image. Avoiding alpha will reduce the pdf size and generation
2418 // CPU time some.
2419
halcanary7a14b312015-10-01 07:28:13 -07002420 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2421
Hal Canaryf50ff392016-09-30 10:25:39 -04002422 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002423 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002424 return;
2425 }
halcanary7a14b312015-10-01 07:28:13 -07002426 SkCanvas* canvas = surface->getCanvas();
2427 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002428
2429 SkScalar deltaX = bounds.left();
2430 SkScalar deltaY = bounds.top();
2431
Hal Canary7cbf5e32017-07-12 13:10:23 -04002432 SkMatrix offsetMatrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002433 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002434 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002435
2436 // Translate the draw in the new canvas, so we perfectly fit the
2437 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002438 canvas->setMatrix(offsetMatrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002439 canvas->drawImage(imageSubset.image(), 0, 0);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002440 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002441 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002442
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002443 // In the new space, we use the identity matrix translated
2444 // and scaled to reflect DPI.
2445 matrix.setScale(1 / scaleX, 1 / scaleY);
2446 matrix.postTranslate(deltaX, deltaY);
2447
Hal Canary7cbf5e32017-07-12 13:10:23 -04002448 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2449 if (!imageSubset) {
2450 return;
2451 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002452 }
2453
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002454 SkMatrix scaled;
2455 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002456 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2457 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002458 // Scale the image up from 1x1 to WxH.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002459 SkIRect subset = imageSubset.image()->bounds();
2460 scaled.postScale(SkIntToScalar(subset.width()),
2461 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002462 scaled.postConcat(matrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002463 ScopedContentEntry content(this, this->cs(), scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002464 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002465 return;
2466 }
2467 if (content.needShape()) {
2468 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002469 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002470 shape.transform(matrix);
2471 content.setShape(shape);
2472 }
2473 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002474 return;
2475 }
2476
halcanary287d22d2015-09-24 10:20:05 -07002477 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002478 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002479 // draw calls. This code here works for all
2480 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2481 // rasterize a layer on this backend). Fortuanely, this seems
2482 // to be how Chromium impements most color-filters.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002483 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2484 imageSubset = SkKeyedImage(std::move(img));
2485 if (!imageSubset) {
2486 return;
2487 }
halcanary7a14b312015-10-01 07:28:13 -07002488 // TODO(halcanary): de-dupe this by caching filtered images.
2489 // (maybe in the resource cache?)
2490 }
halcanarya50151d2016-03-25 11:57:49 -07002491
Hal Canary7cbf5e32017-07-12 13:10:23 -04002492 SkBitmapKey key = imageSubset.key();
Hal Canary5c1b3602017-04-17 16:30:06 -04002493 sk_sp<SkPDFObject>* pdfimagePtr = fDocument->canon()->fPDFBitmapMap.find(key);
2494 sk_sp<SkPDFObject> pdfimage = pdfimagePtr ? *pdfimagePtr : nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002495 if (!pdfimage) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002496 SkASSERT(imageSubset);
2497 pdfimage = SkPDFCreateBitmapObject(imageSubset.release(),
2498 fDocument->canon()->fPixelSerializer.get());
halcanary7a14b312015-10-01 07:28:13 -07002499 if (!pdfimage) {
2500 return;
halcanary287d22d2015-09-24 10:20:05 -07002501 }
halcanarya50151d2016-03-25 11:57:49 -07002502 fDocument->serialize(pdfimage); // serialize images early.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002503 SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
Hal Canary5c1b3602017-04-17 16:30:06 -04002504 fDocument->canon()->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002505 }
halcanarya50151d2016-03-25 11:57:49 -07002506 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
Hal Canary51329c92017-06-27 14:28:37 -04002507 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002508}
reede51c3562016-07-19 14:33:20 -07002509
2510///////////////////////////////////////////////////////////////////////////////////////////////////
2511
2512#include "SkSpecialImage.h"
2513#include "SkImageFilter.h"
2514
Florin Malita53f77bd2017-04-28 13:48:37 -04002515void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2516 SkImage* clipImage, const SkMatrix& clipMatrix) {
reede51c3562016-07-19 14:33:20 -07002517 SkASSERT(!srcImg->isTextureBacked());
2518
Florin Malita53f77bd2017-04-28 13:48:37 -04002519 //TODO: clipImage support
2520
reede51c3562016-07-19 14:33:20 -07002521 SkBitmap resultBM;
2522
2523 SkImageFilter* filter = paint.getImageFilter();
2524 if (filter) {
2525 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002526 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002527 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002528 const SkIRect clipBounds =
Mike Reeda1361362017-03-07 09:37:29 -05002529 this->cs().bounds(this->imageInfo().bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002530 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
brianosman2a75e5d2016-09-22 07:15:37 -07002531 // TODO: Should PDF be operating in a specified color space? For now, run the filter
2532 // in the same color space as the source (this is different from all other backends).
2533 SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2534 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002535
2536 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2537 if (resultImg) {
2538 SkPaint tmpUnfiltered(paint);
2539 tmpUnfiltered.setImageFilter(nullptr);
2540 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002541 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002542 }
2543 }
2544 } else {
2545 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002546 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002547 }
2548 }
2549}
2550
2551sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2552 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2553}
2554
2555sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002556 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2557 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2558 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002559 SkColorSpace* legacyColorSpace = nullptr;
reede51c3562016-07-19 14:33:20 -07002560 return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
Brian Osman61624f02016-12-09 14:51:59 -05002561 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002562}
2563
2564sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002565 return nullptr;
2566}
brianosman04a44d02016-09-21 09:46:57 -07002567
2568SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2569 // We always return a transient cache, so it is freed after each
2570 // filter traversal.
2571 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2572}