blob: 6868aefe5c36482b4aed0562a636c482f7a356f0 [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"
halcanarye06ca962016-09-09 05:34:55 -070020#include "SkDrawFilter.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000021#include "SkGlyphCache.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"
halcanarye06ca962016-09-09 05:34:55 -070046#include "SkTextBlobRunIterator.h"
47#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,
1036 bool defaultPositioning,
1037 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -07001038 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -07001039 , fCurrentMatrixOrigin(origin)
1040 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -07001041 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -07001042 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -07001043 }
halcanary4871f222016-08-26 13:17:44 -07001044 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -07001045 void flush() {
1046 if (fInText) {
1047 fContent->writeText("> Tj\n");
1048 fInText = false;
1049 }
1050 }
halcanary4871f222016-08-26 13:17:44 -07001051 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -07001052 SkScalar advanceWidth,
1053 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -07001054 if (!fInitialized) {
1055 // Flip the text about the x-axis to account for origin swap and include
1056 // the passed parameters.
1057 fContent->writeText("1 0 ");
1058 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
1059 fContent->writeText(" -1 ");
1060 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
1061 fContent->writeText(" ");
1062 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
1063 fContent->writeText(" Tm\n");
1064 fCurrentMatrixOrigin.set(0.0f, 0.0f);
1065 fInitialized = true;
1066 }
halcanary4ed2f012016-08-15 18:40:07 -07001067 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -07001068 SkPoint position = xy - fCurrentMatrixOrigin;
Hal Canary197ca9b2017-05-15 10:29:44 -04001069 if (position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -07001070 this->flush();
Herb Derbyc00d8622018-06-18 14:18:39 -04001071 SkPDFUtils::AppendScalar(position.x() - position.y() * fTextSkewX, fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001072 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -07001073 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001074 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -07001075 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -07001076 fXAdvance = 0;
1077 }
1078 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -07001079 }
1080 if (!fInText) {
1081 fContent->writeText("<");
1082 fInText = true;
1083 }
1084 if (fWideChars) {
1085 SkPDFUtils::WriteUInt16BE(fContent, glyph);
1086 } else {
1087 SkASSERT(0 == glyph >> 8);
1088 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1089 }
halcanaryf0c30f52016-07-15 13:35:45 -07001090 }
1091
1092private:
1093 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -07001094 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001095 SkScalar fXAdvance = 0.0f;
1096 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001097 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001098 bool fInText = false;
1099 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -07001100 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001101};
1102} // namespace
1103
Hal Canary46cc3da2018-05-09 11:50:34 -04001104static SkUnichar map_glyph(const std::vector<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1105 return glyph < glyphToUnicode.size() ? glyphToUnicode[SkToInt(glyph)] : -1;
halcanaryf59d18a2016-09-16 14:44:57 -07001106}
1107
halcanaryc2f9ec12016-09-12 08:55:29 -07001108static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1109 wStream->writeText("/");
1110 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1111 wStream->write(&prefix, 1);
1112 wStream->writeDecAsText(fontIndex);
1113 wStream->writeText(" ");
1114 SkPDFUtils::AppendScalar(textSize, wStream);
1115 wStream->writeText(" Tf\n");
1116}
1117
Hal Canaryd12a6762017-05-26 17:01:16 -04001118static SkPath draw_text_as_path(const void* sourceText, size_t sourceByteCount,
1119 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
1120 SkPoint offset, const SkPaint& srcPaint) {
1121 SkPath path;
1122 int glyphCount;
1123 SkAutoTMalloc<SkPoint> tmpPoints;
1124 switch (positioning) {
1125 case SkTextBlob::kDefault_Positioning:
1126 srcPaint.getTextPath(sourceText, sourceByteCount, offset.x(), offset.y(), &path);
1127 break;
1128 case SkTextBlob::kHorizontal_Positioning:
1129 glyphCount = srcPaint.countText(sourceText, sourceByteCount);
1130 tmpPoints.realloc(glyphCount);
1131 for (int i = 0; i < glyphCount; ++i) {
1132 tmpPoints[i] = {pos[i] + offset.x(), offset.y()};
1133 }
1134 srcPaint.getPosTextPath(sourceText, sourceByteCount, tmpPoints.get(), &path);
1135 break;
1136 case SkTextBlob::kFull_Positioning:
1137 srcPaint.getPosTextPath(sourceText, sourceByteCount, (const SkPoint*)pos, &path);
1138 path.offset(offset.x(), offset.y());
1139 break;
1140 }
1141 return path;
1142}
1143
Hal Canary9b9510a2017-07-18 09:39:00 -04001144static bool has_outline_glyph(SkGlyphID gid, SkGlyphCache* cache) {
1145 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1146 const SkPath* path = cache->findPath(glyph);
1147 return (path && !path->isEmpty()) || (glyph.fWidth == 0 && glyph.fHeight == 0);
1148}
1149
Hal Canary699b8732017-06-13 12:13:29 -04001150static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkGlyphCache* cache,
1151 SkScalar xScale, SkScalar yScale,
1152 SkPoint xy, const SkMatrix& ctm) {
1153 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1154 SkRect glyphBounds = {glyph.fLeft * xScale,
1155 glyph.fTop * yScale,
1156 (glyph.fLeft + glyph.fWidth) * xScale,
1157 (glyph.fTop + glyph.fHeight) * yScale};
1158 glyphBounds.offset(xy);
1159 ctm.mapRect(&glyphBounds); // now in dev space.
1160 return glyphBounds;
1161}
1162
1163static bool contains(const SkRect& r, SkPoint p) {
1164 return r.left() <= p.x() && p.x() <= r.right() &&
1165 r.top() <= p.y() && p.y() <= r.bottom();
1166}
1167
Hal Canary9b9510a2017-07-18 09:39:00 -04001168static sk_sp<SkImage> image_from_mask(const SkMask& mask) {
1169 if (!mask.fImage) {
1170 return nullptr;
1171 }
1172 SkIRect bounds = mask.fBounds;
1173 SkBitmap bm;
1174 switch (mask.fFormat) {
1175 case SkMask::kBW_Format:
1176 bm.allocPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()));
1177 for (int y = 0; y < bm.height(); ++y) {
1178 for (int x8 = 0; x8 < bm.width(); x8 += 8) {
1179 uint8_t v = *mask.getAddr1(x8 + bounds.x(), y + bounds.y());
1180 int e = SkTMin(x8 + 8, bm.width());
1181 for (int x = x8; x < e; ++x) {
1182 *bm.getAddr8(x, y) = (v >> (x & 0x7)) & 0x1 ? 0xFF : 0x00;
1183 }
1184 }
1185 }
1186 bm.setImmutable();
1187 return SkImage::MakeFromBitmap(bm);
1188 case SkMask::kA8_Format:
1189 bm.installPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()),
1190 mask.fImage, mask.fRowBytes);
1191 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1192 case SkMask::kARGB32_Format:
1193 bm.installPixels(SkImageInfo::MakeN32Premul(bounds.width(), bounds.height()),
1194 mask.fImage, mask.fRowBytes);
1195 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1196 case SkMask::k3D_Format:
1197 SkASSERT(false);
1198 return nullptr;
1199 case SkMask::kLCD16_Format:
1200 SkASSERT(false);
1201 return nullptr;
1202 default:
1203 SkASSERT(false);
1204 return nullptr;
1205 }
1206}
1207
halcanary4ed2f012016-08-15 18:40:07 -07001208void SkPDFDevice::internalDrawText(
Mike Reeda1361362017-03-07 09:37:29 -05001209 const void* sourceText, size_t sourceByteCount,
halcanary4ed2f012016-08-15 18:40:07 -07001210 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001211 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1212 uint32_t textByteLength, const char* utf8Text) {
Hal Canary29ebe7a2017-10-18 10:04:57 -04001213 if (0 == sourceByteCount || !sourceText || srcPaint.getTextSize() <= 0) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001214 return;
1215 }
Hal Canaryb4e528d2018-03-09 16:02:15 -05001216 if (this->hasEmptyClip()) {
halcanary4ed2f012016-08-15 18:40:07 -07001217 return;
1218 }
halcanaryea17dfe2016-08-24 09:20:57 -07001219 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1220 if (srcPaint.isVerticalText()) {
1221 // Don't pretend we support drawing vertical text. It is not
1222 // clear to me how to switch to "vertical writing" mode in PDF.
1223 // Currently neither Chromium or Android set this flag.
1224 // https://bug.skia.org/5665
halcanaryea17dfe2016-08-24 09:20:57 -07001225 }
Hal Canaryd12a6762017-05-26 17:01:16 -04001226 if (srcPaint.getPathEffect()
1227 || srcPaint.getMaskFilter()
1228 || SkPaint::kFill_Style != srcPaint.getStyle()) {
1229 // Stroked Text doesn't work well with Type3 fonts.
1230 SkPath path = draw_text_as_path(sourceText, sourceByteCount, pos,
1231 positioning, offset, srcPaint);
1232 this->drawPath(path, srcPaint, nullptr, true);
halcanaryf59d18a2016-09-16 14:44:57 -07001233 return;
halcanarye06ca962016-09-09 05:34:55 -07001234 }
halcanary4ed2f012016-08-15 18:40:07 -07001235 SkPaint paint = calculate_text_paint(srcPaint);
Hal Canaryd12a6762017-05-26 17:01:16 -04001236 remove_color_filter(&paint);
halcanary4ed2f012016-08-15 18:40:07 -07001237 replace_srcmode_on_opaque_paint(&paint);
1238 if (!paint.getTypeface()) {
1239 paint.setTypeface(SkTypeface::MakeDefault());
1240 }
1241 SkTypeface* typeface = paint.getTypeface();
1242 if (!typeface) {
1243 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1244 return;
1245 }
halcanary4871f222016-08-26 13:17:44 -07001246
1247 const SkAdvancedTypefaceMetrics* metrics =
1248 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1249 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001250 return;
1251 }
Hal Canary46cc3da2018-05-09 11:50:34 -04001252 const std::vector<SkUnichar>& glyphToUnicode = SkPDFFont::GetUnicodeMap(
1253 typeface, fDocument->canon());
1254
Hal Canary1521c8a2018-03-28 09:51:00 -07001255 SkClusterator clusterator(sourceText, sourceByteCount, paint,
1256 clusters, textByteLength, utf8Text);
1257 const SkGlyphID* glyphs = clusterator.glyphs();
1258 uint32_t glyphCount = clusterator.glyphCount();
1259 if (glyphCount == 0) {
halcanary2bd295e2016-09-16 08:15:56 -07001260 return;
1261 }
halcanary3b294d52016-09-16 13:21:08 -07001262
halcanary4ed2f012016-08-15 18:40:07 -07001263 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001264 paint.setHinting(SkPaint::kNo_Hinting);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001265
1266 int emSize;
Herb Derby1a605cd2018-03-22 11:16:25 -04001267 auto glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001268
1269 SkScalar textSize = paint.getTextSize();
1270 SkScalar advanceScale = textSize * paint.getTextScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001271
Hal Canary699b8732017-06-13 12:13:29 -04001272 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1273 SkScalar textScaleY = textSize / emSize;
1274 SkScalar textScaleX = advanceScale + paint.getTextSkewX() * textScaleY;
1275
halcanary4ed2f012016-08-15 18:40:07 -07001276 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001277 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1278 SkPaint::kCenter_Align == alignment ? -0.5f :
1279 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001280 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001281 SkScalar advance = 0;
Hal Canary1521c8a2018-03-28 09:51:00 -07001282 for (uint32_t i = 0; i < glyphCount; ++i) {
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001283 advance += advanceScale * glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
halcanary4ed2f012016-08-15 18:40:07 -07001284 }
halcanary4871f222016-08-26 13:17:44 -07001285 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001286 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001287 SkRect clipStackBounds = this->cs().bounds(this->bounds());
Hal Canary9b9510a2017-07-18 09:39:00 -04001288 struct PositionedGlyph {
1289 SkPoint fPos;
1290 SkGlyphID fGlyph;
1291 };
1292 SkTArray<PositionedGlyph> fMissingGlyphs;
1293 {
1294 ScopedContentEntry content(this, paint, true);
1295 if (!content.entry()) {
1296 return;
robertphillips5ba165e2016-08-15 15:36:58 -07001297 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001298 SkDynamicMemoryWStream* out = content.stream();
Hal Canary9b9510a2017-07-18 09:39:00 -04001299
1300 out->writeText("BT\n");
1301 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1302
1303 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
1304
1305 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
1306 if (clusterator.reversedChars()) {
1307 out->writeText("/ReversedChars BMC\n");
1308 }
1309 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1310 GlyphPositioner glyphPositioner(out,
1311 paint.getTextSkewX(),
1312 multiByteGlyphs,
1313 defaultPositioning,
1314 offset);
1315 SkPDFFont* font = nullptr;
1316
Hal Canary1521c8a2018-03-28 09:51:00 -07001317 while (SkClusterator::Cluster c = clusterator.next()) {
Hal Canary9b9510a2017-07-18 09:39:00 -04001318 int index = c.fGlyphIndex;
1319 int glyphLimit = index + c.fGlyphCount;
1320
1321 bool actualText = false;
1322 SK_AT_SCOPE_EXIT(if (actualText) {
1323 glyphPositioner.flush();
1324 out->writeText("EMC\n");
1325 });
1326 if (c.fUtf8Text) { // real cluster
1327 // Check if `/ActualText` needed.
1328 const char* textPtr = c.fUtf8Text;
1329 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1330 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1331 if (unichar < 0) {
halcanaryf59d18a2016-09-16 14:44:57 -07001332 return;
1333 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001334 if (textPtr < textEnd || // more characters left
1335 glyphLimit > index + 1 || // toUnicode wouldn't work
1336 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1337 {
1338 glyphPositioner.flush();
1339 out->writeText("/Span<</ActualText <");
1340 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1341 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1342 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1343 while (textPtr < textEnd) {
1344 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1345 if (unichar < 0) {
1346 break;
1347 }
1348 SkPDFUtils::WriteUTF16beHex(out, unichar);
1349 }
1350 out->writeText("> >> BDC\n"); // begin marked-content sequence
1351 // with an associated property list.
1352 actualText = true;
halcanaryf59d18a2016-09-16 14:44:57 -07001353 }
halcanaryf59d18a2016-09-16 14:44:57 -07001354 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001355 for (; index < glyphLimit; ++index) {
1356 SkGlyphID gid = glyphs[index];
1357 if (gid > maxGlyphID) {
1358 continue;
halcanaryf59d18a2016-09-16 14:44:57 -07001359 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001360 if (!font || !font->hasGlyph(gid)) {
1361 // Not yet specified font or need to switch font.
1362 int fontIndex = this->getFontResourceIndex(typeface, gid);
1363 // All preconditions for SkPDFFont::GetFontResource are met.
1364 SkASSERT(fontIndex >= 0);
1365 if (fontIndex < 0) {
1366 return;
1367 }
1368 glyphPositioner.flush();
1369 update_font(out, fontIndex, textSize);
1370 font = fFontResources[fontIndex];
1371 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1372 if (!font) {
1373 return;
1374 }
1375 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1376 }
1377 SkPoint xy = {0, 0};
1378 SkScalar advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1379 if (!defaultPositioning) {
1380 xy = SkTextBlob::kFull_Positioning == positioning
1381 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1382 : SkPoint{pos[index], 0};
1383 if (alignment != SkPaint::kLeft_Align) {
1384 xy.offset(alignmentFactor * advance, 0);
1385 }
1386 // Do a glyph-by-glyph bounds-reject if positions are absolute.
1387 SkRect glyphBounds = get_glyph_bounds_device_space(
1388 gid, glyphCache.get(), textScaleX, textScaleY,
1389 xy + offset, this->ctm());
1390 if (glyphBounds.isEmpty()) {
1391 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
1392 continue;
1393 }
1394 } else {
1395 if (!clipStackBounds.intersects(glyphBounds)) {
1396 continue; // reject glyphs as out of bounds
1397 }
1398 }
1399 if (!has_outline_glyph(gid, glyphCache.get())) {
Hal Canary10ccb022017-07-19 10:12:11 -04001400 fMissingGlyphs.push_back({xy + offset, gid});
Hal Canary699b8732017-06-13 12:13:29 -04001401 }
1402 } else {
Hal Canary9b9510a2017-07-18 09:39:00 -04001403 if (!has_outline_glyph(gid, glyphCache.get())) {
1404 fMissingGlyphs.push_back({offset, gid});
Hal Canary699b8732017-06-13 12:13:29 -04001405 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001406 offset += SkPoint{advance, 0};
Hal Canary699b8732017-06-13 12:13:29 -04001407 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001408 font->noteGlyphUsage(gid);
1409
1410 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1411 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
halcanaryf59d18a2016-09-16 14:44:57 -07001412 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001413 }
1414 }
1415 if (fMissingGlyphs.count() > 0) {
1416 // Fall back on images.
1417 SkPaint scaledGlyphCachePaint;
1418 scaledGlyphCachePaint.setTextSize(paint.getTextSize());
1419 scaledGlyphCachePaint.setTextScaleX(paint.getTextScaleX());
1420 scaledGlyphCachePaint.setTextSkewX(paint.getTextSkewX());
1421 scaledGlyphCachePaint.setTypeface(sk_ref_sp(typeface));
Herb Derbyfa996902018-04-18 11:36:12 -04001422 auto scaledGlyphCache = SkStrikeCache::FindOrCreateStrikeExclusive(scaledGlyphCachePaint);
Hal Canary9b9510a2017-07-18 09:39:00 -04001423 SkTHashMap<SkPDFCanon::BitmapGlyphKey, SkPDFCanon::BitmapGlyph>* map =
1424 &this->getCanon()->fBitmapGlyphImages;
1425 for (PositionedGlyph positionedGlyph : fMissingGlyphs) {
1426 SkPDFCanon::BitmapGlyphKey key = {typeface->uniqueID(),
1427 paint.getTextSize(),
1428 paint.getTextScaleX(),
1429 paint.getTextSkewX(),
1430 positionedGlyph.fGlyph,
1431 0};
1432 SkImage* img = nullptr;
1433 SkIPoint imgOffset = {0, 0};
1434 if (SkPDFCanon::BitmapGlyph* ptr = map->find(key)) {
1435 img = ptr->fImage.get();
1436 imgOffset = ptr->fOffset;
1437 } else {
1438 (void)scaledGlyphCache->findImage(
1439 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph));
1440 SkMask mask;
1441 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph).toMask(&mask);
1442 imgOffset = {mask.fBounds.x(), mask.fBounds.y()};
1443 img = map->set(key, {image_from_mask(mask), imgOffset})->fImage.get();
1444 }
1445 if (img) {
1446 SkPoint pt = positionedGlyph.fPos +
1447 SkPoint{(SkScalar)imgOffset.x(), (SkScalar)imgOffset.y()};
1448 this->drawImage(img, pt.x(), pt.y(), srcPaint);
1449 }
halcanaryf59d18a2016-09-16 14:44:57 -07001450 }
robertphillips5ba165e2016-08-15 15:36:58 -07001451 }
halcanary4ed2f012016-08-15 18:40:07 -07001452}
1453
Mike Reeda1361362017-03-07 09:37:29 -05001454void SkPDFDevice::drawPosText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001455 const SkScalar pos[], int scalarsPerPos,
1456 const SkPoint& offset, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001457 this->internalDrawText(text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001458 offset, paint, nullptr, 0, nullptr);
1459}
1460
Robert Phillips38580452018-06-28 12:00:35 +00001461void SkPDFDevice::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
1462 const SkPaint &paint, SkDrawFilter* drawFilter) {
1463 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1464 SkPaint runPaint(paint);
halcanarye06ca962016-09-09 05:34:55 -07001465 it.applyFontToPaint(&runPaint);
Robert Phillips38580452018-06-28 12:00:35 +00001466 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1467 continue;
1468 }
1469 SkPoint offset = it.offset() + SkPoint{x, y};
Mike Reeda1361362017-03-07 09:37:29 -05001470 this->internalDrawText(it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
Robert Phillips38580452018-06-28 12:00:35 +00001471 it.pos(), it.positioning(), offset, runPaint,
halcanarye06ca962016-09-09 05:34:55 -07001472 it.clusters(), it.textSize(), it.text());
1473 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001474}
1475
Ruiqi Maof5101492018-06-29 14:32:21 -04001476void SkPDFDevice::drawVertices(const SkVertices*, const SkMatrix*, int, SkBlendMode,
1477 const SkPaint&) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05001478 if (this->hasEmptyClip()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001479 return;
1480 }
reed@google.com85e143c2013-12-30 15:51:25 +00001481 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001482}
1483
Mike Reeda1361362017-03-07 09:37:29 -05001484void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001485 SkASSERT(!paint.getImageFilter());
1486
reed7503d602016-07-15 14:23:29 -07001487 // Check if the source device is really a bitmapdevice (because that's what we returned
1488 // from createDevice (likely due to an imagefilter)
1489 SkPixmap pmap;
1490 if (device->peekPixels(&pmap)) {
1491 SkBitmap bitmap;
1492 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001493 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001494 return;
1495 }
1496
fmalita6987dca2014-11-13 08:33:37 -08001497 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001498 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001499
1500 SkScalar scalarX = SkIntToScalar(x);
1501 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001502 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1503 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001504 fLinkToURLs.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001505 }
halcanary91fcb3e2016-03-04 13:53:22 -08001506 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1507 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001508 fLinkToDestinations.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001509 }
halcanary91fcb3e2016-03-04 13:53:22 -08001510 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1511 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001512 fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001513 }
1514
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001515 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001516 return;
1517 }
1518
Mike Reeda1361362017-03-07 09:37:29 -05001519 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
1520 ScopedContentEntry content(this, this->cs(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001521 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001522 return;
1523 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001524 if (content.needShape()) {
1525 SkPath shape;
1526 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001527 SkIntToScalar(device->width()),
1528 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001529 content.setShape(shape);
1530 }
1531 if (!content.needSource()) {
1532 return;
1533 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001534
halcanary4b1e17e2016-07-27 14:49:46 -07001535 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
Hal Canary51329c92017-06-27 14:28:37 -04001536 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001537}
1538
reede8f30622016-03-23 18:59:25 -07001539sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1540 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001541}
1542
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001543
halcanary8103a342016-03-08 15:10:16 -08001544sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001545 SkTDArray<SkPDFObject*> fonts;
1546 fonts.setReserve(fFontResources.count());
1547 for (SkPDFFont* font : fFontResources) {
1548 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001549 }
halcanary8103a342016-03-08 15:10:16 -08001550 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001551 &fGraphicStateResources,
1552 &fShaderResources,
1553 &fXObjectResources,
1554 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001555}
1556
halcanary8103a342016-03-08 15:10:16 -08001557sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001558 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001559 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001560 mediaBox->appendInt(0);
1561 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001562 mediaBox->appendInt(fPageSize.width());
1563 mediaBox->appendInt(fPageSize.height());
1564 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001565}
1566
mtklein5f939ab2016-03-16 10:28:35 -07001567std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001568 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001569 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001570 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001571 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001572
Hal Canary6d673962017-02-22 17:16:59 -05001573 GraphicStackState gsState(fExistingClipStack, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001574 for (const auto& entry : fContentEntries) {
Hal Canary4e83ff12018-03-09 12:16:42 -05001575 gsState.updateClip(entry.fState.fClipStack, this->bounds());
halcanary2be7e012016-03-28 11:58:08 -07001576 gsState.updateMatrix(entry.fState.fMatrix);
1577 gsState.updateDrawingState(entry.fState);
1578
halcanaryafdc1772016-08-23 09:02:12 -07001579 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001580 }
1581 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001582 if (buffer.bytesWritten() > 0) {
1583 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1584 } else {
1585 return skstd::make_unique<SkMemoryStream>();
1586 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001587}
1588
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001589/* Draws an inverse filled path by using Path Ops to compute the positive
1590 * inverse using the current clip as the inverse bounds.
1591 * Return true if this was an inverse path and was properly handled,
1592 * otherwise returns false and the normal drawing routine should continue,
1593 * either as a (incorrect) fallback or because the path was not inverse
1594 * in the first place.
1595 */
Mike Reeda1361362017-03-07 09:37:29 -05001596bool SkPDFDevice::handleInversePath(const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001597 const SkPaint& paint, bool pathIsMutable,
1598 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001599 if (!origPath.isInverseFillType()) {
1600 return false;
1601 }
1602
Hal Canaryb4e528d2018-03-09 16:02:15 -05001603 if (this->hasEmptyClip()) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001604 return false;
1605 }
1606
1607 SkPath modifiedPath;
1608 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1609 SkPaint noInversePaint(paint);
1610
1611 // Merge stroking operations into final path.
1612 if (SkPaint::kStroke_Style == paint.getStyle() ||
1613 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1614 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1615 if (doFillPath) {
1616 noInversePaint.setStyle(SkPaint::kFill_Style);
1617 noInversePaint.setStrokeWidth(0);
1618 pathPtr = &modifiedPath;
1619 } else {
1620 // To be consistent with the raster output, hairline strokes
1621 // are rendered as non-inverted.
1622 modifiedPath.toggleInverseFillType();
Mike Reeda1361362017-03-07 09:37:29 -05001623 this->drawPath(modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001624 return true;
1625 }
1626 }
1627
1628 // Get bounds of clip in current transform space
1629 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001630 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001631 SkMatrix totalMatrix = this->ctm();
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001632 if (prePathMatrix) {
1633 totalMatrix.preConcat(*prePathMatrix);
1634 }
1635 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001636 return false;
1637 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001638 SkRect bounds = this->cs().bounds(this->bounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001639 transformInverse.mapRect(&bounds);
1640
1641 // Extend the bounds by the line width (plus some padding)
1642 // so the edge doesn't cause a visible stroke.
1643 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1644 paint.getStrokeWidth() + SK_Scalar1);
1645
1646 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1647 return false;
1648 }
1649
Mike Reeda1361362017-03-07 09:37:29 -05001650 this->drawPath(modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001651 return true;
1652}
1653
wangxianzhuef6c50a2015-09-17 20:38:02 -07001654void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1655 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001656 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001657 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001658 fInitialTransform.mapRect(&r, rectWithURL.rect);
Hal Canary7675b362018-06-15 15:32:14 -04001659 array->appendObjRef(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001660 }
halcanary91fcb3e2016-03-04 13:53:22 -08001661 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001662 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001663 fInitialTransform.mapRect(&r, linkToDestination.rect);
Hal Canary7675b362018-06-15 15:32:14 -04001664 array->appendObjRef(
halcanaryd7b28852016-03-07 12:39:14 -08001665 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001666 }
1667}
epoger@google.comb58772f2013-03-08 09:09:10 +00001668
halcanary6d622702015-03-25 08:45:42 -07001669void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001670 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001671 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001672 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001673 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001674 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001675 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001676 pdfDest->appendScalar(p.x());
1677 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001678 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001679 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001680 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001681 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001682}
1683
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001684sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
halcanary5abbb442016-07-29 08:41:33 -07001685 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001686 if (!fInitialTransform.isIdentity()) {
1687 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001688 SkDEBUGFAIL("Layer initial transform should be invertible.");
1689 inverseTransform.reset();
1690 }
1691 }
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001692 const char* colorSpace = alpha ? "DeviceGray" : nullptr;
halcanary4b1e17e2016-07-27 14:49:46 -07001693 sk_sp<SkPDFObject> xobject =
1694 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001695 this->makeResourceDict(), inverseTransform, colorSpace);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001696 // We always draw the form xobjects that we create back into the device, so
1697 // we simply preserve the font usage instead of pulling it out and merging
1698 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001699 this->cleanUp(); // Reset this device to have no content.
1700 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001701 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001702}
1703
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001704void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001705 sk_sp<SkPDFObject> mask,
Mike Reeda1361362017-03-07 09:37:29 -05001706 const SkClipStack& clipStack,
reed374772b2016-10-05 17:33:02 -07001707 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001708 bool invertClip) {
Hal Canary22b2d8c2017-07-19 14:46:12 -04001709 if (!invertClip && clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001710 return;
1711 }
1712
halcanary4b1e17e2016-07-27 14:49:46 -07001713 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001714 std::move(mask), invertClip,
1715 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001716
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001717 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001718 paint.setBlendMode(mode);
Mike Reeda1361362017-03-07 09:37:29 -05001719 ScopedContentEntry content(this, clipStack, SkMatrix::I(), paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001720 if (!content.entry()) {
1721 return;
1722 }
Hal Canary51329c92017-06-27 14:28:37 -04001723 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()), content.stream());
1724 SkPDFUtils::DrawFormXObject(xObjectIndex, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001725 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001726}
1727
Mike Reeda1361362017-03-07 09:37:29 -05001728SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack& clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001729 const SkMatrix& matrix,
1730 const SkPaint& paint,
1731 bool hasText,
1732 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001733 *dst = nullptr;
reed374772b2016-10-05 17:33:02 -07001734 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001735
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001736 // For the following modes, we want to handle source and destination
1737 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001738 if (blendMode == SkBlendMode::kClear ||
1739 blendMode == SkBlendMode::kSrc ||
1740 blendMode == SkBlendMode::kSrcIn ||
1741 blendMode == SkBlendMode::kDstIn ||
1742 blendMode == SkBlendMode::kSrcOut ||
1743 blendMode == SkBlendMode::kDstOut ||
1744 blendMode == SkBlendMode::kSrcATop ||
1745 blendMode == SkBlendMode::kDstATop ||
1746 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001747 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001748 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001749 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001750 } else if (blendMode != SkBlendMode::kSrc &&
1751 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001752 // Except for Src and SrcOut, if there isn't anything already there,
1753 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001754 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001755 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001756 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001757 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001758 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001759
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001760 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001761 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001762 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001763 }
1764
halcanary2be7e012016-03-28 11:58:08 -07001765 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001766 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001767 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001768 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001769 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001770 } else {
halcanary2be7e012016-03-28 11:58:08 -07001771 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001772 }
Mike Reeda1361362017-03-07 09:37:29 -05001773 populateGraphicStateEntryFromPaint(matrix, clipStack, paint, hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001774 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001775}
1776
reed374772b2016-10-05 17:33:02 -07001777void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001778 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001779 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001780 if (blendMode != SkBlendMode::kClear &&
1781 blendMode != SkBlendMode::kSrc &&
1782 blendMode != SkBlendMode::kDstOver &&
1783 blendMode != SkBlendMode::kSrcIn &&
1784 blendMode != SkBlendMode::kDstIn &&
1785 blendMode != SkBlendMode::kSrcOut &&
1786 blendMode != SkBlendMode::kDstOut &&
1787 blendMode != SkBlendMode::kSrcATop &&
1788 blendMode != SkBlendMode::kDstATop &&
1789 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001790 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001791 return;
1792 }
reed374772b2016-10-05 17:33:02 -07001793 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001794 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00001795 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001796 // For DstOver, an empty content entry was inserted before the rest
1797 // of the content entries. If nothing was drawn, it needs to be
1798 // removed.
halcanary2be7e012016-03-28 11:58:08 -07001799 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001800 }
1801 return;
1802 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001803 if (!dst) {
reed374772b2016-10-05 17:33:02 -07001804 SkASSERT(blendMode == SkBlendMode::kSrc ||
1805 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001806 return;
1807 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001808
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001809 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07001810 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001811 // Changing the current content into a form-xobject will destroy the clip
1812 // objects which is fine since the xobject will already be clipped. However
1813 // if source has shape, we need to clip it too, so a copy of the clip is
1814 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001815
1816 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001817
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001818 SkPaint stockPaint;
1819
halcanary4b1e17e2016-07-27 14:49:46 -07001820 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001821 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001822 // If nothing was drawn and there's no shape, then the draw was a
1823 // no-op, but dst needs to be restored for that to be true.
1824 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1825 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1826 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07001827 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1828 blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001829 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07001830 // TODO: addXObjectResource take sk_sp
Hal Canary51329c92017-06-27 14:28:37 -04001831 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001832 return;
1833 } else {
reed374772b2016-10-05 17:33:02 -07001834 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001835 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001836 } else {
halcanary2be7e012016-03-28 11:58:08 -07001837 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07001838 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001839 }
1840
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001841 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1842 // without alpha.
reed374772b2016-10-05 17:33:02 -07001843 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001844 // TODO(vandebo): In order to properly support SrcATop we have to track
1845 // the shape of what's been drawn at all times. It's the intersection of
1846 // the non-transparent parts of the device and the outlines (shape) of
1847 // all images and devices drawn.
1848 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
Mike Reeda1361362017-03-07 09:37:29 -05001849 fExistingClipStack, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001850 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001851 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001852 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001853 SkPaint filledPaint;
1854 filledPaint.setColor(SK_ColorBLACK);
1855 filledPaint.setStyle(SkPaint::kFill_Style);
Mike Reeda1361362017-03-07 09:37:29 -05001856 this->internalDrawPath(clipStack, SkMatrix::I(), *shape, filledPaint, nullptr, true);
1857 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
1858 this->makeFormXObjectFromDevice(),
1859 fExistingClipStack,
1860 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07001861 } else {
Mike Reeda1361362017-03-07 09:37:29 -05001862 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
1863 srcFormXObject,
1864 fExistingClipStack,
1865 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001866 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001867 }
1868
reed374772b2016-10-05 17:33:02 -07001869 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001870 return;
reed374772b2016-10-05 17:33:02 -07001871 } else if (blendMode == SkBlendMode::kSrc ||
1872 blendMode == SkBlendMode::kDstATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001873 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001874 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04001875 SkPDFUtils::DrawFormXObject(this->addXObjectResource(srcFormXObject.get()),
1876 content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001877 }
reed374772b2016-10-05 17:33:02 -07001878 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001879 return;
1880 }
reed374772b2016-10-05 17:33:02 -07001881 } else if (blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001882 ScopedContentEntry content(this, fExistingClipStack,
1883 SkMatrix::I(), stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001884 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04001885 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001886 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001887 }
1888
reed374772b2016-10-05 17:33:02 -07001889 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
1890 blendMode == SkBlendMode::kDstIn ||
1891 blendMode == SkBlendMode::kSrcOut ||
1892 blendMode == SkBlendMode::kDstOut ||
1893 blendMode == SkBlendMode::kSrcATop ||
1894 blendMode == SkBlendMode::kDstATop ||
1895 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001896
reed374772b2016-10-05 17:33:02 -07001897 if (blendMode == SkBlendMode::kSrcIn ||
1898 blendMode == SkBlendMode::kSrcOut ||
1899 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07001900 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1901 std::move(dst),
Mike Reeda1361362017-03-07 09:37:29 -05001902 fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07001903 SkBlendMode::kSrcOver,
1904 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07001905 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001906 } else {
reed374772b2016-10-05 17:33:02 -07001907 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07001908 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07001909 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001910 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
Mike Reeda1361362017-03-07 09:37:29 -05001911 std::move(dst), fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07001912 SkBlendMode::kSrcOver, false);
1913 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001914 }
halcanarydabd4f02016-08-03 11:16:56 -07001915 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
Mike Reeda1361362017-03-07 09:37:29 -05001916 fExistingClipStack, mode,
reed374772b2016-10-05 17:33:02 -07001917 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07001918 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001919 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001920}
1921
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001922bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00001923 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001924 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001925 return true;
1926 }
1927 return false;
1928}
1929
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001930void SkPDFDevice::populateGraphicStateEntryFromPaint(
1931 const SkMatrix& matrix,
1932 const SkClipStack& clipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001933 const SkPaint& paint,
1934 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07001935 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07001936 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1937 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1938 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001939
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001940 entry->fMatrix = matrix;
1941 entry->fClipStack = clipStack;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001942 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1943 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001944
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001945 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08001946 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07001947 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001948 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001949 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05001950 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1951 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001952 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05001953 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001954 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07001955 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001956 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05001957 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1958 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1959 color = gradientColor;
1960 } else {
1961 // PDF positions patterns relative to the initial transform, so
1962 // we need to apply the current transform to the shader parameters.
1963 SkMatrix transform = matrix;
1964 transform.postConcat(fInitialTransform);
1965
1966 // PDF doesn't support kClamp_TileMode, so we simulate it by making
1967 // a pattern the size of the current clip.
Hal Canary22b2d8c2017-07-19 14:46:12 -04001968 SkRect clipStackBounds = clipStack.bounds(this->bounds());
Hal Canaryc8f91802017-02-12 20:29:12 -05001969
1970 // We need to apply the initial transform to bounds in order to get
1971 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05001972 fInitialTransform.mapRect(&clipStackBounds);
1973 SkIRect bounds;
1974 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05001975
Hal Canary7e872ca2017-07-19 15:51:18 -04001976 pdfShader = SkPDFMakeShader(fDocument, shader, transform, bounds, paint.getColor());
Hal Canaryc8f91802017-02-12 20:29:12 -05001977
1978 if (pdfShader.get()) {
1979 // pdfShader has been canonicalized so we can directly compare
1980 // pointers.
1981 int resourceIndex = fShaderResources.find(pdfShader.get());
1982 if (resourceIndex < 0) {
1983 resourceIndex = fShaderResources.count();
1984 fShaderResources.push(pdfShader.get());
1985 pdfShader.get()->ref();
1986 }
1987 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001988 }
1989 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001990 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001991
Hal Canary80fa7ce2017-06-28 16:04:20 -04001992 sk_sp<SkPDFDict> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001993 if (color == paint.getColor()) {
Hal Canary5c1b3602017-04-17 16:30:06 -04001994 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001995 } else {
1996 SkPaint newPaint = paint;
1997 newPaint.setColor(color);
Hal Canary5c1b3602017-04-17 16:30:06 -04001998 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001999 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002000 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002001 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002002
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002003 if (hasText) {
2004 entry->fTextScaleX = paint.getTextScaleX();
2005 entry->fTextFill = paint.getStyle();
2006 } else {
2007 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002008 }
2009}
2010
halcanarybe27a112015-04-01 13:31:19 -07002011int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002012 // Assumes that gs has been canonicalized (so we can directly compare
2013 // pointers).
2014 int result = fGraphicStateResources.find(gs);
2015 if (result < 0) {
2016 result = fGraphicStateResources.count();
2017 fGraphicStateResources.push(gs);
2018 gs->ref();
2019 }
2020 return result;
2021}
2022
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002023int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002024 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002025 // Assumes that xobject has been canonicalized (so we can directly compare
2026 // pointers).
2027 int result = fXObjectResources.find(xObject);
2028 if (result < 0) {
2029 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002030 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002031 }
2032 return result;
2033}
2034
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002035int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002036 sk_sp<SkPDFFont> newFont = SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID);
halcanary7e8d5d32016-08-12 07:59:38 -07002037 if (!newFont) {
2038 return -1;
2039 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002040 int resourceIndex = fFontResources.find(newFont.get());
2041 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002042 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002043 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002044 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002045 }
2046 return resourceIndex;
2047}
2048
Hal Canaryfafe1352017-04-11 12:12:02 -04002049static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07002050
Hal Canary7cbf5e32017-07-12 13:10:23 -04002051static sk_sp<SkImage> color_filter(const SkImage* image,
halcanarya50151d2016-03-25 11:57:49 -07002052 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002053 auto surface =
Hal Canary7cbf5e32017-07-12 13:10:23 -04002054 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07002055 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002056 SkCanvas* canvas = surface->getCanvas();
2057 canvas->clear(SK_ColorTRANSPARENT);
2058 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002059 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canary7cbf5e32017-07-12 13:10:23 -04002060 canvas->drawImage(image, 0, 0, &paint);
halcanarya50151d2016-03-25 11:57:49 -07002061 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002062}
2063
2064////////////////////////////////////////////////////////////////////////////////
Hal Canary7cbf5e32017-07-12 13:10:23 -04002065
2066static bool is_integer(SkScalar x) {
2067 return x == SkScalarTruncToScalar(x);
2068}
2069
2070static bool is_integral(const SkRect& r) {
2071 return is_integer(r.left()) &&
2072 is_integer(r.top()) &&
2073 is_integer(r.right()) &&
2074 is_integer(r.bottom());
2075}
2076
2077void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
2078 const SkRect* src,
2079 const SkRect& dst,
2080 const SkPaint& srcPaint,
2081 const SkMatrix& ctm) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05002082 if (this->hasEmptyClip()) {
2083 return;
2084 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002085 if (!imageSubset) {
halcanarya50151d2016-03-25 11:57:49 -07002086 return;
2087 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002088
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002089 // First, figure out the src->dst transform and subset the image if needed.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002090 SkIRect bounds = imageSubset.image()->bounds();
Hal Canary7cbf5e32017-07-12 13:10:23 -04002091 SkRect srcRect = src ? *src : SkRect::Make(bounds);
2092 SkMatrix transform;
2093 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
2094 if (src && *src != SkRect::Make(bounds)) {
2095 if (!srcRect.intersect(SkRect::Make(bounds))) {
2096 return;
2097 }
2098 srcRect.roundOut(&bounds);
2099 transform.preTranslate(SkIntToScalar(bounds.x()),
2100 SkIntToScalar(bounds.y()));
2101 if (bounds != imageSubset.image()->bounds()) {
2102 imageSubset = imageSubset.subset(bounds);
2103 }
2104 if (!imageSubset) {
2105 return;
2106 }
2107 }
2108
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002109 // If the image is opaque and the paint's alpha is too, replace
2110 // kSrc blendmode with kSrcOver.
2111 SkPaint paint = srcPaint;
2112 if (imageSubset.image()->isOpaque()) {
2113 replace_srcmode_on_opaque_paint(&paint);
Hal Canaryd425a1d2017-07-12 13:13:51 -04002114 }
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002115
2116 // Alpha-only images need to get their color from the shader, before
2117 // applying the colorfilter.
2118 if (imageSubset.image()->isAlphaOnly() && paint.getColorFilter()) {
2119 // must blend alpha image and shader before applying colorfilter.
2120 auto surface =
2121 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
2122 SkCanvas* canvas = surface->getCanvas();
2123 SkPaint tmpPaint;
2124 // In the case of alpha images with shaders, the shader's coordinate
2125 // system is the image's coordiantes.
2126 tmpPaint.setShader(sk_ref_sp(paint.getShader()));
2127 tmpPaint.setColor(paint.getColor());
2128 canvas->clear(0x00000000);
2129 canvas->drawImage(imageSubset.image().get(), 0, 0, &tmpPaint);
2130 paint.setShader(nullptr);
2131 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2132 SkASSERT(!imageSubset.image()->isAlphaOnly());
2133 }
2134
2135 if (imageSubset.image()->isAlphaOnly()) {
2136 // The ColorFilter applies to the paint color/shader, not the alpha layer.
2137 SkASSERT(nullptr == paint.getColorFilter());
2138
Hal Canaryd425a1d2017-07-12 13:13:51 -04002139 sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
2140 if (!mask) {
2141 return;
2142 }
2143 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
2144 // Must mask with a Form XObject.
2145 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
2146 {
Herb Derbyefe39bc2018-05-01 17:06:20 -04002147 SkCanvas canvas(maskDevice);
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002148 if (paint.getMaskFilter()) {
2149 // This clip prevents the mask image shader from covering
2150 // entire device if unnecessary.
2151 canvas.clipRect(this->cs().bounds(this->bounds()));
2152 canvas.concat(ctm);
2153 SkPaint tmpPaint;
2154 tmpPaint.setShader(mask->makeShader(&transform));
2155 tmpPaint.setMaskFilter(sk_ref_sp(paint.getMaskFilter()));
2156 canvas.drawRect(dst, tmpPaint);
2157 } else {
2158 canvas.concat(ctm);
2159 if (src && !is_integral(*src)) {
2160 canvas.clipRect(dst);
2161 }
2162 canvas.concat(transform);
2163 canvas.drawImage(mask, 0, 0);
2164 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04002165 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04002166 if (!ctm.isIdentity() && paint.getShader()) {
2167 transform_shader(&paint, ctm); // Since we are using identity matrix.
2168 }
2169 ScopedContentEntry content(this, this->cs(), SkMatrix::I(), paint);
2170 if (!content.entry()) {
2171 return;
2172 }
2173 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
2174 SkPDFUtils::AppendRectangle(SkRect::Make(fPageSize), content.stream());
2175 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kWinding_FillType, content.stream());
2176 this->clearMaskOnGraphicState(content.stream());
2177 return;
2178 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002179 if (paint.getMaskFilter()) {
2180 paint.setShader(imageSubset.image()->makeShader(&transform));
2181 SkPath path;
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002182 path.addRect(dst); // handles non-integral clipping.
2183 this->internalDrawPath(this->cs(), this->ctm(), path, paint, nullptr, true);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002184 return;
2185 }
2186 transform.postConcat(ctm);
2187
2188 bool needToRestore = false;
2189 if (src && !is_integral(*src)) {
2190 // Need sub-pixel clipping to fix https://bug.skia.org/4374
2191 this->cs().save();
2192 this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
2193 needToRestore = true;
2194 }
2195 SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
2196
halcanary7a14b312015-10-01 07:28:13 -07002197 #ifdef SK_PDF_IMAGE_STATS
2198 gDrawImageCalls.fetch_add(1);
2199 #endif
Hal Canary7cbf5e32017-07-12 13:10:23 -04002200 SkMatrix matrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002201
2202 // Rasterize the bitmap using perspective in a new bitmap.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002203 if (transform.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002204 // Transform the bitmap in the new space, without taking into
2205 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002206 SkPath perspectiveOutline;
Hal Canary7cbf5e32017-07-12 13:10:23 -04002207 SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
halcanary7a14b312015-10-01 07:28:13 -07002208 perspectiveOutline.addRect(imageBounds);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002209 perspectiveOutline.transform(transform);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002210
2211 // TODO(edisonn): perf - use current clip too.
2212 // Retrieve the bounds of the new shape.
2213 SkRect bounds = perspectiveOutline.getBounds();
2214
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002215 // Transform the bitmap in the new space, taking into
2216 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002217 SkMatrix total = transform;
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002218 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002219
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002220 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002221 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002222 physicalPerspectiveOutline.transform(total);
2223
halcanary7a14b312015-10-01 07:28:13 -07002224 SkRect physicalPerspectiveBounds =
2225 physicalPerspectiveOutline.getBounds();
2226 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2227 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002228
2229 // TODO(edisonn): A better approach would be to use a bitmap shader
2230 // (in clamp mode) and draw a rect over the entire bounding box. Then
2231 // intersect perspectiveOutline to the clip. That will avoid introducing
2232 // alpha to the image while still giving good behavior at the edge of
2233 // the image. Avoiding alpha will reduce the pdf size and generation
2234 // CPU time some.
2235
halcanary7a14b312015-10-01 07:28:13 -07002236 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2237
Hal Canaryf50ff392016-09-30 10:25:39 -04002238 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002239 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002240 return;
2241 }
halcanary7a14b312015-10-01 07:28:13 -07002242 SkCanvas* canvas = surface->getCanvas();
2243 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002244
2245 SkScalar deltaX = bounds.left();
2246 SkScalar deltaY = bounds.top();
2247
Hal Canary7cbf5e32017-07-12 13:10:23 -04002248 SkMatrix offsetMatrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002249 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002250 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002251
2252 // Translate the draw in the new canvas, so we perfectly fit the
2253 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002254 canvas->setMatrix(offsetMatrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002255 canvas->drawImage(imageSubset.image(), 0, 0);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002256 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002257 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002258
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002259 // In the new space, we use the identity matrix translated
2260 // and scaled to reflect DPI.
2261 matrix.setScale(1 / scaleX, 1 / scaleY);
2262 matrix.postTranslate(deltaX, deltaY);
2263
Hal Canary7cbf5e32017-07-12 13:10:23 -04002264 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2265 if (!imageSubset) {
2266 return;
2267 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002268 }
2269
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002270 SkMatrix scaled;
2271 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002272 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2273 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002274 // Scale the image up from 1x1 to WxH.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002275 SkIRect subset = imageSubset.image()->bounds();
2276 scaled.postScale(SkIntToScalar(subset.width()),
2277 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002278 scaled.postConcat(matrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002279 ScopedContentEntry content(this, this->cs(), scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002280 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002281 return;
2282 }
2283 if (content.needShape()) {
2284 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002285 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002286 shape.transform(matrix);
2287 content.setShape(shape);
2288 }
2289 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002290 return;
2291 }
2292
halcanary287d22d2015-09-24 10:20:05 -07002293 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002294 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2295 imageSubset = SkKeyedImage(std::move(img));
2296 if (!imageSubset) {
2297 return;
2298 }
halcanary7a14b312015-10-01 07:28:13 -07002299 // TODO(halcanary): de-dupe this by caching filtered images.
2300 // (maybe in the resource cache?)
2301 }
halcanarya50151d2016-03-25 11:57:49 -07002302
Hal Canary7cbf5e32017-07-12 13:10:23 -04002303 SkBitmapKey key = imageSubset.key();
Hal Canary5c1b3602017-04-17 16:30:06 -04002304 sk_sp<SkPDFObject>* pdfimagePtr = fDocument->canon()->fPDFBitmapMap.find(key);
2305 sk_sp<SkPDFObject> pdfimage = pdfimagePtr ? *pdfimagePtr : nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002306 if (!pdfimage) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002307 SkASSERT(imageSubset);
2308 pdfimage = SkPDFCreateBitmapObject(imageSubset.release(),
Mike Reeda4daf192017-12-14 13:25:04 -05002309 fDocument->metadata().fEncodingQuality);
halcanary7a14b312015-10-01 07:28:13 -07002310 if (!pdfimage) {
2311 return;
halcanary287d22d2015-09-24 10:20:05 -07002312 }
halcanarya50151d2016-03-25 11:57:49 -07002313 fDocument->serialize(pdfimage); // serialize images early.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002314 SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
Hal Canary5c1b3602017-04-17 16:30:06 -04002315 fDocument->canon()->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002316 }
halcanarya50151d2016-03-25 11:57:49 -07002317 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
Hal Canary51329c92017-06-27 14:28:37 -04002318 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002319}
reede51c3562016-07-19 14:33:20 -07002320
2321///////////////////////////////////////////////////////////////////////////////////////////////////
2322
2323#include "SkSpecialImage.h"
2324#include "SkImageFilter.h"
2325
Florin Malita53f77bd2017-04-28 13:48:37 -04002326void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2327 SkImage* clipImage, const SkMatrix& clipMatrix) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05002328 if (this->hasEmptyClip()) {
2329 return;
2330 }
reede51c3562016-07-19 14:33:20 -07002331 SkASSERT(!srcImg->isTextureBacked());
2332
Florin Malita53f77bd2017-04-28 13:48:37 -04002333 //TODO: clipImage support
2334
reede51c3562016-07-19 14:33:20 -07002335 SkBitmap resultBM;
2336
2337 SkImageFilter* filter = paint.getImageFilter();
2338 if (filter) {
2339 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002340 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002341 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002342 const SkIRect clipBounds =
Hal Canary22b2d8c2017-07-19 14:46:12 -04002343 this->cs().bounds(this->bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002344 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
Brian Osmana50205f2018-07-06 13:57:01 -04002345 // TODO: Should PDF be operating in a specified color type/space? For now, run the filter
brianosman2a75e5d2016-09-22 07:15:37 -07002346 // in the same color space as the source (this is different from all other backends).
Brian Osmana50205f2018-07-06 13:57:01 -04002347 SkImageFilter::OutputProperties outputProperties(kN32_SkColorType, srcImg->getColorSpace());
brianosman2a75e5d2016-09-22 07:15:37 -07002348 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002349
2350 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2351 if (resultImg) {
2352 SkPaint tmpUnfiltered(paint);
2353 tmpUnfiltered.setImageFilter(nullptr);
2354 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002355 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002356 }
2357 }
2358 } else {
2359 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002360 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002361 }
2362 }
2363}
2364
2365sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2366 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2367}
2368
2369sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002370 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2371 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2372 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002373 SkColorSpace* legacyColorSpace = nullptr;
Hal Canary22b2d8c2017-07-19 14:46:12 -04002374 return SkSpecialImage::MakeFromImage(image->bounds(),
Brian Osman61624f02016-12-09 14:51:59 -05002375 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002376}
2377
2378sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002379 return nullptr;
2380}
brianosman04a44d02016-09-21 09:46:57 -07002381
2382SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2383 // We always return a transient cache, so it is freed after each
2384 // filter traversal.
2385 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2386}