blob: 0dc8fef8ddf15a3049492043c58167f702a94f06 [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"
reedf70b5312016-03-04 16:36:20 -08009#include "SkAnnotationKeys.h"
reed7503d602016-07-15 14:23:29 -070010#include "SkBitmapDevice.h"
martina.kollarovab8d6af12016-06-29 05:12:31 -070011#include "SkBitmapKey.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000012#include "SkColor.h"
halcanary287d22d2015-09-24 10:20:05 -070013#include "SkColorFilter.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000014#include "SkDraw.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000015#include "SkGlyphCache.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000016#include "SkPath.h"
reeda4393342016-03-18 11:22:57 -070017#include "SkPathEffect.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000018#include "SkPathOps.h"
halcanarydb0dcc72015-03-20 12:31:52 -070019#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070020#include "SkPDFCanon.h"
halcanary989da4a2016-03-21 14:33:17 -070021#include "SkPDFDocument.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000022#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000023#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000024#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000025#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000026#include "SkPDFShader.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000027#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000028#include "SkPDFUtils.h"
wangxianzhuef6c50a2015-09-17 20:38:02 -070029#include "SkRasterClip.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000030#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000031#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070032#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000033#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000034#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000035#include "SkTypefacePriv.h"
halcanarya6814332015-05-27 08:53:36 -070036#include "SkXfermodeInterpretation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000037
edisonn@google.com73a7ea32013-11-11 20:55:15 +000038#define DPI_FOR_RASTER_SCALE_ONE 72
39
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000040// Utility functions
41
halcanarya6814332015-05-27 08:53:36 -070042// If the paint will definitely draw opaquely, replace kSrc_Mode with
43// kSrcOver_Mode. http://crbug.com/473572
44static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
45 if (kSrcOver_SkXfermodeInterpretation
46 == SkInterpretXfermode(*paint, false)) {
halcanary96fcdcc2015-08-27 07:41:13 -070047 paint->setXfermode(nullptr);
halcanarya6814332015-05-27 08:53:36 -070048 }
49}
50
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000051static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000052 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
halcanaryeb92cb32016-07-15 13:41:27 -070053 SkPDFUtils::AppendColorComponent(SkColorGetR(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000054 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -070055 SkPDFUtils::AppendColorComponent(SkColorGetG(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000056 result->writeText(" ");
halcanaryeb92cb32016-07-15 13:41:27 -070057 SkPDFUtils::AppendColorComponent(SkColorGetB(color), result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000058 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000059}
60
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000061static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000062 SkPaint result = paint;
63 if (result.isFakeBoldText()) {
64 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
65 kStdFakeBoldInterpKeys,
66 kStdFakeBoldInterpValues,
67 kStdFakeBoldInterpLength);
68 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000069 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000070 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000071 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000072 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000073 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000074 result.setStrokeWidth(width);
75 }
76 return result;
77}
78
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +000079static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
80 SkWStream* content) {
81 // Flip the text about the x-axis to account for origin swap and include
82 // the passed parameters.
83 content->writeText("1 0 ");
halcanarybc4696b2015-05-06 10:56:04 -070084 SkPDFUtils::AppendScalar(0 - textSkewX, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +000085 content->writeText(" -1 ");
halcanarybc4696b2015-05-06 10:56:04 -070086 SkPDFUtils::AppendScalar(x, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +000087 content->writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -070088 SkPDFUtils::AppendScalar(y, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +000089 content->writeText(" Tm\n");
90}
91
halcanary2be7e012016-03-28 11:58:08 -070092SkPDFDevice::GraphicStateEntry::GraphicStateEntry()
93 : fColor(SK_ColorBLACK)
94 , fTextScaleX(SK_Scalar1)
95 , fTextFill(SkPaint::kFill_Style)
96 , fShaderIndex(-1)
97 , fGraphicStateIndex(-1)
98 , fFont(nullptr)
99 , fTextSize(SK_ScalarNaN) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000100 fMatrix.reset();
101}
102
halcanary2be7e012016-03-28 11:58:08 -0700103bool SkPDFDevice::GraphicStateEntry::compareInitialState(
104 const GraphicStateEntry& cur) {
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000105 return fColor == cur.fColor &&
106 fShaderIndex == cur.fShaderIndex &&
107 fGraphicStateIndex == cur.fGraphicStateIndex &&
108 fMatrix == cur.fMatrix &&
109 fClipStack == cur.fClipStack &&
110 (fTextScaleX == 0 ||
111 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000112}
113
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000114class GraphicStackState {
115public:
116 GraphicStackState(const SkClipStack& existingClipStack,
117 const SkRegion& existingClipRegion,
118 SkWStream* contentStream)
119 : fStackDepth(0),
120 fContentStream(contentStream) {
121 fEntries[0].fClipStack = existingClipStack;
122 fEntries[0].fClipRegion = existingClipRegion;
123 }
124
125 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000126 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000127 void updateMatrix(const SkMatrix& matrix);
halcanary2be7e012016-03-28 11:58:08 -0700128 void updateDrawingState(const SkPDFDevice::GraphicStateEntry& state);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000129
130 void drainStack();
131
132private:
133 void push();
134 void pop();
halcanary2be7e012016-03-28 11:58:08 -0700135 SkPDFDevice::GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000136
137 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
138 static const int kMaxStackDepth = 12;
halcanary2be7e012016-03-28 11:58:08 -0700139 SkPDFDevice::GraphicStateEntry fEntries[kMaxStackDepth + 1];
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000140 int fStackDepth;
141 SkWStream* fContentStream;
142};
143
144void GraphicStackState::drainStack() {
145 while (fStackDepth) {
146 pop();
147 }
148}
149
150void GraphicStackState::push() {
151 SkASSERT(fStackDepth < kMaxStackDepth);
152 fContentStream->writeText("q\n");
153 fStackDepth++;
154 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
155}
156
157void GraphicStackState::pop() {
158 SkASSERT(fStackDepth > 0);
159 fContentStream->writeText("Q\n");
160 fStackDepth--;
161}
162
robertphillips@google.com80214e22012-07-20 15:33:18 +0000163// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000164// and then skips over the leading entries as specified in prefix. It requires
165// and asserts that "prefix" will be a prefix to "stack."
166static void skip_clip_stack_prefix(const SkClipStack& prefix,
167 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000168 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000169 SkClipStack::B2TIter prefixIter(prefix);
170 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000171
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000172 const SkClipStack::Element* prefixEntry;
173 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000174
175 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000176 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000177 iterEntry = iter->next();
178 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000179 // Because of SkClipStack does internal intersection, the last clip
180 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000181 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000182 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
183 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
184 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000185 // back up the iterator by one
186 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000187 prefixEntry = prefixIter.next();
188 break;
189 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000190 }
191
halcanary96fcdcc2015-08-27 07:41:13 -0700192 SkASSERT(prefixEntry == nullptr);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000193}
194
195static void emit_clip(SkPath* clipPath, SkRect* clipRect,
196 SkWStream* contentStream) {
197 SkASSERT(clipPath || clipRect);
198
199 SkPath::FillType clipFill;
200 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000201 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000202 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000203 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000204 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
205 clipFill = SkPath::kWinding_FillType;
206 }
207
208 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
209 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
210 if (clipFill == SkPath::kEvenOdd_FillType) {
211 contentStream->writeText("W* n\n");
212 } else {
213 contentStream->writeText("W n\n");
214 }
215}
216
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000217/* Calculate an inverted path's equivalent non-inverted path, given the
218 * canvas bounds.
219 * outPath may alias with invPath (since this is supported by PathOps).
220 */
221static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
222 SkPath* outPath) {
223 SkASSERT(invPath.isInverseFillType());
224
225 SkPath clipPath;
226 clipPath.addRect(bounds);
227
reedcdb42bb2015-06-26 10:23:07 -0700228 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000229}
230
231// Sanity check the numerical values of the SkRegion ops and PathOps ops
232// enums so region_op_to_pathops_op can do a straight passthrough cast.
233// If these are failing, it may be necessary to make region_op_to_pathops_op
234// do more.
bungeman99fe8222015-08-20 07:57:51 -0700235static_assert(SkRegion::kDifference_Op == (int)kDifference_SkPathOp, "region_pathop_mismatch");
236static_assert(SkRegion::kIntersect_Op == (int)kIntersect_SkPathOp, "region_pathop_mismatch");
237static_assert(SkRegion::kUnion_Op == (int)kUnion_SkPathOp, "region_pathop_mismatch");
238static_assert(SkRegion::kXOR_Op == (int)kXOR_SkPathOp, "region_pathop_mismatch");
239static_assert(SkRegion::kReverseDifference_Op == (int)kReverseDifference_SkPathOp,
240 "region_pathop_mismatch");
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000241
242static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
243 SkASSERT(op >= 0);
244 SkASSERT(op <= SkRegion::kReverseDifference_Op);
245 return (SkPathOp)op;
246}
247
248/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
249 * Returns true if successful, or false if not successful.
250 * If successful, the resulting clip is stored in outClipPath.
251 * If not successful, outClipPath is undefined, and a fallback method
252 * should be used.
253 */
254static bool get_clip_stack_path(const SkMatrix& transform,
255 const SkClipStack& clipStack,
256 const SkRegion& clipRegion,
257 SkPath* outClipPath) {
258 outClipPath->reset();
259 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
260
261 const SkClipStack::Element* clipEntry;
262 SkClipStack::Iter iter;
263 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
264 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
265 SkPath entryPath;
266 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
267 outClipPath->reset();
268 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
269 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000270 } else {
271 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000272 }
273 entryPath.transform(transform);
274
275 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
276 *outClipPath = entryPath;
277 } else {
278 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
279 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
280 return false;
281 }
282 }
283 }
284
285 if (outClipPath->isInverseFillType()) {
286 // The bounds are slightly outset to ensure this is correct in the
287 // face of floating-point accuracy and possible SkRegion bitmap
288 // approximations.
289 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
290 clipBounds.outset(SK_Scalar1, SK_Scalar1);
291 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
292 return false;
293 }
294 }
295 return true;
296}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000297
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000298// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000299// graphic state stack, and the fact that we can know all the clips used
300// on the page to optimize this.
301void GraphicStackState::updateClip(const SkClipStack& clipStack,
302 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000303 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000304 if (clipStack == currentEntry()->fClipStack) {
305 return;
306 }
307
308 while (fStackDepth > 0) {
309 pop();
310 if (clipStack == currentEntry()->fClipStack) {
311 return;
312 }
313 }
314 push();
315
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000316 currentEntry()->fClipStack = clipStack;
317 currentEntry()->fClipRegion = clipRegion;
318
319 SkMatrix transform;
320 transform.setTranslate(translation.fX, translation.fY);
321
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000322 SkPath clipPath;
323 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700324 emit_clip(&clipPath, nullptr, fContentStream);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000325 return;
326 }
halcanarydda239e2016-03-31 07:33:57 -0700327
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000328 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
329 // already been applied. (If this is a top level device, then it specifies
330 // a clip to the content area. If this is a layer, then it specifies
331 // the clip in effect when the layer was created.) There's no need to
332 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
333 // initial clip on the parent layer. (This means there's a bug if the user
334 // expands the clip and then uses any xfer mode that uses dst:
335 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000336 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000337 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
338
339 // If the clip stack does anything other than intersect or if it uses
340 // an inverse fill type, we have to fall back to the clip region.
341 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000342 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000343 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000344 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
345 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000346 needRegion = true;
347 break;
348 }
349 }
350
351 if (needRegion) {
352 SkPath clipPath;
353 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
halcanary96fcdcc2015-08-27 07:41:13 -0700354 emit_clip(&clipPath, nullptr, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000355 } else {
356 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000357 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000358 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000359 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
360 switch (clipEntry->getType()) {
361 case SkClipStack::Element::kRect_Type: {
362 SkRect translatedClip;
363 transform.mapRect(&translatedClip, clipEntry->getRect());
halcanary96fcdcc2015-08-27 07:41:13 -0700364 emit_clip(nullptr, &translatedClip, fContentStream);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000365 break;
366 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000367 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000368 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000369 clipEntry->asPath(&translatedPath);
370 translatedPath.transform(transform, &translatedPath);
halcanary96fcdcc2015-08-27 07:41:13 -0700371 emit_clip(&translatedPath, nullptr, fContentStream);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000372 break;
373 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000374 }
375 }
376 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000377}
378
379void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
380 if (matrix == currentEntry()->fMatrix) {
381 return;
382 }
383
384 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
385 SkASSERT(fStackDepth > 0);
386 SkASSERT(fEntries[fStackDepth].fClipStack ==
387 fEntries[fStackDepth -1].fClipStack);
388 pop();
389
390 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
391 }
392 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
393 return;
394 }
395
396 push();
397 SkPDFUtils::AppendTransform(matrix, fContentStream);
398 currentEntry()->fMatrix = matrix;
399}
400
halcanary2be7e012016-03-28 11:58:08 -0700401void GraphicStackState::updateDrawingState(const SkPDFDevice::GraphicStateEntry& state) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000402 // PDF treats a shader as a color, so we only set one or the other.
403 if (state.fShaderIndex >= 0) {
404 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000405 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000406 currentEntry()->fShaderIndex = state.fShaderIndex;
407 }
408 } else {
409 if (state.fColor != currentEntry()->fColor ||
410 currentEntry()->fShaderIndex >= 0) {
411 emit_pdf_color(state.fColor, fContentStream);
412 fContentStream->writeText("RG ");
413 emit_pdf_color(state.fColor, fContentStream);
414 fContentStream->writeText("rg\n");
415 currentEntry()->fColor = state.fColor;
416 currentEntry()->fShaderIndex = -1;
417 }
418 }
419
420 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000421 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000422 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
423 }
424
425 if (state.fTextScaleX) {
426 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
427 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
428 SkIntToScalar(100));
halcanarybc4696b2015-05-06 10:56:04 -0700429 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000430 fContentStream->writeText(" Tz\n");
431 currentEntry()->fTextScaleX = state.fTextScaleX;
432 }
433 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700434 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
435 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
436 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000437 fContentStream->writeDecAsText(state.fTextFill);
438 fContentStream->writeText(" Tr\n");
439 currentEntry()->fTextFill = state.fTextFill;
440 }
441 }
442}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000443
reed76033be2015-03-14 10:54:31 -0700444static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700445 // PDF does not support image filters, so render them on CPU.
446 // Note that this rendering is done at "screen" resolution (100dpi), not
447 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700448 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800449 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700450
451 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700452 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700453}
454
455SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
reedcd4051e2016-07-15 09:41:26 -0700456 if (layerPaint && not_supported_for_layers(*layerPaint)) {
reed7503d602016-07-15 14:23:29 -0700457 // need to return a raster device, which we will detect in drawDevice()
458 return SkBitmapDevice::Create(cinfo.fInfo, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
senorblancob0e89dc2014-10-20 14:03:12 -0700459 }
fmalita6987dca2014-11-13 08:33:37 -0800460 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanary989da4a2016-03-21 14:33:17 -0700461 return SkPDFDevice::Create(size, fRasterDpi, fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000462}
463
halcanary989da4a2016-03-21 14:33:17 -0700464SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
465
bsalomon@google.come97f0852011-06-17 13:10:25 +0000466
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000467
468// A helper class to automatically finish a ContentEntry at the end of a
469// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000470class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000471public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000472 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
473 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000474 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700475 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000476 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700477 fDstFormXObject(nullptr) {
reed1e7f5e72016-04-27 07:49:17 -0700478 init(draw.fClipStack, draw.fRC->bwRgn(), *draw.fMatrix, paint, hasText);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000479 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000480 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
481 const SkRegion& clipRegion, const SkMatrix& matrix,
482 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000483 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700484 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000485 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700486 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000487 init(clipStack, clipRegion, matrix, paint, hasText);
488 }
489
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000490 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000491 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000492 SkPath* shape = &fShape;
493 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700494 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000495 }
halcanarydabd4f02016-08-03 11:16:56 -0700496 fDevice->finishContentEntry(fXfermode, std::move(fDstFormXObject), shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000497 }
498 }
499
halcanary2be7e012016-03-28 11:58:08 -0700500 SkPDFDevice::ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000501
502 /* Returns true when we explicitly need the shape of the drawing. */
503 bool needShape() {
504 switch (fXfermode) {
505 case SkXfermode::kClear_Mode:
506 case SkXfermode::kSrc_Mode:
507 case SkXfermode::kSrcIn_Mode:
508 case SkXfermode::kSrcOut_Mode:
509 case SkXfermode::kDstIn_Mode:
510 case SkXfermode::kDstOut_Mode:
511 case SkXfermode::kSrcATop_Mode:
512 case SkXfermode::kDstATop_Mode:
513 case SkXfermode::kModulate_Mode:
514 return true;
515 default:
516 return false;
517 }
518 }
519
520 /* Returns true unless we only need the shape of the drawing. */
521 bool needSource() {
522 if (fXfermode == SkXfermode::kClear_Mode) {
523 return false;
524 }
525 return true;
526 }
527
528 /* If the shape is different than the alpha component of the content, then
529 * setShape should be called with the shape. In particular, images and
530 * devices have rectangular shape.
531 */
532 void setShape(const SkPath& shape) {
533 fShape = shape;
534 }
535
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000536private:
537 SkPDFDevice* fDevice;
halcanary2be7e012016-03-28 11:58:08 -0700538 SkPDFDevice::ContentEntry* fContentEntry;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000539 SkXfermode::Mode fXfermode;
halcanarydabd4f02016-08-03 11:16:56 -0700540 sk_sp<SkPDFObject> fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000541 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000542
543 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
544 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000545 // Shape has to be flatten before we get here.
546 if (matrix.hasPerspective()) {
547 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000548 return;
549 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000550 if (paint.getXfermode()) {
551 paint.getXfermode()->asMode(&fXfermode);
552 }
553 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
554 matrix, paint, hasText,
555 &fDstFormXObject);
556 }
557};
558
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000559////////////////////////////////////////////////////////////////////////////////
560
halcanary989da4a2016-03-21 14:33:17 -0700561SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFDocument* doc, bool flip)
reed589a39e2016-08-20 07:59:19 -0700562 : INHERITED(SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()),
563 SkSurfaceProps(0, kUnknown_SkPixelGeometry))
robertphillips9a53fd72015-06-22 09:46:59 -0700564 , fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800565 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
halcanarya1f1ee92015-02-20 06:17:26 -0800566 , fRasterDpi(rasterDpi)
halcanary989da4a2016-03-21 14:33:17 -0700567 , fDocument(doc) {
halcanarya1f1ee92015-02-20 06:17:26 -0800568 SkASSERT(pageSize.width() > 0);
569 SkASSERT(pageSize.height() > 0);
robertphillips1f3923e2016-07-21 07:17:54 -0700570
halcanarya1f1ee92015-02-20 06:17:26 -0800571 if (flip) {
572 // Skia generally uses the top left as the origin but PDF
573 // natively has the origin at the bottom left. This matrix
574 // corrects for that. But that only needs to be done once, we
575 // don't do it when layering.
576 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
577 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
578 } else {
579 fInitialTransform.setIdentity();
580 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000581}
582
583SkPDFDevice::~SkPDFDevice() {
halcanary3c35fb32016-06-30 11:55:07 -0700584 this->cleanUp();
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000585}
586
587void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700588 fContentEntries.reset();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000589}
590
halcanary3c35fb32016-06-30 11:55:07 -0700591void SkPDFDevice::cleanUp() {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000592 fGraphicStateResources.unrefAll();
593 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000594 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000595 fShaderResources.unrefAll();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000596}
597
reedf70b5312016-03-04 16:36:20 -0800598void SkPDFDevice::drawAnnotation(const SkDraw& d, const SkRect& rect, const char key[],
599 SkData* value) {
600 if (0 == rect.width() && 0 == rect.height()) {
601 handlePointAnnotation({ rect.x(), rect.y() }, *d.fMatrix, key, value);
602 } else {
603 SkPath path;
604 path.addRect(rect);
605 handlePathAnnotation(path, d, key, value);
606 }
607}
608
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000609void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000610 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700611 replace_srcmode_on_opaque_paint(&newPaint);
612
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000613 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000614 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000615 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000616}
617
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000618void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
halcanary2be7e012016-03-28 11:58:08 -0700619 SkPDFDevice::ContentEntry* contentEntry) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000620 if (!contentEntry) {
621 return;
622 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000623 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
624 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000625 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000626 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000627 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000628 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000629 inverse.mapRect(&bbox);
630
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000631 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000632 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000633 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000634}
635
halcanary682ee012016-01-28 10:59:34 -0800636void SkPDFDevice::drawPoints(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700637 SkCanvas::PointMode mode,
638 size_t count,
639 const SkPoint* points,
640 const SkPaint& srcPaint) {
641 SkPaint passedPaint = srcPaint;
642 replace_srcmode_on_opaque_paint(&passedPaint);
643
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000644 if (count == 0) {
645 return;
646 }
647
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000648 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
649 // We only use this when there's a path effect because of the overhead
650 // of multiple calls to setUpContentEntry it causes.
651 if (passedPaint.getPathEffect()) {
reed1e7f5e72016-04-27 07:49:17 -0700652 if (d.fRC->isEmpty()) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000653 return;
654 }
655 SkDraw pointDraw(d);
656 pointDraw.fDevice = this;
657 pointDraw.drawPoints(mode, count, points, passedPaint, true);
658 return;
659 }
660
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000661 const SkPaint* paint = &passedPaint;
662 SkPaint modifiedPaint;
663
664 if (mode == SkCanvas::kPoints_PointMode &&
665 paint->getStrokeCap() != SkPaint::kRound_Cap) {
666 modifiedPaint = *paint;
667 paint = &modifiedPaint;
668 if (paint->getStrokeWidth()) {
669 // PDF won't draw a single point with square/butt caps because the
670 // orientation is ambiguous. Draw a rectangle instead.
671 modifiedPaint.setStyle(SkPaint::kFill_Style);
672 SkScalar strokeWidth = paint->getStrokeWidth();
673 SkScalar halfStroke = SkScalarHalf(strokeWidth);
674 for (size_t i = 0; i < count; i++) {
675 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
676 r.inset(-halfStroke, -halfStroke);
677 drawRect(d, r, modifiedPaint);
678 }
679 return;
680 } else {
681 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
682 }
683 }
684
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000685 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000686 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000687 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000688 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000689
690 switch (mode) {
691 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000692 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000693 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000694 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000695 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000696 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000697 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000698 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000699 break;
700 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000701 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000702 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000703 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000704 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000705 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000706 &content.entry()->fContent);
707 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000708 }
709 break;
710 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000711 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
712 for (size_t i = 0; i < count; i++) {
713 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000714 &content.entry()->fContent);
715 SkPDFUtils::ClosePath(&content.entry()->fContent);
716 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000717 }
718 break;
719 default:
720 SkASSERT(false);
721 }
722}
723
halcanary8103a342016-03-08 15:10:16 -0800724static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800725 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700726 annotation->insertName("Subtype", "Link");
halcanary488165e2016-04-22 06:10:21 -0700727 annotation->insertInt("F", 4); // required by ISO 19005
wangxianzhud76665d2015-07-17 17:23:15 -0700728
halcanaryece83922016-03-08 08:32:12 -0800729 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700730 border->reserve(3);
731 border->appendInt(0); // Horizontal corner radius.
732 border->appendInt(0); // Vertical corner radius.
733 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800734 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700735
halcanaryece83922016-03-08 08:32:12 -0800736 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700737 rect->reserve(4);
738 rect->appendScalar(translatedRect.fLeft);
739 rect->appendScalar(translatedRect.fTop);
740 rect->appendScalar(translatedRect.fRight);
741 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800742 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700743
halcanary8103a342016-03-08 15:10:16 -0800744 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700745}
746
halcanary8103a342016-03-08 15:10:16 -0800747static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700748 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700749 SkString url(static_cast<const char *>(urlData->data()),
750 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800751 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700752 action->insertName("S", "URI");
753 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800754 annotation->insertObject("A", std::move(action));
755 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700756}
757
halcanary8103a342016-03-08 15:10:16 -0800758static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
759 const SkRect& r) {
halcanary4b1e17e2016-07-27 14:49:46 -0700760 sk_sp<SkPDFDict> annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700761 SkString name(static_cast<const char *>(nameData->data()),
762 nameData->size() - 1);
763 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800764 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700765}
766
halcanary682ee012016-01-28 10:59:34 -0800767void SkPDFDevice::drawRect(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700768 const SkRect& rect,
769 const SkPaint& srcPaint) {
770 SkPaint paint = srcPaint;
771 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000772 SkRect r = rect;
773 r.sort();
774
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000775 if (paint.getPathEffect()) {
reed1e7f5e72016-04-27 07:49:17 -0700776 if (d.fRC->isEmpty()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000777 return;
778 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000779 SkPath path;
780 path.addRect(r);
halcanary96fcdcc2015-08-27 07:41:13 -0700781 drawPath(d, path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000782 return;
783 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000784
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000785 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000786 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000787 return;
788 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000789 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000790 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000791 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000792}
793
halcanarya6814332015-05-27 08:53:36 -0700794void SkPDFDevice::drawRRect(const SkDraw& draw,
795 const SkRRect& rrect,
796 const SkPaint& srcPaint) {
797 SkPaint paint = srcPaint;
798 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000799 SkPath path;
800 path.addRRect(rrect);
halcanary96fcdcc2015-08-27 07:41:13 -0700801 this->drawPath(draw, path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000802}
803
halcanarya6814332015-05-27 08:53:36 -0700804void SkPDFDevice::drawOval(const SkDraw& draw,
805 const SkRect& oval,
806 const SkPaint& srcPaint) {
807 SkPaint paint = srcPaint;
808 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700809 SkPath path;
810 path.addOval(oval);
halcanary96fcdcc2015-08-27 07:41:13 -0700811 this->drawPath(draw, path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700812}
813
halcanary682ee012016-01-28 10:59:34 -0800814void SkPDFDevice::drawPath(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700815 const SkPath& origPath,
816 const SkPaint& srcPaint,
817 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000818 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700819 SkPaint paint = srcPaint;
820 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800821 SkPath modifiedPath;
822 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000823
824 SkMatrix matrix = *d.fMatrix;
825 if (prePathMatrix) {
826 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800827 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000828 pathPtr = &modifiedPath;
829 pathIsMutable = true;
830 }
halcanary682ee012016-01-28 10:59:34 -0800831 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000832 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000833 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000834 }
835 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000836
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000837 if (paint.getPathEffect()) {
reed1e7f5e72016-04-27 07:49:17 -0700838 if (d.fRC->isEmpty()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000839 return;
840 }
halcanary682ee012016-01-28 10:59:34 -0800841 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000842 pathPtr = &modifiedPath;
843 pathIsMutable = true;
844 }
halcanary682ee012016-01-28 10:59:34 -0800845 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000846
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000847 SkPaint noEffectPaint(paint);
halcanary96fcdcc2015-08-27 07:41:13 -0700848 noEffectPaint.setPathEffect(nullptr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000849 if (fill) {
850 noEffectPaint.setStyle(SkPaint::kFill_Style);
851 } else {
852 noEffectPaint.setStyle(SkPaint::kStroke_Style);
853 noEffectPaint.setStrokeWidth(0);
854 }
halcanary96fcdcc2015-08-27 07:41:13 -0700855 drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000856 return;
857 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000858
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000859 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000860 return;
861 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000862
reed1e7f5e72016-04-27 07:49:17 -0700863 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000864 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000865 return;
866 }
halcanary8b2bc252015-10-06 09:41:47 -0700867 bool consumeDegeratePathSegments =
868 paint.getStyle() == SkPaint::kFill_Style ||
869 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
870 paint.getStrokeCap() != SkPaint::kSquare_Cap);
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000871 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
halcanary8b2bc252015-10-06 09:41:47 -0700872 consumeDegeratePathSegments,
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000873 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000874 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000875 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000876}
877
halcanary7a14b312015-10-01 07:28:13 -0700878void SkPDFDevice::drawBitmapRect(const SkDraw& draw,
879 const SkBitmap& bitmap,
880 const SkRect* src,
881 const SkRect& dst,
882 const SkPaint& srcPaint,
883 SkCanvas::SrcRectConstraint constraint) {
halcanary66be6262016-03-21 13:01:34 -0700884 SkASSERT(false);
halcanary7a14b312015-10-01 07:28:13 -0700885}
886
887void SkPDFDevice::drawBitmap(const SkDraw& d,
888 const SkBitmap& bitmap,
889 const SkMatrix& matrix,
890 const SkPaint& srcPaint) {
halcanarya6814332015-05-27 08:53:36 -0700891 SkPaint paint = srcPaint;
892 if (bitmap.isOpaque()) {
893 replace_srcmode_on_opaque_paint(&paint);
894 }
895
reed1e7f5e72016-04-27 07:49:17 -0700896 if (d.fRC->isEmpty()) {
halcanary7a14b312015-10-01 07:28:13 -0700897 return;
898 }
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000899
halcanary7a14b312015-10-01 07:28:13 -0700900 SkMatrix transform = matrix;
901 transform.postConcat(*d.fMatrix);
halcanarya50151d2016-03-25 11:57:49 -0700902 SkImageBitmap imageBitmap(bitmap);
903 this->internalDrawImage(
reed1e7f5e72016-04-27 07:49:17 -0700904 transform, d.fClipStack, d.fRC->bwRgn(), imageBitmap, paint);
halcanary7a14b312015-10-01 07:28:13 -0700905}
906
907void SkPDFDevice::drawSprite(const SkDraw& d,
908 const SkBitmap& bitmap,
909 int x,
910 int y,
911 const SkPaint& srcPaint) {
912 SkPaint paint = srcPaint;
913 if (bitmap.isOpaque()) {
914 replace_srcmode_on_opaque_paint(&paint);
915 }
916
reed1e7f5e72016-04-27 07:49:17 -0700917 if (d.fRC->isEmpty()) {
halcanary7a14b312015-10-01 07:28:13 -0700918 return;
919 }
920
921 SkMatrix matrix;
922 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
halcanarya50151d2016-03-25 11:57:49 -0700923 SkImageBitmap imageBitmap(bitmap);
924 this->internalDrawImage(
reed1e7f5e72016-04-27 07:49:17 -0700925 matrix, d.fClipStack, d.fRC->bwRgn(), imageBitmap, paint);
halcanary7a14b312015-10-01 07:28:13 -0700926}
927
928void SkPDFDevice::drawImage(const SkDraw& draw,
929 const SkImage* image,
930 SkScalar x,
931 SkScalar y,
932 const SkPaint& srcPaint) {
933 SkPaint paint = srcPaint;
934 if (!image) {
935 return;
936 }
937 if (image->isOpaque()) {
938 replace_srcmode_on_opaque_paint(&paint);
939 }
reed1e7f5e72016-04-27 07:49:17 -0700940 if (draw.fRC->isEmpty()) {
halcanary7a14b312015-10-01 07:28:13 -0700941 return;
942 }
943 SkMatrix transform = SkMatrix::MakeTrans(x, y);
944 transform.postConcat(*draw.fMatrix);
halcanarya50151d2016-03-25 11:57:49 -0700945 SkImageBitmap imageBitmap(const_cast<SkImage*>(image));
946 this->internalDrawImage(
reed1e7f5e72016-04-27 07:49:17 -0700947 transform, draw.fClipStack, draw.fRC->bwRgn(), imageBitmap, paint);
halcanary7a14b312015-10-01 07:28:13 -0700948}
949
950void SkPDFDevice::drawImageRect(const SkDraw& draw,
951 const SkImage* image,
952 const SkRect* src,
953 const SkRect& dst,
954 const SkPaint& srcPaint,
955 SkCanvas::SrcRectConstraint constraint) {
halcanary66be6262016-03-21 13:01:34 -0700956 SkASSERT(false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000957}
958
halcanaryf0c30f52016-07-15 13:35:45 -0700959namespace {
960class GlyphPositioner {
961public:
962 GlyphPositioner(SkDynamicMemoryWStream* content,
963 SkScalar textSkewX,
halcanary4ed2f012016-08-15 18:40:07 -0700964 bool wideChars,
965 bool defaultPositioning,
966 SkPoint origin)
halcanaryf0c30f52016-07-15 13:35:45 -0700967 : fContent(content)
968 , fCurrentMatrixX(0.0f)
969 , fCurrentMatrixY(0.0f)
970 , fXAdvance(0.0f)
971 , fWideChars(wideChars)
halcanary4ed2f012016-08-15 18:40:07 -0700972 , fInText(false)
973 , fDefaultPositioning(defaultPositioning) {
974 set_text_transform(origin.x(), origin.y(), textSkewX, fContent);
halcanaryf0c30f52016-07-15 13:35:45 -0700975 }
976 ~GlyphPositioner() { SkASSERT(!fInText); /* flush first */ }
977 void flush() {
978 if (fInText) {
979 fContent->writeText("> Tj\n");
980 fInText = false;
981 }
982 }
983 void setWideChars(bool wideChars) {
984 if (fWideChars != wideChars) {
985 SkASSERT(!fInText);
halcanary4ed2f012016-08-15 18:40:07 -0700986 SkASSERT(fWideChars == wideChars);
halcanaryf0c30f52016-07-15 13:35:45 -0700987 fWideChars = wideChars;
988 }
989 }
990 void writeGlyph(SkScalar x,
991 SkScalar y,
992 SkScalar advanceWidth,
993 uint16_t glyph) {
halcanary4ed2f012016-08-15 18:40:07 -0700994 if (!fDefaultPositioning) {
995 SkScalar xPosition = x - fCurrentMatrixX;
996 SkScalar yPosition = y - fCurrentMatrixY;
997 if (xPosition != fXAdvance || yPosition != 0) {
998 this->flush();
999 SkPDFUtils::AppendScalar(xPosition, fContent);
1000 fContent->writeText(" ");
1001 SkPDFUtils::AppendScalar(-yPosition, fContent);
1002 fContent->writeText(" Td ");
1003 fCurrentMatrixX = x;
1004 fCurrentMatrixY = y;
1005 fXAdvance = 0;
1006 }
1007 fXAdvance += advanceWidth;
halcanaryf0c30f52016-07-15 13:35:45 -07001008 }
1009 if (!fInText) {
1010 fContent->writeText("<");
1011 fInText = true;
1012 }
1013 if (fWideChars) {
1014 SkPDFUtils::WriteUInt16BE(fContent, glyph);
1015 } else {
1016 SkASSERT(0 == glyph >> 8);
1017 SkPDFUtils::WriteUInt8(fContent, static_cast<uint8_t>(glyph));
1018 }
halcanaryf0c30f52016-07-15 13:35:45 -07001019 }
1020
1021private:
1022 SkDynamicMemoryWStream* fContent;
1023 SkScalar fCurrentMatrixX;
1024 SkScalar fCurrentMatrixY;
1025 SkScalar fXAdvance;
1026 bool fWideChars;
1027 bool fInText;
halcanary4ed2f012016-08-15 18:40:07 -07001028 const bool fDefaultPositioning;
halcanaryf0c30f52016-07-15 13:35:45 -07001029};
1030} // namespace
1031
halcanary66a82f32015-10-12 13:05:04 -07001032static void draw_transparent_text(SkPDFDevice* device,
1033 const SkDraw& d,
1034 const void* text, size_t len,
1035 SkScalar x, SkScalar y,
1036 const SkPaint& srcPaint) {
halcanary66a82f32015-10-12 13:05:04 -07001037 SkPaint transparent;
1038 if (!SkPDFFont::CanEmbedTypeface(transparent.getTypeface(),
1039 device->getCanon())) {
halcanary4ed2f012016-08-15 18:40:07 -07001040 SkDebugf("SkPDF: default typeface should be embeddable");
halcanary66a82f32015-10-12 13:05:04 -07001041 return; // Avoid infinite loop in release.
1042 }
1043 transparent.setTextSize(srcPaint.getTextSize());
1044 transparent.setColor(SK_ColorTRANSPARENT);
1045 switch (srcPaint.getTextEncoding()) {
1046 case SkPaint::kGlyphID_TextEncoding: {
1047 // Since a glyphId<->Unicode mapping is typeface-specific,
1048 // map back to Unicode first.
1049 size_t glyphCount = len / 2;
1050 SkAutoTMalloc<SkUnichar> unichars(glyphCount);
1051 srcPaint.glyphsToUnichars(
1052 (const uint16_t*)text, SkToInt(glyphCount), &unichars[0]);
1053 transparent.setTextEncoding(SkPaint::kUTF32_TextEncoding);
halcanary4ed2f012016-08-15 18:40:07 -07001054 // TODO(halcanary): deal with case where default typeface
1055 // does not have glyphs for these unicode code points.
halcanary66a82f32015-10-12 13:05:04 -07001056 device->drawText(d, &unichars[0],
1057 glyphCount * sizeof(SkUnichar),
1058 x, y, transparent);
1059 break;
1060 }
1061 case SkPaint::kUTF8_TextEncoding:
1062 case SkPaint::kUTF16_TextEncoding:
1063 case SkPaint::kUTF32_TextEncoding:
1064 transparent.setTextEncoding(srcPaint.getTextEncoding());
1065 device->drawText(d, text, len, x, y, transparent);
1066 break;
1067 default:
1068 SkFAIL("unknown text encoding");
1069 }
1070}
1071
halcanary4ed2f012016-08-15 18:40:07 -07001072void SkPDFDevice::internalDrawText(
1073 const SkDraw& d, const void* sourceText, size_t sourceByteCount,
1074 const SkScalar pos[], SkTextBlob::GlyphPositioning positioning,
1075 SkPoint offset, const SkPaint& srcPaint) {
1076 NOT_IMPLEMENTED(srcPaint.getMaskFilter() != nullptr, false);
1077 if (srcPaint.getMaskFilter() != nullptr) {
1078 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1079 // making text unreadable (e.g. same text twice when using CSS shadows).
1080 return;
1081 }
halcanaryea17dfe2016-08-24 09:20:57 -07001082 NOT_IMPLEMENTED(srcPaint.isVerticalText(), false);
1083 if (srcPaint.isVerticalText()) {
1084 // Don't pretend we support drawing vertical text. It is not
1085 // clear to me how to switch to "vertical writing" mode in PDF.
1086 // Currently neither Chromium or Android set this flag.
1087 // https://bug.skia.org/5665
1088 return;
1089 }
halcanary4ed2f012016-08-15 18:40:07 -07001090 SkPaint paint = calculate_text_paint(srcPaint);
1091 replace_srcmode_on_opaque_paint(&paint);
1092 if (!paint.getTypeface()) {
1093 paint.setTypeface(SkTypeface::MakeDefault());
1094 }
1095 SkTypeface* typeface = paint.getTypeface();
1096 if (!typeface) {
1097 SkDebugf("SkPDF: SkTypeface::MakeDefault() returned nullptr.\n");
1098 return;
1099 }
1100 int typefaceGlyphCount = typeface->countGlyphs();
1101 if (typefaceGlyphCount < 1) {
1102 SkDebugf("SkPDF: SkTypeface has no glyphs.\n");
1103 return;
1104 }
1105 if (!SkPDFFont::CanEmbedTypeface(typeface, fDocument->canon())) {
1106 SkPath path; // https://bug.skia.org/3866
1107 paint.getTextPath(sourceText, sourceByteCount,
1108 offset.x(), offset.y(), &path);
robertphillips5ba165e2016-08-15 15:36:58 -07001109 this->drawPath(d, path, srcPaint, &SkMatrix::I(), true);
1110 // Draw text transparently to make it copyable/searchable/accessable.
halcanary4ed2f012016-08-15 18:40:07 -07001111 draw_transparent_text(this, d, sourceText, sourceByteCount,
1112 offset.x(), offset.y(), paint);
robertphillips5ba165e2016-08-15 15:36:58 -07001113 return;
1114 }
halcanary4ed2f012016-08-15 18:40:07 -07001115 // Always make a copy (1) to validate user-input glyphs and
1116 // (2) because we may modify the glyphs in place (for
1117 // single-byte-glyph-id PDF fonts).
1118 int glyphCount = paint.textToGlyphs(sourceText, sourceByteCount, nullptr);
1119 if (glyphCount <= 0) { return; }
1120 SkAutoSTMalloc<128, SkGlyphID> glyphStorage(SkToSizeT(glyphCount));
1121 SkGlyphID* glyphs = glyphStorage.get();
1122 (void)paint.textToGlyphs(sourceText, sourceByteCount, glyphs);
1123 if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
1124 // Validate user-input glyphs.
1125 SkGlyphID maxGlyphID = SkToU16(typefaceGlyphCount - 1);
1126 for (int i = 0; i < glyphCount; ++i) {
1127 glyphs[i] = SkTMin(maxGlyphID, glyphs[i]);
1128 }
1129 } else {
1130 paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
1131 }
robertphillips5ba165e2016-08-15 15:36:58 -07001132
halcanary4ed2f012016-08-15 18:40:07 -07001133 bool defaultPositioning = (positioning == SkTextBlob::kDefault_Positioning);
1134 SkAutoGlyphCache glyphCache(paint, nullptr, nullptr);
1135
1136 SkPaint::Align alignment = paint.getTextAlign();
halcanary4ed2f012016-08-15 18:40:07 -07001137 if (defaultPositioning && alignment != SkPaint::kLeft_Align) {
1138 SkScalar advance{0};
1139 for (int i = 0; i < glyphCount; ++i) {
1140 advance += glyphCache->getGlyphIDAdvance(glyphs[i]).fAdvanceX;
1141 }
1142 SkScalar m = alignment == SkPaint::kCenter_Align
1143 ? 0.5f * advance : advance;
halcanaryea17dfe2016-08-24 09:20:57 -07001144 offset -= SkPoint{m, 0};
halcanary6059dc32016-08-15 11:45:36 -07001145 }
halcanary4ed2f012016-08-15 18:40:07 -07001146 ScopedContentEntry content(this, d, paint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001147 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001148 return;
1149 }
halcanary4ed2f012016-08-15 18:40:07 -07001150 SkDynamicMemoryWStream* out = &content.entry()->fContent;
1151 out->writeText("BT\n");
1152 if (!this->updateFont(paint, glyphs[0], content.entry())) {
robertphillips5ba165e2016-08-15 15:36:58 -07001153 SkDebugf("SkPDF: Font error.");
halcanary4ed2f012016-08-15 18:40:07 -07001154 out->writeText("ET\n%SkPDF: Font error.\n");
robertphillips5ba165e2016-08-15 15:36:58 -07001155 return;
1156 }
halcanary4ed2f012016-08-15 18:40:07 -07001157 SkPDFFont* font = content.entry()->fState.fFont;
1158 GlyphPositioner glyphPositioner(out,
1159 paint.getTextSkewX(),
1160 font->multiByteGlyphs(),
1161 defaultPositioning,
1162 offset);
halcanary4ed2f012016-08-15 18:40:07 -07001163 const SkGlyphID* const glyphsEnd = glyphs + glyphCount;
1164
1165 while (glyphs < glyphsEnd) {
1166 font = content.entry()->fState.fFont;
1167 int stretch = font->multiByteGlyphs()
1168 ? SkToInt(glyphsEnd - glyphs)
1169 : font->glyphsToPDFFontEncodingCount(glyphs, SkToInt(glyphsEnd - glyphs));
1170 SkASSERT(glyphs + stretch <= glyphsEnd);
1171 if (stretch < 1) {
1172 SkASSERT(!font->multiByteGlyphs());
1173 // The current pdf font cannot encode the next glyph.
1174 // Try to get a pdf font which can encode the next glyph.
robertphillips5ba165e2016-08-15 15:36:58 -07001175 glyphPositioner.flush();
halcanary4ed2f012016-08-15 18:40:07 -07001176 if (!this->updateFont(paint, *glyphs, content.entry())) {
robertphillips5ba165e2016-08-15 15:36:58 -07001177 SkDebugf("SkPDF: Font error.");
halcanary4ed2f012016-08-15 18:40:07 -07001178 out->writeText("ET\n%SkPDF: Font error.\n");
robertphillips5ba165e2016-08-15 15:36:58 -07001179 return;
1180 }
1181 font = content.entry()->fState.fFont;
1182 glyphPositioner.setWideChars(font->multiByteGlyphs());
halcanary4ed2f012016-08-15 18:40:07 -07001183 // try again
1184 stretch = font->glyphsToPDFFontEncodingCount(glyphs,
1185 SkToInt(glyphsEnd - glyphs));
1186 if (stretch < 1) {
robertphillips5ba165e2016-08-15 15:36:58 -07001187 SkDEBUGFAIL("PDF could not encode glyph.");
halcanary4ed2f012016-08-15 18:40:07 -07001188 glyphPositioner.flush();
1189 out->writeText("ET\n%SkPDF: Font encoding error.\n");
1190 return;
robertphillips5ba165e2016-08-15 15:36:58 -07001191 }
1192 }
halcanary530032a2016-08-18 14:22:52 -07001193 font->noteGlyphUsage(glyphs, stretch);
halcanary4ed2f012016-08-15 18:40:07 -07001194 if (defaultPositioning) {
1195 (void)font->glyphsToPDFFontEncoding(glyphs, SkToInt(glyphsEnd - glyphs));
1196 while (stretch-- > 0) {
1197 glyphPositioner.writeGlyph(0, 0, 0, *glyphs);
1198 ++glyphs;
1199 }
1200 } else {
1201 while (stretch-- > 0) {
1202 SkScalar advance = glyphCache->getGlyphIDAdvance(*glyphs).fAdvanceX;
1203 SkScalar x = *pos++;
1204 // evaluate x and y in order!
1205 SkScalar y = SkTextBlob::kFull_Positioning == positioning ? *pos++ : 0;
1206 SkPoint xy{x, y};
1207 if (alignment != SkPaint::kLeft_Align) {
1208 SkScalar m = alignment == SkPaint::kCenter_Align
1209 ? 0.5f * advance : advance;
halcanaryea17dfe2016-08-24 09:20:57 -07001210 xy -= SkPoint{m, 0};
halcanary4ed2f012016-08-15 18:40:07 -07001211 }
1212 (void)font->glyphsToPDFFontEncoding(glyphs, 1);
1213 glyphPositioner.writeGlyph(xy.x(), xy.y(), advance, *glyphs);
1214 ++glyphs;
1215 }
1216 }
robertphillips5ba165e2016-08-15 15:36:58 -07001217 }
halcanary4ed2f012016-08-15 18:40:07 -07001218 glyphPositioner.flush();
1219 out->writeText("ET\n");
1220}
1221
1222void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
1223 SkScalar x, SkScalar y, const SkPaint& paint) {
1224 this->internalDrawText(d, text, len, nullptr, SkTextBlob::kDefault_Positioning,
1225 SkPoint{x, y}, paint);
1226}
1227
1228void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
1229 const SkScalar pos[], int scalarsPerPos,
1230 const SkPoint& offset, const SkPaint& paint) {
1231 this->internalDrawText(d, text, len, pos, (SkTextBlob::GlyphPositioning)scalarsPerPos,
1232 offset, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001233}
1234
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001235void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001236 int vertexCount, const SkPoint verts[],
1237 const SkPoint texs[], const SkColor colors[],
1238 SkXfermode* xmode, const uint16_t indices[],
1239 int indexCount, const SkPaint& paint) {
reed1e7f5e72016-04-27 07:49:17 -07001240 if (d.fRC->isEmpty()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001241 return;
1242 }
reed@google.com85e143c2013-12-30 15:51:25 +00001243 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001244}
1245
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001246void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1247 int x, int y, const SkPaint& paint) {
reedcf5c8462016-07-20 12:28:40 -07001248 SkASSERT(!paint.getImageFilter());
1249
reed7503d602016-07-15 14:23:29 -07001250 // Check if the source device is really a bitmapdevice (because that's what we returned
1251 // from createDevice (likely due to an imagefilter)
1252 SkPixmap pmap;
1253 if (device->peekPixels(&pmap)) {
1254 SkBitmap bitmap;
1255 bitmap.installPixels(pmap);
reedcf5c8462016-07-20 12:28:40 -07001256 this->drawSprite(d, bitmap, x, y, paint);
reed7503d602016-07-15 14:23:29 -07001257 return;
1258 }
1259
fmalita6987dca2014-11-13 08:33:37 -08001260 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001261 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001262
1263 SkScalar scalarX = SkIntToScalar(x);
1264 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001265 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1266 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001267 fLinkToURLs.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001268 }
halcanary91fcb3e2016-03-04 13:53:22 -08001269 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1270 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001271 fLinkToDestinations.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001272 }
halcanary91fcb3e2016-03-04 13:53:22 -08001273 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1274 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001275 fNamedDestinations.emplace_back(d.nameData.get(), p);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001276 }
1277
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001278 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001279 return;
1280 }
1281
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001282 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001283 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
reed1e7f5e72016-04-27 07:49:17 -07001284 ScopedContentEntry content(this, d.fClipStack, d.fRC->bwRgn(), matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001285 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001286 return;
1287 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001288 if (content.needShape()) {
1289 SkPath shape;
1290 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001291 SkIntToScalar(device->width()),
1292 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001293 content.setShape(shape);
1294 }
1295 if (!content.needSource()) {
1296 return;
1297 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001298
halcanary4b1e17e2016-07-27 14:49:46 -07001299 sk_sp<SkPDFObject> xObject = pdfDevice->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001300 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001301 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001302}
1303
reede8f30622016-03-23 18:59:25 -07001304sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1305 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001306}
1307
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001308
halcanary8103a342016-03-08 15:10:16 -08001309sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001310 SkTDArray<SkPDFObject*> fonts;
1311 fonts.setReserve(fFontResources.count());
1312 for (SkPDFFont* font : fFontResources) {
1313 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001314 }
halcanary8103a342016-03-08 15:10:16 -08001315 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001316 &fGraphicStateResources,
1317 &fShaderResources,
1318 &fXObjectResources,
1319 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001320}
1321
halcanary8103a342016-03-08 15:10:16 -08001322sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001323 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001324 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001325 mediaBox->appendInt(0);
1326 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001327 mediaBox->appendInt(fPageSize.width());
1328 mediaBox->appendInt(fPageSize.height());
1329 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001330}
1331
mtklein5f939ab2016-03-16 10:28:35 -07001332std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001333 SkDynamicMemoryWStream buffer;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001334 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanaryafdc1772016-08-23 09:02:12 -07001335 SkPDFUtils::AppendTransform(fInitialTransform, &buffer);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001336 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001337
halcanaryafdc1772016-08-23 09:02:12 -07001338 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, &buffer);
halcanary2be7e012016-03-28 11:58:08 -07001339 for (const auto& entry : fContentEntries) {
1340 SkPoint translation;
1341 translation.iset(this->getOrigin());
1342 translation.negate();
1343 gsState.updateClip(entry.fState.fClipStack, entry.fState.fClipRegion,
1344 translation);
1345 gsState.updateMatrix(entry.fState.fMatrix);
1346 gsState.updateDrawingState(entry.fState);
1347
halcanaryafdc1772016-08-23 09:02:12 -07001348 entry.fContent.writeToStream(&buffer);
halcanary2be7e012016-03-28 11:58:08 -07001349 }
1350 gsState.drainStack();
halcanaryafdc1772016-08-23 09:02:12 -07001351
1352 return std::unique_ptr<SkStreamAsset>(
1353 buffer.bytesWritten() > 0
1354 ? buffer.detachAsStream()
1355 : new SkMemoryStream);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001356}
1357
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001358/* Draws an inverse filled path by using Path Ops to compute the positive
1359 * inverse using the current clip as the inverse bounds.
1360 * Return true if this was an inverse path and was properly handled,
1361 * otherwise returns false and the normal drawing routine should continue,
1362 * either as a (incorrect) fallback or because the path was not inverse
1363 * in the first place.
1364 */
1365bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001366 const SkPaint& paint, bool pathIsMutable,
1367 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001368 if (!origPath.isInverseFillType()) {
1369 return false;
1370 }
1371
reed1e7f5e72016-04-27 07:49:17 -07001372 if (d.fRC->isEmpty()) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001373 return false;
1374 }
1375
1376 SkPath modifiedPath;
1377 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1378 SkPaint noInversePaint(paint);
1379
1380 // Merge stroking operations into final path.
1381 if (SkPaint::kStroke_Style == paint.getStyle() ||
1382 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1383 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1384 if (doFillPath) {
1385 noInversePaint.setStyle(SkPaint::kFill_Style);
1386 noInversePaint.setStrokeWidth(0);
1387 pathPtr = &modifiedPath;
1388 } else {
1389 // To be consistent with the raster output, hairline strokes
1390 // are rendered as non-inverted.
1391 modifiedPath.toggleInverseFillType();
halcanary96fcdcc2015-08-27 07:41:13 -07001392 drawPath(d, modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001393 return true;
1394 }
1395 }
1396
1397 // Get bounds of clip in current transform space
1398 // (clip bounds are given in device space).
1399 SkRect bounds;
1400 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001401 SkMatrix totalMatrix = *d.fMatrix;
1402 if (prePathMatrix) {
1403 totalMatrix.preConcat(*prePathMatrix);
1404 }
1405 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001406 return false;
1407 }
reed1e7f5e72016-04-27 07:49:17 -07001408 bounds.set(d.fRC->getBounds());
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001409 transformInverse.mapRect(&bounds);
1410
1411 // Extend the bounds by the line width (plus some padding)
1412 // so the edge doesn't cause a visible stroke.
1413 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1414 paint.getStrokeWidth() + SK_Scalar1);
1415
1416 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1417 return false;
1418 }
1419
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001420 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001421 return true;
1422}
1423
reedf70b5312016-03-04 16:36:20 -08001424void SkPDFDevice::handlePointAnnotation(const SkPoint& point,
epoger@google.comb58772f2013-03-08 09:09:10 +00001425 const SkMatrix& matrix,
reedf70b5312016-03-04 16:36:20 -08001426 const char key[], SkData* value) {
1427 if (!value) {
1428 return;
epoger@google.comb58772f2013-03-08 09:09:10 +00001429 }
reedf70b5312016-03-04 16:36:20 -08001430
1431 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
1432 SkPoint transformedPoint;
1433 matrix.mapXY(point.x(), point.y(), &transformedPoint);
1434 fNamedDestinations.emplace_back(value, transformedPoint);
1435 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001436}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001437
reedf70b5312016-03-04 16:36:20 -08001438void SkPDFDevice::handlePathAnnotation(const SkPath& path,
wangxianzhuef6c50a2015-09-17 20:38:02 -07001439 const SkDraw& d,
reedf70b5312016-03-04 16:36:20 -08001440 const char key[], SkData* value) {
1441 if (!value) {
1442 return;
1443 }
wangxianzhuef6c50a2015-09-17 20:38:02 -07001444
1445 SkPath transformedPath = path;
1446 transformedPath.transform(*d.fMatrix);
1447 SkRasterClip clip = *d.fRC;
senorblancoafc7cce2016-02-02 18:44:15 -08001448 clip.op(transformedPath, SkIRect::MakeWH(width(), height()), SkRegion::kIntersect_Op,
1449 false);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001450 SkRect transformedRect = SkRect::Make(clip.getBounds());
1451
reedf70b5312016-03-04 16:36:20 -08001452 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001453 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001454 fLinkToURLs.emplace_back(transformedRect, value);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001455 }
reedf70b5312016-03-04 16:36:20 -08001456 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
reed16108352016-03-03 09:14:36 -08001457 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001458 fLinkToDestinations.emplace_back(transformedRect, value);
reed16108352016-03-03 09:14:36 -08001459 }
reed16108352016-03-03 09:14:36 -08001460 }
halcanary438de492015-04-28 06:21:01 -07001461}
1462
wangxianzhuef6c50a2015-09-17 20:38:02 -07001463void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1464 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001465 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001466 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001467 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001468 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001469 }
halcanary91fcb3e2016-03-04 13:53:22 -08001470 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001471 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001472 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001473 array->appendObject(
1474 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001475 }
1476}
epoger@google.comb58772f2013-03-08 09:09:10 +00001477
halcanary6d622702015-03-25 08:45:42 -07001478void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001479 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001480 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001481 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001482 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001483 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001484 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001485 pdfDest->appendScalar(p.x());
1486 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001487 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001488 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001489 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001490 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001491}
1492
halcanary4b1e17e2016-07-27 14:49:46 -07001493sk_sp<SkPDFObject> SkPDFDevice::makeFormXObjectFromDevice() {
halcanary5abbb442016-07-29 08:41:33 -07001494 SkMatrix inverseTransform = SkMatrix::I();
halcanaryafdc1772016-08-23 09:02:12 -07001495 if (!fInitialTransform.isIdentity()) {
1496 if (!fInitialTransform.invert(&inverseTransform)) {
halcanary5abbb442016-07-29 08:41:33 -07001497 SkDEBUGFAIL("Layer initial transform should be invertible.");
1498 inverseTransform.reset();
1499 }
1500 }
halcanary4b1e17e2016-07-27 14:49:46 -07001501 sk_sp<SkPDFObject> xobject =
1502 SkPDFMakeFormXObject(this->content(), this->copyMediaBox(),
halcanary5abbb442016-07-29 08:41:33 -07001503 this->makeResourceDict(), inverseTransform, nullptr);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001504 // We always draw the form xobjects that we create back into the device, so
1505 // we simply preserve the font usage instead of pulling it out and merging
1506 // it back in later.
halcanary4b1e17e2016-07-27 14:49:46 -07001507 this->cleanUp(); // Reset this device to have no content.
1508 this->init();
reed@google.comfc641d02012-09-20 17:52:20 +00001509 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001510}
1511
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001512void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
halcanarydabd4f02016-08-03 11:16:56 -07001513 sk_sp<SkPDFObject> mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001514 const SkClipStack* clipStack,
1515 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001516 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001517 bool invertClip) {
1518 if (clipRegion.isEmpty() && !invertClip) {
1519 return;
1520 }
1521
halcanary4b1e17e2016-07-27 14:49:46 -07001522 sk_sp<SkPDFDict> sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanarydabd4f02016-08-03 11:16:56 -07001523 std::move(mask), invertClip,
1524 SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001525
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001526 SkMatrix identity;
1527 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001528 SkPaint paint;
1529 paint.setXfermodeMode(mode);
1530 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001531 if (!content.entry()) {
1532 return;
1533 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001534 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001535 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001536 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001537
halcanary1437c1e2016-03-13 18:30:24 -07001538 // Call makeNoSmaskGraphicState() instead of
1539 // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1540 // can deduplicate.
halcanary989da4a2016-03-21 14:33:17 -07001541 sMaskGS = fDocument->canon()->makeNoSmaskGraphicState();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001542 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001543 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001544}
1545
halcanary2be7e012016-03-28 11:58:08 -07001546SkPDFDevice::ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001547 const SkRegion& clipRegion,
1548 const SkMatrix& matrix,
1549 const SkPaint& paint,
1550 bool hasText,
halcanarydabd4f02016-08-03 11:16:56 -07001551 sk_sp<SkPDFObject>* dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001552 *dst = nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001553 if (clipRegion.isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -07001554 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001555 }
1556
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001557 // The clip stack can come from an SkDraw where it is technically optional.
1558 SkClipStack synthesizedClipStack;
halcanary96fcdcc2015-08-27 07:41:13 -07001559 if (clipStack == nullptr) {
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001560 if (clipRegion == fExistingClipRegion) {
1561 clipStack = &fExistingClipStack;
1562 } else {
1563 // GraphicStackState::updateClip expects the clip stack to have
1564 // fExistingClip as a prefix, so start there, then set the clip
1565 // to the passed region.
1566 synthesizedClipStack = fExistingClipStack;
1567 SkPath clipPath;
1568 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001569 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1570 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001571 clipStack = &synthesizedClipStack;
1572 }
1573 }
1574
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001575 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1576 if (paint.getXfermode()) {
1577 paint.getXfermode()->asMode(&xfermode);
1578 }
1579
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001580 // For the following modes, we want to handle source and destination
1581 // separately, so make an object of what's already there.
1582 if (xfermode == SkXfermode::kClear_Mode ||
1583 xfermode == SkXfermode::kSrc_Mode ||
1584 xfermode == SkXfermode::kSrcIn_Mode ||
1585 xfermode == SkXfermode::kDstIn_Mode ||
1586 xfermode == SkXfermode::kSrcOut_Mode ||
1587 xfermode == SkXfermode::kDstOut_Mode ||
1588 xfermode == SkXfermode::kSrcATop_Mode ||
1589 xfermode == SkXfermode::kDstATop_Mode ||
1590 xfermode == SkXfermode::kModulate_Mode) {
1591 if (!isContentEmpty()) {
halcanarydabd4f02016-08-03 11:16:56 -07001592 *dst = this->makeFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001593 SkASSERT(isContentEmpty());
1594 } else if (xfermode != SkXfermode::kSrc_Mode &&
1595 xfermode != SkXfermode::kSrcOut_Mode) {
1596 // Except for Src and SrcOut, if there isn't anything already there,
1597 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001598 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001599 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001600 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001601 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001602 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001603
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001604 // Dst xfer mode doesn't draw source at all.
1605 if (xfermode == SkXfermode::kDst_Mode) {
halcanary96fcdcc2015-08-27 07:41:13 -07001606 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001607 }
1608
halcanary2be7e012016-03-28 11:58:08 -07001609 SkPDFDevice::ContentEntry* entry;
1610 if (fContentEntries.back() && fContentEntries.back()->fContent.getOffset() == 0) {
1611 entry = fContentEntries.back();
1612 } else if (xfermode != SkXfermode::kDstOver_Mode) {
1613 entry = fContentEntries.emplace_back();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001614 } else {
halcanary2be7e012016-03-28 11:58:08 -07001615 entry = fContentEntries.emplace_front();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001616 }
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001617 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001618 hasText, &entry->fState);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001619 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001620}
1621
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001622void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
halcanarydabd4f02016-08-03 11:16:56 -07001623 sk_sp<SkPDFObject> dst,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001624 SkPath* shape) {
1625 if (xfermode != SkXfermode::kClear_Mode &&
1626 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001627 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001628 xfermode != SkXfermode::kSrcIn_Mode &&
1629 xfermode != SkXfermode::kDstIn_Mode &&
1630 xfermode != SkXfermode::kSrcOut_Mode &&
1631 xfermode != SkXfermode::kDstOut_Mode &&
1632 xfermode != SkXfermode::kSrcATop_Mode &&
1633 xfermode != SkXfermode::kDstATop_Mode &&
1634 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001635 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001636 return;
1637 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001638 if (xfermode == SkXfermode::kDstOver_Mode) {
1639 SkASSERT(!dst);
halcanary2be7e012016-03-28 11:58:08 -07001640 if (fContentEntries.front()->fContent.getOffset() == 0) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001641 // For DstOver, an empty content entry was inserted before the rest
1642 // of the content entries. If nothing was drawn, it needs to be
1643 // removed.
halcanary2be7e012016-03-28 11:58:08 -07001644 fContentEntries.pop_front();
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001645 }
1646 return;
1647 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001648 if (!dst) {
1649 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1650 xfermode == SkXfermode::kSrcOut_Mode);
1651 return;
1652 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001653
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001654 SkASSERT(dst);
halcanary2be7e012016-03-28 11:58:08 -07001655 SkASSERT(fContentEntries.count() == 1);
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001656 // Changing the current content into a form-xobject will destroy the clip
1657 // objects which is fine since the xobject will already be clipped. However
1658 // if source has shape, we need to clip it too, so a copy of the clip is
1659 // saved.
halcanary2be7e012016-03-28 11:58:08 -07001660
1661 SkClipStack clipStack = fContentEntries.front()->fState.fClipStack;
1662 SkRegion clipRegion = fContentEntries.front()->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001663
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001664 SkMatrix identity;
1665 identity.reset();
1666 SkPaint stockPaint;
1667
halcanary4b1e17e2016-07-27 14:49:46 -07001668 sk_sp<SkPDFObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001669 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001670 // If nothing was drawn and there's no shape, then the draw was a
1671 // no-op, but dst needs to be restored for that to be true.
1672 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1673 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1674 // reduces to Dst.
halcanary96fcdcc2015-08-27 07:41:13 -07001675 if (shape == nullptr || xfermode == SkXfermode::kDstOut_Mode ||
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001676 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001677 ScopedContentEntry content(this, &fExistingClipStack,
1678 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001679 stockPaint);
halcanarydabd4f02016-08-03 11:16:56 -07001680 // TODO: addXObjectResource take sk_sp
1681 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001682 &content.entry()->fContent);
1683 return;
1684 } else {
1685 xfermode = SkXfermode::kClear_Mode;
1686 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001687 } else {
halcanary2be7e012016-03-28 11:58:08 -07001688 SkASSERT(fContentEntries.count() == 1);
halcanary4b1e17e2016-07-27 14:49:46 -07001689 srcFormXObject = this->makeFormXObjectFromDevice();
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001690 }
1691
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001692 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1693 // without alpha.
1694 if (xfermode == SkXfermode::kSrcATop_Mode) {
1695 // TODO(vandebo): In order to properly support SrcATop we have to track
1696 // the shape of what's been drawn at all times. It's the intersection of
1697 // the non-transparent parts of the device and the outlines (shape) of
1698 // all images and devices drawn.
1699 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001700 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001701 SkXfermode::kSrcOver_Mode, true);
1702 } else {
halcanary96fcdcc2015-08-27 07:41:13 -07001703 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001704 // Draw shape into a form-xobject.
reed1e7f5e72016-04-27 07:49:17 -07001705 SkRasterClip rc(clipRegion);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001706 SkDraw d;
1707 d.fMatrix = &identity;
reed1e7f5e72016-04-27 07:49:17 -07001708 d.fRC = &rc;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001709 d.fClipStack = &clipStack;
1710 SkPaint filledPaint;
1711 filledPaint.setColor(SK_ColorBLACK);
1712 filledPaint.setStyle(SkPaint::kFill_Style);
halcanary96fcdcc2015-08-27 07:41:13 -07001713 this->drawPath(d, *shape, filledPaint, nullptr, true);
halcanarydabd4f02016-08-03 11:16:56 -07001714 drawFormXObjectWithMask(addXObjectResource(dst.get()),
1715 this->makeFormXObjectFromDevice(),
1716 &fExistingClipStack, fExistingClipRegion,
1717 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001718
halcanarydabd4f02016-08-03 11:16:56 -07001719 } else {
1720 drawFormXObjectWithMask(addXObjectResource(dst.get()), srcFormXObject,
1721 &fExistingClipStack, fExistingClipRegion,
1722 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001723 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001724 }
1725
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001726 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001727 return;
1728 } else if (xfermode == SkXfermode::kSrc_Mode ||
1729 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001730 ScopedContentEntry content(this, &fExistingClipStack,
1731 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001732 if (content.entry()) {
1733 SkPDFUtils::DrawFormXObject(
1734 this->addXObjectResource(srcFormXObject.get()),
1735 &content.entry()->fContent);
1736 }
1737 if (xfermode == SkXfermode::kSrc_Mode) {
1738 return;
1739 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001740 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001741 ScopedContentEntry content(this, &fExistingClipStack,
1742 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001743 if (content.entry()) {
halcanarydabd4f02016-08-03 11:16:56 -07001744 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst.get()),
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001745 &content.entry()->fContent);
1746 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001747 }
1748
1749 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1750 xfermode == SkXfermode::kDstIn_Mode ||
1751 xfermode == SkXfermode::kSrcOut_Mode ||
1752 xfermode == SkXfermode::kDstOut_Mode ||
1753 xfermode == SkXfermode::kSrcATop_Mode ||
1754 xfermode == SkXfermode::kDstATop_Mode ||
1755 xfermode == SkXfermode::kModulate_Mode);
1756
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001757 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001758 xfermode == SkXfermode::kSrcOut_Mode ||
1759 xfermode == SkXfermode::kSrcATop_Mode) {
halcanarydabd4f02016-08-03 11:16:56 -07001760 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
1761 std::move(dst),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001762 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001763 SkXfermode::kSrcOver_Mode,
1764 xfermode == SkXfermode::kSrcOut_Mode);
halcanarydabd4f02016-08-03 11:16:56 -07001765 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001766 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001767 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
halcanarydabd4f02016-08-03 11:16:56 -07001768 int resourceID = addXObjectResource(dst.get());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001769 if (xfermode == SkXfermode::kModulate_Mode) {
1770 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
halcanarydabd4f02016-08-03 11:16:56 -07001771 std::move(dst), &fExistingClipStack,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001772 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001773 SkXfermode::kSrcOver_Mode, false);
1774 mode = SkXfermode::kMultiply_Mode;
1775 }
halcanarydabd4f02016-08-03 11:16:56 -07001776 drawFormXObjectWithMask(resourceID, std::move(srcFormXObject),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001777 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001778 xfermode == SkXfermode::kDstOut_Mode);
halcanarydabd4f02016-08-03 11:16:56 -07001779 return;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001780 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001781}
1782
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001783bool SkPDFDevice::isContentEmpty() {
halcanary2be7e012016-03-28 11:58:08 -07001784 if (!fContentEntries.front() || fContentEntries.front()->fContent.getOffset() == 0) {
1785 SkASSERT(fContentEntries.count() <= 1);
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001786 return true;
1787 }
1788 return false;
1789}
1790
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001791void SkPDFDevice::populateGraphicStateEntryFromPaint(
1792 const SkMatrix& matrix,
1793 const SkClipStack& clipStack,
1794 const SkRegion& clipRegion,
1795 const SkPaint& paint,
1796 bool hasText,
halcanary2be7e012016-03-28 11:58:08 -07001797 SkPDFDevice::GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07001798 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1799 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1800 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001801
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001802 entry->fMatrix = matrix;
1803 entry->fClipStack = clipStack;
1804 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001805 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1806 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001807
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001808 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08001809 sk_sp<SkPDFObject> pdfShader;
reedfe630452016-03-25 09:08:00 -07001810 SkShader* shader = paint.getShader();
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001811 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001812 if (shader) {
1813 // PDF positions patterns relative to the initial transform, so
1814 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001815 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001816 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001817
1818 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001819 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001820 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001821
1822 // We need to apply the initial transform to bounds in order to get
1823 // bounds in a consistent coordinate system.
1824 SkRect boundsTemp;
1825 boundsTemp.set(bounds);
1826 fInitialTransform.mapRect(&boundsTemp);
1827 boundsTemp.roundOut(&bounds);
1828
halcanary792c80f2015-02-20 07:21:05 -08001829 SkScalar rasterScale =
1830 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
halcanarydabd4f02016-08-03 11:16:56 -07001831 pdfShader = SkPDFShader::GetPDFShader(
1832 fDocument, fRasterDpi, shader, transform, bounds, rasterScale);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001833
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001834 if (pdfShader.get()) {
1835 // pdfShader has been canonicalized so we can directly compare
1836 // pointers.
1837 int resourceIndex = fShaderResources.find(pdfShader.get());
1838 if (resourceIndex < 0) {
1839 resourceIndex = fShaderResources.count();
1840 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001841 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001842 }
1843 entry->fShaderIndex = resourceIndex;
1844 } else {
1845 // A color shader is treated as an invalid shader so we don't have
1846 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001847 SkShader::GradientInfo gradientInfo;
1848 SkColor gradientColor;
1849 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07001850 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001851 gradientInfo.fColorCount = 1;
1852 if (shader->asAGradient(&gradientInfo) ==
1853 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001854 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1855 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001856 }
1857 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001858 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001859
halcanary48810a02016-03-07 14:57:50 -08001860 sk_sp<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001861 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001862 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07001863 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001864 } else {
1865 SkPaint newPaint = paint;
1866 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001867 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07001868 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001869 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001870 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001871 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001872
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001873 if (hasText) {
1874 entry->fTextScaleX = paint.getTextScaleX();
1875 entry->fTextFill = paint.getStyle();
1876 } else {
1877 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001878 }
1879}
1880
halcanarybe27a112015-04-01 13:31:19 -07001881int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001882 // Assumes that gs has been canonicalized (so we can directly compare
1883 // pointers).
1884 int result = fGraphicStateResources.find(gs);
1885 if (result < 0) {
1886 result = fGraphicStateResources.count();
1887 fGraphicStateResources.push(gs);
1888 gs->ref();
1889 }
1890 return result;
1891}
1892
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001893int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
halcanarydabd4f02016-08-03 11:16:56 -07001894 // TODO(halcanary): make this take a sk_sp<SkPDFObject>
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001895 // Assumes that xobject has been canonicalized (so we can directly compare
1896 // pointers).
1897 int result = fXObjectResources.find(xObject);
1898 if (result < 0) {
1899 result = fXObjectResources.count();
halcanarydabd4f02016-08-03 11:16:56 -07001900 fXObjectResources.push(SkRef(xObject));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001901 }
1902 return result;
1903}
1904
halcanary7e8d5d32016-08-12 07:59:38 -07001905bool SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
halcanary2be7e012016-03-28 11:58:08 -07001906 SkPDFDevice::ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001907 SkTypeface* typeface = paint.getTypeface();
halcanary96fcdcc2015-08-27 07:41:13 -07001908 if (contentEntry->fState.fFont == nullptr ||
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001909 contentEntry->fState.fTextSize != paint.getTextSize() ||
1910 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001911 int fontIndex = getFontResourceIndex(typeface, glyphID);
halcanary7e8d5d32016-08-12 07:59:38 -07001912 if (fontIndex < 0) {
1913 return false;
1914 }
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001915 contentEntry->fContent.writeText("/");
1916 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
1917 SkPDFResourceDict::kFont_ResourceType,
1918 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001919 contentEntry->fContent.writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -07001920 SkPDFUtils::AppendScalar(paint.getTextSize(), &contentEntry->fContent);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001921 contentEntry->fContent.writeText(" Tf\n");
1922 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001923 }
halcanary7e8d5d32016-08-12 07:59:38 -07001924 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001925}
1926
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001927int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary48810a02016-03-07 14:57:50 -08001928 sk_sp<SkPDFFont> newFont(
halcanary989da4a2016-03-21 14:33:17 -07001929 SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID));
halcanary7e8d5d32016-08-12 07:59:38 -07001930 if (!newFont) {
1931 return -1;
1932 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001933 int resourceIndex = fFontResources.find(newFont.get());
1934 if (resourceIndex < 0) {
halcanary530032a2016-08-18 14:22:52 -07001935 fDocument->registerFont(newFont.get());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001936 resourceIndex = fFontResources.count();
halcanary530032a2016-08-18 14:22:52 -07001937 fFontResources.push(newFont.release());
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001938 }
1939 return resourceIndex;
1940}
1941
halcanary7a14b312015-10-01 07:28:13 -07001942static SkSize rect_to_size(const SkRect& r) {
1943 return SkSize::Make(r.width(), r.height());
1944}
1945
halcanarya50151d2016-03-25 11:57:49 -07001946static sk_sp<SkImage> color_filter(const SkImageBitmap& imageBitmap,
1947 SkColorFilter* colorFilter) {
halcanary9d524f22016-03-29 09:03:52 -07001948 auto surface =
halcanarya50151d2016-03-25 11:57:49 -07001949 SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(imageBitmap.dimensions()));
1950 SkASSERT(surface);
halcanary7a14b312015-10-01 07:28:13 -07001951 SkCanvas* canvas = surface->getCanvas();
1952 canvas->clear(SK_ColorTRANSPARENT);
1953 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07001954 paint.setColorFilter(sk_ref_sp(colorFilter));
halcanarya50151d2016-03-25 11:57:49 -07001955 imageBitmap.draw(canvas, &paint);
halcanary7a14b312015-10-01 07:28:13 -07001956 canvas->flush();
halcanarya50151d2016-03-25 11:57:49 -07001957 return surface->makeImageSnapshot();
halcanary7a14b312015-10-01 07:28:13 -07001958}
1959
1960////////////////////////////////////////////////////////////////////////////////
1961void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
1962 const SkClipStack* clipStack,
1963 const SkRegion& origClipRegion,
halcanarya50151d2016-03-25 11:57:49 -07001964 SkImageBitmap imageBitmap,
halcanary7a14b312015-10-01 07:28:13 -07001965 const SkPaint& paint) {
halcanarya50151d2016-03-25 11:57:49 -07001966 if (imageBitmap.dimensions().isZero()) {
1967 return;
1968 }
halcanary7a14b312015-10-01 07:28:13 -07001969 #ifdef SK_PDF_IMAGE_STATS
1970 gDrawImageCalls.fetch_add(1);
1971 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001972 SkMatrix matrix = origMatrix;
1973 SkRegion perspectiveBounds;
1974 const SkRegion* clipRegion = &origClipRegion;
halcanarya50151d2016-03-25 11:57:49 -07001975 sk_sp<SkImage> autoImageUnref;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001976
1977 // Rasterize the bitmap using perspective in a new bitmap.
1978 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001979 if (fRasterDpi == 0) {
1980 return;
1981 }
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001982 // Transform the bitmap in the new space, without taking into
1983 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001984 SkPath perspectiveOutline;
halcanarya50151d2016-03-25 11:57:49 -07001985 SkRect imageBounds = SkRect::Make(imageBitmap.bounds());
halcanary7a14b312015-10-01 07:28:13 -07001986 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00001987 perspectiveOutline.transform(origMatrix);
1988
1989 // TODO(edisonn): perf - use current clip too.
1990 // Retrieve the bounds of the new shape.
1991 SkRect bounds = perspectiveOutline.getBounds();
1992
edisonn@google.com73a7ea32013-11-11 20:55:15 +00001993 // Transform the bitmap in the new space, taking into
1994 // account the initial transform.
1995 SkMatrix total = origMatrix;
1996 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07001997 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
1998 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
1999 total.postScale(dpiScale, dpiScale);
2000
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002001 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002002 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002003 physicalPerspectiveOutline.transform(total);
2004
halcanary7a14b312015-10-01 07:28:13 -07002005 SkRect physicalPerspectiveBounds =
2006 physicalPerspectiveOutline.getBounds();
2007 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2008 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002009
2010 // TODO(edisonn): A better approach would be to use a bitmap shader
2011 // (in clamp mode) and draw a rect over the entire bounding box. Then
2012 // intersect perspectiveOutline to the clip. That will avoid introducing
2013 // alpha to the image while still giving good behavior at the edge of
2014 // the image. Avoiding alpha will reduce the pdf size and generation
2015 // CPU time some.
2016
halcanary7a14b312015-10-01 07:28:13 -07002017 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2018
reede8f30622016-03-23 18:59:25 -07002019 auto surface(SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh)));
halcanary7a14b312015-10-01 07:28:13 -07002020 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002021 return;
2022 }
halcanary7a14b312015-10-01 07:28:13 -07002023 SkCanvas* canvas = surface->getCanvas();
2024 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002025
2026 SkScalar deltaX = bounds.left();
2027 SkScalar deltaY = bounds.top();
2028
2029 SkMatrix offsetMatrix = origMatrix;
2030 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002031 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002032
2033 // Translate the draw in the new canvas, so we perfectly fit the
2034 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002035 canvas->setMatrix(offsetMatrix);
halcanarya50151d2016-03-25 11:57:49 -07002036 imageBitmap.draw(canvas, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002037 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002038 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002039
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002040 // In the new space, we use the identity matrix translated
2041 // and scaled to reflect DPI.
2042 matrix.setScale(1 / scaleX, 1 / scaleY);
2043 matrix.postTranslate(deltaX, deltaY);
2044
halcanary7a14b312015-10-01 07:28:13 -07002045 perspectiveBounds.setRect(bounds.roundOut());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002046 clipRegion = &perspectiveBounds;
halcanary7a14b312015-10-01 07:28:13 -07002047
halcanarya50151d2016-03-25 11:57:49 -07002048 autoImageUnref = surface->makeImageSnapshot();
2049 imageBitmap = SkImageBitmap(autoImageUnref.get());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002050 }
2051
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002052 SkMatrix scaled;
2053 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002054 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2055 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002056 // Scale the image up from 1x1 to WxH.
halcanarya50151d2016-03-25 11:57:49 -07002057 SkIRect subset = imageBitmap.bounds();
2058 scaled.postScale(SkIntToScalar(imageBitmap.dimensions().width()),
2059 SkIntToScalar(imageBitmap.dimensions().height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002060 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002061 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
halcanarya50151d2016-03-25 11:57:49 -07002062 if (!content.entry()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002063 return;
2064 }
2065 if (content.needShape()) {
2066 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002067 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002068 shape.transform(matrix);
2069 content.setShape(shape);
2070 }
2071 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002072 return;
2073 }
2074
halcanary287d22d2015-09-24 10:20:05 -07002075 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002076 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002077 // draw calls. This code here works for all
2078 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2079 // rasterize a layer on this backend). Fortuanely, this seems
2080 // to be how Chromium impements most color-filters.
halcanarya50151d2016-03-25 11:57:49 -07002081 autoImageUnref = color_filter(imageBitmap, colorFilter);
2082 imageBitmap = SkImageBitmap(autoImageUnref.get());
halcanary7a14b312015-10-01 07:28:13 -07002083 // TODO(halcanary): de-dupe this by caching filtered images.
2084 // (maybe in the resource cache?)
2085 }
halcanarya50151d2016-03-25 11:57:49 -07002086
2087 SkBitmapKey key = imageBitmap.getKey();
2088 sk_sp<SkPDFObject> pdfimage = fDocument->canon()->findPDFBitmap(key);
halcanary7a14b312015-10-01 07:28:13 -07002089 if (!pdfimage) {
halcanary4b1e17e2016-07-27 14:49:46 -07002090 sk_sp<SkImage> img = imageBitmap.makeImage();
halcanarya50151d2016-03-25 11:57:49 -07002091 if (!img) {
2092 return;
2093 }
2094 pdfimage = SkPDFCreateBitmapObject(
2095 std::move(img), fDocument->canon()->getPixelSerializer());
halcanary7a14b312015-10-01 07:28:13 -07002096 if (!pdfimage) {
2097 return;
halcanary287d22d2015-09-24 10:20:05 -07002098 }
halcanarya50151d2016-03-25 11:57:49 -07002099 fDocument->serialize(pdfimage); // serialize images early.
2100 fDocument->canon()->addPDFBitmap(key, pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002101 }
halcanarya50151d2016-03-25 11:57:49 -07002102 // TODO(halcanary): addXObjectResource() should take a sk_sp<SkPDFObject>
halcanary3d8c33c2015-10-01 11:06:22 -07002103 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002104 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002105}
reede51c3562016-07-19 14:33:20 -07002106
2107///////////////////////////////////////////////////////////////////////////////////////////////////
2108
2109#include "SkSpecialImage.h"
2110#include "SkImageFilter.h"
2111
2112void SkPDFDevice::drawSpecial(const SkDraw& draw, SkSpecialImage* srcImg, int x, int y,
2113 const SkPaint& paint) {
2114 SkASSERT(!srcImg->isTextureBacked());
2115
2116 SkBitmap resultBM;
2117
2118 SkImageFilter* filter = paint.getImageFilter();
2119 if (filter) {
2120 SkIPoint offset = SkIPoint::Make(0, 0);
2121 SkMatrix matrix = *draw.fMatrix;
2122 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
2123 const SkIRect clipBounds = draw.fRC->getBounds().makeOffset(-x, -y);
2124// SkAutoTUnref<SkImageFilterCache> cache(this->getImageFilterCache());
2125 SkImageFilter::Context ctx(matrix, clipBounds, nullptr /*cache.get()*/);
2126
2127 sk_sp<SkSpecialImage> resultImg(filter->filterImage(srcImg, ctx, &offset));
2128 if (resultImg) {
2129 SkPaint tmpUnfiltered(paint);
2130 tmpUnfiltered.setImageFilter(nullptr);
2131 if (resultImg->getROPixels(&resultBM)) {
2132 this->drawSprite(draw, resultBM, x + offset.x(), y + offset.y(), tmpUnfiltered);
2133 }
2134 }
2135 } else {
2136 if (srcImg->getROPixels(&resultBM)) {
2137 this->drawSprite(draw, resultBM, x, y, paint);
2138 }
2139 }
2140}
2141
2142sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkBitmap& bitmap) {
2143 return SkSpecialImage::MakeFromRaster(bitmap.bounds(), bitmap);
2144}
2145
2146sk_sp<SkSpecialImage> SkPDFDevice::makeSpecial(const SkImage* image) {
2147 return SkSpecialImage::MakeFromImage(SkIRect::MakeWH(image->width(), image->height()),
2148 image->makeNonTextureImage());
2149}
2150
2151sk_sp<SkSpecialImage> SkPDFDevice::snapSpecial() {
reede51c3562016-07-19 14:33:20 -07002152 return nullptr;
2153}