blob: dbe4c84da0d5836a3479452c3354f7ebb13361be [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
reed374772b2016-10-05 17:33:02 -070051// If the paint will definitely draw opaquely, replace kSrc with
52// kSrcOver. http://crbug.com/473572
halcanarya6814332015-05-27 08:53:36 -070053static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
reed374772b2016-10-05 17:33:02 -070054 if (kSrcOver_SkXfermodeInterpretation == SkInterpretXfermode(*paint, false)) {
55 paint->setBlendMode(SkBlendMode::kSrcOver);
halcanarya6814332015-05-27 08:53:36 -070056 }
57}
58
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000059static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000060 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -070061 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000062 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -070063 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000064 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -070065 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000066 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000067}
68
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000069static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000070 SkPaint result = paint;
71 if (result.isFakeBoldText()) {
72 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
73 kStdFakeBoldInterpKeys,
74 kStdFakeBoldInterpValues,
75 kStdFakeBoldInterpLength);
Mike Reed8be952a2017-02-13 20:44:33 -050076 SkScalar width = result.getTextSize() * fakeBoldScale;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000077 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000078 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000079 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000080 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000081 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000082 result.setStrokeWidth(width);
83 }
84 return result;
85}
86
Hal Canaryf50ff392016-09-30 10:25:39 -040087static SkImageSubset make_image_subset(const SkBitmap& bitmap) {
88 SkASSERT(!bitmap.drawsNothing());
89 SkIRect subset = bitmap.getSubset();
90 SkAutoLockPixels autoLockPixels(bitmap);
91 SkASSERT(bitmap.pixelRef());
92 SkBitmap tmp;
93 tmp.setInfo(bitmap.pixelRef()->info(), bitmap.rowBytes());
Hal Canary1b3387b2016-12-12 13:48:12 -050094 tmp.setPixelRef(sk_ref_sp(bitmap.pixelRef()), 0, 0);
Hal Canaryf50ff392016-09-30 10:25:39 -040095 tmp.lockPixels();
96 auto img = SkImage::MakeFromBitmap(tmp);
97 if (img) {
98 SkASSERT(!bitmap.isImmutable() || img->uniqueID() == bitmap.getGenerationID());
99 SkASSERT(img->bounds().contains(subset));
100 }
101 SkImageSubset imageSubset(std::move(img), subset);
102 // SkImage::MakeFromBitmap only preserves genID for immutable
103 // bitmaps. Use the bitmap's original ID for de-duping.
104 imageSubset.setID(bitmap.getGenerationID());
105 return imageSubset;
106}
107
halcanary2be7e012016-03-28 11:58:08 -0700108SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
109 : fColor(SK_ColorBLACK)
110 , fTextScaleX(SK_Scalar1)
111 , fTextFill(SkPaint::kFill_Style)
112 , fShaderIndex(-1)
halcanaryc2f9ec12016-09-12 08:55:29 -0700113 , fGraphicStateIndex(-1) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000114 fMatrix.reset();
115}
116
halcanary2be7e012016-03-28 11:58:08 -0700117bool SkPDFDevice::GraphicStateEntry::compareInitialState(
118 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000119 return fColor == cur.fColor &&
120 fShaderIndex == cur.fShaderIndex &&
121 fGraphicStateIndex == cur.fGraphicStateIndex &&
122 fMatrix == cur.fMatrix &&
123 fClipStack == cur.fClipStack &&
124 (fTextScaleX == 0 ||
125 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000126}
127
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000128class GraphicStackState {
129public:
130 GraphicStackState(const SkClipStack& existingClipStack,
131 const SkRegion& existingClipRegion,
132 SkWStream* contentStream)
133 : fStackDepth(0),
134 fContentStream(contentStream) {
135 fEntries[0].fClipStack = existingClipStack;
136 fEntries[0].fClipRegion = existingClipRegion;
137 }
138
139 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
Hal Canary44a97d52017-02-22 10:45:25 -0500140 const SkPoint& translation, const SkRect& bounds);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000141 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700142 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000143
144 void drainStack();
145
146private:
147 void push();
148 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700149 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000150
151 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
152 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700153 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000154 int fStackDepth;
155 SkWStream* fContentStream;
156};
157
158void GraphicStackState::drainStack() {
159 while (fStackDepth) {
160 pop();
161 }
162}
163
164void GraphicStackState::push() {
165 SkASSERT(fStackDepth < kMaxStackDepth);
166 fContentStream->writeText("q\n");
167 fStackDepth++;
168 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
169}
170
171void GraphicStackState::pop() {
172 SkASSERT(fStackDepth > 0);
173 fContentStream->writeText("Q\n");
174 fStackDepth--;
175}
176
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000177/* Calculate an inverted path's equivalent non-inverted path, given the
178 * canvas bounds.
179 * outPath may alias with invPath (since this is supported by PathOps).
180 */
181static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
182 SkPath* outPath) {
183 SkASSERT(invPath.isInverseFillType());
184
185 SkPath clipPath;
186 clipPath.addRect(bounds);
187
reedcdb42bb2015-06-26 10:23:07 -0700188 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000189}
190
Hal Canary44a97d52017-02-22 10:45:25 -0500191bool apply_clip(SkClipOp op, const SkPath& u, const SkPath& v, SkPath* r) {
192 switch (op) {
193 case SkClipOp::kDifference:
194 return Op(u, v, kDifference_SkPathOp, r);
195 case SkClipOp::kIntersect:
196 return Op(u, v, kIntersect_SkPathOp, r);
197 case SkClipOp::kUnion_deprecated:
198 return Op(u, v, kUnion_SkPathOp, r);
199 case SkClipOp::kXOR_deprecated:
200 return Op(u, v, kXOR_SkPathOp, r);
201 case SkClipOp::kReverseDifference_deprecated:
202 return Op(u, v, kReverseDifference_SkPathOp, r);
203 case SkClipOp::kReplace_deprecated:
204 *r = v;
205 return true;
206 default:
207 return false;
208 }
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000209}
210
211/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
212 * Returns true if successful, or false if not successful.
213 * If successful, the resulting clip is stored in outClipPath.
214 * If not successful, outClipPath is undefined, and a fallback method
215 * should be used.
216 */
217static bool get_clip_stack_path(const SkMatrix& transform,
218 const SkClipStack& clipStack,
Hal Canary44a97d52017-02-22 10:45:25 -0500219 const SkRect& bounds,
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000220 SkPath* outClipPath) {
221 outClipPath->reset();
222 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
223
224 const SkClipStack::Element* clipEntry;
225 SkClipStack::Iter iter;
226 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
227 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
228 SkPath entryPath;
229 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
230 outClipPath->reset();
231 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
232 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000233 } else {
234 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000235 }
236 entryPath.transform(transform);
Hal Canary44a97d52017-02-22 10:45:25 -0500237 if (!apply_clip(clipEntry->getOp(), *outClipPath, entryPath, outClipPath)) {
238 return false;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000239 }
240 }
241
242 if (outClipPath->isInverseFillType()) {
243 // The bounds are slightly outset to ensure this is correct in the
244 // face of floating-point accuracy and possible SkRegion bitmap
245 // approximations.
Hal Canary44a97d52017-02-22 10:45:25 -0500246 SkRect clipBounds = bounds;
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000247 clipBounds.outset(SK_Scalar1, SK_Scalar1);
248 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
249 return false;
250 }
251 }
252 return true;
253}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000254
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000255// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000256// graphic state stack, and the fact that we can know all the clips used
257// on the page to optimize this.
258void GraphicStackState::updateClip(const SkClipStack& clipStack,
259 const SkRegion& clipRegion,
Hal Canary44a97d52017-02-22 10:45:25 -0500260 const SkPoint& translation,
261 const SkRect& bounds) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000262 if (clipStack == currentEntry()->fClipStack) {
263 return;
264 }
265
266 while (fStackDepth > 0) {
267 pop();
268 if (clipStack == currentEntry()->fClipStack) {
269 return;
270 }
271 }
272 push();
273
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000274 currentEntry()->fClipStack = clipStack;
275 currentEntry()->fClipRegion = clipRegion;
276
277 SkMatrix transform;
278 transform.setTranslate(translation.fX, translation.fY);
279
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000280 SkPath clipPath;
Hal Canary44a97d52017-02-22 10:45:25 -0500281 if (get_clip_stack_path(transform, clipStack, bounds, &clipPath)) {
halcanary5edf2902016-09-07 09:05:25 -0700282 SkPDFUtils::EmitPath(clipPath, SkPaint::kFill_Style, fContentStream);
283 SkPath::FillType clipFill = clipPath.getFillType();
284 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
285 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
286 if (clipFill == SkPath::kEvenOdd_FillType) {
287 fContentStream->writeText("W* n\n");
288 } else {
289 fContentStream->writeText("W n\n");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000290 }
291 }
halcanary5edf2902016-09-07 09:05:25 -0700292 // If Op() fails (pathological case; e.g. input values are
293 // extremely large or NaN), emit no clip at all.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000294}
295
296void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
297 if (matrix == currentEntry()->fMatrix) {
298 return;
299 }
300
301 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
302 SkASSERT(fStackDepth > 0);
303 SkASSERT(fEntries[fStackDepth].fClipStack ==
304 fEntries[fStackDepth -1].fClipStack);
305 pop();
306
307 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
308 }
309 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
310 return;
311 }
312
313 push();
314 SkPDFUtils::AppendTransform(matrix, fContentStream);
315 currentEntry()->fMatrix = matrix;
316}
317
halcanary2be7e012016-03-28 11:58:08 -0700318void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000319 // PDF treats a shader as a color, so we only set one or the other.
320 if (state.fShaderIndex >= 0) {
321 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000322 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000323 currentEntry()->fShaderIndex = state.fShaderIndex;
324 }
325 } else {
326 if (state.fColor != currentEntry()->fColor ||
327 currentEntry()->fShaderIndex >= 0) {
328 emit_pdf_color(state.fColor, fContentStream);
329 fContentStream->writeText("RG ");
330 emit_pdf_color(state.fColor, fContentStream);
331 fContentStream->writeText("rg\n");
332 currentEntry()->fColor = state.fColor;
333 currentEntry()->fShaderIndex = -1;
334 }
335 }
336
337 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000338 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000339 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
340 }
341
342 if (state.fTextScaleX) {
343 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
Mike Reed8be952a2017-02-13 20:44:33 -0500344 SkScalar pdfScale = state.fTextScaleX * 1000;
halcanarybc4696b2015-05-06 10:56:04 -0700345 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000346 fContentStream->writeText(" Tz\n");
347 currentEntry()->fTextScaleX = state.fTextScaleX;
348 }
349 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700350 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
351 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
352 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000353 fContentStream->writeDecAsText(state.fTextFill);
354 fContentStream->writeText(" Tr\n");
355 currentEntry()->fTextFill = state.fTextFill;
356 }
357 }
358}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000359
reed76033be2015-03-14 10:54:31 -0700360static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700361 // PDF does not support image filters, so render them on CPU.
362 // Note that this rendering is done at "screen" resolution (100dpi), not
363 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700364 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800365 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700366
367 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700368 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700369}
370
371SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700372 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700373 // need to return a raster device, which we will detect in drawDevice()
374 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700375 }
fmalita6987dca2014-11-13 08:33:37 -0800376 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanary989da4a2016-03-21 14:33:17 -0700377 return SkPDFDevice::Create(size, fRasterDpi, fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000378}
379
halcanary989da4a2016-03-21 14:33:17 -0700380SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
381
bsalomon@google.come97f0852011-06-17 13:10:25 +0000382
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000383
384// A helper class to automatically finish a ContentEntry at the end of a
385// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000386class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000387public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000388 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
389 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000390 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700391 fContentEntry(nullptr),
reed374772b2016-10-05 17:33:02 -0700392 fBlendMode(SkBlendMode::kSrcOver),
halcanary96fcdcc2015-08-27 07:41:13 -0700393 fDstFormXObject(nullptr) {
reed1e7f5e72016-04-27 07:49:17 -0700394 init(draw.fClipStack, draw.fRC->bwRgn(), *draw.fMatrix, paint, hasText);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000395 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000396 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
397 const SkRegion& clipRegion, const SkMatrix& matrix,
398 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000399 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700400 fContentEntry(nullptr),
reed374772b2016-10-05 17:33:02 -0700401 fBlendMode(SkBlendMode::kSrcOver),
halcanary96fcdcc2015-08-27 07:41:13 -0700402 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000403 init(clipStack, clipRegion, matrix, paint, hasText);
404 }
405
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000406 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000407 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000408 SkPath* shape = &fShape;
409 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700410 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000411 }
reed374772b2016-10-05 17:33:02 -0700412 fDevice->finishContentEntry(fBlendMode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000413 }
414 }
415
halcanary2be7e012016-03-28 11:58:08 -0700416 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000417
418 /* Returns true when we explicitly need the shape of the drawing. */
419 bool needShape() {
reed374772b2016-10-05 17:33:02 -0700420 switch (fBlendMode) {
421 case SkBlendMode::kClear:
422 case SkBlendMode::kSrc:
423 case SkBlendMode::kSrcIn:
424 case SkBlendMode::kSrcOut:
425 case SkBlendMode::kDstIn:
426 case SkBlendMode::kDstOut:
427 case SkBlendMode::kSrcATop:
428 case SkBlendMode::kDstATop:
429 case SkBlendMode::kModulate:
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000430 return true;
431 default:
432 return false;
433 }
434 }
435
436 /* Returns true unless we only need the shape of the drawing. */
437 bool needSource() {
reed374772b2016-10-05 17:33:02 -0700438 if (fBlendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000439 return false;
440 }
441 return true;
442 }
443
444 /* If the shape is different than the alpha component of the content, then
445 * setShape should be called with the shape. In particular, images and
446 * devices have rectangular shape.
447 */
448 void setShape(const SkPath& shape) {
449 fShape = shape;
450 }
451
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000452private:
453 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700454 SkPDFDevice::ContentEntry* fContentEntry;
reed374772b2016-10-05 17:33:02 -0700455 SkBlendMode fBlendMode;
halcanarydabd4f02016-08-03 11:16:56 -0700456 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000457 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000458
459 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
460 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000461 // Shape has to be flatten before we get here.
462 if (matrix.hasPerspective()) {
463 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000464 return;
465 }
reed374772b2016-10-05 17:33:02 -0700466 fBlendMode = paint.getBlendMode();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000467 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
468 matrix, paint, hasText,
469 &fDstFormXObject);
470 }
471};
472
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000473////////////////////////////////////////////////////////////////////////////////
474
halcanary989da4a2016-03-21 14:33:17 -0700475SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFDocument* doc, bool flip)
reed589a39e2016-08-20 07:59:19 -0700476 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
477 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700478 , fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800479 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
halcanarya1f1ee92015-02-20 06:17:26 -0800480 , fRasterDpi(rasterDpi)
halcanary989da4a2016-03-21 14:33:17 -0700481 , fDocument(doc) {
halcanarya1f1ee92015-02-20 06:17:26 -0800482 SkASSERT(pageSize.width() > 0);
483 SkASSERT(pageSize.height() > 0);
robertphillips1f3923e2016-07-21 07:17:54 -0700484
halcanarya1f1ee92015-02-20 06:17:26 -0800485 if (flip) {
486 // Skia generally uses the top left as the origin but PDF
487 // natively has the origin at the bottom left. This matrix
488 // corrects for that. But that only needs to be done once, we
489 // don't do it when layering.
490 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
491 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
492 } else {
493 fInitialTransform.setIdentity();
494 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000495}
496
497SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700498 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000499}
500
501void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700502 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000503}
504
halcanary3c35fb32016-06-30 11:55:07 -0700505void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000506 fGraphicStateResources.unrefAll();
507 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000508 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000509 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000510}
511
reedf70b5312016-03-04 16:36:20 -0800512void SkPDFDevice::drawAnnotation(const SkDraw& d, const SkRect& rect, const char key[],
513 SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -0500514 if (!value) {
515 return;
516 }
517 if (rect.isEmpty()) {
518 this->handlePointAnnotation({ rect.x(), rect.y() }, *d.fMatrix, key, value);
reedf70b5312016-03-04 16:36:20 -0800519 } else {
Hal Canary9cd21682017-02-22 15:55:06 -0500520 this->handleRectAnnotation(rect, d, key, value);
reedf70b5312016-03-04 16:36:20 -0800521 }
522}
523
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000524void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000525 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700526 replace_srcmode_on_opaque_paint(&newPaint);
527
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000528 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000529 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000530 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000531}
532
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000533void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700534 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000535 if (!contentEntry) {
536 return;
537 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000538 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
539 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000540 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000541 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000542 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000543 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000544 inverse.mapRect(&bbox);
545
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000546 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000547 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000548 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000549}
550
halcanary682ee012016-01-28 10:59:34 -0800551void SkPDFDevice::drawPoints(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700552 SkCanvas::PointMode mode,
553 size_t count,
554 const SkPoint* points,
555 const SkPaint& srcPaint) {
556 SkPaint passedPaint = srcPaint;
557 replace_srcmode_on_opaque_paint(&passedPaint);
558
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000559 if (count == 0) {
560 return;
561 }
562
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000563 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
564 // We only use this when there's a path effect because of the overhead
565 // of multiple calls to setUpContentEntry it causes.
566 if (passedPaint.getPathEffect()) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500567 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000568 return;
569 }
Mike Reed99330ba2017-02-22 11:01:08 -0500570 d.drawPoints(mode, count, points, passedPaint, this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000571 return;
572 }
573
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000574 const SkPaint* paint = &passedPaint;
575 SkPaint modifiedPaint;
576
577 if (mode == SkCanvas::kPoints_PointMode &&
578 paint->getStrokeCap() != SkPaint::kRound_Cap) {
579 modifiedPaint = *paint;
580 paint = &modifiedPaint;
581 if (paint->getStrokeWidth()) {
582 // PDF won't draw a single point with square/butt caps because the
583 // orientation is ambiguous. Draw a rectangle instead.
584 modifiedPaint.setStyle(SkPaint::kFill_Style);
585 SkScalar strokeWidth = paint->getStrokeWidth();
586 SkScalar halfStroke = SkScalarHalf(strokeWidth);
587 for (size_t i = 0; i < count; i++) {
588 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
589 r.inset(-halfStroke, -halfStroke);
590 drawRect(d, r, modifiedPaint);
591 }
592 return;
593 } else {
594 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
595 }
596 }
597
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000598 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000599 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000600 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000601 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000602
603 switch (mode) {
604 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000605 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000606 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000607 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000608 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000609 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000610 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000611 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000612 break;
613 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000614 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000615 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000616 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000617 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000618 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000619 &content.entry()->fContent);
620 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000621 }
622 break;
623 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000624 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
625 for (size_t i = 0; i < count; i++) {
626 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000627 &content.entry()->fContent);
628 SkPDFUtils::ClosePath(&content.entry()->fContent);
629 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000630 }
631 break;
632 default:
633 SkASSERT(false);
634 }
635}
636
halcanary8103a342016-03-08 15:10:16 -0800637static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800638 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700639 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700640 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700641
halcanaryece83922016-03-08 08:32:12 -0800642 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700643 border->reserve(3);
644 border->appendInt(0); // Horizontal corner radius.
645 border->appendInt(0); // Vertical corner radius.
646 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800647 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700648
halcanaryece83922016-03-08 08:32:12 -0800649 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700650 rect->reserve(4);
651 rect->appendScalar(translatedRect.fLeft);
652 rect->appendScalar(translatedRect.fTop);
653 rect->appendScalar(translatedRect.fRight);
654 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800655 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700656
halcanary8103a342016-03-08 15:10:16 -0800657 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700658}
659
halcanary8103a342016-03-08 15:10:16 -0800660static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700661 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700662 SkString url(static_cast<const char *>(urlData->data()),
663 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800664 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700665 action->insertName("S", "URI");
666 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800667 annotation->insertObject("A", std::move(action));
668 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700669}
670
halcanary8103a342016-03-08 15:10:16 -0800671static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
672 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700673 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700674 SkString name(static_cast<const char *>(nameData->data()),
675 nameData->size() - 1);
676 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800677 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700678}
679
halcanary682ee012016-01-28 10:59:34 -0800680void SkPDFDevice::drawRect(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700681 const SkRect& rect,
682 const SkPaint& srcPaint) {
683 SkPaint paint = srcPaint;
684 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000685 SkRect r = rect;
686 r.sort();
687
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000688 if (paint.getPathEffect()) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500689 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000690 return;
691 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000692 SkPath path;
693 path.addRect(r);
halcanary96fcdcc2015-08-27 07:41:13 -0700694 drawPath(d, path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000695 return;
696 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000697
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000698 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000699 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000700 return;
701 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000702 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000703 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000704 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000705}
706
halcanarya6814332015-05-27 08:53:36 -0700707void SkPDFDevice::drawRRect(const SkDraw& draw,
708 const SkRRect& rrect,
709 const SkPaint& srcPaint) {
710 SkPaint paint = srcPaint;
711 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000712 SkPath path;
713 path.addRRect(rrect);
halcanary96fcdcc2015-08-27 07:41:13 -0700714 this->drawPath(draw, path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000715}
716
halcanarya6814332015-05-27 08:53:36 -0700717void SkPDFDevice::drawOval(const SkDraw& draw,
718 const SkRect& oval,
719 const SkPaint& srcPaint) {
720 SkPaint paint = srcPaint;
721 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700722 SkPath path;
723 path.addOval(oval);
halcanary96fcdcc2015-08-27 07:41:13 -0700724 this->drawPath(draw, path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700725}
726
halcanary682ee012016-01-28 10:59:34 -0800727void SkPDFDevice::drawPath(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700728 const SkPath& origPath,
729 const SkPaint& srcPaint,
730 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000731 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700732 SkPaint paint = srcPaint;
733 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800734 SkPath modifiedPath;
735 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000736
737 SkMatrix matrix = *d.fMatrix;
738 if (prePathMatrix) {
739 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800740 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000741 pathPtr = &modifiedPath;
742 pathIsMutable = true;
743 }
halcanary682ee012016-01-28 10:59:34 -0800744 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000745 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000746 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000747 }
748 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000749
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000750 if (paint.getPathEffect()) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500751 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000752 return;
753 }
halcanary682ee012016-01-28 10:59:34 -0800754 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000755 pathPtr = &modifiedPath;
756 pathIsMutable = true;
757 }
halcanary682ee012016-01-28 10:59:34 -0800758 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000759
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000760 SkPaint noEffectPaint(paint);
halcanary96fcdcc2015-08-27 07:41:13 -0700761 noEffectPaint.setPathEffect(nullptr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000762 if (fill) {
763 noEffectPaint.setStyle(SkPaint::kFill_Style);
764 } else {
765 noEffectPaint.setStyle(SkPaint::kStroke_Style);
766 noEffectPaint.setStrokeWidth(0);
767 }
halcanary96fcdcc2015-08-27 07:41:13 -0700768 drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000769 return;
770 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000771
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000772 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000773 return;
774 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000775
reed1e7f5e72016-04-27 07:49:17 -0700776 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000777 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000778 return;
779 }
Hal Canary385468f2017-02-13 11:03:23 -0500780 SkScalar matrixScale = matrix.mapRadius(1.0f);
781 SkScalar tolerance = matrixScale > 0.0f ? 0.25f / matrixScale : 0.25f;
halcanary8b2bc252015-10-06 09:41:47 -0700782 bool consumeDegeratePathSegments =
783 paint.getStyle() == SkPaint::kFill_Style ||
784 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
785 paint.getStrokeCap() != SkPaint::kSquare_Cap);
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000786 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
halcanary8b2bc252015-10-06 09:41:47 -0700787 consumeDegeratePathSegments,
Hal Canary385468f2017-02-13 11:03:23 -0500788 &content.entry()->fContent,
789 tolerance);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000790 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000791 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000792}
793
Hal Canaryf50ff392016-09-30 10:25:39 -0400794
795void SkPDFDevice::drawImageRect(const SkDraw& d,
796 const SkImage* image,
797 const SkRect* src,
798 const SkRect& dst,
799 const SkPaint& srcPaint,
800 SkCanvas::SrcRectConstraint) {
801 if (!image) {
802 return;
803 }
804 SkIRect bounds = image->bounds();
805 SkPaint paint = srcPaint;
806 if (image->isOpaque()) {
807 replace_srcmode_on_opaque_paint(&paint);
808 }
809 SkRect srcRect = src ? *src : SkRect::Make(bounds);
810 SkMatrix transform;
811 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
812 if (src) {
813 if (!srcRect.intersect(SkRect::Make(bounds))) {
814 return;
815 }
816 srcRect.roundOut(&bounds);
817 transform.preTranslate(SkIntToScalar(bounds.x()),
818 SkIntToScalar(bounds.y()));
819 }
820 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)), bounds);
821 if (!imageSubset.isValid()) {
822 return;
823 }
824 transform.postConcat(*d.fMatrix);
825 this->internalDrawImage(transform, d.fClipStack, d.fRC->bwRgn(),
826 std::move(imageSubset), paint);
827}
828
829void SkPDFDevice::drawBitmapRect(const SkDraw& d,
halcanary7a14b312015-10-01 07:28:13 -0700830 const SkBitmap& bitmap,
831 const SkRect* src,
832 const SkRect& dst,
Hal Canaryf50ff392016-09-30 10:25:39 -0400833 const SkPaint& srcPaint,
834 SkCanvas::SrcRectConstraint) {
835 if (bitmap.drawsNothing()) {
836 return;
837 }
838 SkIRect bounds = bitmap.bounds();
839 SkPaint paint = srcPaint;
840 if (bitmap.isOpaque()) {
841 replace_srcmode_on_opaque_paint(&paint);
842 }
843 SkRect srcRect = src ? *src : SkRect::Make(bounds);
844 SkMatrix transform;
845 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
846 if (src) {
847 if (!srcRect.intersect(SkRect::Make(bounds))) {
848 return;
849 }
850 srcRect.roundOut(&bounds);
851 transform.preTranslate(SkIntToScalar(bounds.x()),
852 SkIntToScalar(bounds.y()));
853 }
854 SkBitmap bitmapSubset;
855 if (!bitmap.extractSubset(&bitmapSubset, bounds)) {
856 return;
857 }
858 SkImageSubset imageSubset = make_image_subset(bitmapSubset);
859 if (!imageSubset.isValid()) {
860 return;
861 }
862 transform.postConcat(*d.fMatrix);
863 this->internalDrawImage(transform, d.fClipStack, d.fRC->bwRgn(),
864 std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700865}
866
867void SkPDFDevice::drawBitmap(const SkDraw& d,
868 const SkBitmap& bitmap,
869 const SkMatrix& matrix,
870 const SkPaint& srcPaint) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500871 if (bitmap.drawsNothing() || d.fClipStack->isEmpty(this->getGlobalBounds())) {
Hal Canaryf50ff392016-09-30 10:25:39 -0400872 return;
873 }
halcanarya6814332015-05-27 08:53:36 -0700874 SkPaint paint = srcPaint;
875 if (bitmap.isOpaque()) {
876 replace_srcmode_on_opaque_paint(&paint);
877 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400878 SkImageSubset imageSubset = make_image_subset(bitmap);
879 if (!imageSubset.isValid()) {
halcanary7a14b312015-10-01 07:28:13 -0700880 return;
881 }
halcanary7a14b312015-10-01 07:28:13 -0700882 SkMatrix transform = matrix;
883 transform.postConcat(*d.fMatrix);
halcanarya50151d2016-03-25 11:57:49 -0700884 this->internalDrawImage(
Hal Canaryf50ff392016-09-30 10:25:39 -0400885 transform, d.fClipStack, d.fRC->bwRgn(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700886}
887
888void SkPDFDevice::drawSprite(const SkDraw& d,
889 const SkBitmap& bitmap,
890 int x,
891 int y,
892 const SkPaint& srcPaint) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500893 if (bitmap.drawsNothing() || d.fClipStack->isEmpty(this->getGlobalBounds())) {
Hal Canaryf50ff392016-09-30 10:25:39 -0400894 return;
895 }
halcanary7a14b312015-10-01 07:28:13 -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 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400904 SkMatrix transform = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
halcanarya50151d2016-03-25 11:57:49 -0700905 this->internalDrawImage(
Hal Canaryf50ff392016-09-30 10:25:39 -0400906 transform, d.fClipStack, d.fRC->bwRgn(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700907}
908
909void SkPDFDevice::drawImage(const SkDraw& draw,
910 const SkImage* image,
911 SkScalar x,
912 SkScalar y,
913 const SkPaint& srcPaint) {
914 SkPaint paint = srcPaint;
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500915 if (!image) {
halcanary7a14b312015-10-01 07:28:13 -0700916 return;
917 }
918 if (image->isOpaque()) {
919 replace_srcmode_on_opaque_paint(&paint);
920 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400921 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)));
922 if (!imageSubset.isValid()) {
923 return;
924 }
halcanary7a14b312015-10-01 07:28:13 -0700925 SkMatrix transform = SkMatrix::MakeTrans(x, y);
926 transform.postConcat(*draw.fMatrix);
halcanarya50151d2016-03-25 11:57:49 -0700927 this->internalDrawImage(
Hal Canaryf50ff392016-09-30 10:25:39 -0400928 transform, draw.fClipStack, draw.fRC->bwRgn(), std::move(imageSubset), paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000929}
930
halcanaryf0c30f52016-07-15 13:35:45 -0700931namespace {
932class GlyphPositioner {
933public:
934 GlyphPositioner(SkDynamicMemoryWStream* content,
935 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -0700936 bool wideChars,
937 bool defaultPositioning,
938 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -0700939 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -0700940 , fCurrentMatrixOrigin(origin)
941 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -0700942 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -0700943 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -0700944 }
halcanary4871f222016-08-26 13:17:44 -0700945 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -0700946 void flush() {
947 if (fInText) {
948 fContent->writeText("> Tj\n");
949 fInText = false;
950 }
951 }
halcanary4871f222016-08-26 13:17:44 -0700952 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -0700953 SkScalar advanceWidth,
954 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -0700955 if (!fInitialized) {
956 // Flip the text about the x-axis to account for origin swap and include
957 // the passed parameters.
958 fContent->writeText("1 0 ");
959 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
960 fContent->writeText(" -1 ");
961 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
962 fContent->writeText(" ");
963 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
964 fContent->writeText(" Tm\n");
965 fCurrentMatrixOrigin.set(0.0f, 0.0f);
966 fInitialized = true;
967 }
Hal Canary7bb93012016-10-31 12:40:49 -0400968#ifdef SK_BUILD_FOR_WIN
969 const bool kAlwaysPosition = true;
970#else
971 const bool kAlwaysPosition = false;
972#endif
halcanary4ed2f012016-08-15 18:40:07 -0700973 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -0700974 SkPoint position = xy - fCurrentMatrixOrigin;
Hal Canary7bb93012016-10-31 12:40:49 -0400975 if (kAlwaysPosition || position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -0700976 this->flush();
halcanary4871f222016-08-26 13:17:44 -0700977 SkPDFUtils::AppendScalar(position.x(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -0700978 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -0700979 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -0700980 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -0700981 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -0700982 fXAdvance = 0;
983 }
984 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -0700985 }
986 if (!fInText) {
987 fContent->writeText("<");
988 fInText = true;
989 }
990 if (fWideChars) {
991 SkPDFUtils::WriteUInt16BE(fContent, glyph);
992 } else {
993 SkASSERT(0 == glyph >> 8);
994 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
995 }
halcanaryf0c30f52016-07-15 13:35:45 -0700996 }
997
998private:
999 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -07001000 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001001 SkScalar fXAdvance = 0.0f;
1002 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001003 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001004 bool fInText = false;
1005 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -07001006 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001007};
halcanaryf59d18a2016-09-16 14:44:57 -07001008
1009/** Given the m-to-n glyph-to-character mapping data (as returned by
1010 harfbuzz), iterate over the clusters. */
1011class Clusterator {
1012public:
1013 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1014 explicit Clusterator(uint32_t glyphCount)
1015 : fClusters(nullptr)
1016 , fUtf8Text(nullptr)
1017 , fGlyphCount(glyphCount)
1018 , fTextByteLength(0) {}
1019 // The clusters[] array is an array of offsets into utf8Text[],
1020 // one offset for each glyph. See SkTextBlobBuilder for more info.
1021 Clusterator(const uint32_t* clusters,
1022 const char* utf8Text,
1023 uint32_t glyphCount,
1024 uint32_t textByteLength)
1025 : fClusters(clusters)
1026 , fUtf8Text(utf8Text)
1027 , fGlyphCount(glyphCount)
1028 , fTextByteLength(textByteLength) {
1029 // This is a cheap heuristic for /ReversedChars which seems to
1030 // work for clusters produced by HarfBuzz, which either
1031 // increase from zero (LTR) or decrease to zero (RTL).
1032 // "ReversedChars" is how PDF deals with RTL text.
1033 fReversedChars =
1034 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1035 }
1036 struct Cluster {
1037 const char* fUtf8Text;
1038 uint32_t fTextByteLength;
1039 uint32_t fGlyphIndex;
1040 uint32_t fGlyphCount;
1041 explicit operator bool() const { return fGlyphCount != 0; }
1042 };
1043 // True if this looks like right-to-left text.
1044 bool reversedChars() const { return fReversedChars; }
1045 Cluster next() {
1046 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1047 // These glyphs have no text. Treat as one "cluster".
1048 uint32_t glyphCount = fGlyphCount;
1049 fGlyphCount = 0;
1050 return Cluster{nullptr, 0, 0, glyphCount};
1051 }
1052 if (fGlyphCount == 0 || fTextByteLength == 0) {
1053 return Cluster{nullptr, 0, 0, 0}; // empty
1054 }
1055 SkASSERT(fUtf8Text);
1056 SkASSERT(fClusters);
1057 uint32_t cluster = fClusters[0];
1058 if (cluster >= fTextByteLength) {
1059 return Cluster{nullptr, 0, 0, 0}; // bad input.
1060 }
1061 uint32_t glyphsInCluster = 1;
1062 while (glyphsInCluster < fGlyphCount &&
1063 fClusters[glyphsInCluster] == cluster) {
1064 ++glyphsInCluster;
1065 }
1066 SkASSERT(glyphsInCluster <= fGlyphCount);
1067 uint32_t textLength = 0;
1068 if (glyphsInCluster == fGlyphCount) {
1069 // consumes rest of glyphs and rest of text
1070 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1071 textLength = fTextByteLength - cluster;
1072 } else { // RTL text; last cluster.
1073 SkASSERT(fPreviousCluster < fTextByteLength);
1074 if (fPreviousCluster <= cluster) { // bad input.
1075 return Cluster{nullptr, 0, 0, 0};
1076 }
1077 textLength = fPreviousCluster - cluster;
1078 }
1079 fGlyphCount = 0;
1080 return Cluster{fUtf8Text + cluster,
1081 textLength,
1082 fGlyphIndex,
1083 glyphsInCluster};
1084 }
1085 SkASSERT(glyphsInCluster < fGlyphCount);
1086 uint32_t nextCluster = fClusters[glyphsInCluster];
1087 if (nextCluster >= fTextByteLength) {
1088 return Cluster{nullptr, 0, 0, 0}; // bad input.
1089 }
1090 if (nextCluster > cluster) { // LTR text
1091 if (kInvalidCluster != fPreviousCluster) {
1092 return Cluster{nullptr, 0, 0, 0}; // bad input.
1093 }
1094 textLength = nextCluster - cluster;
1095 } else { // RTL text
1096 SkASSERT(nextCluster < cluster);
1097 if (kInvalidCluster == fPreviousCluster) { // first cluster
1098 textLength = fTextByteLength - cluster;
1099 } else { // later cluster
1100 if (fPreviousCluster <= cluster) {
1101 return Cluster{nullptr, 0, 0, 0}; // bad input.
1102 }
1103 textLength = fPreviousCluster - cluster;
1104 }
1105 fPreviousCluster = cluster;
1106 }
1107 uint32_t glyphIndex = fGlyphIndex;
1108 fGlyphCount -= glyphsInCluster;
1109 fGlyphIndex += glyphsInCluster;
1110 fClusters += glyphsInCluster;
1111 return Cluster{fUtf8Text + cluster,
1112 textLength,
1113 glyphIndex,
1114 glyphsInCluster};
1115 }
1116
1117private:
1118 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1119 const uint32_t* fClusters;
1120 const char* fUtf8Text;
1121 uint32_t fGlyphCount;
1122 uint32_t fTextByteLength;
1123 uint32_t fGlyphIndex = 0;
1124 uint32_t fPreviousCluster = kInvalidCluster;
1125 bool fReversedChars = false;
1126};
1127
1128struct TextStorage {
1129 SkAutoTMalloc<char> fUtf8textStorage;
1130 SkAutoTMalloc<uint32_t> fClusterStorage;
1131 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1132};
halcanaryf0c30f52016-07-15 13:35:45 -07001133} // namespace
1134
halcanaryf59d18a2016-09-16 14:44:57 -07001135/** Given some unicode text (as passed to drawText(), convert to
1136 glyphs (via primitive shaping), while preserving
1137 glyph-to-character mapping information. */
1138static Clusterator make_clusterator(
1139 const void* sourceText,
1140 size_t sourceByteCount,
1141 const SkPaint& paint,
1142 TextStorage* storage,
1143 int glyphCount) {
1144 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1145 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1146 SkASSERT(glyphCount > 0);
1147 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1148 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1149 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1150 uint32_t* clusters = storage->fClusterStorage.get();
1151 uint32_t utf8ByteCount = 0;
1152 const char* utf8Text = nullptr;
1153 switch (paint.getTextEncoding()) {
1154 case SkPaint::kUTF8_TextEncoding: {
1155 const char* txtPtr = (const char*)sourceText;
1156 for (int i = 0; i < glyphCount; ++i) {
1157 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1158 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1159 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1160 }
1161 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1162 utf8ByteCount = SkToU32(sourceByteCount);
1163 utf8Text = (const char*)sourceText;
1164 break;
1165 }
1166 case SkPaint::kUTF16_TextEncoding: {
1167 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1168 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1169 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1170 storage->fUtf8textStorage.reset(utf8ByteCount);
1171 char* txtPtr = storage->fUtf8textStorage.get();
1172 utf8Text = txtPtr;
1173 int clusterIndex = 0;
1174 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1175 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1176 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1177 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1178 }
1179 SkASSERT(clusterIndex == glyphCount);
1180 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1181 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1182 break;
1183 }
1184 case SkPaint::kUTF32_TextEncoding: {
1185 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1186 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1187 SkASSERT(glyphCount == utf32count);
1188 for (int i = 0; i < utf32count; ++i) {
1189 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1190 }
1191 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1192 char* txtPtr = storage->fUtf8textStorage.get();
1193 utf8Text = txtPtr;
1194 for (int i = 0; i < utf32count; ++i) {
1195 clusters[i] = SkToU32(txtPtr - utf8Text);
1196 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1197 }
1198 break;
1199 }
1200 default:
1201 SkDEBUGFAIL("");
1202 break;
1203 }
1204 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1205}
1206
halcanaryf59d18a2016-09-16 14:44:57 -07001207static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1208 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1209}
1210
halcanaryc2f9ec12016-09-12 08:55:29 -07001211static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1212 wStream->writeText("/");
1213 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1214 wStream->write(&prefix, 1);
1215 wStream->writeDecAsText(fontIndex);
1216 wStream->writeText(" ");
1217 SkPDFUtils::AppendScalar(textSize, wStream);
1218 wStream->writeText(" Tf\n");
1219}
1220
halcanary4ed2f012016-08-15 18:40:07 -07001221void SkPDFDevice::internalDrawText(
1222 const SkDraw& d, const void* sourceText, size_t sourceByteCount,
1223 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001224 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1225 uint32_t textByteLength, const char* utf8Text) {
halcanary4ed2f012016-08-15 18:40:07 -07001226 NOT_IMPLEMENTED(srcPaint.getMaskFilter() != nullptr, false);
1227 if (srcPaint.getMaskFilter() != nullptr) {
1228 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1229 // making text unreadable (e.g. same text twice when using CSS shadows).
1230 return;
1231 }
halcanaryea17dfe2016-08-24 09:20:57 -07001232 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1233 if (srcPaint.isVerticalText()) {
1234 // Don't pretend we support drawing vertical text. It is not
1235 // clear to me how to switch to "vertical writing" mode in PDF.
1236 // Currently neither Chromium or Android set this flag.
1237 // https://bug.skia.org/5665
1238 return;
1239 }
halcanaryf59d18a2016-09-16 14:44:57 -07001240 if (0 == sourceByteCount || !sourceText) {
1241 return;
halcanarye06ca962016-09-09 05:34:55 -07001242 }
halcanary4ed2f012016-08-15 18:40:07 -07001243 SkPaint paint = calculate_text_paint(srcPaint);
1244 replace_srcmode_on_opaque_paint(&paint);
1245 if (!paint.getTypeface()) {
1246 paint.setTypeface(SkTypeface::MakeDefault());
1247 }
1248 SkTypeface* typeface = paint.getTypeface();
1249 if (!typeface) {
1250 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1251 return;
1252 }
halcanary4871f222016-08-26 13:17:44 -07001253
1254 const SkAdvancedTypefaceMetrics* metrics =
1255 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1256 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001257 return;
1258 }
halcanary2bd295e2016-09-16 08:15:56 -07001259 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1260 if (glyphCount <= 0) {
1261 return;
1262 }
halcanary3b294d52016-09-16 13:21:08 -07001263
halcanaryf59d18a2016-09-16 14:44:57 -07001264 // These three heap buffers are only used in the case where no glyphs
1265 // are passed to drawText() (most clients pass glyphs or a textblob).
1266 TextStorage storage;
1267 const SkGlyphID* glyphs = nullptr;
1268 Clusterator clusterator;
1269 if (textByteLength > 0) {
1270 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1271 glyphs = (const SkGlyphID*)sourceText;
1272 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1273 SkASSERT(clusters);
1274 SkASSERT(utf8Text);
1275 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1276 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1277 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1278 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1279 glyphs = (const SkGlyphID*)sourceText;
1280 clusterator = Clusterator(SkToU32(glyphCount));
1281 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1282 SkASSERT(nullptr == clusters);
1283 SkASSERT(nullptr == utf8Text);
1284 } else {
1285 SkASSERT(nullptr == clusters);
1286 SkASSERT(nullptr == utf8Text);
1287 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1288 &storage, glyphCount);
1289 glyphs = storage.fGlyphStorage;
1290 }
halcanary4ed2f012016-08-15 18:40:07 -07001291 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001292 paint.setHinting(SkPaint::kNo_Hinting);
halcanary4ed2f012016-08-15 18:40:07 -07001293 SkAutoGlyphCache glyphCache(paint, nullptr, nullptr);
1294
1295 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001296 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1297 SkPaint::kCenter_Align == alignment ? -0.5f :
1298 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001299 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001300 SkScalar advance = 0;
halcanary4ed2f012016-08-15 18:40:07 -07001301 for (int i = 0; i < glyphCount; ++i) {
1302 advance += glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
1303 }
halcanary4871f222016-08-26 13:17:44 -07001304 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001305 }
halcanary4ed2f012016-08-15 18:40:07 -07001306 ScopedContentEntry content(this, d, paint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001307 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001308 return;
1309 }
halcanary4ed2f012016-08-15 18:40:07 -07001310 SkDynamicMemoryWStream* out = &content.entry()->fContent;
halcanary4871f222016-08-26 13:17:44 -07001311 SkScalar textSize = paint.getTextSize();
halcanaryf59d18a2016-09-16 14:44:57 -07001312 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
halcanary4871f222016-08-26 13:17:44 -07001313
halcanary4871f222016-08-26 13:17:44 -07001314 out->writeText("BT\n");
1315 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1316
halcanaryf59d18a2016-09-16 14:44:57 -07001317 const SkGlyphID maxGlyphID = metrics->fLastGlyphID;
halcanaryc2f9ec12016-09-12 08:55:29 -07001318 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
halcanaryf59d18a2016-09-16 14:44:57 -07001319 if (clusterator.reversedChars()) {
1320 out->writeText("/ReversedChars BMC\n");
1321 }
1322 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
halcanary4ed2f012016-08-15 18:40:07 -07001323 GlyphPositioner glyphPositioner(out,
1324 paint.getTextSkewX(),
halcanaryc2f9ec12016-09-12 08:55:29 -07001325 multiByteGlyphs,
halcanary4ed2f012016-08-15 18:40:07 -07001326 defaultPositioning,
1327 offset);
halcanaryc2f9ec12016-09-12 08:55:29 -07001328 SkPDFFont* font = nullptr;
halcanaryf59d18a2016-09-16 14:44:57 -07001329
1330 while (Clusterator::Cluster c = clusterator.next()) {
1331 int index = c.fGlyphIndex;
1332 int glyphLimit = index + c.fGlyphCount;
1333
1334 bool actualText = false;
1335 SK_AT_SCOPE_EXIT(if (actualText) { glyphPositioner.flush(); out->writeText("EMC\n"); } );
1336 if (c.fUtf8Text) { // real cluster
1337 // Check if `/ActualText` needed.
1338 const char* textPtr = c.fUtf8Text;
halcanaryf59d18a2016-09-16 14:44:57 -07001339 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
Hal Canaryd1c8e562017-01-11 15:53:25 -05001340 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1341 if (unichar < 0) {
1342 return;
1343 }
halcanaryf59d18a2016-09-16 14:44:57 -07001344 if (textPtr < textEnd || // more characters left
1345 glyphLimit > index + 1 || // toUnicode wouldn't work
1346 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1347 {
1348 glyphPositioner.flush();
1349 out->writeText("/Span<</ActualText <");
1350 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1351 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1352 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1353 while (textPtr < textEnd) {
Hal Canaryd1c8e562017-01-11 15:53:25 -05001354 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1355 if (unichar < 0) {
1356 break;
1357 }
halcanaryf59d18a2016-09-16 14:44:57 -07001358 SkPDFUtils::WriteUTF16beHex(out, unichar);
1359 }
1360 out->writeText("> >> BDC\n"); // begin marked-content sequence
1361 // with an associated property list.
1362 actualText = true;
robertphillips5ba165e2016-08-15 15:36:58 -07001363 }
1364 }
halcanaryf59d18a2016-09-16 14:44:57 -07001365 for (; index < glyphLimit; ++index) {
1366 SkGlyphID gid = glyphs[index];
1367 if (gid > maxGlyphID) {
1368 continue;
1369 }
1370 if (!font || !font->hasGlyph(gid)) {
1371 // Not yet specified font or need to switch font.
1372 int fontIndex = this->getFontResourceIndex(typeface, gid);
1373 // All preconditions for SkPDFFont::GetFontResource are met.
1374 SkASSERT(fontIndex >= 0);
1375 if (fontIndex < 0) {
1376 return;
1377 }
1378 glyphPositioner.flush();
1379 update_font(out, fontIndex, textSize);
1380 font = fFontResources[fontIndex];
1381 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1382 if (!font) {
1383 return;
1384 }
1385 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1386 }
1387 SkPoint xy{0, 0};
1388 SkScalar advance{0};
1389 if (!defaultPositioning) {
1390 advance = glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1391 xy = SkTextBlob::kFull_Positioning == positioning
1392 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1393 : SkPoint{pos[index], 0};
1394 if (alignment != SkPaint::kLeft_Align) {
1395 xy.offset(alignmentFactor * advance, 0);
1396 }
1397 }
1398 font->noteGlyphUsage(gid);
1399 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1400 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
1401 }
robertphillips5ba165e2016-08-15 15:36:58 -07001402 }
halcanary4ed2f012016-08-15 18:40:07 -07001403}
1404
1405void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
1406 SkScalar x, SkScalar y, const SkPaint& paint) {
1407 this->internalDrawText(d, text, len, nullptr, SkTextBlob::kDefault_Positioning,
halcanarye06ca962016-09-09 05:34:55 -07001408 SkPoint{x, y}, paint, nullptr, 0, nullptr);
halcanary4ed2f012016-08-15 18:40:07 -07001409}
1410
1411void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
1412 const SkScalar pos[], int scalarsPerPos,
1413 const SkPoint& offset, const SkPaint& paint) {
1414 this->internalDrawText(d, text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001415 offset, paint, nullptr, 0, nullptr);
1416}
1417
1418void SkPDFDevice::drawTextBlob(const SkDraw& draw, const SkTextBlob* blob, SkScalar x, SkScalar y,
1419 const SkPaint &paint, SkDrawFilter* drawFilter) {
1420 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1421 SkPaint runPaint(paint);
1422 it.applyFontToPaint(&runPaint);
1423 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1424 continue;
1425 }
1426 runPaint.setFlags(this->filterTextFlags(runPaint));
1427 SkPoint offset = it.offset() + SkPoint{x, y};
1428 this->internalDrawText(draw, it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
1429 it.pos(), it.positioning(), offset, runPaint,
1430 it.clusters(), it.textSize(), it.text());
1431 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001432}
1433
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001434void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001435 int vertexCount, const SkPoint verts[],
1436 const SkPoint texs[], const SkColor colors[],
Mike Reedfaba3712016-11-03 14:45:31 -04001437 SkBlendMode, const uint16_t indices[],
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001438 int indexCount, const SkPaint& paint) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001439 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001440 return;
1441 }
reed@google.com85e143c2013-12-30 15:51:25 +00001442 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001443}
1444
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001445void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1446 int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001447 SkASSERT(!paint.getImageFilter());
1448
reed7503d602016-07-15 14:23:29 -07001449 // Check if the source device is really a bitmapdevice (because that's what we returned
1450 // from createDevice (likely due to an imagefilter)
1451 SkPixmap pmap;
1452 if (device->peekPixels(&pmap)) {
1453 SkBitmap bitmap;
1454 bitmap.installPixels(pmap);
reedcf5c8462016-07-20 12:28:40 -07001455 this->drawSprite(d, bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001456 return;
1457 }
1458
fmalita6987dca2014-11-13 08:33:37 -08001459 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001460 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001461
1462 SkScalar scalarX = SkIntToScalar(x);
1463 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001464 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1465 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001466 fLinkToURLs.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001467 }
halcanary91fcb3e2016-03-04 13:53:22 -08001468 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1469 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001470 fLinkToDestinations.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001471 }
halcanary91fcb3e2016-03-04 13:53:22 -08001472 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1473 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001474 fNamedDestinations.emplace_back(d.nameData.get(), p);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001475 }
1476
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001477 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001478 return;
1479 }
1480
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001481 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001482 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
reed1e7f5e72016-04-27 07:49:17 -07001483 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001484 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001485 return;
1486 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001487 if (content.needShape()) {
1488 SkPath shape;
1489 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001490 SkIntToScalar(device->width()),
1491 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001492 content.setShape(shape);
1493 }
1494 if (!content.needSource()) {
1495 return;
1496 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001497
halcanary4b1e17e2016-07-27 14:49:46 -07001498 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001499 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001500 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001501}
1502
reede8f30622016-03-23 18:59:25 -07001503sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1504 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001505}
1506
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001507
halcanary8103a342016-03-08 15:10:16 -08001508sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001509 SkTDArray<SkPDFObject*> fonts;
1510 fonts.setReserve(fFontResources.count());
1511 for (SkPDFFont* font : fFontResources) {
1512 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001513 }
halcanary8103a342016-03-08 15:10:16 -08001514 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001515 &fGraphicStateResources,
1516 &fShaderResources,
1517 &fXObjectResources,
1518 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001519}
1520
halcanary8103a342016-03-08 15:10:16 -08001521sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001522 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001523 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001524 mediaBox->appendInt(0);
1525 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001526 mediaBox->appendInt(fPageSize.width());
1527 mediaBox->appendInt(fPageSize.height());
1528 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001529}
1530
mtklein5f939ab2016-03-16 10:28:35 -07001531std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001532 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001533 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001534 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001535 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001536
halcanaryafdc1772016-08-23 09:02:12 -07001537 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001538 for (const auto& entry : fContentEntries) {
1539 SkPoint translation;
1540 translation.iset(this->getOrigin());
1541 translation.negate();
1542 gsState.updateClip(entry.fState.fClipStack, entry.fState.fClipRegion,
Hal Canary44a97d52017-02-22 10:45:25 -05001543 translation, SkRect::Make(this->getGlobalBounds()));
halcanary2be7e012016-03-28 11:58:08 -07001544 gsState.updateMatrix(entry.fState.fMatrix);
1545 gsState.updateDrawingState(entry.fState);
1546
halcanaryafdc1772016-08-23 09:02:12 -07001547 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001548 }
1549 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001550 if (buffer.bytesWritten() > 0) {
1551 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1552 } else {
1553 return skstd::make_unique<SkMemoryStream>();
1554 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001555}
1556
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001557/* Draws an inverse filled path by using Path Ops to compute the positive
1558 * inverse using the current clip as the inverse bounds.
1559 * Return true if this was an inverse path and was properly handled,
1560 * otherwise returns false and the normal drawing routine should continue,
1561 * either as a (incorrect) fallback or because the path was not inverse
1562 * in the first place.
1563 */
1564bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001565 const SkPaint& paint, bool pathIsMutable,
1566 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001567 if (!origPath.isInverseFillType()) {
1568 return false;
1569 }
1570
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001571 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001572 return false;
1573 }
1574
1575 SkPath modifiedPath;
1576 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1577 SkPaint noInversePaint(paint);
1578
1579 // Merge stroking operations into final path.
1580 if (SkPaint::kStroke_Style == paint.getStyle() ||
1581 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1582 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1583 if (doFillPath) {
1584 noInversePaint.setStyle(SkPaint::kFill_Style);
1585 noInversePaint.setStrokeWidth(0);
1586 pathPtr = &modifiedPath;
1587 } else {
1588 // To be consistent with the raster output, hairline strokes
1589 // are rendered as non-inverted.
1590 modifiedPath.toggleInverseFillType();
halcanary96fcdcc2015-08-27 07:41:13 -07001591 drawPath(d, modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001592 return true;
1593 }
1594 }
1595
1596 // Get bounds of clip in current transform space
1597 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001598 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001599 SkMatrix totalMatrix = *d.fMatrix;
1600 if (prePathMatrix) {
1601 totalMatrix.preConcat(*prePathMatrix);
1602 }
1603 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001604 return false;
1605 }
Hal Canary44a97d52017-02-22 10:45:25 -05001606 SkRect bounds = d.fClipStack->bounds(this->getGlobalBounds());
1607 SkIPoint deviceOrigin = this->getOrigin();
1608 bounds.offset(-deviceOrigin.x(), -deviceOrigin.y());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001609 transformInverse.mapRect(&bounds);
1610
1611 // Extend the bounds by the line width (plus some padding)
1612 // so the edge doesn't cause a visible stroke.
1613 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1614 paint.getStrokeWidth() + SK_Scalar1);
1615
1616 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1617 return false;
1618 }
1619
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001620 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001621 return true;
1622}
1623
reedf70b5312016-03-04 16:36:20 -08001624void SkPDFDevice::handlePointAnnotation(const SkPoint& point,
epoger@google.comb58772f2013-03-08 09:09:10 +00001625 const SkMatrix& matrix,
reedf70b5312016-03-04 16:36:20 -08001626 const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -05001627 SkASSERT(value);
reedf70b5312016-03-04 16:36:20 -08001628 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
1629 SkPoint transformedPoint;
1630 matrix.mapXY(point.x(), point.y(), &transformedPoint);
1631 fNamedDestinations.emplace_back(value, transformedPoint);
1632 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001633}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001634
Hal Canary9cd21682017-02-22 15:55:06 -05001635void SkPDFDevice::handleRectAnnotation(const SkRect& rect,
wangxianzhuef6c50a2015-09-17 20:38:02 -07001636 const SkDraw& d,
reedf70b5312016-03-04 16:36:20 -08001637 const char key[], SkData* value) {
Hal Canary9cd21682017-02-22 15:55:06 -05001638 SkASSERT(value);
1639 // Convert to path to handle non-90-degree rotations.
1640 SkPath path;
1641 path.addRect(rect);
1642 path.transform(*d.fMatrix, &path);
1643 SkPath clip;
1644 (void)d.fClipStack->asPath(&clip);
1645 SkIPoint deviceOrigin = this->getOrigin();
1646 clip.offset(-deviceOrigin.x(), -deviceOrigin.y());
1647 // Offset here to make clip and path share coordinates.
1648 // We remove the offset in SkPDFDevice::drawDevice().
1649 Op(clip, path, kIntersect_SkPathOp, &path);
1650 // PDF wants a rectangle only.
1651 SkRect transformedRect = path.getBounds();
wangxianzhuef6c50a2015-09-17 20:38:02 -07001652
Hal Canary9cd21682017-02-22 15:55:06 -05001653 if (!transformedRect.isEmpty()) {
1654 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
reedf70b5312016-03-04 16:36:20 -08001655 fLinkToURLs.emplace_back(transformedRect, value);
Hal Canary9cd21682017-02-22 15:55:06 -05001656 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
reedf70b5312016-03-04 16:36:20 -08001657 fLinkToDestinations.emplace_back(transformedRect, value);
reed16108352016-03-03 09:14:36 -08001658 }
reed16108352016-03-03 09:14:36 -08001659 }
halcanary438de492015-04-28 06:21:01 -07001660}
1661
wangxianzhuef6c50a2015-09-17 20:38:02 -07001662void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1663 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001664 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001665 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001666 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001667 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001668 }
halcanary91fcb3e2016-03-04 13:53:22 -08001669 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001670 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001671 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001672 array->appendObject(
1673 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001674 }
1675}
epoger@google.comb58772f2013-03-08 09:09:10 +00001676
halcanary6d622702015-03-25 08:45:42 -07001677void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001678 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001679 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001680 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001681 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001682 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001683 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001684 pdfDest->appendScalar(p.x());
1685 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001686 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001687 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001688 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001689 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001690}
1691
halcanary4b1e17e2016-07-27 14:49:46 -07001692sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
halcanary5abbb442016-07-29 08:41:33 -07001693 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001694 if (!fInitialTransform.isIdentity()) {
1695 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001696 SkDEBUGFAIL("Layer initial transform should be invertible.");
1697 inverseTransform.reset();
1698 }
1699 }
halcanary4b1e17e2016-07-27 14:49:46 -07001700 sk_sp<SkPDFObject> xobject =
1701 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
halcanary5abbb442016-07-29 08:41:33 -07001702 this->makeResourceDict(), inverseTransform, nullptr);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001703 // We always draw the form xobjects that we create back into the device, so
1704 // we simply preserve the font usage instead of pulling it out and merging
1705 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001706 this->cleanUp(); // Reset this device to have no content.
1707 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001708 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001709}
1710
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001711void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001712 sk_sp<SkPDFObject> mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001713 const SkClipStack* clipStack,
1714 const SkRegion& clipRegion,
reed374772b2016-10-05 17:33:02 -07001715 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001716 bool invertClip) {
1717 if (clipRegion.isEmpty() && !invertClip) {
1718 return;
1719 }
1720
halcanary4b1e17e2016-07-27 14:49:46 -07001721 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001722 std::move(mask), invertClip,
1723 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001724
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001725 SkMatrix identity;
1726 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001727 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001728 paint.setBlendMode(mode);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001729 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001730 if (!content.entry()) {
1731 return;
1732 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001733 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001734 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001735 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001736
halcanary1437c1e2016-03-13 18:30:24 -07001737 // Call makeNoSmaskGraphicState() instead of
1738 // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1739 // can deduplicate.
halcanary989da4a2016-03-21 14:33:17 -07001740 sMaskGS = fDocument->canon()->makeNoSmaskGraphicState();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001741 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001742 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001743}
1744
halcanary2be7e012016-03-28 11:58:08 -07001745SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001746 const SkRegion& clipRegion,
1747 const SkMatrix& matrix,
1748 const SkPaint& paint,
1749 bool hasText,
1750 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001751 *dst = nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001752 if (clipRegion.isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -07001753 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001754 }
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001755 SkASSERT(clipStack);
reed374772b2016-10-05 17:33:02 -07001756 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001757
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001758 // For the following modes, we want to handle source and destination
1759 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001760 if (blendMode == SkBlendMode::kClear ||
1761 blendMode == SkBlendMode::kSrc ||
1762 blendMode == SkBlendMode::kSrcIn ||
1763 blendMode == SkBlendMode::kDstIn ||
1764 blendMode == SkBlendMode::kSrcOut ||
1765 blendMode == SkBlendMode::kDstOut ||
1766 blendMode == SkBlendMode::kSrcATop ||
1767 blendMode == SkBlendMode::kDstATop ||
1768 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001769 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001770 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001771 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001772 } else if (blendMode != SkBlendMode::kSrc &&
1773 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001774 // Except for Src and SrcOut, if there isn't anything already there,
1775 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001776 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001777 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001778 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001779 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001780 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001781
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001782 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001783 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001784 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001785 }
1786
halcanary2be7e012016-03-28 11:58:08 -07001787 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001788 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001789 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001790 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001791 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001792 } else {
halcanary2be7e012016-03-28 11:58:08 -07001793 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001794 }
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001795 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001796 hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001797 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001798}
1799
reed374772b2016-10-05 17:33:02 -07001800void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001801 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001802 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001803 if (blendMode != SkBlendMode::kClear &&
1804 blendMode != SkBlendMode::kSrc &&
1805 blendMode != SkBlendMode::kDstOver &&
1806 blendMode != SkBlendMode::kSrcIn &&
1807 blendMode != SkBlendMode::kDstIn &&
1808 blendMode != SkBlendMode::kSrcOut &&
1809 blendMode != SkBlendMode::kDstOut &&
1810 blendMode != SkBlendMode::kSrcATop &&
1811 blendMode != SkBlendMode::kDstATop &&
1812 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001813 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001814 return;
1815 }
reed374772b2016-10-05 17:33:02 -07001816 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001817 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00001818 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001819 // For DstOver, an empty content entry was inserted before the rest
1820 // of the content entries. If nothing was drawn, it needs to be
1821 // removed.
halcanary2be7e012016-03-28 11:58:08 -07001822 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001823 }
1824 return;
1825 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001826 if (!dst) {
reed374772b2016-10-05 17:33:02 -07001827 SkASSERT(blendMode == SkBlendMode::kSrc ||
1828 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001829 return;
1830 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001831
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001832 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07001833 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001834 // Changing the current content into a form-xobject will destroy the clip
1835 // objects which is fine since the xobject will already be clipped. However
1836 // if source has shape, we need to clip it too, so a copy of the clip is
1837 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001838
1839 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
1840 SkRegion clipRegion = fContentEntries.front()->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001841
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001842 SkMatrix identity;
1843 identity.reset();
1844 SkPaint stockPaint;
1845
halcanary4b1e17e2016-07-27 14:49:46 -07001846 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001847 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001848 // If nothing was drawn and there's no shape, then the draw was a
1849 // no-op, but dst needs to be restored for that to be true.
1850 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1851 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1852 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07001853 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1854 blendMode == SkBlendMode::kSrcATop) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001855 ScopedContentEntry content(this, &fExistingClipStack,
1856 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001857 stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07001858 // TODO: addXObjectResource take sk_sp
1859 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001860 &content.entry()->fContent);
1861 return;
1862 } else {
reed374772b2016-10-05 17:33:02 -07001863 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001864 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001865 } else {
halcanary2be7e012016-03-28 11:58:08 -07001866 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07001867 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001868 }
1869
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001870 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1871 // without alpha.
reed374772b2016-10-05 17:33:02 -07001872 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001873 // TODO(vandebo): In order to properly support SrcATop we have to track
1874 // the shape of what's been drawn at all times. It's the intersection of
1875 // the non-transparent parts of the device and the outlines (shape) of
1876 // all images and devices drawn.
1877 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001878 &fExistingClipStack, fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001879 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001880 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001881 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001882 // Draw shape into a form-xobject.
reed1e7f5e72016-04-27 07:49:17 -07001883 SkRasterClip rc(clipRegion);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001884 SkDraw d;
1885 d.fMatrix = &identity;
reed1e7f5e72016-04-27 07:49:17 -07001886 d.fRC = &rc;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001887 d.fClipStack = &clipStack;
1888 SkPaint filledPaint;
1889 filledPaint.setColor(SK_ColorBLACK);
1890 filledPaint.setStyle(SkPaint::kFill_Style);
halcanary96fcdcc2015-08-27 07:41:13 -07001891 this->drawPath(d, *shape, filledPaint, nullptr, true);
halcanarydabd4f02016-08-03 11:16:56 -07001892 drawFormXObjectWithMask(addXObjectResource(dst.get()),
1893 this->makeFormXObjectFromDevice(),
1894 &fExistingClipStack, fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001895 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001896
halcanarydabd4f02016-08-03 11:16:56 -07001897 } else {
1898 drawFormXObjectWithMask(addXObjectResource(dst.get()), srcFormXObject,
1899 &fExistingClipStack, fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001900 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001901 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001902 }
1903
reed374772b2016-10-05 17:33:02 -07001904 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001905 return;
reed374772b2016-10-05 17:33:02 -07001906 } else if (blendMode == SkBlendMode::kSrc ||
1907 blendMode == SkBlendMode::kDstATop) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001908 ScopedContentEntry content(this, &fExistingClipStack,
1909 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001910 if (content.entry()) {
1911 SkPDFUtils::DrawFormXObject(
1912 this->addXObjectResource(srcFormXObject.get()),
1913 &content.entry()->fContent);
1914 }
reed374772b2016-10-05 17:33:02 -07001915 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001916 return;
1917 }
reed374772b2016-10-05 17:33:02 -07001918 } else if (blendMode == SkBlendMode::kSrcATop) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001919 ScopedContentEntry content(this, &fExistingClipStack,
1920 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001921 if (content.entry()) {
halcanarydabd4f02016-08-03 11:16:56 -07001922 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001923 &content.entry()->fContent);
1924 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001925 }
1926
reed374772b2016-10-05 17:33:02 -07001927 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
1928 blendMode == SkBlendMode::kDstIn ||
1929 blendMode == SkBlendMode::kSrcOut ||
1930 blendMode == SkBlendMode::kDstOut ||
1931 blendMode == SkBlendMode::kSrcATop ||
1932 blendMode == SkBlendMode::kDstATop ||
1933 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001934
reed374772b2016-10-05 17:33:02 -07001935 if (blendMode == SkBlendMode::kSrcIn ||
1936 blendMode == SkBlendMode::kSrcOut ||
1937 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07001938 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1939 std::move(dst),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001940 &fExistingClipStack, fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001941 SkBlendMode::kSrcOver,
1942 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07001943 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001944 } else {
reed374772b2016-10-05 17:33:02 -07001945 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07001946 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07001947 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001948 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
halcanarydabd4f02016-08-03 11:16:56 -07001949 std::move(dst), &fExistingClipStack,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001950 fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001951 SkBlendMode::kSrcOver, false);
1952 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001953 }
halcanarydabd4f02016-08-03 11:16:56 -07001954 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001955 &fExistingClipStack, fExistingClipRegion, mode,
reed374772b2016-10-05 17:33:02 -07001956 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07001957 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001958 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001959}
1960
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001961bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00001962 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001963 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001964 return true;
1965 }
1966 return false;
1967}
1968
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001969void SkPDFDevice::populateGraphicStateEntryFromPaint(
1970 const SkMatrix& matrix,
1971 const SkClipStack& clipStack,
1972 const SkRegion& clipRegion,
1973 const SkPaint& paint,
1974 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07001975 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07001976 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1977 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1978 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001979
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001980 entry->fMatrix = matrix;
1981 entry->fClipStack = clipStack;
1982 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001983 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1984 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001985
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001986 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08001987 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07001988 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001989 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001990 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05001991 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1992 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001993 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05001994 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001995 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07001996 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001997 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05001998 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1999 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2000 color = gradientColor;
2001 } else {
2002 // PDF positions patterns relative to the initial transform, so
2003 // we need to apply the current transform to the shader parameters.
2004 SkMatrix transform = matrix;
2005 transform.postConcat(fInitialTransform);
2006
2007 // PDF doesn't support kClamp_TileMode, so we simulate it by making
2008 // a pattern the size of the current clip.
Hal Canarya41c2aa2017-02-22 16:32:34 -05002009 SkRect clipStackBounds = clipStack.bounds(this->getGlobalBounds());
2010 SkIPoint deviceOrigin = this->getOrigin();
2011 clipStackBounds.offset(-deviceOrigin.x(), -deviceOrigin.y());
Hal Canaryc8f91802017-02-12 20:29:12 -05002012
2013 // We need to apply the initial transform to bounds in order to get
2014 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05002015 fInitialTransform.mapRect(&clipStackBounds);
2016 SkIRect bounds;
2017 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05002018
2019 SkScalar rasterScale =
2020 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
2021 pdfShader = SkPDFShader::GetPDFShader(
2022 fDocument, fRasterDpi, shader, transform, bounds, rasterScale);
2023
2024 if (pdfShader.get()) {
2025 // pdfShader has been canonicalized so we can directly compare
2026 // pointers.
2027 int resourceIndex = fShaderResources.find(pdfShader.get());
2028 if (resourceIndex < 0) {
2029 resourceIndex = fShaderResources.count();
2030 fShaderResources.push(pdfShader.get());
2031 pdfShader.get()->ref();
2032 }
2033 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002034 }
2035 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002036 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002037
halcanary48810a02016-03-07 14:57:50 -08002038 sk_sp<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002039 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002040 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07002041 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002042 } else {
2043 SkPaint newPaint = paint;
2044 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002045 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07002046 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002047 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002048 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002049 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002050
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002051 if (hasText) {
2052 entry->fTextScaleX = paint.getTextScaleX();
2053 entry->fTextFill = paint.getStyle();
2054 } else {
2055 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002056 }
2057}
2058
halcanarybe27a112015-04-01 13:31:19 -07002059int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002060 // Assumes that gs has been canonicalized (so we can directly compare
2061 // pointers).
2062 int result = fGraphicStateResources.find(gs);
2063 if (result < 0) {
2064 result = fGraphicStateResources.count();
2065 fGraphicStateResources.push(gs);
2066 gs->ref();
2067 }
2068 return result;
2069}
2070
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002071int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002072 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002073 // Assumes that xobject has been canonicalized (so we can directly compare
2074 // pointers).
2075 int result = fXObjectResources.find(xObject);
2076 if (result < 0) {
2077 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002078 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002079 }
2080 return result;
2081}
2082
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002083int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary48810a02016-03-07 14:57:50 -08002084 sk_sp<SkPDFFont> newFont(
halcanary989da4a2016-03-21 14:33:17 -07002085 SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID));
halcanary7e8d5d32016-08-12 07:59:38 -07002086 if (!newFont) {
2087 return -1;
2088 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002089 int resourceIndex = fFontResources.find(newFont.get());
2090 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002091 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002092 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002093 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002094 }
2095 return resourceIndex;
2096}
2097
halcanary7a14b312015-10-01 07:28:13 -07002098static SkSize rect_to_size(const SkRect& r) {
2099 return SkSize::Make(r.width(), r.height());
2100}
2101
Hal Canaryf50ff392016-09-30 10:25:39 -04002102static sk_sp<SkImage> color_filter(const SkImageSubset& imageSubset,
halcanarya50151d2016-03-25 11:57:49 -07002103 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002104 auto surface =
Hal Canaryf50ff392016-09-30 10:25:39 -04002105 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07002106 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002107 SkCanvas* canvas = surface->getCanvas();
2108 canvas->clear(SK_ColorTRANSPARENT);
2109 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002110 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canaryf50ff392016-09-30 10:25:39 -04002111 imageSubset.draw(canvas, &paint);
halcanary7a14b312015-10-01 07:28:13 -07002112 canvas->flush();
halcanarya50151d2016-03-25 11:57:49 -07002113 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002114}
2115
2116////////////////////////////////////////////////////////////////////////////////
2117void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
2118 const SkClipStack* clipStack,
2119 const SkRegion& origClipRegion,
Hal Canaryf50ff392016-09-30 10:25:39 -04002120 SkImageSubset imageSubset,
halcanary7a14b312015-10-01 07:28:13 -07002121 const SkPaint& paint) {
Hal Canaryf50ff392016-09-30 10:25:39 -04002122 if (imageSubset.dimensions().isZero()) {
halcanarya50151d2016-03-25 11:57:49 -07002123 return;
2124 }
halcanary7a14b312015-10-01 07:28:13 -07002125 #ifdef SK_PDF_IMAGE_STATS
2126 gDrawImageCalls.fetch_add(1);
2127 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002128 SkMatrix matrix = origMatrix;
2129 SkRegion perspectiveBounds;
2130 const SkRegion* clipRegion = &origClipRegion;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002131
2132 // Rasterize the bitmap using perspective in a new bitmap.
2133 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002134 if (fRasterDpi == 0) {
2135 return;
2136 }
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002137 // Transform the bitmap in the new space, without taking into
2138 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002139 SkPath perspectiveOutline;
Hal Canaryf50ff392016-09-30 10:25:39 -04002140 SkRect imageBounds = SkRect::Make(imageSubset.bounds());
halcanary7a14b312015-10-01 07:28:13 -07002141 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002142 perspectiveOutline.transform(origMatrix);
2143
2144 // TODO(edisonn): perf - use current clip too.
2145 // Retrieve the bounds of the new shape.
2146 SkRect bounds = perspectiveOutline.getBounds();
2147
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002148 // Transform the bitmap in the new space, taking into
2149 // account the initial transform.
2150 SkMatrix total = origMatrix;
2151 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002152 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2153 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2154 total.postScale(dpiScale, dpiScale);
2155
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002156 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002157 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002158 physicalPerspectiveOutline.transform(total);
2159
halcanary7a14b312015-10-01 07:28:13 -07002160 SkRect physicalPerspectiveBounds =
2161 physicalPerspectiveOutline.getBounds();
2162 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2163 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002164
2165 // TODO(edisonn): A better approach would be to use a bitmap shader
2166 // (in clamp mode) and draw a rect over the entire bounding box. Then
2167 // intersect perspectiveOutline to the clip. That will avoid introducing
2168 // alpha to the image while still giving good behavior at the edge of
2169 // the image. Avoiding alpha will reduce the pdf size and generation
2170 // CPU time some.
2171
halcanary7a14b312015-10-01 07:28:13 -07002172 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2173
Hal Canaryf50ff392016-09-30 10:25:39 -04002174 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002175 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002176 return;
2177 }
halcanary7a14b312015-10-01 07:28:13 -07002178 SkCanvas* canvas = surface->getCanvas();
2179 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002180
2181 SkScalar deltaX = bounds.left();
2182 SkScalar deltaY = bounds.top();
2183
2184 SkMatrix offsetMatrix = origMatrix;
2185 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002186 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002187
2188 // Translate the draw in the new canvas, so we perfectly fit the
2189 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002190 canvas->setMatrix(offsetMatrix);
Hal Canaryf50ff392016-09-30 10:25:39 -04002191 imageSubset.draw(canvas, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002192 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002193 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002194
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002195 // In the new space, we use the identity matrix translated
2196 // and scaled to reflect DPI.
2197 matrix.setScale(1 / scaleX, 1 / scaleY);
2198 matrix.postTranslate(deltaX, deltaY);
2199
halcanary7a14b312015-10-01 07:28:13 -07002200 perspectiveBounds.setRect(bounds.roundOut());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002201 clipRegion = &perspectiveBounds;
halcanary7a14b312015-10-01 07:28:13 -07002202
Hal Canaryf50ff392016-09-30 10:25:39 -04002203 imageSubset = SkImageSubset(surface->makeImageSnapshot());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002204 }
2205
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002206 SkMatrix scaled;
2207 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002208 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2209 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002210 // Scale the image up from 1x1 to WxH.
Hal Canaryf50ff392016-09-30 10:25:39 -04002211 SkIRect subset = imageSubset.bounds();
2212 scaled.postScale(SkIntToScalar(imageSubset.dimensions().width()),
2213 SkIntToScalar(imageSubset.dimensions().height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002214 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002215 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002216 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002217 return;
2218 }
2219 if (content.needShape()) {
2220 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002221 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002222 shape.transform(matrix);
2223 content.setShape(shape);
2224 }
2225 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002226 return;
2227 }
2228
halcanary287d22d2015-09-24 10:20:05 -07002229 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002230 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002231 // draw calls. This code here works for all
2232 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2233 // rasterize a layer on this backend). Fortuanely, this seems
2234 // to be how Chromium impements most color-filters.
Hal Canaryf50ff392016-09-30 10:25:39 -04002235 sk_sp<SkImage> img = color_filter(imageSubset, colorFilter);
2236 imageSubset = SkImageSubset(std::move(img));
halcanary7a14b312015-10-01 07:28:13 -07002237 // TODO(halcanary): de-dupe this by caching filtered images.
2238 // (maybe in the resource cache?)
2239 }
halcanarya50151d2016-03-25 11:57:49 -07002240
Hal Canaryf50ff392016-09-30 10:25:39 -04002241 SkBitmapKey key = imageSubset.getKey();
halcanarya50151d2016-03-25 11:57:49 -07002242 sk_sp<SkPDFObject> pdfimage = fDocument->canon()->findPDFBitmap(key);
halcanary7a14b312015-10-01 07:28:13 -07002243 if (!pdfimage) {
Hal Canaryf50ff392016-09-30 10:25:39 -04002244 sk_sp<SkImage> img = imageSubset.makeImage();
halcanarya50151d2016-03-25 11:57:49 -07002245 if (!img) {
2246 return;
2247 }
2248 pdfimage = SkPDFCreateBitmapObject(
2249 std::move(img), fDocument->canon()->getPixelSerializer());
halcanary7a14b312015-10-01 07:28:13 -07002250 if (!pdfimage) {
2251 return;
halcanary287d22d2015-09-24 10:20:05 -07002252 }
halcanarya50151d2016-03-25 11:57:49 -07002253 fDocument->serialize(pdfimage); // serialize images early.
2254 fDocument->canon()->addPDFBitmap(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002255 }
halcanarya50151d2016-03-25 11:57:49 -07002256 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
halcanary3d8c33c2015-10-01 11:06:22 -07002257 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002258 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002259}
reede51c3562016-07-19 14:33:20 -07002260
2261///////////////////////////////////////////////////////////////////////////////////////////////////
2262
2263#include "SkSpecialImage.h"
2264#include "SkImageFilter.h"
2265
2266void SkPDFDevice::drawSpecial(const SkDraw& draw, SkSpecialImage* srcImg, int x, int y,
2267 const SkPaint& paint) {
2268 SkASSERT(!srcImg->isTextureBacked());
2269
2270 SkBitmap resultBM;
2271
2272 SkImageFilter* filter = paint.getImageFilter();
2273 if (filter) {
2274 SkIPoint offset = SkIPoint::Make(0, 0);
2275 SkMatrix matrix = *draw.fMatrix;
2276 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002277 const SkIRect clipBounds =
2278 draw.fClipStack->bounds(this->imageInfo().bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002279 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
brianosman2a75e5d2016-09-22 07:15:37 -07002280 // TODO: Should PDF be operating in a specified color space? For now, run the filter
2281 // in the same color space as the source (this is different from all other backends).
2282 SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2283 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002284
2285 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2286 if (resultImg) {
2287 SkPaint tmpUnfiltered(paint);
2288 tmpUnfiltered.setImageFilter(nullptr);
2289 if (resultImg->getROPixels(&resultBM)) {
2290 this->drawSprite(draw, resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
2291 }
2292 }
2293 } else {
2294 if (srcImg->getROPixels(&resultBM)) {
2295 this->drawSprite(draw, resultBM, x, y, paint);
2296 }
2297 }
2298}
2299
2300sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2301 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2302}
2303
2304sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002305 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2306 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2307 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002308 SkColorSpace* legacyColorSpace = nullptr;
reede51c3562016-07-19 14:33:20 -07002309 return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
Brian Osman61624f02016-12-09 14:51:59 -05002310 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002311}
2312
2313sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002314 return nullptr;
2315}
brianosman04a44d02016-09-21 09:46:57 -07002316
2317SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2318 // We always return a transient cache, so it is freed after each
2319 // filter traversal.
2320 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2321}