blob: 9cd2892a0564d0c912b4bbb62239292fe5f9ad23 [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"
Hal Canary1521c8a2018-03-28 09:51:00 -070016#include "SkClusterator.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000017#include "SkColor.h"
halcanary287d22d2015-09-24 10:20:05 -070018#include "SkColorFilter.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000019#include "SkDraw.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkGlyphCache.h"
Herb Derby736db102018-07-19 12:52:16 -040021#include "SkGlyphRun.h"
brianosman04a44d02016-09-21 09:46:57 -070022#include "SkImageFilterCache.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040023#include "SkJpegEncoder.h"
halcanary022c2bd2016-09-02 11:29:46 -070024#include "SkMakeUnique.h"
Mike Reed80747ef2018-01-23 15:29:32 -050025#include "SkMaskFilterBase.h"
halcanarydb0dcc72015-03-20 12:31:52 -070026#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070027#include "SkPDFCanon.h"
halcanary989da4a2016-03-21 14:33:17 -070028#include "SkPDFDocument.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000029#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000030#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000031#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000032#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000033#include "SkPDFShader.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000034#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000035#include "SkPDFUtils.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040036#include "SkPath.h"
37#include "SkPathEffect.h"
38#include "SkPathOps.h"
Hal Canaryf50ff392016-09-30 10:25:39 -040039#include "SkPixelRef.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000040#include "SkRRect.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040041#include "SkRasterClip.h"
halcanary4871f222016-08-26 13:17:44 -070042#include "SkScopeExit.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000043#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070044#include "SkSurface.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000045#include "SkTemplates.h"
Florin Malitaab54e732018-07-27 09:47:15 -040046#include "SkTextBlob.h"
halcanarye06ca962016-09-09 05:34:55 -070047#include "SkTextFormatParams.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040048#include "SkTo.h"
halcanaryf59d18a2016-09-16 14:44:57 -070049#include "SkUtils.h"
halcanarya6814332015-05-27 08:53:36 -070050#include "SkXfermodeInterpretation.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040051
52#ifndef SK_PDF_MASK_QUALITY
53 // If MASK_QUALITY is in [0,100], will be used for JpegEncoder.
54 // Otherwise, just encode masks losslessly.
55 #define SK_PDF_MASK_QUALITY 50
56 // Since these masks are used for blurry shadows, we shouldn't need
57 // high quality. Raise this value if your shadows have visible JPEG
58 // artifacts.
59 // If SkJpegEncoder::Encode fails, we will fall back to the lossless
60 // encoding.
61#endif
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000062
63// Utility functions
64
Hal Canary51329c92017-06-27 14:28:37 -040065// This function destroys the mask and either frees or takes the pixels.
66sk_sp<SkImage> mask_to_greyscale_image(SkMask* mask) {
67 sk_sp<SkImage> img;
68 SkPixmap pm(SkImageInfo::Make(mask->fBounds.width(), mask->fBounds.height(),
69 kGray_8_SkColorType, kOpaque_SkAlphaType),
70 mask->fImage, mask->fRowBytes);
71 const int imgQuality = SK_PDF_MASK_QUALITY;
72 if (imgQuality <= 100 && imgQuality >= 0) {
73 SkDynamicMemoryWStream buffer;
74 SkJpegEncoder::Options jpegOptions;
75 jpegOptions.fQuality = imgQuality;
76 if (SkJpegEncoder::Encode(&buffer, pm, jpegOptions)) {
77 img = SkImage::MakeFromEncoded(buffer.detachAsData());
78 SkASSERT(img);
79 if (img) {
80 SkMask::FreeImage(mask->fImage);
81 }
82 }
83 }
84 if (!img) {
85 img = SkImage::MakeFromRaster(pm, [](const void* p, void*) { SkMask::FreeImage((void*)p); },
86 nullptr);
87 }
88 *mask = SkMask(); // destructive;
89 return img;
90}
91
Hal Canaryd425a1d2017-07-12 13:13:51 -040092sk_sp<SkImage> alpha_image_to_greyscale_image(const SkImage* mask) {
93 int w = mask->width(), h = mask->height();
94 SkBitmap greyBitmap;
95 greyBitmap.allocPixels(SkImageInfo::Make(w, h, kGray_8_SkColorType, kOpaque_SkAlphaType));
96 if (!mask->readPixels(SkImageInfo::MakeA8(w, h),
97 greyBitmap.getPixels(), greyBitmap.rowBytes(), 0, 0)) {
98 return nullptr;
99 }
100 return SkImage::MakeFromBitmap(greyBitmap);
101}
102
Mike Reeda1361362017-03-07 09:37:29 -0500103static void draw_points(SkCanvas::PointMode mode,
104 size_t count,
105 const SkPoint* points,
106 const SkPaint& paint,
107 const SkIRect& bounds,
108 const SkMatrix& ctm,
109 SkBaseDevice* device) {
110 SkRasterClip rc(bounds);
111 SkDraw draw;
112 draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(bounds.right(), bounds.bottom()), nullptr, 0);
113 draw.fMatrix = &ctm;
114 draw.fRC = &rc;
115 draw.drawPoints(mode, count, points, paint, device);
116}
117
reed374772b2016-10-05 17:33:02 -0700118// If the paint will definitely draw opaquely, replace kSrc with
119// kSrcOver. http://crbug.com/473572
halcanarya6814332015-05-27 08:53:36 -0700120static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
reed374772b2016-10-05 17:33:02 -0700121 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
122 paint->setBlendMode(SkBlendMode::kSrcOver);
halcanarya6814332015-05-27 08:53:36 -0700123 }
124}
125
Hal Canaryd12a6762017-05-26 17:01:16 -0400126// A shader's matrix is: CTMM x LocalMatrix x WrappingLocalMatrix. We want to
127// switch to device space, where CTM = I, while keeping the original behavior.
128//
129// I * LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
130// LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
131// InvLocalMatrix * LocalMatrix * NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
132// NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
133//
134static void transform_shader(SkPaint* paint, const SkMatrix& ctm) {
135 SkMatrix lm = SkPDFUtils::GetShaderLocalMatrix(paint->getShader());
136 SkMatrix lmInv;
137 if (lm.invert(&lmInv)) {
138 SkMatrix m = SkMatrix::Concat(SkMatrix::Concat(lmInv, ctm), lm);
139 paint->setShader(paint->getShader()->makeWithLocalMatrix(m));
140 }
141}
142
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000143static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000144 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -0700145 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000146 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700147 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000148 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700149 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000150 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000151}
152
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000153static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000154 SkPaint result = paint;
155 if (result.isFakeBoldText()) {
156 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
157 kStdFakeBoldInterpKeys,
158 kStdFakeBoldInterpValues,
159 kStdFakeBoldInterpLength);
Mike Reed8be952a2017-02-13 20:44:33 -0500160 SkScalar width = result.getTextSize() * fakeBoldScale;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000161 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000162 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000163 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000164 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000165 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000166 result.setStrokeWidth(width);
167 }
168 return result;
169}
170
Hal Canaryf50ff392016-09-30 10:25:39 -0400171
Hal Canaryd12a6762017-05-26 17:01:16 -0400172// If the paint has a color filter, apply the color filter to the shader or the
173// paint color. Remove the color filter.
174void remove_color_filter(SkPaint* paint) {
175 if (SkColorFilter* cf = paint->getColorFilter()) {
176 if (SkShader* shader = paint->getShader()) {
177 paint->setShader(shader->makeWithColorFilter(paint->refColorFilter()));
178 } else {
179 paint->setColor(cf->filterColor(paint->getColor()));
180 }
181 paint->setColorFilter(nullptr);
182 }
183}
184
halcanary2be7e012016-03-28 11:58:08 -0700185SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
186 : fColor(SK_ColorBLACK)
187 , fTextScaleX(SK_Scalar1)
188 , fTextFill(SkPaint::kFill_Style)
189 , fShaderIndex(-1)
halcanaryc2f9ec12016-09-12 08:55:29 -0700190 , fGraphicStateIndex(-1) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000191 fMatrix.reset();
192}
193
halcanary2be7e012016-03-28 11:58:08 -0700194bool SkPDFDevice::GraphicStateEntry::compareInitialState(
195 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000196 return fColor == cur.fColor &&
197 fShaderIndex == cur.fShaderIndex &&
198 fGraphicStateIndex == cur.fGraphicStateIndex &&
199 fMatrix == cur.fMatrix &&
200 fClipStack == cur.fClipStack &&
201 (fTextScaleX == 0 ||
202 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000203}
204
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000205class GraphicStackState {
206public:
207 GraphicStackState(const SkClipStack& existingClipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000208 SkWStream* contentStream)
209 : fStackDepth(0),
210 fContentStream(contentStream) {
211 fEntries[0].fClipStack = existingClipStack;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000212 }
213
Hal Canary4e83ff12018-03-09 12:16:42 -0500214 void updateClip(const SkClipStack& clipStack, const SkIRect& bounds);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000215 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700216 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000217
218 void drainStack();
219
220private:
221 void push();
222 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700223 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000224
225 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
226 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700227 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000228 int fStackDepth;
229 SkWStream* fContentStream;
230};
231
232void GraphicStackState::drainStack() {
233 while (fStackDepth) {
234 pop();
235 }
236}
237
238void GraphicStackState::push() {
239 SkASSERT(fStackDepth < kMaxStackDepth);
240 fContentStream->writeText("q\n");
241 fStackDepth++;
242 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
243}
244
245void GraphicStackState::pop() {
246 SkASSERT(fStackDepth > 0);
247 fContentStream->writeText("Q\n");
248 fStackDepth--;
249}
250
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000251/* Calculate an inverted path's equivalent non-inverted path, given the
252 * canvas bounds.
253 * outPath may alias with invPath (since this is supported by PathOps).
254 */
255static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
256 SkPath* outPath) {
257 SkASSERT(invPath.isInverseFillType());
258
259 SkPath clipPath;
260 clipPath.addRect(bounds);
261
reedcdb42bb2015-06-26 10:23:07 -0700262 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000263}
264
Hal Canary44a97d52017-02-22 10:45:25 -0500265bool apply_clip(SkClipOp op, const SkPath& u, const SkPath& v, SkPath* r) {
266 switch (op) {
267 case SkClipOp::kDifference:
268 return Op(u, v, kDifference_SkPathOp, r);
269 case SkClipOp::kIntersect:
270 return Op(u, v, kIntersect_SkPathOp, r);
Mike Reed14113bc2017-05-10 14:13:20 -0400271#ifdef SK_SUPPORT_DEPRECATED_CLIPOPS
Hal Canary44a97d52017-02-22 10:45:25 -0500272 case SkClipOp::kUnion_deprecated:
273 return Op(u, v, kUnion_SkPathOp, r);
274 case SkClipOp::kXOR_deprecated:
275 return Op(u, v, kXOR_SkPathOp, r);
276 case SkClipOp::kReverseDifference_deprecated:
277 return Op(u, v, kReverseDifference_SkPathOp, r);
278 case SkClipOp::kReplace_deprecated:
279 *r = v;
280 return true;
Mike Reed14113bc2017-05-10 14:13:20 -0400281#endif
Hal Canary44a97d52017-02-22 10:45:25 -0500282 default:
283 return false;
284 }
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000285}
286
Hal Canaryd00ef062018-06-05 11:53:58 -0400287static SkRect rect_intersect(SkRect u, SkRect v) {
288 if (u.isEmpty() || v.isEmpty()) { return {0, 0, 0, 0}; }
289 return u.intersect(v) ? u : SkRect{0, 0, 0, 0};
290}
291
292// Test to see if the clipstack is a simple rect, If so, we can avoid all PathOps code
293// and speed thing up.
294static bool is_rect(const SkClipStack& clipStack, const SkRect& bounds, SkRect* dst) {
295 SkRect currentClip = bounds;
296 SkClipStack::Iter iter(clipStack, SkClipStack::Iter::kBottom_IterStart);
297 while (const SkClipStack::Element* element = iter.next()) {
298 SkRect elementRect{0, 0, 0, 0};
299 switch (element->getDeviceSpaceType()) {
300 case SkClipStack::Element::DeviceSpaceType::kEmpty:
301 break;
302 case SkClipStack::Element::DeviceSpaceType::kRect:
303 elementRect = element->getDeviceSpaceRect();
304 break;
305 default:
306 return false;
307 }
308 switch (element->getOp()) {
309 case kReplace_SkClipOp:
310 currentClip = rect_intersect(bounds, elementRect);
311 break;
312 case SkClipOp::kIntersect:
313 currentClip = rect_intersect(currentClip, elementRect);
314 break;
315 default:
316 return false;
317 }
318 }
319 *dst = currentClip;
320 return true;
321}
322
323static void append_clip(const SkClipStack& clipStack,
324 const SkIRect& bounds,
325 SkWStream* wStream) {
326 // The bounds are slightly outset to ensure this is correct in the
327 // face of floating-point accuracy and possible SkRegion bitmap
328 // approximations.
329 SkRect outsetBounds = SkRect::Make(bounds.makeOutset(1, 1));
330
331 SkRect clipStackRect;
332 if (is_rect(clipStack, outsetBounds, &clipStackRect)) {
333 SkPDFUtils::AppendRectangle(clipStackRect, wStream);
334 wStream->writeText("W* n\n");
335 return;
336 }
337
338 SkPath clipPath;
339 (void)clipStack.asPath(&clipPath);
340
341 SkPath clipBoundsPath;
342 clipBoundsPath.addRect(outsetBounds);
343
344 if (Op(clipPath, clipBoundsPath, kIntersect_SkPathOp, &clipPath)) {
345 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, wStream);
346 SkPath::FillType clipFill = clipPath.getFillType();
347 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
348 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
349 if (clipFill == SkPath::kEvenOdd_FillType) {
350 wStream->writeText("W* n\n");
351 } else {
352 wStream->writeText("W n\n");
353 }
354 }
355 // If Op() fails (pathological case; e.g. input values are
356 // extremely large or NaN), emit no clip at all.
357}
358
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000359// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000360// graphic state stack, and the fact that we can know all the clips used
361// on the page to optimize this.
362void GraphicStackState::updateClip(const SkClipStack& clipStack,
Hal Canary4e83ff12018-03-09 12:16:42 -0500363 const SkIRect& bounds) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000364 if (clipStack == currentEntry()->fClipStack) {
365 return;
366 }
367
368 while (fStackDepth > 0) {
369 pop();
370 if (clipStack == currentEntry()->fClipStack) {
371 return;
372 }
373 }
374 push();
375
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000376 currentEntry()->fClipStack = clipStack;
Hal Canaryd00ef062018-06-05 11:53:58 -0400377 append_clip(clipStack, bounds, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000378}
379
380void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
381 if (matrix == currentEntry()->fMatrix) {
382 return;
383 }
384
385 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
386 SkASSERT(fStackDepth > 0);
387 SkASSERT(fEntries[fStackDepth].fClipStack ==
388 fEntries[fStackDepth -1].fClipStack);
389 pop();
390
391 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
392 }
393 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
394 return;
395 }
396
397 push();
398 SkPDFUtils::AppendTransform(matrix, fContentStream);
399 currentEntry()->fMatrix = matrix;
400}
401
halcanary2be7e012016-03-28 11:58:08 -0700402void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000403 // PDF treats a shader as a color, so we only set one or the other.
404 if (state.fShaderIndex >= 0) {
405 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000406 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000407 currentEntry()->fShaderIndex = state.fShaderIndex;
408 }
409 } else {
410 if (state.fColor != currentEntry()->fColor ||
411 currentEntry()->fShaderIndex >= 0) {
412 emit_pdf_color(state.fColor, fContentStream);
413 fContentStream->writeText("RG ");
414 emit_pdf_color(state.fColor, fContentStream);
415 fContentStream->writeText("rg\n");
416 currentEntry()->fColor = state.fColor;
417 currentEntry()->fShaderIndex = -1;
418 }
419 }
420
421 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000422 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000423 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
424 }
425
426 if (state.fTextScaleX) {
427 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
Hal Canary9b491b22017-11-28 15:10:13 -0500428 SkScalar pdfScale = state.fTextScaleX * 100;
halcanarybc4696b2015-05-06 10:56:04 -0700429 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000430 fContentStream->writeText(" Tz\n");
431 currentEntry()->fTextScaleX = state.fTextScaleX;
432 }
433 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700434 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
435 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
436 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000437 fContentStream->writeDecAsText(state.fTextFill);
438 fContentStream->writeText(" Tr\n");
439 currentEntry()->fTextFill = state.fTextFill;
440 }
441 }
442}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000443
reed76033be2015-03-14 10:54:31 -0700444static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700445 // PDF does not support image filters, so render them on CPU.
446 // Note that this rendering is done at "screen" resolution (100dpi), not
447 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700448 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800449 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700450
451 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700452 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700453}
454
455SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700456 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700457 // need to return a raster device, which we will detect in drawDevice()
458 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700459 }
Hal Canary22b2d8c2017-07-19 14:46:12 -0400460 return new SkPDFDevice(cinfo.fInfo.dimensions(), fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000461}
462
halcanary989da4a2016-03-21 14:33:17 -0700463SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
464
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000465// A helper class to automatically finish a ContentEntry at the end of a
466// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000467class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000468public:
Mike Reeda1361362017-03-07 09:37:29 -0500469 ScopedContentEntry(SkPDFDevice* device,
470 const SkClipStack& clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000471 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500472 const SkPaint& paint,
473 bool hasText = false)
474 : fDevice(device)
475 , fContentEntry(nullptr)
476 , fBlendMode(SkBlendMode::kSrcOver)
477 , fDstFormXObject(nullptr)
478 {
479 if (matrix.hasPerspective()) {
480 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
481 return;
482 }
483 fBlendMode = paint.getBlendMode();
484 fContentEntry =
485 fDevice->setUpContentEntry(clipStack, matrix, paint, hasText, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000486 }
Mike Reeda1361362017-03-07 09:37:29 -0500487 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, bool hasText = false)
488 : ScopedContentEntry(dev, dev->cs(), dev->ctm(), paint, hasText) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000489
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000490 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000491 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000492 SkPath* shape = &fShape;
493 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700494 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000495 }
reed374772b2016-10-05 17:33:02 -0700496 fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000497 }
498 }
499
halcanary2be7e012016-03-28 11:58:08 -0700500 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
Hal Canary51329c92017-06-27 14:28:37 -0400501 SkDynamicMemoryWStream* stream() { return &fContentEntry->fContent; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000502
503 /* Returns true when we explicitly need the shape of the drawing. */
504 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700505 switch (fBlendMode) {
506 case SkBlendMode::kClear:
507 case SkBlendMode::kSrc:
508 case SkBlendMode::kSrcIn:
509 case SkBlendMode::kSrcOut:
510 case SkBlendMode::kDstIn:
511 case SkBlendMode::kDstOut:
512 case SkBlendMode::kSrcATop:
513 case SkBlendMode::kDstATop:
514 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000515 return true;
516 default:
517 return false;
518 }
519 }
520
521 /* Returns true unless we only need the shape of the drawing. */
522 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700523 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000524 return false;
525 }
526 return true;
527 }
528
529 /* If the shape is different than the alpha component of the content, then
530 * setShape should be called with the shape. In particular, images and
531 * devices have rectangular shape.
532 */
533 void setShape(const SkPath& shape) {
534 fShape = shape;
535 }
536
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000537private:
538 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700539 SkPDFDevice::ContentEntry* fContentEntry;
reed374772b2016-10-05 17:33:02 -0700540 SkBlendMode fBlendMode;
halcanarydabd4f02016-08-03 11:16:56 -0700541 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000542 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000543};
544
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000545////////////////////////////////////////////////////////////////////////////////
546
Hal Canarya0622582017-06-29 18:51:35 -0400547SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc)
reed589a39e2016-08-20 07:59:19 -0700548 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
549 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700550 , fPageSize(pageSize)
Hal Canarya0622582017-06-29 18:51:35 -0400551 , fInitialTransform(SkMatrix::I())
552 , fDocument(doc)
553{
Hal Canary22b2d8c2017-07-19 14:46:12 -0400554 SkASSERT(!pageSize.isEmpty());
Hal Canarya0622582017-06-29 18:51:35 -0400555}
robertphillips1f3923e2016-07-21 07:17:54 -0700556
Hal Canarya0622582017-06-29 18:51:35 -0400557void SkPDFDevice::setFlip() {
558 // Skia generally uses the top left as the origin but PDF
559 // natively has the origin at the bottom left. This matrix
560 // corrects for that. But that only needs to be done once, we
561 // don't do it when layering.
Hal Canary82591142018-05-09 14:20:12 -0400562 SkScalar rasterScale = SkPDFUtils::kDpiForRasterScaleOne / fDocument->rasterDpi();
563 fInitialTransform.setConcat(SkMatrix::MakeScale(rasterScale, -rasterScale),
564 SkMatrix::MakeTrans(0, -fPageSize.fHeight));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000565}
566
567SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700568 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000569}
570
571void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700572 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000573}
574
halcanary3c35fb32016-06-30 11:55:07 -0700575void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000576 fGraphicStateResources.unrefAll();
577 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000578 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000579 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000580}
581
Mike Reeda1361362017-03-07 09:37:29 -0500582void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500583 if (!value) {
584 return;
585 }
586 if (rect.isEmpty()) {
Mike Reeda1361362017-03-07 09:37:29 -0500587 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
588 SkPoint transformedPoint;
589 this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
Hal Canary5c1b3602017-04-17 16:30:06 -0400590 fNamedDestinations.emplace_back(NamedDestination{sk_ref_sp(value), transformedPoint});
Mike Reeda1361362017-03-07 09:37:29 -0500591 }
592 return;
593 }
594 // Convert to path to handle non-90-degree rotations.
595 SkPath path;
596 path.addRect(rect);
597 path.transform(this->ctm(), &path);
598 SkPath clip;
599 (void)this->cs().asPath(&clip);
600 Op(clip, path, kIntersect_SkPathOp, &path);
601 // PDF wants a rectangle only.
602 SkRect transformedRect = path.getBounds();
603 if (transformedRect.isEmpty()) {
604 return;
605 }
606 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400607 fLinkToURLs.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
Mike Reeda1361362017-03-07 09:37:29 -0500608 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400609 fLinkToDestinations.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
reedf70b5312016-03-04 16:36:20 -0800610 }
611}
612
Hal Canaryd12a6762017-05-26 17:01:16 -0400613void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500614 if (this->hasEmptyClip()) {
615 return;
616 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400617 SkPaint newPaint = srcPaint;
618 remove_color_filter(&newPaint);
halcanarya6814332015-05-27 08:53:36 -0700619 replace_srcmode_on_opaque_paint(&newPaint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000620 newPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryd12a6762017-05-26 17:01:16 -0400621
622 SkMatrix ctm = this->ctm();
623 if (ctm.getType() & SkMatrix::kPerspective_Mask) {
624 if (newPaint.getShader()) {
625 transform_shader(&newPaint, ctm);
626 }
627 ctm = SkMatrix::I();
628 }
629 ScopedContentEntry content(this, this->cs(), ctm, newPaint);
Mike Reeda1361362017-03-07 09:37:29 -0500630 this->internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000631}
632
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000633void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700634 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000635 if (!contentEntry) {
636 return;
637 }
Hal Canaryd425a1d2017-07-12 13:13:51 -0400638 SkRect bbox = SkRect::Make(fPageSize);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000639 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000640 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000641 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000642 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000643 inverse.mapRect(&bbox);
644
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000645 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000646 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000647 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000648}
649
Mike Reeda1361362017-03-07 09:37:29 -0500650void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700651 size_t count,
652 const SkPoint* points,
653 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500654 if (this->hasEmptyClip()) {
655 return;
656 }
halcanarya6814332015-05-27 08:53:36 -0700657 SkPaint passedPaint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400658 remove_color_filter(&passedPaint);
halcanarya6814332015-05-27 08:53:36 -0700659 replace_srcmode_on_opaque_paint(&passedPaint);
Hal Canary80fa7ce2017-06-28 16:04:20 -0400660 if (SkCanvas::kPoints_PointMode != mode) {
661 passedPaint.setStyle(SkPaint::kStroke_Style);
662 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000663 if (count == 0) {
664 return;
665 }
666
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000667 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
668 // We only use this when there's a path effect because of the overhead
669 // of multiple calls to setUpContentEntry it causes.
670 if (passedPaint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500671 draw_points(mode, count, points, passedPaint,
672 this->devClipBounds(), this->ctm(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000673 return;
674 }
675
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000676 const SkPaint* paint = &passedPaint;
677 SkPaint modifiedPaint;
678
679 if (mode == SkCanvas::kPoints_PointMode &&
680 paint->getStrokeCap() != SkPaint::kRound_Cap) {
681 modifiedPaint = *paint;
682 paint = &modifiedPaint;
683 if (paint->getStrokeWidth()) {
684 // PDF won't draw a single point with square/butt caps because the
685 // orientation is ambiguous. Draw a rectangle instead.
686 modifiedPaint.setStyle(SkPaint::kFill_Style);
687 SkScalar strokeWidth = paint->getStrokeWidth();
688 SkScalar halfStroke = SkScalarHalf(strokeWidth);
689 for (size_t i = 0; i < count; i++) {
690 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
691 r.inset(-halfStroke, -halfStroke);
Mike Reeda1361362017-03-07 09:37:29 -0500692 this->drawRect(r, modifiedPaint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000693 }
694 return;
695 } else {
696 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
697 }
698 }
699
Mike Reeda1361362017-03-07 09:37:29 -0500700 ScopedContentEntry content(this, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000701 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000702 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000703 }
Hal Canary51329c92017-06-27 14:28:37 -0400704 SkDynamicMemoryWStream* contentStream = content.stream();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000705 switch (mode) {
706 case SkCanvas::kPolygon_PointMode:
Hal Canary51329c92017-06-27 14:28:37 -0400707 SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000708 for (size_t i = 1; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400709 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000710 }
Hal Canary51329c92017-06-27 14:28:37 -0400711 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000712 break;
713 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000714 for (size_t i = 0; i < count/2; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400715 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
716 SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
717 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000718 }
719 break;
720 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000721 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
722 for (size_t i = 0; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400723 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
724 SkPDFUtils::ClosePath(contentStream);
725 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000726 }
727 break;
728 default:
729 SkASSERT(false);
730 }
731}
732
halcanary8103a342016-03-08 15:10:16 -0800733static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800734 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700735 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700736 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700737
halcanaryece83922016-03-08 08:32:12 -0800738 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700739 border->reserve(3);
740 border->appendInt(0); // Horizontal corner radius.
741 border->appendInt(0); // Vertical corner radius.
742 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800743 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700744
halcanaryece83922016-03-08 08:32:12 -0800745 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700746 rect->reserve(4);
747 rect->appendScalar(translatedRect.fLeft);
748 rect->appendScalar(translatedRect.fTop);
749 rect->appendScalar(translatedRect.fRight);
750 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800751 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700752
halcanary8103a342016-03-08 15:10:16 -0800753 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700754}
755
halcanary8103a342016-03-08 15:10:16 -0800756static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700757 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700758 SkString url(static_cast<const char *>(urlData->data()),
759 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800760 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700761 action->insertName("S", "URI");
762 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800763 annotation->insertObject("A", std::move(action));
764 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700765}
766
halcanary8103a342016-03-08 15:10:16 -0800767static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
768 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700769 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700770 SkString name(static_cast<const char *>(nameData->data()),
771 nameData->size() - 1);
772 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800773 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700774}
775
Mike Reeda1361362017-03-07 09:37:29 -0500776void SkPDFDevice::drawRect(const SkRect& rect,
halcanarya6814332015-05-27 08:53:36 -0700777 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500778 if (this->hasEmptyClip()) {
779 return;
780 }
halcanarya6814332015-05-27 08:53:36 -0700781 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400782 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700783 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000784 SkRect r = rect;
785 r.sort();
786
Hal Canaryd12a6762017-05-26 17:01:16 -0400787 if (paint.getPathEffect() || paint.getMaskFilter()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000788 SkPath path;
789 path.addRect(r);
Mike Reeda1361362017-03-07 09:37:29 -0500790 this->drawPath(path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000791 return;
792 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000793
Mike Reeda1361362017-03-07 09:37:29 -0500794 ScopedContentEntry content(this, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000795 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000796 return;
797 }
Hal Canary51329c92017-06-27 14:28:37 -0400798 SkPDFUtils::AppendRectangle(r, content.stream());
799 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000800}
801
Mike Reeda1361362017-03-07 09:37:29 -0500802void SkPDFDevice::drawRRect(const SkRRect& rrect,
halcanarya6814332015-05-27 08:53:36 -0700803 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500804 if (this->hasEmptyClip()) {
805 return;
806 }
halcanarya6814332015-05-27 08:53:36 -0700807 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400808 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700809 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000810 SkPath path;
811 path.addRRect(rrect);
Mike Reeda1361362017-03-07 09:37:29 -0500812 this->drawPath(path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000813}
814
Mike Reeda1361362017-03-07 09:37:29 -0500815void SkPDFDevice::drawOval(const SkRect& oval,
halcanarya6814332015-05-27 08:53:36 -0700816 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500817 if (this->hasEmptyClip()) {
818 return;
819 }
halcanarya6814332015-05-27 08:53:36 -0700820 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400821 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700822 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700823 SkPath path;
824 path.addOval(oval);
Mike Reeda1361362017-03-07 09:37:29 -0500825 this->drawPath(path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700826}
827
Mike Reeda1361362017-03-07 09:37:29 -0500828void SkPDFDevice::drawPath(const SkPath& origPath,
halcanarya6814332015-05-27 08:53:36 -0700829 const SkPaint& srcPaint,
830 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000831 bool pathIsMutable) {
Mike Reeda1361362017-03-07 09:37:29 -0500832 this->internalDrawPath(
833 this->cs(), this->ctm(), origPath, srcPaint, prePathMatrix, pathIsMutable);
834}
835
Hal Canaryd12a6762017-05-26 17:01:16 -0400836void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
837 const SkMatrix& ctm,
838 const SkPath& origPath,
839 const SkPaint& origPaint,
840 const SkMatrix* prePathMatrix) {
841 SkASSERT(origPaint.getMaskFilter());
842 SkPath path(origPath);
843 SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
844 if (prePathMatrix) {
845 path.transform(*prePathMatrix, &path);
846 }
847 SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
848 ? SkStrokeRec::kFill_InitStyle
849 : SkStrokeRec::kHairline_InitStyle;
850 path.transform(ctm, &path);
851
Hal Canary22b2d8c2017-07-19 14:46:12 -0400852 SkIRect bounds = clipStack.bounds(this->bounds()).roundOut();
Hal Canaryd12a6762017-05-26 17:01:16 -0400853 SkMask sourceMask;
854 if (!SkDraw::DrawToMask(path, &bounds, paint->getMaskFilter(), &SkMatrix::I(),
855 &sourceMask, SkMask::kComputeBoundsAndRenderImage_CreateMode,
856 initStyle)) {
857 return;
858 }
859 SkAutoMaskFreeImage srcAutoMaskFreeImage(sourceMask.fImage);
860 SkMask dstMask;
861 SkIPoint margin;
Mike Reed80747ef2018-01-23 15:29:32 -0500862 if (!as_MFB(paint->getMaskFilter())->filterMask(&dstMask, sourceMask, ctm, &margin)) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400863 return;
864 }
Hal Canary51329c92017-06-27 14:28:37 -0400865 SkIRect dstMaskBounds = dstMask.fBounds;
866 sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
Hal Canaryd12a6762017-05-26 17:01:16 -0400867 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
868 // Must mask with a Form XObject.
Hal Canary51329c92017-06-27 14:28:37 -0400869 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
Hal Canaryd12a6762017-05-26 17:01:16 -0400870 {
Herb Derbyefe39bc2018-05-01 17:06:20 -0400871 SkCanvas canvas(maskDevice);
Hal Canary51329c92017-06-27 14:28:37 -0400872 canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
Hal Canaryd12a6762017-05-26 17:01:16 -0400873 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400874 if (!ctm.isIdentity() && paint->getShader()) {
875 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
876 }
877 ScopedContentEntry content(this, clipStack, SkMatrix::I(), *paint);
878 if (!content.entry()) {
879 return;
880 }
Hal Canary51329c92017-06-27 14:28:37 -0400881 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
882 SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
883 SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
884 this->clearMaskOnGraphicState(content.stream());
885}
Hal Canaryd12a6762017-05-26 17:01:16 -0400886
Hal Canary51329c92017-06-27 14:28:37 -0400887void SkPDFDevice::addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,
888 SkDynamicMemoryWStream* contentStream) {
889 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
Hal Canaryb4bd5ef2017-07-26 09:16:01 -0400890 maskDevice->makeFormXObjectFromDevice(true), false,
Hal Canary51329c92017-06-27 14:28:37 -0400891 SkPDFGraphicState::kLuminosity_SMaskMode, this->getCanon());
892 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(sMaskGS.get()), contentStream);
893}
Hal Canaryd12a6762017-05-26 17:01:16 -0400894
Hal Canary51329c92017-06-27 14:28:37 -0400895void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400896 // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
Hal Canaryc02de0b2017-06-28 13:14:03 -0400897 sk_sp<SkPDFDict>& noSMaskGS = this->getCanon()->fNoSmaskGraphicState;
898 if (!noSMaskGS) {
899 noSMaskGS = sk_make_sp<SkPDFDict>("ExtGState");
900 noSMaskGS->insertName("SMask", "None");
901 }
Hal Canary51329c92017-06-27 14:28:37 -0400902 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(noSMaskGS.get()), contentStream);
Hal Canaryd12a6762017-05-26 17:01:16 -0400903}
904
Mike Reeda1361362017-03-07 09:37:29 -0500905void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
906 const SkMatrix& ctm,
907 const SkPath& origPath,
908 const SkPaint& srcPaint,
909 const SkMatrix* prePathMatrix,
910 bool pathIsMutable) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500911 if (clipStack.isEmpty(this->bounds())) {
912 return;
913 }
halcanarya6814332015-05-27 08:53:36 -0700914 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400915 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700916 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800917 SkPath modifiedPath;
918 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000919
Hal Canaryd12a6762017-05-26 17:01:16 -0400920 if (paint.getMaskFilter()) {
921 this->internalDrawPathWithFilter(clipStack, ctm, origPath, paint, prePathMatrix);
922 return;
923 }
924
Mike Reeda1361362017-03-07 09:37:29 -0500925 SkMatrix matrix = ctm;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000926 if (prePathMatrix) {
927 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800928 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000929 pathPtr = &modifiedPath;
930 pathIsMutable = true;
931 }
halcanary682ee012016-01-28 10:59:34 -0800932 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000933 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000934 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000935 }
936 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000937
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000938 if (paint.getPathEffect()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400939 if (clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000940 return;
941 }
halcanary682ee012016-01-28 10:59:34 -0800942 if (!pathIsMutable) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400943 modifiedPath = origPath;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000944 pathPtr = &modifiedPath;
945 pathIsMutable = true;
946 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400947 if (paint.getFillPath(*pathPtr, pathPtr)) {
948 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000949 } else {
Hal Canaryd12a6762017-05-26 17:01:16 -0400950 paint.setStyle(SkPaint::kStroke_Style);
951 paint.setStrokeWidth(0);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000952 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400953 paint.setPathEffect(nullptr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000954 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000955
Hal Canaryd12a6762017-05-26 17:01:16 -0400956 if (this->handleInversePath(*pathPtr, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000957 return;
958 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400959 if (matrix.getType() & SkMatrix::kPerspective_Mask) {
960 if (!pathIsMutable) {
961 modifiedPath = origPath;
962 pathPtr = &modifiedPath;
963 pathIsMutable = true;
964 }
965 pathPtr->transform(matrix);
966 if (paint.getShader()) {
967 transform_shader(&paint, matrix);
968 }
969 matrix = SkMatrix::I();
970 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000971
Mike Reeda1361362017-03-07 09:37:29 -0500972 ScopedContentEntry content(this, clipStack, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000973 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000974 return;
975 }
Hal Canarydfaa0572017-11-27 09:33:44 -0500976 constexpr SkScalar kToleranceScale = 0.0625f; // smaller = better conics (circles).
Hal Canary385468f2017-02-13 11:03:23 -0500977 SkScalar matrixScale = matrix.mapRadius(1.0f);
Hal Canarydfaa0572017-11-27 09:33:44 -0500978 SkScalar tolerance = matrixScale > 0.0f ? kToleranceScale / matrixScale : kToleranceScale;
halcanary8b2bc252015-10-06 09:41:47 -0700979 bool consumeDegeratePathSegments =
980 paint.getStyle() == SkPaint::kFill_Style ||
981 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
982 paint.getStrokeCap() != SkPaint::kSquare_Cap);
Hal Canary51329c92017-06-27 14:28:37 -0400983 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(), consumeDegeratePathSegments, content.stream(),
Hal Canary385468f2017-02-13 11:03:23 -0500984 tolerance);
Hal Canary51329c92017-06-27 14:28:37 -0400985 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000986}
987
Hal Canary7cbf5e32017-07-12 13:10:23 -0400988////////////////////////////////////////////////////////////////////////////////
Hal Canaryf50ff392016-09-30 10:25:39 -0400989
Mike Reeda1361362017-03-07 09:37:29 -0500990void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400991 const SkRect* src,
992 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400993 const SkPaint& paint,
Hal Canaryf50ff392016-09-30 10:25:39 -0400994 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400995 SkASSERT(image);
996 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
997 src, dst, paint, this->ctm());
Hal Canaryf50ff392016-09-30 10:25:39 -0400998}
999
Hal Canary7cbf5e32017-07-12 13:10:23 -04001000void SkPDFDevice::drawBitmapRect(const SkBitmap& bm,
halcanary7a14b312015-10-01 07:28:13 -07001001 const SkRect* src,
1002 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -04001003 const SkPaint& paint,
Mike Reeda1361362017-03-07 09:37:29 -05001004 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04001005 SkASSERT(!bm.drawsNothing());
1006 this->internalDrawImageRect(SkKeyedImage(bm), src, dst, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -07001007}
1008
Hal Canary7cbf5e32017-07-12 13:10:23 -04001009void SkPDFDevice::drawBitmap(const SkBitmap& bm, SkScalar x, SkScalar y, const SkPaint& paint) {
1010 SkASSERT(!bm.drawsNothing());
1011 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
1012 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -07001013}
1014
Hal Canary7cbf5e32017-07-12 13:10:23 -04001015void SkPDFDevice::drawSprite(const SkBitmap& bm, int x, int y, const SkPaint& paint) {
1016 SkASSERT(!bm.drawsNothing());
1017 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
1018 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, SkMatrix::I());
halcanary7a14b312015-10-01 07:28:13 -07001019}
1020
Hal Canary7cbf5e32017-07-12 13:10:23 -04001021void SkPDFDevice::drawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint& paint) {
1022 SkASSERT(image);
1023 auto r = SkRect::MakeXYWH(x, y, image->width(), image->height());
1024 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
1025 nullptr, r, paint, this->ctm());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001026}
1027
Hal Canary7cbf5e32017-07-12 13:10:23 -04001028////////////////////////////////////////////////////////////////////////////////
1029
halcanaryf0c30f52016-07-15 13:35:45 -07001030namespace {
1031class GlyphPositioner {
1032public:
1033 GlyphPositioner(SkDynamicMemoryWStream* content,
1034 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -07001035 bool wideChars,
halcanary4ed2f012016-08-15 18:40:07 -07001036 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -07001037 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -07001038 , fCurrentMatrixOrigin(origin)
1039 , fTextSkewX(textSkewX)
Hal Canary98caedd2018-07-23 10:50:49 -04001040 , fWideChars(wideChars) {
halcanaryf0c30f52016-07-15 13:35:45 -07001041 }
halcanary4871f222016-08-26 13:17:44 -07001042 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -07001043 void flush() {
1044 if (fInText) {
1045 fContent->writeText("> Tj\n");
1046 fInText = false;
1047 }
1048 }
halcanary4871f222016-08-26 13:17:44 -07001049 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -07001050 SkScalar advanceWidth,
1051 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -07001052 if (!fInitialized) {
1053 // Flip the text about the x-axis to account for origin swap and include
1054 // the passed parameters.
1055 fContent->writeText("1 0 ");
1056 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
1057 fContent->writeText(" -1 ");
1058 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
1059 fContent->writeText(" ");
1060 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
1061 fContent->writeText(" Tm\n");
1062 fCurrentMatrixOrigin.set(0.0f, 0.0f);
1063 fInitialized = true;
1064 }
Hal Canary98caedd2018-07-23 10:50:49 -04001065 SkPoint position = xy - fCurrentMatrixOrigin;
1066 if (position != SkPoint{fXAdvance, 0}) {
1067 this->flush();
1068 SkPDFUtils::AppendScalar(position.x() - position.y() * fTextSkewX, fContent);
1069 fContent->writeText(" ");
1070 SkPDFUtils::AppendScalar(-position.y(), fContent);
1071 fContent->writeText(" Td ");
1072 fCurrentMatrixOrigin = xy;
1073 fXAdvance = 0;
halcanaryf0c30f52016-07-15 13:35:45 -07001074 }
Hal Canary98caedd2018-07-23 10:50:49 -04001075 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -07001076 if (!fInText) {
1077 fContent->writeText("<");
1078 fInText = true;
1079 }
1080 if (fWideChars) {
1081 SkPDFUtils::WriteUInt16BE(fContent, glyph);
1082 } else {
1083 SkASSERT(0 == glyph >> 8);
1084 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1085 }
halcanaryf0c30f52016-07-15 13:35:45 -07001086 }
1087
1088private:
1089 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -07001090 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001091 SkScalar fXAdvance = 0.0f;
1092 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001093 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001094 bool fInText = false;
1095 bool fInitialized = false;
halcanaryf0c30f52016-07-15 13:35:45 -07001096};
1097} // namespace
1098
Hal Canary46cc3da2018-05-09 11:50:34 -04001099static SkUnichar map_glyph(const std::vector<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1100 return glyph < glyphToUnicode.size() ? glyphToUnicode[SkToInt(glyph)] : -1;
halcanaryf59d18a2016-09-16 14:44:57 -07001101}
1102
halcanaryc2f9ec12016-09-12 08:55:29 -07001103static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1104 wStream->writeText("/");
1105 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1106 wStream->write(&prefix, 1);
1107 wStream->writeDecAsText(fontIndex);
1108 wStream->writeText(" ");
1109 SkPDFUtils::AppendScalar(textSize, wStream);
1110 wStream->writeText(" Tf\n");
1111}
1112
Hal Canary98caedd2018-07-23 10:50:49 -04001113static void draw_glyph_run_as_path(SkPDFDevice* dev, const SkGlyphRun& glyphRun, SkPoint offset) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001114 SkPath path;
Hal Canary98caedd2018-07-23 10:50:49 -04001115 SkASSERT(glyphRun.paint().getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1116 glyphRun.paint().getPosTextPath(glyphRun.shuntGlyphsIDs().data(),
1117 glyphRun.shuntGlyphsIDs().size() * sizeof(SkGlyphID),
1118 glyphRun.positions().data(),
1119 &path);
1120 path.offset(offset.x(), offset.y());
1121 dev->drawPath(path, glyphRun.paint(), nullptr, true);
Hal Canaryd12a6762017-05-26 17:01:16 -04001122}
1123
Hal Canary9b9510a2017-07-18 09:39:00 -04001124static bool has_outline_glyph(SkGlyphID gid, SkGlyphCache* cache) {
1125 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1126 const SkPath* path = cache->findPath(glyph);
1127 return (path && !path->isEmpty()) || (glyph.fWidth == 0 && glyph.fHeight == 0);
1128}
1129
Hal Canary699b8732017-06-13 12:13:29 -04001130static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkGlyphCache* cache,
1131 SkScalar xScale, SkScalar yScale,
1132 SkPoint xy, const SkMatrix& ctm) {
1133 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1134 SkRect glyphBounds = {glyph.fLeft * xScale,
1135 glyph.fTop * yScale,
1136 (glyph.fLeft + glyph.fWidth) * xScale,
1137 (glyph.fTop + glyph.fHeight) * yScale};
1138 glyphBounds.offset(xy);
1139 ctm.mapRect(&glyphBounds); // now in dev space.
1140 return glyphBounds;
1141}
1142
1143static bool contains(const SkRect& r, SkPoint p) {
1144 return r.left() <= p.x() && p.x() <= r.right() &&
1145 r.top() <= p.y() && p.y() <= r.bottom();
1146}
1147
Hal Canary9b9510a2017-07-18 09:39:00 -04001148static sk_sp<SkImage> image_from_mask(const SkMask& mask) {
1149 if (!mask.fImage) {
1150 return nullptr;
1151 }
1152 SkIRect bounds = mask.fBounds;
1153 SkBitmap bm;
1154 switch (mask.fFormat) {
1155 case SkMask::kBW_Format:
1156 bm.allocPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()));
1157 for (int y = 0; y < bm.height(); ++y) {
1158 for (int x8 = 0; x8 < bm.width(); x8 += 8) {
1159 uint8_t v = *mask.getAddr1(x8 + bounds.x(), y + bounds.y());
1160 int e = SkTMin(x8 + 8, bm.width());
1161 for (int x = x8; x < e; ++x) {
1162 *bm.getAddr8(x, y) = (v >> (x & 0x7)) & 0x1 ? 0xFF : 0x00;
1163 }
1164 }
1165 }
1166 bm.setImmutable();
1167 return SkImage::MakeFromBitmap(bm);
1168 case SkMask::kA8_Format:
1169 bm.installPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()),
1170 mask.fImage, mask.fRowBytes);
1171 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1172 case SkMask::kARGB32_Format:
1173 bm.installPixels(SkImageInfo::MakeN32Premul(bounds.width(), bounds.height()),
1174 mask.fImage, mask.fRowBytes);
1175 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1176 case SkMask::k3D_Format:
1177 SkASSERT(false);
1178 return nullptr;
1179 case SkMask::kLCD16_Format:
1180 SkASSERT(false);
1181 return nullptr;
1182 default:
1183 SkASSERT(false);
1184 return nullptr;
1185 }
1186}
1187
Hal Canary98caedd2018-07-23 10:50:49 -04001188void SkPDFDevice::internalDrawGlyphRun(const SkGlyphRun& glyphRun, SkPoint offset) {
1189
1190 const SkGlyphID* glyphs = glyphRun.shuntGlyphsIDs().data();
1191 uint32_t glyphCount = SkToU32(glyphRun.shuntGlyphsIDs().size());
1192 const SkPaint& srcPaint = glyphRun.paint();
1193 if (!glyphCount || !glyphs || srcPaint.getTextSize() <= 0 || this->hasEmptyClip()) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001194 return;
1195 }
Hal Canaryd12a6762017-05-26 17:01:16 -04001196 if (srcPaint.getPathEffect()
Hal Canary98caedd2018-07-23 10:50:49 -04001197 || srcPaint.getMaskFilter()
1198 || srcPaint.isVerticalText()
1199 || SkPaint::kFill_Style != srcPaint.getStyle()) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001200 // Stroked Text doesn't work well with Type3 fonts.
Hal Canary98caedd2018-07-23 10:50:49 -04001201 return draw_glyph_run_as_path(this, glyphRun, offset);
halcanarye06ca962016-09-09 05:34:55 -07001202 }
halcanary4ed2f012016-08-15 18:40:07 -07001203 SkPaint paint = calculate_text_paint(srcPaint);
Hal Canaryd12a6762017-05-26 17:01:16 -04001204 remove_color_filter(&paint);
halcanary4ed2f012016-08-15 18:40:07 -07001205 replace_srcmode_on_opaque_paint(&paint);
Hal Canary98caedd2018-07-23 10:50:49 -04001206 paint.setHinting(SkPaint::kNo_Hinting);
halcanary4ed2f012016-08-15 18:40:07 -07001207 if (!paint.getTypeface()) {
1208 paint.setTypeface(SkTypeface::MakeDefault());
1209 }
1210 SkTypeface* typeface = paint.getTypeface();
1211 if (!typeface) {
1212 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1213 return;
1214 }
Hal Canary98caedd2018-07-23 10:50:49 -04001215 const SkAdvancedTypefaceMetrics* metrics = SkPDFFont::GetMetrics(typeface, fDocument->canon());
halcanary4871f222016-08-26 13:17:44 -07001216 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001217 return;
1218 }
Hal Canary46cc3da2018-05-09 11:50:34 -04001219 const std::vector<SkUnichar>& glyphToUnicode = SkPDFFont::GetUnicodeMap(
1220 typeface, fDocument->canon());
1221
Hal Canary98caedd2018-07-23 10:50:49 -04001222 SkClusterator clusterator(glyphRun);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001223
1224 int emSize;
Herb Derby1a605cd2018-03-22 11:16:25 -04001225 auto glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001226
1227 SkScalar textSize = paint.getTextSize();
1228 SkScalar advanceScale = textSize * paint.getTextScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001229
Hal Canary699b8732017-06-13 12:13:29 -04001230 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1231 SkScalar textScaleY = textSize / emSize;
1232 SkScalar textScaleX = advanceScale + paint.getTextSkewX() * textScaleY;
1233
Hal Canary98caedd2018-07-23 10:50:49 -04001234 SkASSERT(paint.getTextAlign() == SkPaint::kLeft_Align);
Hal Canary22b2d8c2017-07-19 14:46:12 -04001235 SkRect clipStackBounds = this->cs().bounds(this->bounds());
Hal Canary9b9510a2017-07-18 09:39:00 -04001236 struct PositionedGlyph {
1237 SkPoint fPos;
1238 SkGlyphID fGlyph;
1239 };
Hal Canary98caedd2018-07-23 10:50:49 -04001240 SkTArray<PositionedGlyph> missingGlyphs;
Hal Canary9b9510a2017-07-18 09:39:00 -04001241 {
1242 ScopedContentEntry content(this, paint, true);
1243 if (!content.entry()) {
1244 return;
robertphillips5ba165e2016-08-15 15:36:58 -07001245 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001246 SkDynamicMemoryWStream* out = content.stream();
Hal Canary9b9510a2017-07-18 09:39:00 -04001247
1248 out->writeText("BT\n");
1249 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1250
1251 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
1252
1253 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
1254 if (clusterator.reversedChars()) {
1255 out->writeText("/ReversedChars BMC\n");
1256 }
1257 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1258 GlyphPositioner glyphPositioner(out,
1259 paint.getTextSkewX(),
1260 multiByteGlyphs,
Hal Canary9b9510a2017-07-18 09:39:00 -04001261 offset);
1262 SkPDFFont* font = nullptr;
1263
Hal Canary1521c8a2018-03-28 09:51:00 -07001264 while (SkClusterator::Cluster c = clusterator.next()) {
Hal Canary9b9510a2017-07-18 09:39:00 -04001265 int index = c.fGlyphIndex;
1266 int glyphLimit = index + c.fGlyphCount;
1267
1268 bool actualText = false;
1269 SK_AT_SCOPE_EXIT(if (actualText) {
1270 glyphPositioner.flush();
1271 out->writeText("EMC\n");
1272 });
1273 if (c.fUtf8Text) { // real cluster
1274 // Check if `/ActualText` needed.
1275 const char* textPtr = c.fUtf8Text;
1276 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1277 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1278 if (unichar < 0) {
halcanaryf59d18a2016-09-16 14:44:57 -07001279 return;
1280 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001281 if (textPtr < textEnd || // more characters left
1282 glyphLimit > index + 1 || // toUnicode wouldn't work
1283 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1284 {
1285 glyphPositioner.flush();
1286 out->writeText("/Span<</ActualText <");
1287 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1288 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1289 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1290 while (textPtr < textEnd) {
1291 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1292 if (unichar < 0) {
1293 break;
1294 }
1295 SkPDFUtils::WriteUTF16beHex(out, unichar);
1296 }
1297 out->writeText("> >> BDC\n"); // begin marked-content sequence
1298 // with an associated property list.
1299 actualText = true;
halcanaryf59d18a2016-09-16 14:44:57 -07001300 }
halcanaryf59d18a2016-09-16 14:44:57 -07001301 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001302 for (; index < glyphLimit; ++index) {
1303 SkGlyphID gid = glyphs[index];
1304 if (gid > maxGlyphID) {
1305 continue;
halcanaryf59d18a2016-09-16 14:44:57 -07001306 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001307 if (!font || !font->hasGlyph(gid)) {
1308 // Not yet specified font or need to switch font.
1309 int fontIndex = this->getFontResourceIndex(typeface, gid);
1310 // All preconditions for SkPDFFont::GetFontResource are met.
1311 SkASSERT(fontIndex >= 0);
1312 if (fontIndex < 0) {
1313 return;
1314 }
1315 glyphPositioner.flush();
1316 update_font(out, fontIndex, textSize);
1317 font = fFontResources[fontIndex];
1318 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1319 if (!font) {
1320 return;
1321 }
1322 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1323 }
Hal Canary98caedd2018-07-23 10:50:49 -04001324 SkPoint xy = glyphRun.positions()[index];
1325 // Do a glyph-by-glyph bounds-reject if positions are absolute.
1326 SkRect glyphBounds = get_glyph_bounds_device_space(
1327 gid, glyphCache.get(), textScaleX, textScaleY,
1328 xy + offset, this->ctm());
1329 if (glyphBounds.isEmpty()) {
1330 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
1331 continue;
Hal Canary699b8732017-06-13 12:13:29 -04001332 }
1333 } else {
Hal Canary98caedd2018-07-23 10:50:49 -04001334 if (!clipStackBounds.intersects(glyphBounds)) {
1335 continue; // reject glyphs as out of bounds
Hal Canary699b8732017-06-13 12:13:29 -04001336 }
1337 }
Hal Canary98caedd2018-07-23 10:50:49 -04001338 if (!has_outline_glyph(gid, glyphCache.get())) {
1339 missingGlyphs.push_back({xy + offset, gid});
1340 }
1341
Hal Canary9b9510a2017-07-18 09:39:00 -04001342 font->noteGlyphUsage(gid);
1343
1344 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
Hal Canary98caedd2018-07-23 10:50:49 -04001345 SkScalar advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
Hal Canary9b9510a2017-07-18 09:39:00 -04001346 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
halcanaryf59d18a2016-09-16 14:44:57 -07001347 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001348 }
1349 }
Hal Canary98caedd2018-07-23 10:50:49 -04001350 if (missingGlyphs.count() > 0) {
Hal Canary9b9510a2017-07-18 09:39:00 -04001351 // Fall back on images.
1352 SkPaint scaledGlyphCachePaint;
1353 scaledGlyphCachePaint.setTextSize(paint.getTextSize());
1354 scaledGlyphCachePaint.setTextScaleX(paint.getTextScaleX());
1355 scaledGlyphCachePaint.setTextSkewX(paint.getTextSkewX());
1356 scaledGlyphCachePaint.setTypeface(sk_ref_sp(typeface));
Herb Derbyfa996902018-04-18 11:36:12 -04001357 auto scaledGlyphCache = SkStrikeCache::FindOrCreateStrikeExclusive(scaledGlyphCachePaint);
Hal Canary9b9510a2017-07-18 09:39:00 -04001358 SkTHashMap<SkPDFCanon::BitmapGlyphKey, SkPDFCanon::BitmapGlyph>* map =
1359 &this->getCanon()->fBitmapGlyphImages;
Hal Canary98caedd2018-07-23 10:50:49 -04001360 for (PositionedGlyph positionedGlyph : missingGlyphs) {
Hal Canary9b9510a2017-07-18 09:39:00 -04001361 SkPDFCanon::BitmapGlyphKey key = {typeface->uniqueID(),
1362 paint.getTextSize(),
1363 paint.getTextScaleX(),
1364 paint.getTextSkewX(),
1365 positionedGlyph.fGlyph,
1366 0};
1367 SkImage* img = nullptr;
1368 SkIPoint imgOffset = {0, 0};
1369 if (SkPDFCanon::BitmapGlyph* ptr = map->find(key)) {
1370 img = ptr->fImage.get();
1371 imgOffset = ptr->fOffset;
1372 } else {
1373 (void)scaledGlyphCache->findImage(
1374 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph));
1375 SkMask mask;
1376 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph).toMask(&mask);
1377 imgOffset = {mask.fBounds.x(), mask.fBounds.y()};
1378 img = map->set(key, {image_from_mask(mask), imgOffset})->fImage.get();
1379 }
1380 if (img) {
1381 SkPoint pt = positionedGlyph.fPos +
1382 SkPoint{(SkScalar)imgOffset.x(), (SkScalar)imgOffset.y()};
1383 this->drawImage(img, pt.x(), pt.y(), srcPaint);
1384 }
halcanaryf59d18a2016-09-16 14:44:57 -07001385 }
robertphillips5ba165e2016-08-15 15:36:58 -07001386 }
halcanary4ed2f012016-08-15 18:40:07 -07001387}
1388
Herb Derbyb935cf82018-07-26 16:54:18 -04001389void SkPDFDevice::drawGlyphRunList(const SkGlyphRunList& glyphRunList) {
1390 for (const SkGlyphRun& glyphRun : glyphRunList) {
1391 this->internalDrawGlyphRun(glyphRun, glyphRunList.origin());
halcanarye06ca962016-09-09 05:34:55 -07001392 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001393}
1394
Ruiqi Maof5101492018-06-29 14:32:21 -04001395void SkPDFDevice::drawVertices(const SkVertices*, const SkMatrix*, int, SkBlendMode,
1396 const SkPaint&) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05001397 if (this->hasEmptyClip()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001398 return;
1399 }
reed@google.com85e143c2013-12-30 15:51:25 +00001400 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001401}
1402
Mike Reeda1361362017-03-07 09:37:29 -05001403void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001404 SkASSERT(!paint.getImageFilter());
1405
reed7503d602016-07-15 14:23:29 -07001406 // Check if the source device is really a bitmapdevice (because that's what we returned
1407 // from createDevice (likely due to an imagefilter)
1408 SkPixmap pmap;
1409 if (device->peekPixels(&pmap)) {
1410 SkBitmap bitmap;
1411 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001412 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001413 return;
1414 }
1415
fmalita6987dca2014-11-13 08:33:37 -08001416 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001417 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001418
1419 SkScalar scalarX = SkIntToScalar(x);
1420 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001421 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1422 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001423 fLinkToURLs.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001424 }
halcanary91fcb3e2016-03-04 13:53:22 -08001425 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1426 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001427 fLinkToDestinations.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001428 }
halcanary91fcb3e2016-03-04 13:53:22 -08001429 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1430 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001431 fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001432 }
1433
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001434 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001435 return;
1436 }
1437
Mike Reeda1361362017-03-07 09:37:29 -05001438 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
1439 ScopedContentEntry content(this, this->cs(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001440 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001441 return;
1442 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001443 if (content.needShape()) {
1444 SkPath shape;
1445 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001446 SkIntToScalar(device->width()),
1447 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001448 content.setShape(shape);
1449 }
1450 if (!content.needSource()) {
1451 return;
1452 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001453
halcanary4b1e17e2016-07-27 14:49:46 -07001454 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
Hal Canary51329c92017-06-27 14:28:37 -04001455 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001456}
1457
reede8f30622016-03-23 18:59:25 -07001458sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1459 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001460}
1461
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001462
halcanary8103a342016-03-08 15:10:16 -08001463sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001464 SkTDArray<SkPDFObject*> fonts;
1465 fonts.setReserve(fFontResources.count());
1466 for (SkPDFFont* font : fFontResources) {
1467 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001468 }
halcanary8103a342016-03-08 15:10:16 -08001469 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001470 &fGraphicStateResources,
1471 &fShaderResources,
1472 &fXObjectResources,
1473 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001474}
1475
halcanary8103a342016-03-08 15:10:16 -08001476sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001477 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001478 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001479 mediaBox->appendInt(0);
1480 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001481 mediaBox->appendInt(fPageSize.width());
1482 mediaBox->appendInt(fPageSize.height());
1483 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001484}
1485
mtklein5f939ab2016-03-16 10:28:35 -07001486std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001487 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001488 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001489 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001490 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001491
Hal Canary6d673962017-02-22 17:16:59 -05001492 GraphicStackState gsState(fExistingClipStack, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001493 for (const auto& entry : fContentEntries) {
Hal Canary4e83ff12018-03-09 12:16:42 -05001494 gsState.updateClip(entry.fState.fClipStack, this->bounds());
halcanary2be7e012016-03-28 11:58:08 -07001495 gsState.updateMatrix(entry.fState.fMatrix);
1496 gsState.updateDrawingState(entry.fState);
1497
halcanaryafdc1772016-08-23 09:02:12 -07001498 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001499 }
1500 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001501 if (buffer.bytesWritten() > 0) {
1502 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1503 } else {
1504 return skstd::make_unique<SkMemoryStream>();
1505 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001506}
1507
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001508/* Draws an inverse filled path by using Path Ops to compute the positive
1509 * inverse using the current clip as the inverse bounds.
1510 * Return true if this was an inverse path and was properly handled,
1511 * otherwise returns false and the normal drawing routine should continue,
1512 * either as a (incorrect) fallback or because the path was not inverse
1513 * in the first place.
1514 */
Mike Reeda1361362017-03-07 09:37:29 -05001515bool SkPDFDevice::handleInversePath(const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001516 const SkPaint& paint, bool pathIsMutable,
1517 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001518 if (!origPath.isInverseFillType()) {
1519 return false;
1520 }
1521
Hal Canaryb4e528d2018-03-09 16:02:15 -05001522 if (this->hasEmptyClip()) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001523 return false;
1524 }
1525
1526 SkPath modifiedPath;
1527 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1528 SkPaint noInversePaint(paint);
1529
1530 // Merge stroking operations into final path.
1531 if (SkPaint::kStroke_Style == paint.getStyle() ||
1532 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1533 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1534 if (doFillPath) {
1535 noInversePaint.setStyle(SkPaint::kFill_Style);
1536 noInversePaint.setStrokeWidth(0);
1537 pathPtr = &modifiedPath;
1538 } else {
1539 // To be consistent with the raster output, hairline strokes
1540 // are rendered as non-inverted.
1541 modifiedPath.toggleInverseFillType();
Mike Reeda1361362017-03-07 09:37:29 -05001542 this->drawPath(modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001543 return true;
1544 }
1545 }
1546
1547 // Get bounds of clip in current transform space
1548 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001549 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001550 SkMatrix totalMatrix = this->ctm();
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001551 if (prePathMatrix) {
1552 totalMatrix.preConcat(*prePathMatrix);
1553 }
1554 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001555 return false;
1556 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001557 SkRect bounds = this->cs().bounds(this->bounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001558 transformInverse.mapRect(&bounds);
1559
1560 // Extend the bounds by the line width (plus some padding)
1561 // so the edge doesn't cause a visible stroke.
1562 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1563 paint.getStrokeWidth() + SK_Scalar1);
1564
1565 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1566 return false;
1567 }
1568
Mike Reeda1361362017-03-07 09:37:29 -05001569 this->drawPath(modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001570 return true;
1571}
1572
wangxianzhuef6c50a2015-09-17 20:38:02 -07001573void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1574 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001575 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001576 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001577 fInitialTransform.mapRect(&r, rectWithURL.rect);
Hal Canary7675b362018-06-15 15:32:14 -04001578 array->appendObjRef(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001579 }
halcanary91fcb3e2016-03-04 13:53:22 -08001580 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001581 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001582 fInitialTransform.mapRect(&r, linkToDestination.rect);
Hal Canary7675b362018-06-15 15:32:14 -04001583 array->appendObjRef(
halcanaryd7b28852016-03-07 12:39:14 -08001584 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001585 }
1586}
epoger@google.comb58772f2013-03-08 09:09:10 +00001587
halcanary6d622702015-03-25 08:45:42 -07001588void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001589 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001590 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001591 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001592 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001593 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001594 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001595 pdfDest->appendScalar(p.x());
1596 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001597 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001598 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001599 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001600 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001601}
1602
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001603sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
halcanary5abbb442016-07-29 08:41:33 -07001604 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001605 if (!fInitialTransform.isIdentity()) {
1606 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001607 SkDEBUGFAIL("Layer initial transform should be invertible.");
1608 inverseTransform.reset();
1609 }
1610 }
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001611 const char* colorSpace = alpha ? "DeviceGray" : nullptr;
halcanary4b1e17e2016-07-27 14:49:46 -07001612 sk_sp<SkPDFObject> xobject =
1613 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001614 this->makeResourceDict(), inverseTransform, colorSpace);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001615 // We always draw the form xobjects that we create back into the device, so
1616 // we simply preserve the font usage instead of pulling it out and merging
1617 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001618 this->cleanUp(); // Reset this device to have no content.
1619 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001620 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001621}
1622
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001623void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001624 sk_sp<SkPDFObject> mask,
Mike Reeda1361362017-03-07 09:37:29 -05001625 const SkClipStack& clipStack,
reed374772b2016-10-05 17:33:02 -07001626 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001627 bool invertClip) {
Hal Canary22b2d8c2017-07-19 14:46:12 -04001628 if (!invertClip && clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001629 return;
1630 }
1631
halcanary4b1e17e2016-07-27 14:49:46 -07001632 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001633 std::move(mask), invertClip,
1634 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001635
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001636 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001637 paint.setBlendMode(mode);
Mike Reeda1361362017-03-07 09:37:29 -05001638 ScopedContentEntry content(this, clipStack, SkMatrix::I(), paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001639 if (!content.entry()) {
1640 return;
1641 }
Hal Canary51329c92017-06-27 14:28:37 -04001642 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()), content.stream());
1643 SkPDFUtils::DrawFormXObject(xObjectIndex, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001644 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001645}
1646
Mike Reeda1361362017-03-07 09:37:29 -05001647SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack& clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001648 const SkMatrix& matrix,
1649 const SkPaint& paint,
1650 bool hasText,
1651 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001652 *dst = nullptr;
reed374772b2016-10-05 17:33:02 -07001653 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001654
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001655 // For the following modes, we want to handle source and destination
1656 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001657 if (blendMode == SkBlendMode::kClear ||
1658 blendMode == SkBlendMode::kSrc ||
1659 blendMode == SkBlendMode::kSrcIn ||
1660 blendMode == SkBlendMode::kDstIn ||
1661 blendMode == SkBlendMode::kSrcOut ||
1662 blendMode == SkBlendMode::kDstOut ||
1663 blendMode == SkBlendMode::kSrcATop ||
1664 blendMode == SkBlendMode::kDstATop ||
1665 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001666 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001667 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001668 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001669 } else if (blendMode != SkBlendMode::kSrc &&
1670 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001671 // Except for Src and SrcOut, if there isn't anything already there,
1672 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001673 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001674 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001675 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001676 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001677 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001678
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001679 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001680 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001681 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001682 }
1683
halcanary2be7e012016-03-28 11:58:08 -07001684 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001685 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001686 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001687 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001688 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001689 } else {
halcanary2be7e012016-03-28 11:58:08 -07001690 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001691 }
Mike Reeda1361362017-03-07 09:37:29 -05001692 populateGraphicStateEntryFromPaint(matrix, clipStack, paint, hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001693 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001694}
1695
reed374772b2016-10-05 17:33:02 -07001696void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001697 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001698 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001699 if (blendMode != SkBlendMode::kClear &&
1700 blendMode != SkBlendMode::kSrc &&
1701 blendMode != SkBlendMode::kDstOver &&
1702 blendMode != SkBlendMode::kSrcIn &&
1703 blendMode != SkBlendMode::kDstIn &&
1704 blendMode != SkBlendMode::kSrcOut &&
1705 blendMode != SkBlendMode::kDstOut &&
1706 blendMode != SkBlendMode::kSrcATop &&
1707 blendMode != SkBlendMode::kDstATop &&
1708 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001709 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001710 return;
1711 }
reed374772b2016-10-05 17:33:02 -07001712 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001713 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00001714 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001715 // For DstOver, an empty content entry was inserted before the rest
1716 // of the content entries. If nothing was drawn, it needs to be
1717 // removed.
halcanary2be7e012016-03-28 11:58:08 -07001718 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001719 }
1720 return;
1721 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001722 if (!dst) {
reed374772b2016-10-05 17:33:02 -07001723 SkASSERT(blendMode == SkBlendMode::kSrc ||
1724 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001725 return;
1726 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001727
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001728 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07001729 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001730 // Changing the current content into a form-xobject will destroy the clip
1731 // objects which is fine since the xobject will already be clipped. However
1732 // if source has shape, we need to clip it too, so a copy of the clip is
1733 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001734
1735 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001736
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001737 SkPaint stockPaint;
1738
halcanary4b1e17e2016-07-27 14:49:46 -07001739 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001740 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001741 // If nothing was drawn and there's no shape, then the draw was a
1742 // no-op, but dst needs to be restored for that to be true.
1743 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1744 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1745 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07001746 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1747 blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001748 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07001749 // TODO: addXObjectResource take sk_sp
Hal Canary51329c92017-06-27 14:28:37 -04001750 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001751 return;
1752 } else {
reed374772b2016-10-05 17:33:02 -07001753 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001754 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001755 } else {
halcanary2be7e012016-03-28 11:58:08 -07001756 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07001757 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001758 }
1759
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001760 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1761 // without alpha.
reed374772b2016-10-05 17:33:02 -07001762 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001763 // TODO(vandebo): In order to properly support SrcATop we have to track
1764 // the shape of what's been drawn at all times. It's the intersection of
1765 // the non-transparent parts of the device and the outlines (shape) of
1766 // all images and devices drawn.
1767 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
Mike Reeda1361362017-03-07 09:37:29 -05001768 fExistingClipStack, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001769 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001770 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001771 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001772 SkPaint filledPaint;
1773 filledPaint.setColor(SK_ColorBLACK);
1774 filledPaint.setStyle(SkPaint::kFill_Style);
Mike Reeda1361362017-03-07 09:37:29 -05001775 this->internalDrawPath(clipStack, SkMatrix::I(), *shape, filledPaint, nullptr, true);
1776 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
1777 this->makeFormXObjectFromDevice(),
1778 fExistingClipStack,
1779 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07001780 } else {
Mike Reeda1361362017-03-07 09:37:29 -05001781 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
1782 srcFormXObject,
1783 fExistingClipStack,
1784 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001785 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001786 }
1787
reed374772b2016-10-05 17:33:02 -07001788 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001789 return;
reed374772b2016-10-05 17:33:02 -07001790 } else if (blendMode == SkBlendMode::kSrc ||
1791 blendMode == SkBlendMode::kDstATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001792 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001793 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04001794 SkPDFUtils::DrawFormXObject(this->addXObjectResource(srcFormXObject.get()),
1795 content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001796 }
reed374772b2016-10-05 17:33:02 -07001797 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001798 return;
1799 }
reed374772b2016-10-05 17:33:02 -07001800 } else if (blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001801 ScopedContentEntry content(this, fExistingClipStack,
1802 SkMatrix::I(), stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001803 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04001804 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001805 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001806 }
1807
reed374772b2016-10-05 17:33:02 -07001808 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
1809 blendMode == SkBlendMode::kDstIn ||
1810 blendMode == SkBlendMode::kSrcOut ||
1811 blendMode == SkBlendMode::kDstOut ||
1812 blendMode == SkBlendMode::kSrcATop ||
1813 blendMode == SkBlendMode::kDstATop ||
1814 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001815
reed374772b2016-10-05 17:33:02 -07001816 if (blendMode == SkBlendMode::kSrcIn ||
1817 blendMode == SkBlendMode::kSrcOut ||
1818 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07001819 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1820 std::move(dst),
Mike Reeda1361362017-03-07 09:37:29 -05001821 fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07001822 SkBlendMode::kSrcOver,
1823 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07001824 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001825 } else {
reed374772b2016-10-05 17:33:02 -07001826 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07001827 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07001828 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001829 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
Mike Reeda1361362017-03-07 09:37:29 -05001830 std::move(dst), fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07001831 SkBlendMode::kSrcOver, false);
1832 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001833 }
halcanarydabd4f02016-08-03 11:16:56 -07001834 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
Mike Reeda1361362017-03-07 09:37:29 -05001835 fExistingClipStack, mode,
reed374772b2016-10-05 17:33:02 -07001836 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07001837 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001838 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001839}
1840
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001841bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00001842 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001843 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001844 return true;
1845 }
1846 return false;
1847}
1848
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001849void SkPDFDevice::populateGraphicStateEntryFromPaint(
1850 const SkMatrix& matrix,
1851 const SkClipStack& clipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001852 const SkPaint& paint,
1853 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07001854 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07001855 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1856 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1857 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001858
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001859 entry->fMatrix = matrix;
1860 entry->fClipStack = clipStack;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001861 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1862 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001863
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001864 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08001865 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07001866 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001867 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001868 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05001869 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1870 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001871 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05001872 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001873 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07001874 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001875 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05001876 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1877 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1878 color = gradientColor;
1879 } else {
1880 // PDF positions patterns relative to the initial transform, so
1881 // we need to apply the current transform to the shader parameters.
1882 SkMatrix transform = matrix;
1883 transform.postConcat(fInitialTransform);
1884
1885 // PDF doesn't support kClamp_TileMode, so we simulate it by making
1886 // a pattern the size of the current clip.
Hal Canary22b2d8c2017-07-19 14:46:12 -04001887 SkRect clipStackBounds = clipStack.bounds(this->bounds());
Hal Canaryc8f91802017-02-12 20:29:12 -05001888
1889 // We need to apply the initial transform to bounds in order to get
1890 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05001891 fInitialTransform.mapRect(&clipStackBounds);
1892 SkIRect bounds;
1893 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05001894
Hal Canary7e872ca2017-07-19 15:51:18 -04001895 pdfShader = SkPDFMakeShader(fDocument, shader, transform, bounds, paint.getColor());
Hal Canaryc8f91802017-02-12 20:29:12 -05001896
1897 if (pdfShader.get()) {
1898 // pdfShader has been canonicalized so we can directly compare
1899 // pointers.
1900 int resourceIndex = fShaderResources.find(pdfShader.get());
1901 if (resourceIndex < 0) {
1902 resourceIndex = fShaderResources.count();
1903 fShaderResources.push(pdfShader.get());
1904 pdfShader.get()->ref();
1905 }
1906 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001907 }
1908 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001909 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001910
Hal Canary80fa7ce2017-06-28 16:04:20 -04001911 sk_sp<SkPDFDict> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001912 if (color == paint.getColor()) {
Hal Canary5c1b3602017-04-17 16:30:06 -04001913 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001914 } else {
1915 SkPaint newPaint = paint;
1916 newPaint.setColor(color);
Hal Canary5c1b3602017-04-17 16:30:06 -04001917 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001918 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001919 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001920 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001921
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001922 if (hasText) {
1923 entry->fTextScaleX = paint.getTextScaleX();
1924 entry->fTextFill = paint.getStyle();
1925 } else {
1926 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001927 }
1928}
1929
halcanarybe27a112015-04-01 13:31:19 -07001930int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001931 // Assumes that gs has been canonicalized (so we can directly compare
1932 // pointers).
1933 int result = fGraphicStateResources.find(gs);
1934 if (result < 0) {
1935 result = fGraphicStateResources.count();
1936 fGraphicStateResources.push(gs);
1937 gs->ref();
1938 }
1939 return result;
1940}
1941
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001942int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07001943 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001944 // Assumes that xobject has been canonicalized (so we can directly compare
1945 // pointers).
1946 int result = fXObjectResources.find(xObject);
1947 if (result < 0) {
1948 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07001949 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001950 }
1951 return result;
1952}
1953
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001954int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
Hal Canary5c1b3602017-04-17 16:30:06 -04001955 sk_sp<SkPDFFont> newFont = SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID);
halcanary7e8d5d32016-08-12 07:59:38 -07001956 if (!newFont) {
1957 return -1;
1958 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001959 int resourceIndex = fFontResources.find(newFont.get());
1960 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07001961 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001962 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07001963 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001964 }
1965 return resourceIndex;
1966}
1967
Hal Canaryfafe1352017-04-11 12:12:02 -04001968static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07001969
Hal Canary7cbf5e32017-07-12 13:10:23 -04001970static sk_sp<SkImage> color_filter(const SkImage* image,
halcanarya50151d2016-03-25 11:57:49 -07001971 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07001972 auto surface =
Hal Canary7cbf5e32017-07-12 13:10:23 -04001973 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07001974 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07001975 SkCanvas* canvas = surface->getCanvas();
1976 canvas->clear(SK_ColorTRANSPARENT);
1977 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07001978 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canary7cbf5e32017-07-12 13:10:23 -04001979 canvas->drawImage(image, 0, 0, &paint);
halcanarya50151d2016-03-25 11:57:49 -07001980 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07001981}
1982
1983////////////////////////////////////////////////////////////////////////////////
Hal Canary7cbf5e32017-07-12 13:10:23 -04001984
1985static bool is_integer(SkScalar x) {
1986 return x == SkScalarTruncToScalar(x);
1987}
1988
1989static bool is_integral(const SkRect& r) {
1990 return is_integer(r.left()) &&
1991 is_integer(r.top()) &&
1992 is_integer(r.right()) &&
1993 is_integer(r.bottom());
1994}
1995
1996void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
1997 const SkRect* src,
1998 const SkRect& dst,
1999 const SkPaint& srcPaint,
2000 const SkMatrix& ctm) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05002001 if (this->hasEmptyClip()) {
2002 return;
2003 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002004 if (!imageSubset) {
halcanarya50151d2016-03-25 11:57:49 -07002005 return;
2006 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002007
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002008 // First, figure out the src->dst transform and subset the image if needed.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002009 SkIRect bounds = imageSubset.image()->bounds();
Hal Canary7cbf5e32017-07-12 13:10:23 -04002010 SkRect srcRect = src ? *src : SkRect::Make(bounds);
2011 SkMatrix transform;
2012 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
2013 if (src && *src != SkRect::Make(bounds)) {
2014 if (!srcRect.intersect(SkRect::Make(bounds))) {
2015 return;
2016 }
2017 srcRect.roundOut(&bounds);
2018 transform.preTranslate(SkIntToScalar(bounds.x()),
2019 SkIntToScalar(bounds.y()));
2020 if (bounds != imageSubset.image()->bounds()) {
2021 imageSubset = imageSubset.subset(bounds);
2022 }
2023 if (!imageSubset) {
2024 return;
2025 }
2026 }
2027
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002028 // If the image is opaque and the paint's alpha is too, replace
2029 // kSrc blendmode with kSrcOver.
2030 SkPaint paint = srcPaint;
2031 if (imageSubset.image()->isOpaque()) {
2032 replace_srcmode_on_opaque_paint(&paint);
Hal Canaryd425a1d2017-07-12 13:13:51 -04002033 }
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002034
2035 // Alpha-only images need to get their color from the shader, before
2036 // applying the colorfilter.
2037 if (imageSubset.image()->isAlphaOnly() && paint.getColorFilter()) {
2038 // must blend alpha image and shader before applying colorfilter.
2039 auto surface =
2040 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
2041 SkCanvas* canvas = surface->getCanvas();
2042 SkPaint tmpPaint;
2043 // In the case of alpha images with shaders, the shader's coordinate
2044 // system is the image's coordiantes.
2045 tmpPaint.setShader(sk_ref_sp(paint.getShader()));
2046 tmpPaint.setColor(paint.getColor());
2047 canvas->clear(0x00000000);
2048 canvas->drawImage(imageSubset.image().get(), 0, 0, &tmpPaint);
2049 paint.setShader(nullptr);
2050 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2051 SkASSERT(!imageSubset.image()->isAlphaOnly());
2052 }
2053
2054 if (imageSubset.image()->isAlphaOnly()) {
2055 // The ColorFilter applies to the paint color/shader, not the alpha layer.
2056 SkASSERT(nullptr == paint.getColorFilter());
2057
Hal Canaryd425a1d2017-07-12 13:13:51 -04002058 sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
2059 if (!mask) {
2060 return;
2061 }
2062 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
2063 // Must mask with a Form XObject.
2064 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
2065 {
Herb Derbyefe39bc2018-05-01 17:06:20 -04002066 SkCanvas canvas(maskDevice);
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002067 if (paint.getMaskFilter()) {
2068 // This clip prevents the mask image shader from covering
2069 // entire device if unnecessary.
2070 canvas.clipRect(this->cs().bounds(this->bounds()));
2071 canvas.concat(ctm);
2072 SkPaint tmpPaint;
2073 tmpPaint.setShader(mask->makeShader(&transform));
2074 tmpPaint.setMaskFilter(sk_ref_sp(paint.getMaskFilter()));
2075 canvas.drawRect(dst, tmpPaint);
2076 } else {
2077 canvas.concat(ctm);
2078 if (src && !is_integral(*src)) {
2079 canvas.clipRect(dst);
2080 }
2081 canvas.concat(transform);
2082 canvas.drawImage(mask, 0, 0);
2083 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04002084 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04002085 if (!ctm.isIdentity() && paint.getShader()) {
2086 transform_shader(&paint, ctm); // Since we are using identity matrix.
2087 }
2088 ScopedContentEntry content(this, this->cs(), SkMatrix::I(), paint);
2089 if (!content.entry()) {
2090 return;
2091 }
2092 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
2093 SkPDFUtils::AppendRectangle(SkRect::Make(fPageSize), content.stream());
2094 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kWinding_FillType, content.stream());
2095 this->clearMaskOnGraphicState(content.stream());
2096 return;
2097 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002098 if (paint.getMaskFilter()) {
2099 paint.setShader(imageSubset.image()->makeShader(&transform));
2100 SkPath path;
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002101 path.addRect(dst); // handles non-integral clipping.
2102 this->internalDrawPath(this->cs(), this->ctm(), path, paint, nullptr, true);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002103 return;
2104 }
2105 transform.postConcat(ctm);
2106
2107 bool needToRestore = false;
2108 if (src && !is_integral(*src)) {
2109 // Need sub-pixel clipping to fix https://bug.skia.org/4374
2110 this->cs().save();
2111 this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
2112 needToRestore = true;
2113 }
2114 SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
2115
halcanary7a14b312015-10-01 07:28:13 -07002116 #ifdef SK_PDF_IMAGE_STATS
2117 gDrawImageCalls.fetch_add(1);
2118 #endif
Hal Canary7cbf5e32017-07-12 13:10:23 -04002119 SkMatrix matrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002120
2121 // Rasterize the bitmap using perspective in a new bitmap.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002122 if (transform.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002123 // Transform the bitmap in the new space, without taking into
2124 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002125 SkPath perspectiveOutline;
Hal Canary7cbf5e32017-07-12 13:10:23 -04002126 SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
halcanary7a14b312015-10-01 07:28:13 -07002127 perspectiveOutline.addRect(imageBounds);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002128 perspectiveOutline.transform(transform);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002129
2130 // TODO(edisonn): perf - use current clip too.
2131 // Retrieve the bounds of the new shape.
2132 SkRect bounds = perspectiveOutline.getBounds();
2133
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002134 // Transform the bitmap in the new space, taking into
2135 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002136 SkMatrix total = transform;
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002137 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002138
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002139 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002140 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002141 physicalPerspectiveOutline.transform(total);
2142
halcanary7a14b312015-10-01 07:28:13 -07002143 SkRect physicalPerspectiveBounds =
2144 physicalPerspectiveOutline.getBounds();
2145 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2146 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002147
2148 // TODO(edisonn): A better approach would be to use a bitmap shader
2149 // (in clamp mode) and draw a rect over the entire bounding box. Then
2150 // intersect perspectiveOutline to the clip. That will avoid introducing
2151 // alpha to the image while still giving good behavior at the edge of
2152 // the image. Avoiding alpha will reduce the pdf size and generation
2153 // CPU time some.
2154
halcanary7a14b312015-10-01 07:28:13 -07002155 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2156
Hal Canaryf50ff392016-09-30 10:25:39 -04002157 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002158 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002159 return;
2160 }
halcanary7a14b312015-10-01 07:28:13 -07002161 SkCanvas* canvas = surface->getCanvas();
2162 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002163
2164 SkScalar deltaX = bounds.left();
2165 SkScalar deltaY = bounds.top();
2166
Hal Canary7cbf5e32017-07-12 13:10:23 -04002167 SkMatrix offsetMatrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002168 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002169 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002170
2171 // Translate the draw in the new canvas, so we perfectly fit the
2172 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002173 canvas->setMatrix(offsetMatrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002174 canvas->drawImage(imageSubset.image(), 0, 0);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002175 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002176 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002177
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002178 // In the new space, we use the identity matrix translated
2179 // and scaled to reflect DPI.
2180 matrix.setScale(1 / scaleX, 1 / scaleY);
2181 matrix.postTranslate(deltaX, deltaY);
2182
Hal Canary7cbf5e32017-07-12 13:10:23 -04002183 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2184 if (!imageSubset) {
2185 return;
2186 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002187 }
2188
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002189 SkMatrix scaled;
2190 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002191 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2192 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002193 // Scale the image up from 1x1 to WxH.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002194 SkIRect subset = imageSubset.image()->bounds();
2195 scaled.postScale(SkIntToScalar(subset.width()),
2196 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002197 scaled.postConcat(matrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002198 ScopedContentEntry content(this, this->cs(), scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002199 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002200 return;
2201 }
2202 if (content.needShape()) {
2203 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002204 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002205 shape.transform(matrix);
2206 content.setShape(shape);
2207 }
2208 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002209 return;
2210 }
2211
halcanary287d22d2015-09-24 10:20:05 -07002212 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002213 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2214 imageSubset = SkKeyedImage(std::move(img));
2215 if (!imageSubset) {
2216 return;
2217 }
halcanary7a14b312015-10-01 07:28:13 -07002218 // TODO(halcanary): de-dupe this by caching filtered images.
2219 // (maybe in the resource cache?)
2220 }
halcanarya50151d2016-03-25 11:57:49 -07002221
Hal Canary7cbf5e32017-07-12 13:10:23 -04002222 SkBitmapKey key = imageSubset.key();
Hal Canary5c1b3602017-04-17 16:30:06 -04002223 sk_sp<SkPDFObject>* pdfimagePtr = fDocument->canon()->fPDFBitmapMap.find(key);
2224 sk_sp<SkPDFObject> pdfimage = pdfimagePtr ? *pdfimagePtr : nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002225 if (!pdfimage) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002226 SkASSERT(imageSubset);
2227 pdfimage = SkPDFCreateBitmapObject(imageSubset.release(),
Mike Reeda4daf192017-12-14 13:25:04 -05002228 fDocument->metadata().fEncodingQuality);
halcanary7a14b312015-10-01 07:28:13 -07002229 if (!pdfimage) {
2230 return;
halcanary287d22d2015-09-24 10:20:05 -07002231 }
halcanarya50151d2016-03-25 11:57:49 -07002232 fDocument->serialize(pdfimage); // serialize images early.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002233 SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
Hal Canary5c1b3602017-04-17 16:30:06 -04002234 fDocument->canon()->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002235 }
halcanarya50151d2016-03-25 11:57:49 -07002236 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
Hal Canary51329c92017-06-27 14:28:37 -04002237 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002238}
reede51c3562016-07-19 14:33:20 -07002239
2240///////////////////////////////////////////////////////////////////////////////////////////////////
2241
2242#include "SkSpecialImage.h"
2243#include "SkImageFilter.h"
2244
Florin Malita53f77bd2017-04-28 13:48:37 -04002245void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2246 SkImage* clipImage, const SkMatrix& clipMatrix) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05002247 if (this->hasEmptyClip()) {
2248 return;
2249 }
reede51c3562016-07-19 14:33:20 -07002250 SkASSERT(!srcImg->isTextureBacked());
2251
Florin Malita53f77bd2017-04-28 13:48:37 -04002252 //TODO: clipImage support
2253
reede51c3562016-07-19 14:33:20 -07002254 SkBitmap resultBM;
2255
2256 SkImageFilter* filter = paint.getImageFilter();
2257 if (filter) {
2258 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002259 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002260 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002261 const SkIRect clipBounds =
Hal Canary22b2d8c2017-07-19 14:46:12 -04002262 this->cs().bounds(this->bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002263 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
Brian Osmana50205f2018-07-06 13:57:01 -04002264 // TODO: Should PDF be operating in a specified color type/space? For now, run the filter
brianosman2a75e5d2016-09-22 07:15:37 -07002265 // in the same color space as the source (this is different from all other backends).
Brian Osmana50205f2018-07-06 13:57:01 -04002266 SkImageFilter::OutputProperties outputProperties(kN32_SkColorType, srcImg->getColorSpace());
brianosman2a75e5d2016-09-22 07:15:37 -07002267 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002268
2269 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2270 if (resultImg) {
2271 SkPaint tmpUnfiltered(paint);
2272 tmpUnfiltered.setImageFilter(nullptr);
2273 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002274 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002275 }
2276 }
2277 } else {
2278 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002279 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002280 }
2281 }
2282}
2283
2284sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2285 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2286}
2287
2288sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002289 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2290 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2291 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002292 SkColorSpace* legacyColorSpace = nullptr;
Hal Canary22b2d8c2017-07-19 14:46:12 -04002293 return SkSpecialImage::MakeFromImage(image->bounds(),
Brian Osman61624f02016-12-09 14:51:59 -05002294 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002295}
2296
2297sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002298 return nullptr;
2299}
brianosman04a44d02016-09-21 09:46:57 -07002300
2301SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2302 // We always return a transient cache, so it is freed after each
2303 // filter traversal.
2304 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2305}