blob: 7ba2c293d55ee302b21b0ec06bce0b0712aa7cf9 [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"
Hal Canary4ca9fa32018-12-21 16:15:01 -050028#include "SkPDFDocument.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
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000393// A helper class to automatically finish a ContentEntry at the end of a
394// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000395class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000396public:
Mike Reeda1361362017-03-07 09:37:29 -0500397 ScopedContentEntry(SkPDFDevice* device,
Hal Canaryd892a9d2018-09-24 21:20:47 -0400398 const SkClipStack* clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000399 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500400 const SkPaint& paint,
Hal Canary8f37ce52018-12-28 11:40:10 -0500401 SkScalar textScale = 0)
Mike Reeda1361362017-03-07 09:37:29 -0500402 : fDevice(device)
Mike Reeda1361362017-03-07 09:37:29 -0500403 , fBlendMode(SkBlendMode::kSrcOver)
Hal Canaryb400d4d2018-09-26 16:33:52 -0400404 , fClipStack(clipStack)
Mike Reeda1361362017-03-07 09:37:29 -0500405 {
406 if (matrix.hasPerspective()) {
407 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
408 return;
409 }
410 fBlendMode = paint.getBlendMode();
Hal Canary42137de2018-10-08 16:00:37 -0400411 fContentStream =
Hal Canary8f37ce52018-12-28 11:40:10 -0500412 fDevice->setUpContentEntry(clipStack, matrix, paint, textScale, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000413 }
Hal Canary8f37ce52018-12-28 11:40:10 -0500414 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, SkScalar textScale = 0)
415 : ScopedContentEntry(dev, &dev->cs(), dev->ctm(), paint, textScale) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000416
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000417 ~ScopedContentEntry() {
Hal Canary42137de2018-10-08 16:00:37 -0400418 if (fContentStream) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000419 SkPath* shape = &fShape;
420 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700421 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000422 }
Hal Canary9a3f5542018-12-10 19:59:07 -0500423 fDevice->finishContentEntry(fClipStack, fBlendMode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000424 }
425 }
426
Hal Canary42137de2018-10-08 16:00:37 -0400427 explicit operator bool() const { return fContentStream != nullptr; }
428 SkDynamicMemoryWStream* stream() { return fContentStream; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000429
430 /* Returns true when we explicitly need the shape of the drawing. */
431 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700432 switch (fBlendMode) {
433 case SkBlendMode::kClear:
434 case SkBlendMode::kSrc:
435 case SkBlendMode::kSrcIn:
436 case SkBlendMode::kSrcOut:
437 case SkBlendMode::kDstIn:
438 case SkBlendMode::kDstOut:
439 case SkBlendMode::kSrcATop:
440 case SkBlendMode::kDstATop:
441 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000442 return true;
443 default:
444 return false;
445 }
446 }
447
448 /* Returns true unless we only need the shape of the drawing. */
449 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700450 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000451 return false;
452 }
453 return true;
454 }
455
456 /* If the shape is different than the alpha component of the content, then
457 * setShape should be called with the shape. In particular, images and
458 * devices have rectangular shape.
459 */
460 void setShape(const SkPath& shape) {
461 fShape = shape;
462 }
463
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000464private:
Hal Canary42137de2018-10-08 16:00:37 -0400465 SkPDFDevice* fDevice = nullptr;
466 SkDynamicMemoryWStream* fContentStream = nullptr;
reed374772b2016-10-05 17:33:02 -0700467 SkBlendMode fBlendMode;
Hal Canary9a3f5542018-12-10 19:59:07 -0500468 SkPDFIndirectReference fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000469 SkPath fShape;
Hal Canaryb400d4d2018-09-26 16:33:52 -0400470 const SkClipStack* fClipStack;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000471};
472
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000473////////////////////////////////////////////////////////////////////////////////
474
Hal Canary7d06ab22018-09-10 14:39:13 -0400475SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc, const SkMatrix& transform)
reed589a39e2016-08-20 07:59:19 -0700476 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
477 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
Hal Canary7d06ab22018-09-10 14:39:13 -0400478 , fInitialTransform(transform)
Dominic Mazzoni656cefe2018-09-25 20:29:15 -0700479 , fNodeId(0)
Hal Canarya0622582017-06-29 18:51:35 -0400480 , fDocument(doc)
481{
Hal Canary22b2d8c2017-07-19 14:46:12 -0400482 SkASSERT(!pageSize.isEmpty());
Hal Canarya0622582017-06-29 18:51:35 -0400483}
robertphillips1f3923e2016-07-21 07:17:54 -0700484
Hal Canary9e41c212018-09-03 12:00:23 -0400485SkPDFDevice::~SkPDFDevice() = default;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000486
Hal Canary9e41c212018-09-03 12:00:23 -0400487void SkPDFDevice::reset() {
Hal Canary9e41c212018-09-03 12:00:23 -0400488 fLinkToURLs = std::vector<RectWithData>();
489 fLinkToDestinations = std::vector<RectWithData>();
490 fNamedDestinations = std::vector<NamedDestination>();
Hal Canary9a3f5542018-12-10 19:59:07 -0500491 fGraphicStateResources.reset();
492 fXObjectResources.reset();
493 fShaderResources.reset();
Hal Canaryb10f92e2018-11-16 17:01:50 -0500494 fFontResources.reset();
Hal Canary42137de2018-10-08 16:00:37 -0400495 fContent.reset();
Hal Canary813b5ac2018-09-28 12:30:37 -0400496 fActiveStackState = GraphicStackState();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000497}
498
Mike Reeda1361362017-03-07 09:37:29 -0500499void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500500 if (!value) {
501 return;
502 }
503 if (rect.isEmpty()) {
Dominic Mazzoni656cefe2018-09-25 20:29:15 -0700504 if (!strcmp(key, SkPDFGetNodeIdKey())) {
505 int nodeID;
506 if (value->size() != sizeof(nodeID)) { return; }
507 memcpy(&nodeID, value->data(), sizeof(nodeID));
508 fNodeId = nodeID;
509 return;
510 }
Mike Reeda1361362017-03-07 09:37:29 -0500511 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
512 SkPoint transformedPoint;
513 this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
Hal Canary5c1b3602017-04-17 16:30:06 -0400514 fNamedDestinations.emplace_back(NamedDestination{sk_ref_sp(value), transformedPoint});
Mike Reeda1361362017-03-07 09:37:29 -0500515 }
516 return;
517 }
518 // Convert to path to handle non-90-degree rotations.
Hal Canaryd791a6f2018-09-28 12:14:08 -0400519 SkPath path = to_path(rect);
Mike Reeda1361362017-03-07 09:37:29 -0500520 path.transform(this->ctm(), &path);
521 SkPath clip;
522 (void)this->cs().asPath(&clip);
523 Op(clip, path, kIntersect_SkPathOp, &path);
524 // PDF wants a rectangle only.
525 SkRect transformedRect = path.getBounds();
526 if (transformedRect.isEmpty()) {
527 return;
528 }
529 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400530 fLinkToURLs.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
Mike Reeda1361362017-03-07 09:37:29 -0500531 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400532 fLinkToDestinations.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
reedf70b5312016-03-04 16:36:20 -0800533 }
534}
535
Hal Canaryd12a6762017-05-26 17:01:16 -0400536void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
Hal Canaryabf8e412018-09-24 11:37:23 -0400537 SkMatrix inverse;
538 if (!this->ctm().invert(&inverse)) {
539 return;
540 }
541 SkRect bbox = this->cs().bounds(this->bounds());
542 inverse.mapRect(&bbox);
543 bbox.roundOut(&bbox);
Hal Canaryb4e528d2018-03-09 16:02:15 -0500544 if (this->hasEmptyClip()) {
545 return;
546 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400547 SkPaint newPaint = srcPaint;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000548 newPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryabf8e412018-09-24 11:37:23 -0400549 this->drawRect(bbox, newPaint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000550}
551
Mike Reeda1361362017-03-07 09:37:29 -0500552void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700553 size_t count,
554 const SkPoint* points,
555 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500556 if (this->hasEmptyClip()) {
557 return;
558 }
halcanarya6814332015-05-27 08:53:36 -0700559 SkPaint passedPaint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400560 remove_color_filter(&passedPaint);
halcanarya6814332015-05-27 08:53:36 -0700561 replace_srcmode_on_opaque_paint(&passedPaint);
Hal Canary80fa7ce2017-06-28 16:04:20 -0400562 if (SkCanvas::kPoints_PointMode != mode) {
563 passedPaint.setStyle(SkPaint::kStroke_Style);
564 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000565 if (count == 0) {
566 return;
567 }
568
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000569 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
570 // We only use this when there's a path effect because of the overhead
571 // of multiple calls to setUpContentEntry it causes.
572 if (passedPaint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500573 draw_points(mode, count, points, passedPaint,
574 this->devClipBounds(), this->ctm(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000575 return;
576 }
577
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000578 const SkPaint* paint = &passedPaint;
579 SkPaint modifiedPaint;
580
581 if (mode == SkCanvas::kPoints_PointMode &&
582 paint->getStrokeCap() != SkPaint::kRound_Cap) {
583 modifiedPaint = *paint;
584 paint = &modifiedPaint;
585 if (paint->getStrokeWidth()) {
586 // PDF won't draw a single point with square/butt caps because the
587 // orientation is ambiguous. Draw a rectangle instead.
588 modifiedPaint.setStyle(SkPaint::kFill_Style);
589 SkScalar strokeWidth = paint->getStrokeWidth();
590 SkScalar halfStroke = SkScalarHalf(strokeWidth);
591 for (size_t i = 0; i < count; i++) {
592 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
593 r.inset(-halfStroke, -halfStroke);
Mike Reeda1361362017-03-07 09:37:29 -0500594 this->drawRect(r, modifiedPaint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000595 }
596 return;
597 } else {
598 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
599 }
600 }
601
Mike Reeda1361362017-03-07 09:37:29 -0500602 ScopedContentEntry content(this, *paint);
Hal Canary42137de2018-10-08 16:00:37 -0400603 if (!content) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000604 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000605 }
Hal Canary51329c92017-06-27 14:28:37 -0400606 SkDynamicMemoryWStream* contentStream = content.stream();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000607 switch (mode) {
608 case SkCanvas::kPolygon_PointMode:
Hal Canary51329c92017-06-27 14:28:37 -0400609 SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000610 for (size_t i = 1; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400611 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000612 }
Hal Canary51329c92017-06-27 14:28:37 -0400613 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000614 break;
615 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000616 for (size_t i = 0; i < count/2; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400617 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
618 SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
619 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000620 }
621 break;
622 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000623 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
624 for (size_t i = 0; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400625 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
626 SkPDFUtils::ClosePath(contentStream);
627 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000628 }
629 break;
630 default:
631 SkASSERT(false);
632 }
633}
634
Hal Canary74801582018-12-18 16:30:41 -0500635static std::unique_ptr<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
636 auto annotation = SkPDFMakeDict("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700637 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700638 annotation->insertInt("F", 4); // required by ISO 19005
Hal Canarye650b852018-09-12 09:12:36 -0400639 // Border: 0 = Horizontal corner radius.
640 // 0 = Vertical corner radius.
641 // 0 = Width, 0 = no border.
642 annotation->insertObject("Border", SkPDFMakeArray(0, 0, 0));
wangxianzhud76665d2015-07-17 17:23:15 -0700643
Hal Canarye650b852018-09-12 09:12:36 -0400644 annotation->insertObject("Rect", SkPDFMakeArray(translatedRect.fLeft,
645 translatedRect.fTop,
646 translatedRect.fRight,
647 translatedRect.fBottom));
halcanary8103a342016-03-08 15:10:16 -0800648 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700649}
650
Hal Canary74801582018-12-18 16:30:41 -0500651static std::unique_ptr<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
652 std::unique_ptr<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700653 SkString url(static_cast<const char *>(urlData->data()),
654 urlData->size() - 1);
Hal Canary74801582018-12-18 16:30:41 -0500655 auto action = SkPDFMakeDict("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700656 action->insertName("S", "URI");
657 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800658 annotation->insertObject("A", std::move(action));
659 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700660}
661
Hal Canary74801582018-12-18 16:30:41 -0500662static std::unique_ptr<SkPDFDict> create_link_named_dest(const SkData* nameData,
663 const SkRect& r) {
664 std::unique_ptr<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700665 SkString name(static_cast<const char *>(nameData->data()),
666 nameData->size() - 1);
667 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800668 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700669}
670
Mike Reeda1361362017-03-07 09:37:29 -0500671void SkPDFDevice::drawRect(const SkRect& rect,
halcanarya6814332015-05-27 08:53:36 -0700672 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500673 if (this->hasEmptyClip()) {
674 return;
675 }
halcanarya6814332015-05-27 08:53:36 -0700676 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400677 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700678 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000679 SkRect r = rect;
680 r.sort();
681
Hal Canary8b354dc2018-09-20 12:51:22 -0400682 if (paint.getPathEffect() || paint.getMaskFilter() || this->ctm().hasPerspective()) {
Hal Canaryd791a6f2018-09-28 12:14:08 -0400683 this->drawPath(to_path(r), paint, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000684 return;
685 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000686
Mike Reeda1361362017-03-07 09:37:29 -0500687 ScopedContentEntry content(this, paint);
Hal Canary42137de2018-10-08 16:00:37 -0400688 if (!content) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000689 return;
690 }
Hal Canary51329c92017-06-27 14:28:37 -0400691 SkPDFUtils::AppendRectangle(r, content.stream());
692 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000693}
694
Mike Reeda1361362017-03-07 09:37:29 -0500695void SkPDFDevice::drawRRect(const SkRRect& rrect,
halcanarya6814332015-05-27 08:53:36 -0700696 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500697 if (this->hasEmptyClip()) {
698 return;
699 }
halcanarya6814332015-05-27 08:53:36 -0700700 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400701 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700702 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000703 SkPath path;
704 path.addRRect(rrect);
Robert Phillips137ca522018-08-15 10:14:33 -0400705 this->drawPath(path, paint, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000706}
707
Mike Reeda1361362017-03-07 09:37:29 -0500708void SkPDFDevice::drawOval(const SkRect& oval,
halcanarya6814332015-05-27 08:53:36 -0700709 const SkPaint& srcPaint) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500710 if (this->hasEmptyClip()) {
711 return;
712 }
halcanarya6814332015-05-27 08:53:36 -0700713 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400714 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700715 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700716 SkPath path;
717 path.addOval(oval);
Robert Phillips137ca522018-08-15 10:14:33 -0400718 this->drawPath(path, paint, true);
reed89443ab2014-06-27 11:34:19 -0700719}
720
Mike Reeda1361362017-03-07 09:37:29 -0500721void SkPDFDevice::drawPath(const SkPath& origPath,
halcanarya6814332015-05-27 08:53:36 -0700722 const SkPaint& srcPaint,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000723 bool pathIsMutable) {
Robert Phillips137ca522018-08-15 10:14:33 -0400724 this->internalDrawPath(this->cs(), this->ctm(), origPath, srcPaint, pathIsMutable);
Mike Reeda1361362017-03-07 09:37:29 -0500725}
726
Hal Canaryd12a6762017-05-26 17:01:16 -0400727void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
728 const SkMatrix& ctm,
729 const SkPath& origPath,
Robert Phillips137ca522018-08-15 10:14:33 -0400730 const SkPaint& origPaint) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400731 SkASSERT(origPaint.getMaskFilter());
732 SkPath path(origPath);
733 SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
Robert Phillips137ca522018-08-15 10:14:33 -0400734
Hal Canaryd12a6762017-05-26 17:01:16 -0400735 SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
736 ? SkStrokeRec::kFill_InitStyle
737 : SkStrokeRec::kHairline_InitStyle;
738 path.transform(ctm, &path);
739
Hal Canary22b2d8c2017-07-19 14:46:12 -0400740 SkIRect bounds = clipStack.bounds(this->bounds()).roundOut();
Hal Canaryd12a6762017-05-26 17:01:16 -0400741 SkMask sourceMask;
742 if (!SkDraw::DrawToMask(path, &bounds, paint->getMaskFilter(), &SkMatrix::I(),
743 &sourceMask, SkMask::kComputeBoundsAndRenderImage_CreateMode,
744 initStyle)) {
745 return;
746 }
747 SkAutoMaskFreeImage srcAutoMaskFreeImage(sourceMask.fImage);
748 SkMask dstMask;
749 SkIPoint margin;
Mike Reed80747ef2018-01-23 15:29:32 -0500750 if (!as_MFB(paint->getMaskFilter())->filterMask(&dstMask, sourceMask, ctm, &margin)) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400751 return;
752 }
Hal Canary51329c92017-06-27 14:28:37 -0400753 SkIRect dstMaskBounds = dstMask.fBounds;
754 sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
Hal Canaryd12a6762017-05-26 17:01:16 -0400755 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
756 // Must mask with a Form XObject.
Hal Canary51329c92017-06-27 14:28:37 -0400757 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
Hal Canaryd12a6762017-05-26 17:01:16 -0400758 {
Herb Derbyefe39bc2018-05-01 17:06:20 -0400759 SkCanvas canvas(maskDevice);
Hal Canary51329c92017-06-27 14:28:37 -0400760 canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
Hal Canaryd12a6762017-05-26 17:01:16 -0400761 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400762 if (!ctm.isIdentity() && paint->getShader()) {
763 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
764 }
Hal Canaryd892a9d2018-09-24 21:20:47 -0400765 ScopedContentEntry content(this, &clipStack, SkMatrix::I(), *paint);
Hal Canary42137de2018-10-08 16:00:37 -0400766 if (!content) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400767 return;
768 }
Hal Canary51329c92017-06-27 14:28:37 -0400769 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
770 SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
771 SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
772 this->clearMaskOnGraphicState(content.stream());
773}
Hal Canaryd12a6762017-05-26 17:01:16 -0400774
Hal Canary9a3f5542018-12-10 19:59:07 -0500775void SkPDFDevice::setGraphicState(SkPDFIndirectReference gs, SkDynamicMemoryWStream* content) {
776 SkPDFUtils::ApplyGraphicState(add_resource(fGraphicStateResources, gs), content);
Hal Canary3b8b11e2018-09-29 22:31:34 -0400777}
778
Hal Canary51329c92017-06-27 14:28:37 -0400779void SkPDFDevice::addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,
780 SkDynamicMemoryWStream* contentStream) {
Hal Canary3b8b11e2018-09-29 22:31:34 -0400781 this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
Hal Canaryb4bd5ef2017-07-26 09:16:01 -0400782 maskDevice->makeFormXObjectFromDevice(true), false,
Hal Canary9a3f5542018-12-10 19:59:07 -0500783 SkPDFGraphicState::kLuminosity_SMaskMode, fDocument), contentStream);
Hal Canary51329c92017-06-27 14:28:37 -0400784}
Hal Canaryd12a6762017-05-26 17:01:16 -0400785
Hal Canary51329c92017-06-27 14:28:37 -0400786void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400787 // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
Hal Canary4ca9fa32018-12-21 16:15:01 -0500788 SkPDFIndirectReference& noSMaskGS = fDocument->fNoSmaskGraphicState;
Hal Canaryc02de0b2017-06-28 13:14:03 -0400789 if (!noSMaskGS) {
Hal Canary9a3f5542018-12-10 19:59:07 -0500790 SkPDFDict tmp("ExtGState");
791 tmp.insertName("SMask", "None");
792 noSMaskGS = fDocument->emit(tmp);
Hal Canaryc02de0b2017-06-28 13:14:03 -0400793 }
Hal Canary3b8b11e2018-09-29 22:31:34 -0400794 this->setGraphicState(noSMaskGS, contentStream);
Hal Canaryd12a6762017-05-26 17:01:16 -0400795}
796
Mike Reeda1361362017-03-07 09:37:29 -0500797void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
798 const SkMatrix& ctm,
799 const SkPath& origPath,
800 const SkPaint& srcPaint,
Mike Reeda1361362017-03-07 09:37:29 -0500801 bool pathIsMutable) {
Hal Canaryb4e528d2018-03-09 16:02:15 -0500802 if (clipStack.isEmpty(this->bounds())) {
803 return;
804 }
halcanarya6814332015-05-27 08:53:36 -0700805 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400806 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700807 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800808 SkPath modifiedPath;
809 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000810
Hal Canaryd12a6762017-05-26 17:01:16 -0400811 if (paint.getMaskFilter()) {
Robert Phillips137ca522018-08-15 10:14:33 -0400812 this->internalDrawPathWithFilter(clipStack, ctm, origPath, paint);
Hal Canaryd12a6762017-05-26 17:01:16 -0400813 return;
814 }
815
Mike Reeda1361362017-03-07 09:37:29 -0500816 SkMatrix matrix = ctm;
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000817
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000818 if (paint.getPathEffect()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400819 if (clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000820 return;
821 }
halcanary682ee012016-01-28 10:59:34 -0800822 if (!pathIsMutable) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400823 modifiedPath = origPath;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000824 pathPtr = &modifiedPath;
825 pathIsMutable = true;
826 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400827 if (paint.getFillPath(*pathPtr, pathPtr)) {
828 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000829 } else {
Hal Canaryd12a6762017-05-26 17:01:16 -0400830 paint.setStyle(SkPaint::kStroke_Style);
831 paint.setStrokeWidth(0);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000832 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400833 paint.setPathEffect(nullptr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000834 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000835
Robert Phillips137ca522018-08-15 10:14:33 -0400836 if (this->handleInversePath(*pathPtr, paint, pathIsMutable)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000837 return;
838 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400839 if (matrix.getType() & SkMatrix::kPerspective_Mask) {
840 if (!pathIsMutable) {
841 modifiedPath = origPath;
842 pathPtr = &modifiedPath;
843 pathIsMutable = true;
844 }
845 pathPtr->transform(matrix);
846 if (paint.getShader()) {
847 transform_shader(&paint, matrix);
848 }
849 matrix = SkMatrix::I();
850 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000851
Hal Canaryd892a9d2018-09-24 21:20:47 -0400852 ScopedContentEntry content(this, &clipStack, matrix, paint);
Hal Canary42137de2018-10-08 16:00:37 -0400853 if (!content) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000854 return;
855 }
Hal Canarydfaa0572017-11-27 09:33:44 -0500856 constexpr SkScalar kToleranceScale = 0.0625f; // smaller = better conics (circles).
Hal Canary385468f2017-02-13 11:03:23 -0500857 SkScalar matrixScale = matrix.mapRadius(1.0f);
Hal Canarydfaa0572017-11-27 09:33:44 -0500858 SkScalar tolerance = matrixScale > 0.0f ? kToleranceScale / matrixScale : kToleranceScale;
halcanary8b2bc252015-10-06 09:41:47 -0700859 bool consumeDegeratePathSegments =
860 paint.getStyle() == SkPaint::kFill_Style ||
861 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
862 paint.getStrokeCap() != SkPaint::kSquare_Cap);
Hal Canary51329c92017-06-27 14:28:37 -0400863 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(), consumeDegeratePathSegments, content.stream(),
Hal Canary385468f2017-02-13 11:03:23 -0500864 tolerance);
Hal Canary51329c92017-06-27 14:28:37 -0400865 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000866}
867
Hal Canary7cbf5e32017-07-12 13:10:23 -0400868////////////////////////////////////////////////////////////////////////////////
Hal Canaryf50ff392016-09-30 10:25:39 -0400869
Mike Reeda1361362017-03-07 09:37:29 -0500870void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400871 const SkRect* src,
872 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400873 const SkPaint& paint,
Hal Canaryf50ff392016-09-30 10:25:39 -0400874 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400875 SkASSERT(image);
876 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
877 src, dst, paint, this->ctm());
Hal Canaryf50ff392016-09-30 10:25:39 -0400878}
879
Hal Canary7cbf5e32017-07-12 13:10:23 -0400880void SkPDFDevice::drawBitmapRect(const SkBitmap& bm,
halcanary7a14b312015-10-01 07:28:13 -0700881 const SkRect* src,
882 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400883 const SkPaint& paint,
Mike Reeda1361362017-03-07 09:37:29 -0500884 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400885 SkASSERT(!bm.drawsNothing());
886 this->internalDrawImageRect(SkKeyedImage(bm), src, dst, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700887}
888
Hal Canary7cbf5e32017-07-12 13:10:23 -0400889void SkPDFDevice::drawBitmap(const SkBitmap& bm, SkScalar x, SkScalar y, const SkPaint& paint) {
890 SkASSERT(!bm.drawsNothing());
891 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
892 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700893}
894
Hal Canary7cbf5e32017-07-12 13:10:23 -0400895void SkPDFDevice::drawSprite(const SkBitmap& bm, int x, int y, const SkPaint& paint) {
896 SkASSERT(!bm.drawsNothing());
897 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
898 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, SkMatrix::I());
halcanary7a14b312015-10-01 07:28:13 -0700899}
900
Hal Canary7cbf5e32017-07-12 13:10:23 -0400901void SkPDFDevice::drawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint& paint) {
902 SkASSERT(image);
903 auto r = SkRect::MakeXYWH(x, y, image->width(), image->height());
904 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
905 nullptr, r, paint, this->ctm());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000906}
907
Hal Canary7cbf5e32017-07-12 13:10:23 -0400908////////////////////////////////////////////////////////////////////////////////
909
halcanaryf0c30f52016-07-15 13:35:45 -0700910namespace {
911class GlyphPositioner {
912public:
913 GlyphPositioner(SkDynamicMemoryWStream* content,
914 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -0700915 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -0700916 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -0700917 , fCurrentMatrixOrigin(origin)
Hal Canary8ef78ea2018-10-01 13:38:30 -0400918 , fTextSkewX(textSkewX) {
halcanaryf0c30f52016-07-15 13:35:45 -0700919 }
halcanary4871f222016-08-26 13:17:44 -0700920 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -0700921 void flush() {
922 if (fInText) {
923 fContent->writeText("> Tj\n");
924 fInText = false;
925 }
926 }
Hal Canary8ef78ea2018-10-01 13:38:30 -0400927 void setWideChars(bool wide) {
928 this->flush();
929 fWideChars = wide;
930 }
halcanary4871f222016-08-26 13:17:44 -0700931 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -0700932 SkScalar advanceWidth,
933 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -0700934 if (!fInitialized) {
935 // Flip the text about the x-axis to account for origin swap and include
936 // the passed parameters.
937 fContent->writeText("1 0 ");
938 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
939 fContent->writeText(" -1 ");
940 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
941 fContent->writeText(" ");
942 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
943 fContent->writeText(" Tm\n");
944 fCurrentMatrixOrigin.set(0.0f, 0.0f);
945 fInitialized = true;
946 }
Hal Canary98caedd2018-07-23 10:50:49 -0400947 SkPoint position = xy - fCurrentMatrixOrigin;
948 if (position != SkPoint{fXAdvance, 0}) {
949 this->flush();
950 SkPDFUtils::AppendScalar(position.x() - position.y() * fTextSkewX, fContent);
951 fContent->writeText(" ");
952 SkPDFUtils::AppendScalar(-position.y(), fContent);
953 fContent->writeText(" Td ");
954 fCurrentMatrixOrigin = xy;
955 fXAdvance = 0;
halcanaryf0c30f52016-07-15 13:35:45 -0700956 }
Hal Canary98caedd2018-07-23 10:50:49 -0400957 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -0700958 if (!fInText) {
959 fContent->writeText("<");
960 fInText = true;
961 }
962 if (fWideChars) {
963 SkPDFUtils::WriteUInt16BE(fContent, glyph);
964 } else {
965 SkASSERT(0 == glyph >> 8);
966 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
967 }
halcanaryf0c30f52016-07-15 13:35:45 -0700968 }
969
970private:
971 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -0700972 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -0700973 SkScalar fXAdvance = 0.0f;
974 SkScalar fTextSkewX;
Hal Canary8ef78ea2018-10-01 13:38:30 -0400975 bool fWideChars = true;
halcanaryc2f9ec12016-09-12 08:55:29 -0700976 bool fInText = false;
977 bool fInitialized = false;
halcanaryf0c30f52016-07-15 13:35:45 -0700978};
979} // namespace
980
Hal Canary46cc3da2018-05-09 11:50:34 -0400981static SkUnichar map_glyph(const std::vector<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
982 return glyph < glyphToUnicode.size() ? glyphToUnicode[SkToInt(glyph)] : -1;
halcanaryf59d18a2016-09-16 14:44:57 -0700983}
984
Hal Canary575be302018-09-28 15:01:14 -0400985namespace {
986struct PositionedGlyph {
987 SkPoint fPos;
988 SkGlyphID fGlyph;
989};
Hal Canaryd12a6762017-05-26 17:01:16 -0400990}
991
Hal Canary699b8732017-06-13 12:13:29 -0400992static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkGlyphCache* cache,
993 SkScalar xScale, SkScalar yScale,
994 SkPoint xy, const SkMatrix& ctm) {
995 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
996 SkRect glyphBounds = {glyph.fLeft * xScale,
997 glyph.fTop * yScale,
998 (glyph.fLeft + glyph.fWidth) * xScale,
999 (glyph.fTop + glyph.fHeight) * yScale};
1000 glyphBounds.offset(xy);
1001 ctm.mapRect(&glyphBounds); // now in dev space.
1002 return glyphBounds;
1003}
1004
1005static bool contains(const SkRect& r, SkPoint p) {
1006 return r.left() <= p.x() && p.x() <= r.right() &&
1007 r.top() <= p.y() && p.y() <= r.bottom();
1008}
1009
Herb Derby95e17602018-12-06 17:11:43 -05001010void SkPDFDevice::drawGlyphRunAsPath(
1011 const SkGlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint) {
Hal Canary8f37ce52018-12-28 11:40:10 -05001012 const SkFont& font = glyphRun.font();
Hal Canary575be302018-09-28 15:01:14 -04001013 SkPath path;
Herb Derby4fce0832018-10-02 11:04:29 -04001014
Mike Reedab8f2972018-12-05 13:20:29 -05001015 struct Rec {
1016 SkPath* fPath;
1017 SkPoint fOffset;
1018 const SkPoint* fPos;
1019 } rec = {&path, offset, glyphRun.positions().data()};
1020
1021 font.getPaths(glyphRun.glyphsIDs().data(), glyphRun.glyphsIDs().size(),
1022 [](const SkPath* path, const SkMatrix& mx, void* ctx) {
1023 Rec* rec = reinterpret_cast<Rec*>(ctx);
1024 if (path) {
1025 SkMatrix total = mx;
1026 total.postTranslate(rec->fPos->fX + rec->fOffset.fX,
1027 rec->fPos->fY + rec->fOffset.fY);
1028 rec->fPath->addPath(*path, total);
1029 }
1030 rec->fPos += 1; // move to the next glyph's position
1031 }, &rec);
Hal Canary8f37ce52018-12-28 11:40:10 -05001032 this->drawPath(path, runPaint, true);
Hal Canary575be302018-09-28 15:01:14 -04001033
Herb Derby95e17602018-12-06 17:11:43 -05001034 SkFont transparentFont = glyphRun.font();
1035 transparentFont.setEmbolden(false); // Stop Recursion
1036 SkGlyphRun tmpGlyphRun(glyphRun, transparentFont);
1037
Herb Derby9bb6b7e2018-11-02 13:57:58 -04001038 SkPaint transparent;
Herb Derby9bb6b7e2018-11-02 13:57:58 -04001039 transparent.setColor(SK_ColorTRANSPARENT);
Herb Derby9bb6b7e2018-11-02 13:57:58 -04001040
Hal Canary575be302018-09-28 15:01:14 -04001041 if (this->ctm().hasPerspective()) {
1042 SkMatrix prevCTM = this->ctm();
1043 this->setCTM(SkMatrix::I());
Herb Derby95e17602018-12-06 17:11:43 -05001044 this->internalDrawGlyphRun(tmpGlyphRun, offset, transparent);
Hal Canary575be302018-09-28 15:01:14 -04001045 this->setCTM(prevCTM);
1046 } else {
Herb Derby95e17602018-12-06 17:11:43 -05001047 this->internalDrawGlyphRun(tmpGlyphRun, offset, transparent);
Hal Canary575be302018-09-28 15:01:14 -04001048 }
Hal Canary575be302018-09-28 15:01:14 -04001049}
1050
Hal Canary688afdd2018-10-17 14:57:53 -04001051static bool needs_new_font(SkPDFFont* font, SkGlyphID gid, SkGlyphCache* cache,
1052 SkAdvancedTypefaceMetrics::FontType fontType) {
1053 if (!font || !font->hasGlyph(gid)) {
1054 return true;
1055 }
1056 if (fontType == SkAdvancedTypefaceMetrics::kOther_Font) {
1057 return false;
1058 }
1059 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1060 if (glyph.isEmpty()) {
1061 return false;
1062 }
1063
1064 bool bitmapOnly = nullptr == cache->findPath(glyph);
1065 bool convertedToType3 = (font->getType() == SkAdvancedTypefaceMetrics::kOther_Font);
1066 return convertedToType3 != bitmapOnly;
1067}
1068
Herb Derby95e17602018-12-06 17:11:43 -05001069void SkPDFDevice::internalDrawGlyphRun(
1070 const SkGlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint) {
Hal Canary98caedd2018-07-23 10:50:49 -04001071
Herb Derbyaedc9d22018-10-25 12:27:07 -04001072 const SkGlyphID* glyphs = glyphRun.glyphsIDs().data();
1073 uint32_t glyphCount = SkToU32(glyphRun.glyphsIDs().size());
Hal Canary8f37ce52018-12-28 11:40:10 -05001074 const SkFont& glyphRunFont = glyphRun.font();
Herb Derby4fce0832018-10-02 11:04:29 -04001075
Hal Canary8f37ce52018-12-28 11:40:10 -05001076 if (!glyphCount || !glyphs || glyphRunFont.getSize() <= 0 || this->hasEmptyClip()) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001077 return;
1078 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001079 if (runPaint.getPathEffect()
1080 || runPaint.getMaskFilter()
1081 || glyphRunFont.isEmbolden()
Hal Canary92c500b2018-09-19 16:19:45 -04001082 || this->ctm().hasPerspective()
Hal Canary8f37ce52018-12-28 11:40:10 -05001083 || SkPaint::kFill_Style != runPaint.getStyle()) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001084 // Stroked Text doesn't work well with Type3 fonts.
Herb Derby95e17602018-12-06 17:11:43 -05001085 this->drawGlyphRunAsPath(glyphRun, offset, runPaint);
Hal Canarye9a29c42018-12-07 13:44:26 -05001086 return;
halcanarye06ca962016-09-09 05:34:55 -07001087 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001088 SkTypeface* typeface = SkFontPriv::GetTypefaceOrDefault(glyphRunFont);
halcanary4ed2f012016-08-15 18:40:07 -07001089 if (!typeface) {
1090 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1091 return;
1092 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001093
Hal Canary4ca9fa32018-12-21 16:15:01 -05001094 const SkAdvancedTypefaceMetrics* metrics = SkPDFFont::GetMetrics(typeface, fDocument);
halcanary4871f222016-08-26 13:17:44 -07001095 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001096 return;
1097 }
Hal Canary688afdd2018-10-17 14:57:53 -04001098 SkAdvancedTypefaceMetrics::FontType fontType = SkPDFFont::FontType(*metrics);
1099
Hal Canary4ca9fa32018-12-21 16:15:01 -05001100 const std::vector<SkUnichar>& glyphToUnicode = SkPDFFont::GetUnicodeMap(typeface, fDocument);
Hal Canary46cc3da2018-05-09 11:50:34 -04001101
Hal Canary98caedd2018-07-23 10:50:49 -04001102 SkClusterator clusterator(glyphRun);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001103
1104 int emSize;
Herb Derby1a605cd2018-03-22 11:16:25 -04001105 auto glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001106
Hal Canary8f37ce52018-12-28 11:40:10 -05001107 SkScalar textSize = glyphRunFont.getSize();
1108 SkScalar advanceScale = textSize * glyphRunFont.getScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001109
Hal Canary699b8732017-06-13 12:13:29 -04001110 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1111 SkScalar textScaleY = textSize / emSize;
Hal Canary8f37ce52018-12-28 11:40:10 -05001112 SkScalar textScaleX = advanceScale + glyphRunFont.getSkewX() * textScaleY;
Hal Canary699b8732017-06-13 12:13:29 -04001113
Hal Canary22b2d8c2017-07-19 14:46:12 -04001114 SkRect clipStackBounds = this->cs().bounds(this->bounds());
Hal Canary9b9510a2017-07-18 09:39:00 -04001115
Hal Canary8f37ce52018-12-28 11:40:10 -05001116 SkPaint paint(runPaint);
1117 remove_color_filter(&paint);
1118 replace_srcmode_on_opaque_paint(&paint);
1119 ScopedContentEntry content(this, paint, glyphRunFont.getScaleX());
1120 if (!content) {
1121 return;
1122 }
1123 SkDynamicMemoryWStream* out = content.stream();
Dominic Mazzoni656cefe2018-09-25 20:29:15 -07001124
Hal Canary8f37ce52018-12-28 11:40:10 -05001125 out->writeText("BT\n");
Dominic Mazzoni656cefe2018-09-25 20:29:15 -07001126
Hal Canary8f37ce52018-12-28 11:40:10 -05001127 int markId = -1;
1128 if (fNodeId) {
1129 markId = fDocument->getMarkIdForNodeId(fNodeId);
1130 }
Dominic Mazzoni656cefe2018-09-25 20:29:15 -07001131
Hal Canary8f37ce52018-12-28 11:40:10 -05001132 if (markId != -1) {
1133 out->writeText("/P <</MCID ");
1134 out->writeDecAsText(markId);
1135 out->writeText(" >>BDC\n");
1136 }
1137 SK_AT_SCOPE_EXIT(if (markId != -1) out->writeText("EMC\n"));
Hal Canary9b9510a2017-07-18 09:39:00 -04001138
Hal Canary8f37ce52018-12-28 11:40:10 -05001139 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
Hal Canary9b9510a2017-07-18 09:39:00 -04001140
Hal Canary8f37ce52018-12-28 11:40:10 -05001141 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
Hal Canary9b9510a2017-07-18 09:39:00 -04001142
Hal Canary8f37ce52018-12-28 11:40:10 -05001143 if (clusterator.reversedChars()) {
1144 out->writeText("/ReversedChars BMC\n");
1145 }
1146 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1147 GlyphPositioner glyphPositioner(out, glyphRunFont.getSkewX(), offset);
1148 SkPDFFont* font = nullptr;
Hal Canary9b9510a2017-07-18 09:39:00 -04001149
Hal Canary8f37ce52018-12-28 11:40:10 -05001150 while (SkClusterator::Cluster c = clusterator.next()) {
1151 int index = c.fGlyphIndex;
1152 int glyphLimit = index + c.fGlyphCount;
1153
1154 bool actualText = false;
1155 SK_AT_SCOPE_EXIT(if (actualText) {
1156 glyphPositioner.flush();
1157 out->writeText("EMC\n");
1158 });
1159 if (c.fUtf8Text) { // real cluster
1160 // Check if `/ActualText` needed.
1161 const char* textPtr = c.fUtf8Text;
1162 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1163 SkUnichar unichar = SkUTF::NextUTF8(&textPtr, textEnd);
1164 if (unichar < 0) {
1165 return;
halcanaryf59d18a2016-09-16 14:44:57 -07001166 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001167 if (textPtr < textEnd || // more characters left
1168 glyphLimit > index + 1 || // toUnicode wouldn't work
1169 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1170 {
1171 glyphPositioner.flush();
1172 out->writeText("/Span<</ActualText <");
1173 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1174 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1175 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1176 while (textPtr < textEnd) {
1177 unichar = SkUTF::NextUTF8(&textPtr, textEnd);
1178 if (unichar < 0) {
1179 break;
1180 }
1181 SkPDFUtils::WriteUTF16beHex(out, unichar);
1182 }
1183 out->writeText("> >> BDC\n"); // begin marked-content sequence
1184 // with an associated property list.
1185 actualText = true;
1186 }
1187 }
1188 for (; index < glyphLimit; ++index) {
1189 SkGlyphID gid = glyphs[index];
1190 if (gid > maxGlyphID) {
1191 continue;
1192 }
1193 SkPoint xy = glyphRun.positions()[index];
1194 // Do a glyph-by-glyph bounds-reject if positions are absolute.
1195 SkRect glyphBounds = get_glyph_bounds_device_space(
1196 gid, glyphCache.get(), textScaleX, textScaleY,
1197 xy + offset, this->ctm());
1198 if (glyphBounds.isEmpty()) {
1199 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
Hal Canary9b9510a2017-07-18 09:39:00 -04001200 continue;
halcanaryf59d18a2016-09-16 14:44:57 -07001201 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001202 } else {
1203 if (!clipStackBounds.intersects(glyphBounds)) {
1204 continue; // reject glyphs as out of bounds
Hal Canary688afdd2018-10-17 14:57:53 -04001205 }
halcanaryf59d18a2016-09-16 14:44:57 -07001206 }
Hal Canary8f37ce52018-12-28 11:40:10 -05001207 if (needs_new_font(font, gid, glyphCache.get(), fontType)) {
1208 // Not yet specified font or need to switch font.
1209 font = SkPDFFont::GetFontResource(fDocument, glyphCache.get(), typeface, gid);
1210 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1211 glyphPositioner.flush();
1212 glyphPositioner.setWideChars(font->multiByteGlyphs());
1213 SkPDFWriteResourceName(out, SkPDFResourceType::kFont,
1214 add_resource(fFontResources, font->indirectReference()));
1215 out->writeText(" ");
1216 SkPDFUtils::AppendScalar(textSize, out);
1217 out->writeText(" Tf\n");
1218
1219 }
1220 font->noteGlyphUsage(gid);
1221 SkGlyphID encodedGlyph = font->multiByteGlyphs()
1222 ? gid : font->glyphToPDFFontEncoding(gid);
1223 SkScalar advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1224 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
Hal Canary9b9510a2017-07-18 09:39:00 -04001225 }
1226 }
halcanary4ed2f012016-08-15 18:40:07 -07001227}
1228
Herb Derbyb935cf82018-07-26 16:54:18 -04001229void SkPDFDevice::drawGlyphRunList(const SkGlyphRunList& glyphRunList) {
1230 for (const SkGlyphRun& glyphRun : glyphRunList) {
Herb Derby95e17602018-12-06 17:11:43 -05001231 this->internalDrawGlyphRun(glyphRun, glyphRunList.origin(), glyphRunList.paint());
halcanarye06ca962016-09-09 05:34:55 -07001232 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001233}
1234
Ruiqi Maoc97a3392018-08-15 10:44:19 -04001235void SkPDFDevice::drawVertices(const SkVertices*, const SkVertices::Bone[], int, SkBlendMode,
Ruiqi Maof5101492018-06-29 14:32:21 -04001236 const SkPaint&) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05001237 if (this->hasEmptyClip()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001238 return;
1239 }
reed@google.com85e143c2013-12-30 15:51:25 +00001240 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001241}
1242
Hal Canary9a3f5542018-12-10 19:59:07 -05001243void SkPDFDevice::drawFormXObject(SkPDFIndirectReference xObject, SkDynamicMemoryWStream* content) {
1244 SkASSERT(xObject);
Hal Canary3b8b11e2018-09-29 22:31:34 -04001245 SkPDFWriteResourceName(content, SkPDFResourceType::kXObject,
Hal Canary9a3f5542018-12-10 19:59:07 -05001246 add_resource(fXObjectResources, xObject));
Hal Canarye650b852018-09-12 09:12:36 -04001247 content->writeText(" Do\n");
1248}
1249
Mike Reeda1361362017-03-07 09:37:29 -05001250void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001251 SkASSERT(!paint.getImageFilter());
1252
reed7503d602016-07-15 14:23:29 -07001253 // Check if the source device is really a bitmapdevice (because that's what we returned
1254 // from createDevice (likely due to an imagefilter)
1255 SkPixmap pmap;
1256 if (device->peekPixels(&pmap)) {
1257 SkBitmap bitmap;
1258 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001259 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001260 return;
1261 }
1262
fmalita6987dca2014-11-13 08:33:37 -08001263 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001264 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001265
1266 SkScalar scalarX = SkIntToScalar(x);
1267 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001268 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1269 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001270 fLinkToURLs.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001271 }
halcanary91fcb3e2016-03-04 13:53:22 -08001272 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1273 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001274 fLinkToDestinations.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001275 }
halcanary91fcb3e2016-03-04 13:53:22 -08001276 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1277 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001278 fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001279 }
1280
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001281 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001282 return;
1283 }
1284
Mike Reeda1361362017-03-07 09:37:29 -05001285 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
Hal Canaryd892a9d2018-09-24 21:20:47 -04001286 ScopedContentEntry content(this, &this->cs(), matrix, paint);
Hal Canary42137de2018-10-08 16:00:37 -04001287 if (!content) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001288 return;
1289 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001290 if (content.needShape()) {
Hal Canaryd791a6f2018-09-28 12:14:08 -04001291 SkISize dim = device->imageInfo().dimensions();
1292 content.setShape(to_path(SkRect::Make(SkIRect::MakeXYWH(x, y, dim.width(), dim.height()))));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001293 }
1294 if (!content.needSource()) {
1295 return;
1296 }
Hal Canary3b8b11e2018-09-29 22:31:34 -04001297 this->drawFormXObject(pdfDevice->makeFormXObjectFromDevice(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001298}
1299
reede8f30622016-03-23 18:59:25 -07001300sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1301 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001302}
1303
Hal Canary9a3f5542018-12-10 19:59:07 -05001304static std::vector<SkPDFIndirectReference> sort(const SkTHashSet<SkPDFIndirectReference>& src) {
1305 std::vector<SkPDFIndirectReference> dst;
1306 dst.reserve(src.count());
1307 src.foreach([&dst](SkPDFIndirectReference ref) { dst.push_back(ref); } );
1308 std::sort(dst.begin(), dst.end(),
1309 [](SkPDFIndirectReference a, SkPDFIndirectReference b) { return a.fValue < b.fValue; });
1310 return dst;
1311}
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001312
Hal Canary74801582018-12-18 16:30:41 -05001313std::unique_ptr<SkPDFDict> SkPDFDevice::makeResourceDict() {
Hal Canary9a3f5542018-12-10 19:59:07 -05001314 return SkPDFMakeResourceDict(sort(fGraphicStateResources),
1315 sort(fShaderResources),
1316 sort(fXObjectResources),
1317 sort(fFontResources));
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001318}
1319
Hal Canaryb400d4d2018-09-26 16:33:52 -04001320std::unique_ptr<SkStreamAsset> SkPDFDevice::content() {
1321 if (fActiveStackState.fContentStream) {
1322 fActiveStackState.drainStack();
1323 fActiveStackState = GraphicStackState();
1324 }
Hal Canary42137de2018-10-08 16:00:37 -04001325 if (fContent.bytesWritten() == 0) {
1326 return skstd::make_unique<SkMemoryStream>();
1327 }
halcanary334fcbc2015-02-24 12:56:16 -08001328 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001329 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
Hal Canarye650b852018-09-12 09:12:36 -04001330 append_transform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001331 }
Hal Canary42137de2018-10-08 16:00:37 -04001332 if (fNeedsExtraSave) {
1333 buffer.writeText("q\n");
halcanary2be7e012016-03-28 11:58:08 -07001334 }
Hal Canary42137de2018-10-08 16:00:37 -04001335 fContent.writeToAndReset(&buffer);
1336 if (fNeedsExtraSave) {
1337 buffer.writeText("Q\n");
halcanary022c2bd2016-09-02 11:29:46 -07001338 }
Hal Canary42137de2018-10-08 16:00:37 -04001339 fNeedsExtraSave = false;
1340 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001341}
1342
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001343/* Draws an inverse filled path by using Path Ops to compute the positive
1344 * inverse using the current clip as the inverse bounds.
1345 * Return true if this was an inverse path and was properly handled,
1346 * otherwise returns false and the normal drawing routine should continue,
1347 * either as a (incorrect) fallback or because the path was not inverse
1348 * in the first place.
1349 */
Mike Reeda1361362017-03-07 09:37:29 -05001350bool SkPDFDevice::handleInversePath(const SkPath& origPath,
Robert Phillips137ca522018-08-15 10:14:33 -04001351 const SkPaint& paint,
1352 bool pathIsMutable) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001353 if (!origPath.isInverseFillType()) {
1354 return false;
1355 }
1356
Hal Canaryb4e528d2018-03-09 16:02:15 -05001357 if (this->hasEmptyClip()) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001358 return false;
1359 }
1360
1361 SkPath modifiedPath;
1362 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1363 SkPaint noInversePaint(paint);
1364
1365 // Merge stroking operations into final path.
1366 if (SkPaint::kStroke_Style == paint.getStyle() ||
1367 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1368 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1369 if (doFillPath) {
1370 noInversePaint.setStyle(SkPaint::kFill_Style);
1371 noInversePaint.setStrokeWidth(0);
1372 pathPtr = &modifiedPath;
1373 } else {
1374 // To be consistent with the raster output, hairline strokes
1375 // are rendered as non-inverted.
1376 modifiedPath.toggleInverseFillType();
Robert Phillips137ca522018-08-15 10:14:33 -04001377 this->drawPath(modifiedPath, paint, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001378 return true;
1379 }
1380 }
1381
1382 // Get bounds of clip in current transform space
1383 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001384 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001385 SkMatrix totalMatrix = this->ctm();
Robert Phillips137ca522018-08-15 10:14:33 -04001386
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001387 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001388 return false;
1389 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001390 SkRect bounds = this->cs().bounds(this->bounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001391 transformInverse.mapRect(&bounds);
1392
1393 // Extend the bounds by the line width (plus some padding)
1394 // so the edge doesn't cause a visible stroke.
1395 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1396 paint.getStrokeWidth() + SK_Scalar1);
1397
1398 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1399 return false;
1400 }
1401
Robert Phillips137ca522018-08-15 10:14:33 -04001402 this->drawPath(modifiedPath, noInversePaint, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001403 return true;
1404}
1405
Hal Canary74801582018-12-18 16:30:41 -05001406std::unique_ptr<SkPDFArray> SkPDFDevice::getAnnotations() {
1407 std::unique_ptr<SkPDFArray> array;
Hal Canary9e41c212018-09-03 12:00:23 -04001408 size_t count = fLinkToURLs.size() + fLinkToDestinations.size();
1409 if (0 == count) {
1410 return array;
1411 }
Hal Canary74801582018-12-18 16:30:41 -05001412 array = SkPDFMakeArray();
Hal Canary9e41c212018-09-03 12:00:23 -04001413 array->reserve(count);
halcanary91fcb3e2016-03-04 13:53:22 -08001414 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001415 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001416 fInitialTransform.mapRect(&r, rectWithURL.rect);
Hal Canary9a3f5542018-12-10 19:59:07 -05001417 array->appendRef(fDocument->emit(*create_link_to_url(rectWithURL.data.get(), r)));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001418 }
halcanary91fcb3e2016-03-04 13:53:22 -08001419 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001420 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001421 fInitialTransform.mapRect(&r, linkToDestination.rect);
Hal Canary9a3f5542018-12-10 19:59:07 -05001422 array->appendRef(
1423 fDocument->emit(*create_link_named_dest(linkToDestination.data.get(), r)));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001424 }
Hal Canary9e41c212018-09-03 12:00:23 -04001425 return array;
wangxianzhuef6c50a2015-09-17 20:38:02 -07001426}
epoger@google.comb58772f2013-03-08 09:09:10 +00001427
Hal Canaryfba5b6c2018-12-18 12:55:18 -05001428void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFIndirectReference page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001429 for (const NamedDestination& dest : fNamedDestinations) {
Hal Canaryfba5b6c2018-12-18 12:55:18 -05001430 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
Hal Canary74801582018-12-18 16:30:41 -05001431 auto pdfDest = SkPDFMakeArray();
epoger@google.comb58772f2013-03-08 09:09:10 +00001432 pdfDest->reserve(5);
Hal Canaryfba5b6c2018-12-18 12:55:18 -05001433 pdfDest->appendRef(page);
epoger@google.comb58772f2013-03-08 09:09:10 +00001434 pdfDest->appendName("XYZ");
wangxianzhuef6c50a2015-09-17 20:38:02 -07001435 pdfDest->appendScalar(p.x());
1436 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001437 pdfDest->appendInt(0); // Leave zoom unchanged
Hal Canaryfba5b6c2018-12-18 12:55:18 -05001438 dict->insertObject(SkString(static_cast<const char*>(dest.nameData->data())),
1439 std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001440 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001441}
1442
Hal Canary9a3f5542018-12-10 19:59:07 -05001443SkPDFIndirectReference SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
halcanary5abbb442016-07-29 08:41:33 -07001444 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001445 if (!fInitialTransform.isIdentity()) {
1446 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001447 SkDEBUGFAIL("Layer initial transform should be invertible.");
1448 inverseTransform.reset();
1449 }
1450 }
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001451 const char* colorSpace = alpha ? "DeviceGray" : nullptr;
Hal Canarye650b852018-09-12 09:12:36 -04001452
Hal Canary9a3f5542018-12-10 19:59:07 -05001453 SkPDFIndirectReference xobject =
1454 SkPDFMakeFormXObject(fDocument, this->content(),
Hal Canarye650b852018-09-12 09:12:36 -04001455 SkPDFMakeArray(0, 0, this->width(), this->height()),
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001456 this->makeResourceDict(), inverseTransform, colorSpace);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001457 // We always draw the form xobjects that we create back into the device, so
1458 // we simply preserve the font usage instead of pulling it out and merging
1459 // it back in later.
Hal Canary9e41c212018-09-03 12:00:23 -04001460 this->reset();
reed@google.comfc641d02012-09-20 17:52:20 +00001461 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001462}
1463
Hal Canary9a3f5542018-12-10 19:59:07 -05001464void SkPDFDevice::drawFormXObjectWithMask(SkPDFIndirectReference xObject,
1465 SkPDFIndirectReference sMask,
reed374772b2016-10-05 17:33:02 -07001466 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001467 bool invertClip) {
Hal Canary9a3f5542018-12-10 19:59:07 -05001468 SkASSERT(sMask);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001469 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001470 paint.setBlendMode(mode);
Hal Canaryd892a9d2018-09-24 21:20:47 -04001471 ScopedContentEntry content(this, nullptr, SkMatrix::I(), paint);
Hal Canary42137de2018-10-08 16:00:37 -04001472 if (!content) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001473 return;
1474 }
Hal Canary3b8b11e2018-09-29 22:31:34 -04001475 this->setGraphicState(SkPDFGraphicState::GetSMaskGraphicState(
Hal Canary9a3f5542018-12-10 19:59:07 -05001476 sMask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode,
1477 fDocument), content.stream());
1478 this->drawFormXObject(xObject, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001479 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001480}
1481
Hal Canaryb400d4d2018-09-26 16:33:52 -04001482
1483static bool treat_as_regular_pdf_blend_mode(SkBlendMode blendMode) {
1484 return nullptr != SkPDFUtils::BlendModeName(blendMode);
1485}
1486
Hal Canary8f37ce52018-12-28 11:40:10 -05001487static void populate_graphic_state_entry_from_paint(
1488 SkPDFDocument* doc,
1489 const SkMatrix& matrix,
1490 const SkClipStack* clipStack,
1491 SkIRect deviceBounds,
1492 const SkPaint& paint,
1493 const SkMatrix& initialTransform,
1494 SkScalar textScale,
1495 SkPDFDevice::GraphicStateEntry* entry,
1496 SkTHashSet<SkPDFIndirectReference>* shaderResources,
1497 SkTHashSet<SkPDFIndirectReference>* graphicStateResources) {
1498 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1499 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1500 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
1501
1502 entry->fMatrix = matrix;
1503 entry->fClipStackGenID = clipStack ? clipStack->getTopmostGenID()
1504 : SkClipStack::kWideOpenGenID;
1505 SkColor4f color = paint.getColor4f();
1506 entry->fColor = {color.fR, color.fG, color.fB, 1};
1507 entry->fShaderIndex = -1;
1508
1509 // PDF treats a shader as a color, so we only set one or the other.
1510 SkShader* shader = paint.getShader();
1511 if (shader) {
1512 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1513 // We don't have to set a shader just for a color.
1514 SkShader::GradientInfo gradientInfo;
1515 SkColor gradientColor = SK_ColorBLACK;
1516 gradientInfo.fColors = &gradientColor;
1517 gradientInfo.fColorOffsets = nullptr;
1518 gradientInfo.fColorCount = 1;
1519 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1520 color = SkColor4f::FromColor(gradientColor);
1521 entry->fColor ={color.fR, color.fG, color.fB, 1};
1522
1523 } else {
1524 // PDF positions patterns relative to the initial transform, so
1525 // we need to apply the current transform to the shader parameters.
1526 SkMatrix transform = matrix;
1527 transform.postConcat(initialTransform);
1528
1529 // PDF doesn't support kClamp_TileMode, so we simulate it by making
1530 // a pattern the size of the current clip.
1531 SkRect clipStackBounds = clipStack ? clipStack->bounds(deviceBounds)
1532 : SkRect::Make(deviceBounds);
1533
1534 // We need to apply the initial transform to bounds in order to get
1535 // bounds in a consistent coordinate system.
1536 initialTransform.mapRect(&clipStackBounds);
1537 SkIRect bounds;
1538 clipStackBounds.roundOut(&bounds);
1539
1540 SkPDFIndirectReference pdfShader
1541 = SkPDFMakeShader(doc, shader, transform, bounds, paint.getColor());
1542
1543 if (pdfShader) {
1544 // pdfShader has been canonicalized so we can directly compare pointers.
1545 entry->fShaderIndex = add_resource(*shaderResources, pdfShader);
1546 }
1547 }
1548 }
1549
1550 SkPDFIndirectReference newGraphicState;
1551 if (color == paint.getColor4f()) {
1552 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(doc, paint);
1553 } else {
1554 SkPaint newPaint = paint;
1555 newPaint.setColor4f(color, nullptr);
1556 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(doc, newPaint);
1557 }
1558 entry->fGraphicStateIndex = add_resource(*graphicStateResources, newGraphicState);
1559 entry->fTextScaleX = textScale;
1560}
1561
Hal Canaryb400d4d2018-09-26 16:33:52 -04001562SkDynamicMemoryWStream* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1563 const SkMatrix& matrix,
1564 const SkPaint& paint,
Hal Canary8f37ce52018-12-28 11:40:10 -05001565 SkScalar textScale,
Hal Canary9a3f5542018-12-10 19:59:07 -05001566 SkPDFIndirectReference* dst) {
1567 SkASSERT(!*dst);
reed374772b2016-10-05 17:33:02 -07001568 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001569
Hal Canaryb400d4d2018-09-26 16:33:52 -04001570 // Dst xfer mode doesn't draw source at all.
1571 if (blendMode == SkBlendMode::kDst) {
1572 return nullptr;
1573 }
1574
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001575 // For the following modes, we want to handle source and destination
1576 // separately, so make an object of what's already there.
Hal Canaryb400d4d2018-09-26 16:33:52 -04001577 if (!treat_as_regular_pdf_blend_mode(blendMode) && blendMode != SkBlendMode::kDstOver) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001578 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001579 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001580 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001581 } else if (blendMode != SkBlendMode::kSrc &&
1582 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001583 // Except for Src and SrcOut, if there isn't anything already there,
1584 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001585 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001586 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001587 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001588 // TODO(vandebo): Figure out how/if we can handle the following modes:
Hal Canaryb400d4d2018-09-26 16:33:52 -04001589 // Xor, Plus. For now, we treat them as SrcOver/Normal.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001590
Hal Canaryb400d4d2018-09-26 16:33:52 -04001591 if (treat_as_regular_pdf_blend_mode(blendMode)) {
1592 if (!fActiveStackState.fContentStream) {
Hal Canary42137de2018-10-08 16:00:37 -04001593 if (fContent.bytesWritten() != 0) {
1594 fContent.writeText("Q\nq\n");
1595 fNeedsExtraSave = true;
1596 }
1597 fActiveStackState = GraphicStackState(&fContent);
1598 } else {
1599 SkASSERT(fActiveStackState.fContentStream = &fContent);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001600 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001601 } else {
Hal Canaryb400d4d2018-09-26 16:33:52 -04001602 fActiveStackState.drainStack();
Hal Canary42137de2018-10-08 16:00:37 -04001603 fActiveStackState = GraphicStackState(&fContentBuffer);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001604 }
Hal Canaryb400d4d2018-09-26 16:33:52 -04001605 SkASSERT(fActiveStackState.fContentStream);
1606 GraphicStateEntry entry;
Hal Canary8f37ce52018-12-28 11:40:10 -05001607 populate_graphic_state_entry_from_paint(
1608 fDocument,
1609 matrix,
1610 clipStack,
1611 this->bounds(),
1612 paint,
1613 fInitialTransform,
1614 textScale,
1615 &entry,
1616 &fShaderResources,
1617 &fGraphicStateResources);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001618 fActiveStackState.updateClip(clipStack, this->bounds());
1619 fActiveStackState.updateMatrix(entry.fMatrix);
1620 fActiveStackState.updateDrawingState(entry);
1621
1622 return fActiveStackState.fContentStream;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001623}
1624
Hal Canaryb400d4d2018-09-26 16:33:52 -04001625void SkPDFDevice::finishContentEntry(const SkClipStack* clipStack,
1626 SkBlendMode blendMode,
Hal Canary9a3f5542018-12-10 19:59:07 -05001627 SkPDFIndirectReference dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001628 SkPath* shape) {
Hal Canaryb400d4d2018-09-26 16:33:52 -04001629 SkASSERT(blendMode != SkBlendMode::kDst);
1630 if (treat_as_regular_pdf_blend_mode(blendMode)) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001631 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001632 return;
1633 }
Hal Canaryb400d4d2018-09-26 16:33:52 -04001634
1635 SkASSERT(fActiveStackState.fContentStream);
1636
1637 fActiveStackState.drainStack();
1638 fActiveStackState = GraphicStackState();
1639
reed374772b2016-10-05 17:33:02 -07001640 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001641 SkASSERT(!dst);
Hal Canary42137de2018-10-08 16:00:37 -04001642 if (fContentBuffer.bytesWritten() != 0) {
1643 if (fContent.bytesWritten() != 0) {
1644 fContentBuffer.writeText("Q\nq\n");
1645 fNeedsExtraSave = true;
1646 }
1647 fContentBuffer.prependToAndReset(&fContent);
1648 SkASSERT(fContentBuffer.bytesWritten() == 0);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001649 }
1650 return;
1651 }
Hal Canary42137de2018-10-08 16:00:37 -04001652 if (fContentBuffer.bytesWritten() != 0) {
1653 if (fContent.bytesWritten() != 0) {
1654 fContent.writeText("Q\nq\n");
1655 fNeedsExtraSave = true;
1656 }
1657 fContentBuffer.writeToAndReset(&fContent);
1658 SkASSERT(fContentBuffer.bytesWritten() == 0);
1659 }
1660
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001661 if (!dst) {
reed374772b2016-10-05 17:33:02 -07001662 SkASSERT(blendMode == SkBlendMode::kSrc ||
1663 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001664 return;
1665 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001666
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001667 SkASSERT(dst);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001668 // Changing the current content into a form-xobject will destroy the clip
1669 // objects which is fine since the xobject will already be clipped. However
1670 // if source has shape, we need to clip it too, so a copy of the clip is
1671 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001672
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001673 SkPaint stockPaint;
1674
Hal Canary9a3f5542018-12-10 19:59:07 -05001675 SkPDFIndirectReference srcFormXObject;
Hal Canary9e41c212018-09-03 12:00:23 -04001676 if (this->isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001677 // If nothing was drawn and there's no shape, then the draw was a
1678 // no-op, but dst needs to be restored for that to be true.
1679 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1680 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1681 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07001682 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1683 blendMode == SkBlendMode::kSrcATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001684 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary9a3f5542018-12-10 19:59:07 -05001685 this->drawFormXObject(dst, content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001686 return;
1687 } else {
reed374772b2016-10-05 17:33:02 -07001688 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001689 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001690 } else {
halcanary4b1e17e2016-07-27 14:49:46 -07001691 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001692 }
1693
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001694 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1695 // without alpha.
reed374772b2016-10-05 17:33:02 -07001696 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001697 // TODO(vandebo): In order to properly support SrcATop we have to track
1698 // the shape of what's been drawn at all times. It's the intersection of
1699 // the non-transparent parts of the device and the outlines (shape) of
1700 // all images and devices drawn.
Hal Canaryc4c41c92018-09-28 13:30:45 -04001701 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001702 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001703 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001704 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001705 SkPaint filledPaint;
1706 filledPaint.setColor(SK_ColorBLACK);
1707 filledPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryb400d4d2018-09-26 16:33:52 -04001708 SkClipStack empty;
Hal Canary813b5ac2018-09-28 12:30:37 -04001709 SkPDFDevice shapeDev(this->size(), fDocument, fInitialTransform);
1710 shapeDev.internalDrawPath(clipStack ? *clipStack : empty,
1711 SkMatrix::I(), *shape, filledPaint, true);
Hal Canaryc4c41c92018-09-28 13:30:45 -04001712 this->drawFormXObjectWithMask(dst, shapeDev.makeFormXObjectFromDevice(),
Mike Reeda1361362017-03-07 09:37:29 -05001713 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07001714 } else {
Hal Canaryc4c41c92018-09-28 13:30:45 -04001715 this->drawFormXObjectWithMask(dst, srcFormXObject, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001716 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001717 }
1718
reed374772b2016-10-05 17:33:02 -07001719 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001720 return;
reed374772b2016-10-05 17:33:02 -07001721 } else if (blendMode == SkBlendMode::kSrc ||
1722 blendMode == SkBlendMode::kDstATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001723 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary42137de2018-10-08 16:00:37 -04001724 if (content) {
Hal Canary3b8b11e2018-09-29 22:31:34 -04001725 this->drawFormXObject(srcFormXObject, content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001726 }
reed374772b2016-10-05 17:33:02 -07001727 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001728 return;
1729 }
reed374772b2016-10-05 17:33:02 -07001730 } else if (blendMode == SkBlendMode::kSrcATop) {
Hal Canaryd892a9d2018-09-24 21:20:47 -04001731 ScopedContentEntry content(this, nullptr, SkMatrix::I(), stockPaint);
Hal Canary42137de2018-10-08 16:00:37 -04001732 if (content) {
Hal Canary3b8b11e2018-09-29 22:31:34 -04001733 this->drawFormXObject(dst, content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001734 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001735 }
1736
reed374772b2016-10-05 17:33:02 -07001737 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
1738 blendMode == SkBlendMode::kDstIn ||
1739 blendMode == SkBlendMode::kSrcOut ||
1740 blendMode == SkBlendMode::kDstOut ||
1741 blendMode == SkBlendMode::kSrcATop ||
1742 blendMode == SkBlendMode::kDstATop ||
1743 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001744
reed374772b2016-10-05 17:33:02 -07001745 if (blendMode == SkBlendMode::kSrcIn ||
1746 blendMode == SkBlendMode::kSrcOut ||
1747 blendMode == SkBlendMode::kSrcATop) {
Hal Canary9a3f5542018-12-10 19:59:07 -05001748 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver,
1749 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07001750 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001751 } else {
reed374772b2016-10-05 17:33:02 -07001752 SkBlendMode mode = SkBlendMode::kSrcOver;
reed374772b2016-10-05 17:33:02 -07001753 if (blendMode == SkBlendMode::kModulate) {
Hal Canaryc4c41c92018-09-28 13:30:45 -04001754 this->drawFormXObjectWithMask(srcFormXObject, dst, SkBlendMode::kSrcOver, false);
reed374772b2016-10-05 17:33:02 -07001755 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001756 }
Hal Canary9a3f5542018-12-10 19:59:07 -05001757 this->drawFormXObjectWithMask(dst, srcFormXObject, mode, blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07001758 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001759 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001760}
1761
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001762bool SkPDFDevice::isContentEmpty() {
Hal Canary42137de2018-10-08 16:00:37 -04001763 return fContent.bytesWritten() == 0 && fContentBuffer.bytesWritten() == 0;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001764}
1765
Hal Canaryfafe1352017-04-11 12:12:02 -04001766static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07001767
Hal Canary7cbf5e32017-07-12 13:10:23 -04001768static sk_sp<SkImage> color_filter(const SkImage* image,
halcanarya50151d2016-03-25 11:57:49 -07001769 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07001770 auto surface =
Hal Canary7cbf5e32017-07-12 13:10:23 -04001771 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07001772 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07001773 SkCanvas* canvas = surface->getCanvas();
1774 canvas->clear(SK_ColorTRANSPARENT);
1775 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07001776 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canary7cbf5e32017-07-12 13:10:23 -04001777 canvas->drawImage(image, 0, 0, &paint);
halcanarya50151d2016-03-25 11:57:49 -07001778 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07001779}
1780
1781////////////////////////////////////////////////////////////////////////////////
Hal Canary7cbf5e32017-07-12 13:10:23 -04001782
1783static bool is_integer(SkScalar x) {
1784 return x == SkScalarTruncToScalar(x);
1785}
1786
1787static bool is_integral(const SkRect& r) {
1788 return is_integer(r.left()) &&
1789 is_integer(r.top()) &&
1790 is_integer(r.right()) &&
1791 is_integer(r.bottom());
1792}
1793
1794void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
1795 const SkRect* src,
1796 const SkRect& dst,
1797 const SkPaint& srcPaint,
1798 const SkMatrix& ctm) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05001799 if (this->hasEmptyClip()) {
1800 return;
1801 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04001802 if (!imageSubset) {
halcanarya50151d2016-03-25 11:57:49 -07001803 return;
1804 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04001805
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001806 // First, figure out the src->dst transform and subset the image if needed.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001807 SkIRect bounds = imageSubset.image()->bounds();
Hal Canary7cbf5e32017-07-12 13:10:23 -04001808 SkRect srcRect = src ? *src : SkRect::Make(bounds);
1809 SkMatrix transform;
1810 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
1811 if (src && *src != SkRect::Make(bounds)) {
1812 if (!srcRect.intersect(SkRect::Make(bounds))) {
1813 return;
1814 }
1815 srcRect.roundOut(&bounds);
1816 transform.preTranslate(SkIntToScalar(bounds.x()),
1817 SkIntToScalar(bounds.y()));
1818 if (bounds != imageSubset.image()->bounds()) {
1819 imageSubset = imageSubset.subset(bounds);
1820 }
1821 if (!imageSubset) {
1822 return;
1823 }
1824 }
1825
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001826 // If the image is opaque and the paint's alpha is too, replace
1827 // kSrc blendmode with kSrcOver.
1828 SkPaint paint = srcPaint;
1829 if (imageSubset.image()->isOpaque()) {
1830 replace_srcmode_on_opaque_paint(&paint);
Hal Canaryd425a1d2017-07-12 13:13:51 -04001831 }
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001832
1833 // Alpha-only images need to get their color from the shader, before
1834 // applying the colorfilter.
1835 if (imageSubset.image()->isAlphaOnly() && paint.getColorFilter()) {
1836 // must blend alpha image and shader before applying colorfilter.
1837 auto surface =
1838 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
1839 SkCanvas* canvas = surface->getCanvas();
1840 SkPaint tmpPaint;
1841 // In the case of alpha images with shaders, the shader's coordinate
1842 // system is the image's coordiantes.
1843 tmpPaint.setShader(sk_ref_sp(paint.getShader()));
Hal Canary04ac4612018-10-10 13:09:43 -04001844 tmpPaint.setColor4f(paint.getColor4f(), nullptr);
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001845 canvas->clear(0x00000000);
1846 canvas->drawImage(imageSubset.image().get(), 0, 0, &tmpPaint);
1847 paint.setShader(nullptr);
1848 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1849 SkASSERT(!imageSubset.image()->isAlphaOnly());
1850 }
1851
1852 if (imageSubset.image()->isAlphaOnly()) {
1853 // The ColorFilter applies to the paint color/shader, not the alpha layer.
1854 SkASSERT(nullptr == paint.getColorFilter());
1855
Hal Canaryd425a1d2017-07-12 13:13:51 -04001856 sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
1857 if (!mask) {
1858 return;
1859 }
1860 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
1861 // Must mask with a Form XObject.
1862 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
1863 {
Herb Derbyefe39bc2018-05-01 17:06:20 -04001864 SkCanvas canvas(maskDevice);
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04001865 if (paint.getMaskFilter()) {
1866 // This clip prevents the mask image shader from covering
1867 // entire device if unnecessary.
1868 canvas.clipRect(this->cs().bounds(this->bounds()));
1869 canvas.concat(ctm);
1870 SkPaint tmpPaint;
1871 tmpPaint.setShader(mask->makeShader(&transform));
1872 tmpPaint.setMaskFilter(sk_ref_sp(paint.getMaskFilter()));
1873 canvas.drawRect(dst, tmpPaint);
1874 } else {
1875 canvas.concat(ctm);
1876 if (src && !is_integral(*src)) {
1877 canvas.clipRect(dst);
1878 }
1879 canvas.concat(transform);
1880 canvas.drawImage(mask, 0, 0);
1881 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04001882 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04001883 if (!ctm.isIdentity() && paint.getShader()) {
1884 transform_shader(&paint, ctm); // Since we are using identity matrix.
1885 }
Hal Canaryd892a9d2018-09-24 21:20:47 -04001886 ScopedContentEntry content(this, &this->cs(), SkMatrix::I(), paint);
Hal Canary42137de2018-10-08 16:00:37 -04001887 if (!content) {
Hal Canaryd425a1d2017-07-12 13:13:51 -04001888 return;
1889 }
1890 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
Hal Canary813b5ac2018-09-28 12:30:37 -04001891 SkPDFUtils::AppendRectangle(SkRect::Make(this->size()), content.stream());
Hal Canaryd425a1d2017-07-12 13:13:51 -04001892 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kWinding_FillType, content.stream());
1893 this->clearMaskOnGraphicState(content.stream());
1894 return;
1895 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04001896 if (paint.getMaskFilter()) {
1897 paint.setShader(imageSubset.image()->makeShader(&transform));
Hal Canaryd791a6f2018-09-28 12:14:08 -04001898 SkPath path = to_path(dst); // handles non-integral clipping.
Robert Phillips137ca522018-08-15 10:14:33 -04001899 this->internalDrawPath(this->cs(), this->ctm(), path, paint, true);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001900 return;
1901 }
1902 transform.postConcat(ctm);
1903
1904 bool needToRestore = false;
1905 if (src && !is_integral(*src)) {
1906 // Need sub-pixel clipping to fix https://bug.skia.org/4374
1907 this->cs().save();
1908 this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
1909 needToRestore = true;
1910 }
1911 SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
1912
Hal Canary7cbf5e32017-07-12 13:10:23 -04001913 SkMatrix matrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001914
1915 // Rasterize the bitmap using perspective in a new bitmap.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001916 if (transform.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001917 // Transform the bitmap in the new space, without taking into
1918 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001919 SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
Hal Canaryd791a6f2018-09-28 12:14:08 -04001920 SkPath perspectiveOutline = to_path(imageBounds);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001921 perspectiveOutline.transform(transform);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001922
1923 // TODO(edisonn): perf - use current clip too.
1924 // Retrieve the bounds of the new shape.
1925 SkRect bounds = perspectiveOutline.getBounds();
1926
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001927 // Transform the bitmap in the new space, taking into
1928 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001929 SkMatrix total = transform;
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001930 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07001931
Hal Canaryd791a6f2018-09-28 12:14:08 -04001932 SkPath physicalPerspectiveOutline = to_path(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001933 physicalPerspectiveOutline.transform(total);
1934
halcanary7a14b312015-10-01 07:28:13 -07001935 SkRect physicalPerspectiveBounds =
1936 physicalPerspectiveOutline.getBounds();
1937 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
1938 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001939
1940 // TODO(edisonn): A better approach would be to use a bitmap shader
1941 // (in clamp mode) and draw a rect over the entire bounding box. Then
1942 // intersect perspectiveOutline to the clip. That will avoid introducing
1943 // alpha to the image while still giving good behavior at the edge of
1944 // the image. Avoiding alpha will reduce the pdf size and generation
1945 // CPU time some.
1946
halcanary7a14b312015-10-01 07:28:13 -07001947 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
1948
Hal Canaryf50ff392016-09-30 10:25:39 -04001949 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07001950 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00001951 return;
1952 }
halcanary7a14b312015-10-01 07:28:13 -07001953 SkCanvas* canvas = surface->getCanvas();
1954 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001955
1956 SkScalar deltaX = bounds.left();
1957 SkScalar deltaY = bounds.top();
1958
Hal Canary7cbf5e32017-07-12 13:10:23 -04001959 SkMatrix offsetMatrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001960 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001961 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001962
1963 // Translate the draw in the new canvas, so we perfectly fit the
1964 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07001965 canvas->setMatrix(offsetMatrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04001966 canvas->drawImage(imageSubset.image(), 0, 0);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001967 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07001968 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001969
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001970 // In the new space, we use the identity matrix translated
1971 // and scaled to reflect DPI.
1972 matrix.setScale(1 / scaleX, 1 / scaleY);
1973 matrix.postTranslate(deltaX, deltaY);
1974
Hal Canary7cbf5e32017-07-12 13:10:23 -04001975 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
1976 if (!imageSubset) {
1977 return;
1978 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001979 }
1980
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001981 SkMatrix scaled;
1982 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001983 scaled.setScale(SK_Scalar1, -SK_Scalar1);
1984 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001985 // Scale the image up from 1x1 to WxH.
Hal Canary7cbf5e32017-07-12 13:10:23 -04001986 SkIRect subset = imageSubset.image()->bounds();
1987 scaled.postScale(SkIntToScalar(subset.width()),
1988 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001989 scaled.postConcat(matrix);
Hal Canaryd892a9d2018-09-24 21:20:47 -04001990 ScopedContentEntry content(this, &this->cs(), scaled, paint);
Hal Canary42137de2018-10-08 16:00:37 -04001991 if (!content) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001992 return;
1993 }
1994 if (content.needShape()) {
Hal Canaryd791a6f2018-09-28 12:14:08 -04001995 SkPath shape = to_path(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001996 shape.transform(matrix);
1997 content.setShape(shape);
1998 }
1999 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002000 return;
2001 }
2002
halcanary287d22d2015-09-24 10:20:05 -07002003 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002004 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2005 imageSubset = SkKeyedImage(std::move(img));
2006 if (!imageSubset) {
2007 return;
2008 }
halcanary7a14b312015-10-01 07:28:13 -07002009 // TODO(halcanary): de-dupe this by caching filtered images.
2010 // (maybe in the resource cache?)
2011 }
halcanarya50151d2016-03-25 11:57:49 -07002012
Hal Canary7cbf5e32017-07-12 13:10:23 -04002013 SkBitmapKey key = imageSubset.key();
Hal Canary4ca9fa32018-12-21 16:15:01 -05002014 SkPDFIndirectReference* pdfimagePtr = fDocument->fPDFBitmapMap.find(key);
Hal Canary9a3f5542018-12-10 19:59:07 -05002015 SkPDFIndirectReference pdfimage = pdfimagePtr ? *pdfimagePtr : SkPDFIndirectReference();
2016 if (!pdfimagePtr) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002017 SkASSERT(imageSubset);
Hal Canary9a3f5542018-12-10 19:59:07 -05002018 pdfimage = SkPDFSerializeImage(imageSubset.image().get(), fDocument,
Hal Canarya1211832018-11-13 16:45:14 -05002019 fDocument->metadata().fEncodingQuality);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002020 SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
Hal Canary4ca9fa32018-12-21 16:15:01 -05002021 fDocument->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002022 }
Hal Canary9a3f5542018-12-10 19:59:07 -05002023 SkASSERT(pdfimage != SkPDFIndirectReference());
2024 this->drawFormXObject(pdfimage, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002025}
reede51c3562016-07-19 14:33:20 -07002026
2027///////////////////////////////////////////////////////////////////////////////////////////////////
2028
2029#include "SkSpecialImage.h"
2030#include "SkImageFilter.h"
2031
Florin Malita53f77bd2017-04-28 13:48:37 -04002032void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2033 SkImage* clipImage, const SkMatrix& clipMatrix) {
Hal Canaryb4e528d2018-03-09 16:02:15 -05002034 if (this->hasEmptyClip()) {
2035 return;
2036 }
reede51c3562016-07-19 14:33:20 -07002037 SkASSERT(!srcImg->isTextureBacked());
2038
Florin Malita53f77bd2017-04-28 13:48:37 -04002039 //TODO: clipImage support
2040
reede51c3562016-07-19 14:33:20 -07002041 SkBitmap resultBM;
2042
2043 SkImageFilter* filter = paint.getImageFilter();
2044 if (filter) {
2045 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002046 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002047 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002048 const SkIRect clipBounds =
Hal Canary22b2d8c2017-07-19 14:46:12 -04002049 this->cs().bounds(this->bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002050 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
Brian Osmana50205f2018-07-06 13:57:01 -04002051 // TODO: Should PDF be operating in a specified color type/space? For now, run the filter
brianosman2a75e5d2016-09-22 07:15:37 -07002052 // in the same color space as the source (this is different from all other backends).
Brian Osmana50205f2018-07-06 13:57:01 -04002053 SkImageFilter::OutputProperties outputProperties(kN32_SkColorType, srcImg->getColorSpace());
brianosman2a75e5d2016-09-22 07:15:37 -07002054 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002055
2056 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2057 if (resultImg) {
2058 SkPaint tmpUnfiltered(paint);
2059 tmpUnfiltered.setImageFilter(nullptr);
2060 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002061 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002062 }
2063 }
2064 } else {
2065 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002066 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002067 }
2068 }
2069}
2070
2071sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2072 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2073}
2074
2075sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Robert Phillips27467652019-01-10 16:34:22 -05002076 return SkSpecialImage::MakeFromImage(nullptr, image->bounds(), image->makeNonTextureImage());
reede51c3562016-07-19 14:33:20 -07002077}
2078
2079sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002080 return nullptr;
2081}
brianosman04a44d02016-09-21 09:46:57 -07002082
2083SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2084 // We always return a transient cache, so it is freed after each
2085 // filter traversal.
2086 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2087}