blob: 709dc18b78df0ac630bf09a3e06b7d53419888c5 [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"
Hal Canary8f37ce52018-12-28 11:40:10 -050020#include "SkFontPriv.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000021#include "SkGlyphCache.h"
Herb Derby736db102018-07-19 12:52:16 -040022#include "SkGlyphRun.h"
brianosman04a44d02016-09-21 09:46:57 -070023#include "SkImageFilterCache.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040024#include "SkJpegEncoder.h"
halcanary022c2bd2016-09-02 11:29:46 -070025#include "SkMakeUnique.h"
Mike Reed80747ef2018-01-23 15:29:32 -050026#include "SkMaskFilterBase.h"
halcanarydb0dcc72015-03-20 12:31:52 -070027#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070028#include "SkPDFCanon.h"
Hal Canary23564b92018-09-07 14:33:14 -040029#include "SkPDFDocumentPriv.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000030#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000031#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000032#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000033#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000034#include "SkPDFShader.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000035#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000036#include "SkPDFUtils.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040037#include "SkPath.h"
38#include "SkPathEffect.h"
39#include "SkPathOps.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000040#include "SkRRect.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040041#include "SkRasterClip.h"
halcanary4871f222016-08-26 13:17:44 -070042#include "SkScopeExit.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000043#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070044#include "SkSurface.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000045#include "SkTemplates.h"
Florin Malitaab54e732018-07-27 09:47:15 -040046#include "SkTextBlob.h"
halcanarye06ca962016-09-09 05:34:55 -070047#include "SkTextFormatParams.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040048#include "SkTo.h"
Hal Canaryea60b952018-08-21 11:45:46 -040049#include "SkUTF.h"
halcanarya6814332015-05-27 08:53:36 -070050#include "SkXfermodeInterpretation.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040051
Hal Canary9e41c212018-09-03 12:00:23 -040052#include <vector>
53
Hal Canaryd12a6762017-05-26 17:01:16 -040054#ifndef SK_PDF_MASK_QUALITY
55 // If MASK_QUALITY is in [0,100], will be used for JpegEncoder.
56 // Otherwise, just encode masks losslessly.
57 #define SK_PDF_MASK_QUALITY 50
58 // Since these masks are used for blurry shadows, we shouldn't need
59 // high quality. Raise this value if your shadows have visible JPEG
60 // artifacts.
61 // If SkJpegEncoder::Encode fails, we will fall back to the lossless
62 // encoding.
63#endif
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000064
65// Utility functions
66
Hal Canaryd791a6f2018-09-28 12:14:08 -040067static SkPath to_path(const SkRect& r) {
68 SkPath p;
69 p.addRect(r);
70 return p;
71}
72
Hal Canary51329c92017-06-27 14:28:37 -040073// This function destroys the mask and either frees or takes the pixels.
74sk_sp<SkImage> mask_to_greyscale_image(SkMask* mask) {
75 sk_sp<SkImage> img;
76 SkPixmap pm(SkImageInfo::Make(mask->fBounds.width(), mask->fBounds.height(),
77 kGray_8_SkColorType, kOpaque_SkAlphaType),
78 mask->fImage, mask->fRowBytes);
79 const int imgQuality = SK_PDF_MASK_QUALITY;
80 if (imgQuality <= 100 && imgQuality >= 0) {
81 SkDynamicMemoryWStream buffer;
82 SkJpegEncoder::Options jpegOptions;
83 jpegOptions.fQuality = imgQuality;
84 if (SkJpegEncoder::Encode(&buffer, pm, jpegOptions)) {
85 img = SkImage::MakeFromEncoded(buffer.detachAsData());
86 SkASSERT(img);
87 if (img) {
88 SkMask::FreeImage(mask->fImage);
89 }
90 }
91 }
92 if (!img) {
93 img = SkImage::MakeFromRaster(pm, [](const void* p, void*) { SkMask::FreeImage((void*)p); },
94 nullptr);
95 }
96 *mask = SkMask(); // destructive;
97 return img;
98}
99
Hal Canaryd425a1d2017-07-12 13:13:51 -0400100sk_sp<SkImage> alpha_image_to_greyscale_image(const SkImage* mask) {
101 int w = mask->width(), h = mask->height();
102 SkBitmap greyBitmap;
103 greyBitmap.allocPixels(SkImageInfo::Make(w, h, kGray_8_SkColorType, kOpaque_SkAlphaType));
104 if (!mask->readPixels(SkImageInfo::MakeA8(w, h),
105 greyBitmap.getPixels(), greyBitmap.rowBytes(), 0, 0)) {
106 return nullptr;
107 }
108 return SkImage::MakeFromBitmap(greyBitmap);
109}
110
Hal Canary9a3f5542018-12-10 19:59:07 -0500111static int add_resource(SkTHashSet<SkPDFIndirectReference>& resources, SkPDFIndirectReference ref) {
112 resources.add(ref);
113 return ref.fValue;
114}
115
Mike Reeda1361362017-03-07 09:37:29 -0500116static void draw_points(SkCanvas::PointMode mode,
117 size_t count,
118 const SkPoint* points,
119 const SkPaint& paint,
120 const SkIRect& bounds,
121 const SkMatrix& ctm,
122 SkBaseDevice* device) {
123 SkRasterClip rc(bounds);
124 SkDraw draw;
125 draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(bounds.right(), bounds.bottom()), nullptr, 0);
126 draw.fMatrix = &ctm;
127 draw.fRC = &rc;
128 draw.drawPoints(mode, count, points, paint, device);
129}
130
reed374772b2016-10-05 17:33:02 -0700131// If the paint will definitely draw opaquely, replace kSrc with
132// kSrcOver. http://crbug.com/473572
halcanarya6814332015-05-27 08:53:36 -0700133static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
reed374772b2016-10-05 17:33:02 -0700134 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
135 paint->setBlendMode(SkBlendMode::kSrcOver);
halcanarya6814332015-05-27 08:53:36 -0700136 }
137}
138
Hal Canaryd12a6762017-05-26 17:01:16 -0400139// A shader's matrix is: CTMM x LocalMatrix x WrappingLocalMatrix. We want to
140// switch to device space, where CTM = I, while keeping the original behavior.
141//
142// I * LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
143// LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
144// InvLocalMatrix * LocalMatrix * NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
145// NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
146//
147static void transform_shader(SkPaint* paint, const SkMatrix& ctm) {
148 SkMatrix lm = SkPDFUtils::GetShaderLocalMatrix(paint->getShader());
149 SkMatrix lmInv;
150 if (lm.invert(&lmInv)) {
151 SkMatrix m = SkMatrix::Concat(SkMatrix::Concat(lmInv, ctm), lm);
152 paint->setShader(paint->getShader()->makeWithLocalMatrix(m));
153 }
154}
155
Hal Canary04ac4612018-10-10 13:09:43 -0400156static void emit_pdf_color(SkColor4f color, SkWStream* result) {
157 SkASSERT(color.fA == 1); // We handle alpha elsewhere.
158 SkPDFUtils::AppendColorComponentF(color.fR, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000159 result->writeText(" ");
Hal Canary04ac4612018-10-10 13:09:43 -0400160 SkPDFUtils::AppendColorComponentF(color.fG, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000161 result->writeText(" ");
Hal Canary04ac4612018-10-10 13:09:43 -0400162 SkPDFUtils::AppendColorComponentF(color.fB, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000163 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000164}
165
Hal Canaryd12a6762017-05-26 17:01:16 -0400166// If the paint has a color filter, apply the color filter to the shader or the
167// paint color. Remove the color filter.
168void remove_color_filter(SkPaint* paint) {
169 if (SkColorFilter* cf = paint->getColorFilter()) {
170 if (SkShader* shader = paint->getShader()) {
171 paint->setShader(shader->makeWithColorFilter(paint->refColorFilter()));
172 } else {
Hal Canary04ac4612018-10-10 13:09:43 -0400173 paint->setColor4f(cf->filterColor4f(paint->getColor4f(), nullptr), nullptr);
Hal Canaryd12a6762017-05-26 17:01:16 -0400174 }
175 paint->setColorFilter(nullptr);
176 }
177}
178
Hal Canary42137de2018-10-08 16:00:37 -0400179SkPDFDevice::GraphicStackState::GraphicStackState(SkDynamicMemoryWStream* s) : fContentStream(s) {
180}
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000181
Hal Canaryb400d4d2018-09-26 16:33:52 -0400182void SkPDFDevice::GraphicStackState::drainStack() {
183 if (fContentStream) {
184 while (fStackDepth) {
Hal Canaryb5b72792018-09-28 08:49:33 -0400185 this->pop();
Hal Canaryb400d4d2018-09-26 16:33:52 -0400186 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000187 }
Hal Canaryb400d4d2018-09-26 16:33:52 -0400188 SkASSERT(fStackDepth == 0);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000189}
190
Hal Canaryb400d4d2018-09-26 16:33:52 -0400191void SkPDFDevice::GraphicStackState::push() {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000192 SkASSERT(fStackDepth < kMaxStackDepth);
193 fContentStream->writeText("q\n");
194 fStackDepth++;
195 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
196}
197
Hal Canaryb400d4d2018-09-26 16:33:52 -0400198void SkPDFDevice::GraphicStackState::pop() {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000199 SkASSERT(fStackDepth > 0);
200 fContentStream->writeText("Q\n");
Hal Canaryb400d4d2018-09-26 16:33:52 -0400201 fEntries[fStackDepth] = SkPDFDevice::GraphicStateEntry();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000202 fStackDepth--;
203}
204
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000205/* Calculate an inverted path's equivalent non-inverted path, given the
206 * canvas bounds.
207 * outPath may alias with invPath (since this is supported by PathOps).
208 */
209static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
210 SkPath* outPath) {
211 SkASSERT(invPath.isInverseFillType());
Hal Canaryd791a6f2018-09-28 12:14:08 -0400212 return Op(to_path(bounds), invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000213}
214
Hal Canaryd00ef062018-06-05 11:53:58 -0400215static SkRect rect_intersect(SkRect u, SkRect v) {
216 if (u.isEmpty() || v.isEmpty()) { return {0, 0, 0, 0}; }
217 return u.intersect(v) ? u : SkRect{0, 0, 0, 0};
218}
219
220// Test to see if the clipstack is a simple rect, If so, we can avoid all PathOps code
221// and speed thing up.
222static bool is_rect(const SkClipStack& clipStack, const SkRect& bounds, SkRect* dst) {
223 SkRect currentClip = bounds;
224 SkClipStack::Iter iter(clipStack, SkClipStack::Iter::kBottom_IterStart);
225 while (const SkClipStack::Element* element = iter.next()) {
226 SkRect elementRect{0, 0, 0, 0};
227 switch (element->getDeviceSpaceType()) {
228 case SkClipStack::Element::DeviceSpaceType::kEmpty:
229 break;
230 case SkClipStack::Element::DeviceSpaceType::kRect:
231 elementRect = element->getDeviceSpaceRect();
232 break;
233 default:
234 return false;
235 }
236 switch (element->getOp()) {
237 case kReplace_SkClipOp:
238 currentClip = rect_intersect(bounds, elementRect);
239 break;
240 case SkClipOp::kIntersect:
241 currentClip = rect_intersect(currentClip, elementRect);
242 break;
243 default:
244 return false;
245 }
246 }
247 *dst = currentClip;
248 return true;
249}
250
251static void append_clip(const SkClipStack& clipStack,
252 const SkIRect& bounds,
253 SkWStream* wStream) {
254 // The bounds are slightly outset to ensure this is correct in the
255 // face of floating-point accuracy and possible SkRegion bitmap
256 // approximations.
257 SkRect outsetBounds = SkRect::Make(bounds.makeOutset(1, 1));
258
259 SkRect clipStackRect;
260 if (is_rect(clipStack, outsetBounds, &clipStackRect)) {
261 SkPDFUtils::AppendRectangle(clipStackRect, wStream);
262 wStream->writeText("W* n\n");
263 return;
264 }
265
266 SkPath clipPath;
267 (void)clipStack.asPath(&clipPath);
268
Hal Canaryd791a6f2018-09-28 12:14:08 -0400269 if (Op(clipPath, to_path(outsetBounds), kIntersect_SkPathOp, &clipPath)) {
Hal Canaryd00ef062018-06-05 11:53:58 -0400270 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, wStream);
271 SkPath::FillType clipFill = clipPath.getFillType();
272 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
273 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
274 if (clipFill == SkPath::kEvenOdd_FillType) {
275 wStream->writeText("W* n\n");
276 } else {
277 wStream->writeText("W n\n");
278 }
279 }
280 // If Op() fails (pathological case; e.g. input values are
281 // extremely large or NaN), emit no clip at all.
282}
283
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000284// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000285// graphic state stack, and the fact that we can know all the clips used
286// on the page to optimize this.
Hal Canaryb400d4d2018-09-26 16:33:52 -0400287void SkPDFDevice::GraphicStackState::updateClip(const SkClipStack* clipStack,
288 const SkIRect& bounds) {
289 uint32_t clipStackGenID = clipStack ? clipStack->getTopmostGenID()
290 : SkClipStack::kWideOpenGenID;
291 if (clipStackGenID == currentEntry()->fClipStackGenID) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000292 return;
293 }
294
295 while (fStackDepth > 0) {
Hal Canaryb5b72792018-09-28 08:49:33 -0400296 this->pop();
Hal Canaryb400d4d2018-09-26 16:33:52 -0400297 if (clipStackGenID == currentEntry()->fClipStackGenID) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000298 return;
299 }
300 }
Hal Canaryb5b72792018-09-28 08:49:33 -0400301 SkASSERT(currentEntry()->fClipStackGenID == SkClipStack::kWideOpenGenID);
Hal Canaryb400d4d2018-09-26 16:33:52 -0400302 if (clipStackGenID != SkClipStack::kWideOpenGenID) {
303 SkASSERT(clipStack);
Hal Canaryb5b72792018-09-28 08:49:33 -0400304 this->push();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000305
Hal Canaryb400d4d2018-09-26 16:33:52 -0400306 currentEntry()->fClipStackGenID = clipStackGenID;
307 append_clip(*clipStack, bounds, fContentStream);
308 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000309}
310
Hal Canarye650b852018-09-12 09:12:36 -0400311static void append_transform(const SkMatrix& matrix, SkWStream* content) {
312 SkScalar values[6];
313 if (!matrix.asAffine(values)) {
314 SkMatrix::SetAffineIdentity(values);
315 }
316 for (SkScalar v : values) {
317 SkPDFUtils::AppendScalar(v, content);
318 content->writeText(" ");
319 }
320 content->writeText("cm\n");
321}
322
Hal Canaryb400d4d2018-09-26 16:33:52 -0400323void SkPDFDevice::GraphicStackState::updateMatrix(const SkMatrix& matrix) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000324 if (matrix == currentEntry()->fMatrix) {
325 return;
326 }
327
328 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
329 SkASSERT(fStackDepth > 0);
Hal Canaryb400d4d2018-09-26 16:33:52 -0400330 SkASSERT(fEntries[fStackDepth].fClipStackGenID ==
331 fEntries[fStackDepth -1].fClipStackGenID);
Hal Canaryb5b72792018-09-28 08:49:33 -0400332 this->pop();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000333
334 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
335 }
336 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
337 return;
338 }
339
Hal Canaryb5b72792018-09-28 08:49:33 -0400340 this->push();
Hal Canarye650b852018-09-12 09:12:36 -0400341 append_transform(matrix, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000342 currentEntry()->fMatrix = matrix;
343}
344
Hal Canaryb400d4d2018-09-26 16:33:52 -0400345void SkPDFDevice::GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000346 // PDF treats a shader as a color, so we only set one or the other.
347 if (state.fShaderIndex >= 0) {
348 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000349 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000350 currentEntry()->fShaderIndex = state.fShaderIndex;
351 }
352 } else {
353 if (state.fColor != currentEntry()->fColor ||
354 currentEntry()->fShaderIndex >= 0) {
355 emit_pdf_color(state.fColor, fContentStream);
356 fContentStream->writeText("RG ");
357 emit_pdf_color(state.fColor, fContentStream);
358 fContentStream->writeText("rg\n");
359 currentEntry()->fColor = state.fColor;
360 currentEntry()->fShaderIndex = -1;
361 }
362 }
363
364 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000365 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000366 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
367 }
368
369 if (state.fTextScaleX) {
370 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
Hal Canary9b491b22017-11-28 15:10:13 -0500371 SkScalar pdfScale = state.fTextScaleX * 100;
halcanarybc4696b2015-05-06 10:56:04 -0700372 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000373 fContentStream->writeText(" Tz\n");
374 currentEntry()->fTextScaleX = state.fTextScaleX;
375 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000376 }
377}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000378
Hal Canary8cb73762019-01-09 09:46:43 -0500379SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700380 // PDF does not support image filters, so render them on CPU.
381 // Note that this rendering is done at "screen" resolution (100dpi), not
382 // printer resolution.
Hal Canary8cb73762019-01-09 09:46:43 -0500383
halcanary7a14b312015-10-01 07:28:13 -0700384 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800385 // to improve quality and file size (https://bug.skia.org/3043)
Hal Canary8cb73762019-01-09 09:46:43 -0500386 if (layerPaint && (layerPaint->getImageFilter() || layerPaint->getColorFilter())) {
reed7503d602016-07-15 14:23:29 -0700387 // need to return a raster device, which we will detect in drawDevice()
388 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700389 }
Hal Canary22b2d8c2017-07-19 14:46:12 -0400390 return new SkPDFDevice(cinfo.fInfo.dimensions(), fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000391}
392
halcanary989da4a2016-03-21 14:33:17 -0700393SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
394
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000395// A helper class to automatically finish a ContentEntry at the end of a
396// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000397class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000398public:
Mike Reeda1361362017-03-07 09:37:29 -0500399 ScopedContentEntry(SkPDFDevice* device,
Hal Canaryd892a9d2018-09-24 21:20:47 -0400400 const SkClipStack* clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000401 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500402 const SkPaint& paint,
Hal Canary8f37ce52018-12-28 11:40:10 -0500403 SkScalar textScale = 0)
Mike Reeda1361362017-03-07 09:37:29 -0500404 : fDevice(device)
Mike Reeda1361362017-03-07 09:37:29 -0500405 , fBlendMode(SkBlendMode::kSrcOver)
Hal Canaryb400d4d2018-09-26 16:33:52 -0400406 , fClipStack(clipStack)
Mike Reeda1361362017-03-07 09:37:29 -0500407 {
408 if (matrix.hasPerspective()) {
409 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
410 return;
411 }
412 fBlendMode = paint.getBlendMode();
Hal Canary42137de2018-10-08 16:00:37 -0400413 fContentStream =
Hal Canary8f37ce52018-12-28 11:40:10 -0500414 fDevice->setUpContentEntry(clipStack, matrix, paint, textScale, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000415 }
Hal Canary8f37ce52018-12-28 11:40:10 -0500416 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, SkScalar textScale = 0)
417 : ScopedContentEntry(dev, &dev->cs(), dev->ctm(), paint, textScale) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000418
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000419 ~ScopedContentEntry() {
Hal Canary42137de2018-10-08 16:00:37 -0400420 if (fContentStream) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000421 SkPath* shape = &fShape;
422 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700423 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000424 }
Hal Canary9a3f5542018-12-10 19:59:07 -0500425 fDevice->finishContentEntry(fClipStack, fBlendMode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000426 }
427 }
428
Hal Canary42137de2018-10-08 16:00:37 -0400429 explicit operator bool() const { return fContentStream != nullptr; }
430 SkDynamicMemoryWStream* stream() { return fContentStream; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000431
432 /* Returns true when we explicitly need the shape of the drawing. */
433 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700434 switch (fBlendMode) {
435 case SkBlendMode::kClear:
436 case SkBlendMode::kSrc:
437 case SkBlendMode::kSrcIn:
438 case SkBlendMode::kSrcOut:
439 case SkBlendMode::kDstIn:
440 case SkBlendMode::kDstOut:
441 case SkBlendMode::kSrcATop:
442 case SkBlendMode::kDstATop:
443 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000444 return true;
445 default:
446 return false;
447 }
448 }
449
450 /* Returns true unless we only need the shape of the drawing. */
451 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700452 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000453 return false;
454 }
455 return true;
456 }
457
458 /* If the shape is different than the alpha component of the content, then
459 * setShape should be called with the shape. In particular, images and
460 * devices have rectangular shape.
461 */
462 void setShape(const SkPath& shape) {
463 fShape = shape;
464 }
465
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000466private:
Hal Canary42137de2018-10-08 16:00:37 -0400467 SkPDFDevice* fDevice = nullptr;
468 SkDynamicMemoryWStream* fContentStream = nullptr;
reed374772b2016-10-05 17:33:02 -0700469 SkBlendMode fBlendMode;
Hal Canary9a3f5542018-12-10 19:59:07 -0500470 SkPDFIndirectReference fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000471 SkPath fShape;
Hal Canaryb400d4d2018-09-26 16:33:52 -0400472 const SkClipStack* fClipStack;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000473};
474
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000475////////////////////////////////////////////////////////////////////////////////
476
Hal Canary7d06ab22018-09-10 14:39:13 -0400477SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc, const SkMatrix& transform)
reed589a39e2016-08-20 07:59:19 -0700478 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
479 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
Hal Canary7d06ab22018-09-10 14:39:13 -0400480 , fInitialTransform(transform)
Dominic Mazzoni656cefe2018-09-25 20:29:15 -0700481 , fNodeId(0)
Hal Canarya0622582017-06-29 18:51:35 -0400482 , fDocument(doc)
483{
Hal Canary22b2d8c2017-07-19 14:46:12 -0400484 SkASSERT(!pageSize.isEmpty());
Hal Canarya0622582017-06-29 18:51:35 -0400485}
robertphillips1f3923e2016-07-21 07:17:54 -0700486
Hal Canary9e41c212018-09-03 12:00:23 -0400487SkPDFDevice::~SkPDFDevice() = default;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000488
Hal Canary9e41c212018-09-03 12:00:23 -0400489void SkPDFDevice::reset() {
Hal Canary9e41c212018-09-03 12:00:23 -0400490 fLinkToURLs = std::vector<RectWithData>();
491 fLinkToDestinations = std::vector<RectWithData>();
492 fNamedDestinations = std::vector<NamedDestination>();
Hal Canary9a3f5542018-12-10 19:59:07 -0500493 fGraphicStateResources.reset();
494 fXObjectResources.reset();
495 fShaderResources.reset();
Hal Canaryb10f92e2018-11-16 17:01:50 -0500496 fFontResources.reset();
Hal Canary42137de2018-10-08 16:00:37 -0400497 fContent.reset();
Hal Canary813b5ac2018-09-28 12:30:37 -0400498 fActiveStackState = GraphicStackState();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000499}
500
Mike Reeda1361362017-03-07 09:37:29 -0500501void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500502 if (!value) {
503 return;
504 }
505 if (rect.isEmpty()) {
Dominic Mazzoni656cefe2018-09-25 20:29:15 -0700506 if (!strcmp(key, SkPDFGetNodeIdKey())) {
507 int nodeID;
508 if (value->size() != sizeof(nodeID)) { return; }
509 memcpy(&nodeID, value->data(), sizeof(nodeID));
510 fNodeId = nodeID;
511 return;
512 }
Mike Reeda1361362017-03-07 09:37:29 -0500513 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
514 SkPoint transformedPoint;
515 this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
Hal Canary5c1b3602017-04-17 16:30:06 -0400516 fNamedDestinations.emplace_back(NamedDestination{sk_ref_sp(value), transformedPoint});
Mike Reeda1361362017-03-07 09:37:29 -0500517 }
518 return;
519 }
520 // Convert to path to handle non-90-degree rotations.
Hal Canaryd791a6f2018-09-28 12:14:08 -0400521 SkPath path = to_path(rect);
Mike Reeda1361362017-03-07 09:37:29 -0500522 path.transform(this->ctm(), &path);
523 SkPath clip;
524 (void)this->cs().asPath(&clip);
525 Op(clip, path, kIntersect_SkPathOp, &path);
526 // PDF wants a rectangle only.
527 SkRect transformedRect = path.getBounds();
528 if (transformedRect.isEmpty()) {
529 return;
530 }
531 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400532 fLinkToURLs.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
Mike Reeda1361362017-03-07 09:37:29 -0500533 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400534 fLinkToDestinations.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
reedf70b5312016-03-04 16:36:20 -0800535 }
536}
537
Hal Canaryd12a6762017-05-26 17:01:16 -0400538void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
Hal Canaryabf8e412018-09-24 11:37:23 -0400539 SkMatrix inverse;
540 if (!this->ctm().invert(&inverse)) {
541 return;
542 }
543 SkRect bbox = this->cs().bounds(this->bounds());
544 inverse.mapRect(&bbox);
545 bbox.roundOut(&bbox);
Hal Canaryb4e528d2018-03-09 16:02:15 -0500546 if (this->hasEmptyClip()) {
547 return;
548 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400549 SkPaint newPaint = srcPaint;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000550 newPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryabf8e412018-09-24 11:37:23 -0400551 this->drawRect(bbox, newPaint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000552}
553
Mike Reeda1361362017-03-07 09:37:29 -0500554void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700555 size_t count,
556 const SkPoint* points,
557 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500558 if (this->hasEmptyClip()) {
559 return;
560 }
halcanarya6814332015-05-27 08:53:36 -0700561 SkPaint passedPaint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400562 remove_color_filter(&passedPaint);
halcanarya6814332015-05-27 08:53:36 -0700563 replace_srcmode_on_opaque_paint(&passedPaint);
Hal Canary80fa7ce2017-06-28 16:04:20 -0400564 if (SkCanvas::kPoints_PointMode != mode) {
565 passedPaint.setStyle(SkPaint::kStroke_Style);
566 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000567 if (count == 0) {
568 return;
569 }
570
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000571 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
572 // We only use this when there's a path effect because of the overhead
573 // of multiple calls to setUpContentEntry it causes.
574 if (passedPaint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500575 draw_points(mode, count, points, passedPaint,
576 this->devClipBounds(), this->ctm(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000577 return;
578 }
579
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000580 const SkPaint* paint = &passedPaint;
581 SkPaint modifiedPaint;
582
583 if (mode == SkCanvas::kPoints_PointMode &&
584 paint->getStrokeCap() != SkPaint::kRound_Cap) {
585 modifiedPaint = *paint;
586 paint = &modifiedPaint;
587 if (paint->getStrokeWidth()) {
588 // PDF won't draw a single point with square/butt caps because the
589 // orientation is ambiguous. Draw a rectangle instead.
590 modifiedPaint.setStyle(SkPaint::kFill_Style);
591 SkScalar strokeWidth = paint->getStrokeWidth();
592 SkScalar halfStroke = SkScalarHalf(strokeWidth);
593 for (size_t i = 0; i < count; i++) {
594 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
595 r.inset(-halfStroke, -halfStroke);
Mike Reeda1361362017-03-07 09:37:29 -0500596 this->drawRect(r, modifiedPaint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000597 }
598 return;
599 } else {
600 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
601 }
602 }
603
Mike Reeda1361362017-03-07 09:37:29 -0500604 ScopedContentEntry content(this, *paint);
Hal Canary42137de2018-10-08 16:00:37 -0400605 if (!content) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000606 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000607 }
Hal Canary51329c92017-06-27 14:28:37 -0400608 SkDynamicMemoryWStream* contentStream = content.stream();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000609 switch (mode) {
610 case SkCanvas::kPolygon_PointMode:
Hal Canary51329c92017-06-27 14:28:37 -0400611 SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000612 for (size_t i = 1; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400613 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000614 }
Hal Canary51329c92017-06-27 14:28:37 -0400615 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000616 break;
617 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000618 for (size_t i = 0; i < count/2; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400619 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
620 SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
621 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000622 }
623 break;
624 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000625 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
626 for (size_t i = 0; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400627 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
628 SkPDFUtils::ClosePath(contentStream);
629 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000630 }
631 break;
632 default:
633 SkASSERT(false);
634 }
635}
636
Hal Canary74801582018-12-18 16:30:41 -0500637static std::unique_ptr<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
638 auto annotation = SkPDFMakeDict("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700639 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700640 annotation->insertInt("F", 4); // required by ISO 19005
Hal Canarye650b852018-09-12 09:12:36 -0400641 // Border: 0 = Horizontal corner radius.
642 // 0 = Vertical corner radius.
643 // 0 = Width, 0 = no border.
644 annotation->insertObject("Border", SkPDFMakeArray(0, 0, 0));
wangxianzhud76665d2015-07-17 17:23:15 -0700645
Hal Canarye650b852018-09-12 09:12:36 -0400646 annotation->insertObject("Rect", SkPDFMakeArray(translatedRect.fLeft,
647 translatedRect.fTop,
648 translatedRect.fRight,
649 translatedRect.fBottom));
halcanary8103a342016-03-08 15:10:16 -0800650 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700651}
652
Hal Canary74801582018-12-18 16:30:41 -0500653static std::unique_ptr<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
654 std::unique_ptr<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700655 SkString url(static_cast<const char *>(urlData->data()),
656 urlData->size() - 1);
Hal Canary74801582018-12-18 16:30:41 -0500657 auto action = SkPDFMakeDict("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700658 action->insertName("S", "URI");
659 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800660 annotation->insertObject("A", std::move(action));
661 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700662}
663
Hal Canary74801582018-12-18 16:30:41 -0500664static std::unique_ptr<SkPDFDict> create_link_named_dest(const SkData* nameData,
665 const SkRect& r) {
666 std::unique_ptr<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700667 SkString name(static_cast<const char *>(nameData->data()),
668 nameData->size() - 1);
669 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800670 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700671}
672
Mike Reeda1361362017-03-07 09:37:29 -0500673void SkPDFDevice::drawRect(const SkRect& rect,
halcanarya6814332015-05-27 08:53:36 -0700674 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500675 if (this->hasEmptyClip()) {
676 return;
677 }
halcanarya6814332015-05-27 08:53:36 -0700678 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400679 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700680 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000681 SkRect r = rect;
682 r.sort();
683
Hal Canary8b354dc2018-09-20 12:51:22 -0400684 if (paint.getPathEffect() || paint.getMaskFilter() || this->ctm().hasPerspective()) {
Hal Canaryd791a6f2018-09-28 12:14:08 -0400685 this->drawPath(to_path(r), paint, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000686 return;
687 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000688
Mike Reeda1361362017-03-07 09:37:29 -0500689 ScopedContentEntry content(this, paint);
Hal Canary42137de2018-10-08 16:00:37 -0400690 if (!content) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000691 return;
692 }
Hal Canary51329c92017-06-27 14:28:37 -0400693 SkPDFUtils::AppendRectangle(r, content.stream());
694 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000695}
696
Mike Reeda1361362017-03-07 09:37:29 -0500697void SkPDFDevice::drawRRect(const SkRRect& rrect,
halcanarya6814332015-05-27 08:53:36 -0700698 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500699 if (this->hasEmptyClip()) {
700 return;
701 }
halcanarya6814332015-05-27 08:53:36 -0700702 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400703 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700704 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000705 SkPath path;
706 path.addRRect(rrect);
Robert Phillips137ca522018-08-15 10:14:33 -0400707 this->drawPath(path, paint, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000708}
709
Mike Reeda1361362017-03-07 09:37:29 -0500710void SkPDFDevice::drawOval(const SkRect& oval,
halcanarya6814332015-05-27 08:53:36 -0700711 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500712 if (this->hasEmptyClip()) {
713 return;
714 }
halcanarya6814332015-05-27 08:53:36 -0700715 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400716 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700717 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700718 SkPath path;
719 path.addOval(oval);
Robert Phillips137ca522018-08-15 10:14:33 -0400720 this->drawPath(path, paint, true);
reed89443ab2014-06-27 11:34:19 -0700721}
722
Mike Reeda1361362017-03-07 09:37:29 -0500723void SkPDFDevice::drawPath(const SkPath& origPath,
halcanarya6814332015-05-27 08:53:36 -0700724 const SkPaint& srcPaint,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000725 bool pathIsMutable) {
Robert Phillips137ca522018-08-15 10:14:33 -0400726 this->internalDrawPath(this->cs(), this->ctm(), origPath, srcPaint, pathIsMutable);
Mike Reeda1361362017-03-07 09:37:29 -0500727}
728
Hal Canaryd12a6762017-05-26 17:01:16 -0400729void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
730 const SkMatrix& ctm,
731 const SkPath& origPath,
Robert Phillips137ca522018-08-15 10:14:33 -0400732 const SkPaint& origPaint) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400733 SkASSERT(origPaint.getMaskFilter());
734 SkPath path(origPath);
735 SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
Robert Phillips137ca522018-08-15 10:14:33 -0400736
Hal Canaryd12a6762017-05-26 17:01:16 -0400737 SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
738 ? SkStrokeRec::kFill_InitStyle
739 : SkStrokeRec::kHairline_InitStyle;
740 path.transform(ctm, &path);
741
Hal Canary22b2d8c2017-07-19 14:46:12 -0400742 SkIRect bounds = clipStack.bounds(this->bounds()).roundOut();
Hal Canaryd12a6762017-05-26 17:01:16 -0400743 SkMask sourceMask;
744 if (!SkDraw::DrawToMask(path, &bounds, paint->getMaskFilter(), &SkMatrix::I(),
745 &sourceMask, SkMask::kComputeBoundsAndRenderImage_CreateMode,
746 initStyle)) {
747 return;
748 }
749 SkAutoMaskFreeImage srcAutoMaskFreeImage(sourceMask.fImage);
750 SkMask dstMask;
751 SkIPoint margin;
Mike Reed80747ef2018-01-23 15:29:32 -0500752 if (!as_MFB(paint->getMaskFilter())->filterMask(&dstMask, sourceMask, ctm, &margin)) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400753 return;
754 }
Hal Canary51329c92017-06-27 14:28:37 -0400755 SkIRect dstMaskBounds = dstMask.fBounds;
756 sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
Hal Canaryd12a6762017-05-26 17:01:16 -0400757 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
758 // Must mask with a Form XObject.
Hal Canary51329c92017-06-27 14:28:37 -0400759 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
Hal Canaryd12a6762017-05-26 17:01:16 -0400760 {
Herb Derbyefe39bc2018-05-01 17:06:20 -0400761 SkCanvas canvas(maskDevice);
Hal Canary51329c92017-06-27 14:28:37 -0400762 canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
Hal Canaryd12a6762017-05-26 17:01:16 -0400763 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400764 if (!ctm.isIdentity() && paint->getShader()) {
765 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
766 }
Hal Canaryd892a9d2018-09-24 21:20:47 -0400767 ScopedContentEntry content(this, &clipStack, SkMatrix::I(), *paint);
Hal Canary42137de2018-10-08 16:00:37 -0400768 if (!content) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400769 return;
770 }
Hal Canary51329c92017-06-27 14:28:37 -0400771 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
772 SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
773 SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
774 this->clearMaskOnGraphicState(content.stream());
775}
Hal Canaryd12a6762017-05-26 17:01:16 -0400776
Hal Canary9a3f5542018-12-10 19:59:07 -0500777void SkPDFDevice::setGraphicState(SkPDFIndirectReference gs, SkDynamicMemoryWStream* content) {
778 SkPDFUtils::ApplyGraphicState(add_resource(fGraphicStateResources, gs), content);
Hal Canary3b8b11e2018-09-29 22:31:34 -0400779}
780
Hal Canary51329c92017-06-27 14:28:37 -0400781void SkPDFDevice::addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,
782 SkDynamicMemoryWStream* contentStream) {
Hal Canary3b8b11e2018-09-29 22:31:34 -0400783 this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
Hal Canaryb4bd5ef2017-07-26 09:16:01 -0400784 maskDevice->makeFormXObjectFromDevice(true), false,
Hal Canary9a3f5542018-12-10 19:59:07 -0500785 SkPDFGraphicState::kLuminosity_SMaskMode, fDocument), contentStream);
Hal Canary51329c92017-06-27 14:28:37 -0400786}
Hal Canaryd12a6762017-05-26 17:01:16 -0400787
Hal Canary51329c92017-06-27 14:28:37 -0400788void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400789 // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
Hal Canary9a3f5542018-12-10 19:59:07 -0500790 SkPDFIndirectReference& noSMaskGS = this->getCanon()->fNoSmaskGraphicState;
Hal Canaryc02de0b2017-06-28 13:14:03 -0400791 if (!noSMaskGS) {
Hal Canary9a3f5542018-12-10 19:59:07 -0500792 SkPDFDict tmp("ExtGState");
793 tmp.insertName("SMask", "None");
794 noSMaskGS = fDocument->emit(tmp);
Hal Canaryc02de0b2017-06-28 13:14:03 -0400795 }
Hal Canary3b8b11e2018-09-29 22:31:34 -0400796 this->setGraphicState(noSMaskGS, contentStream);
Hal Canaryd12a6762017-05-26 17:01:16 -0400797}
798
Mike Reeda1361362017-03-07 09:37:29 -0500799void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
800 const SkMatrix& ctm,
801 const SkPath& origPath,
802 const SkPaint& srcPaint,
Mike Reeda1361362017-03-07 09:37:29 -0500803 bool pathIsMutable) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500804 if (clipStack.isEmpty(this->bounds())) {
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);
halcanary682ee012016-01-28 10:59:34 -0800810 SkPath modifiedPath;
811 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000812
Hal Canaryd12a6762017-05-26 17:01:16 -0400813 if (paint.getMaskFilter()) {
Robert Phillips137ca522018-08-15 10:14:33 -0400814 this->internalDrawPathWithFilter(clipStack, ctm, origPath, paint);
Hal Canaryd12a6762017-05-26 17:01:16 -0400815 return;
816 }
817
Mike Reeda1361362017-03-07 09:37:29 -0500818 SkMatrix matrix = ctm;
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000819
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000820 if (paint.getPathEffect()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400821 if (clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000822 return;
823 }
halcanary682ee012016-01-28 10:59:34 -0800824 if (!pathIsMutable) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400825 modifiedPath = origPath;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000826 pathPtr = &modifiedPath;
827 pathIsMutable = true;
828 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400829 if (paint.getFillPath(*pathPtr, pathPtr)) {
830 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000831 } else {
Hal Canaryd12a6762017-05-26 17:01:16 -0400832 paint.setStyle(SkPaint::kStroke_Style);
833 paint.setStrokeWidth(0);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000834 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400835 paint.setPathEffect(nullptr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000836 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000837
Robert Phillips137ca522018-08-15 10:14:33 -0400838 if (this->handleInversePath(*pathPtr, paint, pathIsMutable)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000839 return;
840 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400841 if (matrix.getType() & SkMatrix::kPerspective_Mask) {
842 if (!pathIsMutable) {
843 modifiedPath = origPath;
844 pathPtr = &modifiedPath;
845 pathIsMutable = true;
846 }
847 pathPtr->transform(matrix);
848 if (paint.getShader()) {
849 transform_shader(&paint, matrix);
850 }
851 matrix = SkMatrix::I();
852 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000853
Hal Canaryd892a9d2018-09-24 21:20:47 -0400854 ScopedContentEntry content(this, &clipStack, matrix, paint);
Hal Canary42137de2018-10-08 16:00:37 -0400855 if (!content) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000856 return;
857 }
Hal Canarydfaa0572017-11-27 09:33:44 -0500858 constexpr SkScalar kToleranceScale = 0.0625f; // smaller = better conics (circles).
Hal Canary385468f2017-02-13 11:03:23 -0500859 SkScalar matrixScale = matrix.mapRadius(1.0f);
Hal Canarydfaa0572017-11-27 09:33:44 -0500860 SkScalar tolerance = matrixScale > 0.0f ? kToleranceScale / matrixScale : kToleranceScale;
halcanary8b2bc252015-10-06 09:41:47 -0700861 bool consumeDegeratePathSegments =
862 paint.getStyle() == SkPaint::kFill_Style ||
863 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
864 paint.getStrokeCap() != SkPaint::kSquare_Cap);
Hal Canary51329c92017-06-27 14:28:37 -0400865 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(), consumeDegeratePathSegments, content.stream(),
Hal Canary385468f2017-02-13 11:03:23 -0500866 tolerance);
Hal Canary51329c92017-06-27 14:28:37 -0400867 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000868}
869
Hal Canary7cbf5e32017-07-12 13:10:23 -0400870////////////////////////////////////////////////////////////////////////////////
Hal Canaryf50ff392016-09-30 10:25:39 -0400871
Mike Reeda1361362017-03-07 09:37:29 -0500872void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400873 const SkRect* src,
874 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400875 const SkPaint& paint,
Hal Canaryf50ff392016-09-30 10:25:39 -0400876 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400877 SkASSERT(image);
878 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
879 src, dst, paint, this->ctm());
Hal Canaryf50ff392016-09-30 10:25:39 -0400880}
881
Hal Canary7cbf5e32017-07-12 13:10:23 -0400882void SkPDFDevice::drawBitmapRect(const SkBitmap& bm,
halcanary7a14b312015-10-01 07:28:13 -0700883 const SkRect* src,
884 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400885 const SkPaint& paint,
Mike Reeda1361362017-03-07 09:37:29 -0500886 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400887 SkASSERT(!bm.drawsNothing());
888 this->internalDrawImageRect(SkKeyedImage(bm), src, dst, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700889}
890
Hal Canary7cbf5e32017-07-12 13:10:23 -0400891void SkPDFDevice::drawBitmap(const SkBitmap& bm, SkScalar x, SkScalar y, const SkPaint& paint) {
892 SkASSERT(!bm.drawsNothing());
893 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
894 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700895}
896
Hal Canary7cbf5e32017-07-12 13:10:23 -0400897void SkPDFDevice::drawSprite(const SkBitmap& bm, int x, int y, const SkPaint& paint) {
898 SkASSERT(!bm.drawsNothing());
899 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
900 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, SkMatrix::I());
halcanary7a14b312015-10-01 07:28:13 -0700901}
902
Hal Canary7cbf5e32017-07-12 13:10:23 -0400903void SkPDFDevice::drawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint& paint) {
904 SkASSERT(image);
905 auto r = SkRect::MakeXYWH(x, y, image->width(), image->height());
906 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
907 nullptr, r, paint, this->ctm());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000908}
909
Hal Canary7cbf5e32017-07-12 13:10:23 -0400910////////////////////////////////////////////////////////////////////////////////
911
halcanaryf0c30f52016-07-15 13:35:45 -0700912namespace {
913class GlyphPositioner {
914public:
915 GlyphPositioner(SkDynamicMemoryWStream* content,
916 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -0700917 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -0700918 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -0700919 , fCurrentMatrixOrigin(origin)
Hal Canary8ef78ea2018-10-01 13:38:30 -0400920 , fTextSkewX(textSkewX) {
halcanaryf0c30f52016-07-15 13:35:45 -0700921 }
halcanary4871f222016-08-26 13:17:44 -0700922 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -0700923 void flush() {
924 if (fInText) {
925 fContent->writeText("> Tj\n");
926 fInText = false;
927 }
928 }
Hal Canary8ef78ea2018-10-01 13:38:30 -0400929 void setWideChars(bool wide) {
930 this->flush();
931 fWideChars = wide;
932 }
halcanary4871f222016-08-26 13:17:44 -0700933 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -0700934 SkScalar advanceWidth,
935 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -0700936 if (!fInitialized) {
937 // Flip the text about the x-axis to account for origin swap and include
938 // the passed parameters.
939 fContent->writeText("1 0 ");
940 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
941 fContent->writeText(" -1 ");
942 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
943 fContent->writeText(" ");
944 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
945 fContent->writeText(" Tm\n");
946 fCurrentMatrixOrigin.set(0.0f, 0.0f);
947 fInitialized = true;
948 }
Hal Canary98caedd2018-07-23 10:50:49 -0400949 SkPoint position = xy - fCurrentMatrixOrigin;
950 if (position != SkPoint{fXAdvance, 0}) {
951 this->flush();
952 SkPDFUtils::AppendScalar(position.x() - position.y() * fTextSkewX, fContent);
953 fContent->writeText(" ");
954 SkPDFUtils::AppendScalar(-position.y(), fContent);
955 fContent->writeText(" Td ");
956 fCurrentMatrixOrigin = xy;
957 fXAdvance = 0;
halcanaryf0c30f52016-07-15 13:35:45 -0700958 }
Hal Canary98caedd2018-07-23 10:50:49 -0400959 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -0700960 if (!fInText) {
961 fContent->writeText("<");
962 fInText = true;
963 }
964 if (fWideChars) {
965 SkPDFUtils::WriteUInt16BE(fContent, glyph);
966 } else {
967 SkASSERT(0 == glyph >> 8);
968 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
969 }
halcanaryf0c30f52016-07-15 13:35:45 -0700970 }
971
972private:
973 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -0700974 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -0700975 SkScalar fXAdvance = 0.0f;
976 SkScalar fTextSkewX;
Hal Canary8ef78ea2018-10-01 13:38:30 -0400977 bool fWideChars = true;
halcanaryc2f9ec12016-09-12 08:55:29 -0700978 bool fInText = false;
979 bool fInitialized = false;
halcanaryf0c30f52016-07-15 13:35:45 -0700980};
981} // namespace
982
Hal Canary46cc3da2018-05-09 11:50:34 -0400983static SkUnichar map_glyph(const std::vector<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
984 return glyph < glyphToUnicode.size() ? glyphToUnicode[SkToInt(glyph)] : -1;
halcanaryf59d18a2016-09-16 14:44:57 -0700985}
986
Hal Canary575be302018-09-28 15:01:14 -0400987namespace {
988struct PositionedGlyph {
989 SkPoint fPos;
990 SkGlyphID fGlyph;
991};
Hal Canaryd12a6762017-05-26 17:01:16 -0400992}
993
Hal Canary699b8732017-06-13 12:13:29 -0400994static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkGlyphCache* cache,
995 SkScalar xScale, SkScalar yScale,
996 SkPoint xy, const SkMatrix& ctm) {
997 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
998 SkRect glyphBounds = {glyph.fLeft * xScale,
999 glyph.fTop * yScale,
1000 (glyph.fLeft + glyph.fWidth) * xScale,
1001 (glyph.fTop + glyph.fHeight) * yScale};
1002 glyphBounds.offset(xy);
1003 ctm.mapRect(&glyphBounds); // now in dev space.
1004 return glyphBounds;
1005}
1006
1007static bool contains(const SkRect& r, SkPoint p) {
1008 return r.left() <= p.x() && p.x() <= r.right() &&
1009 r.top() <= p.y() && p.y() <= r.bottom();
1010}
1011
Herb Derby95e17602018-12-06 17:11:43 -05001012void SkPDFDevice::drawGlyphRunAsPath(
1013 const SkGlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint) {
Hal Canary8f37ce52018-12-28 11:40:10 -05001014 const SkFont& font = glyphRun.font();
Hal Canary575be302018-09-28 15:01:14 -04001015 SkPath path;
Herb Derby4fce0832018-10-02 11:04:29 -04001016
Mike Reedab8f2972018-12-05 13:20:29 -05001017 struct Rec {
1018 SkPath* fPath;
1019 SkPoint fOffset;
1020 const SkPoint* fPos;
1021 } rec = {&path, offset, glyphRun.positions().data()};
1022
1023 font.getPaths(glyphRun.glyphsIDs().data(), glyphRun.glyphsIDs().size(),
1024 [](const SkPath* path, const SkMatrix& mx, void* ctx) {
1025 Rec* rec = reinterpret_cast<Rec*>(ctx);
1026 if (path) {
1027 SkMatrix total = mx;
1028 total.postTranslate(rec->fPos->fX + rec->fOffset.fX,
1029 rec->fPos->fY + rec->fOffset.fY);
1030 rec->fPath->addPath(*path, total);
1031 }
1032 rec->fPos += 1; // move to the next glyph's position
1033 }, &rec);
Hal Canary8f37ce52018-12-28 11:40:10 -05001034 this->drawPath(path, runPaint, true);
Hal Canary575be302018-09-28 15:01:14 -04001035
Herb Derby95e17602018-12-06 17:11:43 -05001036 SkFont transparentFont = glyphRun.font();
1037 transparentFont.setEmbolden(false); // Stop Recursion
1038 SkGlyphRun tmpGlyphRun(glyphRun, transparentFont);
1039
Herb Derby9bb6b7e2018-11-02 13:57:58 -04001040 SkPaint transparent;
Herb Derby9bb6b7e2018-11-02 13:57:58 -04001041 transparent.setColor(SK_ColorTRANSPARENT);
Herb Derby9bb6b7e2018-11-02 13:57:58 -04001042
Hal Canary575be302018-09-28 15:01:14 -04001043 if (this->ctm().hasPerspective()) {
1044 SkMatrix prevCTM = this->ctm();
1045 this->setCTM(SkMatrix::I());
Herb Derby95e17602018-12-06 17:11:43 -05001046 this->internalDrawGlyphRun(tmpGlyphRun, offset, transparent);
Hal Canary575be302018-09-28 15:01:14 -04001047 this->setCTM(prevCTM);
1048 } else {
Herb Derby95e17602018-12-06 17:11:43 -05001049 this->internalDrawGlyphRun(tmpGlyphRun, offset, transparent);
Hal Canary575be302018-09-28 15:01:14 -04001050 }
Hal Canary575be302018-09-28 15:01:14 -04001051}
1052
Hal Canary688afdd2018-10-17 14:57:53 -04001053static bool needs_new_font(SkPDFFont* font, SkGlyphID gid, SkGlyphCache* cache,
1054 SkAdvancedTypefaceMetrics::FontType fontType) {
1055 if (!font || !font->hasGlyph(gid)) {
1056 return true;
1057 }
1058 if (fontType == SkAdvancedTypefaceMetrics::kOther_Font) {
1059 return false;
1060 }
1061 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1062 if (glyph.isEmpty()) {
1063 return false;
1064 }
1065
1066 bool bitmapOnly = nullptr == cache->findPath(glyph);
1067 bool convertedToType3 = (font->getType() == SkAdvancedTypefaceMetrics::kOther_Font);
1068 return convertedToType3 != bitmapOnly;
1069}
1070
Herb Derby95e17602018-12-06 17:11:43 -05001071void SkPDFDevice::internalDrawGlyphRun(
1072 const SkGlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint) {
Hal Canary98caedd2018-07-23 10:50:49 -04001073
Herb Derbyaedc9d22018-10-25 12:27:07 -04001074 const SkGlyphID* glyphs = glyphRun.glyphsIDs().data();
1075 uint32_t glyphCount = SkToU32(glyphRun.glyphsIDs().size());
Hal Canary8f37ce52018-12-28 11:40:10 -05001076 const SkFont& glyphRunFont = glyphRun.font();
Herb Derby4fce0832018-10-02 11:04:29 -04001077
Hal Canary8f37ce52018-12-28 11:40:10 -05001078 if (!glyphCount || !glyphs || glyphRunFont.getSize() <= 0 || this->hasEmptyClip()) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001079 return;
1080 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001081 if (runPaint.getPathEffect()
1082 || runPaint.getMaskFilter()
1083 || glyphRunFont.isEmbolden()
Hal Canary92c500b2018-09-19 16:19:45 -04001084 || this->ctm().hasPerspective()
Hal Canary8f37ce52018-12-28 11:40:10 -05001085 || SkPaint::kFill_Style != runPaint.getStyle()) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001086 // Stroked Text doesn't work well with Type3 fonts.
Herb Derby95e17602018-12-06 17:11:43 -05001087 this->drawGlyphRunAsPath(glyphRun, offset, runPaint);
Hal Canarye9a29c42018-12-07 13:44:26 -05001088 return;
halcanarye06ca962016-09-09 05:34:55 -07001089 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001090 SkTypeface* typeface = SkFontPriv::GetTypefaceOrDefault(glyphRunFont);
halcanary4ed2f012016-08-15 18:40:07 -07001091 if (!typeface) {
1092 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1093 return;
1094 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001095
Hal Canary98caedd2018-07-23 10:50:49 -04001096 const SkAdvancedTypefaceMetrics* metrics = SkPDFFont::GetMetrics(typeface, fDocument->canon());
halcanary4871f222016-08-26 13:17:44 -07001097 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001098 return;
1099 }
Hal Canary688afdd2018-10-17 14:57:53 -04001100 SkAdvancedTypefaceMetrics::FontType fontType = SkPDFFont::FontType(*metrics);
1101
Hal Canary46cc3da2018-05-09 11:50:34 -04001102 const std::vector<SkUnichar>& glyphToUnicode = SkPDFFont::GetUnicodeMap(
1103 typeface, fDocument->canon());
1104
Hal Canary98caedd2018-07-23 10:50:49 -04001105 SkClusterator clusterator(glyphRun);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001106
1107 int emSize;
Herb Derby1a605cd2018-03-22 11:16:25 -04001108 auto glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001109
Hal Canary8f37ce52018-12-28 11:40:10 -05001110 SkScalar textSize = glyphRunFont.getSize();
1111 SkScalar advanceScale = textSize * glyphRunFont.getScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001112
Hal Canary699b8732017-06-13 12:13:29 -04001113 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1114 SkScalar textScaleY = textSize / emSize;
Hal Canary8f37ce52018-12-28 11:40:10 -05001115 SkScalar textScaleX = advanceScale + glyphRunFont.getSkewX() * textScaleY;
Hal Canary699b8732017-06-13 12:13:29 -04001116
Hal Canary22b2d8c2017-07-19 14:46:12 -04001117 SkRect clipStackBounds = this->cs().bounds(this->bounds());
Hal Canary9b9510a2017-07-18 09:39:00 -04001118
Hal Canary8f37ce52018-12-28 11:40:10 -05001119 SkPaint paint(runPaint);
1120 remove_color_filter(&paint);
1121 replace_srcmode_on_opaque_paint(&paint);
1122 ScopedContentEntry content(this, paint, glyphRunFont.getScaleX());
1123 if (!content) {
1124 return;
1125 }
1126 SkDynamicMemoryWStream* out = content.stream();
Dominic Mazzoni656cefe2018-09-25 20:29:15 -07001127
Hal Canary8f37ce52018-12-28 11:40:10 -05001128 out->writeText("BT\n");
Dominic Mazzoni656cefe2018-09-25 20:29:15 -07001129
Hal Canary8f37ce52018-12-28 11:40:10 -05001130 int markId = -1;
1131 if (fNodeId) {
1132 markId = fDocument->getMarkIdForNodeId(fNodeId);
1133 }
Dominic Mazzoni656cefe2018-09-25 20:29:15 -07001134
Hal Canary8f37ce52018-12-28 11:40:10 -05001135 if (markId != -1) {
1136 out->writeText("/P <</MCID ");
1137 out->writeDecAsText(markId);
1138 out->writeText(" >>BDC\n");
1139 }
1140 SK_AT_SCOPE_EXIT(if (markId != -1) out->writeText("EMC\n"));
Hal Canary9b9510a2017-07-18 09:39:00 -04001141
Hal Canary8f37ce52018-12-28 11:40:10 -05001142 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
Hal Canary9b9510a2017-07-18 09:39:00 -04001143
Hal Canary8f37ce52018-12-28 11:40:10 -05001144 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
Hal Canary9b9510a2017-07-18 09:39:00 -04001145
Hal Canary8f37ce52018-12-28 11:40:10 -05001146 if (clusterator.reversedChars()) {
1147 out->writeText("/ReversedChars BMC\n");
1148 }
1149 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1150 GlyphPositioner glyphPositioner(out, glyphRunFont.getSkewX(), offset);
1151 SkPDFFont* font = nullptr;
Hal Canary9b9510a2017-07-18 09:39:00 -04001152
Hal Canary8f37ce52018-12-28 11:40:10 -05001153 while (SkClusterator::Cluster c = clusterator.next()) {
1154 int index = c.fGlyphIndex;
1155 int glyphLimit = index + c.fGlyphCount;
1156
1157 bool actualText = false;
1158 SK_AT_SCOPE_EXIT(if (actualText) {
1159 glyphPositioner.flush();
1160 out->writeText("EMC\n");
1161 });
1162 if (c.fUtf8Text) { // real cluster
1163 // Check if `/ActualText` needed.
1164 const char* textPtr = c.fUtf8Text;
1165 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1166 SkUnichar unichar = SkUTF::NextUTF8(&textPtr, textEnd);
1167 if (unichar < 0) {
1168 return;
halcanaryf59d18a2016-09-16 14:44:57 -07001169 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001170 if (textPtr < textEnd || // more characters left
1171 glyphLimit > index + 1 || // toUnicode wouldn't work
1172 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1173 {
1174 glyphPositioner.flush();
1175 out->writeText("/Span<</ActualText <");
1176 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1177 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1178 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1179 while (textPtr < textEnd) {
1180 unichar = SkUTF::NextUTF8(&textPtr, textEnd);
1181 if (unichar < 0) {
1182 break;
1183 }
1184 SkPDFUtils::WriteUTF16beHex(out, unichar);
1185 }
1186 out->writeText("> >> BDC\n"); // begin marked-content sequence
1187 // with an associated property list.
1188 actualText = true;
1189 }
1190 }
1191 for (; index < glyphLimit; ++index) {
1192 SkGlyphID gid = glyphs[index];
1193 if (gid > maxGlyphID) {
1194 continue;
1195 }
1196 SkPoint xy = glyphRun.positions()[index];
1197 // Do a glyph-by-glyph bounds-reject if positions are absolute.
1198 SkRect glyphBounds = get_glyph_bounds_device_space(
1199 gid, glyphCache.get(), textScaleX, textScaleY,
1200 xy + offset, this->ctm());
1201 if (glyphBounds.isEmpty()) {
1202 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
Hal Canary9b9510a2017-07-18 09:39:00 -04001203 continue;
halcanaryf59d18a2016-09-16 14:44:57 -07001204 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001205 } else {
1206 if (!clipStackBounds.intersects(glyphBounds)) {
1207 continue; // reject glyphs as out of bounds
Hal Canary688afdd2018-10-17 14:57:53 -04001208 }
halcanaryf59d18a2016-09-16 14:44:57 -07001209 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001210 if (needs_new_font(font, gid, glyphCache.get(), fontType)) {
1211 // Not yet specified font or need to switch font.
1212 font = SkPDFFont::GetFontResource(fDocument, glyphCache.get(), typeface, gid);
1213 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1214 glyphPositioner.flush();
1215 glyphPositioner.setWideChars(font->multiByteGlyphs());
1216 SkPDFWriteResourceName(out, SkPDFResourceType::kFont,
1217 add_resource(fFontResources, font->indirectReference()));
1218 out->writeText(" ");
1219 SkPDFUtils::AppendScalar(textSize, out);
1220 out->writeText(" Tf\n");
1221
1222 }
1223 font->noteGlyphUsage(gid);
1224 SkGlyphID encodedGlyph = font->multiByteGlyphs()
1225 ? gid : font->glyphToPDFFontEncoding(gid);
1226 SkScalar advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1227 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
Hal Canary9b9510a2017-07-18 09:39:00 -04001228 }
1229 }
halcanary4ed2f012016-08-15 18:40:07 -07001230}
1231
Herb Derbyb935cf82018-07-26 16:54:18 -04001232void SkPDFDevice::drawGlyphRunList(const SkGlyphRunList& glyphRunList) {
1233 for (const SkGlyphRun& glyphRun : glyphRunList) {
Herb Derby95e17602018-12-06 17:11:43 -05001234 this->internalDrawGlyphRun(glyphRun, glyphRunList.origin(), glyphRunList.paint());
halcanarye06ca962016-09-09 05:34:55 -07001235 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001236}
1237
Ruiqi Maoc97a3392018-08-15 10:44:19 -04001238void SkPDFDevice::drawVertices(const SkVertices*, const SkVertices::Bone[], int, SkBlendMode,
Ruiqi Maof5101492018-06-29 14:32:21 -04001239 const SkPaint&) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05001240 if (this->hasEmptyClip()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001241 return;
1242 }
reed@google.com85e143c2013-12-30 15:51:25 +00001243 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001244}
1245
Hal Canary9a3f5542018-12-10 19:59:07 -05001246void SkPDFDevice::drawFormXObject(SkPDFIndirectReference xObject, SkDynamicMemoryWStream* content) {
1247 SkASSERT(xObject);
Hal Canary3b8b11e2018-09-29 22:31:34 -04001248 SkPDFWriteResourceName(content, SkPDFResourceType::kXObject,
Hal Canary9a3f5542018-12-10 19:59:07 -05001249 add_resource(fXObjectResources, xObject));
Hal Canarye650b852018-09-12 09:12:36 -04001250 content->writeText(" Do\n");
1251}
1252
Mike Reeda1361362017-03-07 09:37:29 -05001253void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001254 SkASSERT(!paint.getImageFilter());
1255
reed7503d602016-07-15 14:23:29 -07001256 // Check if the source device is really a bitmapdevice (because that's what we returned
1257 // from createDevice (likely due to an imagefilter)
1258 SkPixmap pmap;
1259 if (device->peekPixels(&pmap)) {
1260 SkBitmap bitmap;
1261 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001262 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001263 return;
1264 }
1265
fmalita6987dca2014-11-13 08:33:37 -08001266 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001267 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001268
1269 SkScalar scalarX = SkIntToScalar(x);
1270 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001271 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1272 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001273 fLinkToURLs.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001274 }
halcanary91fcb3e2016-03-04 13:53:22 -08001275 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1276 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001277 fLinkToDestinations.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001278 }
halcanary91fcb3e2016-03-04 13:53:22 -08001279 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1280 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001281 fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001282 }
1283
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001284 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001285 return;
1286 }
1287
Mike Reeda1361362017-03-07 09:37:29 -05001288 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
Hal Canaryd892a9d2018-09-24 21:20:47 -04001289 ScopedContentEntry content(this, &this->cs(), matrix, paint);
Hal Canary42137de2018-10-08 16:00:37 -04001290 if (!content) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001291 return;
1292 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001293 if (content.needShape()) {
Hal Canaryd791a6f2018-09-28 12:14:08 -04001294 SkISize dim = device->imageInfo().dimensions();
1295 content.setShape(to_path(SkRect::Make(SkIRect::MakeXYWH(x, y, dim.width(), dim.height()))));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001296 }
1297 if (!content.needSource()) {
1298 return;
1299 }
Hal Canary3b8b11e2018-09-29 22:31:34 -04001300 this->drawFormXObject(pdfDevice->makeFormXObjectFromDevice(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001301}
1302
reede8f30622016-03-23 18:59:25 -07001303sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1304 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001305}
1306
Hal Canary9a3f5542018-12-10 19:59:07 -05001307static std::vector<SkPDFIndirectReference> sort(const SkTHashSet<SkPDFIndirectReference>& src) {
1308 std::vector<SkPDFIndirectReference> dst;
1309 dst.reserve(src.count());
1310 src.foreach([&dst](SkPDFIndirectReference ref) { dst.push_back(ref); } );
1311 std::sort(dst.begin(), dst.end(),
1312 [](SkPDFIndirectReference a, SkPDFIndirectReference b) { return a.fValue < b.fValue; });
1313 return dst;
1314}
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001315
Hal Canary74801582018-12-18 16:30:41 -05001316std::unique_ptr<SkPDFDict> SkPDFDevice::makeResourceDict() {
Hal Canary9a3f5542018-12-10 19:59:07 -05001317 return SkPDFMakeResourceDict(sort(fGraphicStateResources),
1318 sort(fShaderResources),
1319 sort(fXObjectResources),
1320 sort(fFontResources));
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001321}
1322
Hal Canaryb400d4d2018-09-26 16:33:52 -04001323std::unique_ptr<SkStreamAsset> SkPDFDevice::content() {
1324 if (fActiveStackState.fContentStream) {
1325 fActiveStackState.drainStack();
1326 fActiveStackState = GraphicStackState();
1327 }
Hal Canary42137de2018-10-08 16:00:37 -04001328 if (fContent.bytesWritten() == 0) {
1329 return skstd::make_unique<SkMemoryStream>();
1330 }
halcanary334fcbc2015-02-24 12:56:16 -08001331 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001332 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
Hal Canarye650b852018-09-12 09:12:36 -04001333 append_transform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001334 }
Hal Canary42137de2018-10-08 16:00:37 -04001335 if (fNeedsExtraSave) {
1336 buffer.writeText("q\n");
halcanary2be7e012016-03-28 11:58:08 -07001337 }
Hal Canary42137de2018-10-08 16:00:37 -04001338 fContent.writeToAndReset(&buffer);
1339 if (fNeedsExtraSave) {
1340 buffer.writeText("Q\n");
halcanary022c2bd2016-09-02 11:29:46 -07001341 }
Hal Canary42137de2018-10-08 16:00:37 -04001342 fNeedsExtraSave = false;
1343 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001344}
1345
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001346/* Draws an inverse filled path by using Path Ops to compute the positive
1347 * inverse using the current clip as the inverse bounds.
1348 * Return true if this was an inverse path and was properly handled,
1349 * otherwise returns false and the normal drawing routine should continue,
1350 * either as a (incorrect) fallback or because the path was not inverse
1351 * in the first place.
1352 */
Mike Reeda1361362017-03-07 09:37:29 -05001353bool SkPDFDevice::handleInversePath(const SkPath& origPath,
Robert Phillips137ca522018-08-15 10:14:33 -04001354 const SkPaint& paint,
1355 bool pathIsMutable) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001356 if (!origPath.isInverseFillType()) {
1357 return false;
1358 }
1359
Hal Canaryb4e528d2018-03-09 16:02:15 -05001360 if (this->hasEmptyClip()) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001361 return false;
1362 }
1363
1364 SkPath modifiedPath;
1365 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1366 SkPaint noInversePaint(paint);
1367
1368 // Merge stroking operations into final path.
1369 if (SkPaint::kStroke_Style == paint.getStyle() ||
1370 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1371 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1372 if (doFillPath) {
1373 noInversePaint.setStyle(SkPaint::kFill_Style);
1374 noInversePaint.setStrokeWidth(0);
1375 pathPtr = &modifiedPath;
1376 } else {
1377 // To be consistent with the raster output, hairline strokes
1378 // are rendered as non-inverted.
1379 modifiedPath.toggleInverseFillType();
Robert Phillips137ca522018-08-15 10:14:33 -04001380 this->drawPath(modifiedPath, paint, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001381 return true;
1382 }
1383 }
1384
1385 // Get bounds of clip in current transform space
1386 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001387 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001388 SkMatrix totalMatrix = this->ctm();
Robert Phillips137ca522018-08-15 10:14:33 -04001389
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001390 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001391 return false;
1392 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001393 SkRect bounds = this->cs().bounds(this->bounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001394 transformInverse.mapRect(&bounds);
1395
1396 // Extend the bounds by the line width (plus some padding)
1397 // so the edge doesn't cause a visible stroke.
1398 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1399 paint.getStrokeWidth() + SK_Scalar1);
1400
1401 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1402 return false;
1403 }
1404
Robert Phillips137ca522018-08-15 10:14:33 -04001405 this->drawPath(modifiedPath, noInversePaint, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001406 return true;
1407}
1408
Hal Canary74801582018-12-18 16:30:41 -05001409std::unique_ptr<SkPDFArray> SkPDFDevice::getAnnotations() {
1410 std::unique_ptr<SkPDFArray> array;
Hal Canary9e41c212018-09-03 12:00:23 -04001411 size_t count = fLinkToURLs.size() + fLinkToDestinations.size();
1412 if (0 == count) {
1413 return array;
1414 }
Hal Canary74801582018-12-18 16:30:41 -05001415 array = SkPDFMakeArray();
Hal Canary9e41c212018-09-03 12:00:23 -04001416 array->reserve(count);
halcanary91fcb3e2016-03-04 13:53:22 -08001417 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001418 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001419 fInitialTransform.mapRect(&r, rectWithURL.rect);
Hal Canary9a3f5542018-12-10 19:59:07 -05001420 array->appendRef(fDocument->emit(*create_link_to_url(rectWithURL.data.get(), r)));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001421 }
halcanary91fcb3e2016-03-04 13:53:22 -08001422 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001423 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001424 fInitialTransform.mapRect(&r, linkToDestination.rect);
Hal Canary9a3f5542018-12-10 19:59:07 -05001425 array->appendRef(
1426 fDocument->emit(*create_link_named_dest(linkToDestination.data.get(), r)));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001427 }
Hal Canary9e41c212018-09-03 12:00:23 -04001428 return array;
wangxianzhuef6c50a2015-09-17 20:38:02 -07001429}
epoger@google.comb58772f2013-03-08 09:09:10 +00001430
Hal Canaryfba5b6c2018-12-18 12:55:18 -05001431void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFIndirectReference page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001432 for (const NamedDestination& dest : fNamedDestinations) {
Hal Canaryfba5b6c2018-12-18 12:55:18 -05001433 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
Hal Canary74801582018-12-18 16:30:41 -05001434 auto pdfDest = SkPDFMakeArray();
epoger@google.comb58772f2013-03-08 09:09:10 +00001435 pdfDest->reserve(5);
Hal Canaryfba5b6c2018-12-18 12:55:18 -05001436 pdfDest->appendRef(page);
epoger@google.comb58772f2013-03-08 09:09:10 +00001437 pdfDest->appendName("XYZ");
wangxianzhuef6c50a2015-09-17 20:38:02 -07001438 pdfDest->appendScalar(p.x());
1439 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001440 pdfDest->appendInt(0); // Leave zoom unchanged
Hal Canaryfba5b6c2018-12-18 12:55:18 -05001441 dict->insertObject(SkString(static_cast<const char*>(dest.nameData->data())),
1442 std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001443 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001444}
1445
Hal Canary9a3f5542018-12-10 19:59:07 -05001446SkPDFIndirectReference SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
halcanary5abbb442016-07-29 08:41:33 -07001447 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001448 if (!fInitialTransform.isIdentity()) {
1449 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001450 SkDEBUGFAIL("Layer initial transform should be invertible.");
1451 inverseTransform.reset();
1452 }
1453 }
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001454 const char* colorSpace = alpha ? "DeviceGray" : nullptr;
Hal Canarye650b852018-09-12 09:12:36 -04001455
Hal Canary9a3f5542018-12-10 19:59:07 -05001456 SkPDFIndirectReference xobject =
1457 SkPDFMakeFormXObject(fDocument, this->content(),
Hal Canarye650b852018-09-12 09:12:36 -04001458 SkPDFMakeArray(0, 0, this->width(), this->height()),
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001459 this->makeResourceDict(), inverseTransform, colorSpace);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001460 // We always draw the form xobjects that we create back into the device, so
1461 // we simply preserve the font usage instead of pulling it out and merging
1462 // it back in later.
Hal Canary9e41c212018-09-03 12:00:23 -04001463 this->reset();
reed@google.comfc641d02012-09-20 17:52:20 +00001464 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001465}
1466
Hal Canary9a3f5542018-12-10 19:59:07 -05001467void SkPDFDevice::drawFormXObjectWithMask(SkPDFIndirectReference xObject,
1468 SkPDFIndirectReference sMask,
reed374772b2016-10-05 17:33:02 -07001469 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001470 bool invertClip) {
Hal Canary9a3f5542018-12-10 19:59:07 -05001471 SkASSERT(sMask);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001472 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001473 paint.setBlendMode(mode);
Hal Canaryd892a9d2018-09-24 21:20:47 -04001474 ScopedContentEntry content(this, nullptr, SkMatrix::I(), paint);
Hal Canary42137de2018-10-08 16:00:37 -04001475 if (!content) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001476 return;
1477 }
Hal Canary3b8b11e2018-09-29 22:31:34 -04001478 this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
Hal Canary9a3f5542018-12-10 19:59:07 -05001479 sMask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode,
1480 fDocument), content.stream());
1481 this->drawFormXObject(xObject, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001482 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001483}
1484
Hal Canaryb400d4d2018-09-26 16:33:52 -04001485
1486static bool treat_as_regular_pdf_blend_mode(SkBlendMode blendMode) {
1487 return nullptr != SkPDFUtils::BlendModeName(blendMode);
1488}
1489
Hal Canary8f37ce52018-12-28 11:40:10 -05001490static void populate_graphic_state_entry_from_paint(
1491 SkPDFDocument* doc,
1492 const SkMatrix& matrix,
1493 const SkClipStack* clipStack,
1494 SkIRect deviceBounds,
1495 const SkPaint& paint,
1496 const SkMatrix& initialTransform,
1497 SkScalar textScale,
1498 SkPDFDevice::GraphicStateEntry* entry,
1499 SkTHashSet<SkPDFIndirectReference>* shaderResources,
1500 SkTHashSet<SkPDFIndirectReference>* graphicStateResources) {
1501 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1502 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1503 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
1504
1505 entry->fMatrix = matrix;
1506 entry->fClipStackGenID = clipStack ? clipStack->getTopmostGenID()
1507 : SkClipStack::kWideOpenGenID;
1508 SkColor4f color = paint.getColor4f();
1509 entry->fColor = {color.fR, color.fG, color.fB, 1};
1510 entry->fShaderIndex = -1;
1511
1512 // PDF treats a shader as a color, so we only set one or the other.
1513 SkShader* shader = paint.getShader();
1514 if (shader) {
1515 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1516 // We don't have to set a shader just for a color.
1517 SkShader::GradientInfo gradientInfo;
1518 SkColor gradientColor = SK_ColorBLACK;
1519 gradientInfo.fColors = &gradientColor;
1520 gradientInfo.fColorOffsets = nullptr;
1521 gradientInfo.fColorCount = 1;
1522 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1523 color = SkColor4f::FromColor(gradientColor);
1524 entry->fColor ={color.fR, color.fG, color.fB, 1};
1525
1526 } else {
1527 // PDF positions patterns relative to the initial transform, so
1528 // we need to apply the current transform to the shader parameters.
1529 SkMatrix transform = matrix;
1530 transform.postConcat(initialTransform);
1531
1532 // PDF doesn't support kClamp_TileMode, so we simulate it by making
1533 // a pattern the size of the current clip.
1534 SkRect clipStackBounds = clipStack ? clipStack->bounds(deviceBounds)
1535 : SkRect::Make(deviceBounds);
1536
1537 // We need to apply the initial transform to bounds in order to get
1538 // bounds in a consistent coordinate system.
1539 initialTransform.mapRect(&clipStackBounds);
1540 SkIRect bounds;
1541 clipStackBounds.roundOut(&bounds);
1542
1543 SkPDFIndirectReference pdfShader
1544 = SkPDFMakeShader(doc, shader, transform, bounds, paint.getColor());
1545
1546 if (pdfShader) {
1547 // pdfShader has been canonicalized so we can directly compare pointers.
1548 entry->fShaderIndex = add_resource(*shaderResources, pdfShader);
1549 }
1550 }
1551 }
1552
1553 SkPDFIndirectReference newGraphicState;
1554 if (color == paint.getColor4f()) {
1555 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(doc, paint);
1556 } else {
1557 SkPaint newPaint = paint;
1558 newPaint.setColor4f(color, nullptr);
1559 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(doc, newPaint);
1560 }
1561 entry->fGraphicStateIndex = add_resource(*graphicStateResources, newGraphicState);
1562 entry->fTextScaleX = textScale;
1563}
1564
Hal Canaryb400d4d2018-09-26 16:33:52 -04001565SkDynamicMemoryWStream* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1566 const SkMatrix& matrix,
1567 const SkPaint& paint,
Hal Canary8f37ce52018-12-28 11:40:10 -05001568 SkScalar textScale,
Hal Canary9a3f5542018-12-10 19:59:07 -05001569 SkPDFIndirectReference* dst) {
1570 SkASSERT(!*dst);
reed374772b2016-10-05 17:33:02 -07001571 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001572
Hal Canaryb400d4d2018-09-26 16:33:52 -04001573 // Dst xfer mode doesn't draw source at all.
1574 if (blendMode == SkBlendMode::kDst) {
1575 return nullptr;
1576 }
1577
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001578 // For the following modes, we want to handle source and destination
1579 // separately, so make an object of what's already there.
Hal Canaryb400d4d2018-09-26 16:33:52 -04001580 if (!treat_as_regular_pdf_blend_mode(blendMode) && blendMode != SkBlendMode::kDstOver) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001581 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001582 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001583 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001584 } else if (blendMode != SkBlendMode::kSrc &&
1585 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001586 // Except for Src and SrcOut, if there isn't anything already there,
1587 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001588 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001589 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001590 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001591 // TODO(vandebo): Figure out how/if we can handle the following modes:
Hal Canaryb400d4d2018-09-26 16:33:52 -04001592 // Xor, Plus. For now, we treat them as SrcOver/Normal.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001593
Hal Canaryb400d4d2018-09-26 16:33:52 -04001594 if (treat_as_regular_pdf_blend_mode(blendMode)) {
1595 if (!fActiveStackState.fContentStream) {
Hal Canary42137de2018-10-08 16:00:37 -04001596 if (fContent.bytesWritten() != 0) {
1597 fContent.writeText("Q\nq\n");
1598 fNeedsExtraSave = true;
1599 }
1600 fActiveStackState = GraphicStackState(&fContent);
1601 } else {
1602 SkASSERT(fActiveStackState.fContentStream = &fContent);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001603 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001604 } else {
Hal Canaryb400d4d2018-09-26 16:33:52 -04001605 fActiveStackState.drainStack();
Hal Canary42137de2018-10-08 16:00:37 -04001606 fActiveStackState = GraphicStackState(&fContentBuffer);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001607 }
Hal Canaryb400d4d2018-09-26 16:33:52 -04001608 SkASSERT(fActiveStackState.fContentStream);
1609 GraphicStateEntry entry;
Hal Canary8f37ce52018-12-28 11:40:10 -05001610 populate_graphic_state_entry_from_paint(
1611 fDocument,
1612 matrix,
1613 clipStack,
1614 this->bounds(),
1615 paint,
1616 fInitialTransform,
1617 textScale,
1618 &entry,
1619 &fShaderResources,
1620 &fGraphicStateResources);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001621 fActiveStackState.updateClip(clipStack, this->bounds());
1622 fActiveStackState.updateMatrix(entry.fMatrix);
1623 fActiveStackState.updateDrawingState(entry);
1624
1625 return fActiveStackState.fContentStream;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001626}
1627
Hal Canaryb400d4d2018-09-26 16:33:52 -04001628void SkPDFDevice::finishContentEntry(const SkClipStack* clipStack,
1629 SkBlendMode blendMode,
Hal Canary9a3f5542018-12-10 19:59:07 -05001630 SkPDFIndirectReference dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001631 SkPath* shape) {
Hal Canaryb400d4d2018-09-26 16:33:52 -04001632 SkASSERT(blendMode != SkBlendMode::kDst);
1633 if (treat_as_regular_pdf_blend_mode(blendMode)) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001634 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001635 return;
1636 }
Hal Canaryb400d4d2018-09-26 16:33:52 -04001637
1638 SkASSERT(fActiveStackState.fContentStream);
1639
1640 fActiveStackState.drainStack();
1641 fActiveStackState = GraphicStackState();
1642
reed374772b2016-10-05 17:33:02 -07001643 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001644 SkASSERT(!dst);
Hal Canary42137de2018-10-08 16:00:37 -04001645 if (fContentBuffer.bytesWritten() != 0) {
1646 if (fContent.bytesWritten() != 0) {
1647 fContentBuffer.writeText("Q\nq\n");
1648 fNeedsExtraSave = true;
1649 }
1650 fContentBuffer.prependToAndReset(&fContent);
1651 SkASSERT(fContentBuffer.bytesWritten() == 0);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001652 }
1653 return;
1654 }
Hal Canary42137de2018-10-08 16:00:37 -04001655 if (fContentBuffer.bytesWritten() != 0) {
1656 if (fContent.bytesWritten() != 0) {
1657 fContent.writeText("Q\nq\n");
1658 fNeedsExtraSave = true;
1659 }
1660 fContentBuffer.writeToAndReset(&fContent);
1661 SkASSERT(fContentBuffer.bytesWritten() == 0);
1662 }
1663
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001664 if (!dst) {
reed374772b2016-10-05 17:33:02 -07001665 SkASSERT(blendMode == SkBlendMode::kSrc ||
1666 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001667 return;
1668 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001669
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001670 SkASSERT(dst);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001671 // Changing the current content into a form-xobject will destroy the clip
1672 // objects which is fine since the xobject will already be clipped. However
1673 // if source has shape, we need to clip it too, so a copy of the clip is
1674 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001675
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001676 SkPaint stockPaint;
1677
Hal Canary9a3f5542018-12-10 19:59:07 -05001678 SkPDFIndirectReference srcFormXObject;
Hal Canary9e41c212018-09-03 12:00:23 -04001679 if (this->isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001680 // If nothing was drawn and there's no shape, then the draw was a
1681 // no-op, but dst needs to be restored for that to be true.
1682 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1683 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1684 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07001685 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1686 blendMode == SkBlendMode::kSrcATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001687 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary9a3f5542018-12-10 19:59:07 -05001688 this->drawFormXObject(dst, content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001689 return;
1690 } else {
reed374772b2016-10-05 17:33:02 -07001691 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001692 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001693 } else {
halcanary4b1e17e2016-07-27 14:49:46 -07001694 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001695 }
1696
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001697 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1698 // without alpha.
reed374772b2016-10-05 17:33:02 -07001699 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001700 // TODO(vandebo): In order to properly support SrcATop we have to track
1701 // the shape of what's been drawn at all times. It's the intersection of
1702 // the non-transparent parts of the device and the outlines (shape) of
1703 // all images and devices drawn.
Hal Canaryc4c41c92018-09-28 13:30:45 -04001704 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001705 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001706 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001707 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001708 SkPaint filledPaint;
1709 filledPaint.setColor(SK_ColorBLACK);
1710 filledPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001711 SkClipStack empty;
Hal Canary813b5ac2018-09-28 12:30:37 -04001712 SkPDFDevice shapeDev(this->size(), fDocument, fInitialTransform);
1713 shapeDev.internalDrawPath(clipStack ? *clipStack : empty,
1714 SkMatrix::I(), *shape, filledPaint, true);
Hal Canaryc4c41c92018-09-28 13:30:45 -04001715 this->drawFormXObjectWithMask(dst, shapeDev.makeFormXObjectFromDevice(),
Mike Reeda1361362017-03-07 09:37:29 -05001716 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07001717 } else {
Hal Canaryc4c41c92018-09-28 13:30:45 -04001718 this->drawFormXObjectWithMask(dst, srcFormXObject, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001719 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001720 }
1721
reed374772b2016-10-05 17:33:02 -07001722 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001723 return;
reed374772b2016-10-05 17:33:02 -07001724 } else if (blendMode == SkBlendMode::kSrc ||
1725 blendMode == SkBlendMode::kDstATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001726 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary42137de2018-10-08 16:00:37 -04001727 if (content) {
Hal Canary3b8b11e2018-09-29 22:31:34 -04001728 this->drawFormXObject(srcFormXObject, content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001729 }
reed374772b2016-10-05 17:33:02 -07001730 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001731 return;
1732 }
reed374772b2016-10-05 17:33:02 -07001733 } else if (blendMode == SkBlendMode::kSrcATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001734 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary42137de2018-10-08 16:00:37 -04001735 if (content) {
Hal Canary3b8b11e2018-09-29 22:31:34 -04001736 this->drawFormXObject(dst, content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001737 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001738 }
1739
reed374772b2016-10-05 17:33:02 -07001740 SkASSERT(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
reed374772b2016-10-05 17:33:02 -07001748 if (blendMode == SkBlendMode::kSrcIn ||
1749 blendMode == SkBlendMode::kSrcOut ||
1750 blendMode == SkBlendMode::kSrcATop) {
Hal Canary9a3f5542018-12-10 19:59:07 -05001751 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver,
1752 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07001753 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001754 } else {
reed374772b2016-10-05 17:33:02 -07001755 SkBlendMode mode = SkBlendMode::kSrcOver;
reed374772b2016-10-05 17:33:02 -07001756 if (blendMode == SkBlendMode::kModulate) {
Hal Canaryc4c41c92018-09-28 13:30:45 -04001757 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, false);
reed374772b2016-10-05 17:33:02 -07001758 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001759 }
Hal Canary9a3f5542018-12-10 19:59:07 -05001760 this->drawFormXObjectWithMask(dst, srcFormXObject, mode, blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07001761 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001762 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001763}
1764
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001765bool SkPDFDevice::isContentEmpty() {
Hal Canary42137de2018-10-08 16:00:37 -04001766 return fContent.bytesWritten() == 0 && fContentBuffer.bytesWritten() == 0;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001767}
1768
Hal Canaryfafe1352017-04-11 12:12:02 -04001769static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07001770
Hal Canary7cbf5e32017-07-12 13:10:23 -04001771static sk_sp<SkImage> color_filter(const SkImage* image,
halcanarya50151d2016-03-25 11:57:49 -07001772 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07001773 auto surface =
Hal Canary7cbf5e32017-07-12 13:10:23 -04001774 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07001775 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07001776 SkCanvas* canvas = surface->getCanvas();
1777 canvas->clear(SK_ColorTRANSPARENT);
1778 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07001779 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canary7cbf5e32017-07-12 13:10:23 -04001780 canvas->drawImage(image, 0, 0, &paint);
halcanarya50151d2016-03-25 11:57:49 -07001781 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07001782}
1783
1784////////////////////////////////////////////////////////////////////////////////
Hal Canary7cbf5e32017-07-12 13:10:23 -04001785
1786static bool is_integer(SkScalar x) {
1787 return x == SkScalarTruncToScalar(x);
1788}
1789
1790static bool is_integral(const SkRect& r) {
1791 return is_integer(r.left()) &&
1792 is_integer(r.top()) &&
1793 is_integer(r.right()) &&
1794 is_integer(r.bottom());
1795}
1796
1797void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
1798 const SkRect* src,
1799 const SkRect& dst,
1800 const SkPaint& srcPaint,
1801 const SkMatrix& ctm) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05001802 if (this->hasEmptyClip()) {
1803 return;
1804 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04001805 if (!imageSubset) {
halcanarya50151d2016-03-25 11:57:49 -07001806 return;
1807 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04001808
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001809 // First, figure out the src->dst transform and subset the image if needed.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001810 SkIRect bounds = imageSubset.image()->bounds();
Hal Canary7cbf5e32017-07-12 13:10:23 -04001811 SkRect srcRect = src ? *src : SkRect::Make(bounds);
1812 SkMatrix transform;
1813 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
1814 if (src && *src != SkRect::Make(bounds)) {
1815 if (!srcRect.intersect(SkRect::Make(bounds))) {
1816 return;
1817 }
1818 srcRect.roundOut(&bounds);
1819 transform.preTranslate(SkIntToScalar(bounds.x()),
1820 SkIntToScalar(bounds.y()));
1821 if (bounds != imageSubset.image()->bounds()) {
1822 imageSubset = imageSubset.subset(bounds);
1823 }
1824 if (!imageSubset) {
1825 return;
1826 }
1827 }
1828
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001829 // If the image is opaque and the paint's alpha is too, replace
1830 // kSrc blendmode with kSrcOver.
1831 SkPaint paint = srcPaint;
1832 if (imageSubset.image()->isOpaque()) {
1833 replace_srcmode_on_opaque_paint(&paint);
Hal Canaryd425a1d2017-07-12 13:13:51 -04001834 }
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001835
1836 // Alpha-only images need to get their color from the shader, before
1837 // applying the colorfilter.
1838 if (imageSubset.image()->isAlphaOnly() && paint.getColorFilter()) {
1839 // must blend alpha image and shader before applying colorfilter.
1840 auto surface =
1841 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
1842 SkCanvas* canvas = surface->getCanvas();
1843 SkPaint tmpPaint;
1844 // In the case of alpha images with shaders, the shader's coordinate
1845 // system is the image's coordiantes.
1846 tmpPaint.setShader(sk_ref_sp(paint.getShader()));
Hal Canary04ac4612018-10-10 13:09:43 -04001847 tmpPaint.setColor4f(paint.getColor4f(), nullptr);
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001848 canvas->clear(0x00000000);
1849 canvas->drawImage(imageSubset.image().get(), 0, 0, &tmpPaint);
1850 paint.setShader(nullptr);
1851 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1852 SkASSERT(!imageSubset.image()->isAlphaOnly());
1853 }
1854
1855 if (imageSubset.image()->isAlphaOnly()) {
1856 // The ColorFilter applies to the paint color/shader, not the alpha layer.
1857 SkASSERT(nullptr == paint.getColorFilter());
1858
Hal Canaryd425a1d2017-07-12 13:13:51 -04001859 sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
1860 if (!mask) {
1861 return;
1862 }
1863 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
1864 // Must mask with a Form XObject.
1865 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
1866 {
Herb Derbyefe39bc2018-05-01 17:06:20 -04001867 SkCanvas canvas(maskDevice);
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001868 if (paint.getMaskFilter()) {
1869 // This clip prevents the mask image shader from covering
1870 // entire device if unnecessary.
1871 canvas.clipRect(this->cs().bounds(this->bounds()));
1872 canvas.concat(ctm);
1873 SkPaint tmpPaint;
1874 tmpPaint.setShader(mask->makeShader(&transform));
1875 tmpPaint.setMaskFilter(sk_ref_sp(paint.getMaskFilter()));
1876 canvas.drawRect(dst, tmpPaint);
1877 } else {
1878 canvas.concat(ctm);
1879 if (src && !is_integral(*src)) {
1880 canvas.clipRect(dst);
1881 }
1882 canvas.concat(transform);
1883 canvas.drawImage(mask, 0, 0);
1884 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04001885 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04001886 if (!ctm.isIdentity() && paint.getShader()) {
1887 transform_shader(&paint, ctm); // Since we are using identity matrix.
1888 }
Hal Canaryd892a9d2018-09-24 21:20:47 -04001889 ScopedContentEntry content(this, &this->cs(), SkMatrix::I(), paint);
Hal Canary42137de2018-10-08 16:00:37 -04001890 if (!content) {
Hal Canaryd425a1d2017-07-12 13:13:51 -04001891 return;
1892 }
1893 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
Hal Canary813b5ac2018-09-28 12:30:37 -04001894 SkPDFUtils::AppendRectangle(SkRect::Make(this->size()), content.stream());
Hal Canaryd425a1d2017-07-12 13:13:51 -04001895 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kWinding_FillType, content.stream());
1896 this->clearMaskOnGraphicState(content.stream());
1897 return;
1898 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04001899 if (paint.getMaskFilter()) {
1900 paint.setShader(imageSubset.image()->makeShader(&transform));
Hal Canaryd791a6f2018-09-28 12:14:08 -04001901 SkPath path = to_path(dst); // handles non-integral clipping.
Robert Phillips137ca522018-08-15 10:14:33 -04001902 this->internalDrawPath(this->cs(), this->ctm(), path, paint, true);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001903 return;
1904 }
1905 transform.postConcat(ctm);
1906
1907 bool needToRestore = false;
1908 if (src && !is_integral(*src)) {
1909 // Need sub-pixel clipping to fix https://bug.skia.org/4374
1910 this->cs().save();
1911 this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
1912 needToRestore = true;
1913 }
1914 SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
1915
halcanary7a14b312015-10-01 07:28:13 -07001916 #ifdef SK_PDF_IMAGE_STATS
1917 gDrawImageCalls.fetch_add(1);
1918 #endif
Hal Canary7cbf5e32017-07-12 13:10:23 -04001919 SkMatrix matrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001920
1921 // Rasterize the bitmap using perspective in a new bitmap.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001922 if (transform.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001923 // Transform the bitmap in the new space, without taking into
1924 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001925 SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
Hal Canaryd791a6f2018-09-28 12:14:08 -04001926 SkPath perspectiveOutline = to_path(imageBounds);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001927 perspectiveOutline.transform(transform);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001928
1929 // TODO(edisonn): perf - use current clip too.
1930 // Retrieve the bounds of the new shape.
1931 SkRect bounds = perspectiveOutline.getBounds();
1932
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001933 // Transform the bitmap in the new space, taking into
1934 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001935 SkMatrix total = transform;
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001936 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07001937
Hal Canaryd791a6f2018-09-28 12:14:08 -04001938 SkPath physicalPerspectiveOutline = to_path(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001939 physicalPerspectiveOutline.transform(total);
1940
halcanary7a14b312015-10-01 07:28:13 -07001941 SkRect physicalPerspectiveBounds =
1942 physicalPerspectiveOutline.getBounds();
1943 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
1944 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001945
1946 // TODO(edisonn): A better approach would be to use a bitmap shader
1947 // (in clamp mode) and draw a rect over the entire bounding box. Then
1948 // intersect perspectiveOutline to the clip. That will avoid introducing
1949 // alpha to the image while still giving good behavior at the edge of
1950 // the image. Avoiding alpha will reduce the pdf size and generation
1951 // CPU time some.
1952
halcanary7a14b312015-10-01 07:28:13 -07001953 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
1954
Hal Canaryf50ff392016-09-30 10:25:39 -04001955 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07001956 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00001957 return;
1958 }
halcanary7a14b312015-10-01 07:28:13 -07001959 SkCanvas* canvas = surface->getCanvas();
1960 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001961
1962 SkScalar deltaX = bounds.left();
1963 SkScalar deltaY = bounds.top();
1964
Hal Canary7cbf5e32017-07-12 13:10:23 -04001965 SkMatrix offsetMatrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001966 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001967 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001968
1969 // Translate the draw in the new canvas, so we perfectly fit the
1970 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07001971 canvas->setMatrix(offsetMatrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001972 canvas->drawImage(imageSubset.image(), 0, 0);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001973 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07001974 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001975
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001976 // In the new space, we use the identity matrix translated
1977 // and scaled to reflect DPI.
1978 matrix.setScale(1 / scaleX, 1 / scaleY);
1979 matrix.postTranslate(deltaX, deltaY);
1980
Hal Canary7cbf5e32017-07-12 13:10:23 -04001981 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1982 if (!imageSubset) {
1983 return;
1984 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001985 }
1986
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001987 SkMatrix scaled;
1988 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001989 scaled.setScale(SK_Scalar1, -SK_Scalar1);
1990 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001991 // Scale the image up from 1x1 to WxH.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001992 SkIRect subset = imageSubset.image()->bounds();
1993 scaled.postScale(SkIntToScalar(subset.width()),
1994 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001995 scaled.postConcat(matrix);
Hal Canaryd892a9d2018-09-24 21:20:47 -04001996 ScopedContentEntry content(this, &this->cs(), scaled, paint);
Hal Canary42137de2018-10-08 16:00:37 -04001997 if (!content) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001998 return;
1999 }
2000 if (content.needShape()) {
Hal Canaryd791a6f2018-09-28 12:14:08 -04002001 SkPath shape = to_path(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002002 shape.transform(matrix);
2003 content.setShape(shape);
2004 }
2005 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002006 return;
2007 }
2008
halcanary287d22d2015-09-24 10:20:05 -07002009 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002010 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2011 imageSubset = SkKeyedImage(std::move(img));
2012 if (!imageSubset) {
2013 return;
2014 }
halcanary7a14b312015-10-01 07:28:13 -07002015 // TODO(halcanary): de-dupe this by caching filtered images.
2016 // (maybe in the resource cache?)
2017 }
halcanarya50151d2016-03-25 11:57:49 -07002018
Hal Canary7cbf5e32017-07-12 13:10:23 -04002019 SkBitmapKey key = imageSubset.key();
Hal Canary9a3f5542018-12-10 19:59:07 -05002020 SkPDFIndirectReference* pdfimagePtr = fDocument->canon()->fPDFBitmapMap.find(key);
2021 SkPDFIndirectReference pdfimage = pdfimagePtr ? *pdfimagePtr : SkPDFIndirectReference();
2022 if (!pdfimagePtr) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002023 SkASSERT(imageSubset);
Hal Canary9a3f5542018-12-10 19:59:07 -05002024 pdfimage = SkPDFSerializeImage(imageSubset.image().get(), fDocument,
Hal Canarya1211832018-11-13 16:45:14 -05002025 fDocument->metadata().fEncodingQuality);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002026 SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
Hal Canary5c1b3602017-04-17 16:30:06 -04002027 fDocument->canon()->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002028 }
Hal Canary9a3f5542018-12-10 19:59:07 -05002029 SkASSERT(pdfimage != SkPDFIndirectReference());
2030 this->drawFormXObject(pdfimage, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002031}
reede51c3562016-07-19 14:33:20 -07002032
2033///////////////////////////////////////////////////////////////////////////////////////////////////
2034
2035#include "SkSpecialImage.h"
2036#include "SkImageFilter.h"
2037
Florin Malita53f77bd2017-04-28 13:48:37 -04002038void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2039 SkImage* clipImage, const SkMatrix& clipMatrix) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05002040 if (this->hasEmptyClip()) {
2041 return;
2042 }
reede51c3562016-07-19 14:33:20 -07002043 SkASSERT(!srcImg->isTextureBacked());
2044
Florin Malita53f77bd2017-04-28 13:48:37 -04002045 //TODO: clipImage support
2046
reede51c3562016-07-19 14:33:20 -07002047 SkBitmap resultBM;
2048
2049 SkImageFilter* filter = paint.getImageFilter();
2050 if (filter) {
2051 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002052 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002053 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002054 const SkIRect clipBounds =
Hal Canary22b2d8c2017-07-19 14:46:12 -04002055 this->cs().bounds(this->bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002056 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
Brian Osmana50205f2018-07-06 13:57:01 -04002057 // TODO: Should PDF be operating in a specified color type/space? For now, run the filter
brianosman2a75e5d2016-09-22 07:15:37 -07002058 // in the same color space as the source (this is different from all other backends).
Brian Osmana50205f2018-07-06 13:57:01 -04002059 SkImageFilter::OutputProperties outputProperties(kN32_SkColorType, srcImg->getColorSpace());
brianosman2a75e5d2016-09-22 07:15:37 -07002060 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002061
2062 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2063 if (resultImg) {
2064 SkPaint tmpUnfiltered(paint);
2065 tmpUnfiltered.setImageFilter(nullptr);
2066 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002067 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002068 }
2069 }
2070 } else {
2071 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002072 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002073 }
2074 }
2075}
2076
2077sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2078 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2079}
2080
2081sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Robert Phillips27467652019-01-10 16:34:22 -05002082 return SkSpecialImage::MakeFromImage(nullptr, image->bounds(), image->makeNonTextureImage());
reede51c3562016-07-19 14:33:20 -07002083}
2084
2085sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002086 return nullptr;
2087}
brianosman04a44d02016-09-21 09:46:57 -07002088
2089SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2090 // We always return a transient cache, so it is freed after each
2091 // filter traversal.
2092 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2093}