blob: aae792bb8b14c0220ca67b74f406c3daed057d0f [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
reed374772b2016-10-05 17:33:02 -0700116// If the paint will definitely draw opaquely, replace kSrc with
117// kSrcOver. http://crbug.com/473572
halcanarya6814332015-05-27 08:53:36 -0700118static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
reed374772b2016-10-05 17:33:02 -0700119 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
120 paint->setBlendMode(SkBlendMode::kSrcOver);
halcanarya6814332015-05-27 08:53:36 -0700121 }
122}
123
Hal Canaryd12a6762017-05-26 17:01:16 -0400124// A shader's matrix is: CTMM x LocalMatrix x WrappingLocalMatrix. We want to
125// switch to device space, where CTM = I, while keeping the original behavior.
126//
127// I * LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
128// LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
129// InvLocalMatrix * LocalMatrix * NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
130// NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
131//
132static void transform_shader(SkPaint* paint, const SkMatrix& ctm) {
133 SkMatrix lm = SkPDFUtils::GetShaderLocalMatrix(paint->getShader());
134 SkMatrix lmInv;
135 if (lm.invert(&lmInv)) {
136 SkMatrix m = SkMatrix::Concat(SkMatrix::Concat(lmInv, ctm), lm);
137 paint->setShader(paint->getShader()->makeWithLocalMatrix(m));
138 }
139}
140
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000141static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000142 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -0700143 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000144 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700145 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000146 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700147 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000148 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000149}
150
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000151static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000152 SkPaint result = paint;
153 if (result.isFakeBoldText()) {
154 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
155 kStdFakeBoldInterpKeys,
156 kStdFakeBoldInterpValues,
157 kStdFakeBoldInterpLength);
Mike Reed8be952a2017-02-13 20:44:33 -0500158 SkScalar width = result.getTextSize() * fakeBoldScale;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000159 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000160 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000161 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000162 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000163 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000164 result.setStrokeWidth(width);
165 }
166 return result;
167}
168
Hal Canaryf50ff392016-09-30 10:25:39 -0400169
Hal Canaryd12a6762017-05-26 17:01:16 -0400170// If the paint has a color filter, apply the color filter to the shader or the
171// paint color. Remove the color filter.
172void remove_color_filter(SkPaint* paint) {
173 if (SkColorFilter* cf = paint->getColorFilter()) {
174 if (SkShader* shader = paint->getShader()) {
175 paint->setShader(shader->makeWithColorFilter(paint->refColorFilter()));
176 } else {
177 paint->setColor(cf->filterColor(paint->getColor()));
178 }
179 paint->setColorFilter(nullptr);
180 }
181}
182
halcanary2be7e012016-03-28 11:58:08 -0700183SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
184 : fColor(SK_ColorBLACK)
185 , fTextScaleX(SK_Scalar1)
186 , fTextFill(SkPaint::kFill_Style)
187 , fShaderIndex(-1)
halcanaryc2f9ec12016-09-12 08:55:29 -0700188 , fGraphicStateIndex(-1) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000189 fMatrix.reset();
190}
191
halcanary2be7e012016-03-28 11:58:08 -0700192bool SkPDFDevice::GraphicStateEntry::compareInitialState(
193 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000194 return fColor == cur.fColor &&
195 fShaderIndex == cur.fShaderIndex &&
196 fGraphicStateIndex == cur.fGraphicStateIndex &&
197 fMatrix == cur.fMatrix &&
198 fClipStack == cur.fClipStack &&
199 (fTextScaleX == 0 ||
200 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000201}
202
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000203class GraphicStackState {
204public:
205 GraphicStackState(const SkClipStack& existingClipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000206 SkWStream* contentStream)
207 : fStackDepth(0),
208 fContentStream(contentStream) {
209 fEntries[0].fClipStack = existingClipStack;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000210 }
211
Hal Canary6d673962017-02-22 17:16:59 -0500212 void updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500213 const SkPoint& translation, const SkRect& bounds);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000214 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700215 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000216
217 void drainStack();
218
219private:
220 void push();
221 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700222 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000223
224 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
225 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700226 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000227 int fStackDepth;
228 SkWStream* fContentStream;
229};
230
231void GraphicStackState::drainStack() {
232 while (fStackDepth) {
233 pop();
234 }
235}
236
237void GraphicStackState::push() {
238 SkASSERT(fStackDepth < kMaxStackDepth);
239 fContentStream->writeText("q\n");
240 fStackDepth++;
241 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
242}
243
244void GraphicStackState::pop() {
245 SkASSERT(fStackDepth > 0);
246 fContentStream->writeText("Q\n");
247 fStackDepth--;
248}
249
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000250/* Calculate an inverted path's equivalent non-inverted path, given the
251 * canvas bounds.
252 * outPath may alias with invPath (since this is supported by PathOps).
253 */
254static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
255 SkPath* outPath) {
256 SkASSERT(invPath.isInverseFillType());
257
258 SkPath clipPath;
259 clipPath.addRect(bounds);
260
reedcdb42bb2015-06-26 10:23:07 -0700261 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000262}
263
Hal Canary44a97d52017-02-22 10:45:25 -0500264bool apply_clip(SkClipOp op, const SkPath& u, const SkPath& v, SkPath* r) {
265 switch (op) {
266 case SkClipOp::kDifference:
267 return Op(u, v, kDifference_SkPathOp, r);
268 case SkClipOp::kIntersect:
269 return Op(u, v, kIntersect_SkPathOp, r);
Mike Reed14113bc2017-05-10 14:13:20 -0400270#ifdef SK_SUPPORT_DEPRECATED_CLIPOPS
Hal Canary44a97d52017-02-22 10:45:25 -0500271 case SkClipOp::kUnion_deprecated:
272 return Op(u, v, kUnion_SkPathOp, r);
273 case SkClipOp::kXOR_deprecated:
274 return Op(u, v, kXOR_SkPathOp, r);
275 case SkClipOp::kReverseDifference_deprecated:
276 return Op(u, v, kReverseDifference_SkPathOp, r);
277 case SkClipOp::kReplace_deprecated:
278 *r = v;
279 return true;
Mike Reed14113bc2017-05-10 14:13:20 -0400280#endif
Hal Canary44a97d52017-02-22 10:45:25 -0500281 default:
282 return false;
283 }
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000284}
285
286/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
287 * Returns true if successful, or false if not successful.
288 * If successful, the resulting clip is stored in outClipPath.
289 * If not successful, outClipPath is undefined, and a fallback method
290 * should be used.
291 */
292static bool get_clip_stack_path(const SkMatrix& transform,
293 const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500294 const SkRect& bounds,
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000295 SkPath* outClipPath) {
296 outClipPath->reset();
297 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
298
299 const SkClipStack::Element* clipEntry;
300 SkClipStack::Iter iter;
301 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
302 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
303 SkPath entryPath;
Brian Salomonf3b46e52017-08-30 11:37:57 -0400304 if (SkClipStack::Element::DeviceSpaceType::kEmpty == clipEntry->getDeviceSpaceType()) {
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000305 outClipPath->reset();
306 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
307 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000308 } else {
Brian Salomonf3b46e52017-08-30 11:37:57 -0400309 clipEntry->asDeviceSpacePath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000310 }
311 entryPath.transform(transform);
Hal Canary44a97d52017-02-22 10:45:25 -0500312 if (!apply_clip(clipEntry->getOp(), *outClipPath, entryPath, outClipPath)) {
313 return false;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000314 }
315 }
316
317 if (outClipPath->isInverseFillType()) {
318 // The bounds are slightly outset to ensure this is correct in the
319 // face of floating-point accuracy and possible SkRegion bitmap
320 // approximations.
Hal Canary44a97d52017-02-22 10:45:25 -0500321 SkRect clipBounds = bounds;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000322 clipBounds.outset(SK_Scalar1, SK_Scalar1);
323 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
324 return false;
325 }
326 }
327 return true;
328}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000329
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000330// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000331// graphic state stack, and the fact that we can know all the clips used
332// on the page to optimize this.
333void GraphicStackState::updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500334 const SkPoint& translation,
335 const SkRect& bounds) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000336 if (clipStack == currentEntry()->fClipStack) {
337 return;
338 }
339
340 while (fStackDepth > 0) {
341 pop();
342 if (clipStack == currentEntry()->fClipStack) {
343 return;
344 }
345 }
346 push();
347
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000348 currentEntry()->fClipStack = clipStack;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000349
350 SkMatrix transform;
351 transform.setTranslate(translation.fX, translation.fY);
352
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000353 SkPath clipPath;
Hal Canary44a97d52017-02-22 10:45:25 -0500354 if (get_clip_stack_path(transform, clipStack, bounds, &clipPath)) {
halcanary5edf2902016-09-07 09:05:25 -0700355 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
356 SkPath::FillType clipFill = clipPath.getFillType();
357 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
358 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
359 if (clipFill == SkPath::kEvenOdd_FillType) {
360 fContentStream->writeText("W* n\n");
361 } else {
362 fContentStream->writeText("W n\n");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000363 }
364 }
halcanary5edf2902016-09-07 09:05:25 -0700365 // If Op() fails (pathological case; e.g. input values are
366 // extremely large or NaN), emit no clip at all.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000367}
368
369void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
370 if (matrix == currentEntry()->fMatrix) {
371 return;
372 }
373
374 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
375 SkASSERT(fStackDepth > 0);
376 SkASSERT(fEntries[fStackDepth].fClipStack ==
377 fEntries[fStackDepth -1].fClipStack);
378 pop();
379
380 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
381 }
382 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
383 return;
384 }
385
386 push();
387 SkPDFUtils::AppendTransform(matrix, fContentStream);
388 currentEntry()->fMatrix = matrix;
389}
390
halcanary2be7e012016-03-28 11:58:08 -0700391void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000392 // PDF treats a shader as a color, so we only set one or the other.
393 if (state.fShaderIndex >= 0) {
394 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000395 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000396 currentEntry()->fShaderIndex = state.fShaderIndex;
397 }
398 } else {
399 if (state.fColor != currentEntry()->fColor ||
400 currentEntry()->fShaderIndex >= 0) {
401 emit_pdf_color(state.fColor, fContentStream);
402 fContentStream->writeText("RG ");
403 emit_pdf_color(state.fColor, fContentStream);
404 fContentStream->writeText("rg\n");
405 currentEntry()->fColor = state.fColor;
406 currentEntry()->fShaderIndex = -1;
407 }
408 }
409
410 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000411 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000412 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
413 }
414
415 if (state.fTextScaleX) {
416 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
Hal Canary9b491b22017-11-28 15:10:13 -0500417 SkScalar pdfScale = state.fTextScaleX * 100;
halcanarybc4696b2015-05-06 10:56:04 -0700418 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000419 fContentStream->writeText(" Tz\n");
420 currentEntry()->fTextScaleX = state.fTextScaleX;
421 }
422 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700423 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
424 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
425 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000426 fContentStream->writeDecAsText(state.fTextFill);
427 fContentStream->writeText(" Tr\n");
428 currentEntry()->fTextFill = state.fTextFill;
429 }
430 }
431}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000432
reed76033be2015-03-14 10:54:31 -0700433static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700434 // PDF does not support image filters, so render them on CPU.
435 // Note that this rendering is done at "screen" resolution (100dpi), not
436 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700437 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800438 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700439
440 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700441 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700442}
443
444SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700445 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700446 // need to return a raster device, which we will detect in drawDevice()
447 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700448 }
Hal Canary22b2d8c2017-07-19 14:46:12 -0400449 return new SkPDFDevice(cinfo.fInfo.dimensions(), fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000450}
451
halcanary989da4a2016-03-21 14:33:17 -0700452SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
453
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000454// A helper class to automatically finish a ContentEntry at the end of a
455// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000456class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000457public:
Mike Reeda1361362017-03-07 09:37:29 -0500458 ScopedContentEntry(SkPDFDevice* device,
459 const SkClipStack& clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000460 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500461 const SkPaint& paint,
462 bool hasText = false)
463 : fDevice(device)
464 , fContentEntry(nullptr)
465 , fBlendMode(SkBlendMode::kSrcOver)
466 , fDstFormXObject(nullptr)
467 {
468 if (matrix.hasPerspective()) {
469 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
470 return;
471 }
472 fBlendMode = paint.getBlendMode();
473 fContentEntry =
474 fDevice->setUpContentEntry(clipStack, matrix, paint, hasText, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000475 }
Mike Reeda1361362017-03-07 09:37:29 -0500476 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, bool hasText = false)
477 : ScopedContentEntry(dev, dev->cs(), dev->ctm(), paint, hasText) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000478
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000479 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000480 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000481 SkPath* shape = &fShape;
482 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700483 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000484 }
reed374772b2016-10-05 17:33:02 -0700485 fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000486 }
487 }
488
halcanary2be7e012016-03-28 11:58:08 -0700489 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
Hal Canary51329c92017-06-27 14:28:37 -0400490 SkDynamicMemoryWStream* stream() { return &fContentEntry->fContent; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000491
492 /* Returns true when we explicitly need the shape of the drawing. */
493 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700494 switch (fBlendMode) {
495 case SkBlendMode::kClear:
496 case SkBlendMode::kSrc:
497 case SkBlendMode::kSrcIn:
498 case SkBlendMode::kSrcOut:
499 case SkBlendMode::kDstIn:
500 case SkBlendMode::kDstOut:
501 case SkBlendMode::kSrcATop:
502 case SkBlendMode::kDstATop:
503 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000504 return true;
505 default:
506 return false;
507 }
508 }
509
510 /* Returns true unless we only need the shape of the drawing. */
511 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700512 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000513 return false;
514 }
515 return true;
516 }
517
518 /* If the shape is different than the alpha component of the content, then
519 * setShape should be called with the shape. In particular, images and
520 * devices have rectangular shape.
521 */
522 void setShape(const SkPath& shape) {
523 fShape = shape;
524 }
525
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000526private:
527 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700528 SkPDFDevice::ContentEntry* fContentEntry;
reed374772b2016-10-05 17:33:02 -0700529 SkBlendMode fBlendMode;
halcanarydabd4f02016-08-03 11:16:56 -0700530 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000531 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000532};
533
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000534////////////////////////////////////////////////////////////////////////////////
535
Hal Canarya0622582017-06-29 18:51:35 -0400536SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc)
reed589a39e2016-08-20 07:59:19 -0700537 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
538 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700539 , fPageSize(pageSize)
Hal Canarya0622582017-06-29 18:51:35 -0400540 , fInitialTransform(SkMatrix::I())
541 , fDocument(doc)
542{
Hal Canary22b2d8c2017-07-19 14:46:12 -0400543 SkASSERT(!pageSize.isEmpty());
Hal Canarya0622582017-06-29 18:51:35 -0400544}
robertphillips1f3923e2016-07-21 07:17:54 -0700545
Hal Canarya0622582017-06-29 18:51:35 -0400546void SkPDFDevice::setFlip() {
547 // Skia generally uses the top left as the origin but PDF
548 // natively has the origin at the bottom left. This matrix
549 // corrects for that. But that only needs to be done once, we
550 // don't do it when layering.
551 fInitialTransform.setTranslate(0, SkIntToScalar(fPageSize.fHeight));
552 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000553}
554
555SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700556 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000557}
558
559void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700560 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000561}
562
halcanary3c35fb32016-06-30 11:55:07 -0700563void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000564 fGraphicStateResources.unrefAll();
565 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000566 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000567 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000568}
569
Mike Reeda1361362017-03-07 09:37:29 -0500570void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500571 if (!value) {
572 return;
573 }
574 if (rect.isEmpty()) {
Mike Reeda1361362017-03-07 09:37:29 -0500575 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
576 SkPoint transformedPoint;
577 this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
Hal Canary5c1b3602017-04-17 16:30:06 -0400578 fNamedDestinations.emplace_back(NamedDestination{sk_ref_sp(value), transformedPoint});
Mike Reeda1361362017-03-07 09:37:29 -0500579 }
580 return;
581 }
582 // Convert to path to handle non-90-degree rotations.
583 SkPath path;
584 path.addRect(rect);
585 path.transform(this->ctm(), &path);
586 SkPath clip;
587 (void)this->cs().asPath(&clip);
588 Op(clip, path, kIntersect_SkPathOp, &path);
589 // PDF wants a rectangle only.
590 SkRect transformedRect = path.getBounds();
591 if (transformedRect.isEmpty()) {
592 return;
593 }
594 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400595 fLinkToURLs.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
Mike Reeda1361362017-03-07 09:37:29 -0500596 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400597 fLinkToDestinations.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
reedf70b5312016-03-04 16:36:20 -0800598 }
599}
600
Hal Canaryd12a6762017-05-26 17:01:16 -0400601void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
602 SkPaint newPaint = srcPaint;
603 remove_color_filter(&newPaint);
halcanarya6814332015-05-27 08:53:36 -0700604 replace_srcmode_on_opaque_paint(&newPaint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000605 newPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryd12a6762017-05-26 17:01:16 -0400606
607 SkMatrix ctm = this->ctm();
608 if (ctm.getType() & SkMatrix::kPerspective_Mask) {
609 if (newPaint.getShader()) {
610 transform_shader(&newPaint, ctm);
611 }
612 ctm = SkMatrix::I();
613 }
614 ScopedContentEntry content(this, this->cs(), ctm, newPaint);
Mike Reeda1361362017-03-07 09:37:29 -0500615 this->internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000616}
617
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000618void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700619 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000620 if (!contentEntry) {
621 return;
622 }
Hal Canaryd425a1d2017-07-12 13:13:51 -0400623 SkRect bbox = SkRect::Make(fPageSize);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000624 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000625 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000626 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000627 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000628 inverse.mapRect(&bbox);
629
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000630 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000631 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000632 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000633}
634
Mike Reeda1361362017-03-07 09:37:29 -0500635void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700636 size_t count,
637 const SkPoint* points,
638 const SkPaint& srcPaint) {
639 SkPaint passedPaint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400640 remove_color_filter(&passedPaint);
halcanarya6814332015-05-27 08:53:36 -0700641 replace_srcmode_on_opaque_paint(&passedPaint);
Hal Canary80fa7ce2017-06-28 16:04:20 -0400642 if (SkCanvas::kPoints_PointMode != mode) {
643 passedPaint.setStyle(SkPaint::kStroke_Style);
644 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000645 if (count == 0) {
646 return;
647 }
648
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000649 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
650 // We only use this when there's a path effect because of the overhead
651 // of multiple calls to setUpContentEntry it causes.
652 if (passedPaint.getPathEffect()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400653 if (this->cs().isEmpty(this->bounds())) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000654 return;
655 }
Mike Reeda1361362017-03-07 09:37:29 -0500656 draw_points(mode, count, points, passedPaint,
657 this->devClipBounds(), this->ctm(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000658 return;
659 }
660
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000661 const SkPaint* paint = &passedPaint;
662 SkPaint modifiedPaint;
663
664 if (mode == SkCanvas::kPoints_PointMode &&
665 paint->getStrokeCap() != SkPaint::kRound_Cap) {
666 modifiedPaint = *paint;
667 paint = &modifiedPaint;
668 if (paint->getStrokeWidth()) {
669 // PDF won't draw a single point with square/butt caps because the
670 // orientation is ambiguous. Draw a rectangle instead.
671 modifiedPaint.setStyle(SkPaint::kFill_Style);
672 SkScalar strokeWidth = paint->getStrokeWidth();
673 SkScalar halfStroke = SkScalarHalf(strokeWidth);
674 for (size_t i = 0; i < count; i++) {
675 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
676 r.inset(-halfStroke, -halfStroke);
Mike Reeda1361362017-03-07 09:37:29 -0500677 this->drawRect(r, modifiedPaint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000678 }
679 return;
680 } else {
681 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
682 }
683 }
684
Mike Reeda1361362017-03-07 09:37:29 -0500685 ScopedContentEntry content(this, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000686 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000687 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000688 }
Hal Canary51329c92017-06-27 14:28:37 -0400689 SkDynamicMemoryWStream* contentStream = content.stream();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000690 switch (mode) {
691 case SkCanvas::kPolygon_PointMode:
Hal Canary51329c92017-06-27 14:28:37 -0400692 SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000693 for (size_t i = 1; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400694 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000695 }
Hal Canary51329c92017-06-27 14:28:37 -0400696 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000697 break;
698 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000699 for (size_t i = 0; i < count/2; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400700 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
701 SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
702 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000703 }
704 break;
705 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000706 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
707 for (size_t i = 0; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400708 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
709 SkPDFUtils::ClosePath(contentStream);
710 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000711 }
712 break;
713 default:
714 SkASSERT(false);
715 }
716}
717
halcanary8103a342016-03-08 15:10:16 -0800718static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800719 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700720 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700721 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700722
halcanaryece83922016-03-08 08:32:12 -0800723 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700724 border->reserve(3);
725 border->appendInt(0); // Horizontal corner radius.
726 border->appendInt(0); // Vertical corner radius.
727 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800728 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700729
halcanaryece83922016-03-08 08:32:12 -0800730 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700731 rect->reserve(4);
732 rect->appendScalar(translatedRect.fLeft);
733 rect->appendScalar(translatedRect.fTop);
734 rect->appendScalar(translatedRect.fRight);
735 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800736 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700737
halcanary8103a342016-03-08 15:10:16 -0800738 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700739}
740
halcanary8103a342016-03-08 15:10:16 -0800741static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700742 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700743 SkString url(static_cast<const char *>(urlData->data()),
744 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800745 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700746 action->insertName("S", "URI");
747 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800748 annotation->insertObject("A", std::move(action));
749 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700750}
751
halcanary8103a342016-03-08 15:10:16 -0800752static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
753 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700754 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700755 SkString name(static_cast<const char *>(nameData->data()),
756 nameData->size() - 1);
757 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800758 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700759}
760
Mike Reeda1361362017-03-07 09:37:29 -0500761void SkPDFDevice::drawRect(const SkRect& rect,
halcanarya6814332015-05-27 08:53:36 -0700762 const SkPaint& srcPaint) {
763 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400764 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700765 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000766 SkRect r = rect;
767 r.sort();
768
Hal Canaryd12a6762017-05-26 17:01:16 -0400769 if (paint.getPathEffect() || paint.getMaskFilter()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400770 if (this->cs().isEmpty(this->bounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000771 return;
772 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000773 SkPath path;
774 path.addRect(r);
Mike Reeda1361362017-03-07 09:37:29 -0500775 this->drawPath(path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000776 return;
777 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000778
Mike Reeda1361362017-03-07 09:37:29 -0500779 ScopedContentEntry content(this, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000780 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000781 return;
782 }
Hal Canary51329c92017-06-27 14:28:37 -0400783 SkPDFUtils::AppendRectangle(r, content.stream());
784 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000785}
786
Mike Reeda1361362017-03-07 09:37:29 -0500787void SkPDFDevice::drawRRect(const SkRRect& rrect,
halcanarya6814332015-05-27 08:53:36 -0700788 const SkPaint& srcPaint) {
789 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400790 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700791 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000792 SkPath path;
793 path.addRRect(rrect);
Mike Reeda1361362017-03-07 09:37:29 -0500794 this->drawPath(path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000795}
796
Mike Reeda1361362017-03-07 09:37:29 -0500797void SkPDFDevice::drawOval(const SkRect& oval,
halcanarya6814332015-05-27 08:53:36 -0700798 const SkPaint& srcPaint) {
799 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400800 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700801 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700802 SkPath path;
803 path.addOval(oval);
Mike Reeda1361362017-03-07 09:37:29 -0500804 this->drawPath(path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700805}
806
Mike Reeda1361362017-03-07 09:37:29 -0500807void SkPDFDevice::drawPath(const SkPath& origPath,
halcanarya6814332015-05-27 08:53:36 -0700808 const SkPaint& srcPaint,
809 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000810 bool pathIsMutable) {
Mike Reeda1361362017-03-07 09:37:29 -0500811 this->internalDrawPath(
812 this->cs(), this->ctm(), origPath, srcPaint, prePathMatrix, pathIsMutable);
813}
814
Hal Canaryd12a6762017-05-26 17:01:16 -0400815void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
816 const SkMatrix& ctm,
817 const SkPath& origPath,
818 const SkPaint& origPaint,
819 const SkMatrix* prePathMatrix) {
820 SkASSERT(origPaint.getMaskFilter());
821 SkPath path(origPath);
822 SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
823 if (prePathMatrix) {
824 path.transform(*prePathMatrix, &path);
825 }
826 SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
827 ? SkStrokeRec::kFill_InitStyle
828 : SkStrokeRec::kHairline_InitStyle;
829 path.transform(ctm, &path);
830
Hal Canarya0622582017-06-29 18:51:35 -0400831 // TODO(halcanary): respect fDocument->rasterDpi().
832 // SkScalar rasterScale = (float)rasterDpi / SkPDFUtils::kDpiForRasterScaleOne;
Hal Canaryd12a6762017-05-26 17:01:16 -0400833 // Would it be easier to just change the device size (and pre-scale the canvas)?
Hal Canary22b2d8c2017-07-19 14:46:12 -0400834 SkIRect bounds = clipStack.bounds(this->bounds()).roundOut();
Hal Canaryd12a6762017-05-26 17:01:16 -0400835 SkMask sourceMask;
836 if (!SkDraw::DrawToMask(path, &bounds, paint->getMaskFilter(), &SkMatrix::I(),
837 &sourceMask, SkMask::kComputeBoundsAndRenderImage_CreateMode,
838 initStyle)) {
839 return;
840 }
841 SkAutoMaskFreeImage srcAutoMaskFreeImage(sourceMask.fImage);
842 SkMask dstMask;
843 SkIPoint margin;
844 if (!paint->getMaskFilter()->filterMask(&dstMask, sourceMask, ctm, &margin)) {
845 return;
846 }
Hal Canary51329c92017-06-27 14:28:37 -0400847 SkIRect dstMaskBounds = dstMask.fBounds;
848 sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
Hal Canaryd12a6762017-05-26 17:01:16 -0400849 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
850 // Must mask with a Form XObject.
Hal Canary51329c92017-06-27 14:28:37 -0400851 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
Hal Canaryd12a6762017-05-26 17:01:16 -0400852 {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400853 SkCanvas canvas(maskDevice.get());
Hal Canary51329c92017-06-27 14:28:37 -0400854 canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
Hal Canaryd12a6762017-05-26 17:01:16 -0400855 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400856 if (!ctm.isIdentity() && paint->getShader()) {
857 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
858 }
859 ScopedContentEntry content(this, clipStack, SkMatrix::I(), *paint);
860 if (!content.entry()) {
861 return;
862 }
Hal Canary51329c92017-06-27 14:28:37 -0400863 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
864 SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
865 SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
866 this->clearMaskOnGraphicState(content.stream());
867}
Hal Canaryd12a6762017-05-26 17:01:16 -0400868
Hal Canary51329c92017-06-27 14:28:37 -0400869void SkPDFDevice::addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,
870 SkDynamicMemoryWStream* contentStream) {
871 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
Hal Canaryb4bd5ef2017-07-26 09:16:01 -0400872 maskDevice->makeFormXObjectFromDevice(true), false,
Hal Canary51329c92017-06-27 14:28:37 -0400873 SkPDFGraphicState::kLuminosity_SMaskMode, this->getCanon());
874 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(sMaskGS.get()), contentStream);
875}
Hal Canaryd12a6762017-05-26 17:01:16 -0400876
Hal Canary51329c92017-06-27 14:28:37 -0400877void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400878 // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
Hal Canaryc02de0b2017-06-28 13:14:03 -0400879 sk_sp<SkPDFDict>& noSMaskGS = this->getCanon()->fNoSmaskGraphicState;
880 if (!noSMaskGS) {
881 noSMaskGS = sk_make_sp<SkPDFDict>("ExtGState");
882 noSMaskGS->insertName("SMask", "None");
883 }
Hal Canary51329c92017-06-27 14:28:37 -0400884 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(noSMaskGS.get()), contentStream);
Hal Canaryd12a6762017-05-26 17:01:16 -0400885}
886
Mike Reeda1361362017-03-07 09:37:29 -0500887void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
888 const SkMatrix& ctm,
889 const SkPath& origPath,
890 const SkPaint& srcPaint,
891 const SkMatrix* prePathMatrix,
892 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700893 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400894 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700895 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800896 SkPath modifiedPath;
897 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000898
Hal Canaryd12a6762017-05-26 17:01:16 -0400899 if (paint.getMaskFilter()) {
900 this->internalDrawPathWithFilter(clipStack, ctm, origPath, paint, prePathMatrix);
901 return;
902 }
903
Mike Reeda1361362017-03-07 09:37:29 -0500904 SkMatrix matrix = ctm;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000905 if (prePathMatrix) {
906 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800907 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000908 pathPtr = &modifiedPath;
909 pathIsMutable = true;
910 }
halcanary682ee012016-01-28 10:59:34 -0800911 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000912 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000913 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000914 }
915 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000916
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000917 if (paint.getPathEffect()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400918 if (clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000919 return;
920 }
halcanary682ee012016-01-28 10:59:34 -0800921 if (!pathIsMutable) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400922 modifiedPath = origPath;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000923 pathPtr = &modifiedPath;
924 pathIsMutable = true;
925 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400926 if (paint.getFillPath(*pathPtr, pathPtr)) {
927 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000928 } else {
Hal Canaryd12a6762017-05-26 17:01:16 -0400929 paint.setStyle(SkPaint::kStroke_Style);
930 paint.setStrokeWidth(0);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000931 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400932 paint.setPathEffect(nullptr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000933 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000934
Hal Canaryd12a6762017-05-26 17:01:16 -0400935 if (this->handleInversePath(*pathPtr, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000936 return;
937 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400938 if (matrix.getType() & SkMatrix::kPerspective_Mask) {
939 if (!pathIsMutable) {
940 modifiedPath = origPath;
941 pathPtr = &modifiedPath;
942 pathIsMutable = true;
943 }
944 pathPtr->transform(matrix);
945 if (paint.getShader()) {
946 transform_shader(&paint, matrix);
947 }
948 matrix = SkMatrix::I();
949 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000950
Mike Reeda1361362017-03-07 09:37:29 -0500951 ScopedContentEntry content(this, clipStack, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000952 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000953 return;
954 }
Hal Canarydfaa0572017-11-27 09:33:44 -0500955 constexpr SkScalar kToleranceScale = 0.0625f; // smaller = better conics (circles).
Hal Canary385468f2017-02-13 11:03:23 -0500956 SkScalar matrixScale = matrix.mapRadius(1.0f);
Hal Canarydfaa0572017-11-27 09:33:44 -0500957 SkScalar tolerance = matrixScale > 0.0f ? kToleranceScale / matrixScale : kToleranceScale;
halcanary8b2bc252015-10-06 09:41:47 -0700958 bool consumeDegeratePathSegments =
959 paint.getStyle() == SkPaint::kFill_Style ||
960 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
961 paint.getStrokeCap() != SkPaint::kSquare_Cap);
Hal Canary51329c92017-06-27 14:28:37 -0400962 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(), consumeDegeratePathSegments, content.stream(),
Hal Canary385468f2017-02-13 11:03:23 -0500963 tolerance);
Hal Canary51329c92017-06-27 14:28:37 -0400964 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000965}
966
Hal Canary7cbf5e32017-07-12 13:10:23 -0400967////////////////////////////////////////////////////////////////////////////////
Hal Canaryf50ff392016-09-30 10:25:39 -0400968
Mike Reeda1361362017-03-07 09:37:29 -0500969void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400970 const SkRect* src,
971 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400972 const SkPaint& paint,
Hal Canaryf50ff392016-09-30 10:25:39 -0400973 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400974 SkASSERT(image);
975 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
976 src, dst, paint, this->ctm());
Hal Canaryf50ff392016-09-30 10:25:39 -0400977}
978
Hal Canary7cbf5e32017-07-12 13:10:23 -0400979void SkPDFDevice::drawBitmapRect(const SkBitmap& bm,
halcanary7a14b312015-10-01 07:28:13 -0700980 const SkRect* src,
981 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400982 const SkPaint& paint,
Mike Reeda1361362017-03-07 09:37:29 -0500983 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400984 SkASSERT(!bm.drawsNothing());
985 this->internalDrawImageRect(SkKeyedImage(bm), src, dst, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700986}
987
Hal Canary7cbf5e32017-07-12 13:10:23 -0400988void SkPDFDevice::drawBitmap(const SkBitmap& bm, SkScalar x, SkScalar y, const SkPaint& paint) {
989 SkASSERT(!bm.drawsNothing());
990 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
991 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700992}
993
Hal Canary7cbf5e32017-07-12 13:10:23 -0400994void SkPDFDevice::drawSprite(const SkBitmap& bm, int x, int y, const SkPaint& paint) {
995 SkASSERT(!bm.drawsNothing());
996 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
997 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, SkMatrix::I());
halcanary7a14b312015-10-01 07:28:13 -0700998}
999
Hal Canary7cbf5e32017-07-12 13:10:23 -04001000void SkPDFDevice::drawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint& paint) {
1001 SkASSERT(image);
1002 auto r = SkRect::MakeXYWH(x, y, image->width(), image->height());
1003 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
1004 nullptr, r, paint, this->ctm());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001005}
1006
Hal Canary7cbf5e32017-07-12 13:10:23 -04001007////////////////////////////////////////////////////////////////////////////////
1008
halcanaryf0c30f52016-07-15 13:35:45 -07001009namespace {
1010class GlyphPositioner {
1011public:
1012 GlyphPositioner(SkDynamicMemoryWStream* content,
1013 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -07001014 bool wideChars,
1015 bool defaultPositioning,
1016 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -07001017 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -07001018 , fCurrentMatrixOrigin(origin)
1019 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -07001020 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -07001021 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -07001022 }
halcanary4871f222016-08-26 13:17:44 -07001023 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -07001024 void flush() {
1025 if (fInText) {
1026 fContent->writeText("> Tj\n");
1027 fInText = false;
1028 }
1029 }
halcanary4871f222016-08-26 13:17:44 -07001030 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -07001031 SkScalar advanceWidth,
1032 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -07001033 if (!fInitialized) {
1034 // Flip the text about the x-axis to account for origin swap and include
1035 // the passed parameters.
1036 fContent->writeText("1 0 ");
1037 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
1038 fContent->writeText(" -1 ");
1039 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
1040 fContent->writeText(" ");
1041 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
1042 fContent->writeText(" Tm\n");
1043 fCurrentMatrixOrigin.set(0.0f, 0.0f);
1044 fInitialized = true;
1045 }
halcanary4ed2f012016-08-15 18:40:07 -07001046 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -07001047 SkPoint position = xy - fCurrentMatrixOrigin;
Hal Canary197ca9b2017-05-15 10:29:44 -04001048 if (position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -07001049 this->flush();
halcanary4871f222016-08-26 13:17:44 -07001050 SkPDFUtils::AppendScalar(position.x(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001051 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -07001052 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001053 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -07001054 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -07001055 fXAdvance = 0;
1056 }
1057 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -07001058 }
1059 if (!fInText) {
1060 fContent->writeText("<");
1061 fInText = true;
1062 }
1063 if (fWideChars) {
1064 SkPDFUtils::WriteUInt16BE(fContent, glyph);
1065 } else {
1066 SkASSERT(0 == glyph >> 8);
1067 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1068 }
halcanaryf0c30f52016-07-15 13:35:45 -07001069 }
1070
1071private:
1072 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -07001073 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001074 SkScalar fXAdvance = 0.0f;
1075 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001076 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001077 bool fInText = false;
1078 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -07001079 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001080};
halcanaryf59d18a2016-09-16 14:44:57 -07001081
1082/** Given the m-to-n glyph-to-character mapping data (as returned by
1083 harfbuzz), iterate over the clusters. */
1084class Clusterator {
1085public:
1086 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1087 explicit Clusterator(uint32_t glyphCount)
1088 : fClusters(nullptr)
1089 , fUtf8Text(nullptr)
1090 , fGlyphCount(glyphCount)
1091 , fTextByteLength(0) {}
1092 // The clusters[] array is an array of offsets into utf8Text[],
1093 // one offset for each glyph. See SkTextBlobBuilder for more info.
1094 Clusterator(const uint32_t* clusters,
1095 const char* utf8Text,
1096 uint32_t glyphCount,
1097 uint32_t textByteLength)
1098 : fClusters(clusters)
1099 , fUtf8Text(utf8Text)
1100 , fGlyphCount(glyphCount)
1101 , fTextByteLength(textByteLength) {
1102 // This is a cheap heuristic for /ReversedChars which seems to
1103 // work for clusters produced by HarfBuzz, which either
1104 // increase from zero (LTR) or decrease to zero (RTL).
1105 // "ReversedChars" is how PDF deals with RTL text.
1106 fReversedChars =
1107 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1108 }
1109 struct Cluster {
1110 const char* fUtf8Text;
1111 uint32_t fTextByteLength;
1112 uint32_t fGlyphIndex;
1113 uint32_t fGlyphCount;
1114 explicit operator bool() const { return fGlyphCount != 0; }
1115 };
1116 // True if this looks like right-to-left text.
1117 bool reversedChars() const { return fReversedChars; }
1118 Cluster next() {
1119 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1120 // These glyphs have no text. Treat as one "cluster".
1121 uint32_t glyphCount = fGlyphCount;
1122 fGlyphCount = 0;
1123 return Cluster{nullptr, 0, 0, glyphCount};
1124 }
1125 if (fGlyphCount == 0 || fTextByteLength == 0) {
1126 return Cluster{nullptr, 0, 0, 0}; // empty
1127 }
1128 SkASSERT(fUtf8Text);
1129 SkASSERT(fClusters);
1130 uint32_t cluster = fClusters[0];
1131 if (cluster >= fTextByteLength) {
1132 return Cluster{nullptr, 0, 0, 0}; // bad input.
1133 }
1134 uint32_t glyphsInCluster = 1;
1135 while (glyphsInCluster < fGlyphCount &&
1136 fClusters[glyphsInCluster] == cluster) {
1137 ++glyphsInCluster;
1138 }
1139 SkASSERT(glyphsInCluster <= fGlyphCount);
1140 uint32_t textLength = 0;
1141 if (glyphsInCluster == fGlyphCount) {
1142 // consumes rest of glyphs and rest of text
1143 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1144 textLength = fTextByteLength - cluster;
1145 } else { // RTL text; last cluster.
1146 SkASSERT(fPreviousCluster < fTextByteLength);
1147 if (fPreviousCluster <= cluster) { // bad input.
1148 return Cluster{nullptr, 0, 0, 0};
1149 }
1150 textLength = fPreviousCluster - cluster;
1151 }
1152 fGlyphCount = 0;
1153 return Cluster{fUtf8Text + cluster,
1154 textLength,
1155 fGlyphIndex,
1156 glyphsInCluster};
1157 }
1158 SkASSERT(glyphsInCluster < fGlyphCount);
1159 uint32_t nextCluster = fClusters[glyphsInCluster];
1160 if (nextCluster >= fTextByteLength) {
1161 return Cluster{nullptr, 0, 0, 0}; // bad input.
1162 }
1163 if (nextCluster > cluster) { // LTR text
1164 if (kInvalidCluster != fPreviousCluster) {
1165 return Cluster{nullptr, 0, 0, 0}; // bad input.
1166 }
1167 textLength = nextCluster - cluster;
1168 } else { // RTL text
1169 SkASSERT(nextCluster < cluster);
1170 if (kInvalidCluster == fPreviousCluster) { // first cluster
1171 textLength = fTextByteLength - cluster;
1172 } else { // later cluster
1173 if (fPreviousCluster <= cluster) {
1174 return Cluster{nullptr, 0, 0, 0}; // bad input.
1175 }
1176 textLength = fPreviousCluster - cluster;
1177 }
1178 fPreviousCluster = cluster;
1179 }
1180 uint32_t glyphIndex = fGlyphIndex;
1181 fGlyphCount -= glyphsInCluster;
1182 fGlyphIndex += glyphsInCluster;
1183 fClusters += glyphsInCluster;
1184 return Cluster{fUtf8Text + cluster,
1185 textLength,
1186 glyphIndex,
1187 glyphsInCluster};
1188 }
1189
1190private:
1191 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1192 const uint32_t* fClusters;
1193 const char* fUtf8Text;
1194 uint32_t fGlyphCount;
1195 uint32_t fTextByteLength;
1196 uint32_t fGlyphIndex = 0;
1197 uint32_t fPreviousCluster = kInvalidCluster;
1198 bool fReversedChars = false;
1199};
1200
1201struct TextStorage {
1202 SkAutoTMalloc<char> fUtf8textStorage;
1203 SkAutoTMalloc<uint32_t> fClusterStorage;
1204 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1205};
halcanaryf0c30f52016-07-15 13:35:45 -07001206} // namespace
1207
halcanaryf59d18a2016-09-16 14:44:57 -07001208/** Given some unicode text (as passed to drawText(), convert to
1209 glyphs (via primitive shaping), while preserving
1210 glyph-to-character mapping information. */
1211static Clusterator make_clusterator(
1212 const void* sourceText,
1213 size_t sourceByteCount,
1214 const SkPaint& paint,
1215 TextStorage* storage,
1216 int glyphCount) {
1217 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1218 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1219 SkASSERT(glyphCount > 0);
1220 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1221 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1222 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1223 uint32_t* clusters = storage->fClusterStorage.get();
1224 uint32_t utf8ByteCount = 0;
1225 const char* utf8Text = nullptr;
1226 switch (paint.getTextEncoding()) {
1227 case SkPaint::kUTF8_TextEncoding: {
1228 const char* txtPtr = (const char*)sourceText;
1229 for (int i = 0; i < glyphCount; ++i) {
1230 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1231 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1232 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1233 }
1234 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1235 utf8ByteCount = SkToU32(sourceByteCount);
1236 utf8Text = (const char*)sourceText;
1237 break;
1238 }
1239 case SkPaint::kUTF16_TextEncoding: {
1240 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1241 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1242 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1243 storage->fUtf8textStorage.reset(utf8ByteCount);
1244 char* txtPtr = storage->fUtf8textStorage.get();
1245 utf8Text = txtPtr;
1246 int clusterIndex = 0;
1247 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1248 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1249 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1250 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1251 }
1252 SkASSERT(clusterIndex == glyphCount);
1253 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1254 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1255 break;
1256 }
1257 case SkPaint::kUTF32_TextEncoding: {
1258 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1259 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1260 SkASSERT(glyphCount == utf32count);
1261 for (int i = 0; i < utf32count; ++i) {
1262 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1263 }
1264 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1265 char* txtPtr = storage->fUtf8textStorage.get();
1266 utf8Text = txtPtr;
1267 for (int i = 0; i < utf32count; ++i) {
1268 clusters[i] = SkToU32(txtPtr - utf8Text);
1269 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1270 }
1271 break;
1272 }
1273 default:
1274 SkDEBUGFAIL("");
1275 break;
1276 }
1277 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1278}
1279
halcanaryf59d18a2016-09-16 14:44:57 -07001280static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1281 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1282}
1283
halcanaryc2f9ec12016-09-12 08:55:29 -07001284static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1285 wStream->writeText("/");
1286 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1287 wStream->write(&prefix, 1);
1288 wStream->writeDecAsText(fontIndex);
1289 wStream->writeText(" ");
1290 SkPDFUtils::AppendScalar(textSize, wStream);
1291 wStream->writeText(" Tf\n");
1292}
1293
Hal Canaryd12a6762017-05-26 17:01:16 -04001294static SkPath draw_text_as_path(const void* sourceText, size_t sourceByteCount,
1295 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
1296 SkPoint offset, const SkPaint& srcPaint) {
1297 SkPath path;
1298 int glyphCount;
1299 SkAutoTMalloc<SkPoint> tmpPoints;
1300 switch (positioning) {
1301 case SkTextBlob::kDefault_Positioning:
1302 srcPaint.getTextPath(sourceText, sourceByteCount, offset.x(), offset.y(), &path);
1303 break;
1304 case SkTextBlob::kHorizontal_Positioning:
1305 glyphCount = srcPaint.countText(sourceText, sourceByteCount);
1306 tmpPoints.realloc(glyphCount);
1307 for (int i = 0; i < glyphCount; ++i) {
1308 tmpPoints[i] = {pos[i] + offset.x(), offset.y()};
1309 }
1310 srcPaint.getPosTextPath(sourceText, sourceByteCount, tmpPoints.get(), &path);
1311 break;
1312 case SkTextBlob::kFull_Positioning:
1313 srcPaint.getPosTextPath(sourceText, sourceByteCount, (const SkPoint*)pos, &path);
1314 path.offset(offset.x(), offset.y());
1315 break;
1316 }
1317 return path;
1318}
1319
Hal Canary9b9510a2017-07-18 09:39:00 -04001320static bool has_outline_glyph(SkGlyphID gid, SkGlyphCache* cache) {
1321 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1322 const SkPath* path = cache->findPath(glyph);
1323 return (path && !path->isEmpty()) || (glyph.fWidth == 0 && glyph.fHeight == 0);
1324}
1325
Hal Canary699b8732017-06-13 12:13:29 -04001326static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkGlyphCache* cache,
1327 SkScalar xScale, SkScalar yScale,
1328 SkPoint xy, const SkMatrix& ctm) {
1329 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1330 SkRect glyphBounds = {glyph.fLeft * xScale,
1331 glyph.fTop * yScale,
1332 (glyph.fLeft + glyph.fWidth) * xScale,
1333 (glyph.fTop + glyph.fHeight) * yScale};
1334 glyphBounds.offset(xy);
1335 ctm.mapRect(&glyphBounds); // now in dev space.
1336 return glyphBounds;
1337}
1338
1339static bool contains(const SkRect& r, SkPoint p) {
1340 return r.left() <= p.x() && p.x() <= r.right() &&
1341 r.top() <= p.y() && p.y() <= r.bottom();
1342}
1343
Hal Canary9b9510a2017-07-18 09:39:00 -04001344static sk_sp<SkImage> image_from_mask(const SkMask& mask) {
1345 if (!mask.fImage) {
1346 return nullptr;
1347 }
1348 SkIRect bounds = mask.fBounds;
1349 SkBitmap bm;
1350 switch (mask.fFormat) {
1351 case SkMask::kBW_Format:
1352 bm.allocPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()));
1353 for (int y = 0; y < bm.height(); ++y) {
1354 for (int x8 = 0; x8 < bm.width(); x8 += 8) {
1355 uint8_t v = *mask.getAddr1(x8 + bounds.x(), y + bounds.y());
1356 int e = SkTMin(x8 + 8, bm.width());
1357 for (int x = x8; x < e; ++x) {
1358 *bm.getAddr8(x, y) = (v >> (x & 0x7)) & 0x1 ? 0xFF : 0x00;
1359 }
1360 }
1361 }
1362 bm.setImmutable();
1363 return SkImage::MakeFromBitmap(bm);
1364 case SkMask::kA8_Format:
1365 bm.installPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()),
1366 mask.fImage, mask.fRowBytes);
1367 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1368 case SkMask::kARGB32_Format:
1369 bm.installPixels(SkImageInfo::MakeN32Premul(bounds.width(), bounds.height()),
1370 mask.fImage, mask.fRowBytes);
1371 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1372 case SkMask::k3D_Format:
1373 SkASSERT(false);
1374 return nullptr;
1375 case SkMask::kLCD16_Format:
1376 SkASSERT(false);
1377 return nullptr;
1378 default:
1379 SkASSERT(false);
1380 return nullptr;
1381 }
1382}
1383
halcanary4ed2f012016-08-15 18:40:07 -07001384void SkPDFDevice::internalDrawText(
Mike Reeda1361362017-03-07 09:37:29 -05001385 const void* sourceText, size_t sourceByteCount,
halcanary4ed2f012016-08-15 18:40:07 -07001386 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001387 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1388 uint32_t textByteLength, const char* utf8Text) {
Hal Canary29ebe7a2017-10-18 10:04:57 -04001389 if (0 == sourceByteCount || !sourceText || srcPaint.getTextSize() <= 0) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001390 return;
1391 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001392 if (this->cs().isEmpty(this->bounds())) {
halcanary4ed2f012016-08-15 18:40:07 -07001393 return;
1394 }
halcanaryea17dfe2016-08-24 09:20:57 -07001395 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1396 if (srcPaint.isVerticalText()) {
1397 // Don't pretend we support drawing vertical text. It is not
1398 // clear to me how to switch to "vertical writing" mode in PDF.
1399 // Currently neither Chromium or Android set this flag.
1400 // https://bug.skia.org/5665
halcanaryea17dfe2016-08-24 09:20:57 -07001401 }
Hal Canaryd12a6762017-05-26 17:01:16 -04001402 if (srcPaint.getPathEffect()
1403 || srcPaint.getMaskFilter()
1404 || SkPaint::kFill_Style != srcPaint.getStyle()) {
1405 // Stroked Text doesn't work well with Type3 fonts.
1406 SkPath path = draw_text_as_path(sourceText, sourceByteCount, pos,
1407 positioning, offset, srcPaint);
1408 this->drawPath(path, srcPaint, nullptr, true);
halcanaryf59d18a2016-09-16 14:44:57 -07001409 return;
halcanarye06ca962016-09-09 05:34:55 -07001410 }
halcanary4ed2f012016-08-15 18:40:07 -07001411 SkPaint paint = calculate_text_paint(srcPaint);
Hal Canaryd12a6762017-05-26 17:01:16 -04001412 remove_color_filter(&paint);
halcanary4ed2f012016-08-15 18:40:07 -07001413 replace_srcmode_on_opaque_paint(&paint);
1414 if (!paint.getTypeface()) {
1415 paint.setTypeface(SkTypeface::MakeDefault());
1416 }
1417 SkTypeface* typeface = paint.getTypeface();
1418 if (!typeface) {
1419 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1420 return;
1421 }
halcanary4871f222016-08-26 13:17:44 -07001422
1423 const SkAdvancedTypefaceMetrics* metrics =
1424 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1425 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001426 return;
1427 }
halcanary2bd295e2016-09-16 08:15:56 -07001428 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1429 if (glyphCount <= 0) {
1430 return;
1431 }
halcanary3b294d52016-09-16 13:21:08 -07001432
halcanaryf59d18a2016-09-16 14:44:57 -07001433 // These three heap buffers are only used in the case where no glyphs
1434 // are passed to drawText() (most clients pass glyphs or a textblob).
1435 TextStorage storage;
1436 const SkGlyphID* glyphs = nullptr;
1437 Clusterator clusterator;
1438 if (textByteLength > 0) {
1439 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1440 glyphs = (const SkGlyphID*)sourceText;
1441 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1442 SkASSERT(clusters);
1443 SkASSERT(utf8Text);
1444 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1445 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1446 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1447 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1448 glyphs = (const SkGlyphID*)sourceText;
1449 clusterator = Clusterator(SkToU32(glyphCount));
1450 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1451 SkASSERT(nullptr == clusters);
1452 SkASSERT(nullptr == utf8Text);
1453 } else {
1454 SkASSERT(nullptr == clusters);
1455 SkASSERT(nullptr == utf8Text);
1456 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1457 &storage, glyphCount);
1458 glyphs = storage.fGlyphStorage;
1459 }
halcanary4ed2f012016-08-15 18:40:07 -07001460 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001461 paint.setHinting(SkPaint::kNo_Hinting);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001462
1463 int emSize;
1464 SkAutoGlyphCache glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
1465
1466 SkScalar textSize = paint.getTextSize();
1467 SkScalar advanceScale = textSize * paint.getTextScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001468
Hal Canary699b8732017-06-13 12:13:29 -04001469 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1470 SkScalar textScaleY = textSize / emSize;
1471 SkScalar textScaleX = advanceScale + paint.getTextSkewX() * textScaleY;
1472
halcanary4ed2f012016-08-15 18:40:07 -07001473 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001474 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1475 SkPaint::kCenter_Align == alignment ? -0.5f :
1476 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001477 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001478 SkScalar advance = 0;
halcanary4ed2f012016-08-15 18:40:07 -07001479 for (int i = 0; i < glyphCount; ++i) {
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001480 advance += advanceScale * glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
halcanary4ed2f012016-08-15 18:40:07 -07001481 }
halcanary4871f222016-08-26 13:17:44 -07001482 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001483 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001484 SkRect clipStackBounds = this->cs().bounds(this->bounds());
Hal Canary9b9510a2017-07-18 09:39:00 -04001485 struct PositionedGlyph {
1486 SkPoint fPos;
1487 SkGlyphID fGlyph;
1488 };
1489 SkTArray<PositionedGlyph> fMissingGlyphs;
1490 {
1491 ScopedContentEntry content(this, paint, true);
1492 if (!content.entry()) {
1493 return;
robertphillips5ba165e2016-08-15 15:36:58 -07001494 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001495 SkDynamicMemoryWStream* out = content.stream();
1496 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
1497
1498 out->writeText("BT\n");
1499 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1500
1501 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
1502
1503 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
1504 if (clusterator.reversedChars()) {
1505 out->writeText("/ReversedChars BMC\n");
1506 }
1507 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1508 GlyphPositioner glyphPositioner(out,
1509 paint.getTextSkewX(),
1510 multiByteGlyphs,
1511 defaultPositioning,
1512 offset);
1513 SkPDFFont* font = nullptr;
1514
1515 while (Clusterator::Cluster c = clusterator.next()) {
1516 int index = c.fGlyphIndex;
1517 int glyphLimit = index + c.fGlyphCount;
1518
1519 bool actualText = false;
1520 SK_AT_SCOPE_EXIT(if (actualText) {
1521 glyphPositioner.flush();
1522 out->writeText("EMC\n");
1523 });
1524 if (c.fUtf8Text) { // real cluster
1525 // Check if `/ActualText` needed.
1526 const char* textPtr = c.fUtf8Text;
1527 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1528 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1529 if (unichar < 0) {
halcanaryf59d18a2016-09-16 14:44:57 -07001530 return;
1531 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001532 if (textPtr < textEnd || // more characters left
1533 glyphLimit > index + 1 || // toUnicode wouldn't work
1534 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1535 {
1536 glyphPositioner.flush();
1537 out->writeText("/Span<</ActualText <");
1538 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1539 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1540 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1541 while (textPtr < textEnd) {
1542 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1543 if (unichar < 0) {
1544 break;
1545 }
1546 SkPDFUtils::WriteUTF16beHex(out, unichar);
1547 }
1548 out->writeText("> >> BDC\n"); // begin marked-content sequence
1549 // with an associated property list.
1550 actualText = true;
halcanaryf59d18a2016-09-16 14:44:57 -07001551 }
halcanaryf59d18a2016-09-16 14:44:57 -07001552 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001553 for (; index < glyphLimit; ++index) {
1554 SkGlyphID gid = glyphs[index];
1555 if (gid > maxGlyphID) {
1556 continue;
halcanaryf59d18a2016-09-16 14:44:57 -07001557 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001558 if (!font || !font->hasGlyph(gid)) {
1559 // Not yet specified font or need to switch font.
1560 int fontIndex = this->getFontResourceIndex(typeface, gid);
1561 // All preconditions for SkPDFFont::GetFontResource are met.
1562 SkASSERT(fontIndex >= 0);
1563 if (fontIndex < 0) {
1564 return;
1565 }
1566 glyphPositioner.flush();
1567 update_font(out, fontIndex, textSize);
1568 font = fFontResources[fontIndex];
1569 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1570 if (!font) {
1571 return;
1572 }
1573 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1574 }
1575 SkPoint xy = {0, 0};
1576 SkScalar advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1577 if (!defaultPositioning) {
1578 xy = SkTextBlob::kFull_Positioning == positioning
1579 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1580 : SkPoint{pos[index], 0};
1581 if (alignment != SkPaint::kLeft_Align) {
1582 xy.offset(alignmentFactor * advance, 0);
1583 }
1584 // Do a glyph-by-glyph bounds-reject if positions are absolute.
1585 SkRect glyphBounds = get_glyph_bounds_device_space(
1586 gid, glyphCache.get(), textScaleX, textScaleY,
1587 xy + offset, this->ctm());
1588 if (glyphBounds.isEmpty()) {
1589 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
1590 continue;
1591 }
1592 } else {
1593 if (!clipStackBounds.intersects(glyphBounds)) {
1594 continue; // reject glyphs as out of bounds
1595 }
1596 }
1597 if (!has_outline_glyph(gid, glyphCache.get())) {
Hal Canary10ccb022017-07-19 10:12:11 -04001598 fMissingGlyphs.push_back({xy + offset, gid});
Hal Canary699b8732017-06-13 12:13:29 -04001599 }
1600 } else {
Hal Canary9b9510a2017-07-18 09:39:00 -04001601 if (!has_outline_glyph(gid, glyphCache.get())) {
1602 fMissingGlyphs.push_back({offset, gid});
Hal Canary699b8732017-06-13 12:13:29 -04001603 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001604 offset += SkPoint{advance, 0};
Hal Canary699b8732017-06-13 12:13:29 -04001605 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001606 font->noteGlyphUsage(gid);
1607
1608 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1609 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
halcanaryf59d18a2016-09-16 14:44:57 -07001610 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001611 }
1612 }
1613 if (fMissingGlyphs.count() > 0) {
1614 // Fall back on images.
1615 SkPaint scaledGlyphCachePaint;
1616 scaledGlyphCachePaint.setTextSize(paint.getTextSize());
1617 scaledGlyphCachePaint.setTextScaleX(paint.getTextScaleX());
1618 scaledGlyphCachePaint.setTextSkewX(paint.getTextSkewX());
1619 scaledGlyphCachePaint.setTypeface(sk_ref_sp(typeface));
1620 SkAutoGlyphCache scaledGlyphCache(scaledGlyphCachePaint, nullptr, nullptr);
1621 SkTHashMap<SkPDFCanon::BitmapGlyphKey, SkPDFCanon::BitmapGlyph>* map =
1622 &this->getCanon()->fBitmapGlyphImages;
1623 for (PositionedGlyph positionedGlyph : fMissingGlyphs) {
1624 SkPDFCanon::BitmapGlyphKey key = {typeface->uniqueID(),
1625 paint.getTextSize(),
1626 paint.getTextScaleX(),
1627 paint.getTextSkewX(),
1628 positionedGlyph.fGlyph,
1629 0};
1630 SkImage* img = nullptr;
1631 SkIPoint imgOffset = {0, 0};
1632 if (SkPDFCanon::BitmapGlyph* ptr = map->find(key)) {
1633 img = ptr->fImage.get();
1634 imgOffset = ptr->fOffset;
1635 } else {
1636 (void)scaledGlyphCache->findImage(
1637 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph));
1638 SkMask mask;
1639 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph).toMask(&mask);
1640 imgOffset = {mask.fBounds.x(), mask.fBounds.y()};
1641 img = map->set(key, {image_from_mask(mask), imgOffset})->fImage.get();
1642 }
1643 if (img) {
1644 SkPoint pt = positionedGlyph.fPos +
1645 SkPoint{(SkScalar)imgOffset.x(), (SkScalar)imgOffset.y()};
1646 this->drawImage(img, pt.x(), pt.y(), srcPaint);
1647 }
halcanaryf59d18a2016-09-16 14:44:57 -07001648 }
robertphillips5ba165e2016-08-15 15:36:58 -07001649 }
halcanary4ed2f012016-08-15 18:40:07 -07001650}
1651
Mike Reeda1361362017-03-07 09:37:29 -05001652void SkPDFDevice::drawText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001653 SkScalar x, SkScalar y, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001654 this->internalDrawText(text, len, nullptr, SkTextBlob::kDefault_Positioning,
halcanarye06ca962016-09-09 05:34:55 -07001655 SkPoint{x, y}, paint, nullptr, 0, nullptr);
halcanary4ed2f012016-08-15 18:40:07 -07001656}
1657
Mike Reeda1361362017-03-07 09:37:29 -05001658void SkPDFDevice::drawPosText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001659 const SkScalar pos[], int scalarsPerPos,
1660 const SkPoint& offset, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001661 this->internalDrawText(text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001662 offset, paint, nullptr, 0, nullptr);
1663}
1664
Mike Reeda1361362017-03-07 09:37:29 -05001665void SkPDFDevice::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
halcanarye06ca962016-09-09 05:34:55 -07001666 const SkPaint &paint, SkDrawFilter* drawFilter) {
1667 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1668 SkPaint runPaint(paint);
1669 it.applyFontToPaint(&runPaint);
1670 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1671 continue;
1672 }
1673 runPaint.setFlags(this->filterTextFlags(runPaint));
1674 SkPoint offset = it.offset() + SkPoint{x, y};
Mike Reeda1361362017-03-07 09:37:29 -05001675 this->internalDrawText(it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
halcanarye06ca962016-09-09 05:34:55 -07001676 it.pos(), it.positioning(), offset, runPaint,
1677 it.clusters(), it.textSize(), it.text());
1678 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001679}
1680
Mike Reed2f6b5a42017-03-19 15:04:17 -04001681void SkPDFDevice::drawVertices(const SkVertices*, SkBlendMode, const SkPaint&) {
Hal Canary22b2d8c2017-07-19 14:46:12 -04001682 if (this->cs().isEmpty(this->bounds())) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001683 return;
1684 }
reed@google.com85e143c2013-12-30 15:51:25 +00001685 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001686}
1687
Mike Reeda1361362017-03-07 09:37:29 -05001688void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001689 SkASSERT(!paint.getImageFilter());
1690
reed7503d602016-07-15 14:23:29 -07001691 // Check if the source device is really a bitmapdevice (because that's what we returned
1692 // from createDevice (likely due to an imagefilter)
1693 SkPixmap pmap;
1694 if (device->peekPixels(&pmap)) {
1695 SkBitmap bitmap;
1696 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001697 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001698 return;
1699 }
1700
fmalita6987dca2014-11-13 08:33:37 -08001701 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001702 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001703
1704 SkScalar scalarX = SkIntToScalar(x);
1705 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001706 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1707 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001708 fLinkToURLs.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001709 }
halcanary91fcb3e2016-03-04 13:53:22 -08001710 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1711 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001712 fLinkToDestinations.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001713 }
halcanary91fcb3e2016-03-04 13:53:22 -08001714 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1715 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001716 fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001717 }
1718
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001719 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001720 return;
1721 }
1722
Mike Reeda1361362017-03-07 09:37:29 -05001723 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
1724 ScopedContentEntry content(this, this->cs(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001725 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001726 return;
1727 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001728 if (content.needShape()) {
1729 SkPath shape;
1730 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001731 SkIntToScalar(device->width()),
1732 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001733 content.setShape(shape);
1734 }
1735 if (!content.needSource()) {
1736 return;
1737 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001738
halcanary4b1e17e2016-07-27 14:49:46 -07001739 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
Hal Canary51329c92017-06-27 14:28:37 -04001740 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001741}
1742
reede8f30622016-03-23 18:59:25 -07001743sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1744 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001745}
1746
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001747
halcanary8103a342016-03-08 15:10:16 -08001748sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001749 SkTDArray<SkPDFObject*> fonts;
1750 fonts.setReserve(fFontResources.count());
1751 for (SkPDFFont* font : fFontResources) {
1752 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001753 }
halcanary8103a342016-03-08 15:10:16 -08001754 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001755 &fGraphicStateResources,
1756 &fShaderResources,
1757 &fXObjectResources,
1758 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001759}
1760
halcanary8103a342016-03-08 15:10:16 -08001761sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001762 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001763 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001764 mediaBox->appendInt(0);
1765 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001766 mediaBox->appendInt(fPageSize.width());
1767 mediaBox->appendInt(fPageSize.height());
1768 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001769}
1770
mtklein5f939ab2016-03-16 10:28:35 -07001771std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001772 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001773 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001774 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001775 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001776
Hal Canary6d673962017-02-22 17:16:59 -05001777 GraphicStackState gsState(fExistingClipStack, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001778 for (const auto& entry : fContentEntries) {
Hal Canary6d673962017-02-22 17:16:59 -05001779 gsState.updateClip(entry.fState.fClipStack,
Hal Canary22b2d8c2017-07-19 14:46:12 -04001780 {0, 0}, SkRect::Make(this->bounds()));
halcanary2be7e012016-03-28 11:58:08 -07001781 gsState.updateMatrix(entry.fState.fMatrix);
1782 gsState.updateDrawingState(entry.fState);
1783
halcanaryafdc1772016-08-23 09:02:12 -07001784 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001785 }
1786 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001787 if (buffer.bytesWritten() > 0) {
1788 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1789 } else {
1790 return skstd::make_unique<SkMemoryStream>();
1791 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001792}
1793
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001794/* Draws an inverse filled path by using Path Ops to compute the positive
1795 * inverse using the current clip as the inverse bounds.
1796 * Return true if this was an inverse path and was properly handled,
1797 * otherwise returns false and the normal drawing routine should continue,
1798 * either as a (incorrect) fallback or because the path was not inverse
1799 * in the first place.
1800 */
Mike Reeda1361362017-03-07 09:37:29 -05001801bool SkPDFDevice::handleInversePath(const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001802 const SkPaint& paint, bool pathIsMutable,
1803 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001804 if (!origPath.isInverseFillType()) {
1805 return false;
1806 }
1807
Hal Canary22b2d8c2017-07-19 14:46:12 -04001808 if (this->cs().isEmpty(this->bounds())) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001809 return false;
1810 }
1811
1812 SkPath modifiedPath;
1813 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1814 SkPaint noInversePaint(paint);
1815
1816 // Merge stroking operations into final path.
1817 if (SkPaint::kStroke_Style == paint.getStyle() ||
1818 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1819 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1820 if (doFillPath) {
1821 noInversePaint.setStyle(SkPaint::kFill_Style);
1822 noInversePaint.setStrokeWidth(0);
1823 pathPtr = &modifiedPath;
1824 } else {
1825 // To be consistent with the raster output, hairline strokes
1826 // are rendered as non-inverted.
1827 modifiedPath.toggleInverseFillType();
Mike Reeda1361362017-03-07 09:37:29 -05001828 this->drawPath(modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001829 return true;
1830 }
1831 }
1832
1833 // Get bounds of clip in current transform space
1834 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001835 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001836 SkMatrix totalMatrix = this->ctm();
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001837 if (prePathMatrix) {
1838 totalMatrix.preConcat(*prePathMatrix);
1839 }
1840 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001841 return false;
1842 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001843 SkRect bounds = this->cs().bounds(this->bounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001844 transformInverse.mapRect(&bounds);
1845
1846 // Extend the bounds by the line width (plus some padding)
1847 // so the edge doesn't cause a visible stroke.
1848 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1849 paint.getStrokeWidth() + SK_Scalar1);
1850
1851 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1852 return false;
1853 }
1854
Mike Reeda1361362017-03-07 09:37:29 -05001855 this->drawPath(modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001856 return true;
1857}
1858
wangxianzhuef6c50a2015-09-17 20:38:02 -07001859void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1860 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001861 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001862 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001863 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001864 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001865 }
halcanary91fcb3e2016-03-04 13:53:22 -08001866 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001867 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001868 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001869 array->appendObject(
1870 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001871 }
1872}
epoger@google.comb58772f2013-03-08 09:09:10 +00001873
halcanary6d622702015-03-25 08:45:42 -07001874void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001875 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001876 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001877 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001878 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001879 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001880 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001881 pdfDest->appendScalar(p.x());
1882 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001883 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001884 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001885 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001886 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001887}
1888
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001889sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
halcanary5abbb442016-07-29 08:41:33 -07001890 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001891 if (!fInitialTransform.isIdentity()) {
1892 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001893 SkDEBUGFAIL("Layer initial transform should be invertible.");
1894 inverseTransform.reset();
1895 }
1896 }
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001897 const char* colorSpace = alpha ? "DeviceGray" : nullptr;
halcanary4b1e17e2016-07-27 14:49:46 -07001898 sk_sp<SkPDFObject> xobject =
1899 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001900 this->makeResourceDict(), inverseTransform, colorSpace);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001901 // We always draw the form xobjects that we create back into the device, so
1902 // we simply preserve the font usage instead of pulling it out and merging
1903 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001904 this->cleanUp(); // Reset this device to have no content.
1905 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001906 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001907}
1908
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001909void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001910 sk_sp<SkPDFObject> mask,
Mike Reeda1361362017-03-07 09:37:29 -05001911 const SkClipStack& clipStack,
reed374772b2016-10-05 17:33:02 -07001912 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001913 bool invertClip) {
Hal Canary22b2d8c2017-07-19 14:46:12 -04001914 if (!invertClip && clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001915 return;
1916 }
1917
halcanary4b1e17e2016-07-27 14:49:46 -07001918 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001919 std::move(mask), invertClip,
1920 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001921
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001922 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001923 paint.setBlendMode(mode);
Mike Reeda1361362017-03-07 09:37:29 -05001924 ScopedContentEntry content(this, clipStack, SkMatrix::I(), paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001925 if (!content.entry()) {
1926 return;
1927 }
Hal Canary51329c92017-06-27 14:28:37 -04001928 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()), content.stream());
1929 SkPDFUtils::DrawFormXObject(xObjectIndex, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001930 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001931}
1932
Mike Reeda1361362017-03-07 09:37:29 -05001933SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack& clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001934 const SkMatrix& matrix,
1935 const SkPaint& paint,
1936 bool hasText,
1937 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001938 *dst = nullptr;
reed374772b2016-10-05 17:33:02 -07001939 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001940
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001941 // For the following modes, we want to handle source and destination
1942 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001943 if (blendMode == SkBlendMode::kClear ||
1944 blendMode == SkBlendMode::kSrc ||
1945 blendMode == SkBlendMode::kSrcIn ||
1946 blendMode == SkBlendMode::kDstIn ||
1947 blendMode == SkBlendMode::kSrcOut ||
1948 blendMode == SkBlendMode::kDstOut ||
1949 blendMode == SkBlendMode::kSrcATop ||
1950 blendMode == SkBlendMode::kDstATop ||
1951 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001952 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001953 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001954 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001955 } else if (blendMode != SkBlendMode::kSrc &&
1956 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001957 // Except for Src and SrcOut, if there isn't anything already there,
1958 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001959 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001960 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001961 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001962 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001963 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001964
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001965 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001966 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001967 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001968 }
1969
halcanary2be7e012016-03-28 11:58:08 -07001970 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001971 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001972 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001973 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001974 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001975 } else {
halcanary2be7e012016-03-28 11:58:08 -07001976 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001977 }
Mike Reeda1361362017-03-07 09:37:29 -05001978 populateGraphicStateEntryFromPaint(matrix, clipStack, paint, hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001979 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001980}
1981
reed374772b2016-10-05 17:33:02 -07001982void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001983 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001984 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001985 if (blendMode != SkBlendMode::kClear &&
1986 blendMode != SkBlendMode::kSrc &&
1987 blendMode != SkBlendMode::kDstOver &&
1988 blendMode != SkBlendMode::kSrcIn &&
1989 blendMode != SkBlendMode::kDstIn &&
1990 blendMode != SkBlendMode::kSrcOut &&
1991 blendMode != SkBlendMode::kDstOut &&
1992 blendMode != SkBlendMode::kSrcATop &&
1993 blendMode != SkBlendMode::kDstATop &&
1994 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001995 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001996 return;
1997 }
reed374772b2016-10-05 17:33:02 -07001998 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001999 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00002000 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002001 // For DstOver, an empty content entry was inserted before the rest
2002 // of the content entries. If nothing was drawn, it needs to be
2003 // removed.
halcanary2be7e012016-03-28 11:58:08 -07002004 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002005 }
2006 return;
2007 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002008 if (!dst) {
reed374772b2016-10-05 17:33:02 -07002009 SkASSERT(blendMode == SkBlendMode::kSrc ||
2010 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002011 return;
2012 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002013
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002014 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07002015 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002016 // Changing the current content into a form-xobject will destroy the clip
2017 // objects which is fine since the xobject will already be clipped. However
2018 // if source has shape, we need to clip it too, so a copy of the clip is
2019 // saved.
halcanary2be7e012016-03-28 11:58:08 -07002020
2021 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002022
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002023 SkPaint stockPaint;
2024
halcanary4b1e17e2016-07-27 14:49:46 -07002025 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002026 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002027 // If nothing was drawn and there's no shape, then the draw was a
2028 // no-op, but dst needs to be restored for that to be true.
2029 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
2030 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
2031 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07002032 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
2033 blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002034 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07002035 // TODO: addXObjectResource take sk_sp
Hal Canary51329c92017-06-27 14:28:37 -04002036 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002037 return;
2038 } else {
reed374772b2016-10-05 17:33:02 -07002039 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002040 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002041 } else {
halcanary2be7e012016-03-28 11:58:08 -07002042 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07002043 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002044 }
2045
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002046 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
2047 // without alpha.
reed374772b2016-10-05 17:33:02 -07002048 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002049 // TODO(vandebo): In order to properly support SrcATop we have to track
2050 // the shape of what's been drawn at all times. It's the intersection of
2051 // the non-transparent parts of the device and the outlines (shape) of
2052 // all images and devices drawn.
2053 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
Mike Reeda1361362017-03-07 09:37:29 -05002054 fExistingClipStack, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002055 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07002056 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002057 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002058 SkPaint filledPaint;
2059 filledPaint.setColor(SK_ColorBLACK);
2060 filledPaint.setStyle(SkPaint::kFill_Style);
Mike Reeda1361362017-03-07 09:37:29 -05002061 this->internalDrawPath(clipStack, SkMatrix::I(), *shape, filledPaint, nullptr, true);
2062 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
2063 this->makeFormXObjectFromDevice(),
2064 fExistingClipStack,
2065 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07002066 } else {
Mike Reeda1361362017-03-07 09:37:29 -05002067 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
2068 srcFormXObject,
2069 fExistingClipStack,
2070 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002071 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002072 }
2073
reed374772b2016-10-05 17:33:02 -07002074 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002075 return;
reed374772b2016-10-05 17:33:02 -07002076 } else if (blendMode == SkBlendMode::kSrc ||
2077 blendMode == SkBlendMode::kDstATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002078 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002079 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04002080 SkPDFUtils::DrawFormXObject(this->addXObjectResource(srcFormXObject.get()),
2081 content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002082 }
reed374772b2016-10-05 17:33:02 -07002083 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002084 return;
2085 }
reed374772b2016-10-05 17:33:02 -07002086 } else if (blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002087 ScopedContentEntry content(this, fExistingClipStack,
2088 SkMatrix::I(), stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002089 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04002090 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002091 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002092 }
2093
reed374772b2016-10-05 17:33:02 -07002094 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
2095 blendMode == SkBlendMode::kDstIn ||
2096 blendMode == SkBlendMode::kSrcOut ||
2097 blendMode == SkBlendMode::kDstOut ||
2098 blendMode == SkBlendMode::kSrcATop ||
2099 blendMode == SkBlendMode::kDstATop ||
2100 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002101
reed374772b2016-10-05 17:33:02 -07002102 if (blendMode == SkBlendMode::kSrcIn ||
2103 blendMode == SkBlendMode::kSrcOut ||
2104 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07002105 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
2106 std::move(dst),
Mike Reeda1361362017-03-07 09:37:29 -05002107 fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07002108 SkBlendMode::kSrcOver,
2109 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07002110 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002111 } else {
reed374772b2016-10-05 17:33:02 -07002112 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07002113 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07002114 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002115 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
Mike Reeda1361362017-03-07 09:37:29 -05002116 std::move(dst), fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07002117 SkBlendMode::kSrcOver, false);
2118 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002119 }
halcanarydabd4f02016-08-03 11:16:56 -07002120 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
Mike Reeda1361362017-03-07 09:37:29 -05002121 fExistingClipStack, mode,
reed374772b2016-10-05 17:33:02 -07002122 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07002123 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002124 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002125}
2126
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002127bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00002128 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07002129 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002130 return true;
2131 }
2132 return false;
2133}
2134
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002135void SkPDFDevice::populateGraphicStateEntryFromPaint(
2136 const SkMatrix& matrix,
2137 const SkClipStack& clipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002138 const SkPaint& paint,
2139 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07002140 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07002141 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
2142 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
2143 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002144
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002145 entry->fMatrix = matrix;
2146 entry->fClipStack = clipStack;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002147 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2148 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002149
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002150 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08002151 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07002152 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002153 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002154 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05002155 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
2156 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002157 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05002158 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002159 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07002160 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002161 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05002162 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
2163 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2164 color = gradientColor;
2165 } else {
2166 // PDF positions patterns relative to the initial transform, so
2167 // we need to apply the current transform to the shader parameters.
2168 SkMatrix transform = matrix;
2169 transform.postConcat(fInitialTransform);
2170
2171 // PDF doesn't support kClamp_TileMode, so we simulate it by making
2172 // a pattern the size of the current clip.
Hal Canary22b2d8c2017-07-19 14:46:12 -04002173 SkRect clipStackBounds = clipStack.bounds(this->bounds());
Hal Canaryc8f91802017-02-12 20:29:12 -05002174
2175 // We need to apply the initial transform to bounds in order to get
2176 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05002177 fInitialTransform.mapRect(&clipStackBounds);
2178 SkIRect bounds;
2179 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05002180
Hal Canary7e872ca2017-07-19 15:51:18 -04002181 pdfShader = SkPDFMakeShader(fDocument, shader, transform, bounds, paint.getColor());
Hal Canaryc8f91802017-02-12 20:29:12 -05002182
2183 if (pdfShader.get()) {
2184 // pdfShader has been canonicalized so we can directly compare
2185 // pointers.
2186 int resourceIndex = fShaderResources.find(pdfShader.get());
2187 if (resourceIndex < 0) {
2188 resourceIndex = fShaderResources.count();
2189 fShaderResources.push(pdfShader.get());
2190 pdfShader.get()->ref();
2191 }
2192 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002193 }
2194 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002195 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002196
Hal Canary80fa7ce2017-06-28 16:04:20 -04002197 sk_sp<SkPDFDict> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002198 if (color == paint.getColor()) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002199 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002200 } else {
2201 SkPaint newPaint = paint;
2202 newPaint.setColor(color);
Hal Canary5c1b3602017-04-17 16:30:06 -04002203 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002204 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002205 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002206 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002207
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002208 if (hasText) {
2209 entry->fTextScaleX = paint.getTextScaleX();
2210 entry->fTextFill = paint.getStyle();
2211 } else {
2212 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002213 }
2214}
2215
halcanarybe27a112015-04-01 13:31:19 -07002216int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002217 // Assumes that gs has been canonicalized (so we can directly compare
2218 // pointers).
2219 int result = fGraphicStateResources.find(gs);
2220 if (result < 0) {
2221 result = fGraphicStateResources.count();
2222 fGraphicStateResources.push(gs);
2223 gs->ref();
2224 }
2225 return result;
2226}
2227
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002228int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002229 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002230 // Assumes that xobject has been canonicalized (so we can directly compare
2231 // pointers).
2232 int result = fXObjectResources.find(xObject);
2233 if (result < 0) {
2234 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002235 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002236 }
2237 return result;
2238}
2239
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002240int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002241 sk_sp<SkPDFFont> newFont = SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID);
halcanary7e8d5d32016-08-12 07:59:38 -07002242 if (!newFont) {
2243 return -1;
2244 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002245 int resourceIndex = fFontResources.find(newFont.get());
2246 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002247 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002248 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002249 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002250 }
2251 return resourceIndex;
2252}
2253
Hal Canaryfafe1352017-04-11 12:12:02 -04002254static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07002255
Hal Canary7cbf5e32017-07-12 13:10:23 -04002256static sk_sp<SkImage> color_filter(const SkImage* image,
halcanarya50151d2016-03-25 11:57:49 -07002257 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002258 auto surface =
Hal Canary7cbf5e32017-07-12 13:10:23 -04002259 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07002260 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002261 SkCanvas* canvas = surface->getCanvas();
2262 canvas->clear(SK_ColorTRANSPARENT);
2263 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002264 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canary7cbf5e32017-07-12 13:10:23 -04002265 canvas->drawImage(image, 0, 0, &paint);
halcanarya50151d2016-03-25 11:57:49 -07002266 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002267}
2268
2269////////////////////////////////////////////////////////////////////////////////
Hal Canary7cbf5e32017-07-12 13:10:23 -04002270
2271static bool is_integer(SkScalar x) {
2272 return x == SkScalarTruncToScalar(x);
2273}
2274
2275static bool is_integral(const SkRect& r) {
2276 return is_integer(r.left()) &&
2277 is_integer(r.top()) &&
2278 is_integer(r.right()) &&
2279 is_integer(r.bottom());
2280}
2281
2282void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
2283 const SkRect* src,
2284 const SkRect& dst,
2285 const SkPaint& srcPaint,
2286 const SkMatrix& ctm) {
2287 if (!imageSubset) {
halcanarya50151d2016-03-25 11:57:49 -07002288 return;
2289 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002290
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002291 // First, figure out the src->dst transform and subset the image if needed.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002292 SkIRect bounds = imageSubset.image()->bounds();
Hal Canary7cbf5e32017-07-12 13:10:23 -04002293 SkRect srcRect = src ? *src : SkRect::Make(bounds);
2294 SkMatrix transform;
2295 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
2296 if (src && *src != SkRect::Make(bounds)) {
2297 if (!srcRect.intersect(SkRect::Make(bounds))) {
2298 return;
2299 }
2300 srcRect.roundOut(&bounds);
2301 transform.preTranslate(SkIntToScalar(bounds.x()),
2302 SkIntToScalar(bounds.y()));
2303 if (bounds != imageSubset.image()->bounds()) {
2304 imageSubset = imageSubset.subset(bounds);
2305 }
2306 if (!imageSubset) {
2307 return;
2308 }
2309 }
2310
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002311 // If the image is opaque and the paint's alpha is too, replace
2312 // kSrc blendmode with kSrcOver.
2313 SkPaint paint = srcPaint;
2314 if (imageSubset.image()->isOpaque()) {
2315 replace_srcmode_on_opaque_paint(&paint);
Hal Canaryd425a1d2017-07-12 13:13:51 -04002316 }
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002317
2318 // Alpha-only images need to get their color from the shader, before
2319 // applying the colorfilter.
2320 if (imageSubset.image()->isAlphaOnly() && paint.getColorFilter()) {
2321 // must blend alpha image and shader before applying colorfilter.
2322 auto surface =
2323 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
2324 SkCanvas* canvas = surface->getCanvas();
2325 SkPaint tmpPaint;
2326 // In the case of alpha images with shaders, the shader's coordinate
2327 // system is the image's coordiantes.
2328 tmpPaint.setShader(sk_ref_sp(paint.getShader()));
2329 tmpPaint.setColor(paint.getColor());
2330 canvas->clear(0x00000000);
2331 canvas->drawImage(imageSubset.image().get(), 0, 0, &tmpPaint);
2332 paint.setShader(nullptr);
2333 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2334 SkASSERT(!imageSubset.image()->isAlphaOnly());
2335 }
2336
2337 if (imageSubset.image()->isAlphaOnly()) {
2338 // The ColorFilter applies to the paint color/shader, not the alpha layer.
2339 SkASSERT(nullptr == paint.getColorFilter());
2340
Hal Canaryd425a1d2017-07-12 13:13:51 -04002341 sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
2342 if (!mask) {
2343 return;
2344 }
2345 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
2346 // Must mask with a Form XObject.
2347 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
2348 {
2349 SkCanvas canvas(maskDevice.get());
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002350 if (paint.getMaskFilter()) {
2351 // This clip prevents the mask image shader from covering
2352 // entire device if unnecessary.
2353 canvas.clipRect(this->cs().bounds(this->bounds()));
2354 canvas.concat(ctm);
2355 SkPaint tmpPaint;
2356 tmpPaint.setShader(mask->makeShader(&transform));
2357 tmpPaint.setMaskFilter(sk_ref_sp(paint.getMaskFilter()));
2358 canvas.drawRect(dst, tmpPaint);
2359 } else {
2360 canvas.concat(ctm);
2361 if (src && !is_integral(*src)) {
2362 canvas.clipRect(dst);
2363 }
2364 canvas.concat(transform);
2365 canvas.drawImage(mask, 0, 0);
2366 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04002367 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04002368 if (!ctm.isIdentity() && paint.getShader()) {
2369 transform_shader(&paint, ctm); // Since we are using identity matrix.
2370 }
2371 ScopedContentEntry content(this, this->cs(), SkMatrix::I(), paint);
2372 if (!content.entry()) {
2373 return;
2374 }
2375 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
2376 SkPDFUtils::AppendRectangle(SkRect::Make(fPageSize), content.stream());
2377 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kWinding_FillType, content.stream());
2378 this->clearMaskOnGraphicState(content.stream());
2379 return;
2380 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002381 if (paint.getMaskFilter()) {
2382 paint.setShader(imageSubset.image()->makeShader(&transform));
2383 SkPath path;
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002384 path.addRect(dst); // handles non-integral clipping.
2385 this->internalDrawPath(this->cs(), this->ctm(), path, paint, nullptr, true);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002386 return;
2387 }
2388 transform.postConcat(ctm);
2389
2390 bool needToRestore = false;
2391 if (src && !is_integral(*src)) {
2392 // Need sub-pixel clipping to fix https://bug.skia.org/4374
2393 this->cs().save();
2394 this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
2395 needToRestore = true;
2396 }
2397 SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
2398
halcanary7a14b312015-10-01 07:28:13 -07002399 #ifdef SK_PDF_IMAGE_STATS
2400 gDrawImageCalls.fetch_add(1);
2401 #endif
Hal Canary7cbf5e32017-07-12 13:10:23 -04002402 SkMatrix matrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002403
2404 // Rasterize the bitmap using perspective in a new bitmap.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002405 if (transform.hasPerspective()) {
Hal Canarya0622582017-06-29 18:51:35 -04002406 SkASSERT(fDocument->rasterDpi() > 0);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002407 // Transform the bitmap in the new space, without taking into
2408 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002409 SkPath perspectiveOutline;
Hal Canary7cbf5e32017-07-12 13:10:23 -04002410 SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
halcanary7a14b312015-10-01 07:28:13 -07002411 perspectiveOutline.addRect(imageBounds);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002412 perspectiveOutline.transform(transform);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002413
2414 // TODO(edisonn): perf - use current clip too.
2415 // Retrieve the bounds of the new shape.
2416 SkRect bounds = perspectiveOutline.getBounds();
2417
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002418 // Transform the bitmap in the new space, taking into
2419 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002420 SkMatrix total = transform;
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002421 total.postConcat(fInitialTransform);
Hal Canarya0622582017-06-29 18:51:35 -04002422 SkScalar dpiScale = SkIntToScalar(fDocument->rasterDpi()) /
2423 SkIntToScalar(SkPDFUtils::kDpiForRasterScaleOne);
halcanary7a14b312015-10-01 07:28:13 -07002424 total.postScale(dpiScale, dpiScale);
2425
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002426 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002427 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002428 physicalPerspectiveOutline.transform(total);
2429
halcanary7a14b312015-10-01 07:28:13 -07002430 SkRect physicalPerspectiveBounds =
2431 physicalPerspectiveOutline.getBounds();
2432 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2433 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002434
2435 // TODO(edisonn): A better approach would be to use a bitmap shader
2436 // (in clamp mode) and draw a rect over the entire bounding box. Then
2437 // intersect perspectiveOutline to the clip. That will avoid introducing
2438 // alpha to the image while still giving good behavior at the edge of
2439 // the image. Avoiding alpha will reduce the pdf size and generation
2440 // CPU time some.
2441
halcanary7a14b312015-10-01 07:28:13 -07002442 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2443
Hal Canaryf50ff392016-09-30 10:25:39 -04002444 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002445 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002446 return;
2447 }
halcanary7a14b312015-10-01 07:28:13 -07002448 SkCanvas* canvas = surface->getCanvas();
2449 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002450
2451 SkScalar deltaX = bounds.left();
2452 SkScalar deltaY = bounds.top();
2453
Hal Canary7cbf5e32017-07-12 13:10:23 -04002454 SkMatrix offsetMatrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002455 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002456 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002457
2458 // Translate the draw in the new canvas, so we perfectly fit the
2459 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002460 canvas->setMatrix(offsetMatrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002461 canvas->drawImage(imageSubset.image(), 0, 0);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002462 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002463 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002464
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002465 // In the new space, we use the identity matrix translated
2466 // and scaled to reflect DPI.
2467 matrix.setScale(1 / scaleX, 1 / scaleY);
2468 matrix.postTranslate(deltaX, deltaY);
2469
Hal Canary7cbf5e32017-07-12 13:10:23 -04002470 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2471 if (!imageSubset) {
2472 return;
2473 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002474 }
2475
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002476 SkMatrix scaled;
2477 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002478 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2479 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002480 // Scale the image up from 1x1 to WxH.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002481 SkIRect subset = imageSubset.image()->bounds();
2482 scaled.postScale(SkIntToScalar(subset.width()),
2483 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002484 scaled.postConcat(matrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002485 ScopedContentEntry content(this, this->cs(), scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002486 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002487 return;
2488 }
2489 if (content.needShape()) {
2490 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002491 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002492 shape.transform(matrix);
2493 content.setShape(shape);
2494 }
2495 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002496 return;
2497 }
2498
halcanary287d22d2015-09-24 10:20:05 -07002499 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002500 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2501 imageSubset = SkKeyedImage(std::move(img));
2502 if (!imageSubset) {
2503 return;
2504 }
halcanary7a14b312015-10-01 07:28:13 -07002505 // TODO(halcanary): de-dupe this by caching filtered images.
2506 // (maybe in the resource cache?)
2507 }
halcanarya50151d2016-03-25 11:57:49 -07002508
Hal Canary7cbf5e32017-07-12 13:10:23 -04002509 SkBitmapKey key = imageSubset.key();
Hal Canary5c1b3602017-04-17 16:30:06 -04002510 sk_sp<SkPDFObject>* pdfimagePtr = fDocument->canon()->fPDFBitmapMap.find(key);
2511 sk_sp<SkPDFObject> pdfimage = pdfimagePtr ? *pdfimagePtr : nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002512 if (!pdfimage) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002513 SkASSERT(imageSubset);
2514 pdfimage = SkPDFCreateBitmapObject(imageSubset.release(),
2515 fDocument->canon()->fPixelSerializer.get());
halcanary7a14b312015-10-01 07:28:13 -07002516 if (!pdfimage) {
2517 return;
halcanary287d22d2015-09-24 10:20:05 -07002518 }
halcanarya50151d2016-03-25 11:57:49 -07002519 fDocument->serialize(pdfimage); // serialize images early.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002520 SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
Hal Canary5c1b3602017-04-17 16:30:06 -04002521 fDocument->canon()->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002522 }
halcanarya50151d2016-03-25 11:57:49 -07002523 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
Hal Canary51329c92017-06-27 14:28:37 -04002524 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002525}
reede51c3562016-07-19 14:33:20 -07002526
2527///////////////////////////////////////////////////////////////////////////////////////////////////
2528
2529#include "SkSpecialImage.h"
2530#include "SkImageFilter.h"
2531
Florin Malita53f77bd2017-04-28 13:48:37 -04002532void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2533 SkImage* clipImage, const SkMatrix& clipMatrix) {
reede51c3562016-07-19 14:33:20 -07002534 SkASSERT(!srcImg->isTextureBacked());
2535
Florin Malita53f77bd2017-04-28 13:48:37 -04002536 //TODO: clipImage support
2537
reede51c3562016-07-19 14:33:20 -07002538 SkBitmap resultBM;
2539
2540 SkImageFilter* filter = paint.getImageFilter();
2541 if (filter) {
2542 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002543 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002544 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002545 const SkIRect clipBounds =
Hal Canary22b2d8c2017-07-19 14:46:12 -04002546 this->cs().bounds(this->bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002547 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
brianosman2a75e5d2016-09-22 07:15:37 -07002548 // TODO: Should PDF be operating in a specified color space? For now, run the filter
2549 // in the same color space as the source (this is different from all other backends).
2550 SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2551 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002552
2553 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2554 if (resultImg) {
2555 SkPaint tmpUnfiltered(paint);
2556 tmpUnfiltered.setImageFilter(nullptr);
2557 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002558 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002559 }
2560 }
2561 } else {
2562 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002563 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002564 }
2565 }
2566}
2567
2568sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2569 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2570}
2571
2572sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002573 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2574 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2575 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002576 SkColorSpace* legacyColorSpace = nullptr;
Hal Canary22b2d8c2017-07-19 14:46:12 -04002577 return SkSpecialImage::MakeFromImage(image->bounds(),
Brian Osman61624f02016-12-09 14:51:59 -05002578 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002579}
2580
2581sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002582 return nullptr;
2583}
brianosman04a44d02016-09-21 09:46:57 -07002584
2585SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2586 // We always return a transient cache, so it is freed after each
2587 // filter traversal.
2588 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2589}