blob: 6888f54ca53c454c7e69215cdad1c212093d3dd0 [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 Canaryd12a6762017-05-26 17:01:16 -040014#include "SkClipOpPriv.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000015#include "SkColor.h"
halcanary287d22d2015-09-24 10:20:05 -070016#include "SkColorFilter.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000017#include "SkDraw.h"
halcanarye06ca962016-09-09 05:34:55 -070018#include "SkDrawFilter.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000019#include "SkGlyphCache.h"
brianosman04a44d02016-09-21 09:46:57 -070020#include "SkImageFilterCache.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040021#include "SkJpegEncoder.h"
halcanary022c2bd2016-09-02 11:29:46 -070022#include "SkMakeUnique.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040023#include "SkMaskFilter.h"
halcanarydb0dcc72015-03-20 12:31:52 -070024#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070025#include "SkPDFCanon.h"
Hal Canaryd12a6762017-05-26 17:01:16 -040026#include "SkPDFCanvas.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
Mike Reeda1361362017-03-07 09:37:29 -050090static void draw_points(SkCanvas::PointMode mode,
91 size_t count,
92 const SkPoint* points,
93 const SkPaint& paint,
94 const SkIRect& bounds,
95 const SkMatrix& ctm,
96 SkBaseDevice* device) {
97 SkRasterClip rc(bounds);
98 SkDraw draw;
99 draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(bounds.right(), bounds.bottom()), nullptr, 0);
100 draw.fMatrix = &ctm;
101 draw.fRC = &rc;
102 draw.drawPoints(mode, count, points, paint, device);
103}
104
105static SkIRect size(const SkBaseDevice& dev) { return {0, 0, dev.width(), dev.height()}; }
106
reed374772b2016-10-05 17:33:02 -0700107// If the paint will definitely draw opaquely, replace kSrc with
108// kSrcOver. http://crbug.com/473572
halcanarya6814332015-05-27 08:53:36 -0700109static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
reed374772b2016-10-05 17:33:02 -0700110 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
111 paint->setBlendMode(SkBlendMode::kSrcOver);
halcanarya6814332015-05-27 08:53:36 -0700112 }
113}
114
Hal Canaryd12a6762017-05-26 17:01:16 -0400115// A shader's matrix is: CTMM x LocalMatrix x WrappingLocalMatrix. We want to
116// switch to device space, where CTM = I, while keeping the original behavior.
117//
118// I * LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
119// LocalMatrix * NewWrappingMatrix = CTM * LocalMatrix
120// InvLocalMatrix * LocalMatrix * NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
121// NewWrappingMatrix = InvLocalMatrix * CTM * LocalMatrix
122//
123static void transform_shader(SkPaint* paint, const SkMatrix& ctm) {
124 SkMatrix lm = SkPDFUtils::GetShaderLocalMatrix(paint->getShader());
125 SkMatrix lmInv;
126 if (lm.invert(&lmInv)) {
127 SkMatrix m = SkMatrix::Concat(SkMatrix::Concat(lmInv, ctm), lm);
128 paint->setShader(paint->getShader()->makeWithLocalMatrix(m));
129 }
130}
131
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000132static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000133 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -0700134 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000135 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700136 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000137 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -0700138 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +0000139 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000140}
141
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000142static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000143 SkPaint result = paint;
144 if (result.isFakeBoldText()) {
145 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
146 kStdFakeBoldInterpKeys,
147 kStdFakeBoldInterpValues,
148 kStdFakeBoldInterpLength);
Mike Reed8be952a2017-02-13 20:44:33 -0500149 SkScalar width = result.getTextSize() * fakeBoldScale;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000150 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000151 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000152 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000153 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000154 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000155 result.setStrokeWidth(width);
156 }
157 return result;
158}
159
Hal Canaryf50ff392016-09-30 10:25:39 -0400160static SkImageSubset make_image_subset(const SkBitmap& bitmap) {
161 SkASSERT(!bitmap.drawsNothing());
162 SkIRect subset = bitmap.getSubset();
Hal Canaryf50ff392016-09-30 10:25:39 -0400163 SkASSERT(bitmap.pixelRef());
164 SkBitmap tmp;
Matt Saretta6e976a2017-04-28 15:43:35 -0400165 SkImageInfo pixelRefInfo =
166 bitmap.info().makeWH(bitmap.pixelRef()->width(), bitmap.pixelRef()->height());
167 tmp.setInfo(pixelRefInfo, bitmap.rowBytes());
Hal Canary1b3387b2016-12-12 13:48:12 -0500168 tmp.setPixelRef(sk_ref_sp(bitmap.pixelRef()), 0, 0);
Hal Canaryf50ff392016-09-30 10:25:39 -0400169 auto img = SkImage::MakeFromBitmap(tmp);
170 if (img) {
171 SkASSERT(!bitmap.isImmutable() || img->uniqueID() == bitmap.getGenerationID());
172 SkASSERT(img->bounds().contains(subset));
173 }
174 SkImageSubset imageSubset(std::move(img), subset);
175 // SkImage::MakeFromBitmap only preserves genID for immutable
176 // bitmaps. Use the bitmap's original ID for de-duping.
177 imageSubset.setID(bitmap.getGenerationID());
178 return imageSubset;
179}
180
Hal Canaryd12a6762017-05-26 17:01:16 -0400181// If the paint has a color filter, apply the color filter to the shader or the
182// paint color. Remove the color filter.
183void remove_color_filter(SkPaint* paint) {
184 if (SkColorFilter* cf = paint->getColorFilter()) {
185 if (SkShader* shader = paint->getShader()) {
186 paint->setShader(shader->makeWithColorFilter(paint->refColorFilter()));
187 } else {
188 paint->setColor(cf->filterColor(paint->getColor()));
189 }
190 paint->setColorFilter(nullptr);
191 }
192}
193
halcanary2be7e012016-03-28 11:58:08 -0700194SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
195 : fColor(SK_ColorBLACK)
196 , fTextScaleX(SK_Scalar1)
197 , fTextFill(SkPaint::kFill_Style)
198 , fShaderIndex(-1)
halcanaryc2f9ec12016-09-12 08:55:29 -0700199 , fGraphicStateIndex(-1) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000200 fMatrix.reset();
201}
202
halcanary2be7e012016-03-28 11:58:08 -0700203bool SkPDFDevice::GraphicStateEntry::compareInitialState(
204 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000205 return fColor == cur.fColor &&
206 fShaderIndex == cur.fShaderIndex &&
207 fGraphicStateIndex == cur.fGraphicStateIndex &&
208 fMatrix == cur.fMatrix &&
209 fClipStack == cur.fClipStack &&
210 (fTextScaleX == 0 ||
211 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000212}
213
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000214class GraphicStackState {
215public:
216 GraphicStackState(const SkClipStack& existingClipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000217 SkWStream* contentStream)
218 : fStackDepth(0),
219 fContentStream(contentStream) {
220 fEntries[0].fClipStack = existingClipStack;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000221 }
222
Hal Canary6d673962017-02-22 17:16:59 -0500223 void updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500224 const SkPoint& translation, const SkRect& bounds);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000225 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700226 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000227
228 void drainStack();
229
230private:
231 void push();
232 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700233 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000234
235 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
236 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700237 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000238 int fStackDepth;
239 SkWStream* fContentStream;
240};
241
242void GraphicStackState::drainStack() {
243 while (fStackDepth) {
244 pop();
245 }
246}
247
248void GraphicStackState::push() {
249 SkASSERT(fStackDepth < kMaxStackDepth);
250 fContentStream->writeText("q\n");
251 fStackDepth++;
252 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
253}
254
255void GraphicStackState::pop() {
256 SkASSERT(fStackDepth > 0);
257 fContentStream->writeText("Q\n");
258 fStackDepth--;
259}
260
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000261/* Calculate an inverted path's equivalent non-inverted path, given the
262 * canvas bounds.
263 * outPath may alias with invPath (since this is supported by PathOps).
264 */
265static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
266 SkPath* outPath) {
267 SkASSERT(invPath.isInverseFillType());
268
269 SkPath clipPath;
270 clipPath.addRect(bounds);
271
reedcdb42bb2015-06-26 10:23:07 -0700272 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000273}
274
Hal Canary44a97d52017-02-22 10:45:25 -0500275bool apply_clip(SkClipOp op, const SkPath& u, const SkPath& v, SkPath* r) {
276 switch (op) {
277 case SkClipOp::kDifference:
278 return Op(u, v, kDifference_SkPathOp, r);
279 case SkClipOp::kIntersect:
280 return Op(u, v, kIntersect_SkPathOp, r);
Mike Reed14113bc2017-05-10 14:13:20 -0400281#ifdef SK_SUPPORT_DEPRECATED_CLIPOPS
Hal Canary44a97d52017-02-22 10:45:25 -0500282 case SkClipOp::kUnion_deprecated:
283 return Op(u, v, kUnion_SkPathOp, r);
284 case SkClipOp::kXOR_deprecated:
285 return Op(u, v, kXOR_SkPathOp, r);
286 case SkClipOp::kReverseDifference_deprecated:
287 return Op(u, v, kReverseDifference_SkPathOp, r);
288 case SkClipOp::kReplace_deprecated:
289 *r = v;
290 return true;
Mike Reed14113bc2017-05-10 14:13:20 -0400291#endif
Hal Canary44a97d52017-02-22 10:45:25 -0500292 default:
293 return false;
294 }
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000295}
296
297/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
298 * Returns true if successful, or false if not successful.
299 * If successful, the resulting clip is stored in outClipPath.
300 * If not successful, outClipPath is undefined, and a fallback method
301 * should be used.
302 */
303static bool get_clip_stack_path(const SkMatrix& transform,
304 const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500305 const SkRect& bounds,
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000306 SkPath* outClipPath) {
307 outClipPath->reset();
308 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
309
310 const SkClipStack::Element* clipEntry;
311 SkClipStack::Iter iter;
312 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
313 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
314 SkPath entryPath;
315 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
316 outClipPath->reset();
317 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
318 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000319 } else {
320 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000321 }
322 entryPath.transform(transform);
Hal Canary44a97d52017-02-22 10:45:25 -0500323 if (!apply_clip(clipEntry->getOp(), *outClipPath, entryPath, outClipPath)) {
324 return false;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000325 }
326 }
327
328 if (outClipPath->isInverseFillType()) {
329 // The bounds are slightly outset to ensure this is correct in the
330 // face of floating-point accuracy and possible SkRegion bitmap
331 // approximations.
Hal Canary44a97d52017-02-22 10:45:25 -0500332 SkRect clipBounds = bounds;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000333 clipBounds.outset(SK_Scalar1, SK_Scalar1);
334 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
335 return false;
336 }
337 }
338 return true;
339}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000340
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000341// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000342// graphic state stack, and the fact that we can know all the clips used
343// on the page to optimize this.
344void GraphicStackState::updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500345 const SkPoint& translation,
346 const SkRect& bounds) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000347 if (clipStack == currentEntry()->fClipStack) {
348 return;
349 }
350
351 while (fStackDepth > 0) {
352 pop();
353 if (clipStack == currentEntry()->fClipStack) {
354 return;
355 }
356 }
357 push();
358
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000359 currentEntry()->fClipStack = clipStack;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000360
361 SkMatrix transform;
362 transform.setTranslate(translation.fX, translation.fY);
363
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000364 SkPath clipPath;
Hal Canary44a97d52017-02-22 10:45:25 -0500365 if (get_clip_stack_path(transform, clipStack, bounds, &clipPath)) {
halcanary5edf2902016-09-07 09:05:25 -0700366 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
367 SkPath::FillType clipFill = clipPath.getFillType();
368 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
369 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
370 if (clipFill == SkPath::kEvenOdd_FillType) {
371 fContentStream->writeText("W* n\n");
372 } else {
373 fContentStream->writeText("W n\n");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000374 }
375 }
halcanary5edf2902016-09-07 09:05:25 -0700376 // If Op() fails (pathological case; e.g. input values are
377 // extremely large or NaN), emit no clip at all.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000378}
379
380void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
381 if (matrix == currentEntry()->fMatrix) {
382 return;
383 }
384
385 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
386 SkASSERT(fStackDepth > 0);
387 SkASSERT(fEntries[fStackDepth].fClipStack ==
388 fEntries[fStackDepth -1].fClipStack);
389 pop();
390
391 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
392 }
393 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
394 return;
395 }
396
397 push();
398 SkPDFUtils::AppendTransform(matrix, fContentStream);
399 currentEntry()->fMatrix = matrix;
400}
401
halcanary2be7e012016-03-28 11:58:08 -0700402void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000403 // PDF treats a shader as a color, so we only set one or the other.
404 if (state.fShaderIndex >= 0) {
405 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000406 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000407 currentEntry()->fShaderIndex = state.fShaderIndex;
408 }
409 } else {
410 if (state.fColor != currentEntry()->fColor ||
411 currentEntry()->fShaderIndex >= 0) {
412 emit_pdf_color(state.fColor, fContentStream);
413 fContentStream->writeText("RG ");
414 emit_pdf_color(state.fColor, fContentStream);
415 fContentStream->writeText("rg\n");
416 currentEntry()->fColor = state.fColor;
417 currentEntry()->fShaderIndex = -1;
418 }
419 }
420
421 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000422 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000423 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
424 }
425
426 if (state.fTextScaleX) {
427 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
Mike Reed8be952a2017-02-13 20:44:33 -0500428 SkScalar pdfScale = state.fTextScaleX * 1000;
halcanarybc4696b2015-05-06 10:56:04 -0700429 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000430 fContentStream->writeText(" Tz\n");
431 currentEntry()->fTextScaleX = state.fTextScaleX;
432 }
433 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700434 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
435 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
436 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000437 fContentStream->writeDecAsText(state.fTextFill);
438 fContentStream->writeText(" Tr\n");
439 currentEntry()->fTextFill = state.fTextFill;
440 }
441 }
442}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000443
reed76033be2015-03-14 10:54:31 -0700444static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700445 // PDF does not support image filters, so render them on CPU.
446 // Note that this rendering is done at "screen" resolution (100dpi), not
447 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700448 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800449 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700450
451 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700452 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700453}
454
455SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700456 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700457 // need to return a raster device, which we will detect in drawDevice()
458 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700459 }
fmalita6987dca2014-11-13 08:33:37 -0800460 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
Hal Canarya0622582017-06-29 18:51:35 -0400461 return new SkPDFDevice(size, fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000462}
463
halcanary989da4a2016-03-21 14:33:17 -0700464SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
465
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000466// A helper class to automatically finish a ContentEntry at the end of a
467// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000468class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000469public:
Mike Reeda1361362017-03-07 09:37:29 -0500470 ScopedContentEntry(SkPDFDevice* device,
471 const SkClipStack& clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000472 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500473 const SkPaint& paint,
474 bool hasText = false)
475 : fDevice(device)
476 , fContentEntry(nullptr)
477 , fBlendMode(SkBlendMode::kSrcOver)
478 , fDstFormXObject(nullptr)
479 {
480 if (matrix.hasPerspective()) {
481 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
482 return;
483 }
484 fBlendMode = paint.getBlendMode();
485 fContentEntry =
486 fDevice->setUpContentEntry(clipStack, matrix, paint, hasText, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000487 }
Mike Reeda1361362017-03-07 09:37:29 -0500488 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, bool hasText = false)
489 : ScopedContentEntry(dev, dev->cs(), dev->ctm(), paint, hasText) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000490
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000491 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000492 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000493 SkPath* shape = &fShape;
494 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700495 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000496 }
reed374772b2016-10-05 17:33:02 -0700497 fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000498 }
499 }
500
halcanary2be7e012016-03-28 11:58:08 -0700501 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
Hal Canary51329c92017-06-27 14:28:37 -0400502 SkDynamicMemoryWStream* stream() { return &fContentEntry->fContent; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000503
504 /* Returns true when we explicitly need the shape of the drawing. */
505 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700506 switch (fBlendMode) {
507 case SkBlendMode::kClear:
508 case SkBlendMode::kSrc:
509 case SkBlendMode::kSrcIn:
510 case SkBlendMode::kSrcOut:
511 case SkBlendMode::kDstIn:
512 case SkBlendMode::kDstOut:
513 case SkBlendMode::kSrcATop:
514 case SkBlendMode::kDstATop:
515 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000516 return true;
517 default:
518 return false;
519 }
520 }
521
522 /* Returns true unless we only need the shape of the drawing. */
523 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700524 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000525 return false;
526 }
527 return true;
528 }
529
530 /* If the shape is different than the alpha component of the content, then
531 * setShape should be called with the shape. In particular, images and
532 * devices have rectangular shape.
533 */
534 void setShape(const SkPath& shape) {
535 fShape = shape;
536 }
537
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000538private:
539 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700540 SkPDFDevice::ContentEntry* fContentEntry;
reed374772b2016-10-05 17:33:02 -0700541 SkBlendMode fBlendMode;
halcanarydabd4f02016-08-03 11:16:56 -0700542 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000543 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000544};
545
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000546////////////////////////////////////////////////////////////////////////////////
547
Hal Canarya0622582017-06-29 18:51:35 -0400548SkPDFDevice::SkPDFDevice(SkISize pageSize, SkPDFDocument* doc)
reed589a39e2016-08-20 07:59:19 -0700549 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
550 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700551 , fPageSize(pageSize)
Hal Canarya0622582017-06-29 18:51:35 -0400552 , fInitialTransform(SkMatrix::I())
553 , fDocument(doc)
554{
halcanarya1f1ee92015-02-20 06:17:26 -0800555 SkASSERT(pageSize.width() > 0);
556 SkASSERT(pageSize.height() > 0);
Hal Canarya0622582017-06-29 18:51:35 -0400557}
robertphillips1f3923e2016-07-21 07:17:54 -0700558
Hal Canarya0622582017-06-29 18:51:35 -0400559void SkPDFDevice::setFlip() {
560 // Skia generally uses the top left as the origin but PDF
561 // natively has the origin at the bottom left. This matrix
562 // corrects for that. But that only needs to be done once, we
563 // don't do it when layering.
564 fInitialTransform.setTranslate(0, SkIntToScalar(fPageSize.fHeight));
565 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000566}
567
568SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700569 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000570}
571
572void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700573 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000574}
575
halcanary3c35fb32016-06-30 11:55:07 -0700576void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000577 fGraphicStateResources.unrefAll();
578 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000579 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000580 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000581}
582
Mike Reeda1361362017-03-07 09:37:29 -0500583void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500584 if (!value) {
585 return;
586 }
587 if (rect.isEmpty()) {
Mike Reeda1361362017-03-07 09:37:29 -0500588 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
589 SkPoint transformedPoint;
590 this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
Hal Canary5c1b3602017-04-17 16:30:06 -0400591 fNamedDestinations.emplace_back(NamedDestination{sk_ref_sp(value), transformedPoint});
Mike Reeda1361362017-03-07 09:37:29 -0500592 }
593 return;
594 }
595 // Convert to path to handle non-90-degree rotations.
596 SkPath path;
597 path.addRect(rect);
598 path.transform(this->ctm(), &path);
599 SkPath clip;
600 (void)this->cs().asPath(&clip);
601 Op(clip, path, kIntersect_SkPathOp, &path);
602 // PDF wants a rectangle only.
603 SkRect transformedRect = path.getBounds();
604 if (transformedRect.isEmpty()) {
605 return;
606 }
607 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400608 fLinkToURLs.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
Mike Reeda1361362017-03-07 09:37:29 -0500609 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
Hal Canary5c1b3602017-04-17 16:30:06 -0400610 fLinkToDestinations.emplace_back(RectWithData{transformedRect, sk_ref_sp(value)});
reedf70b5312016-03-04 16:36:20 -0800611 }
612}
613
Hal Canaryd12a6762017-05-26 17:01:16 -0400614void SkPDFDevice::drawPaint(const SkPaint& srcPaint) {
615 SkPaint newPaint = srcPaint;
616 remove_color_filter(&newPaint);
halcanarya6814332015-05-27 08:53:36 -0700617 replace_srcmode_on_opaque_paint(&newPaint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000618 newPaint.setStyle(SkPaint::kFill_Style);
Hal Canaryd12a6762017-05-26 17:01:16 -0400619
620 SkMatrix ctm = this->ctm();
621 if (ctm.getType() & SkMatrix::kPerspective_Mask) {
622 if (newPaint.getShader()) {
623 transform_shader(&newPaint, ctm);
624 }
625 ctm = SkMatrix::I();
626 }
627 ScopedContentEntry content(this, this->cs(), ctm, newPaint);
Mike Reeda1361362017-03-07 09:37:29 -0500628 this->internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000629}
630
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000631void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700632 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000633 if (!contentEntry) {
634 return;
635 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000636 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
637 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000638 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000639 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000640 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000641 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000642 inverse.mapRect(&bbox);
643
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000644 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000645 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000646 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000647}
648
Mike Reeda1361362017-03-07 09:37:29 -0500649void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700650 size_t count,
651 const SkPoint* points,
652 const SkPaint& srcPaint) {
653 SkPaint passedPaint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400654 remove_color_filter(&passedPaint);
halcanarya6814332015-05-27 08:53:36 -0700655 replace_srcmode_on_opaque_paint(&passedPaint);
Hal Canary80fa7ce2017-06-28 16:04:20 -0400656 if (SkCanvas::kPoints_PointMode != mode) {
657 passedPaint.setStyle(SkPaint::kStroke_Style);
658 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000659 if (count == 0) {
660 return;
661 }
662
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000663 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
664 // We only use this when there's a path effect because of the overhead
665 // of multiple calls to setUpContentEntry it causes.
666 if (passedPaint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500667 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000668 return;
669 }
Mike Reeda1361362017-03-07 09:37:29 -0500670 draw_points(mode, count, points, passedPaint,
671 this->devClipBounds(), this->ctm(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000672 return;
673 }
674
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000675 const SkPaint* paint = &passedPaint;
676 SkPaint modifiedPaint;
677
678 if (mode == SkCanvas::kPoints_PointMode &&
679 paint->getStrokeCap() != SkPaint::kRound_Cap) {
680 modifiedPaint = *paint;
681 paint = &modifiedPaint;
682 if (paint->getStrokeWidth()) {
683 // PDF won't draw a single point with square/butt caps because the
684 // orientation is ambiguous. Draw a rectangle instead.
685 modifiedPaint.setStyle(SkPaint::kFill_Style);
686 SkScalar strokeWidth = paint->getStrokeWidth();
687 SkScalar halfStroke = SkScalarHalf(strokeWidth);
688 for (size_t i = 0; i < count; i++) {
689 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
690 r.inset(-halfStroke, -halfStroke);
Mike Reeda1361362017-03-07 09:37:29 -0500691 this->drawRect(r, modifiedPaint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000692 }
693 return;
694 } else {
695 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
696 }
697 }
698
Mike Reeda1361362017-03-07 09:37:29 -0500699 ScopedContentEntry content(this, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000700 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000701 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000702 }
Hal Canary51329c92017-06-27 14:28:37 -0400703 SkDynamicMemoryWStream* contentStream = content.stream();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000704 switch (mode) {
705 case SkCanvas::kPolygon_PointMode:
Hal Canary51329c92017-06-27 14:28:37 -0400706 SkPDFUtils::MoveTo(points[0].fX, points[0].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000707 for (size_t i = 1; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400708 SkPDFUtils::AppendLine(points[i].fX, points[i].fY, contentStream);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000709 }
Hal Canary51329c92017-06-27 14:28:37 -0400710 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000711 break;
712 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000713 for (size_t i = 0; i < count/2; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400714 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY, contentStream);
715 SkPDFUtils::AppendLine(points[i * 2 + 1].fX, points[i * 2 + 1].fY, contentStream);
716 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000717 }
718 break;
719 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000720 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
721 for (size_t i = 0; i < count; i++) {
Hal Canary51329c92017-06-27 14:28:37 -0400722 SkPDFUtils::MoveTo(points[i].fX, points[i].fY, contentStream);
723 SkPDFUtils::ClosePath(contentStream);
724 SkPDFUtils::StrokePath(contentStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000725 }
726 break;
727 default:
728 SkASSERT(false);
729 }
730}
731
halcanary8103a342016-03-08 15:10:16 -0800732static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800733 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700734 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700735 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700736
halcanaryece83922016-03-08 08:32:12 -0800737 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700738 border->reserve(3);
739 border->appendInt(0); // Horizontal corner radius.
740 border->appendInt(0); // Vertical corner radius.
741 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800742 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700743
halcanaryece83922016-03-08 08:32:12 -0800744 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700745 rect->reserve(4);
746 rect->appendScalar(translatedRect.fLeft);
747 rect->appendScalar(translatedRect.fTop);
748 rect->appendScalar(translatedRect.fRight);
749 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800750 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700751
halcanary8103a342016-03-08 15:10:16 -0800752 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700753}
754
halcanary8103a342016-03-08 15:10:16 -0800755static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700756 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700757 SkString url(static_cast<const char *>(urlData->data()),
758 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800759 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700760 action->insertName("S", "URI");
761 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800762 annotation->insertObject("A", std::move(action));
763 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700764}
765
halcanary8103a342016-03-08 15:10:16 -0800766static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
767 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700768 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700769 SkString name(static_cast<const char *>(nameData->data()),
770 nameData->size() - 1);
771 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800772 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700773}
774
Mike Reeda1361362017-03-07 09:37:29 -0500775void SkPDFDevice::drawRect(const SkRect& rect,
halcanarya6814332015-05-27 08:53:36 -0700776 const SkPaint& srcPaint) {
777 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400778 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700779 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000780 SkRect r = rect;
781 r.sort();
782
Hal Canaryd12a6762017-05-26 17:01:16 -0400783 if (paint.getPathEffect() || paint.getMaskFilter()) {
Mike Reeda1361362017-03-07 09:37:29 -0500784 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000785 return;
786 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000787 SkPath path;
788 path.addRect(r);
Mike Reeda1361362017-03-07 09:37:29 -0500789 this->drawPath(path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000790 return;
791 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000792
Mike Reeda1361362017-03-07 09:37:29 -0500793 ScopedContentEntry content(this, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000794 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000795 return;
796 }
Hal Canary51329c92017-06-27 14:28:37 -0400797 SkPDFUtils::AppendRectangle(r, content.stream());
798 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType, content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000799}
800
Mike Reeda1361362017-03-07 09:37:29 -0500801void SkPDFDevice::drawRRect(const SkRRect& rrect,
halcanarya6814332015-05-27 08:53:36 -0700802 const SkPaint& srcPaint) {
803 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400804 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700805 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000806 SkPath path;
807 path.addRRect(rrect);
Mike Reeda1361362017-03-07 09:37:29 -0500808 this->drawPath(path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000809}
810
Mike Reeda1361362017-03-07 09:37:29 -0500811void SkPDFDevice::drawOval(const SkRect& oval,
halcanarya6814332015-05-27 08:53:36 -0700812 const SkPaint& srcPaint) {
813 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400814 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700815 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700816 SkPath path;
817 path.addOval(oval);
Mike Reeda1361362017-03-07 09:37:29 -0500818 this->drawPath(path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700819}
820
Mike Reeda1361362017-03-07 09:37:29 -0500821void SkPDFDevice::drawPath(const SkPath& origPath,
halcanarya6814332015-05-27 08:53:36 -0700822 const SkPaint& srcPaint,
823 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000824 bool pathIsMutable) {
Mike Reeda1361362017-03-07 09:37:29 -0500825 this->internalDrawPath(
826 this->cs(), this->ctm(), origPath, srcPaint, prePathMatrix, pathIsMutable);
827}
828
Hal Canaryd12a6762017-05-26 17:01:16 -0400829void SkPDFDevice::internalDrawPathWithFilter(const SkClipStack& clipStack,
830 const SkMatrix& ctm,
831 const SkPath& origPath,
832 const SkPaint& origPaint,
833 const SkMatrix* prePathMatrix) {
834 SkASSERT(origPaint.getMaskFilter());
835 SkPath path(origPath);
836 SkTCopyOnFirstWrite<SkPaint> paint(origPaint);
837 if (prePathMatrix) {
838 path.transform(*prePathMatrix, &path);
839 }
840 SkStrokeRec::InitStyle initStyle = paint->getFillPath(path, &path)
841 ? SkStrokeRec::kFill_InitStyle
842 : SkStrokeRec::kHairline_InitStyle;
843 path.transform(ctm, &path);
844
Hal Canarya0622582017-06-29 18:51:35 -0400845 // TODO(halcanary): respect fDocument->rasterDpi().
846 // SkScalar rasterScale = (float)rasterDpi / SkPDFUtils::kDpiForRasterScaleOne;
Hal Canaryd12a6762017-05-26 17:01:16 -0400847 // Would it be easier to just change the device size (and pre-scale the canvas)?
848 SkIRect bounds = clipStack.bounds(size(*this)).roundOut();
849 SkMask sourceMask;
850 if (!SkDraw::DrawToMask(path, &bounds, paint->getMaskFilter(), &SkMatrix::I(),
851 &sourceMask, SkMask::kComputeBoundsAndRenderImage_CreateMode,
852 initStyle)) {
853 return;
854 }
855 SkAutoMaskFreeImage srcAutoMaskFreeImage(sourceMask.fImage);
856 SkMask dstMask;
857 SkIPoint margin;
858 if (!paint->getMaskFilter()->filterMask(&dstMask, sourceMask, ctm, &margin)) {
859 return;
860 }
Hal Canary51329c92017-06-27 14:28:37 -0400861 SkIRect dstMaskBounds = dstMask.fBounds;
862 sk_sp<SkImage> mask = mask_to_greyscale_image(&dstMask);
Hal Canaryd12a6762017-05-26 17:01:16 -0400863 // PDF doesn't seem to allow masking vector graphics with an Image XObject.
864 // Must mask with a Form XObject.
Hal Canary51329c92017-06-27 14:28:37 -0400865 sk_sp<SkPDFDevice> maskDevice = this->makeCongruentDevice();
Hal Canaryd12a6762017-05-26 17:01:16 -0400866 {
867 SkPDFCanvas canvas(maskDevice);
Hal Canary51329c92017-06-27 14:28:37 -0400868 canvas.drawImage(mask, dstMaskBounds.x(), dstMaskBounds.y());
Hal Canaryd12a6762017-05-26 17:01:16 -0400869 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400870 if (!ctm.isIdentity() && paint->getShader()) {
871 transform_shader(paint.writable(), ctm); // Since we are using identity matrix.
872 }
873 ScopedContentEntry content(this, clipStack, SkMatrix::I(), *paint);
874 if (!content.entry()) {
875 return;
876 }
Hal Canary51329c92017-06-27 14:28:37 -0400877 this->addSMaskGraphicState(std::move(maskDevice), content.stream());
878 SkPDFUtils::AppendRectangle(SkRect::Make(dstMaskBounds), content.stream());
879 SkPDFUtils::PaintPath(SkPaint::kFill_Style, path.getFillType(), content.stream());
880 this->clearMaskOnGraphicState(content.stream());
881}
Hal Canaryd12a6762017-05-26 17:01:16 -0400882
Hal Canary51329c92017-06-27 14:28:37 -0400883void SkPDFDevice::addSMaskGraphicState(sk_sp<SkPDFDevice> maskDevice,
884 SkDynamicMemoryWStream* contentStream) {
885 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
886 maskDevice->makeFormXObjectFromDevice(), false,
887 SkPDFGraphicState::kLuminosity_SMaskMode, this->getCanon());
888 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(sMaskGS.get()), contentStream);
889}
Hal Canaryd12a6762017-05-26 17:01:16 -0400890
Hal Canary51329c92017-06-27 14:28:37 -0400891void SkPDFDevice::clearMaskOnGraphicState(SkDynamicMemoryWStream* contentStream) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400892 // The no-softmask graphic state is used to "turn off" the mask for later draw calls.
Hal Canaryc02de0b2017-06-28 13:14:03 -0400893 sk_sp<SkPDFDict>& noSMaskGS = this->getCanon()->fNoSmaskGraphicState;
894 if (!noSMaskGS) {
895 noSMaskGS = sk_make_sp<SkPDFDict>("ExtGState");
896 noSMaskGS->insertName("SMask", "None");
897 }
Hal Canary51329c92017-06-27 14:28:37 -0400898 SkPDFUtils::ApplyGraphicState(this->addGraphicStateResource(noSMaskGS.get()), contentStream);
Hal Canaryd12a6762017-05-26 17:01:16 -0400899}
900
Mike Reeda1361362017-03-07 09:37:29 -0500901void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
902 const SkMatrix& ctm,
903 const SkPath& origPath,
904 const SkPaint& srcPaint,
905 const SkMatrix* prePathMatrix,
906 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700907 SkPaint paint = srcPaint;
Hal Canaryd12a6762017-05-26 17:01:16 -0400908 remove_color_filter(&paint);
halcanarya6814332015-05-27 08:53:36 -0700909 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800910 SkPath modifiedPath;
911 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000912
Hal Canaryd12a6762017-05-26 17:01:16 -0400913 if (paint.getMaskFilter()) {
914 this->internalDrawPathWithFilter(clipStack, ctm, origPath, paint, prePathMatrix);
915 return;
916 }
917
Mike Reeda1361362017-03-07 09:37:29 -0500918 SkMatrix matrix = ctm;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000919 if (prePathMatrix) {
920 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800921 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000922 pathPtr = &modifiedPath;
923 pathIsMutable = true;
924 }
halcanary682ee012016-01-28 10:59:34 -0800925 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000926 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000927 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000928 }
929 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000930
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000931 if (paint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500932 if (clipStack.isEmpty(size(*this))) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000933 return;
934 }
halcanary682ee012016-01-28 10:59:34 -0800935 if (!pathIsMutable) {
Hal Canaryd12a6762017-05-26 17:01:16 -0400936 modifiedPath = origPath;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000937 pathPtr = &modifiedPath;
938 pathIsMutable = true;
939 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400940 if (paint.getFillPath(*pathPtr, pathPtr)) {
941 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000942 } else {
Hal Canaryd12a6762017-05-26 17:01:16 -0400943 paint.setStyle(SkPaint::kStroke_Style);
944 paint.setStrokeWidth(0);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000945 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400946 paint.setPathEffect(nullptr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000947 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000948
Hal Canaryd12a6762017-05-26 17:01:16 -0400949 if (this->handleInversePath(*pathPtr, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000950 return;
951 }
Hal Canaryd12a6762017-05-26 17:01:16 -0400952 if (matrix.getType() & SkMatrix::kPerspective_Mask) {
953 if (!pathIsMutable) {
954 modifiedPath = origPath;
955 pathPtr = &modifiedPath;
956 pathIsMutable = true;
957 }
958 pathPtr->transform(matrix);
959 if (paint.getShader()) {
960 transform_shader(&paint, matrix);
961 }
962 matrix = SkMatrix::I();
963 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000964
Mike Reeda1361362017-03-07 09:37:29 -0500965 ScopedContentEntry content(this, clipStack, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000966 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000967 return;
968 }
Hal Canary385468f2017-02-13 11:03:23 -0500969 SkScalar matrixScale = matrix.mapRadius(1.0f);
970 SkScalar tolerance = matrixScale > 0.0f ? 0.25f / matrixScale : 0.25f;
halcanary8b2bc252015-10-06 09:41:47 -0700971 bool consumeDegeratePathSegments =
972 paint.getStyle() == SkPaint::kFill_Style ||
973 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
974 paint.getStrokeCap() != SkPaint::kSquare_Cap);
Hal Canary51329c92017-06-27 14:28:37 -0400975 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(), consumeDegeratePathSegments, content.stream(),
Hal Canary385468f2017-02-13 11:03:23 -0500976 tolerance);
Hal Canary51329c92017-06-27 14:28:37 -0400977 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000978}
979
Hal Canaryf50ff392016-09-30 10:25:39 -0400980
Mike Reeda1361362017-03-07 09:37:29 -0500981void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400982 const SkRect* src,
983 const SkRect& dst,
984 const SkPaint& srcPaint,
985 SkCanvas::SrcRectConstraint) {
986 if (!image) {
987 return;
988 }
989 SkIRect bounds = image->bounds();
990 SkPaint paint = srcPaint;
991 if (image->isOpaque()) {
992 replace_srcmode_on_opaque_paint(&paint);
993 }
994 SkRect srcRect = src ? *src : SkRect::Make(bounds);
995 SkMatrix transform;
996 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
997 if (src) {
998 if (!srcRect.intersect(SkRect::Make(bounds))) {
999 return;
1000 }
1001 srcRect.roundOut(&bounds);
1002 transform.preTranslate(SkIntToScalar(bounds.x()),
1003 SkIntToScalar(bounds.y()));
1004 }
1005 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)), bounds);
1006 if (!imageSubset.isValid()) {
1007 return;
1008 }
Mike Reeda1361362017-03-07 09:37:29 -05001009 transform.postConcat(this->ctm());
1010 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
Hal Canaryf50ff392016-09-30 10:25:39 -04001011}
1012
Mike Reeda1361362017-03-07 09:37:29 -05001013void SkPDFDevice::drawBitmapRect(const SkBitmap& bitmap,
halcanary7a14b312015-10-01 07:28:13 -07001014 const SkRect* src,
1015 const SkRect& dst,
Mike Reeda1361362017-03-07 09:37:29 -05001016 const SkPaint& srcPaint,
1017 SkCanvas::SrcRectConstraint) {
Hal Canaryf50ff392016-09-30 10:25:39 -04001018 if (bitmap.drawsNothing()) {
1019 return;
1020 }
1021 SkIRect bounds = bitmap.bounds();
1022 SkPaint paint = srcPaint;
1023 if (bitmap.isOpaque()) {
1024 replace_srcmode_on_opaque_paint(&paint);
1025 }
1026 SkRect srcRect = src ? *src : SkRect::Make(bounds);
1027 SkMatrix transform;
1028 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
1029 if (src) {
1030 if (!srcRect.intersect(SkRect::Make(bounds))) {
1031 return;
1032 }
1033 srcRect.roundOut(&bounds);
1034 transform.preTranslate(SkIntToScalar(bounds.x()),
1035 SkIntToScalar(bounds.y()));
1036 }
1037 SkBitmap bitmapSubset;
1038 if (!bitmap.extractSubset(&bitmapSubset, bounds)) {
1039 return;
1040 }
1041 SkImageSubset imageSubset = make_image_subset(bitmapSubset);
1042 if (!imageSubset.isValid()) {
1043 return;
1044 }
Mike Reeda1361362017-03-07 09:37:29 -05001045 transform.postConcat(this->ctm());
1046 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -07001047}
1048
Mike Reeda1361362017-03-07 09:37:29 -05001049void SkPDFDevice::drawBitmap(const SkBitmap& bitmap,
Hal Canaryb9642382017-06-27 09:58:56 -04001050 SkScalar x,
1051 SkScalar y,
halcanary7a14b312015-10-01 07:28:13 -07001052 const SkPaint& srcPaint) {
Mike Reeda1361362017-03-07 09:37:29 -05001053 if (bitmap.drawsNothing() || this->cs().isEmpty(size(*this))) {
Hal Canaryf50ff392016-09-30 10:25:39 -04001054 return;
1055 }
halcanarya6814332015-05-27 08:53:36 -07001056 SkPaint paint = srcPaint;
1057 if (bitmap.isOpaque()) {
1058 replace_srcmode_on_opaque_paint(&paint);
1059 }
Hal Canaryf50ff392016-09-30 10:25:39 -04001060 SkImageSubset imageSubset = make_image_subset(bitmap);
1061 if (!imageSubset.isValid()) {
halcanary7a14b312015-10-01 07:28:13 -07001062 return;
1063 }
Hal Canaryb9642382017-06-27 09:58:56 -04001064 SkMatrix transform = SkMatrix::MakeTrans(x, y);
Mike Reeda1361362017-03-07 09:37:29 -05001065 transform.postConcat(this->ctm());
1066 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -07001067}
1068
Mike Reeda1361362017-03-07 09:37:29 -05001069void SkPDFDevice::drawSprite(const SkBitmap& bitmap,
halcanary7a14b312015-10-01 07:28:13 -07001070 int x,
1071 int y,
1072 const SkPaint& srcPaint) {
Mike Reeda1361362017-03-07 09:37:29 -05001073 if (bitmap.drawsNothing() || this->cs().isEmpty(size(*this))) {
Hal Canaryf50ff392016-09-30 10:25:39 -04001074 return;
1075 }
halcanary7a14b312015-10-01 07:28:13 -07001076 SkPaint paint = srcPaint;
1077 if (bitmap.isOpaque()) {
1078 replace_srcmode_on_opaque_paint(&paint);
1079 }
Hal Canaryf50ff392016-09-30 10:25:39 -04001080 SkImageSubset imageSubset = make_image_subset(bitmap);
1081 if (!imageSubset.isValid()) {
halcanary7a14b312015-10-01 07:28:13 -07001082 return;
1083 }
Hal Canaryf50ff392016-09-30 10:25:39 -04001084 SkMatrix transform = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
Mike Reeda1361362017-03-07 09:37:29 -05001085 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -07001086}
1087
Mike Reeda1361362017-03-07 09:37:29 -05001088void SkPDFDevice::drawImage(const SkImage* image,
halcanary7a14b312015-10-01 07:28:13 -07001089 SkScalar x,
1090 SkScalar y,
1091 const SkPaint& srcPaint) {
1092 SkPaint paint = srcPaint;
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001093 if (!image) {
halcanary7a14b312015-10-01 07:28:13 -07001094 return;
1095 }
1096 if (image->isOpaque()) {
1097 replace_srcmode_on_opaque_paint(&paint);
1098 }
Hal Canaryf50ff392016-09-30 10:25:39 -04001099 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)));
1100 if (!imageSubset.isValid()) {
1101 return;
1102 }
halcanary7a14b312015-10-01 07:28:13 -07001103 SkMatrix transform = SkMatrix::MakeTrans(x, y);
Mike Reeda1361362017-03-07 09:37:29 -05001104 transform.postConcat(this->ctm());
1105 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001106}
1107
halcanaryf0c30f52016-07-15 13:35:45 -07001108namespace {
1109class GlyphPositioner {
1110public:
1111 GlyphPositioner(SkDynamicMemoryWStream* content,
1112 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -07001113 bool wideChars,
1114 bool defaultPositioning,
1115 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -07001116 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -07001117 , fCurrentMatrixOrigin(origin)
1118 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -07001119 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -07001120 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -07001121 }
halcanary4871f222016-08-26 13:17:44 -07001122 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -07001123 void flush() {
1124 if (fInText) {
1125 fContent->writeText("> Tj\n");
1126 fInText = false;
1127 }
1128 }
halcanary4871f222016-08-26 13:17:44 -07001129 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -07001130 SkScalar advanceWidth,
1131 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -07001132 if (!fInitialized) {
1133 // Flip the text about the x-axis to account for origin swap and include
1134 // the passed parameters.
1135 fContent->writeText("1 0 ");
1136 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
1137 fContent->writeText(" -1 ");
1138 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
1139 fContent->writeText(" ");
1140 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
1141 fContent->writeText(" Tm\n");
1142 fCurrentMatrixOrigin.set(0.0f, 0.0f);
1143 fInitialized = true;
1144 }
halcanary4ed2f012016-08-15 18:40:07 -07001145 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -07001146 SkPoint position = xy - fCurrentMatrixOrigin;
Hal Canary197ca9b2017-05-15 10:29:44 -04001147 if (position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -07001148 this->flush();
halcanary4871f222016-08-26 13:17:44 -07001149 SkPDFUtils::AppendScalar(position.x(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001150 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -07001151 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -07001152 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -07001153 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -07001154 fXAdvance = 0;
1155 }
1156 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -07001157 }
1158 if (!fInText) {
1159 fContent->writeText("<");
1160 fInText = true;
1161 }
1162 if (fWideChars) {
1163 SkPDFUtils::WriteUInt16BE(fContent, glyph);
1164 } else {
1165 SkASSERT(0 == glyph >> 8);
1166 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1167 }
halcanaryf0c30f52016-07-15 13:35:45 -07001168 }
1169
1170private:
1171 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -07001172 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001173 SkScalar fXAdvance = 0.0f;
1174 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001175 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001176 bool fInText = false;
1177 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -07001178 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001179};
halcanaryf59d18a2016-09-16 14:44:57 -07001180
1181/** Given the m-to-n glyph-to-character mapping data (as returned by
1182 harfbuzz), iterate over the clusters. */
1183class Clusterator {
1184public:
1185 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1186 explicit Clusterator(uint32_t glyphCount)
1187 : fClusters(nullptr)
1188 , fUtf8Text(nullptr)
1189 , fGlyphCount(glyphCount)
1190 , fTextByteLength(0) {}
1191 // The clusters[] array is an array of offsets into utf8Text[],
1192 // one offset for each glyph. See SkTextBlobBuilder for more info.
1193 Clusterator(const uint32_t* clusters,
1194 const char* utf8Text,
1195 uint32_t glyphCount,
1196 uint32_t textByteLength)
1197 : fClusters(clusters)
1198 , fUtf8Text(utf8Text)
1199 , fGlyphCount(glyphCount)
1200 , fTextByteLength(textByteLength) {
1201 // This is a cheap heuristic for /ReversedChars which seems to
1202 // work for clusters produced by HarfBuzz, which either
1203 // increase from zero (LTR) or decrease to zero (RTL).
1204 // "ReversedChars" is how PDF deals with RTL text.
1205 fReversedChars =
1206 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1207 }
1208 struct Cluster {
1209 const char* fUtf8Text;
1210 uint32_t fTextByteLength;
1211 uint32_t fGlyphIndex;
1212 uint32_t fGlyphCount;
1213 explicit operator bool() const { return fGlyphCount != 0; }
1214 };
1215 // True if this looks like right-to-left text.
1216 bool reversedChars() const { return fReversedChars; }
1217 Cluster next() {
1218 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1219 // These glyphs have no text. Treat as one "cluster".
1220 uint32_t glyphCount = fGlyphCount;
1221 fGlyphCount = 0;
1222 return Cluster{nullptr, 0, 0, glyphCount};
1223 }
1224 if (fGlyphCount == 0 || fTextByteLength == 0) {
1225 return Cluster{nullptr, 0, 0, 0}; // empty
1226 }
1227 SkASSERT(fUtf8Text);
1228 SkASSERT(fClusters);
1229 uint32_t cluster = fClusters[0];
1230 if (cluster >= fTextByteLength) {
1231 return Cluster{nullptr, 0, 0, 0}; // bad input.
1232 }
1233 uint32_t glyphsInCluster = 1;
1234 while (glyphsInCluster < fGlyphCount &&
1235 fClusters[glyphsInCluster] == cluster) {
1236 ++glyphsInCluster;
1237 }
1238 SkASSERT(glyphsInCluster <= fGlyphCount);
1239 uint32_t textLength = 0;
1240 if (glyphsInCluster == fGlyphCount) {
1241 // consumes rest of glyphs and rest of text
1242 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1243 textLength = fTextByteLength - cluster;
1244 } else { // RTL text; last cluster.
1245 SkASSERT(fPreviousCluster < fTextByteLength);
1246 if (fPreviousCluster <= cluster) { // bad input.
1247 return Cluster{nullptr, 0, 0, 0};
1248 }
1249 textLength = fPreviousCluster - cluster;
1250 }
1251 fGlyphCount = 0;
1252 return Cluster{fUtf8Text + cluster,
1253 textLength,
1254 fGlyphIndex,
1255 glyphsInCluster};
1256 }
1257 SkASSERT(glyphsInCluster < fGlyphCount);
1258 uint32_t nextCluster = fClusters[glyphsInCluster];
1259 if (nextCluster >= fTextByteLength) {
1260 return Cluster{nullptr, 0, 0, 0}; // bad input.
1261 }
1262 if (nextCluster > cluster) { // LTR text
1263 if (kInvalidCluster != fPreviousCluster) {
1264 return Cluster{nullptr, 0, 0, 0}; // bad input.
1265 }
1266 textLength = nextCluster - cluster;
1267 } else { // RTL text
1268 SkASSERT(nextCluster < cluster);
1269 if (kInvalidCluster == fPreviousCluster) { // first cluster
1270 textLength = fTextByteLength - cluster;
1271 } else { // later cluster
1272 if (fPreviousCluster <= cluster) {
1273 return Cluster{nullptr, 0, 0, 0}; // bad input.
1274 }
1275 textLength = fPreviousCluster - cluster;
1276 }
1277 fPreviousCluster = cluster;
1278 }
1279 uint32_t glyphIndex = fGlyphIndex;
1280 fGlyphCount -= glyphsInCluster;
1281 fGlyphIndex += glyphsInCluster;
1282 fClusters += glyphsInCluster;
1283 return Cluster{fUtf8Text + cluster,
1284 textLength,
1285 glyphIndex,
1286 glyphsInCluster};
1287 }
1288
1289private:
1290 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1291 const uint32_t* fClusters;
1292 const char* fUtf8Text;
1293 uint32_t fGlyphCount;
1294 uint32_t fTextByteLength;
1295 uint32_t fGlyphIndex = 0;
1296 uint32_t fPreviousCluster = kInvalidCluster;
1297 bool fReversedChars = false;
1298};
1299
1300struct TextStorage {
1301 SkAutoTMalloc<char> fUtf8textStorage;
1302 SkAutoTMalloc<uint32_t> fClusterStorage;
1303 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1304};
halcanaryf0c30f52016-07-15 13:35:45 -07001305} // namespace
1306
halcanaryf59d18a2016-09-16 14:44:57 -07001307/** Given some unicode text (as passed to drawText(), convert to
1308 glyphs (via primitive shaping), while preserving
1309 glyph-to-character mapping information. */
1310static Clusterator make_clusterator(
1311 const void* sourceText,
1312 size_t sourceByteCount,
1313 const SkPaint& paint,
1314 TextStorage* storage,
1315 int glyphCount) {
1316 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1317 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1318 SkASSERT(glyphCount > 0);
1319 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1320 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1321 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1322 uint32_t* clusters = storage->fClusterStorage.get();
1323 uint32_t utf8ByteCount = 0;
1324 const char* utf8Text = nullptr;
1325 switch (paint.getTextEncoding()) {
1326 case SkPaint::kUTF8_TextEncoding: {
1327 const char* txtPtr = (const char*)sourceText;
1328 for (int i = 0; i < glyphCount; ++i) {
1329 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1330 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1331 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1332 }
1333 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1334 utf8ByteCount = SkToU32(sourceByteCount);
1335 utf8Text = (const char*)sourceText;
1336 break;
1337 }
1338 case SkPaint::kUTF16_TextEncoding: {
1339 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1340 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1341 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1342 storage->fUtf8textStorage.reset(utf8ByteCount);
1343 char* txtPtr = storage->fUtf8textStorage.get();
1344 utf8Text = txtPtr;
1345 int clusterIndex = 0;
1346 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1347 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1348 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1349 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1350 }
1351 SkASSERT(clusterIndex == glyphCount);
1352 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1353 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1354 break;
1355 }
1356 case SkPaint::kUTF32_TextEncoding: {
1357 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1358 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1359 SkASSERT(glyphCount == utf32count);
1360 for (int i = 0; i < utf32count; ++i) {
1361 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1362 }
1363 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1364 char* txtPtr = storage->fUtf8textStorage.get();
1365 utf8Text = txtPtr;
1366 for (int i = 0; i < utf32count; ++i) {
1367 clusters[i] = SkToU32(txtPtr - utf8Text);
1368 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1369 }
1370 break;
1371 }
1372 default:
1373 SkDEBUGFAIL("");
1374 break;
1375 }
1376 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1377}
1378
halcanaryf59d18a2016-09-16 14:44:57 -07001379static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1380 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1381}
1382
halcanaryc2f9ec12016-09-12 08:55:29 -07001383static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1384 wStream->writeText("/");
1385 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1386 wStream->write(&prefix, 1);
1387 wStream->writeDecAsText(fontIndex);
1388 wStream->writeText(" ");
1389 SkPDFUtils::AppendScalar(textSize, wStream);
1390 wStream->writeText(" Tf\n");
1391}
1392
Hal Canaryd12a6762017-05-26 17:01:16 -04001393static SkPath draw_text_as_path(const void* sourceText, size_t sourceByteCount,
1394 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
1395 SkPoint offset, const SkPaint& srcPaint) {
1396 SkPath path;
1397 int glyphCount;
1398 SkAutoTMalloc<SkPoint> tmpPoints;
1399 switch (positioning) {
1400 case SkTextBlob::kDefault_Positioning:
1401 srcPaint.getTextPath(sourceText, sourceByteCount, offset.x(), offset.y(), &path);
1402 break;
1403 case SkTextBlob::kHorizontal_Positioning:
1404 glyphCount = srcPaint.countText(sourceText, sourceByteCount);
1405 tmpPoints.realloc(glyphCount);
1406 for (int i = 0; i < glyphCount; ++i) {
1407 tmpPoints[i] = {pos[i] + offset.x(), offset.y()};
1408 }
1409 srcPaint.getPosTextPath(sourceText, sourceByteCount, tmpPoints.get(), &path);
1410 break;
1411 case SkTextBlob::kFull_Positioning:
1412 srcPaint.getPosTextPath(sourceText, sourceByteCount, (const SkPoint*)pos, &path);
1413 path.offset(offset.x(), offset.y());
1414 break;
1415 }
1416 return path;
1417}
1418
Hal Canary699b8732017-06-13 12:13:29 -04001419static SkRect get_glyph_bounds_device_space(SkGlyphID gid, SkGlyphCache* cache,
1420 SkScalar xScale, SkScalar yScale,
1421 SkPoint xy, const SkMatrix& ctm) {
1422 const SkGlyph& glyph = cache->getGlyphIDMetrics(gid);
1423 SkRect glyphBounds = {glyph.fLeft * xScale,
1424 glyph.fTop * yScale,
1425 (glyph.fLeft + glyph.fWidth) * xScale,
1426 (glyph.fTop + glyph.fHeight) * yScale};
1427 glyphBounds.offset(xy);
1428 ctm.mapRect(&glyphBounds); // now in dev space.
1429 return glyphBounds;
1430}
1431
1432static bool contains(const SkRect& r, SkPoint p) {
1433 return r.left() <= p.x() && p.x() <= r.right() &&
1434 r.top() <= p.y() && p.y() <= r.bottom();
1435}
1436
halcanary4ed2f012016-08-15 18:40:07 -07001437void SkPDFDevice::internalDrawText(
Mike Reeda1361362017-03-07 09:37:29 -05001438 const void* sourceText, size_t sourceByteCount,
halcanary4ed2f012016-08-15 18:40:07 -07001439 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001440 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1441 uint32_t textByteLength, const char* utf8Text) {
Hal Canaryd12a6762017-05-26 17:01:16 -04001442 if (0 == sourceByteCount || !sourceText) {
1443 return;
1444 }
1445 if (this->cs().isEmpty(size(*this))) {
halcanary4ed2f012016-08-15 18:40:07 -07001446 return;
1447 }
halcanaryea17dfe2016-08-24 09:20:57 -07001448 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1449 if (srcPaint.isVerticalText()) {
1450 // Don't pretend we support drawing vertical text. It is not
1451 // clear to me how to switch to "vertical writing" mode in PDF.
1452 // Currently neither Chromium or Android set this flag.
1453 // https://bug.skia.org/5665
halcanaryea17dfe2016-08-24 09:20:57 -07001454 }
Hal Canaryd12a6762017-05-26 17:01:16 -04001455 if (srcPaint.getPathEffect()
1456 || srcPaint.getMaskFilter()
1457 || SkPaint::kFill_Style != srcPaint.getStyle()) {
1458 // Stroked Text doesn't work well with Type3 fonts.
1459 SkPath path = draw_text_as_path(sourceText, sourceByteCount, pos,
1460 positioning, offset, srcPaint);
1461 this->drawPath(path, srcPaint, nullptr, true);
halcanaryf59d18a2016-09-16 14:44:57 -07001462 return;
halcanarye06ca962016-09-09 05:34:55 -07001463 }
halcanary4ed2f012016-08-15 18:40:07 -07001464 SkPaint paint = calculate_text_paint(srcPaint);
Hal Canaryd12a6762017-05-26 17:01:16 -04001465 remove_color_filter(&paint);
halcanary4ed2f012016-08-15 18:40:07 -07001466 replace_srcmode_on_opaque_paint(&paint);
1467 if (!paint.getTypeface()) {
1468 paint.setTypeface(SkTypeface::MakeDefault());
1469 }
1470 SkTypeface* typeface = paint.getTypeface();
1471 if (!typeface) {
1472 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1473 return;
1474 }
halcanary4871f222016-08-26 13:17:44 -07001475
1476 const SkAdvancedTypefaceMetrics* metrics =
1477 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1478 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001479 return;
1480 }
halcanary2bd295e2016-09-16 08:15:56 -07001481 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1482 if (glyphCount <= 0) {
1483 return;
1484 }
halcanary3b294d52016-09-16 13:21:08 -07001485
halcanaryf59d18a2016-09-16 14:44:57 -07001486 // These three heap buffers are only used in the case where no glyphs
1487 // are passed to drawText() (most clients pass glyphs or a textblob).
1488 TextStorage storage;
1489 const SkGlyphID* glyphs = nullptr;
1490 Clusterator clusterator;
1491 if (textByteLength > 0) {
1492 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1493 glyphs = (const SkGlyphID*)sourceText;
1494 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1495 SkASSERT(clusters);
1496 SkASSERT(utf8Text);
1497 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1498 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1499 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1500 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1501 glyphs = (const SkGlyphID*)sourceText;
1502 clusterator = Clusterator(SkToU32(glyphCount));
1503 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1504 SkASSERT(nullptr == clusters);
1505 SkASSERT(nullptr == utf8Text);
1506 } else {
1507 SkASSERT(nullptr == clusters);
1508 SkASSERT(nullptr == utf8Text);
1509 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1510 &storage, glyphCount);
1511 glyphs = storage.fGlyphStorage;
1512 }
halcanary4ed2f012016-08-15 18:40:07 -07001513 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001514 paint.setHinting(SkPaint::kNo_Hinting);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001515
1516 int emSize;
1517 SkAutoGlyphCache glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
1518
1519 SkScalar textSize = paint.getTextSize();
1520 SkScalar advanceScale = textSize * paint.getTextScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001521
Hal Canary699b8732017-06-13 12:13:29 -04001522 // textScaleX and textScaleY are used to get a conservative bounding box for glyphs.
1523 SkScalar textScaleY = textSize / emSize;
1524 SkScalar textScaleX = advanceScale + paint.getTextSkewX() * textScaleY;
1525
halcanary4ed2f012016-08-15 18:40:07 -07001526 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001527 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1528 SkPaint::kCenter_Align == alignment ? -0.5f :
1529 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001530 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001531 SkScalar advance = 0;
halcanary4ed2f012016-08-15 18:40:07 -07001532 for (int i = 0; i < glyphCount; ++i) {
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001533 advance += advanceScale * glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
halcanary4ed2f012016-08-15 18:40:07 -07001534 }
halcanary4871f222016-08-26 13:17:44 -07001535 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001536 }
Hal Canary699b8732017-06-13 12:13:29 -04001537 SkRect clipStackBounds = this->cs().bounds(size(*this));
Mike Reeda1361362017-03-07 09:37:29 -05001538 ScopedContentEntry content(this, paint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001539 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001540 return;
1541 }
Hal Canary51329c92017-06-27 14:28:37 -04001542 SkDynamicMemoryWStream* out = content.stream();
halcanaryf59d18a2016-09-16 14:44:57 -07001543 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
halcanary4871f222016-08-26 13:17:44 -07001544
halcanary4871f222016-08-26 13:17:44 -07001545 out->writeText("BT\n");
1546 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1547
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001548 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
1549
halcanaryc2f9ec12016-09-12 08:55:29 -07001550 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
halcanaryf59d18a2016-09-16 14:44:57 -07001551 if (clusterator.reversedChars()) {
1552 out->writeText("/ReversedChars BMC\n");
1553 }
1554 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
halcanary4ed2f012016-08-15 18:40:07 -07001555 GlyphPositioner glyphPositioner(out,
1556 paint.getTextSkewX(),
halcanaryc2f9ec12016-09-12 08:55:29 -07001557 multiByteGlyphs,
halcanary4ed2f012016-08-15 18:40:07 -07001558 defaultPositioning,
1559 offset);
halcanaryc2f9ec12016-09-12 08:55:29 -07001560 SkPDFFont* font = nullptr;
halcanaryf59d18a2016-09-16 14:44:57 -07001561
1562 while (Clusterator::Cluster c = clusterator.next()) {
1563 int index = c.fGlyphIndex;
1564 int glyphLimit = index + c.fGlyphCount;
1565
1566 bool actualText = false;
1567 SK_AT_SCOPE_EXIT(if (actualText) { glyphPositioner.flush(); out->writeText("EMC\n"); } );
1568 if (c.fUtf8Text) { // real cluster
1569 // Check if `/ActualText` needed.
1570 const char* textPtr = c.fUtf8Text;
halcanaryf59d18a2016-09-16 14:44:57 -07001571 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
Hal Canaryd1c8e562017-01-11 15:53:25 -05001572 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1573 if (unichar < 0) {
1574 return;
1575 }
halcanaryf59d18a2016-09-16 14:44:57 -07001576 if (textPtr < textEnd || // more characters left
1577 glyphLimit > index + 1 || // toUnicode wouldn't work
1578 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1579 {
1580 glyphPositioner.flush();
1581 out->writeText("/Span<</ActualText <");
1582 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1583 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1584 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1585 while (textPtr < textEnd) {
Hal Canaryd1c8e562017-01-11 15:53:25 -05001586 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1587 if (unichar < 0) {
1588 break;
1589 }
halcanaryf59d18a2016-09-16 14:44:57 -07001590 SkPDFUtils::WriteUTF16beHex(out, unichar);
1591 }
1592 out->writeText("> >> BDC\n"); // begin marked-content sequence
1593 // with an associated property list.
1594 actualText = true;
robertphillips5ba165e2016-08-15 15:36:58 -07001595 }
1596 }
halcanaryf59d18a2016-09-16 14:44:57 -07001597 for (; index < glyphLimit; ++index) {
1598 SkGlyphID gid = glyphs[index];
1599 if (gid > maxGlyphID) {
1600 continue;
1601 }
1602 if (!font || !font->hasGlyph(gid)) {
1603 // Not yet specified font or need to switch font.
1604 int fontIndex = this->getFontResourceIndex(typeface, gid);
1605 // All preconditions for SkPDFFont::GetFontResource are met.
1606 SkASSERT(fontIndex >= 0);
1607 if (fontIndex < 0) {
1608 return;
1609 }
1610 glyphPositioner.flush();
1611 update_font(out, fontIndex, textSize);
1612 font = fFontResources[fontIndex];
1613 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1614 if (!font) {
1615 return;
1616 }
1617 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1618 }
1619 SkPoint xy{0, 0};
1620 SkScalar advance{0};
1621 if (!defaultPositioning) {
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001622 advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
halcanaryf59d18a2016-09-16 14:44:57 -07001623 xy = SkTextBlob::kFull_Positioning == positioning
1624 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1625 : SkPoint{pos[index], 0};
1626 if (alignment != SkPaint::kLeft_Align) {
1627 xy.offset(alignmentFactor * advance, 0);
1628 }
Hal Canary699b8732017-06-13 12:13:29 -04001629 // Do a glyph-by-glyph bounds-reject if positions are absolute.
1630 SkRect glyphBounds = get_glyph_bounds_device_space(
1631 gid, glyphCache.get(), textScaleX, textScaleY, xy + offset, this->ctm());
1632 if (glyphBounds.isEmpty()) {
1633 if (!contains(clipStackBounds, {glyphBounds.x(), glyphBounds.y()})) {
1634 continue;
1635 }
1636 } else {
1637 if (!clipStackBounds.intersects(glyphBounds)) {
1638 continue; // reject glyphs as out of bounds
1639 }
1640 }
halcanaryf59d18a2016-09-16 14:44:57 -07001641 }
1642 font->noteGlyphUsage(gid);
1643 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1644 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
1645 }
robertphillips5ba165e2016-08-15 15:36:58 -07001646 }
halcanary4ed2f012016-08-15 18:40:07 -07001647}
1648
Mike Reeda1361362017-03-07 09:37:29 -05001649void SkPDFDevice::drawText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001650 SkScalar x, SkScalar y, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001651 this->internalDrawText(text, len, nullptr, SkTextBlob::kDefault_Positioning,
halcanarye06ca962016-09-09 05:34:55 -07001652 SkPoint{x, y}, paint, nullptr, 0, nullptr);
halcanary4ed2f012016-08-15 18:40:07 -07001653}
1654
Mike Reeda1361362017-03-07 09:37:29 -05001655void SkPDFDevice::drawPosText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001656 const SkScalar pos[], int scalarsPerPos,
1657 const SkPoint& offset, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001658 this->internalDrawText(text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001659 offset, paint, nullptr, 0, nullptr);
1660}
1661
Mike Reeda1361362017-03-07 09:37:29 -05001662void SkPDFDevice::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
halcanarye06ca962016-09-09 05:34:55 -07001663 const SkPaint &paint, SkDrawFilter* drawFilter) {
1664 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1665 SkPaint runPaint(paint);
1666 it.applyFontToPaint(&runPaint);
1667 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1668 continue;
1669 }
1670 runPaint.setFlags(this->filterTextFlags(runPaint));
1671 SkPoint offset = it.offset() + SkPoint{x, y};
Mike Reeda1361362017-03-07 09:37:29 -05001672 this->internalDrawText(it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
halcanarye06ca962016-09-09 05:34:55 -07001673 it.pos(), it.positioning(), offset, runPaint,
1674 it.clusters(), it.textSize(), it.text());
1675 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001676}
1677
Mike Reed2f6b5a42017-03-19 15:04:17 -04001678void SkPDFDevice::drawVertices(const SkVertices*, SkBlendMode, const SkPaint&) {
Mike Reeda1361362017-03-07 09:37:29 -05001679 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001680 return;
1681 }
reed@google.com85e143c2013-12-30 15:51:25 +00001682 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001683}
1684
Mike Reeda1361362017-03-07 09:37:29 -05001685void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001686 SkASSERT(!paint.getImageFilter());
1687
reed7503d602016-07-15 14:23:29 -07001688 // Check if the source device is really a bitmapdevice (because that's what we returned
1689 // from createDevice (likely due to an imagefilter)
1690 SkPixmap pmap;
1691 if (device->peekPixels(&pmap)) {
1692 SkBitmap bitmap;
1693 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001694 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001695 return;
1696 }
1697
fmalita6987dca2014-11-13 08:33:37 -08001698 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001699 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001700
1701 SkScalar scalarX = SkIntToScalar(x);
1702 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001703 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1704 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001705 fLinkToURLs.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001706 }
halcanary91fcb3e2016-03-04 13:53:22 -08001707 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1708 SkRect r = l.rect.makeOffset(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001709 fLinkToDestinations.emplace_back(RectWithData{r, l.data});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001710 }
halcanary91fcb3e2016-03-04 13:53:22 -08001711 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1712 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
Hal Canary5c1b3602017-04-17 16:30:06 -04001713 fNamedDestinations.emplace_back(NamedDestination{d.nameData, p});
wangxianzhuef6c50a2015-09-17 20:38:02 -07001714 }
1715
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001716 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001717 return;
1718 }
1719
Mike Reeda1361362017-03-07 09:37:29 -05001720 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
1721 ScopedContentEntry content(this, this->cs(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001722 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001723 return;
1724 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001725 if (content.needShape()) {
1726 SkPath shape;
1727 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001728 SkIntToScalar(device->width()),
1729 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001730 content.setShape(shape);
1731 }
1732 if (!content.needSource()) {
1733 return;
1734 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001735
halcanary4b1e17e2016-07-27 14:49:46 -07001736 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
Hal Canary51329c92017-06-27 14:28:37 -04001737 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001738}
1739
reede8f30622016-03-23 18:59:25 -07001740sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1741 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001742}
1743
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001744
halcanary8103a342016-03-08 15:10:16 -08001745sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001746 SkTDArray<SkPDFObject*> fonts;
1747 fonts.setReserve(fFontResources.count());
1748 for (SkPDFFont* font : fFontResources) {
1749 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001750 }
halcanary8103a342016-03-08 15:10:16 -08001751 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001752 &fGraphicStateResources,
1753 &fShaderResources,
1754 &fXObjectResources,
1755 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001756}
1757
halcanary8103a342016-03-08 15:10:16 -08001758sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001759 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001760 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001761 mediaBox->appendInt(0);
1762 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001763 mediaBox->appendInt(fPageSize.width());
1764 mediaBox->appendInt(fPageSize.height());
1765 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001766}
1767
mtklein5f939ab2016-03-16 10:28:35 -07001768std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001769 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001770 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001771 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001772 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001773
Hal Canary6d673962017-02-22 17:16:59 -05001774 GraphicStackState gsState(fExistingClipStack, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001775 for (const auto& entry : fContentEntries) {
Hal Canary6d673962017-02-22 17:16:59 -05001776 gsState.updateClip(entry.fState.fClipStack,
Mike Reeda1361362017-03-07 09:37:29 -05001777 {0, 0}, SkRect::Make(size(*this)));
halcanary2be7e012016-03-28 11:58:08 -07001778 gsState.updateMatrix(entry.fState.fMatrix);
1779 gsState.updateDrawingState(entry.fState);
1780
halcanaryafdc1772016-08-23 09:02:12 -07001781 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001782 }
1783 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001784 if (buffer.bytesWritten() > 0) {
1785 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1786 } else {
1787 return skstd::make_unique<SkMemoryStream>();
1788 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001789}
1790
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001791/* Draws an inverse filled path by using Path Ops to compute the positive
1792 * inverse using the current clip as the inverse bounds.
1793 * Return true if this was an inverse path and was properly handled,
1794 * otherwise returns false and the normal drawing routine should continue,
1795 * either as a (incorrect) fallback or because the path was not inverse
1796 * in the first place.
1797 */
Mike Reeda1361362017-03-07 09:37:29 -05001798bool SkPDFDevice::handleInversePath(const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001799 const SkPaint& paint, bool pathIsMutable,
1800 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001801 if (!origPath.isInverseFillType()) {
1802 return false;
1803 }
1804
Mike Reeda1361362017-03-07 09:37:29 -05001805 if (this->cs().isEmpty(size(*this))) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001806 return false;
1807 }
1808
1809 SkPath modifiedPath;
1810 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1811 SkPaint noInversePaint(paint);
1812
1813 // Merge stroking operations into final path.
1814 if (SkPaint::kStroke_Style == paint.getStyle() ||
1815 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1816 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1817 if (doFillPath) {
1818 noInversePaint.setStyle(SkPaint::kFill_Style);
1819 noInversePaint.setStrokeWidth(0);
1820 pathPtr = &modifiedPath;
1821 } else {
1822 // To be consistent with the raster output, hairline strokes
1823 // are rendered as non-inverted.
1824 modifiedPath.toggleInverseFillType();
Mike Reeda1361362017-03-07 09:37:29 -05001825 this->drawPath(modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001826 return true;
1827 }
1828 }
1829
1830 // Get bounds of clip in current transform space
1831 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001832 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001833 SkMatrix totalMatrix = this->ctm();
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001834 if (prePathMatrix) {
1835 totalMatrix.preConcat(*prePathMatrix);
1836 }
1837 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001838 return false;
1839 }
Mike Reeda1361362017-03-07 09:37:29 -05001840 SkRect bounds = this->cs().bounds(size(*this));
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001841 transformInverse.mapRect(&bounds);
1842
1843 // Extend the bounds by the line width (plus some padding)
1844 // so the edge doesn't cause a visible stroke.
1845 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1846 paint.getStrokeWidth() + SK_Scalar1);
1847
1848 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1849 return false;
1850 }
1851
Mike Reeda1361362017-03-07 09:37:29 -05001852 this->drawPath(modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001853 return true;
1854}
1855
wangxianzhuef6c50a2015-09-17 20:38:02 -07001856void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1857 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001858 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001859 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001860 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001861 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001862 }
halcanary91fcb3e2016-03-04 13:53:22 -08001863 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001864 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001865 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001866 array->appendObject(
1867 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001868 }
1869}
epoger@google.comb58772f2013-03-08 09:09:10 +00001870
halcanary6d622702015-03-25 08:45:42 -07001871void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001872 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001873 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001874 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001875 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001876 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001877 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001878 pdfDest->appendScalar(p.x());
1879 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001880 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001881 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001882 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001883 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001884}
1885
halcanary4b1e17e2016-07-27 14:49:46 -07001886sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
halcanary5abbb442016-07-29 08:41:33 -07001887 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001888 if (!fInitialTransform.isIdentity()) {
1889 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001890 SkDEBUGFAIL("Layer initial transform should be invertible.");
1891 inverseTransform.reset();
1892 }
1893 }
halcanary4b1e17e2016-07-27 14:49:46 -07001894 sk_sp<SkPDFObject> xobject =
1895 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
halcanary5abbb442016-07-29 08:41:33 -07001896 this->makeResourceDict(), inverseTransform, nullptr);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001897 // We always draw the form xobjects that we create back into the device, so
1898 // we simply preserve the font usage instead of pulling it out and merging
1899 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001900 this->cleanUp(); // Reset this device to have no content.
1901 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001902 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001903}
1904
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001905void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001906 sk_sp<SkPDFObject> mask,
Mike Reeda1361362017-03-07 09:37:29 -05001907 const SkClipStack& clipStack,
reed374772b2016-10-05 17:33:02 -07001908 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001909 bool invertClip) {
Mike Reeda1361362017-03-07 09:37:29 -05001910 if (!invertClip && clipStack.isEmpty(size(*this))) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001911 return;
1912 }
1913
halcanary4b1e17e2016-07-27 14:49:46 -07001914 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001915 std::move(mask), invertClip,
1916 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001917
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001918 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001919 paint.setBlendMode(mode);
Mike Reeda1361362017-03-07 09:37:29 -05001920 ScopedContentEntry content(this, clipStack, SkMatrix::I(), paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001921 if (!content.entry()) {
1922 return;
1923 }
Hal Canary51329c92017-06-27 14:28:37 -04001924 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()), content.stream());
1925 SkPDFUtils::DrawFormXObject(xObjectIndex, content.stream());
Hal Canaryc02de0b2017-06-28 13:14:03 -04001926 this->clearMaskOnGraphicState(content.stream());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001927}
1928
Mike Reeda1361362017-03-07 09:37:29 -05001929SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack& clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001930 const SkMatrix& matrix,
1931 const SkPaint& paint,
1932 bool hasText,
1933 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001934 *dst = nullptr;
reed374772b2016-10-05 17:33:02 -07001935 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001936
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001937 // For the following modes, we want to handle source and destination
1938 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001939 if (blendMode == SkBlendMode::kClear ||
1940 blendMode == SkBlendMode::kSrc ||
1941 blendMode == SkBlendMode::kSrcIn ||
1942 blendMode == SkBlendMode::kDstIn ||
1943 blendMode == SkBlendMode::kSrcOut ||
1944 blendMode == SkBlendMode::kDstOut ||
1945 blendMode == SkBlendMode::kSrcATop ||
1946 blendMode == SkBlendMode::kDstATop ||
1947 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001948 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001949 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001950 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001951 } else if (blendMode != SkBlendMode::kSrc &&
1952 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001953 // Except for Src and SrcOut, if there isn't anything already there,
1954 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001955 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001956 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001957 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001958 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001959 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001960
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001961 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001962 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001963 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001964 }
1965
halcanary2be7e012016-03-28 11:58:08 -07001966 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001967 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001968 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001969 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001970 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001971 } else {
halcanary2be7e012016-03-28 11:58:08 -07001972 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001973 }
Mike Reeda1361362017-03-07 09:37:29 -05001974 populateGraphicStateEntryFromPaint(matrix, clipStack, paint, hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001975 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001976}
1977
reed374772b2016-10-05 17:33:02 -07001978void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001979 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001980 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001981 if (blendMode != SkBlendMode::kClear &&
1982 blendMode != SkBlendMode::kSrc &&
1983 blendMode != SkBlendMode::kDstOver &&
1984 blendMode != SkBlendMode::kSrcIn &&
1985 blendMode != SkBlendMode::kDstIn &&
1986 blendMode != SkBlendMode::kSrcOut &&
1987 blendMode != SkBlendMode::kDstOut &&
1988 blendMode != SkBlendMode::kSrcATop &&
1989 blendMode != SkBlendMode::kDstATop &&
1990 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001991 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001992 return;
1993 }
reed374772b2016-10-05 17:33:02 -07001994 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001995 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00001996 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001997 // For DstOver, an empty content entry was inserted before the rest
1998 // of the content entries. If nothing was drawn, it needs to be
1999 // removed.
halcanary2be7e012016-03-28 11:58:08 -07002000 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002001 }
2002 return;
2003 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002004 if (!dst) {
reed374772b2016-10-05 17:33:02 -07002005 SkASSERT(blendMode == SkBlendMode::kSrc ||
2006 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002007 return;
2008 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002009
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002010 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07002011 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002012 // Changing the current content into a form-xobject will destroy the clip
2013 // objects which is fine since the xobject will already be clipped. However
2014 // if source has shape, we need to clip it too, so a copy of the clip is
2015 // saved.
halcanary2be7e012016-03-28 11:58:08 -07002016
2017 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002018
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002019 SkPaint stockPaint;
2020
halcanary4b1e17e2016-07-27 14:49:46 -07002021 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002022 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002023 // If nothing was drawn and there's no shape, then the draw was a
2024 // no-op, but dst needs to be restored for that to be true.
2025 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
2026 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
2027 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07002028 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
2029 blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002030 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07002031 // TODO: addXObjectResource take sk_sp
Hal Canary51329c92017-06-27 14:28:37 -04002032 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002033 return;
2034 } else {
reed374772b2016-10-05 17:33:02 -07002035 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002036 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002037 } else {
halcanary2be7e012016-03-28 11:58:08 -07002038 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07002039 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002040 }
2041
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002042 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
2043 // without alpha.
reed374772b2016-10-05 17:33:02 -07002044 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002045 // TODO(vandebo): In order to properly support SrcATop we have to track
2046 // the shape of what's been drawn at all times. It's the intersection of
2047 // the non-transparent parts of the device and the outlines (shape) of
2048 // all images and devices drawn.
2049 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
Mike Reeda1361362017-03-07 09:37:29 -05002050 fExistingClipStack, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002051 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07002052 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002053 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002054 SkPaint filledPaint;
2055 filledPaint.setColor(SK_ColorBLACK);
2056 filledPaint.setStyle(SkPaint::kFill_Style);
Mike Reeda1361362017-03-07 09:37:29 -05002057 this->internalDrawPath(clipStack, SkMatrix::I(), *shape, filledPaint, nullptr, true);
2058 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
2059 this->makeFormXObjectFromDevice(),
2060 fExistingClipStack,
2061 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07002062 } else {
Mike Reeda1361362017-03-07 09:37:29 -05002063 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
2064 srcFormXObject,
2065 fExistingClipStack,
2066 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002067 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002068 }
2069
reed374772b2016-10-05 17:33:02 -07002070 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002071 return;
reed374772b2016-10-05 17:33:02 -07002072 } else if (blendMode == SkBlendMode::kSrc ||
2073 blendMode == SkBlendMode::kDstATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002074 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002075 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04002076 SkPDFUtils::DrawFormXObject(this->addXObjectResource(srcFormXObject.get()),
2077 content.stream());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002078 }
reed374772b2016-10-05 17:33:02 -07002079 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002080 return;
2081 }
reed374772b2016-10-05 17:33:02 -07002082 } else if (blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05002083 ScopedContentEntry content(this, fExistingClipStack,
2084 SkMatrix::I(), stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002085 if (content.entry()) {
Hal Canary51329c92017-06-27 14:28:37 -04002086 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()), content.stream());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002087 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002088 }
2089
reed374772b2016-10-05 17:33:02 -07002090 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
2091 blendMode == SkBlendMode::kDstIn ||
2092 blendMode == SkBlendMode::kSrcOut ||
2093 blendMode == SkBlendMode::kDstOut ||
2094 blendMode == SkBlendMode::kSrcATop ||
2095 blendMode == SkBlendMode::kDstATop ||
2096 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002097
reed374772b2016-10-05 17:33:02 -07002098 if (blendMode == SkBlendMode::kSrcIn ||
2099 blendMode == SkBlendMode::kSrcOut ||
2100 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07002101 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
2102 std::move(dst),
Mike Reeda1361362017-03-07 09:37:29 -05002103 fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07002104 SkBlendMode::kSrcOver,
2105 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07002106 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002107 } else {
reed374772b2016-10-05 17:33:02 -07002108 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07002109 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07002110 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002111 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
Mike Reeda1361362017-03-07 09:37:29 -05002112 std::move(dst), fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07002113 SkBlendMode::kSrcOver, false);
2114 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002115 }
halcanarydabd4f02016-08-03 11:16:56 -07002116 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
Mike Reeda1361362017-03-07 09:37:29 -05002117 fExistingClipStack, mode,
reed374772b2016-10-05 17:33:02 -07002118 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07002119 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002120 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002121}
2122
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002123bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00002124 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07002125 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002126 return true;
2127 }
2128 return false;
2129}
2130
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002131void SkPDFDevice::populateGraphicStateEntryFromPaint(
2132 const SkMatrix& matrix,
2133 const SkClipStack& clipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002134 const SkPaint& paint,
2135 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07002136 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07002137 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
2138 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
2139 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002140
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002141 entry->fMatrix = matrix;
2142 entry->fClipStack = clipStack;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002143 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2144 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002145
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002146 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08002147 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07002148 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002149 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002150 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05002151 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
2152 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002153 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05002154 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002155 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07002156 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002157 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05002158 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
2159 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2160 color = gradientColor;
2161 } else {
2162 // PDF positions patterns relative to the initial transform, so
2163 // we need to apply the current transform to the shader parameters.
2164 SkMatrix transform = matrix;
2165 transform.postConcat(fInitialTransform);
2166
2167 // PDF doesn't support kClamp_TileMode, so we simulate it by making
2168 // a pattern the size of the current clip.
Mike Reeda1361362017-03-07 09:37:29 -05002169 SkRect clipStackBounds = clipStack.bounds(size(*this));
Hal Canaryc8f91802017-02-12 20:29:12 -05002170
2171 // We need to apply the initial transform to bounds in order to get
2172 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05002173 fInitialTransform.mapRect(&clipStackBounds);
2174 SkIRect bounds;
2175 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05002176
Hal Canarya0622582017-06-29 18:51:35 -04002177 pdfShader = SkPDFShader::GetPDFShader(fDocument, shader, transform, bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05002178
2179 if (pdfShader.get()) {
2180 // pdfShader has been canonicalized so we can directly compare
2181 // pointers.
2182 int resourceIndex = fShaderResources.find(pdfShader.get());
2183 if (resourceIndex < 0) {
2184 resourceIndex = fShaderResources.count();
2185 fShaderResources.push(pdfShader.get());
2186 pdfShader.get()->ref();
2187 }
2188 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002189 }
2190 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002191 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002192
Hal Canary80fa7ce2017-06-28 16:04:20 -04002193 sk_sp<SkPDFDict> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002194 if (color == paint.getColor()) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002195 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002196 } else {
2197 SkPaint newPaint = paint;
2198 newPaint.setColor(color);
Hal Canary5c1b3602017-04-17 16:30:06 -04002199 newGraphicState = SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002200 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002201 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002202 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002203
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002204 if (hasText) {
2205 entry->fTextScaleX = paint.getTextScaleX();
2206 entry->fTextFill = paint.getStyle();
2207 } else {
2208 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002209 }
2210}
2211
halcanarybe27a112015-04-01 13:31:19 -07002212int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002213 // Assumes that gs has been canonicalized (so we can directly compare
2214 // pointers).
2215 int result = fGraphicStateResources.find(gs);
2216 if (result < 0) {
2217 result = fGraphicStateResources.count();
2218 fGraphicStateResources.push(gs);
2219 gs->ref();
2220 }
2221 return result;
2222}
2223
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002224int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002225 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002226 // Assumes that xobject has been canonicalized (so we can directly compare
2227 // pointers).
2228 int result = fXObjectResources.find(xObject);
2229 if (result < 0) {
2230 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002231 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002232 }
2233 return result;
2234}
2235
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002236int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
Hal Canary5c1b3602017-04-17 16:30:06 -04002237 sk_sp<SkPDFFont> newFont = SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID);
halcanary7e8d5d32016-08-12 07:59:38 -07002238 if (!newFont) {
2239 return -1;
2240 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002241 int resourceIndex = fFontResources.find(newFont.get());
2242 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002243 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002244 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002245 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002246 }
2247 return resourceIndex;
2248}
2249
Hal Canaryfafe1352017-04-11 12:12:02 -04002250static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07002251
Hal Canaryf50ff392016-09-30 10:25:39 -04002252static sk_sp<SkImage> color_filter(const SkImageSubset& imageSubset,
halcanarya50151d2016-03-25 11:57:49 -07002253 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002254 auto surface =
Hal Canaryf50ff392016-09-30 10:25:39 -04002255 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07002256 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002257 SkCanvas* canvas = surface->getCanvas();
2258 canvas->clear(SK_ColorTRANSPARENT);
2259 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002260 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canaryf50ff392016-09-30 10:25:39 -04002261 imageSubset.draw(canvas, &paint);
halcanary7a14b312015-10-01 07:28:13 -07002262 canvas->flush();
halcanarya50151d2016-03-25 11:57:49 -07002263 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002264}
2265
2266////////////////////////////////////////////////////////////////////////////////
2267void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
Mike Reeda1361362017-03-07 09:37:29 -05002268 const SkClipStack& clipStack,
Hal Canaryf50ff392016-09-30 10:25:39 -04002269 SkImageSubset imageSubset,
halcanary7a14b312015-10-01 07:28:13 -07002270 const SkPaint& paint) {
Hal Canaryf50ff392016-09-30 10:25:39 -04002271 if (imageSubset.dimensions().isZero()) {
halcanarya50151d2016-03-25 11:57:49 -07002272 return;
2273 }
halcanary7a14b312015-10-01 07:28:13 -07002274 #ifdef SK_PDF_IMAGE_STATS
2275 gDrawImageCalls.fetch_add(1);
2276 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002277 SkMatrix matrix = origMatrix;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002278
2279 // Rasterize the bitmap using perspective in a new bitmap.
2280 if (origMatrix.hasPerspective()) {
Hal Canarya0622582017-06-29 18:51:35 -04002281 SkASSERT(fDocument->rasterDpi() > 0);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002282 // Transform the bitmap in the new space, without taking into
2283 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002284 SkPath perspectiveOutline;
Hal Canaryf50ff392016-09-30 10:25:39 -04002285 SkRect imageBounds = SkRect::Make(imageSubset.bounds());
halcanary7a14b312015-10-01 07:28:13 -07002286 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002287 perspectiveOutline.transform(origMatrix);
2288
2289 // TODO(edisonn): perf - use current clip too.
2290 // Retrieve the bounds of the new shape.
2291 SkRect bounds = perspectiveOutline.getBounds();
2292
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002293 // Transform the bitmap in the new space, taking into
2294 // account the initial transform.
2295 SkMatrix total = origMatrix;
2296 total.postConcat(fInitialTransform);
Hal Canarya0622582017-06-29 18:51:35 -04002297 SkScalar dpiScale = SkIntToScalar(fDocument->rasterDpi()) /
2298 SkIntToScalar(SkPDFUtils::kDpiForRasterScaleOne);
halcanary7a14b312015-10-01 07:28:13 -07002299 total.postScale(dpiScale, dpiScale);
2300
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002301 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002302 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002303 physicalPerspectiveOutline.transform(total);
2304
halcanary7a14b312015-10-01 07:28:13 -07002305 SkRect physicalPerspectiveBounds =
2306 physicalPerspectiveOutline.getBounds();
2307 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2308 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002309
2310 // TODO(edisonn): A better approach would be to use a bitmap shader
2311 // (in clamp mode) and draw a rect over the entire bounding box. Then
2312 // intersect perspectiveOutline to the clip. That will avoid introducing
2313 // alpha to the image while still giving good behavior at the edge of
2314 // the image. Avoiding alpha will reduce the pdf size and generation
2315 // CPU time some.
2316
halcanary7a14b312015-10-01 07:28:13 -07002317 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2318
Hal Canaryf50ff392016-09-30 10:25:39 -04002319 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002320 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002321 return;
2322 }
halcanary7a14b312015-10-01 07:28:13 -07002323 SkCanvas* canvas = surface->getCanvas();
2324 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002325
2326 SkScalar deltaX = bounds.left();
2327 SkScalar deltaY = bounds.top();
2328
2329 SkMatrix offsetMatrix = origMatrix;
2330 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002331 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002332
2333 // Translate the draw in the new canvas, so we perfectly fit the
2334 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002335 canvas->setMatrix(offsetMatrix);
Hal Canaryf50ff392016-09-30 10:25:39 -04002336 imageSubset.draw(canvas, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002337 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002338 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002339
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002340 // In the new space, we use the identity matrix translated
2341 // and scaled to reflect DPI.
2342 matrix.setScale(1 / scaleX, 1 / scaleY);
2343 matrix.postTranslate(deltaX, deltaY);
2344
Hal Canaryf50ff392016-09-30 10:25:39 -04002345 imageSubset = SkImageSubset(surface->makeImageSnapshot());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002346 }
2347
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002348 SkMatrix scaled;
2349 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002350 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2351 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002352 // Scale the image up from 1x1 to WxH.
Hal Canaryf50ff392016-09-30 10:25:39 -04002353 SkIRect subset = imageSubset.bounds();
2354 scaled.postScale(SkIntToScalar(imageSubset.dimensions().width()),
2355 SkIntToScalar(imageSubset.dimensions().height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002356 scaled.postConcat(matrix);
Hal Canary6d673962017-02-22 17:16:59 -05002357 ScopedContentEntry content(this, clipStack, scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002358 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002359 return;
2360 }
2361 if (content.needShape()) {
2362 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002363 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002364 shape.transform(matrix);
2365 content.setShape(shape);
2366 }
2367 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002368 return;
2369 }
2370
halcanary287d22d2015-09-24 10:20:05 -07002371 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002372 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002373 // draw calls. This code here works for all
2374 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2375 // rasterize a layer on this backend). Fortuanely, this seems
2376 // to be how Chromium impements most color-filters.
Hal Canaryf50ff392016-09-30 10:25:39 -04002377 sk_sp<SkImage> img = color_filter(imageSubset, colorFilter);
2378 imageSubset = SkImageSubset(std::move(img));
halcanary7a14b312015-10-01 07:28:13 -07002379 // TODO(halcanary): de-dupe this by caching filtered images.
2380 // (maybe in the resource cache?)
2381 }
halcanarya50151d2016-03-25 11:57:49 -07002382
Hal Canaryf50ff392016-09-30 10:25:39 -04002383 SkBitmapKey key = imageSubset.getKey();
Hal Canary5c1b3602017-04-17 16:30:06 -04002384 sk_sp<SkPDFObject>* pdfimagePtr = fDocument->canon()->fPDFBitmapMap.find(key);
2385 sk_sp<SkPDFObject> pdfimage = pdfimagePtr ? *pdfimagePtr : nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002386 if (!pdfimage) {
Hal Canaryf50ff392016-09-30 10:25:39 -04002387 sk_sp<SkImage> img = imageSubset.makeImage();
halcanarya50151d2016-03-25 11:57:49 -07002388 if (!img) {
2389 return;
2390 }
Hal Canary5c1b3602017-04-17 16:30:06 -04002391 pdfimage =
2392 SkPDFCreateBitmapObject(std::move(img), fDocument->canon()->fPixelSerializer.get());
halcanary7a14b312015-10-01 07:28:13 -07002393 if (!pdfimage) {
2394 return;
halcanary287d22d2015-09-24 10:20:05 -07002395 }
halcanarya50151d2016-03-25 11:57:49 -07002396 fDocument->serialize(pdfimage); // serialize images early.
Hal Canary5c1b3602017-04-17 16:30:06 -04002397 fDocument->canon()->fPDFBitmapMap.set(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002398 }
halcanarya50151d2016-03-25 11:57:49 -07002399 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
Hal Canary51329c92017-06-27 14:28:37 -04002400 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()), content.stream());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002401}
reede51c3562016-07-19 14:33:20 -07002402
2403///////////////////////////////////////////////////////////////////////////////////////////////////
2404
2405#include "SkSpecialImage.h"
2406#include "SkImageFilter.h"
2407
Florin Malita53f77bd2017-04-28 13:48:37 -04002408void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2409 SkImage* clipImage, const SkMatrix& clipMatrix) {
reede51c3562016-07-19 14:33:20 -07002410 SkASSERT(!srcImg->isTextureBacked());
2411
Florin Malita53f77bd2017-04-28 13:48:37 -04002412 //TODO: clipImage support
2413
reede51c3562016-07-19 14:33:20 -07002414 SkBitmap resultBM;
2415
2416 SkImageFilter* filter = paint.getImageFilter();
2417 if (filter) {
2418 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002419 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002420 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002421 const SkIRect clipBounds =
Mike Reeda1361362017-03-07 09:37:29 -05002422 this->cs().bounds(this->imageInfo().bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002423 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
brianosman2a75e5d2016-09-22 07:15:37 -07002424 // TODO: Should PDF be operating in a specified color space? For now, run the filter
2425 // in the same color space as the source (this is different from all other backends).
2426 SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2427 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002428
2429 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2430 if (resultImg) {
2431 SkPaint tmpUnfiltered(paint);
2432 tmpUnfiltered.setImageFilter(nullptr);
2433 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002434 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002435 }
2436 }
2437 } else {
2438 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002439 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002440 }
2441 }
2442}
2443
2444sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2445 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2446}
2447
2448sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002449 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2450 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2451 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002452 SkColorSpace* legacyColorSpace = nullptr;
reede51c3562016-07-19 14:33:20 -07002453 return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
Brian Osman61624f02016-12-09 14:51:59 -05002454 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002455}
2456
2457sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002458 return nullptr;
2459}
brianosman04a44d02016-09-21 09:46:57 -07002460
2461SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2462 // We always return a transient cache, so it is freed after each
2463 // filter traversal.
2464 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2465}