blob: 57a0f7df61859ee758990b85d705569a45155bf9 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
halcanarye06ca962016-09-09 05:34:55 -07009
halcanaryf59d18a2016-09-16 14:44:57 -070010#include "SkAdvancedTypefaceMetrics.h"
reedf70b5312016-03-04 16:36:20 -080011#include "SkAnnotationKeys.h"
Mike Reed986480a2017-01-13 22:43:16 +000012#include "SkBitmapDevice.h"
martina.kollarovab8d6af12016-06-29 05:12:31 -070013#include "SkBitmapKey.h"
Hal Canary7cbf5e32017-07-12 13:10:23 -040014#include "SkCanvas.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040015#include "SkClipOpPriv.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000016#include "SkColor.h"
halcanary287d22d2015-09-24 10:20:05 -070017#include "SkColorFilter.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000018#include "SkDraw.h"
halcanarye06ca962016-09-09 05:34:55 -070019#include "SkDrawFilter.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkGlyphCache.h"
brianosman04a44d02016-09-21 09:46:57 -070021#include "SkImageFilterCache.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040022#include "SkJpegEncoder.h"
halcanary022c2bd2016-09-02 11:29:46 -070023#include "SkMakeUnique.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040024#include "SkMaskFilter.h"
halcanarydb0dcc72015-03-20 12:31:52 -070025#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070026#include "SkPDFCanon.h"
halcanary989da4a2016-03-21 14:33:17 -070027#include "SkPDFDocument.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000028#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000029#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000030#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000031#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000032#include "SkPDFShader.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000033#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000034#include "SkPDFUtils.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040035#include "SkPath.h"
36#include "SkPathEffect.h"
37#include "SkPathOps.h"
Hal Canaryf50ff392016-09-30 10:25:39 -040038#include "SkPixelRef.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000039#include "SkRRect.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040040#include "SkRasterClip.h"
halcanary4871f222016-08-26 13:17:44 -070041#include "SkScopeExit.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000042#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070043#include "SkSurface.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000044#include "SkTemplates.h"
halcanarye06ca962016-09-09 05:34:55 -070045#include "SkTextBlobRunIterator.h"
46#include "SkTextFormatParams.h"
halcanaryf59d18a2016-09-16 14:44:57 -070047#include "SkUtils.h"
halcanarya6814332015-05-27 08:53:36 -070048#include "SkXfermodeInterpretation.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040049
50#ifndef SK_PDF_MASK_QUALITY
51 // If MASK_QUALITY is in [0,100], will be used for JpegEncoder.
52 // Otherwise, just encode masks losslessly.
53 #define SK_PDF_MASK_QUALITY 50
54 // Since these masks are used for blurry shadows, we shouldn't need
55 // high quality. Raise this value if your shadows have visible JPEG
56 // artifacts.
57 // If SkJpegEncoder::Encode fails, we will fall back to the lossless
58 // encoding.
59#endif
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000060
61// Utility functions
62
Hal Canary51329c92017-06-27 14:28:37 -040063// This function destroys the mask and either frees or takes the pixels.
64sk_sp<SkImage> mask_to_greyscale_image(SkMask* mask) {
65 sk_sp<SkImage> img;
66 SkPixmap pm(SkImageInfo::Make(mask->fBounds.width(), mask->fBounds.height(),
67 kGray_8_SkColorType, kOpaque_SkAlphaType),
68 mask->fImage, mask->fRowBytes);
69 const int imgQuality = SK_PDF_MASK_QUALITY;
70 if (imgQuality <= 100 && imgQuality >= 0) {
71 SkDynamicMemoryWStream buffer;
72 SkJpegEncoder::Options jpegOptions;
73 jpegOptions.fQuality = imgQuality;
74 if (SkJpegEncoder::Encode(&buffer, pm, jpegOptions)) {
75 img = SkImage::MakeFromEncoded(buffer.detachAsData());
76 SkASSERT(img);
77 if (img) {
78 SkMask::FreeImage(mask->fImage);
79 }
80 }
81 }
82 if (!img) {
83 img = SkImage::MakeFromRaster(pm, [](const void* p, void*) { SkMask::FreeImage((void*)p); },
84 nullptr);
85 }
86 *mask = SkMask(); // destructive;
87 return img;
88}
89
Hal Canaryd425a1d2017-07-12 13:13:51 -040090sk_sp<SkImage> alpha_image_to_greyscale_image(const SkImage* mask) {
91 int w = mask->width(), h = mask->height();
92 SkBitmap greyBitmap;
93 greyBitmap.allocPixels(SkImageInfo::Make(w, h, kGray_8_SkColorType, kOpaque_SkAlphaType));
94 if (!mask->readPixels(SkImageInfo::MakeA8(w, h),
95 greyBitmap.getPixels(), greyBitmap.rowBytes(), 0, 0)) {
96 return nullptr;
97 }
98 return SkImage::MakeFromBitmap(greyBitmap);
99}
100
Mike Reeda1361362017-03-07 09:37:29 -0500101static void draw_points(SkCanvas::PointMode mode,
102 size_t count,
103 const SkPoint* points,
104 const SkPaint& paint,
105 const SkIRect& bounds,
106 const SkMatrix& ctm,
107 SkBaseDevice* device) {
108 SkRasterClip rc(bounds);
109 SkDraw draw;
110 draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(bounds.right(), bounds.bottom()), nullptr, 0);
111 draw.fMatrix = &ctm;
112 draw.fRC = &rc;
113 draw.drawPoints(mode, count, points, paint, device);
114}
115
reed374772b2016-10-05 17:33:02 -0700116// If the paint will definitely draw opaquely, replace kSrc with
117// kSrcOver. http://crbug.com/473572
halcanarya6814332015-05-27 08:53:36 -0700118static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
reed374772b2016-10-05 17:33:02 -0700119 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
120 paint->setBlendMode(SkBlendMode::kSrcOver);
halcanarya6814332015-05-27 08:53:36 -0700121 }
122}
123
Hal Canaryd12a6762017-05-26 17:01:16 -0400124// A shader's matrix is: CTMM x LocalMatrix x WrappingLocalMatrix. We want to
125// switch to device space, where CTM = I, while keeping the original behavior.
126//
127// I * LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
128// LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
129// InvLocalMatrix * LocalMatrix * NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
130// NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
131//
132static void transform_shader(SkPaint* paint, const SkMatrix& ctm) {
133 SkMatrix lm = SkPDFUtils::GetShaderLocalMatrix(paint->getShader());
134 SkMatrix lmInv;
135 if (lm.invert(&lmInv)) {
136 SkMatrix m = SkMatrix::Concat(SkMatrix::Concat(lmInv, ctm), lm);
137 paint->setShader(paint->getShader()->makeWithLocalMatrix(m));
138 }
139}
140
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000141static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000142 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -0700143 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000144 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700145 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000146 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700147 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000148 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000149}
150
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000151static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000152 SkPaint result = paint;
153 if (result.isFakeBoldText()) {
154 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
155 kStdFakeBoldInterpKeys,
156 kStdFakeBoldInterpValues,
157 kStdFakeBoldInterpLength);
Mike Reed8be952a2017-02-13 20:44:33 -0500158 SkScalar width = result.getTextSize() * fakeBoldScale;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000159 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000160 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000161 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000162 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000163 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000164 result.setStrokeWidth(width);
165 }
166 return result;
167}
168
Hal Canaryf50ff392016-09-30 10:25:39 -0400169
Hal Canaryd12a6762017-05-26 17:01:16 -0400170// If the paint has a color filter, apply the color filter to the shader or the
171// paint color. Remove the color filter.
172void remove_color_filter(SkPaint* paint) {
173 if (SkColorFilter* cf = paint->getColorFilter()) {
174 if (SkShader* shader = paint->getShader()) {
175 paint->setShader(shader->makeWithColorFilter(paint->refColorFilter()));
176 } else {
177 paint->setColor(cf->filterColor(paint->getColor()));
178 }
179 paint->setColorFilter(nullptr);
180 }
181}
182
halcanary2be7e012016-03-28 11:58:08 -0700183SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
184 : fColor(SK_ColorBLACK)
185 , fTextScaleX(SK_Scalar1)
186 , fTextFill(SkPaint::kFill_Style)
187 , fShaderIndex(-1)
halcanaryc2f9ec12016-09-12 08:55:29 -0700188 , fGraphicStateIndex(-1) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000189 fMatrix.reset();
190}
191
halcanary2be7e012016-03-28 11:58:08 -0700192bool SkPDFDevice::GraphicStateEntry::compareInitialState(
193 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000194 return fColor == cur.fColor &&
195 fShaderIndex == cur.fShaderIndex &&
196 fGraphicStateIndex == cur.fGraphicStateIndex &&
197 fMatrix == cur.fMatrix &&
198 fClipStack == cur.fClipStack &&
199 (fTextScaleX == 0 ||
200 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000201}
202
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000203class GraphicStackState {
204public:
205 GraphicStackState(const SkClipStack& existingClipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000206 SkWStream* contentStream)
207 : fStackDepth(0),
208 fContentStream(contentStream) {
209 fEntries[0].fClipStack = existingClipStack;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000210 }
211
Hal Canary6d673962017-02-22 17:16:59 -0500212 void updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500213 const SkPoint& translation, const SkRect& bounds);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000214 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700215 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000216
217 void drainStack();
218
219private:
220 void push();
221 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700222 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000223
224 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
225 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700226 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000227 int fStackDepth;
228 SkWStream* fContentStream;
229};
230
231void GraphicStackState::drainStack() {
232 while (fStackDepth) {
233 pop();
234 }
235}
236
237void GraphicStackState::push() {
238 SkASSERT(fStackDepth < kMaxStackDepth);
239 fContentStream->writeText("q\n");
240 fStackDepth++;
241 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
242}
243
244void GraphicStackState::pop() {
245 SkASSERT(fStackDepth > 0);
246 fContentStream->writeText("Q\n");
247 fStackDepth--;
248}
249
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000250/* Calculate an inverted path's equivalent non-inverted path, given the
251 * canvas bounds.
252 * outPath may alias with invPath (since this is supported by PathOps).
253 */
254static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
255 SkPath* outPath) {
256 SkASSERT(invPath.isInverseFillType());
257
258 SkPath clipPath;
259 clipPath.addRect(bounds);
260
reedcdb42bb2015-06-26 10:23:07 -0700261 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000262}
263
Hal Canary44a97d52017-02-22 10:45:25 -0500264bool apply_clip(SkClipOp op, const SkPath& u, const SkPath& v, SkPath* r) {
265 switch (op) {
266 case SkClipOp::kDifference:
267 return Op(u, v, kDifference_SkPathOp, r);
268 case SkClipOp::kIntersect:
269 return Op(u, v, kIntersect_SkPathOp, r);
Mike Reed14113bc2017-05-10 14:13:20 -0400270#ifdef SK_SUPPORT_DEPRECATED_CLIPOPS
Hal Canary44a97d52017-02-22 10:45:25 -0500271 case SkClipOp::kUnion_deprecated:
272 return Op(u, v, kUnion_SkPathOp, r);
273 case SkClipOp::kXOR_deprecated:
274 return Op(u, v, kXOR_SkPathOp, r);
275 case SkClipOp::kReverseDifference_deprecated:
276 return Op(u, v, kReverseDifference_SkPathOp, r);
277 case SkClipOp::kReplace_deprecated:
278 *r = v;
279 return true;
Mike Reed14113bc2017-05-10 14:13:20 -0400280#endif
Hal Canary44a97d52017-02-22 10:45:25 -0500281 default:
282 return false;
283 }
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000284}
285
286/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
287 * Returns true if successful, or false if not successful.
288 * If successful, the resulting clip is stored in outClipPath.
289 * If not successful, outClipPath is undefined, and a fallback method
290 * should be used.
291 */
292static bool get_clip_stack_path(const SkMatrix& transform,
293 const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500294 const SkRect& bounds,
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000295 SkPath* outClipPath) {
296 outClipPath->reset();
297 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
298
299 const SkClipStack::Element* clipEntry;
300 SkClipStack::Iter iter;
301 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
302 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
303 SkPath entryPath;
304 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
305 outClipPath->reset();
306 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
307 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000308 } else {
309 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000310 }
311 entryPath.transform(transform);
Hal Canary44a97d52017-02-22 10:45:25 -0500312 if (!apply_clip(clipEntry->getOp(), *outClipPath, entryPath, outClipPath)) {
313 return false;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000314 }
315 }
316
317 if (outClipPath->isInverseFillType()) {
318 // The bounds are slightly outset to ensure this is correct in the
319 // face of floating-point accuracy and possible SkRegion bitmap
320 // approximations.
Hal Canary44a97d52017-02-22 10:45:25 -0500321 SkRect clipBounds = bounds;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000322 clipBounds.outset(SK_Scalar1, SK_Scalar1);
323 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
324 return false;
325 }
326 }
327 return true;
328}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000329
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000330// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000331// graphic state stack, and the fact that we can know all the clips used
332// on the page to optimize this.
333void GraphicStackState::updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500334 const SkPoint& translation,
335 const SkRect& bounds) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000336 if (clipStack == currentEntry()->fClipStack) {
337 return;
338 }
339
340 while (fStackDepth > 0) {
341 pop();
342 if (clipStack == currentEntry()->fClipStack) {
343 return;
344 }
345 }
346 push();
347
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000348 currentEntry()->fClipStack = clipStack;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000349
350 SkMatrix transform;
351 transform.setTranslate(translation.fX, translation.fY);
352
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000353 SkPath clipPath;
Hal Canary44a97d52017-02-22 10:45:25 -0500354 if (get_clip_stack_path(transform, clipStack, bounds, &clipPath)) {
halcanary5edf2902016-09-07 09:05:25 -0700355 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
356 SkPath::FillType clipFill = clipPath.getFillType();
357 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
358 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
359 if (clipFill == SkPath::kEvenOdd_FillType) {
360 fContentStream->writeText("W* n\n");
361 } else {
362 fContentStream->writeText("W n\n");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000363 }
364 }
halcanary5edf2902016-09-07 09:05:25 -0700365 // If Op() fails (pathological case; e.g. input values are
366 // extremely large or NaN), emit no clip at all.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000367}
368
369void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
370 if (matrix == currentEntry()->fMatrix) {
371 return;
372 }
373
374 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
375 SkASSERT(fStackDepth > 0);
376 SkASSERT(fEntries[fStackDepth].fClipStack ==
377 fEntries[fStackDepth -1].fClipStack);
378 pop();
379
380 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
381 }
382 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
383 return;
384 }
385
386 push();
387 SkPDFUtils::AppendTransform(matrix, fContentStream);
388 currentEntry()->fMatrix = matrix;
389}
390
halcanary2be7e012016-03-28 11:58:08 -0700391void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000392 // PDF treats a shader as a color, so we only set one or the other.
393 if (state.fShaderIndex >= 0) {
394 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000395 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000396 currentEntry()->fShaderIndex = state.fShaderIndex;
397 }
398 } else {
399 if (state.fColor != currentEntry()->fColor ||
400 currentEntry()->fShaderIndex >= 0) {
401 emit_pdf_color(state.fColor, fContentStream);
402 fContentStream->writeText("RG ");
403 emit_pdf_color(state.fColor, fContentStream);
404 fContentStream->writeText("rg\n");
405 currentEntry()->fColor = state.fColor;
406 currentEntry()->fShaderIndex = -1;
407 }
408 }
409
410 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000411 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000412 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
413 }
414
415 if (state.fTextScaleX) {
416 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
Mike Reed8be952a2017-02-13 20:44:33 -0500417 SkScalar pdfScale = state.fTextScaleX * 1000;
halcanarybc4696b2015-05-06 10:56:04 -0700418 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000419 fContentStream->writeText(" Tz\n");
420 currentEntry()->fTextScaleX = state.fTextScaleX;
421 }
422 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700423 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
424 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
425 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000426 fContentStream->writeDecAsText(state.fTextFill);
427 fContentStream->writeText(" Tr\n");
428 currentEntry()->fTextFill = state.fTextFill;
429 }
430 }
431}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000432
reed76033be2015-03-14 10:54:31 -0700433static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700434 // PDF does not support image filters, so render them on CPU.
435 // Note that this rendering is done at "screen" resolution (100dpi), not
436 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700437 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800438 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700439
440 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700441 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700442}
443
444SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700445 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700446 // need to return a raster device, which we will detect in drawDevice()
447 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700448 }
Hal Canary22b2d8c2017-07-19 14:46:12 -0400449 return new SkPDFDevice(cinfo.fInfo.dimensions(), fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000450}
451
halcanary989da4a2016-03-21 14:33:17 -0700452SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
453
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000454// A helper class to automatically finish a ContentEntry at the end of a
455// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000456class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000457public:
Mike Reeda1361362017-03-07 09:37:29 -0500458 ScopedContentEntry(SkPDFDevice* device,
459 const SkClipStack& clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000460 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500461 const SkPaint& paint,
462 bool hasText = false)
463 : fDevice(device)
464 , fContentEntry(nullptr)
465 , fBlendMode(SkBlendMode::kSrcOver)
466 , fDstFormXObject(nullptr)
467 {
468 if (matrix.hasPerspective()) {
469 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
470 return;
471 }
472 fBlendMode = paint.getBlendMode();
473 fContentEntry =
474 fDevice->setUpContentEntry(clipStack, matrix, paint, hasText, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000475 }
Mike Reeda1361362017-03-07 09:37:29 -0500476 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, bool hasText = false)
477 : ScopedContentEntry(dev, dev->cs(), dev->ctm(), paint, hasText) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000478
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000479 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000480 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000481 SkPath* shape = &fShape;
482 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700483 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000484 }
reed374772b2016-10-05 17:33:02 -0700485 fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000486 }
487 }
488
halcanary2be7e012016-03-28 11:58:08 -0700489 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
Hal Canary51329c92017-06-27 14:28:37 -0400490 SkDynamicMemoryWStream* stream() { return &fContentEntry->fContent; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000491
492 /* Returns true when we explicitly need the shape of the drawing. */
493 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700494 switch (fBlendMode) {
495 case SkBlendMode::kClear:
496 case SkBlendMode::kSrc:
497 case SkBlendMode::kSrcIn:
498 case SkBlendMode::kSrcOut:
499 case SkBlendMode::kDstIn:
500 case SkBlendMode::kDstOut:
501 case SkBlendMode::kSrcATop:
502 case SkBlendMode::kDstATop:
503 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000504 return true;
505 default:
506 return false;
507 }
508 }
509
510 /* Returns true unless we only need the shape of the drawing. */
511 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700512 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000513 return false;
514 }
515 return true;
516 }
517
518 /* If the shape is different than the alpha component of the content, then
519 * setShape should be called with the shape. In particular, images and
520 * devices have rectangular shape.
521 */
522 void setShape(const SkPath& shape) {
523 fShape = shape;
524 }
525
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000526private:
527 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700528 SkPDFDevice::ContentEntry* fContentEntry;
reed374772b2016-10-05 17:33:02 -0700529 SkBlendMode fBlendMode;
halcanarydabd4f02016-08-03 11:16:56 -0700530 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000531 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000532};
533
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000534////////////////////////////////////////////////////////////////////////////////
535
Hal Canarya0622582017-06-29 18:51:35 -0400536SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc)
reed589a39e2016-08-20 07:59:19 -0700537 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
538 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700539 , fPageSize(pageSize)
Hal Canarya0622582017-06-29 18:51:35 -0400540 , fInitialTransform(SkMatrix::I())
541 , fDocument(doc)
542{
Hal Canary22b2d8c2017-07-19 14:46:12 -0400543 SkASSERT(!pageSize.isEmpty());
Hal Canarya0622582017-06-29 18:51:35 -0400544}
robertphillips1f3923e2016-07-21 07:17:54 -0700545
Hal Canarya0622582017-06-29 18:51:35 -0400546void SkPDFDevice::setFlip() {
547 // Skia generally uses the top left as the origin but PDF
548 // natively has the origin at the bottom left. This matrix
549 // corrects for that. But that only needs to be done once, we
550 // don't do it when layering.
551 fInitialTransform.setTranslate(0, SkIntToScalar(fPageSize.fHeight));
552 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000553}
554
555SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700556 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000557}
558
559void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700560 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000561}
562
halcanary3c35fb32016-06-30 11:55:07 -0700563void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000564 fGraphicStateResources.unrefAll();
565 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000566 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000567 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000568}
569
Mike Reeda1361362017-03-07 09:37:29 -0500570void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500571 if (!value) {
572 return;
573 }
574 if (rect.isEmpty()) {
Mike Reeda1361362017-03-07 09:37:29 -0500575 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
576 SkPoint transformedPoint;
577 this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
Hal Canary5c1b3602017-04-17 16:30:06 -0400578 fNamedDestinations.emplace_back(NamedDestination{sk_ref_sp(value), transformedPoint});
Mike Reeda1361362017-03-07 09:37:29 -0500579 }
580 return;
581 }
582 // Convert to path to handle non-90-degree rotations.
583 SkPath path;
584 path.addRect(rect);
585 path.transform(this->ctm(), &path);
586 SkPath clip;
587 (void)this->cs().asPath(&clip);
588 Op(clip, path, kIntersect_SkPathOp, &path);
589 // PDF wants a rectangle only.
590 SkRect transformedRect = path.getBounds();
591 if (transformedRect.isEmpty()) {
592 return;
593 }
594 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400595 fLinkToURLs.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
Mike Reeda1361362017-03-07 09:37:29 -0500596 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400597 fLinkToDestinations.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
reedf70b5312016-03-04 16:36:20 -0800598 }
599}
600
Hal Canaryd12a6762017-05-26 17:01:16 -0400601void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
602 SkPaint newPaint = srcPaint;
603 remove_color_filter(&newPaint);
halcanarya6814332015-05-27 08:53:36 -0700604 replace_srcmode_on_opaque_paint(&newPaint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000605 newPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryd12a6762017-05-26 17:01:16 -0400606
607 SkMatrix ctm = this->ctm();
608 if (ctm.getType() & SkMatrix::kPerspective_Mask) {
609 if (newPaint.getShader()) {
610 transform_shader(&newPaint, ctm);
611 }
612 ctm = SkMatrix::I();
613 }
614 ScopedContentEntry content(this, this->cs(), ctm, newPaint);
Mike Reeda1361362017-03-07 09:37:29 -0500615 this->internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000616}
617
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000618void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700619 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000620 if (!contentEntry) {
621 return;
622 }
Hal Canaryd425a1d2017-07-12 13:13:51 -0400623 SkRect bbox = SkRect::Make(fPageSize);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000624 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000625 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000626 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000627 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000628 inverse.mapRect(&bbox);
629
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000630 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000631 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000632 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000633}
634
Mike Reeda1361362017-03-07 09:37:29 -0500635void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700636 size_t count,
637 const SkPoint* points,
638 const SkPaint& srcPaint) {
639 SkPaint passedPaint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400640 remove_color_filter(&passedPaint);
halcanarya6814332015-05-27 08:53:36 -0700641 replace_srcmode_on_opaque_paint(&passedPaint);
Hal Canary80fa7ce2017-06-28 16:04:20 -0400642 if (SkCanvas::kPoints_PointMode != mode) {
643 passedPaint.setStyle(SkPaint::kStroke_Style);
644 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000645 if (count == 0) {
646 return;
647 }
648
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000649 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
650 // We only use this when there's a path effect because of the overhead
651 // of multiple calls to setUpContentEntry it causes.
652 if (passedPaint.getPathEffect()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400653 if (this->cs().isEmpty(this->bounds())) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000654 return;
655 }
Mike Reeda1361362017-03-07 09:37:29 -0500656 draw_points(mode, count, points, passedPaint,
657 this->devClipBounds(), this->ctm(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000658 return;
659 }
660
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000661 const SkPaint* paint = &passedPaint;
662 SkPaint modifiedPaint;
663
664 if (mode == SkCanvas::kPoints_PointMode &&
665 paint->getStrokeCap() != SkPaint::kRound_Cap) {
666 modifiedPaint = *paint;
667 paint = &modifiedPaint;
668 if (paint->getStrokeWidth()) {
669 // PDF won't draw a single point with square/butt caps because the
670 // orientation is ambiguous. Draw a rectangle instead.
671 modifiedPaint.setStyle(SkPaint::kFill_Style);
672 SkScalar strokeWidth = paint->getStrokeWidth();
673 SkScalar halfStroke = SkScalarHalf(strokeWidth);
674 for (size_t i = 0; i < count; i++) {
675 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
676 r.inset(-halfStroke, -halfStroke);
Mike Reeda1361362017-03-07 09:37:29 -0500677 this->drawRect(r, modifiedPaint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000678 }
679 return;
680 } else {
681 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
682 }
683 }
684
Mike Reeda1361362017-03-07 09:37:29 -0500685 ScopedContentEntry content(this, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000686 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000687 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000688 }
Hal Canary51329c92017-06-27 14:28:37 -0400689 SkDynamicMemoryWStream* contentStream = content.stream();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000690 switch (mode) {
691 case SkCanvas::kPolygon_PointMode:
Hal Canary51329c92017-06-27 14:28:37 -0400692 SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000693 for (size_t i = 1; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400694 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000695 }
Hal Canary51329c92017-06-27 14:28:37 -0400696 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000697 break;
698 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000699 for (size_t i = 0; i < count/2; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400700 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
701 SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
702 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000703 }
704 break;
705 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000706 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
707 for (size_t i = 0; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400708 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
709 SkPDFUtils::ClosePath(contentStream);
710 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000711 }
712 break;
713 default:
714 SkASSERT(false);
715 }
716}
717
halcanary8103a342016-03-08 15:10:16 -0800718static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800719 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700720 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700721 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700722
halcanaryece83922016-03-08 08:32:12 -0800723 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700724 border->reserve(3);
725 border->appendInt(0); // Horizontal corner radius.
726 border->appendInt(0); // Vertical corner radius.
727 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800728 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700729
halcanaryece83922016-03-08 08:32:12 -0800730 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700731 rect->reserve(4);
732 rect->appendScalar(translatedRect.fLeft);
733 rect->appendScalar(translatedRect.fTop);
734 rect->appendScalar(translatedRect.fRight);
735 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800736 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700737
halcanary8103a342016-03-08 15:10:16 -0800738 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700739}
740
halcanary8103a342016-03-08 15:10:16 -0800741static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700742 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700743 SkString url(static_cast<const char *>(urlData->data()),
744 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800745 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700746 action->insertName("S", "URI");
747 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800748 annotation->insertObject("A", std::move(action));
749 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700750}
751
halcanary8103a342016-03-08 15:10:16 -0800752static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
753 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700754 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700755 SkString name(static_cast<const char *>(nameData->data()),
756 nameData->size() - 1);
757 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800758 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700759}
760
Mike Reeda1361362017-03-07 09:37:29 -0500761void SkPDFDevice::drawRect(const SkRect& rect,
halcanarya6814332015-05-27 08:53:36 -0700762 const SkPaint& srcPaint) {
763 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400764 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700765 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000766 SkRect r = rect;
767 r.sort();
768
Hal Canaryd12a6762017-05-26 17:01:16 -0400769 if (paint.getPathEffect() || paint.getMaskFilter()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400770 if (this->cs().isEmpty(this->bounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000771 return;
772 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000773 SkPath path;
774 path.addRect(r);
Mike Reeda1361362017-03-07 09:37:29 -0500775 this->drawPath(path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000776 return;
777 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000778
Mike Reeda1361362017-03-07 09:37:29 -0500779 ScopedContentEntry content(this, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000780 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000781 return;
782 }
Hal Canary51329c92017-06-27 14:28:37 -0400783 SkPDFUtils::AppendRectangle(r, content.stream());
784 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000785}
786
Mike Reeda1361362017-03-07 09:37:29 -0500787void SkPDFDevice::drawRRect(const SkRRect& rrect,
halcanarya6814332015-05-27 08:53:36 -0700788 const SkPaint& srcPaint) {
789 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400790 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700791 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000792 SkPath path;
793 path.addRRect(rrect);
Mike Reeda1361362017-03-07 09:37:29 -0500794 this->drawPath(path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000795}
796
Mike Reeda1361362017-03-07 09:37:29 -0500797void SkPDFDevice::drawOval(const SkRect& oval,
halcanarya6814332015-05-27 08:53:36 -0700798 const SkPaint& srcPaint) {
799 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400800 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700801 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700802 SkPath path;
803 path.addOval(oval);
Mike Reeda1361362017-03-07 09:37:29 -0500804 this->drawPath(path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700805}
806
Mike Reeda1361362017-03-07 09:37:29 -0500807void SkPDFDevice::drawPath(const SkPath& origPath,
halcanarya6814332015-05-27 08:53:36 -0700808 const SkPaint& srcPaint,
809 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000810 bool pathIsMutable) {
Mike Reeda1361362017-03-07 09:37:29 -0500811 this->internalDrawPath(
812 this->cs(), this->ctm(), origPath, srcPaint, prePathMatrix, pathIsMutable);
813}
814
Hal Canaryd12a6762017-05-26 17:01:16 -0400815void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
816 const SkMatrix& ctm,
817 const SkPath& origPath,
818 const SkPaint& origPaint,
819 const SkMatrix* prePathMatrix) {
820 SkASSERT(origPaint.getMaskFilter());
821 SkPath path(origPath);
822 SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
823 if (prePathMatrix) {
824 path.transform(*prePathMatrix, &path);
825 }
826 SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
827 ? SkStrokeRec::kFill_InitStyle
828 : SkStrokeRec::kHairline_InitStyle;
829 path.transform(ctm, &path);
830
Hal Canarya0622582017-06-29 18:51:35 -0400831 // TODO(halcanary): respect fDocument->rasterDpi().
832 // SkScalar rasterScale = (float)rasterDpi / SkPDFUtils::kDpiForRasterScaleOne;
Hal Canaryd12a6762017-05-26 17:01:16 -0400833 // Would it be easier to just change the device size (and pre-scale the canvas)?
Hal Canary22b2d8c2017-07-19 14:46:12 -0400834 SkIRect bounds = clipStack.bounds(this->bounds()).roundOut();
Hal Canaryd12a6762017-05-26 17:01:16 -0400835 SkMask sourceMask;
836 if (!SkDraw::DrawToMask(path, &bounds, paint->getMaskFilter(), &SkMatrix::I(),
837 &sourceMask, SkMask::kComputeBoundsAndRenderImage_CreateMode,
838 initStyle)) {
839 return;
840 }
841 SkAutoMaskFreeImage srcAutoMaskFreeImage(sourceMask.fImage);
842 SkMask dstMask;
843 SkIPoint margin;
844 if (!paint->getMaskFilter()->filterMask(&dstMask, sourceMask, ctm, &margin)) {
845 return;
846 }
Hal Canary51329c92017-06-27 14:28:37 -0400847 SkIRect dstMaskBounds = dstMask.fBounds;
848 sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
Hal Canaryd12a6762017-05-26 17:01:16 -0400849 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
850 // Must mask with a Form XObject.
Hal Canary51329c92017-06-27 14:28:37 -0400851 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
Hal Canaryd12a6762017-05-26 17:01:16 -0400852 {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400853 SkCanvas canvas(maskDevice.get());
Hal Canary51329c92017-06-27 14:28:37 -0400854 canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
Hal Canaryd12a6762017-05-26 17:01:16 -0400855 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400856 if (!ctm.isIdentity() && paint->getShader()) {
857 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
858 }
859 ScopedContentEntry content(this, clipStack, SkMatrix::I(), *paint);
860 if (!content.entry()) {
861 return;
862 }
Hal Canary51329c92017-06-27 14:28:37 -0400863 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
864 SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
865 SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
866 this->clearMaskOnGraphicState(content.stream());
867}
Hal Canaryd12a6762017-05-26 17:01:16 -0400868
Hal Canary51329c92017-06-27 14:28:37 -0400869void SkPDFDevice::addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,
870 SkDynamicMemoryWStream* contentStream) {
871 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
Hal Canaryb4bd5ef2017-07-26 09:16:01 -0400872 maskDevice->makeFormXObjectFromDevice(true), false,
Hal Canary51329c92017-06-27 14:28:37 -0400873 SkPDFGraphicState::kLuminosity_SMaskMode, this->getCanon());
874 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(sMaskGS.get()), contentStream);
875}
Hal Canaryd12a6762017-05-26 17:01:16 -0400876
Hal Canary51329c92017-06-27 14:28:37 -0400877void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400878 // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
Hal Canaryc02de0b2017-06-28 13:14:03 -0400879 sk_sp<SkPDFDict>& noSMaskGS = this->getCanon()->fNoSmaskGraphicState;
880 if (!noSMaskGS) {
881 noSMaskGS = sk_make_sp<SkPDFDict>("ExtGState");
882 noSMaskGS->insertName("SMask", "None");
883 }
Hal Canary51329c92017-06-27 14:28:37 -0400884 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(noSMaskGS.get()), contentStream);
Hal Canaryd12a6762017-05-26 17:01:16 -0400885}
886
Mike Reeda1361362017-03-07 09:37:29 -0500887void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
888 const SkMatrix& ctm,
889 const SkPath& origPath,
890 const SkPaint& srcPaint,
891 const SkMatrix* prePathMatrix,
892 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700893 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400894 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700895 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800896 SkPath modifiedPath;
897 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000898
Hal Canaryd12a6762017-05-26 17:01:16 -0400899 if (paint.getMaskFilter()) {
900 this->internalDrawPathWithFilter(clipStack, ctm, origPath, paint, prePathMatrix);
901 return;
902 }
903
Mike Reeda1361362017-03-07 09:37:29 -0500904 SkMatrix matrix = ctm;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000905 if (prePathMatrix) {
906 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800907 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000908 pathPtr = &modifiedPath;
909 pathIsMutable = true;
910 }
halcanary682ee012016-01-28 10:59:34 -0800911 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000912 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000913 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000914 }
915 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000916
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000917 if (paint.getPathEffect()) {
Hal Canary22b2d8c2017-07-19 14:46:12 -0400918 if (clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000919 return;
920 }
halcanary682ee012016-01-28 10:59:34 -0800921 if (!pathIsMutable) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400922 modifiedPath = origPath;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000923 pathPtr = &modifiedPath;
924 pathIsMutable = true;
925 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400926 if (paint.getFillPath(*pathPtr, pathPtr)) {
927 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000928 } else {
Hal Canaryd12a6762017-05-26 17:01:16 -0400929 paint.setStyle(SkPaint::kStroke_Style);
930 paint.setStrokeWidth(0);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000931 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400932 paint.setPathEffect(nullptr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000933 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000934
Hal Canaryd12a6762017-05-26 17:01:16 -0400935 if (this->handleInversePath(*pathPtr, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000936 return;
937 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400938 if (matrix.getType() & SkMatrix::kPerspective_Mask) {
939 if (!pathIsMutable) {
940 modifiedPath = origPath;
941 pathPtr = &modifiedPath;
942 pathIsMutable = true;
943 }
944 pathPtr->transform(matrix);
945 if (paint.getShader()) {
946 transform_shader(&paint, matrix);
947 }
948 matrix = SkMatrix::I();
949 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000950
Mike Reeda1361362017-03-07 09:37:29 -0500951 ScopedContentEntry content(this, clipStack, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000952 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000953 return;
954 }
Hal Canary385468f2017-02-13 11:03:23 -0500955 SkScalar matrixScale = matrix.mapRadius(1.0f);
956 SkScalar tolerance = matrixScale > 0.0f ? 0.25f / matrixScale : 0.25f;
halcanary8b2bc252015-10-06 09:41:47 -0700957 bool consumeDegeratePathSegments =
958 paint.getStyle() == SkPaint::kFill_Style ||
959 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
960 paint.getStrokeCap() != SkPaint::kSquare_Cap);
Hal Canary51329c92017-06-27 14:28:37 -0400961 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(), consumeDegeratePathSegments, content.stream(),
Hal Canary385468f2017-02-13 11:03:23 -0500962 tolerance);
Hal Canary51329c92017-06-27 14:28:37 -0400963 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000964}
965
Hal Canary7cbf5e32017-07-12 13:10:23 -0400966////////////////////////////////////////////////////////////////////////////////
Hal Canaryf50ff392016-09-30 10:25:39 -0400967
Mike Reeda1361362017-03-07 09:37:29 -0500968void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400969 const SkRect* src,
970 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400971 const SkPaint& paint,
Hal Canaryf50ff392016-09-30 10:25:39 -0400972 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400973 SkASSERT(image);
974 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
975 src, dst, paint, this->ctm());
Hal Canaryf50ff392016-09-30 10:25:39 -0400976}
977
Hal Canary7cbf5e32017-07-12 13:10:23 -0400978void SkPDFDevice::drawBitmapRect(const SkBitmap& bm,
halcanary7a14b312015-10-01 07:28:13 -0700979 const SkRect* src,
980 const SkRect& dst,
Hal Canary7cbf5e32017-07-12 13:10:23 -0400981 const SkPaint& paint,
Mike Reeda1361362017-03-07 09:37:29 -0500982 SkCanvas::SrcRectConstraint) {
Hal Canary7cbf5e32017-07-12 13:10:23 -0400983 SkASSERT(!bm.drawsNothing());
984 this->internalDrawImageRect(SkKeyedImage(bm), src, dst, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700985}
986
Hal Canary7cbf5e32017-07-12 13:10:23 -0400987void SkPDFDevice::drawBitmap(const SkBitmap& bm, SkScalar x, SkScalar y, const SkPaint& paint) {
988 SkASSERT(!bm.drawsNothing());
989 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
990 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, this->ctm());
halcanary7a14b312015-10-01 07:28:13 -0700991}
992
Hal Canary7cbf5e32017-07-12 13:10:23 -0400993void SkPDFDevice::drawSprite(const SkBitmap& bm, int x, int y, const SkPaint& paint) {
994 SkASSERT(!bm.drawsNothing());
995 auto r = SkRect::MakeXYWH(x, y, bm.width(), bm.height());
996 this->internalDrawImageRect(SkKeyedImage(bm), nullptr, r, paint, SkMatrix::I());
halcanary7a14b312015-10-01 07:28:13 -0700997}
998
Hal Canary7cbf5e32017-07-12 13:10:23 -0400999void SkPDFDevice::drawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint& paint) {
1000 SkASSERT(image);
1001 auto r = SkRect::MakeXYWH(x, y, image->width(), image->height());
1002 this->internalDrawImageRect(SkKeyedImage(sk_ref_sp(const_cast<SkImage*>(image))),
1003 nullptr, r, paint, this->ctm());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001004}
1005
Hal Canary7cbf5e32017-07-12 13:10:23 -04001006////////////////////////////////////////////////////////////////////////////////
1007
halcanaryf0c30f52016-07-15 13:35:45 -07001008namespace {
1009class GlyphPositioner {
1010public:
1011 GlyphPositioner(SkDynamicMemoryWStream* content,
1012 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -07001013 bool wideChars,
1014 bool defaultPositioning,
1015 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -07001016 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -07001017 , fCurrentMatrixOrigin(origin)
1018 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -07001019 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -07001020 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -07001021 }
halcanary4871f222016-08-26 13:17:44 -07001022 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -07001023 void flush() {
1024 if (fInText) {
1025 fContent->writeText("> Tj\n");
1026 fInText = false;
1027 }
1028 }
halcanary4871f222016-08-26 13:17:44 -07001029 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -07001030 SkScalar advanceWidth,
1031 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -07001032 if (!fInitialized) {
1033 // Flip the text about the x-axis to account for origin swap and include
1034 // the passed parameters.
1035 fContent->writeText("1 0 ");
1036 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
1037 fContent->writeText(" -1 ");
1038 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
1039 fContent->writeText(" ");
1040 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
1041 fContent->writeText(" Tm\n");
1042 fCurrentMatrixOrigin.set(0.0f, 0.0f);
1043 fInitialized = true;
1044 }
halcanary4ed2f012016-08-15 18:40:07 -07001045 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -07001046 SkPoint position = xy - fCurrentMatrixOrigin;
Hal Canary197ca9b2017-05-15 10:29:44 -04001047 if (position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -07001048 this->flush();
halcanary4871f222016-08-26 13:17:44 -07001049 SkPDFUtils::AppendScalar(position.x(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001050 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -07001051 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001052 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -07001053 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -07001054 fXAdvance = 0;
1055 }
1056 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -07001057 }
1058 if (!fInText) {
1059 fContent->writeText("<");
1060 fInText = true;
1061 }
1062 if (fWideChars) {
1063 SkPDFUtils::WriteUInt16BE(fContent, glyph);
1064 } else {
1065 SkASSERT(0 == glyph >> 8);
1066 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1067 }
halcanaryf0c30f52016-07-15 13:35:45 -07001068 }
1069
1070private:
1071 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -07001072 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001073 SkScalar fXAdvance = 0.0f;
1074 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001075 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001076 bool fInText = false;
1077 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -07001078 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001079};
halcanaryf59d18a2016-09-16 14:44:57 -07001080
1081/** Given the m-to-n glyph-to-character mapping data (as returned by
1082 harfbuzz), iterate over the clusters. */
1083class Clusterator {
1084public:
1085 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1086 explicit Clusterator(uint32_t glyphCount)
1087 : fClusters(nullptr)
1088 , fUtf8Text(nullptr)
1089 , fGlyphCount(glyphCount)
1090 , fTextByteLength(0) {}
1091 // The clusters[] array is an array of offsets into utf8Text[],
1092 // one offset for each glyph. See SkTextBlobBuilder for more info.
1093 Clusterator(const uint32_t* clusters,
1094 const char* utf8Text,
1095 uint32_t glyphCount,
1096 uint32_t textByteLength)
1097 : fClusters(clusters)
1098 , fUtf8Text(utf8Text)
1099 , fGlyphCount(glyphCount)
1100 , fTextByteLength(textByteLength) {
1101 // This is a cheap heuristic for /ReversedChars which seems to
1102 // work for clusters produced by HarfBuzz, which either
1103 // increase from zero (LTR) or decrease to zero (RTL).
1104 // "ReversedChars" is how PDF deals with RTL text.
1105 fReversedChars =
1106 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1107 }
1108 struct Cluster {
1109 const char* fUtf8Text;
1110 uint32_t fTextByteLength;
1111 uint32_t fGlyphIndex;
1112 uint32_t fGlyphCount;
1113 explicit operator bool() const { return fGlyphCount != 0; }
1114 };
1115 // True if this looks like right-to-left text.
1116 bool reversedChars() const { return fReversedChars; }
1117 Cluster next() {
1118 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1119 // These glyphs have no text. Treat as one "cluster".
1120 uint32_t glyphCount = fGlyphCount;
1121 fGlyphCount = 0;
1122 return Cluster{nullptr, 0, 0, glyphCount};
1123 }
1124 if (fGlyphCount == 0 || fTextByteLength == 0) {
1125 return Cluster{nullptr, 0, 0, 0}; // empty
1126 }
1127 SkASSERT(fUtf8Text);
1128 SkASSERT(fClusters);
1129 uint32_t cluster = fClusters[0];
1130 if (cluster >= fTextByteLength) {
1131 return Cluster{nullptr, 0, 0, 0}; // bad input.
1132 }
1133 uint32_t glyphsInCluster = 1;
1134 while (glyphsInCluster < fGlyphCount &&
1135 fClusters[glyphsInCluster] == cluster) {
1136 ++glyphsInCluster;
1137 }
1138 SkASSERT(glyphsInCluster <= fGlyphCount);
1139 uint32_t textLength = 0;
1140 if (glyphsInCluster == fGlyphCount) {
1141 // consumes rest of glyphs and rest of text
1142 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1143 textLength = fTextByteLength - cluster;
1144 } else { // RTL text; last cluster.
1145 SkASSERT(fPreviousCluster < fTextByteLength);
1146 if (fPreviousCluster <= cluster) { // bad input.
1147 return Cluster{nullptr, 0, 0, 0};
1148 }
1149 textLength = fPreviousCluster - cluster;
1150 }
1151 fGlyphCount = 0;
1152 return Cluster{fUtf8Text + cluster,
1153 textLength,
1154 fGlyphIndex,
1155 glyphsInCluster};
1156 }
1157 SkASSERT(glyphsInCluster < fGlyphCount);
1158 uint32_t nextCluster = fClusters[glyphsInCluster];
1159 if (nextCluster >= fTextByteLength) {
1160 return Cluster{nullptr, 0, 0, 0}; // bad input.
1161 }
1162 if (nextCluster > cluster) { // LTR text
1163 if (kInvalidCluster != fPreviousCluster) {
1164 return Cluster{nullptr, 0, 0, 0}; // bad input.
1165 }
1166 textLength = nextCluster - cluster;
1167 } else { // RTL text
1168 SkASSERT(nextCluster < cluster);
1169 if (kInvalidCluster == fPreviousCluster) { // first cluster
1170 textLength = fTextByteLength - cluster;
1171 } else { // later cluster
1172 if (fPreviousCluster <= cluster) {
1173 return Cluster{nullptr, 0, 0, 0}; // bad input.
1174 }
1175 textLength = fPreviousCluster - cluster;
1176 }
1177 fPreviousCluster = cluster;
1178 }
1179 uint32_t glyphIndex = fGlyphIndex;
1180 fGlyphCount -= glyphsInCluster;
1181 fGlyphIndex += glyphsInCluster;
1182 fClusters += glyphsInCluster;
1183 return Cluster{fUtf8Text + cluster,
1184 textLength,
1185 glyphIndex,
1186 glyphsInCluster};
1187 }
1188
1189private:
1190 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1191 const uint32_t* fClusters;
1192 const char* fUtf8Text;
1193 uint32_t fGlyphCount;
1194 uint32_t fTextByteLength;
1195 uint32_t fGlyphIndex = 0;
1196 uint32_t fPreviousCluster = kInvalidCluster;
1197 bool fReversedChars = false;
1198};
1199
1200struct TextStorage {
1201 SkAutoTMalloc<char> fUtf8textStorage;
1202 SkAutoTMalloc<uint32_t> fClusterStorage;
1203 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1204};
halcanaryf0c30f52016-07-15 13:35:45 -07001205} // namespace
1206
halcanaryf59d18a2016-09-16 14:44:57 -07001207/** Given some unicode text (as passed to drawText(), convert to
1208 glyphs (via primitive shaping), while preserving
1209 glyph-to-character mapping information. */
1210static Clusterator make_clusterator(
1211 const void* sourceText,
1212 size_t sourceByteCount,
1213 const SkPaint& paint,
1214 TextStorage* storage,
1215 int glyphCount) {
1216 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1217 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1218 SkASSERT(glyphCount > 0);
1219 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1220 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1221 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1222 uint32_t* clusters = storage->fClusterStorage.get();
1223 uint32_t utf8ByteCount = 0;
1224 const char* utf8Text = nullptr;
1225 switch (paint.getTextEncoding()) {
1226 case SkPaint::kUTF8_TextEncoding: {
1227 const char* txtPtr = (const char*)sourceText;
1228 for (int i = 0; i < glyphCount; ++i) {
1229 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1230 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1231 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1232 }
1233 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1234 utf8ByteCount = SkToU32(sourceByteCount);
1235 utf8Text = (const char*)sourceText;
1236 break;
1237 }
1238 case SkPaint::kUTF16_TextEncoding: {
1239 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1240 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1241 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1242 storage->fUtf8textStorage.reset(utf8ByteCount);
1243 char* txtPtr = storage->fUtf8textStorage.get();
1244 utf8Text = txtPtr;
1245 int clusterIndex = 0;
1246 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1247 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1248 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1249 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1250 }
1251 SkASSERT(clusterIndex == glyphCount);
1252 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1253 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1254 break;
1255 }
1256 case SkPaint::kUTF32_TextEncoding: {
1257 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1258 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1259 SkASSERT(glyphCount == utf32count);
1260 for (int i = 0; i < utf32count; ++i) {
1261 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1262 }
1263 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1264 char* txtPtr = storage->fUtf8textStorage.get();
1265 utf8Text = txtPtr;
1266 for (int i = 0; i < utf32count; ++i) {
1267 clusters[i] = SkToU32(txtPtr - utf8Text);
1268 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1269 }
1270 break;
1271 }
1272 default:
1273 SkDEBUGFAIL("");
1274 break;
1275 }
1276 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1277}
1278
halcanaryf59d18a2016-09-16 14:44:57 -07001279static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1280 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1281}
1282
halcanaryc2f9ec12016-09-12 08:55:29 -07001283static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1284 wStream->writeText("/");
1285 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1286 wStream->write(&prefix, 1);
1287 wStream->writeDecAsText(fontIndex);
1288 wStream->writeText(" ");
1289 SkPDFUtils::AppendScalar(textSize, wStream);
1290 wStream->writeText(" Tf\n");
1291}
1292
Hal Canaryd12a6762017-05-26 17:01:16 -04001293static SkPath draw_text_as_path(const void* sourceText, size_t sourceByteCount,
1294 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
1295 SkPoint offset, const SkPaint& srcPaint) {
1296 SkPath path;
1297 int glyphCount;
1298 SkAutoTMalloc<SkPoint> tmpPoints;
1299 switch (positioning) {
1300 case SkTextBlob::kDefault_Positioning:
1301 srcPaint.getTextPath(sourceText, sourceByteCount, offset.x(), offset.y(), &path);
1302 break;
1303 case SkTextBlob::kHorizontal_Positioning:
1304 glyphCount = srcPaint.countText(sourceText, sourceByteCount);
1305 tmpPoints.realloc(glyphCount);
1306 for (int i = 0; i < glyphCount; ++i) {
1307 tmpPoints[i] = {pos[i] + offset.x(), offset.y()};
1308 }
1309 srcPaint.getPosTextPath(sourceText, sourceByteCount, tmpPoints.get(), &path);
1310 break;
1311 case SkTextBlob::kFull_Positioning:
1312 srcPaint.getPosTextPath(sourceText, sourceByteCount, (const SkPoint*)pos, &path);
1313 path.offset(offset.x(), offset.y());
1314 break;
1315 }
1316 return path;
1317}
1318
Hal Canary9b9510a2017-07-18 09:39:00 -04001319static bool has_outline_glyph(SkGlyphID gid, SkGlyphCache* cache) {
1320 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1321 const SkPath* path = cache->findPath(glyph);
1322 return (path && !path->isEmpty()) || (glyph.fWidth == 0 && glyph.fHeight == 0);
1323}
1324
Hal Canary699b8732017-06-13 12:13:29 -04001325static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkGlyphCache* cache,
1326 SkScalar xScale, SkScalar yScale,
1327 SkPoint xy, const SkMatrix& ctm) {
1328 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1329 SkRect glyphBounds = {glyph.fLeft * xScale,
1330 glyph.fTop * yScale,
1331 (glyph.fLeft + glyph.fWidth) * xScale,
1332 (glyph.fTop + glyph.fHeight) * yScale};
1333 glyphBounds.offset(xy);
1334 ctm.mapRect(&glyphBounds); // now in dev space.
1335 return glyphBounds;
1336}
1337
1338static bool contains(const SkRect& r, SkPoint p) {
1339 return r.left() <= p.x() && p.x() <= r.right() &&
1340 r.top() <= p.y() && p.y() <= r.bottom();
1341}
1342
Hal Canary9b9510a2017-07-18 09:39:00 -04001343static sk_sp<SkImage> image_from_mask(const SkMask& mask) {
1344 if (!mask.fImage) {
1345 return nullptr;
1346 }
1347 SkIRect bounds = mask.fBounds;
1348 SkBitmap bm;
1349 switch (mask.fFormat) {
1350 case SkMask::kBW_Format:
1351 bm.allocPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()));
1352 for (int y = 0; y < bm.height(); ++y) {
1353 for (int x8 = 0; x8 < bm.width(); x8 += 8) {
1354 uint8_t v = *mask.getAddr1(x8 + bounds.x(), y + bounds.y());
1355 int e = SkTMin(x8 + 8, bm.width());
1356 for (int x = x8; x < e; ++x) {
1357 *bm.getAddr8(x, y) = (v >> (x & 0x7)) & 0x1 ? 0xFF : 0x00;
1358 }
1359 }
1360 }
1361 bm.setImmutable();
1362 return SkImage::MakeFromBitmap(bm);
1363 case SkMask::kA8_Format:
1364 bm.installPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()),
1365 mask.fImage, mask.fRowBytes);
1366 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1367 case SkMask::kARGB32_Format:
1368 bm.installPixels(SkImageInfo::MakeN32Premul(bounds.width(), bounds.height()),
1369 mask.fImage, mask.fRowBytes);
1370 return SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode);
1371 case SkMask::k3D_Format:
1372 SkASSERT(false);
1373 return nullptr;
1374 case SkMask::kLCD16_Format:
1375 SkASSERT(false);
1376 return nullptr;
1377 default:
1378 SkASSERT(false);
1379 return nullptr;
1380 }
1381}
1382
halcanary4ed2f012016-08-15 18:40:07 -07001383void SkPDFDevice::internalDrawText(
Mike Reeda1361362017-03-07 09:37:29 -05001384 const void* sourceText, size_t sourceByteCount,
halcanary4ed2f012016-08-15 18:40:07 -07001385 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001386 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1387 uint32_t textByteLength, const char* utf8Text) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001388 if (0 == sourceByteCount || !sourceText) {
1389 return;
1390 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001391 if (this->cs().isEmpty(this->bounds())) {
halcanary4ed2f012016-08-15 18:40:07 -07001392 return;
1393 }
halcanaryea17dfe2016-08-24 09:20:57 -07001394 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1395 if (srcPaint.isVerticalText()) {
1396 // Don't pretend we support drawing vertical text. It is not
1397 // clear to me how to switch to "vertical writing" mode in PDF.
1398 // Currently neither Chromium or Android set this flag.
1399 // https://bug.skia.org/5665
halcanaryea17dfe2016-08-24 09:20:57 -07001400 }
Hal Canaryd12a6762017-05-26 17:01:16 -04001401 if (srcPaint.getPathEffect()
1402 || srcPaint.getMaskFilter()
1403 || SkPaint::kFill_Style != srcPaint.getStyle()) {
1404 // Stroked Text doesn't work well with Type3 fonts.
1405 SkPath path = draw_text_as_path(sourceText, sourceByteCount, pos,
1406 positioning, offset, srcPaint);
1407 this->drawPath(path, srcPaint, nullptr, true);
halcanaryf59d18a2016-09-16 14:44:57 -07001408 return;
halcanarye06ca962016-09-09 05:34:55 -07001409 }
halcanary4ed2f012016-08-15 18:40:07 -07001410 SkPaint paint = calculate_text_paint(srcPaint);
Hal Canaryd12a6762017-05-26 17:01:16 -04001411 remove_color_filter(&paint);
halcanary4ed2f012016-08-15 18:40:07 -07001412 replace_srcmode_on_opaque_paint(&paint);
1413 if (!paint.getTypeface()) {
1414 paint.setTypeface(SkTypeface::MakeDefault());
1415 }
1416 SkTypeface* typeface = paint.getTypeface();
1417 if (!typeface) {
1418 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1419 return;
1420 }
halcanary4871f222016-08-26 13:17:44 -07001421
1422 const SkAdvancedTypefaceMetrics* metrics =
1423 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1424 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001425 return;
1426 }
halcanary2bd295e2016-09-16 08:15:56 -07001427 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1428 if (glyphCount <= 0) {
1429 return;
1430 }
halcanary3b294d52016-09-16 13:21:08 -07001431
halcanaryf59d18a2016-09-16 14:44:57 -07001432 // These three heap buffers are only used in the case where no glyphs
1433 // are passed to drawText() (most clients pass glyphs or a textblob).
1434 TextStorage storage;
1435 const SkGlyphID* glyphs = nullptr;
1436 Clusterator clusterator;
1437 if (textByteLength > 0) {
1438 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1439 glyphs = (const SkGlyphID*)sourceText;
1440 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1441 SkASSERT(clusters);
1442 SkASSERT(utf8Text);
1443 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1444 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1445 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1446 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1447 glyphs = (const SkGlyphID*)sourceText;
1448 clusterator = Clusterator(SkToU32(glyphCount));
1449 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1450 SkASSERT(nullptr == clusters);
1451 SkASSERT(nullptr == utf8Text);
1452 } else {
1453 SkASSERT(nullptr == clusters);
1454 SkASSERT(nullptr == utf8Text);
1455 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1456 &storage, glyphCount);
1457 glyphs = storage.fGlyphStorage;
1458 }
halcanary4ed2f012016-08-15 18:40:07 -07001459 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001460 paint.setHinting(SkPaint::kNo_Hinting);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001461
1462 int emSize;
1463 SkAutoGlyphCache glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
1464
1465 SkScalar textSize = paint.getTextSize();
1466 SkScalar advanceScale = textSize * paint.getTextScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001467
Hal Canary699b8732017-06-13 12:13:29 -04001468 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1469 SkScalar textScaleY = textSize / emSize;
1470 SkScalar textScaleX = advanceScale + paint.getTextSkewX() * textScaleY;
1471
halcanary4ed2f012016-08-15 18:40:07 -07001472 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001473 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1474 SkPaint::kCenter_Align == alignment ? -0.5f :
1475 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001476 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001477 SkScalar advance = 0;
halcanary4ed2f012016-08-15 18:40:07 -07001478 for (int i = 0; i < glyphCount; ++i) {
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001479 advance += advanceScale * glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
halcanary4ed2f012016-08-15 18:40:07 -07001480 }
halcanary4871f222016-08-26 13:17:44 -07001481 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001482 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001483 SkRect clipStackBounds = this->cs().bounds(this->bounds());
Hal Canary9b9510a2017-07-18 09:39:00 -04001484 struct PositionedGlyph {
1485 SkPoint fPos;
1486 SkGlyphID fGlyph;
1487 };
1488 SkTArray<PositionedGlyph> fMissingGlyphs;
1489 {
1490 ScopedContentEntry content(this, paint, true);
1491 if (!content.entry()) {
1492 return;
robertphillips5ba165e2016-08-15 15:36:58 -07001493 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001494 SkDynamicMemoryWStream* out = content.stream();
1495 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
1496
1497 out->writeText("BT\n");
1498 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1499
1500 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
1501
1502 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
1503 if (clusterator.reversedChars()) {
1504 out->writeText("/ReversedChars BMC\n");
1505 }
1506 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
1507 GlyphPositioner glyphPositioner(out,
1508 paint.getTextSkewX(),
1509 multiByteGlyphs,
1510 defaultPositioning,
1511 offset);
1512 SkPDFFont* font = nullptr;
1513
1514 while (Clusterator::Cluster c = clusterator.next()) {
1515 int index = c.fGlyphIndex;
1516 int glyphLimit = index + c.fGlyphCount;
1517
1518 bool actualText = false;
1519 SK_AT_SCOPE_EXIT(if (actualText) {
1520 glyphPositioner.flush();
1521 out->writeText("EMC\n");
1522 });
1523 if (c.fUtf8Text) { // real cluster
1524 // Check if `/ActualText` needed.
1525 const char* textPtr = c.fUtf8Text;
1526 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
1527 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1528 if (unichar < 0) {
halcanaryf59d18a2016-09-16 14:44:57 -07001529 return;
1530 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001531 if (textPtr < textEnd || // more characters left
1532 glyphLimit > index + 1 || // toUnicode wouldn't work
1533 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1534 {
1535 glyphPositioner.flush();
1536 out->writeText("/Span<</ActualText <");
1537 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1538 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1539 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1540 while (textPtr < textEnd) {
1541 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1542 if (unichar < 0) {
1543 break;
1544 }
1545 SkPDFUtils::WriteUTF16beHex(out, unichar);
1546 }
1547 out->writeText("> >> BDC\n"); // begin marked-content sequence
1548 // with an associated property list.
1549 actualText = true;
halcanaryf59d18a2016-09-16 14:44:57 -07001550 }
halcanaryf59d18a2016-09-16 14:44:57 -07001551 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001552 for (; index < glyphLimit; ++index) {
1553 SkGlyphID gid = glyphs[index];
1554 if (gid > maxGlyphID) {
1555 continue;
halcanaryf59d18a2016-09-16 14:44:57 -07001556 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001557 if (!font || !font->hasGlyph(gid)) {
1558 // Not yet specified font or need to switch font.
1559 int fontIndex = this->getFontResourceIndex(typeface, gid);
1560 // All preconditions for SkPDFFont::GetFontResource are met.
1561 SkASSERT(fontIndex >= 0);
1562 if (fontIndex < 0) {
1563 return;
1564 }
1565 glyphPositioner.flush();
1566 update_font(out, fontIndex, textSize);
1567 font = fFontResources[fontIndex];
1568 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1569 if (!font) {
1570 return;
1571 }
1572 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1573 }
1574 SkPoint xy = {0, 0};
1575 SkScalar advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1576 if (!defaultPositioning) {
1577 xy = SkTextBlob::kFull_Positioning == positioning
1578 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1579 : SkPoint{pos[index], 0};
1580 if (alignment != SkPaint::kLeft_Align) {
1581 xy.offset(alignmentFactor * advance, 0);
1582 }
1583 // Do a glyph-by-glyph bounds-reject if positions are absolute.
1584 SkRect glyphBounds = get_glyph_bounds_device_space(
1585 gid, glyphCache.get(), textScaleX, textScaleY,
1586 xy + offset, this->ctm());
1587 if (glyphBounds.isEmpty()) {
1588 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
1589 continue;
1590 }
1591 } else {
1592 if (!clipStackBounds.intersects(glyphBounds)) {
1593 continue; // reject glyphs as out of bounds
1594 }
1595 }
1596 if (!has_outline_glyph(gid, glyphCache.get())) {
Hal Canary10ccb022017-07-19 10:12:11 -04001597 fMissingGlyphs.push_back({xy + offset, gid});
Hal Canary699b8732017-06-13 12:13:29 -04001598 }
1599 } else {
Hal Canary9b9510a2017-07-18 09:39:00 -04001600 if (!has_outline_glyph(gid, glyphCache.get())) {
1601 fMissingGlyphs.push_back({offset, gid});
Hal Canary699b8732017-06-13 12:13:29 -04001602 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001603 offset += SkPoint{advance, 0};
Hal Canary699b8732017-06-13 12:13:29 -04001604 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001605 font->noteGlyphUsage(gid);
1606
1607 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1608 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
halcanaryf59d18a2016-09-16 14:44:57 -07001609 }
Hal Canary9b9510a2017-07-18 09:39:00 -04001610 }
1611 }
1612 if (fMissingGlyphs.count() > 0) {
1613 // Fall back on images.
1614 SkPaint scaledGlyphCachePaint;
1615 scaledGlyphCachePaint.setTextSize(paint.getTextSize());
1616 scaledGlyphCachePaint.setTextScaleX(paint.getTextScaleX());
1617 scaledGlyphCachePaint.setTextSkewX(paint.getTextSkewX());
1618 scaledGlyphCachePaint.setTypeface(sk_ref_sp(typeface));
1619 SkAutoGlyphCache scaledGlyphCache(scaledGlyphCachePaint, nullptr, nullptr);
1620 SkTHashMap<SkPDFCanon::BitmapGlyphKey, SkPDFCanon::BitmapGlyph>* map =
1621 &this->getCanon()->fBitmapGlyphImages;
1622 for (PositionedGlyph positionedGlyph : fMissingGlyphs) {
1623 SkPDFCanon::BitmapGlyphKey key = {typeface->uniqueID(),
1624 paint.getTextSize(),
1625 paint.getTextScaleX(),
1626 paint.getTextSkewX(),
1627 positionedGlyph.fGlyph,
1628 0};
1629 SkImage* img = nullptr;
1630 SkIPoint imgOffset = {0, 0};
1631 if (SkPDFCanon::BitmapGlyph* ptr = map->find(key)) {
1632 img = ptr->fImage.get();
1633 imgOffset = ptr->fOffset;
1634 } else {
1635 (void)scaledGlyphCache->findImage(
1636 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph));
1637 SkMask mask;
1638 scaledGlyphCache->getGlyphIDMetrics(positionedGlyph.fGlyph).toMask(&mask);
1639 imgOffset = {mask.fBounds.x(), mask.fBounds.y()};
1640 img = map->set(key, {image_from_mask(mask), imgOffset})->fImage.get();
1641 }
1642 if (img) {
1643 SkPoint pt = positionedGlyph.fPos +
1644 SkPoint{(SkScalar)imgOffset.x(), (SkScalar)imgOffset.y()};
1645 this->drawImage(img, pt.x(), pt.y(), srcPaint);
1646 }
halcanaryf59d18a2016-09-16 14:44:57 -07001647 }
robertphillips5ba165e2016-08-15 15:36:58 -07001648 }
halcanary4ed2f012016-08-15 18:40:07 -07001649}
1650
Mike Reeda1361362017-03-07 09:37:29 -05001651void SkPDFDevice::drawText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001652 SkScalar x, SkScalar y, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001653 this->internalDrawText(text, len, nullptr, SkTextBlob::kDefault_Positioning,
halcanarye06ca962016-09-09 05:34:55 -07001654 SkPoint{x, y}, paint, nullptr, 0, nullptr);
halcanary4ed2f012016-08-15 18:40:07 -07001655}
1656
Mike Reeda1361362017-03-07 09:37:29 -05001657void SkPDFDevice::drawPosText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001658 const SkScalar pos[], int scalarsPerPos,
1659 const SkPoint& offset, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001660 this->internalDrawText(text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001661 offset, paint, nullptr, 0, nullptr);
1662}
1663
Mike Reeda1361362017-03-07 09:37:29 -05001664void SkPDFDevice::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
halcanarye06ca962016-09-09 05:34:55 -07001665 const SkPaint &paint, SkDrawFilter* drawFilter) {
1666 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1667 SkPaint runPaint(paint);
1668 it.applyFontToPaint(&runPaint);
1669 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1670 continue;
1671 }
1672 runPaint.setFlags(this->filterTextFlags(runPaint));
1673 SkPoint offset = it.offset() + SkPoint{x, y};
Mike Reeda1361362017-03-07 09:37:29 -05001674 this->internalDrawText(it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
halcanarye06ca962016-09-09 05:34:55 -07001675 it.pos(), it.positioning(), offset, runPaint,
1676 it.clusters(), it.textSize(), it.text());
1677 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001678}
1679
Mike Reed2f6b5a42017-03-19 15:04:17 -04001680void SkPDFDevice::drawVertices(const SkVertices*, SkBlendMode, const SkPaint&) {
Hal Canary22b2d8c2017-07-19 14:46:12 -04001681 if (this->cs().isEmpty(this->bounds())) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001682 return;
1683 }
reed@google.com85e143c2013-12-30 15:51:25 +00001684 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001685}
1686
Mike Reeda1361362017-03-07 09:37:29 -05001687void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001688 SkASSERT(!paint.getImageFilter());
1689
reed7503d602016-07-15 14:23:29 -07001690 // Check if the source device is really a bitmapdevice (because that's what we returned
1691 // from createDevice (likely due to an imagefilter)
1692 SkPixmap pmap;
1693 if (device->peekPixels(&pmap)) {
1694 SkBitmap bitmap;
1695 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001696 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001697 return;
1698 }
1699
fmalita6987dca2014-11-13 08:33:37 -08001700 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001701 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001702
1703 SkScalar scalarX = SkIntToScalar(x);
1704 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001705 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1706 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001707 fLinkToURLs.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001708 }
halcanary91fcb3e2016-03-04 13:53:22 -08001709 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1710 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001711 fLinkToDestinations.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001712 }
halcanary91fcb3e2016-03-04 13:53:22 -08001713 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1714 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001715 fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001716 }
1717
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001718 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001719 return;
1720 }
1721
Mike Reeda1361362017-03-07 09:37:29 -05001722 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
1723 ScopedContentEntry content(this, this->cs(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001724 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001725 return;
1726 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001727 if (content.needShape()) {
1728 SkPath shape;
1729 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001730 SkIntToScalar(device->width()),
1731 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001732 content.setShape(shape);
1733 }
1734 if (!content.needSource()) {
1735 return;
1736 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001737
halcanary4b1e17e2016-07-27 14:49:46 -07001738 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
Hal Canary51329c92017-06-27 14:28:37 -04001739 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001740}
1741
reede8f30622016-03-23 18:59:25 -07001742sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1743 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001744}
1745
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001746
halcanary8103a342016-03-08 15:10:16 -08001747sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001748 SkTDArray<SkPDFObject*> fonts;
1749 fonts.setReserve(fFontResources.count());
1750 for (SkPDFFont* font : fFontResources) {
1751 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001752 }
halcanary8103a342016-03-08 15:10:16 -08001753 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001754 &fGraphicStateResources,
1755 &fShaderResources,
1756 &fXObjectResources,
1757 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001758}
1759
halcanary8103a342016-03-08 15:10:16 -08001760sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001761 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001762 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001763 mediaBox->appendInt(0);
1764 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001765 mediaBox->appendInt(fPageSize.width());
1766 mediaBox->appendInt(fPageSize.height());
1767 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001768}
1769
mtklein5f939ab2016-03-16 10:28:35 -07001770std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001771 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001772 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001773 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001774 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001775
Hal Canary6d673962017-02-22 17:16:59 -05001776 GraphicStackState gsState(fExistingClipStack, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001777 for (const auto& entry : fContentEntries) {
Hal Canary6d673962017-02-22 17:16:59 -05001778 gsState.updateClip(entry.fState.fClipStack,
Hal Canary22b2d8c2017-07-19 14:46:12 -04001779 {0, 0}, SkRect::Make(this->bounds()));
halcanary2be7e012016-03-28 11:58:08 -07001780 gsState.updateMatrix(entry.fState.fMatrix);
1781 gsState.updateDrawingState(entry.fState);
1782
halcanaryafdc1772016-08-23 09:02:12 -07001783 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001784 }
1785 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001786 if (buffer.bytesWritten() > 0) {
1787 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1788 } else {
1789 return skstd::make_unique<SkMemoryStream>();
1790 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001791}
1792
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001793/* Draws an inverse filled path by using Path Ops to compute the positive
1794 * inverse using the current clip as the inverse bounds.
1795 * Return true if this was an inverse path and was properly handled,
1796 * otherwise returns false and the normal drawing routine should continue,
1797 * either as a (incorrect) fallback or because the path was not inverse
1798 * in the first place.
1799 */
Mike Reeda1361362017-03-07 09:37:29 -05001800bool SkPDFDevice::handleInversePath(const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001801 const SkPaint& paint, bool pathIsMutable,
1802 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001803 if (!origPath.isInverseFillType()) {
1804 return false;
1805 }
1806
Hal Canary22b2d8c2017-07-19 14:46:12 -04001807 if (this->cs().isEmpty(this->bounds())) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001808 return false;
1809 }
1810
1811 SkPath modifiedPath;
1812 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1813 SkPaint noInversePaint(paint);
1814
1815 // Merge stroking operations into final path.
1816 if (SkPaint::kStroke_Style == paint.getStyle() ||
1817 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1818 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1819 if (doFillPath) {
1820 noInversePaint.setStyle(SkPaint::kFill_Style);
1821 noInversePaint.setStrokeWidth(0);
1822 pathPtr = &modifiedPath;
1823 } else {
1824 // To be consistent with the raster output, hairline strokes
1825 // are rendered as non-inverted.
1826 modifiedPath.toggleInverseFillType();
Mike Reeda1361362017-03-07 09:37:29 -05001827 this->drawPath(modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001828 return true;
1829 }
1830 }
1831
1832 // Get bounds of clip in current transform space
1833 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001834 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001835 SkMatrix totalMatrix = this->ctm();
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001836 if (prePathMatrix) {
1837 totalMatrix.preConcat(*prePathMatrix);
1838 }
1839 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001840 return false;
1841 }
Hal Canary22b2d8c2017-07-19 14:46:12 -04001842 SkRect bounds = this->cs().bounds(this->bounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001843 transformInverse.mapRect(&bounds);
1844
1845 // Extend the bounds by the line width (plus some padding)
1846 // so the edge doesn't cause a visible stroke.
1847 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1848 paint.getStrokeWidth() + SK_Scalar1);
1849
1850 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1851 return false;
1852 }
1853
Mike Reeda1361362017-03-07 09:37:29 -05001854 this->drawPath(modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001855 return true;
1856}
1857
wangxianzhuef6c50a2015-09-17 20:38:02 -07001858void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1859 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001860 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001861 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001862 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001863 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001864 }
halcanary91fcb3e2016-03-04 13:53:22 -08001865 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001866 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001867 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001868 array->appendObject(
1869 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001870 }
1871}
epoger@google.comb58772f2013-03-08 09:09:10 +00001872
halcanary6d622702015-03-25 08:45:42 -07001873void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001874 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001875 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001876 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001877 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001878 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001879 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001880 pdfDest->appendScalar(p.x());
1881 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001882 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001883 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001884 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001885 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001886}
1887
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001888sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice(bool alpha) {
halcanary5abbb442016-07-29 08:41:33 -07001889 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001890 if (!fInitialTransform.isIdentity()) {
1891 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001892 SkDEBUGFAIL("Layer initial transform should be invertible.");
1893 inverseTransform.reset();
1894 }
1895 }
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001896 const char* colorSpace = alpha ? "DeviceGray" : nullptr;
halcanary4b1e17e2016-07-27 14:49:46 -07001897 sk_sp<SkPDFObject> xobject =
1898 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
Hal Canaryb4bd5ef2017-07-26 09:16:01 -04001899 this->makeResourceDict(), inverseTransform, colorSpace);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001900 // We always draw the form xobjects that we create back into the device, so
1901 // we simply preserve the font usage instead of pulling it out and merging
1902 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001903 this->cleanUp(); // Reset this device to have no content.
1904 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001905 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001906}
1907
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001908void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001909 sk_sp<SkPDFObject> mask,
Mike Reeda1361362017-03-07 09:37:29 -05001910 const SkClipStack& clipStack,
reed374772b2016-10-05 17:33:02 -07001911 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001912 bool invertClip) {
Hal Canary22b2d8c2017-07-19 14:46:12 -04001913 if (!invertClip && clipStack.isEmpty(this->bounds())) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001914 return;
1915 }
1916
halcanary4b1e17e2016-07-27 14:49:46 -07001917 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001918 std::move(mask), invertClip,
1919 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001920
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001921 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001922 paint.setBlendMode(mode);
Mike Reeda1361362017-03-07 09:37:29 -05001923 ScopedContentEntry content(this, clipStack, SkMatrix::I(), paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001924 if (!content.entry()) {
1925 return;
1926 }
Hal Canary51329c92017-06-27 14:28:37 -04001927 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()), content.stream());
1928 SkPDFUtils::DrawFormXObject(xObjectIndex, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001929 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001930}
1931
Mike Reeda1361362017-03-07 09:37:29 -05001932SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack& clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001933 const SkMatrix& matrix,
1934 const SkPaint& paint,
1935 bool hasText,
1936 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001937 *dst = nullptr;
reed374772b2016-10-05 17:33:02 -07001938 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001939
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001940 // For the following modes, we want to handle source and destination
1941 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001942 if (blendMode == SkBlendMode::kClear ||
1943 blendMode == SkBlendMode::kSrc ||
1944 blendMode == SkBlendMode::kSrcIn ||
1945 blendMode == SkBlendMode::kDstIn ||
1946 blendMode == SkBlendMode::kSrcOut ||
1947 blendMode == SkBlendMode::kDstOut ||
1948 blendMode == SkBlendMode::kSrcATop ||
1949 blendMode == SkBlendMode::kDstATop ||
1950 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001951 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001952 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001953 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001954 } else if (blendMode != SkBlendMode::kSrc &&
1955 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001956 // Except for Src and SrcOut, if there isn't anything already there,
1957 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001958 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001959 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001960 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001961 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001962 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001963
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001964 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001965 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001966 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001967 }
1968
halcanary2be7e012016-03-28 11:58:08 -07001969 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001970 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001971 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001972 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001973 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001974 } else {
halcanary2be7e012016-03-28 11:58:08 -07001975 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001976 }
Mike Reeda1361362017-03-07 09:37:29 -05001977 populateGraphicStateEntryFromPaint(matrix, clipStack, paint, hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001978 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001979}
1980
reed374772b2016-10-05 17:33:02 -07001981void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001982 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001983 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001984 if (blendMode != SkBlendMode::kClear &&
1985 blendMode != SkBlendMode::kSrc &&
1986 blendMode != SkBlendMode::kDstOver &&
1987 blendMode != SkBlendMode::kSrcIn &&
1988 blendMode != SkBlendMode::kDstIn &&
1989 blendMode != SkBlendMode::kSrcOut &&
1990 blendMode != SkBlendMode::kDstOut &&
1991 blendMode != SkBlendMode::kSrcATop &&
1992 blendMode != SkBlendMode::kDstATop &&
1993 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001994 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001995 return;
1996 }
reed374772b2016-10-05 17:33:02 -07001997 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001998 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00001999 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002000 // For DstOver, an empty content entry was inserted before the rest
2001 // of the content entries. If nothing was drawn, it needs to be
2002 // removed.
halcanary2be7e012016-03-28 11:58:08 -07002003 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002004 }
2005 return;
2006 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002007 if (!dst) {
reed374772b2016-10-05 17:33:02 -07002008 SkASSERT(blendMode == SkBlendMode::kSrc ||
2009 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002010 return;
2011 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002012
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002013 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07002014 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002015 // Changing the current content into a form-xobject will destroy the clip
2016 // objects which is fine since the xobject will already be clipped. However
2017 // if source has shape, we need to clip it too, so a copy of the clip is
2018 // saved.
halcanary2be7e012016-03-28 11:58:08 -07002019
2020 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002021
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002022 SkPaint stockPaint;
2023
halcanary4b1e17e2016-07-27 14:49:46 -07002024 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002025 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002026 // If nothing was drawn and there's no shape, then the draw was a
2027 // no-op, but dst needs to be restored for that to be true.
2028 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
2029 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
2030 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07002031 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
2032 blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002033 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07002034 // TODO: addXObjectResource take sk_sp
Hal Canary51329c92017-06-27 14:28:37 -04002035 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002036 return;
2037 } else {
reed374772b2016-10-05 17:33:02 -07002038 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002039 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002040 } else {
halcanary2be7e012016-03-28 11:58:08 -07002041 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07002042 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002043 }
2044
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002045 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
2046 // without alpha.
reed374772b2016-10-05 17:33:02 -07002047 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002048 // TODO(vandebo): In order to properly support SrcATop we have to track
2049 // the shape of what's been drawn at all times. It's the intersection of
2050 // the non-transparent parts of the device and the outlines (shape) of
2051 // all images and devices drawn.
2052 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
Mike Reeda1361362017-03-07 09:37:29 -05002053 fExistingClipStack, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002054 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07002055 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002056 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002057 SkPaint filledPaint;
2058 filledPaint.setColor(SK_ColorBLACK);
2059 filledPaint.setStyle(SkPaint::kFill_Style);
Mike Reeda1361362017-03-07 09:37:29 -05002060 this->internalDrawPath(clipStack, SkMatrix::I(), *shape, filledPaint, nullptr, true);
2061 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
2062 this->makeFormXObjectFromDevice(),
2063 fExistingClipStack,
2064 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07002065 } else {
Mike Reeda1361362017-03-07 09:37:29 -05002066 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
2067 srcFormXObject,
2068 fExistingClipStack,
2069 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002070 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002071 }
2072
reed374772b2016-10-05 17:33:02 -07002073 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002074 return;
reed374772b2016-10-05 17:33:02 -07002075 } else if (blendMode == SkBlendMode::kSrc ||
2076 blendMode == SkBlendMode::kDstATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002077 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002078 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04002079 SkPDFUtils::DrawFormXObject(this->addXObjectResource(srcFormXObject.get()),
2080 content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002081 }
reed374772b2016-10-05 17:33:02 -07002082 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002083 return;
2084 }
reed374772b2016-10-05 17:33:02 -07002085 } else if (blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002086 ScopedContentEntry content(this, fExistingClipStack,
2087 SkMatrix::I(), stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002088 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04002089 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002090 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002091 }
2092
reed374772b2016-10-05 17:33:02 -07002093 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
2094 blendMode == SkBlendMode::kDstIn ||
2095 blendMode == SkBlendMode::kSrcOut ||
2096 blendMode == SkBlendMode::kDstOut ||
2097 blendMode == SkBlendMode::kSrcATop ||
2098 blendMode == SkBlendMode::kDstATop ||
2099 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002100
reed374772b2016-10-05 17:33:02 -07002101 if (blendMode == SkBlendMode::kSrcIn ||
2102 blendMode == SkBlendMode::kSrcOut ||
2103 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07002104 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
2105 std::move(dst),
Mike Reeda1361362017-03-07 09:37:29 -05002106 fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07002107 SkBlendMode::kSrcOver,
2108 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07002109 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002110 } else {
reed374772b2016-10-05 17:33:02 -07002111 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07002112 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07002113 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002114 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
Mike Reeda1361362017-03-07 09:37:29 -05002115 std::move(dst), fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07002116 SkBlendMode::kSrcOver, false);
2117 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002118 }
halcanarydabd4f02016-08-03 11:16:56 -07002119 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
Mike Reeda1361362017-03-07 09:37:29 -05002120 fExistingClipStack, mode,
reed374772b2016-10-05 17:33:02 -07002121 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07002122 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002123 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002124}
2125
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002126bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00002127 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07002128 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002129 return true;
2130 }
2131 return false;
2132}
2133
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002134void SkPDFDevice::populateGraphicStateEntryFromPaint(
2135 const SkMatrix& matrix,
2136 const SkClipStack& clipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002137 const SkPaint& paint,
2138 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07002139 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07002140 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
2141 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
2142 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002143
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002144 entry->fMatrix = matrix;
2145 entry->fClipStack = clipStack;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002146 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2147 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002148
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002149 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08002150 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07002151 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002152 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002153 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05002154 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
2155 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002156 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05002157 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002158 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07002159 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002160 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05002161 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
2162 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2163 color = gradientColor;
2164 } else {
2165 // PDF positions patterns relative to the initial transform, so
2166 // we need to apply the current transform to the shader parameters.
2167 SkMatrix transform = matrix;
2168 transform.postConcat(fInitialTransform);
2169
2170 // PDF doesn't support kClamp_TileMode, so we simulate it by making
2171 // a pattern the size of the current clip.
Hal Canary22b2d8c2017-07-19 14:46:12 -04002172 SkRect clipStackBounds = clipStack.bounds(this->bounds());
Hal Canaryc8f91802017-02-12 20:29:12 -05002173
2174 // We need to apply the initial transform to bounds in order to get
2175 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05002176 fInitialTransform.mapRect(&clipStackBounds);
2177 SkIRect bounds;
2178 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05002179
Hal Canary7e872ca2017-07-19 15:51:18 -04002180 pdfShader = SkPDFMakeShader(fDocument, shader, transform, bounds, paint.getColor());
Hal Canaryc8f91802017-02-12 20:29:12 -05002181
2182 if (pdfShader.get()) {
2183 // pdfShader has been canonicalized so we can directly compare
2184 // pointers.
2185 int resourceIndex = fShaderResources.find(pdfShader.get());
2186 if (resourceIndex < 0) {
2187 resourceIndex = fShaderResources.count();
2188 fShaderResources.push(pdfShader.get());
2189 pdfShader.get()->ref();
2190 }
2191 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002192 }
2193 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002194 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002195
Hal Canary80fa7ce2017-06-28 16:04:20 -04002196 sk_sp<SkPDFDict> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002197 if (color == paint.getColor()) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002198 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002199 } else {
2200 SkPaint newPaint = paint;
2201 newPaint.setColor(color);
Hal Canary5c1b3602017-04-17 16:30:06 -04002202 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002203 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002204 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002205 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002206
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002207 if (hasText) {
2208 entry->fTextScaleX = paint.getTextScaleX();
2209 entry->fTextFill = paint.getStyle();
2210 } else {
2211 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002212 }
2213}
2214
halcanarybe27a112015-04-01 13:31:19 -07002215int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002216 // Assumes that gs has been canonicalized (so we can directly compare
2217 // pointers).
2218 int result = fGraphicStateResources.find(gs);
2219 if (result < 0) {
2220 result = fGraphicStateResources.count();
2221 fGraphicStateResources.push(gs);
2222 gs->ref();
2223 }
2224 return result;
2225}
2226
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002227int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002228 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002229 // Assumes that xobject has been canonicalized (so we can directly compare
2230 // pointers).
2231 int result = fXObjectResources.find(xObject);
2232 if (result < 0) {
2233 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002234 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002235 }
2236 return result;
2237}
2238
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002239int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002240 sk_sp<SkPDFFont> newFont = SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID);
halcanary7e8d5d32016-08-12 07:59:38 -07002241 if (!newFont) {
2242 return -1;
2243 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002244 int resourceIndex = fFontResources.find(newFont.get());
2245 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002246 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002247 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002248 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002249 }
2250 return resourceIndex;
2251}
2252
Hal Canaryfafe1352017-04-11 12:12:02 -04002253static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07002254
Hal Canary7cbf5e32017-07-12 13:10:23 -04002255static sk_sp<SkImage> color_filter(const SkImage* image,
halcanarya50151d2016-03-25 11:57:49 -07002256 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002257 auto surface =
Hal Canary7cbf5e32017-07-12 13:10:23 -04002258 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07002259 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002260 SkCanvas* canvas = surface->getCanvas();
2261 canvas->clear(SK_ColorTRANSPARENT);
2262 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002263 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canary7cbf5e32017-07-12 13:10:23 -04002264 canvas->drawImage(image, 0, 0, &paint);
halcanarya50151d2016-03-25 11:57:49 -07002265 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002266}
2267
2268////////////////////////////////////////////////////////////////////////////////
Hal Canary7cbf5e32017-07-12 13:10:23 -04002269
2270static bool is_integer(SkScalar x) {
2271 return x == SkScalarTruncToScalar(x);
2272}
2273
2274static bool is_integral(const SkRect& r) {
2275 return is_integer(r.left()) &&
2276 is_integer(r.top()) &&
2277 is_integer(r.right()) &&
2278 is_integer(r.bottom());
2279}
2280
2281void SkPDFDevice::internalDrawImageRect(SkKeyedImage imageSubset,
2282 const SkRect* src,
2283 const SkRect& dst,
2284 const SkPaint& srcPaint,
2285 const SkMatrix& ctm) {
2286 if (!imageSubset) {
halcanarya50151d2016-03-25 11:57:49 -07002287 return;
2288 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002289
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002290 // First, figure out the src->dst transform and subset the image if needed.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002291 SkIRect bounds = imageSubset.image()->bounds();
Hal Canary7cbf5e32017-07-12 13:10:23 -04002292 SkRect srcRect = src ? *src : SkRect::Make(bounds);
2293 SkMatrix transform;
2294 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
2295 if (src && *src != SkRect::Make(bounds)) {
2296 if (!srcRect.intersect(SkRect::Make(bounds))) {
2297 return;
2298 }
2299 srcRect.roundOut(&bounds);
2300 transform.preTranslate(SkIntToScalar(bounds.x()),
2301 SkIntToScalar(bounds.y()));
2302 if (bounds != imageSubset.image()->bounds()) {
2303 imageSubset = imageSubset.subset(bounds);
2304 }
2305 if (!imageSubset) {
2306 return;
2307 }
2308 }
2309
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002310 // If the image is opaque and the paint's alpha is too, replace
2311 // kSrc blendmode with kSrcOver.
2312 SkPaint paint = srcPaint;
2313 if (imageSubset.image()->isOpaque()) {
2314 replace_srcmode_on_opaque_paint(&paint);
Hal Canaryd425a1d2017-07-12 13:13:51 -04002315 }
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002316
2317 // Alpha-only images need to get their color from the shader, before
2318 // applying the colorfilter.
2319 if (imageSubset.image()->isAlphaOnly() && paint.getColorFilter()) {
2320 // must blend alpha image and shader before applying colorfilter.
2321 auto surface =
2322 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.image()->dimensions()));
2323 SkCanvas* canvas = surface->getCanvas();
2324 SkPaint tmpPaint;
2325 // In the case of alpha images with shaders, the shader's coordinate
2326 // system is the image's coordiantes.
2327 tmpPaint.setShader(sk_ref_sp(paint.getShader()));
2328 tmpPaint.setColor(paint.getColor());
2329 canvas->clear(0x00000000);
2330 canvas->drawImage(imageSubset.image().get(), 0, 0, &tmpPaint);
2331 paint.setShader(nullptr);
2332 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2333 SkASSERT(!imageSubset.image()->isAlphaOnly());
2334 }
2335
2336 if (imageSubset.image()->isAlphaOnly()) {
2337 // The ColorFilter applies to the paint color/shader, not the alpha layer.
2338 SkASSERT(nullptr == paint.getColorFilter());
2339
Hal Canaryd425a1d2017-07-12 13:13:51 -04002340 sk_sp<SkImage> mask = alpha_image_to_greyscale_image(imageSubset.image().get());
2341 if (!mask) {
2342 return;
2343 }
2344 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
2345 // Must mask with a Form XObject.
2346 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
2347 {
2348 SkCanvas canvas(maskDevice.get());
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002349 if (paint.getMaskFilter()) {
2350 // This clip prevents the mask image shader from covering
2351 // entire device if unnecessary.
2352 canvas.clipRect(this->cs().bounds(this->bounds()));
2353 canvas.concat(ctm);
2354 SkPaint tmpPaint;
2355 tmpPaint.setShader(mask->makeShader(&transform));
2356 tmpPaint.setMaskFilter(sk_ref_sp(paint.getMaskFilter()));
2357 canvas.drawRect(dst, tmpPaint);
2358 } else {
2359 canvas.concat(ctm);
2360 if (src && !is_integral(*src)) {
2361 canvas.clipRect(dst);
2362 }
2363 canvas.concat(transform);
2364 canvas.drawImage(mask, 0, 0);
2365 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04002366 }
Hal Canaryd425a1d2017-07-12 13:13:51 -04002367 if (!ctm.isIdentity() && paint.getShader()) {
2368 transform_shader(&paint, ctm); // Since we are using identity matrix.
2369 }
2370 ScopedContentEntry content(this, this->cs(), SkMatrix::I(), paint);
2371 if (!content.entry()) {
2372 return;
2373 }
2374 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
2375 SkPDFUtils::AppendRectangle(SkRect::Make(fPageSize), content.stream());
2376 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kWinding_FillType, content.stream());
2377 this->clearMaskOnGraphicState(content.stream());
2378 return;
2379 }
Hal Canary7cbf5e32017-07-12 13:10:23 -04002380 if (paint.getMaskFilter()) {
2381 paint.setShader(imageSubset.image()->makeShader(&transform));
2382 SkPath path;
Hal Canaryf0f4c0c2017-07-19 15:48:38 -04002383 path.addRect(dst); // handles non-integral clipping.
2384 this->internalDrawPath(this->cs(), this->ctm(), path, paint, nullptr, true);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002385 return;
2386 }
2387 transform.postConcat(ctm);
2388
2389 bool needToRestore = false;
2390 if (src && !is_integral(*src)) {
2391 // Need sub-pixel clipping to fix https://bug.skia.org/4374
2392 this->cs().save();
2393 this->cs().clipRect(dst, ctm, SkClipOp::kIntersect, true);
2394 needToRestore = true;
2395 }
2396 SK_AT_SCOPE_EXIT(if (needToRestore) { this->cs().restore(); });
2397
halcanary7a14b312015-10-01 07:28:13 -07002398 #ifdef SK_PDF_IMAGE_STATS
2399 gDrawImageCalls.fetch_add(1);
2400 #endif
Hal Canary7cbf5e32017-07-12 13:10:23 -04002401 SkMatrix matrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002402
2403 // Rasterize the bitmap using perspective in a new bitmap.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002404 if (transform.hasPerspective()) {
Hal Canarya0622582017-06-29 18:51:35 -04002405 SkASSERT(fDocument->rasterDpi() > 0);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002406 // Transform the bitmap in the new space, without taking into
2407 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002408 SkPath perspectiveOutline;
Hal Canary7cbf5e32017-07-12 13:10:23 -04002409 SkRect imageBounds = SkRect::Make(imageSubset.image()->bounds());
halcanary7a14b312015-10-01 07:28:13 -07002410 perspectiveOutline.addRect(imageBounds);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002411 perspectiveOutline.transform(transform);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002412
2413 // TODO(edisonn): perf - use current clip too.
2414 // Retrieve the bounds of the new shape.
2415 SkRect bounds = perspectiveOutline.getBounds();
2416
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002417 // Transform the bitmap in the new space, taking into
2418 // account the initial transform.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002419 SkMatrix total = transform;
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002420 total.postConcat(fInitialTransform);
Hal Canarya0622582017-06-29 18:51:35 -04002421 SkScalar dpiScale = SkIntToScalar(fDocument->rasterDpi()) /
2422 SkIntToScalar(SkPDFUtils::kDpiForRasterScaleOne);
halcanary7a14b312015-10-01 07:28:13 -07002423 total.postScale(dpiScale, dpiScale);
2424
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002425 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002426 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002427 physicalPerspectiveOutline.transform(total);
2428
halcanary7a14b312015-10-01 07:28:13 -07002429 SkRect physicalPerspectiveBounds =
2430 physicalPerspectiveOutline.getBounds();
2431 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2432 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002433
2434 // TODO(edisonn): A better approach would be to use a bitmap shader
2435 // (in clamp mode) and draw a rect over the entire bounding box. Then
2436 // intersect perspectiveOutline to the clip. That will avoid introducing
2437 // alpha to the image while still giving good behavior at the edge of
2438 // the image. Avoiding alpha will reduce the pdf size and generation
2439 // CPU time some.
2440
halcanary7a14b312015-10-01 07:28:13 -07002441 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2442
Hal Canaryf50ff392016-09-30 10:25:39 -04002443 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002444 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002445 return;
2446 }
halcanary7a14b312015-10-01 07:28:13 -07002447 SkCanvas* canvas = surface->getCanvas();
2448 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002449
2450 SkScalar deltaX = bounds.left();
2451 SkScalar deltaY = bounds.top();
2452
Hal Canary7cbf5e32017-07-12 13:10:23 -04002453 SkMatrix offsetMatrix = transform;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002454 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002455 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002456
2457 // Translate the draw in the new canvas, so we perfectly fit the
2458 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002459 canvas->setMatrix(offsetMatrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002460 canvas->drawImage(imageSubset.image(), 0, 0);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002461 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002462 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002463
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002464 // In the new space, we use the identity matrix translated
2465 // and scaled to reflect DPI.
2466 matrix.setScale(1 / scaleX, 1 / scaleY);
2467 matrix.postTranslate(deltaX, deltaY);
2468
Hal Canary7cbf5e32017-07-12 13:10:23 -04002469 imageSubset = SkKeyedImage(surface->makeImageSnapshot());
2470 if (!imageSubset) {
2471 return;
2472 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002473 }
2474
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002475 SkMatrix scaled;
2476 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002477 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2478 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002479 // Scale the image up from 1x1 to WxH.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002480 SkIRect subset = imageSubset.image()->bounds();
2481 scaled.postScale(SkIntToScalar(subset.width()),
2482 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002483 scaled.postConcat(matrix);
Hal Canary7cbf5e32017-07-12 13:10:23 -04002484 ScopedContentEntry content(this, this->cs(), scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002485 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002486 return;
2487 }
2488 if (content.needShape()) {
2489 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002490 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002491 shape.transform(matrix);
2492 content.setShape(shape);
2493 }
2494 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002495 return;
2496 }
2497
halcanary287d22d2015-09-24 10:20:05 -07002498 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002499 sk_sp<SkImage> img = color_filter(imageSubset.image().get(), colorFilter);
2500 imageSubset = SkKeyedImage(std::move(img));
2501 if (!imageSubset) {
2502 return;
2503 }
halcanary7a14b312015-10-01 07:28:13 -07002504 // TODO(halcanary): de-dupe this by caching filtered images.
2505 // (maybe in the resource cache?)
2506 }
halcanarya50151d2016-03-25 11:57:49 -07002507
Hal Canary7cbf5e32017-07-12 13:10:23 -04002508 SkBitmapKey key = imageSubset.key();
Hal Canary5c1b3602017-04-17 16:30:06 -04002509 sk_sp<SkPDFObject>* pdfimagePtr = fDocument->canon()->fPDFBitmapMap.find(key);
2510 sk_sp<SkPDFObject> pdfimage = pdfimagePtr ? *pdfimagePtr : nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002511 if (!pdfimage) {
Hal Canary7cbf5e32017-07-12 13:10:23 -04002512 SkASSERT(imageSubset);
2513 pdfimage = SkPDFCreateBitmapObject(imageSubset.release(),
2514 fDocument->canon()->fPixelSerializer.get());
halcanary7a14b312015-10-01 07:28:13 -07002515 if (!pdfimage) {
2516 return;
halcanary287d22d2015-09-24 10:20:05 -07002517 }
halcanarya50151d2016-03-25 11:57:49 -07002518 fDocument->serialize(pdfimage); // serialize images early.
Hal Canary7cbf5e32017-07-12 13:10:23 -04002519 SkASSERT((key != SkBitmapKey{{0, 0, 0, 0}, 0}));
Hal Canary5c1b3602017-04-17 16:30:06 -04002520 fDocument->canon()->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002521 }
halcanarya50151d2016-03-25 11:57:49 -07002522 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
Hal Canary51329c92017-06-27 14:28:37 -04002523 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002524}
reede51c3562016-07-19 14:33:20 -07002525
2526///////////////////////////////////////////////////////////////////////////////////////////////////
2527
2528#include "SkSpecialImage.h"
2529#include "SkImageFilter.h"
2530
Florin Malita53f77bd2017-04-28 13:48:37 -04002531void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2532 SkImage* clipImage, const SkMatrix& clipMatrix) {
reede51c3562016-07-19 14:33:20 -07002533 SkASSERT(!srcImg->isTextureBacked());
2534
Florin Malita53f77bd2017-04-28 13:48:37 -04002535 //TODO: clipImage support
2536
reede51c3562016-07-19 14:33:20 -07002537 SkBitmap resultBM;
2538
2539 SkImageFilter* filter = paint.getImageFilter();
2540 if (filter) {
2541 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002542 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002543 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002544 const SkIRect clipBounds =
Hal Canary22b2d8c2017-07-19 14:46:12 -04002545 this->cs().bounds(this->bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002546 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
brianosman2a75e5d2016-09-22 07:15:37 -07002547 // TODO: Should PDF be operating in a specified color space? For now, run the filter
2548 // in the same color space as the source (this is different from all other backends).
2549 SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2550 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002551
2552 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2553 if (resultImg) {
2554 SkPaint tmpUnfiltered(paint);
2555 tmpUnfiltered.setImageFilter(nullptr);
2556 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002557 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002558 }
2559 }
2560 } else {
2561 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002562 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002563 }
2564 }
2565}
2566
2567sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2568 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2569}
2570
2571sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002572 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2573 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2574 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002575 SkColorSpace* legacyColorSpace = nullptr;
Hal Canary22b2d8c2017-07-19 14:46:12 -04002576 return SkSpecialImage::MakeFromImage(image->bounds(),
Brian Osman61624f02016-12-09 14:51:59 -05002577 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002578}
2579
2580sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002581 return nullptr;
2582}
brianosman04a44d02016-09-21 09:46:57 -07002583
2584SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2585 // We always return a transient cache, so it is freed after each
2586 // filter traversal.
2587 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2588}