blob: 36c1418d68cd105cba07242d51c7bf8f6e89bda7 [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) {
514 if (0 == rect.width() && 0 == rect.height()) {
515 handlePointAnnotation({ rect.x(), rect.y() }, *d.fMatrix, key, value);
516 } else {
517 SkPath path;
518 path.addRect(rect);
519 handlePathAnnotation(path, d, key, value);
520 }
521}
522
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000523void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000524 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700525 replace_srcmode_on_opaque_paint(&newPaint);
526
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000527 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000528 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000529 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000530}
531
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000532void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700533 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000534 if (!contentEntry) {
535 return;
536 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000537 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
538 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000539 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000540 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000541 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000542 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000543 inverse.mapRect(&bbox);
544
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000545 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000546 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000547 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000548}
549
halcanary682ee012016-01-28 10:59:34 -0800550void SkPDFDevice::drawPoints(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700551 SkCanvas::PointMode mode,
552 size_t count,
553 const SkPoint* points,
554 const SkPaint& srcPaint) {
555 SkPaint passedPaint = srcPaint;
556 replace_srcmode_on_opaque_paint(&passedPaint);
557
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000558 if (count == 0) {
559 return;
560 }
561
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000562 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
563 // We only use this when there's a path effect because of the overhead
564 // of multiple calls to setUpContentEntry it causes.
565 if (passedPaint.getPathEffect()) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500566 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000567 return;
568 }
Mike Reed99330ba2017-02-22 11:01:08 -0500569 d.drawPoints(mode, count, points, passedPaint, this);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000570 return;
571 }
572
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000573 const SkPaint* paint = &passedPaint;
574 SkPaint modifiedPaint;
575
576 if (mode == SkCanvas::kPoints_PointMode &&
577 paint->getStrokeCap() != SkPaint::kRound_Cap) {
578 modifiedPaint = *paint;
579 paint = &modifiedPaint;
580 if (paint->getStrokeWidth()) {
581 // PDF won't draw a single point with square/butt caps because the
582 // orientation is ambiguous. Draw a rectangle instead.
583 modifiedPaint.setStyle(SkPaint::kFill_Style);
584 SkScalar strokeWidth = paint->getStrokeWidth();
585 SkScalar halfStroke = SkScalarHalf(strokeWidth);
586 for (size_t i = 0; i < count; i++) {
587 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
588 r.inset(-halfStroke, -halfStroke);
589 drawRect(d, r, modifiedPaint);
590 }
591 return;
592 } else {
593 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
594 }
595 }
596
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000597 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000598 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000599 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000600 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000601
602 switch (mode) {
603 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000604 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000605 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000606 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000607 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000608 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000609 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000610 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000611 break;
612 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000613 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000614 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000615 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000616 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000617 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000618 &content.entry()->fContent);
619 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000620 }
621 break;
622 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000623 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
624 for (size_t i = 0; i < count; i++) {
625 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000626 &content.entry()->fContent);
627 SkPDFUtils::ClosePath(&content.entry()->fContent);
628 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000629 }
630 break;
631 default:
632 SkASSERT(false);
633 }
634}
635
halcanary8103a342016-03-08 15:10:16 -0800636static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800637 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700638 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700639 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700640
halcanaryece83922016-03-08 08:32:12 -0800641 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700642 border->reserve(3);
643 border->appendInt(0); // Horizontal corner radius.
644 border->appendInt(0); // Vertical corner radius.
645 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800646 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700647
halcanaryece83922016-03-08 08:32:12 -0800648 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700649 rect->reserve(4);
650 rect->appendScalar(translatedRect.fLeft);
651 rect->appendScalar(translatedRect.fTop);
652 rect->appendScalar(translatedRect.fRight);
653 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800654 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700655
halcanary8103a342016-03-08 15:10:16 -0800656 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700657}
658
halcanary8103a342016-03-08 15:10:16 -0800659static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700660 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700661 SkString url(static_cast<const char *>(urlData->data()),
662 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800663 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700664 action->insertName("S", "URI");
665 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800666 annotation->insertObject("A", std::move(action));
667 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700668}
669
halcanary8103a342016-03-08 15:10:16 -0800670static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
671 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700672 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700673 SkString name(static_cast<const char *>(nameData->data()),
674 nameData->size() - 1);
675 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800676 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700677}
678
halcanary682ee012016-01-28 10:59:34 -0800679void SkPDFDevice::drawRect(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700680 const SkRect& rect,
681 const SkPaint& srcPaint) {
682 SkPaint paint = srcPaint;
683 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000684 SkRect r = rect;
685 r.sort();
686
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000687 if (paint.getPathEffect()) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500688 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000689 return;
690 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000691 SkPath path;
692 path.addRect(r);
halcanary96fcdcc2015-08-27 07:41:13 -0700693 drawPath(d, path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000694 return;
695 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000696
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000697 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000698 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000699 return;
700 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000701 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000702 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000703 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000704}
705
halcanarya6814332015-05-27 08:53:36 -0700706void SkPDFDevice::drawRRect(const SkDraw& draw,
707 const SkRRect& rrect,
708 const SkPaint& srcPaint) {
709 SkPaint paint = srcPaint;
710 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000711 SkPath path;
712 path.addRRect(rrect);
halcanary96fcdcc2015-08-27 07:41:13 -0700713 this->drawPath(draw, path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000714}
715
halcanarya6814332015-05-27 08:53:36 -0700716void SkPDFDevice::drawOval(const SkDraw& draw,
717 const SkRect& oval,
718 const SkPaint& srcPaint) {
719 SkPaint paint = srcPaint;
720 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700721 SkPath path;
722 path.addOval(oval);
halcanary96fcdcc2015-08-27 07:41:13 -0700723 this->drawPath(draw, path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700724}
725
halcanary682ee012016-01-28 10:59:34 -0800726void SkPDFDevice::drawPath(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700727 const SkPath& origPath,
728 const SkPaint& srcPaint,
729 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000730 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700731 SkPaint paint = srcPaint;
732 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800733 SkPath modifiedPath;
734 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000735
736 SkMatrix matrix = *d.fMatrix;
737 if (prePathMatrix) {
738 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800739 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000740 pathPtr = &modifiedPath;
741 pathIsMutable = true;
742 }
halcanary682ee012016-01-28 10:59:34 -0800743 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000744 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000745 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000746 }
747 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000748
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000749 if (paint.getPathEffect()) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500750 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000751 return;
752 }
halcanary682ee012016-01-28 10:59:34 -0800753 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000754 pathPtr = &modifiedPath;
755 pathIsMutable = true;
756 }
halcanary682ee012016-01-28 10:59:34 -0800757 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000758
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000759 SkPaint noEffectPaint(paint);
halcanary96fcdcc2015-08-27 07:41:13 -0700760 noEffectPaint.setPathEffect(nullptr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000761 if (fill) {
762 noEffectPaint.setStyle(SkPaint::kFill_Style);
763 } else {
764 noEffectPaint.setStyle(SkPaint::kStroke_Style);
765 noEffectPaint.setStrokeWidth(0);
766 }
halcanary96fcdcc2015-08-27 07:41:13 -0700767 drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000768 return;
769 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000770
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000771 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000772 return;
773 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000774
reed1e7f5e72016-04-27 07:49:17 -0700775 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000776 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000777 return;
778 }
Hal Canary385468f2017-02-13 11:03:23 -0500779 SkScalar matrixScale = matrix.mapRadius(1.0f);
780 SkScalar tolerance = matrixScale > 0.0f ? 0.25f / matrixScale : 0.25f;
halcanary8b2bc252015-10-06 09:41:47 -0700781 bool consumeDegeratePathSegments =
782 paint.getStyle() == SkPaint::kFill_Style ||
783 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
784 paint.getStrokeCap() != SkPaint::kSquare_Cap);
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000785 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
halcanary8b2bc252015-10-06 09:41:47 -0700786 consumeDegeratePathSegments,
Hal Canary385468f2017-02-13 11:03:23 -0500787 &content.entry()->fContent,
788 tolerance);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000789 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000790 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000791}
792
Hal Canaryf50ff392016-09-30 10:25:39 -0400793
794void SkPDFDevice::drawImageRect(const SkDraw& d,
795 const SkImage* image,
796 const SkRect* src,
797 const SkRect& dst,
798 const SkPaint& srcPaint,
799 SkCanvas::SrcRectConstraint) {
800 if (!image) {
801 return;
802 }
803 SkIRect bounds = image->bounds();
804 SkPaint paint = srcPaint;
805 if (image->isOpaque()) {
806 replace_srcmode_on_opaque_paint(&paint);
807 }
808 SkRect srcRect = src ? *src : SkRect::Make(bounds);
809 SkMatrix transform;
810 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
811 if (src) {
812 if (!srcRect.intersect(SkRect::Make(bounds))) {
813 return;
814 }
815 srcRect.roundOut(&bounds);
816 transform.preTranslate(SkIntToScalar(bounds.x()),
817 SkIntToScalar(bounds.y()));
818 }
819 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)), bounds);
820 if (!imageSubset.isValid()) {
821 return;
822 }
823 transform.postConcat(*d.fMatrix);
824 this->internalDrawImage(transform, d.fClipStack, d.fRC->bwRgn(),
825 std::move(imageSubset), paint);
826}
827
828void SkPDFDevice::drawBitmapRect(const SkDraw& d,
halcanary7a14b312015-10-01 07:28:13 -0700829 const SkBitmap& bitmap,
830 const SkRect* src,
831 const SkRect& dst,
Hal Canaryf50ff392016-09-30 10:25:39 -0400832 const SkPaint& srcPaint,
833 SkCanvas::SrcRectConstraint) {
834 if (bitmap.drawsNothing()) {
835 return;
836 }
837 SkIRect bounds = bitmap.bounds();
838 SkPaint paint = srcPaint;
839 if (bitmap.isOpaque()) {
840 replace_srcmode_on_opaque_paint(&paint);
841 }
842 SkRect srcRect = src ? *src : SkRect::Make(bounds);
843 SkMatrix transform;
844 transform.setRectToRect(srcRect, dst, SkMatrix::kFill_ScaleToFit);
845 if (src) {
846 if (!srcRect.intersect(SkRect::Make(bounds))) {
847 return;
848 }
849 srcRect.roundOut(&bounds);
850 transform.preTranslate(SkIntToScalar(bounds.x()),
851 SkIntToScalar(bounds.y()));
852 }
853 SkBitmap bitmapSubset;
854 if (!bitmap.extractSubset(&bitmapSubset, bounds)) {
855 return;
856 }
857 SkImageSubset imageSubset = make_image_subset(bitmapSubset);
858 if (!imageSubset.isValid()) {
859 return;
860 }
861 transform.postConcat(*d.fMatrix);
862 this->internalDrawImage(transform, d.fClipStack, d.fRC->bwRgn(),
863 std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700864}
865
866void SkPDFDevice::drawBitmap(const SkDraw& d,
867 const SkBitmap& bitmap,
868 const SkMatrix& matrix,
869 const SkPaint& srcPaint) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500870 if (bitmap.drawsNothing() || d.fClipStack->isEmpty(this->getGlobalBounds())) {
Hal Canaryf50ff392016-09-30 10:25:39 -0400871 return;
872 }
halcanarya6814332015-05-27 08:53:36 -0700873 SkPaint paint = srcPaint;
874 if (bitmap.isOpaque()) {
875 replace_srcmode_on_opaque_paint(&paint);
876 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400877 SkImageSubset imageSubset = make_image_subset(bitmap);
878 if (!imageSubset.isValid()) {
halcanary7a14b312015-10-01 07:28:13 -0700879 return;
880 }
halcanary7a14b312015-10-01 07:28:13 -0700881 SkMatrix transform = matrix;
882 transform.postConcat(*d.fMatrix);
halcanarya50151d2016-03-25 11:57:49 -0700883 this->internalDrawImage(
Hal Canaryf50ff392016-09-30 10:25:39 -0400884 transform, d.fClipStack, d.fRC->bwRgn(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700885}
886
887void SkPDFDevice::drawSprite(const SkDraw& d,
888 const SkBitmap& bitmap,
889 int x,
890 int y,
891 const SkPaint& srcPaint) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500892 if (bitmap.drawsNothing() || d.fClipStack->isEmpty(this->getGlobalBounds())) {
Hal Canaryf50ff392016-09-30 10:25:39 -0400893 return;
894 }
halcanary7a14b312015-10-01 07:28:13 -0700895 SkPaint paint = srcPaint;
896 if (bitmap.isOpaque()) {
897 replace_srcmode_on_opaque_paint(&paint);
898 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400899 SkImageSubset imageSubset = make_image_subset(bitmap);
900 if (!imageSubset.isValid()) {
halcanary7a14b312015-10-01 07:28:13 -0700901 return;
902 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400903 SkMatrix transform = SkMatrix::MakeTrans(SkIntToScalar(x), SkIntToScalar(y));
halcanarya50151d2016-03-25 11:57:49 -0700904 this->internalDrawImage(
Hal Canaryf50ff392016-09-30 10:25:39 -0400905 transform, d.fClipStack, d.fRC->bwRgn(), std::move(imageSubset), paint);
halcanary7a14b312015-10-01 07:28:13 -0700906}
907
908void SkPDFDevice::drawImage(const SkDraw& draw,
909 const SkImage* image,
910 SkScalar x,
911 SkScalar y,
912 const SkPaint& srcPaint) {
913 SkPaint paint = srcPaint;
Hal Canaryf3ee34f2017-02-07 16:58:28 -0500914 if (!image) {
halcanary7a14b312015-10-01 07:28:13 -0700915 return;
916 }
917 if (image->isOpaque()) {
918 replace_srcmode_on_opaque_paint(&paint);
919 }
Hal Canaryf50ff392016-09-30 10:25:39 -0400920 SkImageSubset imageSubset(sk_ref_sp(const_cast<SkImage*>(image)));
921 if (!imageSubset.isValid()) {
922 return;
923 }
halcanary7a14b312015-10-01 07:28:13 -0700924 SkMatrix transform = SkMatrix::MakeTrans(x, y);
925 transform.postConcat(*draw.fMatrix);
halcanarya50151d2016-03-25 11:57:49 -0700926 this->internalDrawImage(
Hal Canaryf50ff392016-09-30 10:25:39 -0400927 transform, draw.fClipStack, draw.fRC->bwRgn(), std::move(imageSubset), paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000928}
929
halcanaryf0c30f52016-07-15 13:35:45 -0700930namespace {
931class GlyphPositioner {
932public:
933 GlyphPositioner(SkDynamicMemoryWStream* content,
934 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -0700935 bool wideChars,
936 bool defaultPositioning,
937 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -0700938 : fContent(content)
halcanaryc2f9ec12016-09-12 08:55:29 -0700939 , fCurrentMatrixOrigin(origin)
940 , fTextSkewX(textSkewX)
halcanaryf0c30f52016-07-15 13:35:45 -0700941 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -0700942 , fDefaultPositioning(defaultPositioning) {
halcanaryf0c30f52016-07-15 13:35:45 -0700943 }
halcanary4871f222016-08-26 13:17:44 -0700944 ~GlyphPositioner() { this->flush(); }
halcanaryf0c30f52016-07-15 13:35:45 -0700945 void flush() {
946 if (fInText) {
947 fContent->writeText("> Tj\n");
948 fInText = false;
949 }
950 }
halcanary4871f222016-08-26 13:17:44 -0700951 void writeGlyph(SkPoint xy,
halcanaryf0c30f52016-07-15 13:35:45 -0700952 SkScalar advanceWidth,
953 uint16_t glyph) {
halcanaryc2f9ec12016-09-12 08:55:29 -0700954 if (!fInitialized) {
955 // Flip the text about the x-axis to account for origin swap and include
956 // the passed parameters.
957 fContent->writeText("1 0 ");
958 SkPDFUtils::AppendScalar(-fTextSkewX, fContent);
959 fContent->writeText(" -1 ");
960 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.x(), fContent);
961 fContent->writeText(" ");
962 SkPDFUtils::AppendScalar(fCurrentMatrixOrigin.y(), fContent);
963 fContent->writeText(" Tm\n");
964 fCurrentMatrixOrigin.set(0.0f, 0.0f);
965 fInitialized = true;
966 }
Hal Canary7bb93012016-10-31 12:40:49 -0400967#ifdef SK_BUILD_FOR_WIN
968 const bool kAlwaysPosition = true;
969#else
970 const bool kAlwaysPosition = false;
971#endif
halcanary4ed2f012016-08-15 18:40:07 -0700972 if (!fDefaultPositioning) {
halcanary4871f222016-08-26 13:17:44 -0700973 SkPoint position = xy - fCurrentMatrixOrigin;
Hal Canary7bb93012016-10-31 12:40:49 -0400974 if (kAlwaysPosition || position != SkPoint{fXAdvance, 0}) {
halcanary4ed2f012016-08-15 18:40:07 -0700975 this->flush();
halcanary4871f222016-08-26 13:17:44 -0700976 SkPDFUtils::AppendScalar(position.x(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -0700977 fContent->writeText(" ");
halcanary4871f222016-08-26 13:17:44 -0700978 SkPDFUtils::AppendScalar(-position.y(), fContent);
halcanary4ed2f012016-08-15 18:40:07 -0700979 fContent->writeText(" Td ");
halcanary4871f222016-08-26 13:17:44 -0700980 fCurrentMatrixOrigin = xy;
halcanary4ed2f012016-08-15 18:40:07 -0700981 fXAdvance = 0;
982 }
983 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -0700984 }
985 if (!fInText) {
986 fContent->writeText("<");
987 fInText = true;
988 }
989 if (fWideChars) {
990 SkPDFUtils::WriteUInt16BE(fContent, glyph);
991 } else {
992 SkASSERT(0 == glyph >> 8);
993 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
994 }
halcanaryf0c30f52016-07-15 13:35:45 -0700995 }
996
997private:
998 SkDynamicMemoryWStream* fContent;
halcanary4871f222016-08-26 13:17:44 -0700999 SkPoint fCurrentMatrixOrigin;
halcanaryc2f9ec12016-09-12 08:55:29 -07001000 SkScalar fXAdvance = 0.0f;
1001 SkScalar fTextSkewX;
halcanaryf0c30f52016-07-15 13:35:45 -07001002 bool fWideChars;
halcanaryc2f9ec12016-09-12 08:55:29 -07001003 bool fInText = false;
1004 bool fInitialized = false;
halcanary4ed2f012016-08-15 18:40:07 -07001005 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001006};
halcanaryf59d18a2016-09-16 14:44:57 -07001007
1008/** Given the m-to-n glyph-to-character mapping data (as returned by
1009 harfbuzz), iterate over the clusters. */
1010class Clusterator {
1011public:
1012 Clusterator() : fClusters(nullptr), fUtf8Text(nullptr), fGlyphCount(0), fTextByteLength(0) {}
1013 explicit Clusterator(uint32_t glyphCount)
1014 : fClusters(nullptr)
1015 , fUtf8Text(nullptr)
1016 , fGlyphCount(glyphCount)
1017 , fTextByteLength(0) {}
1018 // The clusters[] array is an array of offsets into utf8Text[],
1019 // one offset for each glyph. See SkTextBlobBuilder for more info.
1020 Clusterator(const uint32_t* clusters,
1021 const char* utf8Text,
1022 uint32_t glyphCount,
1023 uint32_t textByteLength)
1024 : fClusters(clusters)
1025 , fUtf8Text(utf8Text)
1026 , fGlyphCount(glyphCount)
1027 , fTextByteLength(textByteLength) {
1028 // This is a cheap heuristic for /ReversedChars which seems to
1029 // work for clusters produced by HarfBuzz, which either
1030 // increase from zero (LTR) or decrease to zero (RTL).
1031 // "ReversedChars" is how PDF deals with RTL text.
1032 fReversedChars =
1033 fUtf8Text && fClusters && fGlyphCount && fClusters[0] != 0;
1034 }
1035 struct Cluster {
1036 const char* fUtf8Text;
1037 uint32_t fTextByteLength;
1038 uint32_t fGlyphIndex;
1039 uint32_t fGlyphCount;
1040 explicit operator bool() const { return fGlyphCount != 0; }
1041 };
1042 // True if this looks like right-to-left text.
1043 bool reversedChars() const { return fReversedChars; }
1044 Cluster next() {
1045 if ((!fUtf8Text || !fClusters) && fGlyphCount) {
1046 // These glyphs have no text. Treat as one "cluster".
1047 uint32_t glyphCount = fGlyphCount;
1048 fGlyphCount = 0;
1049 return Cluster{nullptr, 0, 0, glyphCount};
1050 }
1051 if (fGlyphCount == 0 || fTextByteLength == 0) {
1052 return Cluster{nullptr, 0, 0, 0}; // empty
1053 }
1054 SkASSERT(fUtf8Text);
1055 SkASSERT(fClusters);
1056 uint32_t cluster = fClusters[0];
1057 if (cluster >= fTextByteLength) {
1058 return Cluster{nullptr, 0, 0, 0}; // bad input.
1059 }
1060 uint32_t glyphsInCluster = 1;
1061 while (glyphsInCluster < fGlyphCount &&
1062 fClusters[glyphsInCluster] == cluster) {
1063 ++glyphsInCluster;
1064 }
1065 SkASSERT(glyphsInCluster <= fGlyphCount);
1066 uint32_t textLength = 0;
1067 if (glyphsInCluster == fGlyphCount) {
1068 // consumes rest of glyphs and rest of text
1069 if (kInvalidCluster == fPreviousCluster) { // LTR text or single cluster
1070 textLength = fTextByteLength - cluster;
1071 } else { // RTL text; last cluster.
1072 SkASSERT(fPreviousCluster < fTextByteLength);
1073 if (fPreviousCluster <= cluster) { // bad input.
1074 return Cluster{nullptr, 0, 0, 0};
1075 }
1076 textLength = fPreviousCluster - cluster;
1077 }
1078 fGlyphCount = 0;
1079 return Cluster{fUtf8Text + cluster,
1080 textLength,
1081 fGlyphIndex,
1082 glyphsInCluster};
1083 }
1084 SkASSERT(glyphsInCluster < fGlyphCount);
1085 uint32_t nextCluster = fClusters[glyphsInCluster];
1086 if (nextCluster >= fTextByteLength) {
1087 return Cluster{nullptr, 0, 0, 0}; // bad input.
1088 }
1089 if (nextCluster > cluster) { // LTR text
1090 if (kInvalidCluster != fPreviousCluster) {
1091 return Cluster{nullptr, 0, 0, 0}; // bad input.
1092 }
1093 textLength = nextCluster - cluster;
1094 } else { // RTL text
1095 SkASSERT(nextCluster < cluster);
1096 if (kInvalidCluster == fPreviousCluster) { // first cluster
1097 textLength = fTextByteLength - cluster;
1098 } else { // later cluster
1099 if (fPreviousCluster <= cluster) {
1100 return Cluster{nullptr, 0, 0, 0}; // bad input.
1101 }
1102 textLength = fPreviousCluster - cluster;
1103 }
1104 fPreviousCluster = cluster;
1105 }
1106 uint32_t glyphIndex = fGlyphIndex;
1107 fGlyphCount -= glyphsInCluster;
1108 fGlyphIndex += glyphsInCluster;
1109 fClusters += glyphsInCluster;
1110 return Cluster{fUtf8Text + cluster,
1111 textLength,
1112 glyphIndex,
1113 glyphsInCluster};
1114 }
1115
1116private:
1117 static constexpr uint32_t kInvalidCluster = 0xFFFFFFFF;
1118 const uint32_t* fClusters;
1119 const char* fUtf8Text;
1120 uint32_t fGlyphCount;
1121 uint32_t fTextByteLength;
1122 uint32_t fGlyphIndex = 0;
1123 uint32_t fPreviousCluster = kInvalidCluster;
1124 bool fReversedChars = false;
1125};
1126
1127struct TextStorage {
1128 SkAutoTMalloc<char> fUtf8textStorage;
1129 SkAutoTMalloc<uint32_t> fClusterStorage;
1130 SkAutoTMalloc<SkGlyphID> fGlyphStorage;
1131};
halcanaryf0c30f52016-07-15 13:35:45 -07001132} // namespace
1133
halcanaryf59d18a2016-09-16 14:44:57 -07001134/** Given some unicode text (as passed to drawText(), convert to
1135 glyphs (via primitive shaping), while preserving
1136 glyph-to-character mapping information. */
1137static Clusterator make_clusterator(
1138 const void* sourceText,
1139 size_t sourceByteCount,
1140 const SkPaint& paint,
1141 TextStorage* storage,
1142 int glyphCount) {
1143 SkASSERT(SkPaint::kGlyphID_TextEncoding != paint.getTextEncoding());
1144 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1145 SkASSERT(glyphCount > 0);
1146 storage->fGlyphStorage.reset(SkToSizeT(glyphCount));
1147 (void)paint.textToGlyphs(sourceText, sourceByteCount, storage->fGlyphStorage.get());
1148 storage->fClusterStorage.reset(SkToSizeT(glyphCount));
1149 uint32_t* clusters = storage->fClusterStorage.get();
1150 uint32_t utf8ByteCount = 0;
1151 const char* utf8Text = nullptr;
1152 switch (paint.getTextEncoding()) {
1153 case SkPaint::kUTF8_TextEncoding: {
1154 const char* txtPtr = (const char*)sourceText;
1155 for (int i = 0; i < glyphCount; ++i) {
1156 clusters[i] = SkToU32(txtPtr - (const char*)sourceText);
1157 txtPtr += SkUTF8_LeadByteToCount(*(const unsigned char*)txtPtr);
1158 SkASSERT(txtPtr <= (const char*)sourceText + sourceByteCount);
1159 }
1160 SkASSERT(txtPtr == (const char*)sourceText + sourceByteCount);
1161 utf8ByteCount = SkToU32(sourceByteCount);
1162 utf8Text = (const char*)sourceText;
1163 break;
1164 }
1165 case SkPaint::kUTF16_TextEncoding: {
1166 const uint16_t* utf16ptr = (const uint16_t*)sourceText;
1167 int utf16count = SkToInt(sourceByteCount / sizeof(uint16_t));
1168 utf8ByteCount = SkToU32(SkUTF16_ToUTF8(utf16ptr, utf16count));
1169 storage->fUtf8textStorage.reset(utf8ByteCount);
1170 char* txtPtr = storage->fUtf8textStorage.get();
1171 utf8Text = txtPtr;
1172 int clusterIndex = 0;
1173 while (utf16ptr < (const uint16_t*)sourceText + utf16count) {
1174 clusters[clusterIndex++] = SkToU32(txtPtr - utf8Text);
1175 SkUnichar uni = SkUTF16_NextUnichar(&utf16ptr);
1176 txtPtr += SkUTF8_FromUnichar(uni, txtPtr);
1177 }
1178 SkASSERT(clusterIndex == glyphCount);
1179 SkASSERT(txtPtr == storage->fUtf8textStorage.get() + utf8ByteCount);
1180 SkASSERT(utf16ptr == (const uint16_t*)sourceText + utf16count);
1181 break;
1182 }
1183 case SkPaint::kUTF32_TextEncoding: {
1184 const SkUnichar* utf32 = (const SkUnichar*)sourceText;
1185 int utf32count = SkToInt(sourceByteCount / sizeof(SkUnichar));
1186 SkASSERT(glyphCount == utf32count);
1187 for (int i = 0; i < utf32count; ++i) {
1188 utf8ByteCount += SkToU32(SkUTF8_FromUnichar(utf32[i]));
1189 }
1190 storage->fUtf8textStorage.reset(SkToSizeT(utf8ByteCount));
1191 char* txtPtr = storage->fUtf8textStorage.get();
1192 utf8Text = txtPtr;
1193 for (int i = 0; i < utf32count; ++i) {
1194 clusters[i] = SkToU32(txtPtr - utf8Text);
1195 txtPtr += SkUTF8_FromUnichar(utf32[i], txtPtr);
1196 }
1197 break;
1198 }
1199 default:
1200 SkDEBUGFAIL("");
1201 break;
1202 }
1203 return Clusterator(clusters, utf8Text, SkToU32(glyphCount), utf8ByteCount);
1204}
1205
halcanaryf59d18a2016-09-16 14:44:57 -07001206static SkUnichar map_glyph(const SkTDArray<SkUnichar>& glyphToUnicode, SkGlyphID glyph) {
1207 return SkToInt(glyph) < glyphToUnicode.count() ? glyphToUnicode[SkToInt(glyph)] : -1;
1208}
1209
halcanaryc2f9ec12016-09-12 08:55:29 -07001210static void update_font(SkWStream* wStream, int fontIndex, SkScalar textSize) {
1211 wStream->writeText("/");
1212 char prefix = SkPDFResourceDict::GetResourceTypePrefix(SkPDFResourceDict::kFont_ResourceType);
1213 wStream->write(&prefix, 1);
1214 wStream->writeDecAsText(fontIndex);
1215 wStream->writeText(" ");
1216 SkPDFUtils::AppendScalar(textSize, wStream);
1217 wStream->writeText(" Tf\n");
1218}
1219
halcanary4ed2f012016-08-15 18:40:07 -07001220void SkPDFDevice::internalDrawText(
1221 const SkDraw& d, const void* sourceText, size_t sourceByteCount,
1222 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
halcanarye06ca962016-09-09 05:34:55 -07001223 SkPoint offset, const SkPaint& srcPaint, const uint32_t* clusters,
1224 uint32_t textByteLength, const char* utf8Text) {
halcanary4ed2f012016-08-15 18:40:07 -07001225 NOT_IMPLEMENTED(srcPaint.getMaskFilter() != nullptr, false);
1226 if (srcPaint.getMaskFilter() != nullptr) {
1227 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1228 // making text unreadable (e.g. same text twice when using CSS shadows).
1229 return;
1230 }
halcanaryea17dfe2016-08-24 09:20:57 -07001231 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1232 if (srcPaint.isVerticalText()) {
1233 // Don't pretend we support drawing vertical text. It is not
1234 // clear to me how to switch to "vertical writing" mode in PDF.
1235 // Currently neither Chromium or Android set this flag.
1236 // https://bug.skia.org/5665
1237 return;
1238 }
halcanaryf59d18a2016-09-16 14:44:57 -07001239 if (0 == sourceByteCount || !sourceText) {
1240 return;
halcanarye06ca962016-09-09 05:34:55 -07001241 }
halcanary4ed2f012016-08-15 18:40:07 -07001242 SkPaint paint = calculate_text_paint(srcPaint);
1243 replace_srcmode_on_opaque_paint(&paint);
1244 if (!paint.getTypeface()) {
1245 paint.setTypeface(SkTypeface::MakeDefault());
1246 }
1247 SkTypeface* typeface = paint.getTypeface();
1248 if (!typeface) {
1249 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1250 return;
1251 }
halcanary4871f222016-08-26 13:17:44 -07001252
1253 const SkAdvancedTypefaceMetrics* metrics =
1254 SkPDFFont::GetMetrics(typeface, fDocument->canon());
1255 if (!metrics) {
halcanary4ed2f012016-08-15 18:40:07 -07001256 return;
1257 }
halcanary2bd295e2016-09-16 08:15:56 -07001258 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1259 if (glyphCount <= 0) {
1260 return;
1261 }
halcanary3b294d52016-09-16 13:21:08 -07001262
halcanaryf59d18a2016-09-16 14:44:57 -07001263 // These three heap buffers are only used in the case where no glyphs
1264 // are passed to drawText() (most clients pass glyphs or a textblob).
1265 TextStorage storage;
1266 const SkGlyphID* glyphs = nullptr;
1267 Clusterator clusterator;
1268 if (textByteLength > 0) {
1269 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1270 glyphs = (const SkGlyphID*)sourceText;
1271 clusterator = Clusterator(clusters, utf8Text, SkToU32(glyphCount), textByteLength);
1272 SkASSERT(clusters);
1273 SkASSERT(utf8Text);
1274 SkASSERT(srcPaint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
1275 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1276 } else if (SkPaint::kGlyphID_TextEncoding == srcPaint.getTextEncoding()) {
1277 SkASSERT(glyphCount == SkToInt(sourceByteCount / sizeof(SkGlyphID)));
1278 glyphs = (const SkGlyphID*)sourceText;
1279 clusterator = Clusterator(SkToU32(glyphCount));
1280 SkASSERT(glyphCount == paint.textToGlyphs(sourceText, sourceByteCount, nullptr));
1281 SkASSERT(nullptr == clusters);
1282 SkASSERT(nullptr == utf8Text);
1283 } else {
1284 SkASSERT(nullptr == clusters);
1285 SkASSERT(nullptr == utf8Text);
1286 clusterator = make_clusterator(sourceText, sourceByteCount, srcPaint,
1287 &storage, glyphCount);
1288 glyphs = storage.fGlyphStorage;
1289 }
halcanary4ed2f012016-08-15 18:40:07 -07001290 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
halcanary9df5a4c2016-08-24 10:08:13 -07001291 paint.setHinting(SkPaint::kNo_Hinting);
halcanary4ed2f012016-08-15 18:40:07 -07001292 SkAutoGlyphCache glyphCache(paint, nullptr, nullptr);
1293
1294 SkPaint::Align alignment = paint.getTextAlign();
halcanary4871f222016-08-26 13:17:44 -07001295 float alignmentFactor = SkPaint::kLeft_Align == alignment ? 0.0f :
1296 SkPaint::kCenter_Align == alignment ? -0.5f :
1297 /* SkPaint::kRight_Align */ -1.0f;
halcanary4ed2f012016-08-15 18:40:07 -07001298 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
halcanary4871f222016-08-26 13:17:44 -07001299 SkScalar advance = 0;
halcanary4ed2f012016-08-15 18:40:07 -07001300 for (int i = 0; i < glyphCount; ++i) {
1301 advance += glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
1302 }
halcanary4871f222016-08-26 13:17:44 -07001303 offset.offset(alignmentFactor * advance, 0);
halcanary6059dc32016-08-15 11:45:36 -07001304 }
halcanary4ed2f012016-08-15 18:40:07 -07001305 ScopedContentEntry content(this, d, paint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001306 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001307 return;
1308 }
halcanary4ed2f012016-08-15 18:40:07 -07001309 SkDynamicMemoryWStream* out = &content.entry()->fContent;
halcanary4871f222016-08-26 13:17:44 -07001310 SkScalar textSize = paint.getTextSize();
halcanaryf59d18a2016-09-16 14:44:57 -07001311 const SkTDArray<SkUnichar>& glyphToUnicode = metrics->fGlyphToUnicode;
halcanary4871f222016-08-26 13:17:44 -07001312
halcanary4871f222016-08-26 13:17:44 -07001313 out->writeText("BT\n");
1314 SK_AT_SCOPE_EXIT(out->writeText("ET\n"));
1315
halcanaryf59d18a2016-09-16 14:44:57 -07001316 const SkGlyphID maxGlyphID = metrics->fLastGlyphID;
halcanaryc2f9ec12016-09-12 08:55:29 -07001317 bool multiByteGlyphs = SkPDFFont::IsMultiByte(SkPDFFont::FontType(*metrics));
halcanaryf59d18a2016-09-16 14:44:57 -07001318 if (clusterator.reversedChars()) {
1319 out->writeText("/ReversedChars BMC\n");
1320 }
1321 SK_AT_SCOPE_EXIT(if (clusterator.reversedChars()) { out->writeText("EMC\n"); } );
halcanary4ed2f012016-08-15 18:40:07 -07001322 GlyphPositioner glyphPositioner(out,
1323 paint.getTextSkewX(),
halcanaryc2f9ec12016-09-12 08:55:29 -07001324 multiByteGlyphs,
halcanary4ed2f012016-08-15 18:40:07 -07001325 defaultPositioning,
1326 offset);
halcanaryc2f9ec12016-09-12 08:55:29 -07001327 SkPDFFont* font = nullptr;
halcanaryf59d18a2016-09-16 14:44:57 -07001328
1329 while (Clusterator::Cluster c = clusterator.next()) {
1330 int index = c.fGlyphIndex;
1331 int glyphLimit = index + c.fGlyphCount;
1332
1333 bool actualText = false;
1334 SK_AT_SCOPE_EXIT(if (actualText) { glyphPositioner.flush(); out->writeText("EMC\n"); } );
1335 if (c.fUtf8Text) { // real cluster
1336 // Check if `/ActualText` needed.
1337 const char* textPtr = c.fUtf8Text;
halcanaryf59d18a2016-09-16 14:44:57 -07001338 const char* textEnd = c.fUtf8Text + c.fTextByteLength;
Hal Canaryd1c8e562017-01-11 15:53:25 -05001339 SkUnichar unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1340 if (unichar < 0) {
1341 return;
1342 }
halcanaryf59d18a2016-09-16 14:44:57 -07001343 if (textPtr < textEnd || // more characters left
1344 glyphLimit > index + 1 || // toUnicode wouldn't work
1345 unichar != map_glyph(glyphToUnicode, glyphs[index])) // test single Unichar map
1346 {
1347 glyphPositioner.flush();
1348 out->writeText("/Span<</ActualText <");
1349 SkPDFUtils::WriteUTF16beHex(out, 0xFEFF); // U+FEFF = BYTE ORDER MARK
1350 // the BOM marks this text as UTF-16BE, not PDFDocEncoding.
1351 SkPDFUtils::WriteUTF16beHex(out, unichar); // first char
1352 while (textPtr < textEnd) {
Hal Canaryd1c8e562017-01-11 15:53:25 -05001353 unichar = SkUTF8_NextUnicharWithError(&textPtr, textEnd);
1354 if (unichar < 0) {
1355 break;
1356 }
halcanaryf59d18a2016-09-16 14:44:57 -07001357 SkPDFUtils::WriteUTF16beHex(out, unichar);
1358 }
1359 out->writeText("> >> BDC\n"); // begin marked-content sequence
1360 // with an associated property list.
1361 actualText = true;
robertphillips5ba165e2016-08-15 15:36:58 -07001362 }
1363 }
halcanaryf59d18a2016-09-16 14:44:57 -07001364 for (; index < glyphLimit; ++index) {
1365 SkGlyphID gid = glyphs[index];
1366 if (gid > maxGlyphID) {
1367 continue;
1368 }
1369 if (!font || !font->hasGlyph(gid)) {
1370 // Not yet specified font or need to switch font.
1371 int fontIndex = this->getFontResourceIndex(typeface, gid);
1372 // All preconditions for SkPDFFont::GetFontResource are met.
1373 SkASSERT(fontIndex >= 0);
1374 if (fontIndex < 0) {
1375 return;
1376 }
1377 glyphPositioner.flush();
1378 update_font(out, fontIndex, textSize);
1379 font = fFontResources[fontIndex];
1380 SkASSERT(font); // All preconditions for SkPDFFont::GetFontResource are met.
1381 if (!font) {
1382 return;
1383 }
1384 SkASSERT(font->multiByteGlyphs() == multiByteGlyphs);
1385 }
1386 SkPoint xy{0, 0};
1387 SkScalar advance{0};
1388 if (!defaultPositioning) {
1389 advance = glyphCache->getGlyphIDAdvance(gid).fAdvanceX;
1390 xy = SkTextBlob::kFull_Positioning == positioning
1391 ? SkPoint{pos[2 * index], pos[2 * index + 1]}
1392 : SkPoint{pos[index], 0};
1393 if (alignment != SkPaint::kLeft_Align) {
1394 xy.offset(alignmentFactor * advance, 0);
1395 }
1396 }
1397 font->noteGlyphUsage(gid);
1398 SkGlyphID encodedGlyph = multiByteGlyphs ? gid : font->glyphToPDFFontEncoding(gid);
1399 glyphPositioner.writeGlyph(xy, advance, encodedGlyph);
1400 }
robertphillips5ba165e2016-08-15 15:36:58 -07001401 }
halcanary4ed2f012016-08-15 18:40:07 -07001402}
1403
1404void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
1405 SkScalar x, SkScalar y, const SkPaint& paint) {
1406 this->internalDrawText(d, text, len, nullptr, SkTextBlob::kDefault_Positioning,
halcanarye06ca962016-09-09 05:34:55 -07001407 SkPoint{x, y}, paint, nullptr, 0, nullptr);
halcanary4ed2f012016-08-15 18:40:07 -07001408}
1409
1410void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
1411 const SkScalar pos[], int scalarsPerPos,
1412 const SkPoint& offset, const SkPaint& paint) {
1413 this->internalDrawText(d, text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
halcanarye06ca962016-09-09 05:34:55 -07001414 offset, paint, nullptr, 0, nullptr);
1415}
1416
1417void SkPDFDevice::drawTextBlob(const SkDraw& draw, const SkTextBlob* blob, SkScalar x, SkScalar y,
1418 const SkPaint &paint, SkDrawFilter* drawFilter) {
1419 for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1420 SkPaint runPaint(paint);
1421 it.applyFontToPaint(&runPaint);
1422 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
1423 continue;
1424 }
1425 runPaint.setFlags(this->filterTextFlags(runPaint));
1426 SkPoint offset = it.offset() + SkPoint{x, y};
1427 this->internalDrawText(draw, it.glyphs(), sizeof(SkGlyphID) * it.glyphCount(),
1428 it.pos(), it.positioning(), offset, runPaint,
1429 it.clusters(), it.textSize(), it.text());
1430 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001431}
1432
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001433void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001434 int vertexCount, const SkPoint verts[],
1435 const SkPoint texs[], const SkColor colors[],
Mike Reedfaba3712016-11-03 14:45:31 -04001436 SkBlendMode, const uint16_t indices[],
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001437 int indexCount, const SkPaint& paint) {
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001438 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001439 return;
1440 }
reed@google.com85e143c2013-12-30 15:51:25 +00001441 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001442}
1443
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001444void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1445 int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001446 SkASSERT(!paint.getImageFilter());
1447
reed7503d602016-07-15 14:23:29 -07001448 // Check if the source device is really a bitmapdevice (because that's what we returned
1449 // from createDevice (likely due to an imagefilter)
1450 SkPixmap pmap;
1451 if (device->peekPixels(&pmap)) {
1452 SkBitmap bitmap;
1453 bitmap.installPixels(pmap);
reedcf5c8462016-07-20 12:28:40 -07001454 this->drawSprite(d, bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001455 return;
1456 }
1457
fmalita6987dca2014-11-13 08:33:37 -08001458 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001459 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001460
1461 SkScalar scalarX = SkIntToScalar(x);
1462 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001463 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1464 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001465 fLinkToURLs.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001466 }
halcanary91fcb3e2016-03-04 13:53:22 -08001467 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1468 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001469 fLinkToDestinations.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001470 }
halcanary91fcb3e2016-03-04 13:53:22 -08001471 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1472 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001473 fNamedDestinations.emplace_back(d.nameData.get(), p);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001474 }
1475
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001476 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001477 return;
1478 }
1479
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001480 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001481 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
reed1e7f5e72016-04-27 07:49:17 -07001482 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001483 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001484 return;
1485 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001486 if (content.needShape()) {
1487 SkPath shape;
1488 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001489 SkIntToScalar(device->width()),
1490 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001491 content.setShape(shape);
1492 }
1493 if (!content.needSource()) {
1494 return;
1495 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001496
halcanary4b1e17e2016-07-27 14:49:46 -07001497 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001498 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001499 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001500}
1501
reede8f30622016-03-23 18:59:25 -07001502sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1503 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001504}
1505
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001506
halcanary8103a342016-03-08 15:10:16 -08001507sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001508 SkTDArray<SkPDFObject*> fonts;
1509 fonts.setReserve(fFontResources.count());
1510 for (SkPDFFont* font : fFontResources) {
1511 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001512 }
halcanary8103a342016-03-08 15:10:16 -08001513 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001514 &fGraphicStateResources,
1515 &fShaderResources,
1516 &fXObjectResources,
1517 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001518}
1519
halcanary8103a342016-03-08 15:10:16 -08001520sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001521 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001522 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001523 mediaBox->appendInt(0);
1524 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001525 mediaBox->appendInt(fPageSize.width());
1526 mediaBox->appendInt(fPageSize.height());
1527 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001528}
1529
mtklein5f939ab2016-03-16 10:28:35 -07001530std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001531 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001532 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001533 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001534 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001535
halcanaryafdc1772016-08-23 09:02:12 -07001536 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001537 for (const auto& entry : fContentEntries) {
1538 SkPoint translation;
1539 translation.iset(this->getOrigin());
1540 translation.negate();
1541 gsState.updateClip(entry.fState.fClipStack, entry.fState.fClipRegion,
Hal Canary44a97d52017-02-22 10:45:25 -05001542 translation, SkRect::Make(this->getGlobalBounds()));
halcanary2be7e012016-03-28 11:58:08 -07001543 gsState.updateMatrix(entry.fState.fMatrix);
1544 gsState.updateDrawingState(entry.fState);
1545
halcanaryafdc1772016-08-23 09:02:12 -07001546 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001547 }
1548 gsState.drainStack();
halcanary022c2bd2016-09-02 11:29:46 -07001549 if (buffer.bytesWritten() > 0) {
1550 return std::unique_ptr<SkStreamAsset>(buffer.detachAsStream());
1551 } else {
1552 return skstd::make_unique<SkMemoryStream>();
1553 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001554}
1555
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001556/* Draws an inverse filled path by using Path Ops to compute the positive
1557 * inverse using the current clip as the inverse bounds.
1558 * Return true if this was an inverse path and was properly handled,
1559 * otherwise returns false and the normal drawing routine should continue,
1560 * either as a (incorrect) fallback or because the path was not inverse
1561 * in the first place.
1562 */
1563bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001564 const SkPaint& paint, bool pathIsMutable,
1565 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001566 if (!origPath.isInverseFillType()) {
1567 return false;
1568 }
1569
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001570 if (d.fClipStack->isEmpty(this->getGlobalBounds())) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001571 return false;
1572 }
1573
1574 SkPath modifiedPath;
1575 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1576 SkPaint noInversePaint(paint);
1577
1578 // Merge stroking operations into final path.
1579 if (SkPaint::kStroke_Style == paint.getStyle() ||
1580 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1581 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1582 if (doFillPath) {
1583 noInversePaint.setStyle(SkPaint::kFill_Style);
1584 noInversePaint.setStrokeWidth(0);
1585 pathPtr = &modifiedPath;
1586 } else {
1587 // To be consistent with the raster output, hairline strokes
1588 // are rendered as non-inverted.
1589 modifiedPath.toggleInverseFillType();
halcanary96fcdcc2015-08-27 07:41:13 -07001590 drawPath(d, modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001591 return true;
1592 }
1593 }
1594
1595 // Get bounds of clip in current transform space
1596 // (clip bounds are given in device space).
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001597 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001598 SkMatrix totalMatrix = *d.fMatrix;
1599 if (prePathMatrix) {
1600 totalMatrix.preConcat(*prePathMatrix);
1601 }
1602 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001603 return false;
1604 }
Hal Canary44a97d52017-02-22 10:45:25 -05001605 SkRect bounds = d.fClipStack->bounds(this->getGlobalBounds());
1606 SkIPoint deviceOrigin = this->getOrigin();
1607 bounds.offset(-deviceOrigin.x(), -deviceOrigin.y());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001608 transformInverse.mapRect(&bounds);
1609
1610 // Extend the bounds by the line width (plus some padding)
1611 // so the edge doesn't cause a visible stroke.
1612 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1613 paint.getStrokeWidth() + SK_Scalar1);
1614
1615 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1616 return false;
1617 }
1618
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001619 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001620 return true;
1621}
1622
reedf70b5312016-03-04 16:36:20 -08001623void SkPDFDevice::handlePointAnnotation(const SkPoint& point,
epoger@google.comb58772f2013-03-08 09:09:10 +00001624 const SkMatrix& matrix,
reedf70b5312016-03-04 16:36:20 -08001625 const char key[], SkData* value) {
1626 if (!value) {
1627 return;
epoger@google.comb58772f2013-03-08 09:09:10 +00001628 }
reedf70b5312016-03-04 16:36:20 -08001629
1630 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
1631 SkPoint transformedPoint;
1632 matrix.mapXY(point.x(), point.y(), &transformedPoint);
1633 fNamedDestinations.emplace_back(value, transformedPoint);
1634 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001635}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001636
reedf70b5312016-03-04 16:36:20 -08001637void SkPDFDevice::handlePathAnnotation(const SkPath& path,
wangxianzhuef6c50a2015-09-17 20:38:02 -07001638 const SkDraw& d,
reedf70b5312016-03-04 16:36:20 -08001639 const char key[], SkData* value) {
1640 if (!value) {
1641 return;
1642 }
wangxianzhuef6c50a2015-09-17 20:38:02 -07001643
wangxianzhuef6c50a2015-09-17 20:38:02 -07001644 SkRasterClip clip = *d.fRC;
Brian Salomona3b45d42016-10-03 11:36:16 -04001645 clip.op(path, *d.fMatrix, SkIRect::MakeWH(width(), height()),
1646 SkRegion::kIntersect_Op,
senorblancoafc7cce2016-02-02 18:44:15 -08001647 false);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001648 SkRect transformedRect = SkRect::Make(clip.getBounds());
1649
reedf70b5312016-03-04 16:36:20 -08001650 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001651 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001652 fLinkToURLs.emplace_back(transformedRect, value);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001653 }
reedf70b5312016-03-04 16:36:20 -08001654 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
reed16108352016-03-03 09:14:36 -08001655 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001656 fLinkToDestinations.emplace_back(transformedRect, value);
reed16108352016-03-03 09:14:36 -08001657 }
reed16108352016-03-03 09:14:36 -08001658 }
halcanary438de492015-04-28 06:21:01 -07001659}
1660
wangxianzhuef6c50a2015-09-17 20:38:02 -07001661void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1662 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001663 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001664 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001665 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001666 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001667 }
halcanary91fcb3e2016-03-04 13:53:22 -08001668 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001669 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001670 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001671 array->appendObject(
1672 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001673 }
1674}
epoger@google.comb58772f2013-03-08 09:09:10 +00001675
halcanary6d622702015-03-25 08:45:42 -07001676void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001677 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001678 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001679 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001680 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001681 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001682 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001683 pdfDest->appendScalar(p.x());
1684 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001685 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001686 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001687 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001688 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001689}
1690
halcanary4b1e17e2016-07-27 14:49:46 -07001691sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
halcanary5abbb442016-07-29 08:41:33 -07001692 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001693 if (!fInitialTransform.isIdentity()) {
1694 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001695 SkDEBUGFAIL("Layer initial transform should be invertible.");
1696 inverseTransform.reset();
1697 }
1698 }
halcanary4b1e17e2016-07-27 14:49:46 -07001699 sk_sp<SkPDFObject> xobject =
1700 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
halcanary5abbb442016-07-29 08:41:33 -07001701 this->makeResourceDict(), inverseTransform, nullptr);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001702 // We always draw the form xobjects that we create back into the device, so
1703 // we simply preserve the font usage instead of pulling it out and merging
1704 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001705 this->cleanUp(); // Reset this device to have no content.
1706 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001707 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001708}
1709
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001710void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001711 sk_sp<SkPDFObject> mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001712 const SkClipStack* clipStack,
1713 const SkRegion& clipRegion,
reed374772b2016-10-05 17:33:02 -07001714 SkBlendMode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001715 bool invertClip) {
1716 if (clipRegion.isEmpty() && !invertClip) {
1717 return;
1718 }
1719
halcanary4b1e17e2016-07-27 14:49:46 -07001720 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001721 std::move(mask), invertClip,
1722 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001723
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001724 SkMatrix identity;
1725 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001726 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001727 paint.setBlendMode(mode);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001728 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001729 if (!content.entry()) {
1730 return;
1731 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001732 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001733 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001734 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001735
halcanary1437c1e2016-03-13 18:30:24 -07001736 // Call makeNoSmaskGraphicState() instead of
1737 // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1738 // can deduplicate.
halcanary989da4a2016-03-21 14:33:17 -07001739 sMaskGS = fDocument->canon()->makeNoSmaskGraphicState();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001740 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001741 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001742}
1743
halcanary2be7e012016-03-28 11:58:08 -07001744SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001745 const SkRegion& clipRegion,
1746 const SkMatrix& matrix,
1747 const SkPaint& paint,
1748 bool hasText,
1749 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001750 *dst = nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001751 if (clipRegion.isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -07001752 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001753 }
Hal Canaryf3ee34f2017-02-07 16:58:28 -05001754 SkASSERT(clipStack);
reed374772b2016-10-05 17:33:02 -07001755 SkBlendMode blendMode = paint.getBlendMode();
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001756
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001757 // For the following modes, we want to handle source and destination
1758 // separately, so make an object of what's already there.
reed374772b2016-10-05 17:33:02 -07001759 if (blendMode == SkBlendMode::kClear ||
1760 blendMode == SkBlendMode::kSrc ||
1761 blendMode == SkBlendMode::kSrcIn ||
1762 blendMode == SkBlendMode::kDstIn ||
1763 blendMode == SkBlendMode::kSrcOut ||
1764 blendMode == SkBlendMode::kDstOut ||
1765 blendMode == SkBlendMode::kSrcATop ||
1766 blendMode == SkBlendMode::kDstATop ||
1767 blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001768 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001769 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001770 SkASSERT(isContentEmpty());
reed374772b2016-10-05 17:33:02 -07001771 } else if (blendMode != SkBlendMode::kSrc &&
1772 blendMode != SkBlendMode::kSrcOut) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001773 // Except for Src and SrcOut, if there isn't anything already there,
1774 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001775 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001776 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001777 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001778 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001779 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001780
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001781 // Dst xfer mode doesn't draw source at all.
reed374772b2016-10-05 17:33:02 -07001782 if (blendMode == SkBlendMode::kDst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001783 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001784 }
1785
halcanary2be7e012016-03-28 11:58:08 -07001786 SkPDFDevice::ContentEntry* entry;
Ben Wagner884300d2016-12-16 16:51:41 +00001787 if (fContentEntries.back() && fContentEntries.back()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001788 entry = fContentEntries.back();
reed374772b2016-10-05 17:33:02 -07001789 } else if (blendMode != SkBlendMode::kDstOver) {
halcanary2be7e012016-03-28 11:58:08 -07001790 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001791 } else {
halcanary2be7e012016-03-28 11:58:08 -07001792 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001793 }
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001794 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001795 hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001796 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001797}
1798
reed374772b2016-10-05 17:33:02 -07001799void SkPDFDevice::finishContentEntry(SkBlendMode blendMode,
halcanarydabd4f02016-08-03 11:16:56 -07001800 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001801 SkPath* shape) {
reed374772b2016-10-05 17:33:02 -07001802 if (blendMode != SkBlendMode::kClear &&
1803 blendMode != SkBlendMode::kSrc &&
1804 blendMode != SkBlendMode::kDstOver &&
1805 blendMode != SkBlendMode::kSrcIn &&
1806 blendMode != SkBlendMode::kDstIn &&
1807 blendMode != SkBlendMode::kSrcOut &&
1808 blendMode != SkBlendMode::kDstOut &&
1809 blendMode != SkBlendMode::kSrcATop &&
1810 blendMode != SkBlendMode::kDstATop &&
1811 blendMode != SkBlendMode::kModulate) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001812 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001813 return;
1814 }
reed374772b2016-10-05 17:33:02 -07001815 if (blendMode == SkBlendMode::kDstOver) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001816 SkASSERT(!dst);
Ben Wagner884300d2016-12-16 16:51:41 +00001817 if (fContentEntries.front()->fContent.bytesWritten() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001818 // For DstOver, an empty content entry was inserted before the rest
1819 // of the content entries. If nothing was drawn, it needs to be
1820 // removed.
halcanary2be7e012016-03-28 11:58:08 -07001821 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001822 }
1823 return;
1824 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001825 if (!dst) {
reed374772b2016-10-05 17:33:02 -07001826 SkASSERT(blendMode == SkBlendMode::kSrc ||
1827 blendMode == SkBlendMode::kSrcOut);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001828 return;
1829 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001830
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001831 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07001832 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001833 // Changing the current content into a form-xobject will destroy the clip
1834 // objects which is fine since the xobject will already be clipped. However
1835 // if source has shape, we need to clip it too, so a copy of the clip is
1836 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001837
1838 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
1839 SkRegion clipRegion = fContentEntries.front()->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001840
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001841 SkMatrix identity;
1842 identity.reset();
1843 SkPaint stockPaint;
1844
halcanary4b1e17e2016-07-27 14:49:46 -07001845 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001846 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001847 // If nothing was drawn and there's no shape, then the draw was a
1848 // no-op, but dst needs to be restored for that to be true.
1849 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1850 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1851 // reduces to Dst.
reed374772b2016-10-05 17:33:02 -07001852 if (shape == nullptr || blendMode == SkBlendMode::kDstOut ||
1853 blendMode == SkBlendMode::kSrcATop) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001854 ScopedContentEntry content(this, &fExistingClipStack,
1855 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001856 stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07001857 // TODO: addXObjectResource take sk_sp
1858 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001859 &content.entry()->fContent);
1860 return;
1861 } else {
reed374772b2016-10-05 17:33:02 -07001862 blendMode = SkBlendMode::kClear;
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001863 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001864 } else {
halcanary2be7e012016-03-28 11:58:08 -07001865 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07001866 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001867 }
1868
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001869 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1870 // without alpha.
reed374772b2016-10-05 17:33:02 -07001871 if (blendMode == SkBlendMode::kSrcATop) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001872 // TODO(vandebo): In order to properly support SrcATop we have to track
1873 // the shape of what's been drawn at all times. It's the intersection of
1874 // the non-transparent parts of the device and the outlines (shape) of
1875 // all images and devices drawn.
1876 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001877 &fExistingClipStack, fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001878 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001879 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001880 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001881 // Draw shape into a form-xobject.
reed1e7f5e72016-04-27 07:49:17 -07001882 SkRasterClip rc(clipRegion);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001883 SkDraw d;
1884 d.fMatrix = &identity;
reed1e7f5e72016-04-27 07:49:17 -07001885 d.fRC = &rc;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001886 d.fClipStack = &clipStack;
1887 SkPaint filledPaint;
1888 filledPaint.setColor(SK_ColorBLACK);
1889 filledPaint.setStyle(SkPaint::kFill_Style);
halcanary96fcdcc2015-08-27 07:41:13 -07001890 this->drawPath(d, *shape, filledPaint, nullptr, true);
halcanarydabd4f02016-08-03 11:16:56 -07001891 drawFormXObjectWithMask(addXObjectResource(dst.get()),
1892 this->makeFormXObjectFromDevice(),
1893 &fExistingClipStack, fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001894 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001895
halcanarydabd4f02016-08-03 11:16:56 -07001896 } else {
1897 drawFormXObjectWithMask(addXObjectResource(dst.get()), srcFormXObject,
1898 &fExistingClipStack, fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001899 SkBlendMode::kSrcOver, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001900 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001901 }
1902
reed374772b2016-10-05 17:33:02 -07001903 if (blendMode == SkBlendMode::kClear) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001904 return;
reed374772b2016-10-05 17:33:02 -07001905 } else if (blendMode == SkBlendMode::kSrc ||
1906 blendMode == SkBlendMode::kDstATop) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001907 ScopedContentEntry content(this, &fExistingClipStack,
1908 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001909 if (content.entry()) {
1910 SkPDFUtils::DrawFormXObject(
1911 this->addXObjectResource(srcFormXObject.get()),
1912 &content.entry()->fContent);
1913 }
reed374772b2016-10-05 17:33:02 -07001914 if (blendMode == SkBlendMode::kSrc) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001915 return;
1916 }
reed374772b2016-10-05 17:33:02 -07001917 } else if (blendMode == SkBlendMode::kSrcATop) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001918 ScopedContentEntry content(this, &fExistingClipStack,
1919 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001920 if (content.entry()) {
halcanarydabd4f02016-08-03 11:16:56 -07001921 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001922 &content.entry()->fContent);
1923 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001924 }
1925
reed374772b2016-10-05 17:33:02 -07001926 SkASSERT(blendMode == SkBlendMode::kSrcIn ||
1927 blendMode == SkBlendMode::kDstIn ||
1928 blendMode == SkBlendMode::kSrcOut ||
1929 blendMode == SkBlendMode::kDstOut ||
1930 blendMode == SkBlendMode::kSrcATop ||
1931 blendMode == SkBlendMode::kDstATop ||
1932 blendMode == SkBlendMode::kModulate);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001933
reed374772b2016-10-05 17:33:02 -07001934 if (blendMode == SkBlendMode::kSrcIn ||
1935 blendMode == SkBlendMode::kSrcOut ||
1936 blendMode == SkBlendMode::kSrcATop) {
halcanarydabd4f02016-08-03 11:16:56 -07001937 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1938 std::move(dst),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001939 &fExistingClipStack, fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001940 SkBlendMode::kSrcOver,
1941 blendMode == SkBlendMode::kSrcOut);
halcanarydabd4f02016-08-03 11:16:56 -07001942 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001943 } else {
reed374772b2016-10-05 17:33:02 -07001944 SkBlendMode mode = SkBlendMode::kSrcOver;
halcanarydabd4f02016-08-03 11:16:56 -07001945 int resourceID = addXObjectResource(dst.get());
reed374772b2016-10-05 17:33:02 -07001946 if (blendMode == SkBlendMode::kModulate) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001947 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
halcanarydabd4f02016-08-03 11:16:56 -07001948 std::move(dst), &fExistingClipStack,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001949 fExistingClipRegion,
reed374772b2016-10-05 17:33:02 -07001950 SkBlendMode::kSrcOver, false);
1951 mode = SkBlendMode::kMultiply;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001952 }
halcanarydabd4f02016-08-03 11:16:56 -07001953 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001954 &fExistingClipStack, fExistingClipRegion, mode,
reed374772b2016-10-05 17:33:02 -07001955 blendMode == SkBlendMode::kDstOut);
halcanarydabd4f02016-08-03 11:16:56 -07001956 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001957 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001958}
1959
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001960bool SkPDFDevice::isContentEmpty() {
Ben Wagner884300d2016-12-16 16:51:41 +00001961 if (!fContentEntries.front() || fContentEntries.front()->fContent.bytesWritten() == 0) {
halcanary2be7e012016-03-28 11:58:08 -07001962 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001963 return true;
1964 }
1965 return false;
1966}
1967
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001968void SkPDFDevice::populateGraphicStateEntryFromPaint(
1969 const SkMatrix& matrix,
1970 const SkClipStack& clipStack,
1971 const SkRegion& clipRegion,
1972 const SkPaint& paint,
1973 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07001974 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07001975 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1976 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1977 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001978
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001979 entry->fMatrix = matrix;
1980 entry->fClipStack = clipStack;
1981 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001982 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1983 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001984
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001985 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08001986 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07001987 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001988 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001989 if (shader) {
Hal Canaryc8f91802017-02-12 20:29:12 -05001990 if (SkShader::kColor_GradientType == shader->asAGradient(nullptr)) {
1991 // We don't have to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001992 SkShader::GradientInfo gradientInfo;
Hal Canaryc8f91802017-02-12 20:29:12 -05001993 SkColor gradientColor = SK_ColorBLACK;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001994 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07001995 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001996 gradientInfo.fColorCount = 1;
Hal Canaryc8f91802017-02-12 20:29:12 -05001997 SkAssertResult(shader->asAGradient(&gradientInfo) == SkShader::kColor_GradientType);
1998 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1999 color = gradientColor;
2000 } else {
2001 // PDF positions patterns relative to the initial transform, so
2002 // we need to apply the current transform to the shader parameters.
2003 SkMatrix transform = matrix;
2004 transform.postConcat(fInitialTransform);
2005
2006 // PDF doesn't support kClamp_TileMode, so we simulate it by making
2007 // a pattern the size of the current clip.
Hal Canarya41c2aa2017-02-22 16:32:34 -05002008 SkRect clipStackBounds = clipStack.bounds(this->getGlobalBounds());
2009 SkIPoint deviceOrigin = this->getOrigin();
2010 clipStackBounds.offset(-deviceOrigin.x(), -deviceOrigin.y());
Hal Canaryc8f91802017-02-12 20:29:12 -05002011
2012 // We need to apply the initial transform to bounds in order to get
2013 // bounds in a consistent coordinate system.
Hal Canarya41c2aa2017-02-22 16:32:34 -05002014 fInitialTransform.mapRect(&clipStackBounds);
2015 SkIRect bounds;
2016 clipStackBounds.roundOut(&bounds);
Hal Canaryc8f91802017-02-12 20:29:12 -05002017
2018 SkScalar rasterScale =
2019 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
2020 pdfShader = SkPDFShader::GetPDFShader(
2021 fDocument, fRasterDpi, shader, transform, bounds, rasterScale);
2022
2023 if (pdfShader.get()) {
2024 // pdfShader has been canonicalized so we can directly compare
2025 // pointers.
2026 int resourceIndex = fShaderResources.find(pdfShader.get());
2027 if (resourceIndex < 0) {
2028 resourceIndex = fShaderResources.count();
2029 fShaderResources.push(pdfShader.get());
2030 pdfShader.get()->ref();
2031 }
2032 entry->fShaderIndex = resourceIndex;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002033 }
2034 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002035 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002036
halcanary48810a02016-03-07 14:57:50 -08002037 sk_sp<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002038 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002039 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07002040 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002041 } else {
2042 SkPaint newPaint = paint;
2043 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002044 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07002045 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002046 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002047 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002048 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002049
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002050 if (hasText) {
2051 entry->fTextScaleX = paint.getTextScaleX();
2052 entry->fTextFill = paint.getStyle();
2053 } else {
2054 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002055 }
2056}
2057
halcanarybe27a112015-04-01 13:31:19 -07002058int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002059 // Assumes that gs has been canonicalized (so we can directly compare
2060 // pointers).
2061 int result = fGraphicStateResources.find(gs);
2062 if (result < 0) {
2063 result = fGraphicStateResources.count();
2064 fGraphicStateResources.push(gs);
2065 gs->ref();
2066 }
2067 return result;
2068}
2069
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002070int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07002071 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002072 // Assumes that xobject has been canonicalized (so we can directly compare
2073 // pointers).
2074 int result = fXObjectResources.find(xObject);
2075 if (result < 0) {
2076 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07002077 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002078 }
2079 return result;
2080}
2081
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002082int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary48810a02016-03-07 14:57:50 -08002083 sk_sp<SkPDFFont> newFont(
halcanary989da4a2016-03-21 14:33:17 -07002084 SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID));
halcanary7e8d5d32016-08-12 07:59:38 -07002085 if (!newFont) {
2086 return -1;
2087 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002088 int resourceIndex = fFontResources.find(newFont.get());
2089 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07002090 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002091 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07002092 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002093 }
2094 return resourceIndex;
2095}
2096
halcanary7a14b312015-10-01 07:28:13 -07002097static SkSize rect_to_size(const SkRect& r) {
2098 return SkSize::Make(r.width(), r.height());
2099}
2100
Hal Canaryf50ff392016-09-30 10:25:39 -04002101static sk_sp<SkImage> color_filter(const SkImageSubset& imageSubset,
halcanarya50151d2016-03-25 11:57:49 -07002102 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07002103 auto surface =
Hal Canaryf50ff392016-09-30 10:25:39 -04002104 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageSubset.dimensions()));
halcanarya50151d2016-03-25 11:57:49 -07002105 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07002106 SkCanvas* canvas = surface->getCanvas();
2107 canvas->clear(SK_ColorTRANSPARENT);
2108 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002109 paint.setColorFilter(sk_ref_sp(colorFilter));
Hal Canaryf50ff392016-09-30 10:25:39 -04002110 imageSubset.draw(canvas, &paint);
halcanary7a14b312015-10-01 07:28:13 -07002111 canvas->flush();
halcanarya50151d2016-03-25 11:57:49 -07002112 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07002113}
2114
2115////////////////////////////////////////////////////////////////////////////////
2116void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
2117 const SkClipStack* clipStack,
2118 const SkRegion& origClipRegion,
Hal Canaryf50ff392016-09-30 10:25:39 -04002119 SkImageSubset imageSubset,
halcanary7a14b312015-10-01 07:28:13 -07002120 const SkPaint& paint) {
Hal Canaryf50ff392016-09-30 10:25:39 -04002121 if (imageSubset.dimensions().isZero()) {
halcanarya50151d2016-03-25 11:57:49 -07002122 return;
2123 }
halcanary7a14b312015-10-01 07:28:13 -07002124 #ifdef SK_PDF_IMAGE_STATS
2125 gDrawImageCalls.fetch_add(1);
2126 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002127 SkMatrix matrix = origMatrix;
2128 SkRegion perspectiveBounds;
2129 const SkRegion* clipRegion = &origClipRegion;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002130
2131 // Rasterize the bitmap using perspective in a new bitmap.
2132 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002133 if (fRasterDpi == 0) {
2134 return;
2135 }
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002136 // Transform the bitmap in the new space, without taking into
2137 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002138 SkPath perspectiveOutline;
Hal Canaryf50ff392016-09-30 10:25:39 -04002139 SkRect imageBounds = SkRect::Make(imageSubset.bounds());
halcanary7a14b312015-10-01 07:28:13 -07002140 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002141 perspectiveOutline.transform(origMatrix);
2142
2143 // TODO(edisonn): perf - use current clip too.
2144 // Retrieve the bounds of the new shape.
2145 SkRect bounds = perspectiveOutline.getBounds();
2146
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002147 // Transform the bitmap in the new space, taking into
2148 // account the initial transform.
2149 SkMatrix total = origMatrix;
2150 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002151 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2152 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2153 total.postScale(dpiScale, dpiScale);
2154
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002155 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002156 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002157 physicalPerspectiveOutline.transform(total);
2158
halcanary7a14b312015-10-01 07:28:13 -07002159 SkRect physicalPerspectiveBounds =
2160 physicalPerspectiveOutline.getBounds();
2161 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2162 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002163
2164 // TODO(edisonn): A better approach would be to use a bitmap shader
2165 // (in clamp mode) and draw a rect over the entire bounding box. Then
2166 // intersect perspectiveOutline to the clip. That will avoid introducing
2167 // alpha to the image while still giving good behavior at the edge of
2168 // the image. Avoiding alpha will reduce the pdf size and generation
2169 // CPU time some.
2170
halcanary7a14b312015-10-01 07:28:13 -07002171 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2172
Hal Canaryf50ff392016-09-30 10:25:39 -04002173 auto surface = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh));
halcanary7a14b312015-10-01 07:28:13 -07002174 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002175 return;
2176 }
halcanary7a14b312015-10-01 07:28:13 -07002177 SkCanvas* canvas = surface->getCanvas();
2178 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002179
2180 SkScalar deltaX = bounds.left();
2181 SkScalar deltaY = bounds.top();
2182
2183 SkMatrix offsetMatrix = origMatrix;
2184 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002185 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002186
2187 // Translate the draw in the new canvas, so we perfectly fit the
2188 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002189 canvas->setMatrix(offsetMatrix);
Hal Canaryf50ff392016-09-30 10:25:39 -04002190 imageSubset.draw(canvas, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002191 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002192 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002193
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002194 // In the new space, we use the identity matrix translated
2195 // and scaled to reflect DPI.
2196 matrix.setScale(1 / scaleX, 1 / scaleY);
2197 matrix.postTranslate(deltaX, deltaY);
2198
halcanary7a14b312015-10-01 07:28:13 -07002199 perspectiveBounds.setRect(bounds.roundOut());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002200 clipRegion = &perspectiveBounds;
halcanary7a14b312015-10-01 07:28:13 -07002201
Hal Canaryf50ff392016-09-30 10:25:39 -04002202 imageSubset = SkImageSubset(surface->makeImageSnapshot());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002203 }
2204
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002205 SkMatrix scaled;
2206 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002207 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2208 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002209 // Scale the image up from 1x1 to WxH.
Hal Canaryf50ff392016-09-30 10:25:39 -04002210 SkIRect subset = imageSubset.bounds();
2211 scaled.postScale(SkIntToScalar(imageSubset.dimensions().width()),
2212 SkIntToScalar(imageSubset.dimensions().height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002213 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002214 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002215 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002216 return;
2217 }
2218 if (content.needShape()) {
2219 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002220 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002221 shape.transform(matrix);
2222 content.setShape(shape);
2223 }
2224 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002225 return;
2226 }
2227
halcanary287d22d2015-09-24 10:20:05 -07002228 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002229 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002230 // draw calls. This code here works for all
2231 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2232 // rasterize a layer on this backend). Fortuanely, this seems
2233 // to be how Chromium impements most color-filters.
Hal Canaryf50ff392016-09-30 10:25:39 -04002234 sk_sp<SkImage> img = color_filter(imageSubset, colorFilter);
2235 imageSubset = SkImageSubset(std::move(img));
halcanary7a14b312015-10-01 07:28:13 -07002236 // TODO(halcanary): de-dupe this by caching filtered images.
2237 // (maybe in the resource cache?)
2238 }
halcanarya50151d2016-03-25 11:57:49 -07002239
Hal Canaryf50ff392016-09-30 10:25:39 -04002240 SkBitmapKey key = imageSubset.getKey();
halcanarya50151d2016-03-25 11:57:49 -07002241 sk_sp<SkPDFObject> pdfimage = fDocument->canon()->findPDFBitmap(key);
halcanary7a14b312015-10-01 07:28:13 -07002242 if (!pdfimage) {
Hal Canaryf50ff392016-09-30 10:25:39 -04002243 sk_sp<SkImage> img = imageSubset.makeImage();
halcanarya50151d2016-03-25 11:57:49 -07002244 if (!img) {
2245 return;
2246 }
2247 pdfimage = SkPDFCreateBitmapObject(
2248 std::move(img), fDocument->canon()->getPixelSerializer());
halcanary7a14b312015-10-01 07:28:13 -07002249 if (!pdfimage) {
2250 return;
halcanary287d22d2015-09-24 10:20:05 -07002251 }
halcanarya50151d2016-03-25 11:57:49 -07002252 fDocument->serialize(pdfimage); // serialize images early.
2253 fDocument->canon()->addPDFBitmap(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002254 }
halcanarya50151d2016-03-25 11:57:49 -07002255 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
halcanary3d8c33c2015-10-01 11:06:22 -07002256 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002257 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002258}
reede51c3562016-07-19 14:33:20 -07002259
2260///////////////////////////////////////////////////////////////////////////////////////////////////
2261
2262#include "SkSpecialImage.h"
2263#include "SkImageFilter.h"
2264
2265void SkPDFDevice::drawSpecial(const SkDraw& draw, SkSpecialImage* srcImg, int x, int y,
2266 const SkPaint& paint) {
2267 SkASSERT(!srcImg->isTextureBacked());
2268
2269 SkBitmap resultBM;
2270
2271 SkImageFilter* filter = paint.getImageFilter();
2272 if (filter) {
2273 SkIPoint offset = SkIPoint::Make(0, 0);
2274 SkMatrix matrix = *draw.fMatrix;
2275 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
Hal Canaryf3ee34f2017-02-07 16:58:28 -05002276 const SkIRect clipBounds =
2277 draw.fClipStack->bounds(this->imageInfo().bounds()).roundOut().makeOffset(-x, -y);
Hal Canary67b39de2016-11-07 11:47:44 -05002278 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
brianosman2a75e5d2016-09-22 07:15:37 -07002279 // TODO: Should PDF be operating in a specified color space? For now, run the filter
2280 // in the same color space as the source (this is different from all other backends).
2281 SkImageFilter::OutputProperties outputProperties(srcImg->getColorSpace());
2282 SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
reede51c3562016-07-19 14:33:20 -07002283
2284 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2285 if (resultImg) {
2286 SkPaint tmpUnfiltered(paint);
2287 tmpUnfiltered.setImageFilter(nullptr);
2288 if (resultImg->getROPixels(&resultBM)) {
2289 this->drawSprite(draw, resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
2290 }
2291 }
2292 } else {
2293 if (srcImg->getROPixels(&resultBM)) {
2294 this->drawSprite(draw, resultBM, x, y, paint);
2295 }
2296 }
2297}
2298
2299sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2300 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2301}
2302
2303sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
Brian Osman7992da32016-11-18 11:28:24 -05002304 // TODO: See comment above in drawSpecial. The color mode we use for decode should be driven
2305 // by the destination where we're going to draw thing thing (ie this device). But we don't have
2306 // a color space, so we always decode in legacy mode for now.
Brian Osman61624f02016-12-09 14:51:59 -05002307 SkColorSpace* legacyColorSpace = nullptr;
reede51c3562016-07-19 14:33:20 -07002308 return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
Brian Osman61624f02016-12-09 14:51:59 -05002309 image->makeNonTextureImage(), legacyColorSpace);
reede51c3562016-07-19 14:33:20 -07002310}
2311
2312sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002313 return nullptr;
2314}
brianosman04a44d02016-09-21 09:46:57 -07002315
2316SkImageFilterCache* SkPDFDevice::getImageFilterCache() {
2317 // We always return a transient cache, so it is freed after each
2318 // filter traversal.
2319 return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
2320}