blob: aa8f7ae23f4f11c18d1786e668d000f261687989 [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"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000014#include "SkColor.h"
halcanary287d22d2015-09-24 10:20:05 -070015#include "SkColorFilter.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000016#include "SkDraw.h"
halcanarye06ca962016-09-09 05:34:55 -070017#include "SkDrawFilter.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000018#include "SkGlyphCache.h"
brianosman04a44d02016-09-21 09:46:57 -070019#include "SkImageFilterCache.h"
halcanary022c2bd2016-09-02 11:29:46 -070020#include "SkMakeUnique.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000021#include "SkPath.h"
reeda4393342016-03-18 11:22:57 -070022#include "SkPathEffect.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000023#include "SkPathOps.h"
halcanarydb0dcc72015-03-20 12:31:52 -070024#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070025#include "SkPDFCanon.h"
halcanary989da4a2016-03-21 14:33:17 -070026#include "SkPDFDocument.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000027#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000028#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000029#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000030#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000031#include "SkPDFShader.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000032#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000033#include "SkPDFUtils.h"
Hal Canaryf50ff392016-09-30 10:25:39 -040034#include "SkPixelRef.h"
wangxianzhuef6c50a2015-09-17 20:38:02 -070035#include "SkRasterClip.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000036#include "SkRRect.h"
halcanary4871f222016-08-26 13:17:44 -070037#include "SkScopeExit.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000038#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070039#include "SkSurface.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000040#include "SkTemplates.h"
halcanarye06ca962016-09-09 05:34:55 -070041#include "SkTextBlobRunIterator.h"
42#include "SkTextFormatParams.h"
halcanaryf59d18a2016-09-16 14:44:57 -070043#include "SkUtils.h"
halcanarya6814332015-05-27 08:53:36 -070044#include "SkXfermodeInterpretation.h"
Mike Reedebfce6d2016-12-12 10:02:12 -050045#include "SkClipOpPriv.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000046
edisonn@google.com73a7ea32013-11-11 20:55:15 +000047#define DPI_FOR_RASTER_SCALE_ONE 72
48
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000049// Utility functions
50
Mike Reeda1361362017-03-07 09:37:29 -050051static void draw_points(SkCanvas::PointMode mode,
52 size_t count,
53 const SkPoint* points,
54 const SkPaint& paint,
55 const SkIRect& bounds,
56 const SkMatrix& ctm,
57 SkBaseDevice* device) {
58 SkRasterClip rc(bounds);
59 SkDraw draw;
60 draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(bounds.right(), bounds.bottom()), nullptr, 0);
61 draw.fMatrix = &ctm;
62 draw.fRC = &rc;
63 draw.drawPoints(mode, count, points, paint, device);
64}
65
66static SkIRect size(const SkBaseDevice& dev) { return {0, 0, dev.width(), dev.height()}; }
67
reed374772b2016-10-05 17:33:02 -070068// If the paint will definitely draw opaquely, replace kSrc with
69// kSrcOver. http://crbug.com/473572
halcanarya6814332015-05-27 08:53:36 -070070static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
reed374772b2016-10-05 17:33:02 -070071 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
72 paint->setBlendMode(SkBlendMode::kSrcOver);
halcanarya6814332015-05-27 08:53:36 -070073 }
74}
75
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000076static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000077 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -070078 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000079 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -070080 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000081 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -070082 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000083 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000084}
85
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000086static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000087 SkPaint result = paint;
88 if (result.isFakeBoldText()) {
89 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
90 kStdFakeBoldInterpKeys,
91 kStdFakeBoldInterpValues,
92 kStdFakeBoldInterpLength);
Mike Reed8be952a2017-02-13 20:44:33 -050093 SkScalar width = result.getTextSize() * fakeBoldScale;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000094 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000095 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000096 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000097 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000098 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000099 result.setStrokeWidth(width);
100 }
101 return result;
102}
103
Hal Canaryf50ff392016-09-30 10:25:39 -0400104static SkImageSubset make_image_subset(const SkBitmap& bitmap) {
105 SkASSERT(!bitmap.drawsNothing());
106 SkIRect subset = bitmap.getSubset();
Hal Canaryf50ff392016-09-30 10:25:39 -0400107 SkASSERT(bitmap.pixelRef());
108 SkBitmap tmp;
Matt Saretta6e976a2017-04-28 15:43:35 -0400109 SkImageInfo pixelRefInfo =
110 bitmap.info().makeWH(bitmap.pixelRef()->width(), bitmap.pixelRef()->height());
111 tmp.setInfo(pixelRefInfo, bitmap.rowBytes());
Hal Canary1b3387b2016-12-12 13:48:12 -0500112 tmp.setPixelRef(sk_ref_sp(bitmap.pixelRef()), 0, 0);
Hal Canaryf50ff392016-09-30 10:25:39 -0400113 auto img = SkImage::MakeFromBitmap(tmp);
114 if (img) {
115 SkASSERT(!bitmap.isImmutable() || img->uniqueID() == bitmap.getGenerationID());
116 SkASSERT(img->bounds().contains(subset));
117 }
118 SkImageSubset imageSubset(std::move(img), subset);
119 // SkImage::MakeFromBitmap only preserves genID for immutable
120 // bitmaps. Use the bitmap's original ID for de-duping.
121 imageSubset.setID(bitmap.getGenerationID());
122 return imageSubset;
123}
124
halcanary2be7e012016-03-28 11:58:08 -0700125SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
126 : fColor(SK_ColorBLACK)
127 , fTextScaleX(SK_Scalar1)
128 , fTextFill(SkPaint::kFill_Style)
129 , fShaderIndex(-1)
halcanaryc2f9ec12016-09-12 08:55:29 -0700130 , fGraphicStateIndex(-1) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000131 fMatrix.reset();
132}
133
halcanary2be7e012016-03-28 11:58:08 -0700134bool SkPDFDevice::GraphicStateEntry::compareInitialState(
135 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000136 return fColor == cur.fColor &&
137 fShaderIndex == cur.fShaderIndex &&
138 fGraphicStateIndex == cur.fGraphicStateIndex &&
139 fMatrix == cur.fMatrix &&
140 fClipStack == cur.fClipStack &&
141 (fTextScaleX == 0 ||
142 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000143}
144
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000145class GraphicStackState {
146public:
147 GraphicStackState(const SkClipStack& existingClipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000148 SkWStream* contentStream)
149 : fStackDepth(0),
150 fContentStream(contentStream) {
151 fEntries[0].fClipStack = existingClipStack;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000152 }
153
Hal Canary6d673962017-02-22 17:16:59 -0500154 void updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500155 const SkPoint& translation, const SkRect& bounds);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000156 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700157 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000158
159 void drainStack();
160
161private:
162 void push();
163 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700164 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000165
166 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
167 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700168 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000169 int fStackDepth;
170 SkWStream* fContentStream;
171};
172
173void GraphicStackState::drainStack() {
174 while (fStackDepth) {
175 pop();
176 }
177}
178
179void GraphicStackState::push() {
180 SkASSERT(fStackDepth < kMaxStackDepth);
181 fContentStream->writeText("q\n");
182 fStackDepth++;
183 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
184}
185
186void GraphicStackState::pop() {
187 SkASSERT(fStackDepth > 0);
188 fContentStream->writeText("Q\n");
189 fStackDepth--;
190}
191
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000192/* Calculate an inverted path's equivalent non-inverted path, given the
193 * canvas bounds.
194 * outPath may alias with invPath (since this is supported by PathOps).
195 */
196static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
197 SkPath* outPath) {
198 SkASSERT(invPath.isInverseFillType());
199
200 SkPath clipPath;
201 clipPath.addRect(bounds);
202
reedcdb42bb2015-06-26 10:23:07 -0700203 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000204}
205
Hal Canary44a97d52017-02-22 10:45:25 -0500206bool apply_clip(SkClipOp op, const SkPath& u, const SkPath& v, SkPath* r) {
207 switch (op) {
208 case SkClipOp::kDifference:
209 return Op(u, v, kDifference_SkPathOp, r);
210 case SkClipOp::kIntersect:
211 return Op(u, v, kIntersect_SkPathOp, r);
212 case SkClipOp::kUnion_deprecated:
213 return Op(u, v, kUnion_SkPathOp, r);
214 case SkClipOp::kXOR_deprecated:
215 return Op(u, v, kXOR_SkPathOp, r);
216 case SkClipOp::kReverseDifference_deprecated:
217 return Op(u, v, kReverseDifference_SkPathOp, r);
218 case SkClipOp::kReplace_deprecated:
219 *r = v;
220 return true;
221 default:
222 return false;
223 }
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000224}
225
226/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
227 * Returns true if successful, or false if not successful.
228 * If successful, the resulting clip is stored in outClipPath.
229 * If not successful, outClipPath is undefined, and a fallback method
230 * should be used.
231 */
232static bool get_clip_stack_path(const SkMatrix& transform,
233 const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500234 const SkRect& bounds,
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000235 SkPath* outClipPath) {
236 outClipPath->reset();
237 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
238
239 const SkClipStack::Element* clipEntry;
240 SkClipStack::Iter iter;
241 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
242 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
243 SkPath entryPath;
244 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
245 outClipPath->reset();
246 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
247 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000248 } else {
249 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000250 }
251 entryPath.transform(transform);
Hal Canary44a97d52017-02-22 10:45:25 -0500252 if (!apply_clip(clipEntry->getOp(), *outClipPath, entryPath, outClipPath)) {
253 return false;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000254 }
255 }
256
257 if (outClipPath->isInverseFillType()) {
258 // The bounds are slightly outset to ensure this is correct in the
259 // face of floating-point accuracy and possible SkRegion bitmap
260 // approximations.
Hal Canary44a97d52017-02-22 10:45:25 -0500261 SkRect clipBounds = bounds;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000262 clipBounds.outset(SK_Scalar1, SK_Scalar1);
263 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
264 return false;
265 }
266 }
267 return true;
268}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000269
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000270// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000271// graphic state stack, and the fact that we can know all the clips used
272// on the page to optimize this.
273void GraphicStackState::updateClip(const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500274 const SkPoint& translation,
275 const SkRect& bounds) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000276 if (clipStack == currentEntry()->fClipStack) {
277 return;
278 }
279
280 while (fStackDepth > 0) {
281 pop();
282 if (clipStack == currentEntry()->fClipStack) {
283 return;
284 }
285 }
286 push();
287
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000288 currentEntry()->fClipStack = clipStack;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000289
290 SkMatrix transform;
291 transform.setTranslate(translation.fX, translation.fY);
292
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000293 SkPath clipPath;
Hal Canary44a97d52017-02-22 10:45:25 -0500294 if (get_clip_stack_path(transform, clipStack, bounds, &clipPath)) {
halcanary5edf2902016-09-07 09:05:25 -0700295 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
296 SkPath::FillType clipFill = clipPath.getFillType();
297 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
298 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
299 if (clipFill == SkPath::kEvenOdd_FillType) {
300 fContentStream->writeText("W* n\n");
301 } else {
302 fContentStream->writeText("W n\n");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000303 }
304 }
halcanary5edf2902016-09-07 09:05:25 -0700305 // If Op() fails (pathological case; e.g. input values are
306 // extremely large or NaN), emit no clip at all.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000307}
308
309void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
310 if (matrix == currentEntry()->fMatrix) {
311 return;
312 }
313
314 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
315 SkASSERT(fStackDepth > 0);
316 SkASSERT(fEntries[fStackDepth].fClipStack ==
317 fEntries[fStackDepth -1].fClipStack);
318 pop();
319
320 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
321 }
322 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
323 return;
324 }
325
326 push();
327 SkPDFUtils::AppendTransform(matrix, fContentStream);
328 currentEntry()->fMatrix = matrix;
329}
330
halcanary2be7e012016-03-28 11:58:08 -0700331void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000332 // PDF treats a shader as a color, so we only set one or the other.
333 if (state.fShaderIndex >= 0) {
334 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000335 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000336 currentEntry()->fShaderIndex = state.fShaderIndex;
337 }
338 } else {
339 if (state.fColor != currentEntry()->fColor ||
340 currentEntry()->fShaderIndex >= 0) {
341 emit_pdf_color(state.fColor, fContentStream);
342 fContentStream->writeText("RG ");
343 emit_pdf_color(state.fColor, fContentStream);
344 fContentStream->writeText("rg\n");
345 currentEntry()->fColor = state.fColor;
346 currentEntry()->fShaderIndex = -1;
347 }
348 }
349
350 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000351 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000352 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
353 }
354
355 if (state.fTextScaleX) {
356 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
Mike Reed8be952a2017-02-13 20:44:33 -0500357 SkScalar pdfScale = state.fTextScaleX * 1000;
halcanarybc4696b2015-05-06 10:56:04 -0700358 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000359 fContentStream->writeText(" Tz\n");
360 currentEntry()->fTextScaleX = state.fTextScaleX;
361 }
362 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700363 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
364 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
365 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000366 fContentStream->writeDecAsText(state.fTextFill);
367 fContentStream->writeText(" Tr\n");
368 currentEntry()->fTextFill = state.fTextFill;
369 }
370 }
371}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000372
reed76033be2015-03-14 10:54:31 -0700373static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700374 // PDF does not support image filters, so render them on CPU.
375 // Note that this rendering is done at "screen" resolution (100dpi), not
376 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700377 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800378 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700379
380 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700381 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700382}
383
384SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700385 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700386 // need to return a raster device, which we will detect in drawDevice()
387 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700388 }
fmalita6987dca2014-11-13 08:33:37 -0800389 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanary989da4a2016-03-21 14:33:17 -0700390 return SkPDFDevice::Create(size, fRasterDpi, fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000391}
392
halcanary989da4a2016-03-21 14:33:17 -0700393SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
394
bsalomon@google.come97f0852011-06-17 13:10:25 +0000395
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000396
397// A helper class to automatically finish a ContentEntry at the end of a
398// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000399class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000400public:
Mike Reeda1361362017-03-07 09:37:29 -0500401 ScopedContentEntry(SkPDFDevice* device,
402 const SkClipStack& clipStack,
Mike Reed27d07f02017-03-04 21:47:47 +0000403 const SkMatrix& matrix,
Mike Reeda1361362017-03-07 09:37:29 -0500404 const SkPaint& paint,
405 bool hasText = false)
406 : fDevice(device)
407 , fContentEntry(nullptr)
408 , fBlendMode(SkBlendMode::kSrcOver)
409 , fDstFormXObject(nullptr)
410 {
411 if (matrix.hasPerspective()) {
412 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
413 return;
414 }
415 fBlendMode = paint.getBlendMode();
416 fContentEntry =
417 fDevice->setUpContentEntry(clipStack, matrix, paint, hasText, &fDstFormXObject);
Mike Reed27d07f02017-03-04 21:47:47 +0000418 }
Mike Reeda1361362017-03-07 09:37:29 -0500419 ScopedContentEntry(SkPDFDevice* dev, const SkPaint& paint, bool hasText = false)
420 : ScopedContentEntry(dev, dev->cs(), dev->ctm(), paint, hasText) {}
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000421
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000422 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000423 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000424 SkPath* shape = &fShape;
425 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700426 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000427 }
reed374772b2016-10-05 17:33:02 -0700428 fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000429 }
430 }
431
halcanary2be7e012016-03-28 11:58:08 -0700432 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000433
434 /* Returns true when we explicitly need the shape of the drawing. */
435 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700436 switch (fBlendMode) {
437 case SkBlendMode::kClear:
438 case SkBlendMode::kSrc:
439 case SkBlendMode::kSrcIn:
440 case SkBlendMode::kSrcOut:
441 case SkBlendMode::kDstIn:
442 case SkBlendMode::kDstOut:
443 case SkBlendMode::kSrcATop:
444 case SkBlendMode::kDstATop:
445 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000446 return true;
447 default:
448 return false;
449 }
450 }
451
452 /* Returns true unless we only need the shape of the drawing. */
453 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700454 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000455 return false;
456 }
457 return true;
458 }
459
460 /* If the shape is different than the alpha component of the content, then
461 * setShape should be called with the shape. In particular, images and
462 * devices have rectangular shape.
463 */
464 void setShape(const SkPath& shape) {
465 fShape = shape;
466 }
467
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000468private:
469 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700470 SkPDFDevice::ContentEntry* fContentEntry;
reed374772b2016-10-05 17:33:02 -0700471 SkBlendMode fBlendMode;
halcanarydabd4f02016-08-03 11:16:56 -0700472 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000473 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000474};
475
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000476////////////////////////////////////////////////////////////////////////////////
477
halcanary989da4a2016-03-21 14:33:17 -0700478SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFDocument* doc, bool flip)
reed589a39e2016-08-20 07:59:19 -0700479 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
480 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700481 , fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800482 , fRasterDpi(rasterDpi)
halcanary989da4a2016-03-21 14:33:17 -0700483 , fDocument(doc) {
halcanarya1f1ee92015-02-20 06:17:26 -0800484 SkASSERT(pageSize.width() > 0);
485 SkASSERT(pageSize.height() > 0);
robertphillips1f3923e2016-07-21 07:17:54 -0700486
halcanarya1f1ee92015-02-20 06:17:26 -0800487 if (flip) {
488 // Skia generally uses the top left as the origin but PDF
489 // natively has the origin at the bottom left. This matrix
490 // corrects for that. But that only needs to be done once, we
491 // don't do it when layering.
492 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
493 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
494 } else {
495 fInitialTransform.setIdentity();
496 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000497}
498
499SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700500 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000501}
502
503void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700504 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000505}
506
halcanary3c35fb32016-06-30 11:55:07 -0700507void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000508 fGraphicStateResources.unrefAll();
509 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000510 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000511 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000512}
513
Mike Reeda1361362017-03-07 09:37:29 -0500514void SkPDFDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500515 if (!value) {
516 return;
517 }
518 if (rect.isEmpty()) {
Mike Reeda1361362017-03-07 09:37:29 -0500519 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
520 SkPoint transformedPoint;
521 this->ctm().mapXY(rect.x(), rect.y(), &transformedPoint);
522 fNamedDestinations.emplace_back(value, transformedPoint);
523 }
524 return;
525 }
526 // Convert to path to handle non-90-degree rotations.
527 SkPath path;
528 path.addRect(rect);
529 path.transform(this->ctm(), &path);
530 SkPath clip;
531 (void)this->cs().asPath(&clip);
532 Op(clip, path, kIntersect_SkPathOp, &path);
533 // PDF wants a rectangle only.
534 SkRect transformedRect = path.getBounds();
535 if (transformedRect.isEmpty()) {
536 return;
537 }
538 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
539 fLinkToURLs.emplace_back(transformedRect, value);
540 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
541 fLinkToDestinations.emplace_back(transformedRect, value);
reedf70b5312016-03-04 16:36:20 -0800542 }
543}
544
Mike Reeda1361362017-03-07 09:37:29 -0500545void SkPDFDevice::drawPaint(const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000546 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700547 replace_srcmode_on_opaque_paint(&newPaint);
548
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000549 newPaint.setStyle(SkPaint::kFill_Style);
Mike Reeda1361362017-03-07 09:37:29 -0500550 ScopedContentEntry content(this, newPaint);
551 this->internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000552}
553
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000554void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700555 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000556 if (!contentEntry) {
557 return;
558 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000559 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
560 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000561 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000562 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000563 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000564 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000565 inverse.mapRect(&bbox);
566
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000567 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000568 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000569 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000570}
571
Mike Reeda1361362017-03-07 09:37:29 -0500572void SkPDFDevice::drawPoints(SkCanvas::PointMode mode,
halcanarya6814332015-05-27 08:53:36 -0700573 size_t count,
574 const SkPoint* points,
575 const SkPaint& srcPaint) {
576 SkPaint passedPaint = srcPaint;
577 replace_srcmode_on_opaque_paint(&passedPaint);
578
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000579 if (count == 0) {
580 return;
581 }
582
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000583 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
584 // We only use this when there's a path effect because of the overhead
585 // of multiple calls to setUpContentEntry it causes.
586 if (passedPaint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500587 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000588 return;
589 }
Mike Reeda1361362017-03-07 09:37:29 -0500590 draw_points(mode, count, points, passedPaint,
591 this->devClipBounds(), this->ctm(), this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000592 return;
593 }
594
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000595 const SkPaint* paint = &passedPaint;
596 SkPaint modifiedPaint;
597
598 if (mode == SkCanvas::kPoints_PointMode &&
599 paint->getStrokeCap() != SkPaint::kRound_Cap) {
600 modifiedPaint = *paint;
601 paint = &modifiedPaint;
602 if (paint->getStrokeWidth()) {
603 // PDF won't draw a single point with square/butt caps because the
604 // orientation is ambiguous. Draw a rectangle instead.
605 modifiedPaint.setStyle(SkPaint::kFill_Style);
606 SkScalar strokeWidth = paint->getStrokeWidth();
607 SkScalar halfStroke = SkScalarHalf(strokeWidth);
608 for (size_t i = 0; i < count; i++) {
609 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
610 r.inset(-halfStroke, -halfStroke);
Mike Reeda1361362017-03-07 09:37:29 -0500611 this->drawRect(r, modifiedPaint);
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000612 }
613 return;
614 } else {
615 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
616 }
617 }
618
Mike Reeda1361362017-03-07 09:37:29 -0500619 ScopedContentEntry content(this, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000620 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000621 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000622 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000623
624 switch (mode) {
625 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000626 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000627 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000628 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000629 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000630 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000631 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000632 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000633 break;
634 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000635 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000636 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000637 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000638 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000639 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000640 &content.entry()->fContent);
641 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000642 }
643 break;
644 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000645 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
646 for (size_t i = 0; i < count; i++) {
647 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000648 &content.entry()->fContent);
649 SkPDFUtils::ClosePath(&content.entry()->fContent);
650 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000651 }
652 break;
653 default:
654 SkASSERT(false);
655 }
656}
657
halcanary8103a342016-03-08 15:10:16 -0800658static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800659 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700660 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700661 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700662
halcanaryece83922016-03-08 08:32:12 -0800663 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700664 border->reserve(3);
665 border->appendInt(0); // Horizontal corner radius.
666 border->appendInt(0); // Vertical corner radius.
667 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800668 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700669
halcanaryece83922016-03-08 08:32:12 -0800670 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700671 rect->reserve(4);
672 rect->appendScalar(translatedRect.fLeft);
673 rect->appendScalar(translatedRect.fTop);
674 rect->appendScalar(translatedRect.fRight);
675 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800676 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700677
halcanary8103a342016-03-08 15:10:16 -0800678 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700679}
680
halcanary8103a342016-03-08 15:10:16 -0800681static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700682 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700683 SkString url(static_cast<const char *>(urlData->data()),
684 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800685 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700686 action->insertName("S", "URI");
687 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800688 annotation->insertObject("A", std::move(action));
689 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700690}
691
halcanary8103a342016-03-08 15:10:16 -0800692static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
693 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700694 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700695 SkString name(static_cast<const char *>(nameData->data()),
696 nameData->size() - 1);
697 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800698 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700699}
700
Mike Reeda1361362017-03-07 09:37:29 -0500701void SkPDFDevice::drawRect(const SkRect& rect,
halcanarya6814332015-05-27 08:53:36 -0700702 const SkPaint& srcPaint) {
703 SkPaint paint = srcPaint;
704 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000705 SkRect r = rect;
706 r.sort();
707
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000708 if (paint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500709 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000710 return;
711 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000712 SkPath path;
713 path.addRect(r);
Mike Reeda1361362017-03-07 09:37:29 -0500714 this->drawPath(path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000715 return;
716 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000717
Mike Reeda1361362017-03-07 09:37:29 -0500718 ScopedContentEntry content(this, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000719 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000720 return;
721 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000722 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000723 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000724 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000725}
726
Mike Reeda1361362017-03-07 09:37:29 -0500727void SkPDFDevice::drawRRect(const SkRRect& rrect,
halcanarya6814332015-05-27 08:53:36 -0700728 const SkPaint& srcPaint) {
729 SkPaint paint = srcPaint;
730 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000731 SkPath path;
732 path.addRRect(rrect);
Mike Reeda1361362017-03-07 09:37:29 -0500733 this->drawPath(path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000734}
735
Mike Reeda1361362017-03-07 09:37:29 -0500736void SkPDFDevice::drawOval(const SkRect& oval,
halcanarya6814332015-05-27 08:53:36 -0700737 const SkPaint& srcPaint) {
738 SkPaint paint = srcPaint;
739 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700740 SkPath path;
741 path.addOval(oval);
Mike Reeda1361362017-03-07 09:37:29 -0500742 this->drawPath(path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700743}
744
Mike Reeda1361362017-03-07 09:37:29 -0500745void SkPDFDevice::drawPath(const SkPath& origPath,
halcanarya6814332015-05-27 08:53:36 -0700746 const SkPaint& srcPaint,
747 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000748 bool pathIsMutable) {
Mike Reeda1361362017-03-07 09:37:29 -0500749 this->internalDrawPath(
750 this->cs(), this->ctm(), origPath, srcPaint, prePathMatrix, pathIsMutable);
751}
752
753void SkPDFDevice::internalDrawPath(const SkClipStack& clipStack,
754 const SkMatrix& ctm,
755 const SkPath& origPath,
756 const SkPaint& srcPaint,
757 const SkMatrix* prePathMatrix,
758 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700759 SkPaint paint = srcPaint;
760 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800761 SkPath modifiedPath;
762 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000763
Mike Reeda1361362017-03-07 09:37:29 -0500764 SkMatrix matrix = ctm;
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000765 if (prePathMatrix) {
766 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800767 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000768 pathPtr = &modifiedPath;
769 pathIsMutable = true;
770 }
halcanary682ee012016-01-28 10:59:34 -0800771 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000772 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000773 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000774 }
775 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000776
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000777 if (paint.getPathEffect()) {
Mike Reeda1361362017-03-07 09:37:29 -0500778 if (clipStack.isEmpty(size(*this))) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000779 return;
780 }
halcanary682ee012016-01-28 10:59:34 -0800781 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000782 pathPtr = &modifiedPath;
783 pathIsMutable = true;
784 }
halcanary682ee012016-01-28 10:59:34 -0800785 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000786
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000787 SkPaint noEffectPaint(paint);
halcanary96fcdcc2015-08-27 07:41:13 -0700788 noEffectPaint.setPathEffect(nullptr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000789 if (fill) {
790 noEffectPaint.setStyle(SkPaint::kFill_Style);
791 } else {
792 noEffectPaint.setStyle(SkPaint::kStroke_Style);
793 noEffectPaint.setStrokeWidth(0);
794 }
Mike Reeda1361362017-03-07 09:37:29 -0500795 this->internalDrawPath(clipStack, ctm, *pathPtr, noEffectPaint, nullptr, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000796 return;
797 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000798
Mike Reeda1361362017-03-07 09:37:29 -0500799 if (this->handleInversePath(origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000800 return;
801 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000802
Mike Reeda1361362017-03-07 09:37:29 -0500803 ScopedContentEntry content(this, clipStack, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000804 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000805 return;
806 }
Hal Canary385468f2017-02-13 11:03:23 -0500807 SkScalar matrixScale = matrix.mapRadius(1.0f);
808 SkScalar tolerance = matrixScale > 0.0f ? 0.25f / matrixScale : 0.25f;
halcanary8b2bc252015-10-06 09:41:47 -0700809 bool consumeDegeratePathSegments =
810 paint.getStyle() == SkPaint::kFill_Style ||
811 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
812 paint.getStrokeCap() != SkPaint::kSquare_Cap);
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000813 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
halcanary8b2bc252015-10-06 09:41:47 -0700814 consumeDegeratePathSegments,
Hal Canary385468f2017-02-13 11:03:23 -0500815 &content.entry()->fContent,
816 tolerance);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000817 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000818 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000819}
820
Hal Canaryf50ff392016-09-30 10:25:39 -0400821
Mike Reeda1361362017-03-07 09:37:29 -0500822void SkPDFDevice::drawImageRect(const SkImage* image,
Hal Canaryf50ff392016-09-30 10:25:39 -0400823 const SkRect* src,
824 const SkRect& dst,
825 const SkPaint& srcPaint,
826 SkCanvas::SrcRectConstraint) {
827 if (!image) {
828 return;
829 }
830 SkIRect bounds = image->bounds();
831 SkPaint paint = srcPaint;
832 if (image->isOpaque()) {
833 replace_srcmode_on_opaque_paint(&paint);
834 }
835 SkRect srcRect = src ? *src : SkRect::Make(bounds);
836 SkMatrix transform;
837 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
838 if (src) {
839 if (!srcRect.intersect(SkRect::Make(bounds))) {
840 return;
841 }
842 srcRect.roundOut(&bounds);
843 transform.preTranslate(SkIntToScalar(bounds.x()),
844 SkIntToScalar(bounds.y()));
845 }
846 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)), bounds);
847 if (!imageSubset.isValid()) {
848 return;
849 }
Mike Reeda1361362017-03-07 09:37:29 -0500850 transform.postConcat(this->ctm());
851 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
Hal Canaryf50ff392016-09-30 10:25:39 -0400852}
853
Mike Reeda1361362017-03-07 09:37:29 -0500854void SkPDFDevice::drawBitmapRect(const SkBitmap& bitmap,
halcanary7a14b312015-10-01 07:28:13 -0700855 const SkRect* src,
856 const SkRect& dst,
Mike Reeda1361362017-03-07 09:37:29 -0500857 const SkPaint& srcPaint,
858 SkCanvas::SrcRectConstraint) {
Hal Canaryf50ff392016-09-30 10:25:39 -0400859 if (bitmap.drawsNothing()) {
860 return;
861 }
862 SkIRect bounds = bitmap.bounds();
863 SkPaint paint = srcPaint;
864 if (bitmap.isOpaque()) {
865 replace_srcmode_on_opaque_paint(&paint);
866 }
867 SkRect srcRect = src ? *src : SkRect::Make(bounds);
868 SkMatrix transform;
869 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
870 if (src) {
871 if (!srcRect.intersect(SkRect::Make(bounds))) {
872 return;
873 }
874 srcRect.roundOut(&bounds);
875 transform.preTranslate(SkIntToScalar(bounds.x()),
876 SkIntToScalar(bounds.y()));
877 }
878 SkBitmap bitmapSubset;
879 if (!bitmap.extractSubset(&bitmapSubset, bounds)) {
880 return;
881 }
882 SkImageSubset imageSubset = make_image_subset(bitmapSubset);
883 if (!imageSubset.isValid()) {
884 return;
885 }
Mike Reeda1361362017-03-07 09:37:29 -0500886 transform.postConcat(this->ctm());
887 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700888}
889
Mike Reeda1361362017-03-07 09:37:29 -0500890void SkPDFDevice::drawBitmap(const SkBitmap& bitmap,
halcanary7a14b312015-10-01 07:28:13 -0700891 const SkMatrix& matrix,
892 const SkPaint& srcPaint) {
Mike Reeda1361362017-03-07 09:37:29 -0500893 if (bitmap.drawsNothing() || this->cs().isEmpty(size(*this))) {
Hal Canaryf50ff392016-09-30 10:25:39 -0400894 return;
895 }
halcanarya6814332015-05-27 08:53:36 -0700896 SkPaint paint = srcPaint;
897 if (bitmap.isOpaque()) {
898 replace_srcmode_on_opaque_paint(&paint);
899 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400900 SkImageSubset imageSubset = make_image_subset(bitmap);
901 if (!imageSubset.isValid()) {
halcanary7a14b312015-10-01 07:28:13 -0700902 return;
903 }
halcanary7a14b312015-10-01 07:28:13 -0700904 SkMatrix transform = matrix;
Mike Reeda1361362017-03-07 09:37:29 -0500905 transform.postConcat(this->ctm());
906 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700907}
908
Mike Reeda1361362017-03-07 09:37:29 -0500909void SkPDFDevice::drawSprite(const SkBitmap& bitmap,
halcanary7a14b312015-10-01 07:28:13 -0700910 int x,
911 int y,
912 const SkPaint& srcPaint) {
Mike Reeda1361362017-03-07 09:37:29 -0500913 if (bitmap.drawsNothing() || this->cs().isEmpty(size(*this))) {
Hal Canaryf50ff392016-09-30 10:25:39 -0400914 return;
915 }
halcanary7a14b312015-10-01 07:28:13 -0700916 SkPaint paint = srcPaint;
917 if (bitmap.isOpaque()) {
918 replace_srcmode_on_opaque_paint(&paint);
919 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400920 SkImageSubset imageSubset = make_image_subset(bitmap);
921 if (!imageSubset.isValid()) {
halcanary7a14b312015-10-01 07:28:13 -0700922 return;
923 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400924 SkMatrix transform = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
Mike Reeda1361362017-03-07 09:37:29 -0500925 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700926}
927
Mike Reeda1361362017-03-07 09:37:29 -0500928void SkPDFDevice::drawImage(const SkImage* image,
halcanary7a14b312015-10-01 07:28:13 -0700929 SkScalar x,
930 SkScalar y,
931 const SkPaint& srcPaint) {
932 SkPaint paint = srcPaint;
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500933 if (!image) {
halcanary7a14b312015-10-01 07:28:13 -0700934 return;
935 }
936 if (image->isOpaque()) {
937 replace_srcmode_on_opaque_paint(&paint);
938 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400939 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)));
940 if (!imageSubset.isValid()) {
941 return;
942 }
halcanary7a14b312015-10-01 07:28:13 -0700943 SkMatrix transform = SkMatrix::MakeTrans(x, y);
Mike Reeda1361362017-03-07 09:37:29 -0500944 transform.postConcat(this->ctm());
945 this->internalDrawImage(transform, this->cs(), std::move(imageSubset), paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000946}
947
halcanaryf0c30f52016-07-15 13:35:45 -0700948namespace {
949class GlyphPositioner {
950public:
951 GlyphPositioner(SkDynamicMemoryWStream* content,
952 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -0700953 bool wideChars,
954 bool defaultPositioning,
955 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -0700956 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -0700957 , fCurrentMatrixOrigin(origin)
958 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -0700959 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -0700960 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -0700961 }
halcanary4871f222016-08-26 13:17:44 -0700962 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -0700963 void flush() {
964 if (fInText) {
965 fContent->writeText("> Tj\n");
966 fInText = false;
967 }
968 }
halcanary4871f222016-08-26 13:17:44 -0700969 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -0700970 SkScalar advanceWidth,
971 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -0700972 if (!fInitialized) {
973 // Flip the text about the x-axis to account for origin swap and include
974 // the passed parameters.
975 fContent->writeText("1 0 ");
976 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
977 fContent->writeText(" -1 ");
978 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
979 fContent->writeText(" ");
980 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
981 fContent->writeText(" Tm\n");
982 fCurrentMatrixOrigin.set(0.0f, 0.0f);
983 fInitialized = true;
984 }
Hal Canary7bb93012016-10-31 12:40:49 -0400985#ifdef SK_BUILD_FOR_WIN
986 const bool kAlwaysPosition = true;
987#else
988 const bool kAlwaysPosition = false;
989#endif
halcanary4ed2f012016-08-15 18:40:07 -0700990 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -0700991 SkPoint position = xy - fCurrentMatrixOrigin;
Hal Canary7bb93012016-10-31 12:40:49 -0400992 if (kAlwaysPosition || position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -0700993 this->flush();
halcanary4871f222016-08-26 13:17:44 -0700994 SkPDFUtils::AppendScalar(position.x(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -0700995 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -0700996 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -0700997 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -0700998 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -0700999 fXAdvance = 0;
1000 }
1001 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -07001002 }
1003 if (!fInText) {
1004 fContent->writeText("<");
1005 fInText = true;
1006 }
1007 if (fWideChars) {
1008 SkPDFUtils::WriteUInt16BE(fContent, glyph);
1009 } else {
1010 SkASSERT(0 == glyph >> 8);
1011 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1012 }
halcanaryf0c30f52016-07-15 13:35:45 -07001013 }
1014
1015private:
1016 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -07001017 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001018 SkScalar fXAdvance = 0.0f;
1019 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001020 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001021 bool fInText = false;
1022 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -07001023 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001024};
halcanaryf59d18a2016-09-16 14:44:57 -07001025
1026/** Given the m-to-n glyph-to-character mapping data (as returned by
1027 harfbuzz), iterate over the clusters. */
1028class Clusterator {
1029public:
1030 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1031 explicit Clusterator(uint32_t glyphCount)
1032 : fClusters(nullptr)
1033 , fUtf8Text(nullptr)
1034 , fGlyphCount(glyphCount)
1035 , fTextByteLength(0) {}
1036 // The clusters[] array is an array of offsets into utf8Text[],
1037 // one offset for each glyph. See SkTextBlobBuilder for more info.
1038 Clusterator(const uint32_t* clusters,
1039 const char* utf8Text,
1040 uint32_t glyphCount,
1041 uint32_t textByteLength)
1042 : fClusters(clusters)
1043 , fUtf8Text(utf8Text)
1044 , fGlyphCount(glyphCount)
1045 , fTextByteLength(textByteLength) {
1046 // This is a cheap heuristic for /ReversedChars which seems to
1047 // work for clusters produced by HarfBuzz, which either
1048 // increase from zero (LTR) or decrease to zero (RTL).
1049 // "ReversedChars" is how PDF deals with RTL text.
1050 fReversedChars =
1051 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1052 }
1053 struct Cluster {
1054 const char* fUtf8Text;
1055 uint32_t fTextByteLength;
1056 uint32_t fGlyphIndex;
1057 uint32_t fGlyphCount;
1058 explicit operator bool() const { return fGlyphCount != 0; }
1059 };
1060 // True if this looks like right-to-left text.
1061 bool reversedChars() const { return fReversedChars; }
1062 Cluster next() {
1063 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1064 // These glyphs have no text. Treat as one "cluster".
1065 uint32_t glyphCount = fGlyphCount;
1066 fGlyphCount = 0;
1067 return Cluster{nullptr, 0, 0, glyphCount};
1068 }
1069 if (fGlyphCount == 0 || fTextByteLength == 0) {
1070 return Cluster{nullptr, 0, 0, 0}; // empty
1071 }
1072 SkASSERT(fUtf8Text);
1073 SkASSERT(fClusters);
1074 uint32_t cluster = fClusters[0];
1075 if (cluster >= fTextByteLength) {
1076 return Cluster{nullptr, 0, 0, 0}; // bad input.
1077 }
1078 uint32_t glyphsInCluster = 1;
1079 while (glyphsInCluster < fGlyphCount &&
1080 fClusters[glyphsInCluster] == cluster) {
1081 ++glyphsInCluster;
1082 }
1083 SkASSERT(glyphsInCluster <= fGlyphCount);
1084 uint32_t textLength = 0;
1085 if (glyphsInCluster == fGlyphCount) {
1086 // consumes rest of glyphs and rest of text
1087 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1088 textLength = fTextByteLength - cluster;
1089 } else { // RTL text; last cluster.
1090 SkASSERT(fPreviousCluster < fTextByteLength);
1091 if (fPreviousCluster <= cluster) { // bad input.
1092 return Cluster{nullptr, 0, 0, 0};
1093 }
1094 textLength = fPreviousCluster - cluster;
1095 }
1096 fGlyphCount = 0;
1097 return Cluster{fUtf8Text + cluster,
1098 textLength,
1099 fGlyphIndex,
1100 glyphsInCluster};
1101 }
1102 SkASSERT(glyphsInCluster < fGlyphCount);
1103 uint32_t nextCluster = fClusters[glyphsInCluster];
1104 if (nextCluster >= fTextByteLength) {
1105 return Cluster{nullptr, 0, 0, 0}; // bad input.
1106 }
1107 if (nextCluster > cluster) { // LTR text
1108 if (kInvalidCluster != fPreviousCluster) {
1109 return Cluster{nullptr, 0, 0, 0}; // bad input.
1110 }
1111 textLength = nextCluster - cluster;
1112 } else { // RTL text
1113 SkASSERT(nextCluster < cluster);
1114 if (kInvalidCluster == fPreviousCluster) { // first cluster
1115 textLength = fTextByteLength - cluster;
1116 } else { // later cluster
1117 if (fPreviousCluster <= cluster) {
1118 return Cluster{nullptr, 0, 0, 0}; // bad input.
1119 }
1120 textLength = fPreviousCluster - cluster;
1121 }
1122 fPreviousCluster = cluster;
1123 }
1124 uint32_t glyphIndex = fGlyphIndex;
1125 fGlyphCount -= glyphsInCluster;
1126 fGlyphIndex += glyphsInCluster;
1127 fClusters += glyphsInCluster;
1128 return Cluster{fUtf8Text + cluster,
1129 textLength,
1130 glyphIndex,
1131 glyphsInCluster};
1132 }
1133
1134private:
1135 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1136 const uint32_t* fClusters;
1137 const char* fUtf8Text;
1138 uint32_t fGlyphCount;
1139 uint32_t fTextByteLength;
1140 uint32_t fGlyphIndex = 0;
1141 uint32_t fPreviousCluster = kInvalidCluster;
1142 bool fReversedChars = false;
1143};
1144
1145struct TextStorage {
1146 SkAutoTMalloc<char> fUtf8textStorage;
1147 SkAutoTMalloc<uint32_t> fClusterStorage;
1148 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1149};
halcanaryf0c30f52016-07-15 13:35:45 -07001150} // namespace
1151
halcanaryf59d18a2016-09-16 14:44:57 -07001152/** Given some unicode text (as passed to drawText(), convert to
1153 glyphs (via primitive shaping), while preserving
1154 glyph-to-character mapping information. */
1155static Clusterator make_clusterator(
1156 const void* sourceText,
1157 size_t sourceByteCount,
1158 const SkPaint& paint,
1159 TextStorage* storage,
1160 int glyphCount) {
1161 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1162 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1163 SkASSERT(glyphCount > 0);
1164 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1165 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1166 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1167 uint32_t* clusters = storage->fClusterStorage.get();
1168 uint32_t utf8ByteCount = 0;
1169 const char* utf8Text = nullptr;
1170 switch (paint.getTextEncoding()) {
1171 case SkPaint::kUTF8_TextEncoding: {
1172 const char* txtPtr = (const char*)sourceText;
1173 for (int i = 0; i < glyphCount; ++i) {
1174 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1175 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1176 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1177 }
1178 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1179 utf8ByteCount = SkToU32(sourceByteCount);
1180 utf8Text = (const char*)sourceText;
1181 break;
1182 }
1183 case SkPaint::kUTF16_TextEncoding: {
1184 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1185 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1186 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1187 storage->fUtf8textStorage.reset(utf8ByteCount);
1188 char* txtPtr = storage->fUtf8textStorage.get();
1189 utf8Text = txtPtr;
1190 int clusterIndex = 0;
1191 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1192 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1193 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1194 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1195 }
1196 SkASSERT(clusterIndex == glyphCount);
1197 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1198 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1199 break;
1200 }
1201 case SkPaint::kUTF32_TextEncoding: {
1202 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1203 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1204 SkASSERT(glyphCount == utf32count);
1205 for (int i = 0; i < utf32count; ++i) {
1206 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1207 }
1208 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1209 char* txtPtr = storage->fUtf8textStorage.get();
1210 utf8Text = txtPtr;
1211 for (int i = 0; i < utf32count; ++i) {
1212 clusters[i] = SkToU32(txtPtr - utf8Text);
1213 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1214 }
1215 break;
1216 }
1217 default:
1218 SkDEBUGFAIL("");
1219 break;
1220 }
1221 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1222}
1223
halcanaryf59d18a2016-09-16 14:44:57 -07001224static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1225 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1226}
1227
halcanaryc2f9ec12016-09-12 08:55:29 -07001228static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1229 wStream->writeText("/");
1230 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1231 wStream->write(&prefix, 1);
1232 wStream->writeDecAsText(fontIndex);
1233 wStream->writeText(" ");
1234 SkPDFUtils::AppendScalar(textSize, wStream);
1235 wStream->writeText(" Tf\n");
1236}
1237
halcanary4ed2f012016-08-15 18:40:07 -07001238void SkPDFDevice::internalDrawText(
Mike Reeda1361362017-03-07 09:37:29 -05001239 const void* sourceText, size_t sourceByteCount,
halcanary4ed2f012016-08-15 18:40:07 -07001240 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001241 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1242 uint32_t textByteLength, const char* utf8Text) {
halcanary4ed2f012016-08-15 18:40:07 -07001243 NOT_IMPLEMENTED(srcPaint.getMaskFilter() != nullptr, false);
1244 if (srcPaint.getMaskFilter() != nullptr) {
1245 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1246 // making text unreadable (e.g. same text twice when using CSS shadows).
1247 return;
1248 }
halcanaryea17dfe2016-08-24 09:20:57 -07001249 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1250 if (srcPaint.isVerticalText()) {
1251 // Don't pretend we support drawing vertical text. It is not
1252 // clear to me how to switch to "vertical writing" mode in PDF.
1253 // Currently neither Chromium or Android set this flag.
1254 // https://bug.skia.org/5665
1255 return;
1256 }
halcanaryf59d18a2016-09-16 14:44:57 -07001257 if (0 == sourceByteCount || !sourceText) {
1258 return;
halcanarye06ca962016-09-09 05:34:55 -07001259 }
halcanary4ed2f012016-08-15 18:40:07 -07001260 SkPaint paint = calculate_text_paint(srcPaint);
1261 replace_srcmode_on_opaque_paint(&paint);
1262 if (!paint.getTypeface()) {
1263 paint.setTypeface(SkTypeface::MakeDefault());
1264 }
1265 SkTypeface* typeface = paint.getTypeface();
1266 if (!typeface) {
1267 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1268 return;
1269 }
halcanary4871f222016-08-26 13:17:44 -07001270
1271 const SkAdvancedTypefaceMetrics* metrics =
1272 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1273 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001274 return;
1275 }
halcanary2bd295e2016-09-16 08:15:56 -07001276 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1277 if (glyphCount <= 0) {
1278 return;
1279 }
halcanary3b294d52016-09-16 13:21:08 -07001280
halcanaryf59d18a2016-09-16 14:44:57 -07001281 // These three heap buffers are only used in the case where no glyphs
1282 // are passed to drawText() (most clients pass glyphs or a textblob).
1283 TextStorage storage;
1284 const SkGlyphID* glyphs = nullptr;
1285 Clusterator clusterator;
1286 if (textByteLength > 0) {
1287 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1288 glyphs = (const SkGlyphID*)sourceText;
1289 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1290 SkASSERT(clusters);
1291 SkASSERT(utf8Text);
1292 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1293 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1294 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1295 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1296 glyphs = (const SkGlyphID*)sourceText;
1297 clusterator = Clusterator(SkToU32(glyphCount));
1298 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1299 SkASSERT(nullptr == clusters);
1300 SkASSERT(nullptr == utf8Text);
1301 } else {
1302 SkASSERT(nullptr == clusters);
1303 SkASSERT(nullptr == utf8Text);
1304 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1305 &storage, glyphCount);
1306 glyphs = storage.fGlyphStorage;
1307 }
halcanary4ed2f012016-08-15 18:40:07 -07001308 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001309 paint.setHinting(SkPaint::kNo_Hinting);
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001310
1311 int emSize;
1312 SkAutoGlyphCache glyphCache = SkPDFFont::MakeVectorCache(typeface, &emSize);
1313
1314 SkScalar textSize = paint.getTextSize();
1315 SkScalar advanceScale = textSize * paint.getTextScaleX() / emSize;
halcanary4ed2f012016-08-15 18:40:07 -07001316
1317 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001318 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1319 SkPaint::kCenter_Align == alignment ? -0.5f :
1320 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001321 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001322 SkScalar advance = 0;
halcanary4ed2f012016-08-15 18:40:07 -07001323 for (int i = 0; i < glyphCount; ++i) {
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001324 advance += advanceScale * glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
halcanary4ed2f012016-08-15 18:40:07 -07001325 }
halcanary4871f222016-08-26 13:17:44 -07001326 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001327 }
Mike Reeda1361362017-03-07 09:37:29 -05001328 ScopedContentEntry content(this, paint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001329 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001330 return;
1331 }
halcanary4ed2f012016-08-15 18:40:07 -07001332 SkDynamicMemoryWStream* out = &content.entry()->fContent;
halcanaryf59d18a2016-09-16 14:44:57 -07001333 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
halcanary4871f222016-08-26 13:17:44 -07001334
halcanary4871f222016-08-26 13:17:44 -07001335 out->writeText("BT\n");
1336 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1337
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001338 const SkGlyphID maxGlyphID = SkToU16(typeface->countGlyphs() - 1);
1339
halcanaryc2f9ec12016-09-12 08:55:29 -07001340 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
halcanaryf59d18a2016-09-16 14:44:57 -07001341 if (clusterator.reversedChars()) {
1342 out->writeText("/ReversedChars BMC\n");
1343 }
1344 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
halcanary4ed2f012016-08-15 18:40:07 -07001345 GlyphPositioner glyphPositioner(out,
1346 paint.getTextSkewX(),
halcanaryc2f9ec12016-09-12 08:55:29 -07001347 multiByteGlyphs,
halcanary4ed2f012016-08-15 18:40:07 -07001348 defaultPositioning,
1349 offset);
halcanaryc2f9ec12016-09-12 08:55:29 -07001350 SkPDFFont* font = nullptr;
halcanaryf59d18a2016-09-16 14:44:57 -07001351
1352 while (Clusterator::Cluster c = clusterator.next()) {
1353 int index = c.fGlyphIndex;
1354 int glyphLimit = index + c.fGlyphCount;
1355
1356 bool actualText = false;
1357 SK_AT_SCOPE_EXIT(if (actualText) { glyphPositioner.flush(); out->writeText("EMC\n"); } );
1358 if (c.fUtf8Text) { // real cluster
1359 // Check if `/ActualText` needed.
1360 const char* textPtr = c.fUtf8Text;
halcanaryf59d18a2016-09-16 14:44:57 -07001361 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
Hal Canaryd1c8e562017-01-11 15:53:25 -05001362 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1363 if (unichar < 0) {
1364 return;
1365 }
halcanaryf59d18a2016-09-16 14:44:57 -07001366 if (textPtr < textEnd || // more characters left
1367 glyphLimit > index + 1 || // toUnicode wouldn't work
1368 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1369 {
1370 glyphPositioner.flush();
1371 out->writeText("/Span<</ActualText <");
1372 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1373 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1374 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1375 while (textPtr < textEnd) {
Hal Canaryd1c8e562017-01-11 15:53:25 -05001376 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1377 if (unichar < 0) {
1378 break;
1379 }
halcanaryf59d18a2016-09-16 14:44:57 -07001380 SkPDFUtils::WriteUTF16beHex(out, unichar);
1381 }
1382 out->writeText("> >> BDC\n"); // begin marked-content sequence
1383 // with an associated property list.
1384 actualText = true;
robertphillips5ba165e2016-08-15 15:36:58 -07001385 }
1386 }
halcanaryf59d18a2016-09-16 14:44:57 -07001387 for (; index < glyphLimit; ++index) {
1388 SkGlyphID gid = glyphs[index];
1389 if (gid > maxGlyphID) {
1390 continue;
1391 }
1392 if (!font || !font->hasGlyph(gid)) {
1393 // Not yet specified font or need to switch font.
1394 int fontIndex = this->getFontResourceIndex(typeface, gid);
1395 // All preconditions for SkPDFFont::GetFontResource are met.
1396 SkASSERT(fontIndex >= 0);
1397 if (fontIndex < 0) {
1398 return;
1399 }
1400 glyphPositioner.flush();
1401 update_font(out, fontIndex, textSize);
1402 font = fFontResources[fontIndex];
1403 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1404 if (!font) {
1405 return;
1406 }
1407 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1408 }
1409 SkPoint xy{0, 0};
1410 SkScalar advance{0};
1411 if (!defaultPositioning) {
Hal Canaryaa3af7b2017-03-06 16:18:49 -05001412 advance = advanceScale * glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
halcanaryf59d18a2016-09-16 14:44:57 -07001413 xy = SkTextBlob::kFull_Positioning == positioning
1414 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1415 : SkPoint{pos[index], 0};
1416 if (alignment != SkPaint::kLeft_Align) {
1417 xy.offset(alignmentFactor * advance, 0);
1418 }
1419 }
1420 font->noteGlyphUsage(gid);
1421 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1422 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
1423 }
robertphillips5ba165e2016-08-15 15:36:58 -07001424 }
halcanary4ed2f012016-08-15 18:40:07 -07001425}
1426
Mike Reeda1361362017-03-07 09:37:29 -05001427void SkPDFDevice::drawText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001428 SkScalar x, SkScalar y, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001429 this->internalDrawText(text, len, nullptr, SkTextBlob::kDefault_Positioning,
halcanarye06ca962016-09-09 05:34:55 -07001430 SkPoint{x, y}, paint, nullptr, 0, nullptr);
halcanary4ed2f012016-08-15 18:40:07 -07001431}
1432
Mike Reeda1361362017-03-07 09:37:29 -05001433void SkPDFDevice::drawPosText(const void* text, size_t len,
halcanary4ed2f012016-08-15 18:40:07 -07001434 const SkScalar pos[], int scalarsPerPos,
1435 const SkPoint& offset, const SkPaint& paint) {
Mike Reeda1361362017-03-07 09:37:29 -05001436 this->internalDrawText(text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001437 offset, paint, nullptr, 0, nullptr);
1438}
1439
Mike Reeda1361362017-03-07 09:37:29 -05001440void SkPDFDevice::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
halcanarye06ca962016-09-09 05:34:55 -07001441 const SkPaint &paint, SkDrawFilter* drawFilter) {
1442 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1443 SkPaint runPaint(paint);
1444 it.applyFontToPaint(&runPaint);
1445 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1446 continue;
1447 }
1448 runPaint.setFlags(this->filterTextFlags(runPaint));
1449 SkPoint offset = it.offset() + SkPoint{x, y};
Mike Reeda1361362017-03-07 09:37:29 -05001450 this->internalDrawText(it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
halcanarye06ca962016-09-09 05:34:55 -07001451 it.pos(), it.positioning(), offset, runPaint,
1452 it.clusters(), it.textSize(), it.text());
1453 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001454}
1455
Mike Reed2f6b5a42017-03-19 15:04:17 -04001456void SkPDFDevice::drawVertices(const SkVertices*, SkBlendMode, const SkPaint&) {
Mike Reeda1361362017-03-07 09:37:29 -05001457 if (this->cs().isEmpty(size(*this))) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001458 return;
1459 }
reed@google.com85e143c2013-12-30 15:51:25 +00001460 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001461}
1462
Mike Reeda1361362017-03-07 09:37:29 -05001463void SkPDFDevice::drawDevice(SkBaseDevice* device, int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001464 SkASSERT(!paint.getImageFilter());
1465
reed7503d602016-07-15 14:23:29 -07001466 // Check if the source device is really a bitmapdevice (because that's what we returned
1467 // from createDevice (likely due to an imagefilter)
1468 SkPixmap pmap;
1469 if (device->peekPixels(&pmap)) {
1470 SkBitmap bitmap;
1471 bitmap.installPixels(pmap);
Mike Reeda1361362017-03-07 09:37:29 -05001472 this->drawSprite(bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001473 return;
1474 }
1475
fmalita6987dca2014-11-13 08:33:37 -08001476 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001477 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001478
1479 SkScalar scalarX = SkIntToScalar(x);
1480 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001481 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1482 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001483 fLinkToURLs.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001484 }
halcanary91fcb3e2016-03-04 13:53:22 -08001485 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1486 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001487 fLinkToDestinations.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001488 }
halcanary91fcb3e2016-03-04 13:53:22 -08001489 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1490 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001491 fNamedDestinations.emplace_back(d.nameData.get(), p);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001492 }
1493
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001494 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001495 return;
1496 }
1497
Mike Reeda1361362017-03-07 09:37:29 -05001498 SkMatrix matrix = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
1499 ScopedContentEntry content(this, this->cs(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001500 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001501 return;
1502 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001503 if (content.needShape()) {
1504 SkPath shape;
1505 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001506 SkIntToScalar(device->width()),
1507 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001508 content.setShape(shape);
1509 }
1510 if (!content.needSource()) {
1511 return;
1512 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001513
halcanary4b1e17e2016-07-27 14:49:46 -07001514 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001515 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001516 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001517}
1518
reede8f30622016-03-23 18:59:25 -07001519sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1520 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001521}
1522
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001523
halcanary8103a342016-03-08 15:10:16 -08001524sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001525 SkTDArray<SkPDFObject*> fonts;
1526 fonts.setReserve(fFontResources.count());
1527 for (SkPDFFont* font : fFontResources) {
1528 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001529 }
halcanary8103a342016-03-08 15:10:16 -08001530 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001531 &fGraphicStateResources,
1532 &fShaderResources,
1533 &fXObjectResources,
1534 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001535}
1536
halcanary8103a342016-03-08 15:10:16 -08001537sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001538 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001539 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001540 mediaBox->appendInt(0);
1541 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001542 mediaBox->appendInt(fPageSize.width());
1543 mediaBox->appendInt(fPageSize.height());
1544 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001545}
1546
mtklein5f939ab2016-03-16 10:28:35 -07001547std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001548 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001549 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001550 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001551 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001552
Hal Canary6d673962017-02-22 17:16:59 -05001553 GraphicStackState gsState(fExistingClipStack, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001554 for (const auto& entry : fContentEntries) {
Hal Canary6d673962017-02-22 17:16:59 -05001555 gsState.updateClip(entry.fState.fClipStack,
Mike Reeda1361362017-03-07 09:37:29 -05001556 {0, 0}, SkRect::Make(size(*this)));
halcanary2be7e012016-03-28 11:58:08 -07001557 gsState.updateMatrix(entry.fState.fMatrix);
1558 gsState.updateDrawingState(entry.fState);
1559
halcanaryafdc1772016-08-23 09:02:12 -07001560 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001561 }
1562 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001563 if (buffer.bytesWritten() > 0) {
1564 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1565 } else {
1566 return skstd::make_unique<SkMemoryStream>();
1567 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001568}
1569
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001570/* Draws an inverse filled path by using Path Ops to compute the positive
1571 * inverse using the current clip as the inverse bounds.
1572 * Return true if this was an inverse path and was properly handled,
1573 * otherwise returns false and the normal drawing routine should continue,
1574 * either as a (incorrect) fallback or because the path was not inverse
1575 * in the first place.
1576 */
Mike Reeda1361362017-03-07 09:37:29 -05001577bool SkPDFDevice::handleInversePath(const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001578 const SkPaint& paint, bool pathIsMutable,
1579 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001580 if (!origPath.isInverseFillType()) {
1581 return false;
1582 }
1583
Mike Reeda1361362017-03-07 09:37:29 -05001584 if (this->cs().isEmpty(size(*this))) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001585 return false;
1586 }
1587
1588 SkPath modifiedPath;
1589 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1590 SkPaint noInversePaint(paint);
1591
1592 // Merge stroking operations into final path.
1593 if (SkPaint::kStroke_Style == paint.getStyle() ||
1594 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1595 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1596 if (doFillPath) {
1597 noInversePaint.setStyle(SkPaint::kFill_Style);
1598 noInversePaint.setStrokeWidth(0);
1599 pathPtr = &modifiedPath;
1600 } else {
1601 // To be consistent with the raster output, hairline strokes
1602 // are rendered as non-inverted.
1603 modifiedPath.toggleInverseFillType();
Mike Reeda1361362017-03-07 09:37:29 -05001604 this->drawPath(modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001605 return true;
1606 }
1607 }
1608
1609 // Get bounds of clip in current transform space
1610 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001611 SkMatrix transformInverse;
Mike Reeda1361362017-03-07 09:37:29 -05001612 SkMatrix totalMatrix = this->ctm();
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001613 if (prePathMatrix) {
1614 totalMatrix.preConcat(*prePathMatrix);
1615 }
1616 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001617 return false;
1618 }
Mike Reeda1361362017-03-07 09:37:29 -05001619 SkRect bounds = this->cs().bounds(size(*this));
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001620 transformInverse.mapRect(&bounds);
1621
1622 // Extend the bounds by the line width (plus some padding)
1623 // so the edge doesn't cause a visible stroke.
1624 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1625 paint.getStrokeWidth() + SK_Scalar1);
1626
1627 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1628 return false;
1629 }
1630
Mike Reeda1361362017-03-07 09:37:29 -05001631 this->drawPath(modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001632 return true;
1633}
1634
wangxianzhuef6c50a2015-09-17 20:38:02 -07001635void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1636 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001637 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001638 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001639 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001640 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001641 }
halcanary91fcb3e2016-03-04 13:53:22 -08001642 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001643 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001644 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001645 array->appendObject(
1646 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001647 }
1648}
epoger@google.comb58772f2013-03-08 09:09:10 +00001649
halcanary6d622702015-03-25 08:45:42 -07001650void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001651 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001652 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001653 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001654 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001655 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001656 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001657 pdfDest->appendScalar(p.x());
1658 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001659 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001660 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001661 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001662 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001663}
1664
halcanary4b1e17e2016-07-27 14:49:46 -07001665sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
halcanary5abbb442016-07-29 08:41:33 -07001666 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001667 if (!fInitialTransform.isIdentity()) {
1668 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001669 SkDEBUGFAIL("Layer initial transform should be invertible.");
1670 inverseTransform.reset();
1671 }
1672 }
halcanary4b1e17e2016-07-27 14:49:46 -07001673 sk_sp<SkPDFObject> xobject =
1674 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
halcanary5abbb442016-07-29 08:41:33 -07001675 this->makeResourceDict(), inverseTransform, nullptr);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001676 // We always draw the form xobjects that we create back into the device, so
1677 // we simply preserve the font usage instead of pulling it out and merging
1678 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001679 this->cleanUp(); // Reset this device to have no content.
1680 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001681 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001682}
1683
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001684void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001685 sk_sp<SkPDFObject> mask,
Mike Reeda1361362017-03-07 09:37:29 -05001686 const SkClipStack& clipStack,
reed374772b2016-10-05 17:33:02 -07001687 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001688 bool invertClip) {
Mike Reeda1361362017-03-07 09:37:29 -05001689 if (!invertClip && clipStack.isEmpty(size(*this))) {
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001690 return;
1691 }
1692
halcanary4b1e17e2016-07-27 14:49:46 -07001693 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001694 std::move(mask), invertClip,
1695 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001696
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001697 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001698 paint.setBlendMode(mode);
Mike Reeda1361362017-03-07 09:37:29 -05001699 ScopedContentEntry content(this, clipStack, SkMatrix::I(), paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001700 if (!content.entry()) {
1701 return;
1702 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001703 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001704 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001705 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001706
halcanary1437c1e2016-03-13 18:30:24 -07001707 // Call makeNoSmaskGraphicState() instead of
1708 // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1709 // can deduplicate.
halcanary989da4a2016-03-21 14:33:17 -07001710 sMaskGS = fDocument->canon()->makeNoSmaskGraphicState();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001711 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001712 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001713}
1714
Mike Reeda1361362017-03-07 09:37:29 -05001715SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack& clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001716 const SkMatrix& matrix,
1717 const SkPaint& paint,
1718 bool hasText,
1719 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001720 *dst = nullptr;
reed374772b2016-10-05 17:33:02 -07001721 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001722
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001723 // For the following modes, we want to handle source and destination
1724 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001725 if (blendMode == SkBlendMode::kClear ||
1726 blendMode == SkBlendMode::kSrc ||
1727 blendMode == SkBlendMode::kSrcIn ||
1728 blendMode == SkBlendMode::kDstIn ||
1729 blendMode == SkBlendMode::kSrcOut ||
1730 blendMode == SkBlendMode::kDstOut ||
1731 blendMode == SkBlendMode::kSrcATop ||
1732 blendMode == SkBlendMode::kDstATop ||
1733 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001734 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001735 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001736 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001737 } else if (blendMode != SkBlendMode::kSrc &&
1738 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001739 // Except for Src and SrcOut, if there isn't anything already there,
1740 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001741 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001742 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001743 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001744 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001745 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001746
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001747 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001748 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001749 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001750 }
1751
halcanary2be7e012016-03-28 11:58:08 -07001752 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001753 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001754 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001755 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001756 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001757 } else {
halcanary2be7e012016-03-28 11:58:08 -07001758 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001759 }
Mike Reeda1361362017-03-07 09:37:29 -05001760 populateGraphicStateEntryFromPaint(matrix, clipStack, paint, hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001761 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001762}
1763
reed374772b2016-10-05 17:33:02 -07001764void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001765 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001766 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001767 if (blendMode != SkBlendMode::kClear &&
1768 blendMode != SkBlendMode::kSrc &&
1769 blendMode != SkBlendMode::kDstOver &&
1770 blendMode != SkBlendMode::kSrcIn &&
1771 blendMode != SkBlendMode::kDstIn &&
1772 blendMode != SkBlendMode::kSrcOut &&
1773 blendMode != SkBlendMode::kDstOut &&
1774 blendMode != SkBlendMode::kSrcATop &&
1775 blendMode != SkBlendMode::kDstATop &&
1776 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001777 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001778 return;
1779 }
reed374772b2016-10-05 17:33:02 -07001780 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001781 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00001782 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001783 // For DstOver, an empty content entry was inserted before the rest
1784 // of the content entries. If nothing was drawn, it needs to be
1785 // removed.
halcanary2be7e012016-03-28 11:58:08 -07001786 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001787 }
1788 return;
1789 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001790 if (!dst) {
reed374772b2016-10-05 17:33:02 -07001791 SkASSERT(blendMode == SkBlendMode::kSrc ||
1792 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001793 return;
1794 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001795
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001796 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07001797 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001798 // Changing the current content into a form-xobject will destroy the clip
1799 // objects which is fine since the xobject will already be clipped. However
1800 // if source has shape, we need to clip it too, so a copy of the clip is
1801 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001802
1803 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001804
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001805 SkPaint stockPaint;
1806
halcanary4b1e17e2016-07-27 14:49:46 -07001807 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001808 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001809 // If nothing was drawn and there's no shape, then the draw was a
1810 // no-op, but dst needs to be restored for that to be true.
1811 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1812 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1813 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07001814 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1815 blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001816 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07001817 // TODO: addXObjectResource take sk_sp
1818 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001819 &content.entry()->fContent);
1820 return;
1821 } else {
reed374772b2016-10-05 17:33:02 -07001822 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001823 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001824 } else {
halcanary2be7e012016-03-28 11:58:08 -07001825 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07001826 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001827 }
1828
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001829 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1830 // without alpha.
reed374772b2016-10-05 17:33:02 -07001831 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001832 // TODO(vandebo): In order to properly support SrcATop we have to track
1833 // the shape of what's been drawn at all times. It's the intersection of
1834 // the non-transparent parts of the device and the outlines (shape) of
1835 // all images and devices drawn.
1836 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
Mike Reeda1361362017-03-07 09:37:29 -05001837 fExistingClipStack, SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001838 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001839 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001840 // Draw shape into a form-xobject.
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001841 SkPaint filledPaint;
1842 filledPaint.setColor(SK_ColorBLACK);
1843 filledPaint.setStyle(SkPaint::kFill_Style);
Mike Reeda1361362017-03-07 09:37:29 -05001844 this->internalDrawPath(clipStack, SkMatrix::I(), *shape, filledPaint, nullptr, true);
1845 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
1846 this->makeFormXObjectFromDevice(),
1847 fExistingClipStack,
1848 SkBlendMode::kSrcOver, true);
halcanarydabd4f02016-08-03 11:16:56 -07001849 } else {
Mike Reeda1361362017-03-07 09:37:29 -05001850 this->drawFormXObjectWithMask(this->addXObjectResource(dst.get()),
1851 srcFormXObject,
1852 fExistingClipStack,
1853 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001854 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001855 }
1856
reed374772b2016-10-05 17:33:02 -07001857 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001858 return;
reed374772b2016-10-05 17:33:02 -07001859 } else if (blendMode == SkBlendMode::kSrc ||
1860 blendMode == SkBlendMode::kDstATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001861 ScopedContentEntry content(this, fExistingClipStack, SkMatrix::I(), stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001862 if (content.entry()) {
1863 SkPDFUtils::DrawFormXObject(
1864 this->addXObjectResource(srcFormXObject.get()),
1865 &content.entry()->fContent);
1866 }
reed374772b2016-10-05 17:33:02 -07001867 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001868 return;
1869 }
reed374772b2016-10-05 17:33:02 -07001870 } else if (blendMode == SkBlendMode::kSrcATop) {
Mike Reeda1361362017-03-07 09:37:29 -05001871 ScopedContentEntry content(this, fExistingClipStack,
1872 SkMatrix::I(), stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001873 if (content.entry()) {
halcanarydabd4f02016-08-03 11:16:56 -07001874 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001875 &content.entry()->fContent);
1876 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001877 }
1878
reed374772b2016-10-05 17:33:02 -07001879 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
1880 blendMode == SkBlendMode::kDstIn ||
1881 blendMode == SkBlendMode::kSrcOut ||
1882 blendMode == SkBlendMode::kDstOut ||
1883 blendMode == SkBlendMode::kSrcATop ||
1884 blendMode == SkBlendMode::kDstATop ||
1885 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001886
reed374772b2016-10-05 17:33:02 -07001887 if (blendMode == SkBlendMode::kSrcIn ||
1888 blendMode == SkBlendMode::kSrcOut ||
1889 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07001890 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1891 std::move(dst),
Mike Reeda1361362017-03-07 09:37:29 -05001892 fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07001893 SkBlendMode::kSrcOver,
1894 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07001895 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001896 } else {
reed374772b2016-10-05 17:33:02 -07001897 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07001898 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07001899 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001900 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
Mike Reeda1361362017-03-07 09:37:29 -05001901 std::move(dst), fExistingClipStack,
reed374772b2016-10-05 17:33:02 -07001902 SkBlendMode::kSrcOver, false);
1903 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001904 }
halcanarydabd4f02016-08-03 11:16:56 -07001905 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
Mike Reeda1361362017-03-07 09:37:29 -05001906 fExistingClipStack, mode,
reed374772b2016-10-05 17:33:02 -07001907 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07001908 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001909 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001910}
1911
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001912bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00001913 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001914 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001915 return true;
1916 }
1917 return false;
1918}
1919
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001920void SkPDFDevice::populateGraphicStateEntryFromPaint(
1921 const SkMatrix& matrix,
1922 const SkClipStack& clipStack,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001923 const SkPaint& paint,
1924 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07001925 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07001926 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1927 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1928 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001929
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001930 entry->fMatrix = matrix;
1931 entry->fClipStack = clipStack;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001932 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1933 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001934
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001935 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08001936 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07001937 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001938 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001939 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05001940 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1941 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001942 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05001943 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001944 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07001945 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001946 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05001947 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1948 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1949 color = gradientColor;
1950 } else {
1951 // PDF positions patterns relative to the initial transform, so
1952 // we need to apply the current transform to the shader parameters.
1953 SkMatrix transform = matrix;
1954 transform.postConcat(fInitialTransform);
1955
1956 // PDF doesn't support kClamp_TileMode, so we simulate it by making
1957 // a pattern the size of the current clip.
Mike Reeda1361362017-03-07 09:37:29 -05001958 SkRect clipStackBounds = clipStack.bounds(size(*this));
Hal Canaryc8f91802017-02-12 20:29:12 -05001959
1960 // We need to apply the initial transform to bounds in order to get
1961 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05001962 fInitialTransform.mapRect(&clipStackBounds);
1963 SkIRect bounds;
1964 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05001965
1966 SkScalar rasterScale =
1967 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
1968 pdfShader = SkPDFShader::GetPDFShader(
1969 fDocument, fRasterDpi, shader, transform, bounds, rasterScale);
1970
1971 if (pdfShader.get()) {
1972 // pdfShader has been canonicalized so we can directly compare
1973 // pointers.
1974 int resourceIndex = fShaderResources.find(pdfShader.get());
1975 if (resourceIndex < 0) {
1976 resourceIndex = fShaderResources.count();
1977 fShaderResources.push(pdfShader.get());
1978 pdfShader.get()->ref();
1979 }
1980 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001981 }
1982 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001983 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001984
halcanary48810a02016-03-07 14:57:50 -08001985 sk_sp<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001986 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001987 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07001988 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001989 } else {
1990 SkPaint newPaint = paint;
1991 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001992 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07001993 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001994 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001995 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001996 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001997
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001998 if (hasText) {
1999 entry->fTextScaleX = paint.getTextScaleX();
2000 entry->fTextFill = paint.getStyle();
2001 } else {
2002 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002003 }
2004}
2005
halcanarybe27a112015-04-01 13:31:19 -07002006int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002007 // Assumes that gs has been canonicalized (so we can directly compare
2008 // pointers).
2009 int result = fGraphicStateResources.find(gs);
2010 if (result < 0) {
2011 result = fGraphicStateResources.count();
2012 fGraphicStateResources.push(gs);
2013 gs->ref();
2014 }
2015 return result;
2016}
2017
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002018int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002019 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002020 // Assumes that xobject has been canonicalized (so we can directly compare
2021 // pointers).
2022 int result = fXObjectResources.find(xObject);
2023 if (result < 0) {
2024 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002025 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002026 }
2027 return result;
2028}
2029
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002030int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary48810a02016-03-07 14:57:50 -08002031 sk_sp<SkPDFFont> newFont(
halcanary989da4a2016-03-21 14:33:17 -07002032 SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID));
halcanary7e8d5d32016-08-12 07:59:38 -07002033 if (!newFont) {
2034 return -1;
2035 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002036 int resourceIndex = fFontResources.find(newFont.get());
2037 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002038 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002039 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002040 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002041 }
2042 return resourceIndex;
2043}
2044
Hal Canaryfafe1352017-04-11 12:12:02 -04002045static SkSize rect_to_size(const SkRect& r) { return {r.width(), r.height()}; }
halcanary7a14b312015-10-01 07:28:13 -07002046
Hal Canaryf50ff392016-09-30 10:25:39 -04002047static sk_sp<SkImage> color_filter(const SkImageSubset& imageSubset,
halcanarya50151d2016-03-25 11:57:49 -07002048 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002049 auto surface =
Hal Canaryf50ff392016-09-30 10:25:39 -04002050 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07002051 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002052 SkCanvas* canvas = surface->getCanvas();
2053 canvas->clear(SK_ColorTRANSPARENT);
2054 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002055 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canaryf50ff392016-09-30 10:25:39 -04002056 imageSubset.draw(canvas, &paint);
halcanary7a14b312015-10-01 07:28:13 -07002057 canvas->flush();
halcanarya50151d2016-03-25 11:57:49 -07002058 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002059}
2060
2061////////////////////////////////////////////////////////////////////////////////
2062void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
Mike Reeda1361362017-03-07 09:37:29 -05002063 const SkClipStack& clipStack,
Hal Canaryf50ff392016-09-30 10:25:39 -04002064 SkImageSubset imageSubset,
halcanary7a14b312015-10-01 07:28:13 -07002065 const SkPaint& paint) {
Hal Canaryf50ff392016-09-30 10:25:39 -04002066 if (imageSubset.dimensions().isZero()) {
halcanarya50151d2016-03-25 11:57:49 -07002067 return;
2068 }
halcanary7a14b312015-10-01 07:28:13 -07002069 #ifdef SK_PDF_IMAGE_STATS
2070 gDrawImageCalls.fetch_add(1);
2071 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002072 SkMatrix matrix = origMatrix;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002073
2074 // Rasterize the bitmap using perspective in a new bitmap.
2075 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002076 if (fRasterDpi == 0) {
2077 return;
2078 }
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002079 // Transform the bitmap in the new space, without taking into
2080 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002081 SkPath perspectiveOutline;
Hal Canaryf50ff392016-09-30 10:25:39 -04002082 SkRect imageBounds = SkRect::Make(imageSubset.bounds());
halcanary7a14b312015-10-01 07:28:13 -07002083 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002084 perspectiveOutline.transform(origMatrix);
2085
2086 // TODO(edisonn): perf - use current clip too.
2087 // Retrieve the bounds of the new shape.
2088 SkRect bounds = perspectiveOutline.getBounds();
2089
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002090 // Transform the bitmap in the new space, taking into
2091 // account the initial transform.
2092 SkMatrix total = origMatrix;
2093 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002094 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2095 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2096 total.postScale(dpiScale, dpiScale);
2097
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002098 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002099 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002100 physicalPerspectiveOutline.transform(total);
2101
halcanary7a14b312015-10-01 07:28:13 -07002102 SkRect physicalPerspectiveBounds =
2103 physicalPerspectiveOutline.getBounds();
2104 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2105 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002106
2107 // TODO(edisonn): A better approach would be to use a bitmap shader
2108 // (in clamp mode) and draw a rect over the entire bounding box. Then
2109 // intersect perspectiveOutline to the clip. That will avoid introducing
2110 // alpha to the image while still giving good behavior at the edge of
2111 // the image. Avoiding alpha will reduce the pdf size and generation
2112 // CPU time some.
2113
halcanary7a14b312015-10-01 07:28:13 -07002114 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2115
Hal Canaryf50ff392016-09-30 10:25:39 -04002116 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002117 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002118 return;
2119 }
halcanary7a14b312015-10-01 07:28:13 -07002120 SkCanvas* canvas = surface->getCanvas();
2121 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002122
2123 SkScalar deltaX = bounds.left();
2124 SkScalar deltaY = bounds.top();
2125
2126 SkMatrix offsetMatrix = origMatrix;
2127 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002128 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002129
2130 // Translate the draw in the new canvas, so we perfectly fit the
2131 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002132 canvas->setMatrix(offsetMatrix);
Hal Canaryf50ff392016-09-30 10:25:39 -04002133 imageSubset.draw(canvas, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002134 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002135 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002136
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002137 // In the new space, we use the identity matrix translated
2138 // and scaled to reflect DPI.
2139 matrix.setScale(1 / scaleX, 1 / scaleY);
2140 matrix.postTranslate(deltaX, deltaY);
2141
Hal Canaryf50ff392016-09-30 10:25:39 -04002142 imageSubset = SkImageSubset(surface->makeImageSnapshot());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002143 }
2144
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002145 SkMatrix scaled;
2146 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002147 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2148 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002149 // Scale the image up from 1x1 to WxH.
Hal Canaryf50ff392016-09-30 10:25:39 -04002150 SkIRect subset = imageSubset.bounds();
2151 scaled.postScale(SkIntToScalar(imageSubset.dimensions().width()),
2152 SkIntToScalar(imageSubset.dimensions().height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002153 scaled.postConcat(matrix);
Hal Canary6d673962017-02-22 17:16:59 -05002154 ScopedContentEntry content(this, clipStack, scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002155 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002156 return;
2157 }
2158 if (content.needShape()) {
2159 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002160 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002161 shape.transform(matrix);
2162 content.setShape(shape);
2163 }
2164 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002165 return;
2166 }
2167
halcanary287d22d2015-09-24 10:20:05 -07002168 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002169 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002170 // draw calls. This code here works for all
2171 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2172 // rasterize a layer on this backend). Fortuanely, this seems
2173 // to be how Chromium impements most color-filters.
Hal Canaryf50ff392016-09-30 10:25:39 -04002174 sk_sp<SkImage> img = color_filter(imageSubset, colorFilter);
2175 imageSubset = SkImageSubset(std::move(img));
halcanary7a14b312015-10-01 07:28:13 -07002176 // TODO(halcanary): de-dupe this by caching filtered images.
2177 // (maybe in the resource cache?)
2178 }
halcanarya50151d2016-03-25 11:57:49 -07002179
Hal Canaryf50ff392016-09-30 10:25:39 -04002180 SkBitmapKey key = imageSubset.getKey();
halcanarya50151d2016-03-25 11:57:49 -07002181 sk_sp<SkPDFObject> pdfimage = fDocument->canon()->findPDFBitmap(key);
halcanary7a14b312015-10-01 07:28:13 -07002182 if (!pdfimage) {
Hal Canaryf50ff392016-09-30 10:25:39 -04002183 sk_sp<SkImage> img = imageSubset.makeImage();
halcanarya50151d2016-03-25 11:57:49 -07002184 if (!img) {
2185 return;
2186 }
2187 pdfimage = SkPDFCreateBitmapObject(
2188 std::move(img), fDocument->canon()->getPixelSerializer());
halcanary7a14b312015-10-01 07:28:13 -07002189 if (!pdfimage) {
2190 return;
halcanary287d22d2015-09-24 10:20:05 -07002191 }
halcanarya50151d2016-03-25 11:57:49 -07002192 fDocument->serialize(pdfimage); // serialize images early.
2193 fDocument->canon()->addPDFBitmap(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002194 }
halcanarya50151d2016-03-25 11:57:49 -07002195 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
halcanary3d8c33c2015-10-01 11:06:22 -07002196 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002197 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002198}
reede51c3562016-07-19 14:33:20 -07002199
2200///////////////////////////////////////////////////////////////////////////////////////////////////
2201
2202#include "SkSpecialImage.h"
2203#include "SkImageFilter.h"
2204
Florin Malita53f77bd2017-04-28 13:48:37 -04002205void SkPDFDevice::drawSpecial(SkSpecialImage* srcImg, int x, int y, const SkPaint& paint,
2206 SkImage* clipImage, const SkMatrix& clipMatrix) {
reede51c3562016-07-19 14:33:20 -07002207 SkASSERT(!srcImg->isTextureBacked());
2208
Florin Malita53f77bd2017-04-28 13:48:37 -04002209 //TODO: clipImage support
2210
reede51c3562016-07-19 14:33:20 -07002211 SkBitmap resultBM;
2212
2213 SkImageFilter* filter = paint.getImageFilter();
2214 if (filter) {
2215 SkIPoint offset = SkIPoint::Make(0, 0);
Mike Reeda1361362017-03-07 09:37:29 -05002216 SkMatrix matrix = this->ctm();
reede51c3562016-07-19 14:33:20 -07002217 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002218 const SkIRect clipBounds =
Mike Reeda1361362017-03-07 09:37:29 -05002219 this->cs().bounds(this->imageInfo().bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002220 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
brianosman2a75e5d2016-09-22 07:15:37 -07002221 // TODO: Should PDF be operating in a specified color space? For now, run the filter
2222 // in the same color space as the source (this is different from all other backends).
2223 SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2224 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002225
2226 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2227 if (resultImg) {
2228 SkPaint tmpUnfiltered(paint);
2229 tmpUnfiltered.setImageFilter(nullptr);
2230 if (resultImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002231 this->drawSprite(resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
reede51c3562016-07-19 14:33:20 -07002232 }
2233 }
2234 } else {
2235 if (srcImg->getROPixels(&resultBM)) {
Mike Reeda1361362017-03-07 09:37:29 -05002236 this->drawSprite(resultBM, x, y, paint);
reede51c3562016-07-19 14:33:20 -07002237 }
2238 }
2239}
2240
2241sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2242 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2243}
2244
2245sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002246 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2247 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2248 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002249 SkColorSpace* legacyColorSpace = nullptr;
reede51c3562016-07-19 14:33:20 -07002250 return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
Brian Osman61624f02016-12-09 14:51:59 -05002251 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002252}
2253
2254sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002255 return nullptr;
2256}
brianosman04a44d02016-09-21 09:46:57 -07002257
2258SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2259 // We always return a transient cache, so it is freed after each
2260 // filter traversal.
2261 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2262}