blob: 0054143a9aa5cb561f9094b51ee03493c1cffb54 [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"
9
reedf70b5312016-03-04 16:36:20 -080010#include "SkAnnotationKeys.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000011#include "SkColor.h"
halcanary287d22d2015-09-24 10:20:05 -070012#include "SkColorFilter.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000013#include "SkClipStack.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.org9b49dc02010-10-20 22:23:29 +000016#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000017#include "SkPath.h"
reeda4393342016-03-18 11:22:57 -070018#include "SkPathEffect.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000019#include "SkPathOps.h"
halcanarydb0dcc72015-03-20 12:31:52 -070020#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070021#include "SkPDFCanon.h"
halcanary989da4a2016-03-21 14:33:17 -070022#include "SkPDFDocument.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000023#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000024#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000025#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000026#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000027#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000028#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000029#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000030#include "SkPDFUtils.h"
wangxianzhuef6c50a2015-09-17 20:38:02 -070031#include "SkRasterClip.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000032#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000033#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000034#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070035#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000036#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000037#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000038#include "SkTypefacePriv.h"
halcanarya6814332015-05-27 08:53:36 -070039#include "SkXfermodeInterpretation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000040
edisonn@google.com73a7ea32013-11-11 20:55:15 +000041#define DPI_FOR_RASTER_SCALE_ONE 72
42
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000043// Utility functions
44
halcanarya6814332015-05-27 08:53:36 -070045// If the paint will definitely draw opaquely, replace kSrc_Mode with
46// kSrcOver_Mode. http://crbug.com/473572
47static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
48 if (kSrcOver_SkXfermodeInterpretation
49 == SkInterpretXfermode(*paint, false)) {
halcanary96fcdcc2015-08-27 07:41:13 -070050 paint->setXfermode(nullptr);
halcanarya6814332015-05-27 08:53:36 -070051 }
52}
53
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000054static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000055 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
reed80ea19c2015-05-12 10:37:34 -070056 SkScalar colorScale = SkScalarInvert(0xFF);
57 SkPDFUtils::AppendScalar(SkColorGetR(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000058 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070059 SkPDFUtils::AppendScalar(SkColorGetG(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000060 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070061 SkPDFUtils::AppendScalar(SkColorGetB(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000062 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000063}
64
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000065static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000066 SkPaint result = paint;
67 if (result.isFakeBoldText()) {
68 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
69 kStdFakeBoldInterpKeys,
70 kStdFakeBoldInterpValues,
71 kStdFakeBoldInterpLength);
72 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000073 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000074 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000075 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000076 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000077 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000078 result.setStrokeWidth(width);
79 }
80 return result;
81}
82
83// Stolen from measure_text in SkDraw.cpp and then tweaked.
benjaminwagnerd936f632016-02-23 10:44:31 -080084static void align_text(SkPaint::GlyphCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000085 const uint16_t* glyphs, size_t len,
86 SkScalar* x, SkScalar* y) {
87 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000088 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000089 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000090
91 SkMatrix ident;
92 ident.reset();
halcanary96fcdcc2015-08-27 07:41:13 -070093 SkAutoGlyphCache autoCache(paint, nullptr, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000094 SkGlyphCache* cache = autoCache.getCache();
95
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000096 const char* start = reinterpret_cast<const char*>(glyphs);
97 const char* stop = reinterpret_cast<const char*>(glyphs + len);
benjaminwagner6b3eacb2016-03-24 19:07:58 -070098 SkScalar xAdv = 0, yAdv = 0;
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000099
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000100 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000101 while (start < stop) {
benjaminwagnerd936f632016-02-23 10:44:31 -0800102 const SkGlyph& glyph = glyphCacheProc(cache, &start);
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700103 xAdv += SkFloatToScalar(glyph.fAdvanceX);
104 yAdv += SkFloatToScalar(glyph.fAdvanceY);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000105 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000106 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000107 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000108 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000109
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000110 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700111 xAdv = SkScalarHalf(xAdv);
112 yAdv = SkScalarHalf(yAdv);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000113 }
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700114 *x = *x - xAdv;
115 *y = *y - yAdv;
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000116}
117
robertphillips@google.coma4662862013-11-21 14:24:16 +0000118static int max_glyphid_for_typeface(SkTypeface* typeface) {
reed@google.comfed86bd2013-03-14 15:04:57 +0000119 SkAutoResolveDefaultTypeface autoResolve(typeface);
120 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000121 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000122}
123
124typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
125
reed@google.comaec40662014-04-18 19:29:07 +0000126static int force_glyph_encoding(const SkPaint& paint, const void* text,
127 size_t len, SkGlyphStorage* storage,
bungeman22edc832014-10-03 07:55:58 -0700128 const uint16_t** glyphIDs) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000129 // Make sure we have a glyph id encoding.
130 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
halcanary96fcdcc2015-08-27 07:41:13 -0700131 int numGlyphs = paint.textToGlyphs(text, len, nullptr);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000132 storage->reset(numGlyphs);
133 paint.textToGlyphs(text, len, storage->get());
134 *glyphIDs = storage->get();
135 return numGlyphs;
136 }
137
138 // For user supplied glyph ids we need to validate them.
139 SkASSERT((len & 1) == 0);
reed@google.comaec40662014-04-18 19:29:07 +0000140 int numGlyphs = SkToInt(len / 2);
bungeman22edc832014-10-03 07:55:58 -0700141 const uint16_t* input = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000142
143 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
reed@google.comaec40662014-04-18 19:29:07 +0000144 int validated;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000145 for (validated = 0; validated < numGlyphs; ++validated) {
146 if (input[validated] > maxGlyphID) {
147 break;
148 }
149 }
150 if (validated >= numGlyphs) {
bungeman22edc832014-10-03 07:55:58 -0700151 *glyphIDs = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000152 return numGlyphs;
153 }
154
155 // Silently drop anything out of range.
156 storage->reset(numGlyphs);
157 if (validated > 0) {
158 memcpy(storage->get(), input, validated * sizeof(uint16_t));
159 }
160
reed@google.comaec40662014-04-18 19:29:07 +0000161 for (int i = validated; i < numGlyphs; ++i) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000162 storage->get()[i] = input[i];
163 if (input[i] > maxGlyphID) {
164 storage->get()[i] = 0;
165 }
166 }
167 *glyphIDs = storage->get();
168 return numGlyphs;
169}
170
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000171static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
172 SkWStream* content) {
173 // Flip the text about the x-axis to account for origin swap and include
174 // the passed parameters.
175 content->writeText("1 0 ");
halcanarybc4696b2015-05-06 10:56:04 -0700176 SkPDFUtils::AppendScalar(0 - textSkewX, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000177 content->writeText(" -1 ");
halcanarybc4696b2015-05-06 10:56:04 -0700178 SkPDFUtils::AppendScalar(x, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000179 content->writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -0700180 SkPDFUtils::AppendScalar(y, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000181 content->writeText(" Tm\n");
182}
183
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000184// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
185// later being our representation of an object in the PDF file.
186struct GraphicStateEntry {
187 GraphicStateEntry();
188
189 // Compare the fields we care about when setting up a new content entry.
190 bool compareInitialState(const GraphicStateEntry& b);
191
192 SkMatrix fMatrix;
193 // We can't do set operations on Paths, though PDF natively supports
194 // intersect. If the clip stack does anything other than intersect,
195 // we have to fall back to the region. Treat fClipStack as authoritative.
196 // See http://code.google.com/p/skia/issues/detail?id=221
197 SkClipStack fClipStack;
198 SkRegion fClipRegion;
199
200 // When emitting the content entry, we will ensure the graphic state
201 // is set to these values first.
202 SkColor fColor;
203 SkScalar fTextScaleX; // Zero means we don't care what the value is.
204 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
205 int fShaderIndex;
206 int fGraphicStateIndex;
207
208 // We may change the font (i.e. for Type1 support) within a
halcanary96fcdcc2015-08-27 07:41:13 -0700209 // ContentEntry. This is the one currently in effect, or nullptr if none.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000210 SkPDFFont* fFont;
211 // In PDF, text size has no default value. It is only valid if fFont is
halcanary96fcdcc2015-08-27 07:41:13 -0700212 // not nullptr.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000213 SkScalar fTextSize;
214};
215
216GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
217 fTextScaleX(SK_Scalar1),
218 fTextFill(SkPaint::kFill_Style),
219 fShaderIndex(-1),
220 fGraphicStateIndex(-1),
halcanary96fcdcc2015-08-27 07:41:13 -0700221 fFont(nullptr),
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000222 fTextSize(SK_ScalarNaN) {
223 fMatrix.reset();
224}
225
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000226bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
227 return fColor == cur.fColor &&
228 fShaderIndex == cur.fShaderIndex &&
229 fGraphicStateIndex == cur.fGraphicStateIndex &&
230 fMatrix == cur.fMatrix &&
231 fClipStack == cur.fClipStack &&
232 (fTextScaleX == 0 ||
233 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000234}
235
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000236class GraphicStackState {
237public:
238 GraphicStackState(const SkClipStack& existingClipStack,
239 const SkRegion& existingClipRegion,
240 SkWStream* contentStream)
241 : fStackDepth(0),
242 fContentStream(contentStream) {
243 fEntries[0].fClipStack = existingClipStack;
244 fEntries[0].fClipRegion = existingClipRegion;
245 }
246
247 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000248 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000249 void updateMatrix(const SkMatrix& matrix);
250 void updateDrawingState(const GraphicStateEntry& state);
251
252 void drainStack();
253
254private:
255 void push();
256 void pop();
257 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
258
259 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
260 static const int kMaxStackDepth = 12;
261 GraphicStateEntry fEntries[kMaxStackDepth + 1];
262 int fStackDepth;
263 SkWStream* fContentStream;
264};
265
266void GraphicStackState::drainStack() {
267 while (fStackDepth) {
268 pop();
269 }
270}
271
272void GraphicStackState::push() {
273 SkASSERT(fStackDepth < kMaxStackDepth);
274 fContentStream->writeText("q\n");
275 fStackDepth++;
276 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
277}
278
279void GraphicStackState::pop() {
280 SkASSERT(fStackDepth > 0);
281 fContentStream->writeText("Q\n");
282 fStackDepth--;
283}
284
robertphillips@google.com80214e22012-07-20 15:33:18 +0000285// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000286// and then skips over the leading entries as specified in prefix. It requires
287// and asserts that "prefix" will be a prefix to "stack."
288static void skip_clip_stack_prefix(const SkClipStack& prefix,
289 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000290 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000291 SkClipStack::B2TIter prefixIter(prefix);
292 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000293
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000294 const SkClipStack::Element* prefixEntry;
295 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000296
297 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000298 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000299 iterEntry = iter->next();
300 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000301 // Because of SkClipStack does internal intersection, the last clip
302 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000303 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000304 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
305 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
306 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000307 // back up the iterator by one
308 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000309 prefixEntry = prefixIter.next();
310 break;
311 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000312 }
313
halcanary96fcdcc2015-08-27 07:41:13 -0700314 SkASSERT(prefixEntry == nullptr);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000315}
316
317static void emit_clip(SkPath* clipPath, SkRect* clipRect,
318 SkWStream* contentStream) {
319 SkASSERT(clipPath || clipRect);
320
321 SkPath::FillType clipFill;
322 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000323 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000324 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000325 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000326 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
327 clipFill = SkPath::kWinding_FillType;
328 }
329
330 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
331 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
332 if (clipFill == SkPath::kEvenOdd_FillType) {
333 contentStream->writeText("W* n\n");
334 } else {
335 contentStream->writeText("W n\n");
336 }
337}
338
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000339/* Calculate an inverted path's equivalent non-inverted path, given the
340 * canvas bounds.
341 * outPath may alias with invPath (since this is supported by PathOps).
342 */
343static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
344 SkPath* outPath) {
345 SkASSERT(invPath.isInverseFillType());
346
347 SkPath clipPath;
348 clipPath.addRect(bounds);
349
reedcdb42bb2015-06-26 10:23:07 -0700350 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000351}
352
fmalita632e92f2015-04-22 15:02:03 -0700353#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000354// Sanity check the numerical values of the SkRegion ops and PathOps ops
355// enums so region_op_to_pathops_op can do a straight passthrough cast.
356// If these are failing, it may be necessary to make region_op_to_pathops_op
357// do more.
bungeman99fe8222015-08-20 07:57:51 -0700358static_assert(SkRegion::kDifference_Op == (int)kDifference_SkPathOp, "region_pathop_mismatch");
359static_assert(SkRegion::kIntersect_Op == (int)kIntersect_SkPathOp, "region_pathop_mismatch");
360static_assert(SkRegion::kUnion_Op == (int)kUnion_SkPathOp, "region_pathop_mismatch");
361static_assert(SkRegion::kXOR_Op == (int)kXOR_SkPathOp, "region_pathop_mismatch");
362static_assert(SkRegion::kReverseDifference_Op == (int)kReverseDifference_SkPathOp,
363 "region_pathop_mismatch");
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000364
365static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
366 SkASSERT(op >= 0);
367 SkASSERT(op <= SkRegion::kReverseDifference_Op);
368 return (SkPathOp)op;
369}
370
371/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
372 * Returns true if successful, or false if not successful.
373 * If successful, the resulting clip is stored in outClipPath.
374 * If not successful, outClipPath is undefined, and a fallback method
375 * should be used.
376 */
377static bool get_clip_stack_path(const SkMatrix& transform,
378 const SkClipStack& clipStack,
379 const SkRegion& clipRegion,
380 SkPath* outClipPath) {
381 outClipPath->reset();
382 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
383
384 const SkClipStack::Element* clipEntry;
385 SkClipStack::Iter iter;
386 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
387 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
388 SkPath entryPath;
389 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
390 outClipPath->reset();
391 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
392 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000393 } else {
394 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000395 }
396 entryPath.transform(transform);
397
398 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
399 *outClipPath = entryPath;
400 } else {
401 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
402 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
403 return false;
404 }
405 }
406 }
407
408 if (outClipPath->isInverseFillType()) {
409 // The bounds are slightly outset to ensure this is correct in the
410 // face of floating-point accuracy and possible SkRegion bitmap
411 // approximations.
412 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
413 clipBounds.outset(SK_Scalar1, SK_Scalar1);
414 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
415 return false;
416 }
417 }
418 return true;
419}
420#endif
421
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000422// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000423// graphic state stack, and the fact that we can know all the clips used
424// on the page to optimize this.
425void GraphicStackState::updateClip(const SkClipStack& clipStack,
426 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000427 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000428 if (clipStack == currentEntry()->fClipStack) {
429 return;
430 }
431
432 while (fStackDepth > 0) {
433 pop();
434 if (clipStack == currentEntry()->fClipStack) {
435 return;
436 }
437 }
438 push();
439
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000440 currentEntry()->fClipStack = clipStack;
441 currentEntry()->fClipRegion = clipRegion;
442
443 SkMatrix transform;
444 transform.setTranslate(translation.fX, translation.fY);
445
fmalita632e92f2015-04-22 15:02:03 -0700446#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000447 SkPath clipPath;
448 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700449 emit_clip(&clipPath, nullptr, fContentStream);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000450 return;
451 }
452#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000453 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
454 // already been applied. (If this is a top level device, then it specifies
455 // a clip to the content area. If this is a layer, then it specifies
456 // the clip in effect when the layer was created.) There's no need to
457 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
458 // initial clip on the parent layer. (This means there's a bug if the user
459 // expands the clip and then uses any xfer mode that uses dst:
460 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000461 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000462 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
463
464 // If the clip stack does anything other than intersect or if it uses
465 // an inverse fill type, we have to fall back to the clip region.
466 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000467 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000468 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000469 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
470 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000471 needRegion = true;
472 break;
473 }
474 }
475
476 if (needRegion) {
477 SkPath clipPath;
478 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
halcanary96fcdcc2015-08-27 07:41:13 -0700479 emit_clip(&clipPath, nullptr, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000480 } else {
481 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000482 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000483 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000484 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
485 switch (clipEntry->getType()) {
486 case SkClipStack::Element::kRect_Type: {
487 SkRect translatedClip;
488 transform.mapRect(&translatedClip, clipEntry->getRect());
halcanary96fcdcc2015-08-27 07:41:13 -0700489 emit_clip(nullptr, &translatedClip, fContentStream);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000490 break;
491 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000492 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000493 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000494 clipEntry->asPath(&translatedPath);
495 translatedPath.transform(transform, &translatedPath);
halcanary96fcdcc2015-08-27 07:41:13 -0700496 emit_clip(&translatedPath, nullptr, fContentStream);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000497 break;
498 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000499 }
500 }
501 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000502}
503
504void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
505 if (matrix == currentEntry()->fMatrix) {
506 return;
507 }
508
509 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
510 SkASSERT(fStackDepth > 0);
511 SkASSERT(fEntries[fStackDepth].fClipStack ==
512 fEntries[fStackDepth -1].fClipStack);
513 pop();
514
515 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
516 }
517 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
518 return;
519 }
520
521 push();
522 SkPDFUtils::AppendTransform(matrix, fContentStream);
523 currentEntry()->fMatrix = matrix;
524}
525
526void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
527 // PDF treats a shader as a color, so we only set one or the other.
528 if (state.fShaderIndex >= 0) {
529 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000530 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000531 currentEntry()->fShaderIndex = state.fShaderIndex;
532 }
533 } else {
534 if (state.fColor != currentEntry()->fColor ||
535 currentEntry()->fShaderIndex >= 0) {
536 emit_pdf_color(state.fColor, fContentStream);
537 fContentStream->writeText("RG ");
538 emit_pdf_color(state.fColor, fContentStream);
539 fContentStream->writeText("rg\n");
540 currentEntry()->fColor = state.fColor;
541 currentEntry()->fShaderIndex = -1;
542 }
543 }
544
545 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000546 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000547 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
548 }
549
550 if (state.fTextScaleX) {
551 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
552 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
553 SkIntToScalar(100));
halcanarybc4696b2015-05-06 10:56:04 -0700554 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000555 fContentStream->writeText(" Tz\n");
556 currentEntry()->fTextScaleX = state.fTextScaleX;
557 }
558 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700559 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
560 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
561 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000562 fContentStream->writeDecAsText(state.fTextFill);
563 fContentStream->writeText(" Tr\n");
564 currentEntry()->fTextFill = state.fTextFill;
565 }
566 }
567}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000568
reed76033be2015-03-14 10:54:31 -0700569static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700570 // PDF does not support image filters, so render them on CPU.
571 // Note that this rendering is done at "screen" resolution (100dpi), not
572 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700573 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800574 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700575
576 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700577 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700578}
579
580SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
halcanary00b7e5e2015-04-15 13:05:18 -0700581 if (cinfo.fForImageFilter ||
582 (layerPaint && not_supported_for_layers(*layerPaint))) {
halcanary96fcdcc2015-08-27 07:41:13 -0700583 return nullptr;
senorblancob0e89dc2014-10-20 14:03:12 -0700584 }
fmalita6987dca2014-11-13 08:33:37 -0800585 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanary989da4a2016-03-21 14:33:17 -0700586 return SkPDFDevice::Create(size, fRasterDpi, fDocument);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000587}
588
halcanary989da4a2016-03-21 14:33:17 -0700589SkPDFCanon* SkPDFDevice::getCanon() const { return fDocument->canon(); }
590
bsalomon@google.come97f0852011-06-17 13:10:25 +0000591
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000592struct ContentEntry {
593 GraphicStateEntry fState;
594 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000595 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000596
597 // If the stack is too deep we could get Stack Overflow.
598 // So we manually destruct the object.
599 ~ContentEntry() {
mtklein18300a32016-03-16 13:53:35 -0700600 ContentEntry* val = fNext.release();
halcanary96fcdcc2015-08-27 07:41:13 -0700601 while (val != nullptr) {
mtklein18300a32016-03-16 13:53:35 -0700602 ContentEntry* valNext = val->fNext.release();
halcanary96fcdcc2015-08-27 07:41:13 -0700603 // When the destructor is called, fNext is nullptr and exits.
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000604 delete val;
605 val = valNext;
606 }
607 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000608};
609
610// A helper class to automatically finish a ContentEntry at the end of a
611// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000612class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000613public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000614 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
615 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000616 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700617 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000618 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700619 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000620 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
621 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000622 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
623 const SkRegion& clipRegion, const SkMatrix& matrix,
624 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000625 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700626 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000627 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700628 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000629 init(clipStack, clipRegion, matrix, paint, hasText);
630 }
631
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000632 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000633 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000634 SkPath* shape = &fShape;
635 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700636 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000637 }
638 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000639 }
reed@google.comfc641d02012-09-20 17:52:20 +0000640 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000641 }
642
643 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000644
645 /* Returns true when we explicitly need the shape of the drawing. */
646 bool needShape() {
647 switch (fXfermode) {
648 case SkXfermode::kClear_Mode:
649 case SkXfermode::kSrc_Mode:
650 case SkXfermode::kSrcIn_Mode:
651 case SkXfermode::kSrcOut_Mode:
652 case SkXfermode::kDstIn_Mode:
653 case SkXfermode::kDstOut_Mode:
654 case SkXfermode::kSrcATop_Mode:
655 case SkXfermode::kDstATop_Mode:
656 case SkXfermode::kModulate_Mode:
657 return true;
658 default:
659 return false;
660 }
661 }
662
663 /* Returns true unless we only need the shape of the drawing. */
664 bool needSource() {
665 if (fXfermode == SkXfermode::kClear_Mode) {
666 return false;
667 }
668 return true;
669 }
670
671 /* If the shape is different than the alpha component of the content, then
672 * setShape should be called with the shape. In particular, images and
673 * devices have rectangular shape.
674 */
675 void setShape(const SkPath& shape) {
676 fShape = shape;
677 }
678
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000679private:
680 SkPDFDevice* fDevice;
681 ContentEntry* fContentEntry;
682 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000683 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000684 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000685
686 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
687 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000688 // Shape has to be flatten before we get here.
689 if (matrix.hasPerspective()) {
690 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000691 return;
692 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000693 if (paint.getXfermode()) {
694 paint.getXfermode()->asMode(&fXfermode);
695 }
696 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
697 matrix, paint, hasText,
698 &fDstFormXObject);
699 }
700};
701
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000702////////////////////////////////////////////////////////////////////////////////
703
halcanary989da4a2016-03-21 14:33:17 -0700704SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFDocument* doc, bool flip)
robertphillips9a53fd72015-06-22 09:46:59 -0700705 : INHERITED(SkSurfaceProps(0, kUnknown_SkPixelGeometry))
706 , fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800707 , fContentSize(pageSize)
708 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
halcanary96fcdcc2015-08-27 07:41:13 -0700709 , fLastContentEntry(nullptr)
710 , fLastMarginContentEntry(nullptr)
halcanarya1f1ee92015-02-20 06:17:26 -0800711 , fDrawingArea(kContent_DrawingArea)
halcanary96fcdcc2015-08-27 07:41:13 -0700712 , fClipStack(nullptr)
halcanary385fe4d2015-08-26 13:07:48 -0700713 , fFontGlyphUsage(new SkPDFGlyphSetMap)
halcanarya1f1ee92015-02-20 06:17:26 -0800714 , fRasterDpi(rasterDpi)
halcanary989da4a2016-03-21 14:33:17 -0700715 , fDocument(doc) {
halcanarya1f1ee92015-02-20 06:17:26 -0800716 SkASSERT(pageSize.width() > 0);
717 SkASSERT(pageSize.height() > 0);
718 fLegacyBitmap.setInfo(
719 SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()));
720 if (flip) {
721 // Skia generally uses the top left as the origin but PDF
722 // natively has the origin at the bottom left. This matrix
723 // corrects for that. But that only needs to be done once, we
724 // don't do it when layering.
725 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
726 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
727 } else {
728 fInitialTransform.setIdentity();
729 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000730}
731
732SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000733 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000734}
735
736void SkPDFDevice::init() {
mtklein852f15d2016-03-17 10:51:27 -0700737 fContentEntries.reset();
halcanary96fcdcc2015-08-27 07:41:13 -0700738 fLastContentEntry = nullptr;
mtklein852f15d2016-03-17 10:51:27 -0700739 fMarginContentEntries.reset();
halcanary96fcdcc2015-08-27 07:41:13 -0700740 fLastMarginContentEntry = nullptr;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000741 fDrawingArea = kContent_DrawingArea;
halcanary96fcdcc2015-08-27 07:41:13 -0700742 if (fFontGlyphUsage.get() == nullptr) {
halcanary385fe4d2015-08-26 13:07:48 -0700743 fFontGlyphUsage.reset(new SkPDFGlyphSetMap);
vandebo@chromium.org98594282011-07-25 22:34:12 +0000744 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000745}
746
vandebo@chromium.org98594282011-07-25 22:34:12 +0000747void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000748 fGraphicStateResources.unrefAll();
749 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000750 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000751 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000752
vandebo@chromium.org98594282011-07-25 22:34:12 +0000753 if (clearFontUsage) {
754 fFontGlyphUsage->reset();
755 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000756}
757
reedf70b5312016-03-04 16:36:20 -0800758void SkPDFDevice::drawAnnotation(const SkDraw& d, const SkRect& rect, const char key[],
759 SkData* value) {
760 if (0 == rect.width() && 0 == rect.height()) {
761 handlePointAnnotation({ rect.x(), rect.y() }, *d.fMatrix, key, value);
762 } else {
763 SkPath path;
764 path.addRect(rect);
765 handlePathAnnotation(path, d, key, value);
766 }
767}
768
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000769void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000770 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700771 replace_srcmode_on_opaque_paint(&newPaint);
772
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000773 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000774 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000775 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000776}
777
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000778void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
779 ContentEntry* contentEntry) {
780 if (!contentEntry) {
781 return;
782 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000783 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
784 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000785 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000786 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000787 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000788 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000789 inverse.mapRect(&bbox);
790
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000791 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000792 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000793 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000794}
795
halcanary682ee012016-01-28 10:59:34 -0800796void SkPDFDevice::drawPoints(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700797 SkCanvas::PointMode mode,
798 size_t count,
799 const SkPoint* points,
800 const SkPaint& srcPaint) {
801 SkPaint passedPaint = srcPaint;
802 replace_srcmode_on_opaque_paint(&passedPaint);
803
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000804 if (count == 0) {
805 return;
806 }
807
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000808 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
809 // We only use this when there's a path effect because of the overhead
810 // of multiple calls to setUpContentEntry it causes.
811 if (passedPaint.getPathEffect()) {
812 if (d.fClip->isEmpty()) {
813 return;
814 }
815 SkDraw pointDraw(d);
816 pointDraw.fDevice = this;
817 pointDraw.drawPoints(mode, count, points, passedPaint, true);
818 return;
819 }
820
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000821 const SkPaint* paint = &passedPaint;
822 SkPaint modifiedPaint;
823
824 if (mode == SkCanvas::kPoints_PointMode &&
825 paint->getStrokeCap() != SkPaint::kRound_Cap) {
826 modifiedPaint = *paint;
827 paint = &modifiedPaint;
828 if (paint->getStrokeWidth()) {
829 // PDF won't draw a single point with square/butt caps because the
830 // orientation is ambiguous. Draw a rectangle instead.
831 modifiedPaint.setStyle(SkPaint::kFill_Style);
832 SkScalar strokeWidth = paint->getStrokeWidth();
833 SkScalar halfStroke = SkScalarHalf(strokeWidth);
834 for (size_t i = 0; i < count; i++) {
835 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
836 r.inset(-halfStroke, -halfStroke);
837 drawRect(d, r, modifiedPaint);
838 }
839 return;
840 } else {
841 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
842 }
843 }
844
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000845 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000846 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000847 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000848 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000849
850 switch (mode) {
851 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000852 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000853 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000854 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000855 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000856 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000857 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000858 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000859 break;
860 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000861 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000862 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000863 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000864 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000865 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000866 &content.entry()->fContent);
867 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000868 }
869 break;
870 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000871 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
872 for (size_t i = 0; i < count; i++) {
873 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000874 &content.entry()->fContent);
875 SkPDFUtils::ClosePath(&content.entry()->fContent);
876 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000877 }
878 break;
879 default:
880 SkASSERT(false);
881 }
882}
883
halcanary8103a342016-03-08 15:10:16 -0800884static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800885 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700886 annotation->insertName("Subtype", "Link");
887
halcanaryece83922016-03-08 08:32:12 -0800888 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700889 border->reserve(3);
890 border->appendInt(0); // Horizontal corner radius.
891 border->appendInt(0); // Vertical corner radius.
892 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800893 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700894
halcanaryece83922016-03-08 08:32:12 -0800895 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700896 rect->reserve(4);
897 rect->appendScalar(translatedRect.fLeft);
898 rect->appendScalar(translatedRect.fTop);
899 rect->appendScalar(translatedRect.fRight);
900 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800901 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700902
halcanary8103a342016-03-08 15:10:16 -0800903 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700904}
905
halcanary8103a342016-03-08 15:10:16 -0800906static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
907 auto annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700908 SkString url(static_cast<const char *>(urlData->data()),
909 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800910 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700911 action->insertName("S", "URI");
912 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800913 annotation->insertObject("A", std::move(action));
914 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700915}
916
halcanary8103a342016-03-08 15:10:16 -0800917static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
918 const SkRect& r) {
919 auto annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700920 SkString name(static_cast<const char *>(nameData->data()),
921 nameData->size() - 1);
922 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800923 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700924}
925
halcanary682ee012016-01-28 10:59:34 -0800926void SkPDFDevice::drawRect(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700927 const SkRect& rect,
928 const SkPaint& srcPaint) {
929 SkPaint paint = srcPaint;
930 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000931 SkRect r = rect;
932 r.sort();
933
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000934 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000935 if (d.fClip->isEmpty()) {
936 return;
937 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000938 SkPath path;
939 path.addRect(r);
halcanary96fcdcc2015-08-27 07:41:13 -0700940 drawPath(d, path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000941 return;
942 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000943
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000944 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000945 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000946 return;
947 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000948 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000949 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000950 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000951}
952
halcanarya6814332015-05-27 08:53:36 -0700953void SkPDFDevice::drawRRect(const SkDraw& draw,
954 const SkRRect& rrect,
955 const SkPaint& srcPaint) {
956 SkPaint paint = srcPaint;
957 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000958 SkPath path;
959 path.addRRect(rrect);
halcanary96fcdcc2015-08-27 07:41:13 -0700960 this->drawPath(draw, path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000961}
962
halcanarya6814332015-05-27 08:53:36 -0700963void SkPDFDevice::drawOval(const SkDraw& draw,
964 const SkRect& oval,
965 const SkPaint& srcPaint) {
966 SkPaint paint = srcPaint;
967 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700968 SkPath path;
969 path.addOval(oval);
halcanary96fcdcc2015-08-27 07:41:13 -0700970 this->drawPath(draw, path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700971}
972
halcanary682ee012016-01-28 10:59:34 -0800973void SkPDFDevice::drawPath(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700974 const SkPath& origPath,
975 const SkPaint& srcPaint,
976 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000977 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700978 SkPaint paint = srcPaint;
979 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800980 SkPath modifiedPath;
981 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000982
983 SkMatrix matrix = *d.fMatrix;
984 if (prePathMatrix) {
985 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800986 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000987 pathPtr = &modifiedPath;
988 pathIsMutable = true;
989 }
halcanary682ee012016-01-28 10:59:34 -0800990 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000991 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000992 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000993 }
994 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000995
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000996 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000997 if (d.fClip->isEmpty()) {
998 return;
999 }
halcanary682ee012016-01-28 10:59:34 -08001000 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001001 pathPtr = &modifiedPath;
1002 pathIsMutable = true;
1003 }
halcanary682ee012016-01-28 10:59:34 -08001004 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001005
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001006 SkPaint noEffectPaint(paint);
halcanary96fcdcc2015-08-27 07:41:13 -07001007 noEffectPaint.setPathEffect(nullptr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001008 if (fill) {
1009 noEffectPaint.setStyle(SkPaint::kFill_Style);
1010 } else {
1011 noEffectPaint.setStyle(SkPaint::kStroke_Style);
1012 noEffectPaint.setStrokeWidth(0);
1013 }
halcanary96fcdcc2015-08-27 07:41:13 -07001014 drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001015 return;
1016 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001017
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001018 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001019 return;
1020 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001021
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001022 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001023 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001024 return;
1025 }
halcanary8b2bc252015-10-06 09:41:47 -07001026 bool consumeDegeratePathSegments =
1027 paint.getStyle() == SkPaint::kFill_Style ||
1028 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
1029 paint.getStrokeCap() != SkPaint::kSquare_Cap);
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001030 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
halcanary8b2bc252015-10-06 09:41:47 -07001031 consumeDegeratePathSegments,
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001032 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001033 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001034 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001035}
1036
halcanary7a14b312015-10-01 07:28:13 -07001037void SkPDFDevice::drawBitmapRect(const SkDraw& draw,
1038 const SkBitmap& bitmap,
1039 const SkRect* src,
1040 const SkRect& dst,
1041 const SkPaint& srcPaint,
1042 SkCanvas::SrcRectConstraint constraint) {
halcanary66be6262016-03-21 13:01:34 -07001043 SkASSERT(false);
halcanary7a14b312015-10-01 07:28:13 -07001044}
1045
1046void SkPDFDevice::drawBitmap(const SkDraw& d,
1047 const SkBitmap& bitmap,
1048 const SkMatrix& matrix,
1049 const SkPaint& srcPaint) {
halcanarya6814332015-05-27 08:53:36 -07001050 SkPaint paint = srcPaint;
1051 if (bitmap.isOpaque()) {
1052 replace_srcmode_on_opaque_paint(&paint);
1053 }
1054
halcanary7a14b312015-10-01 07:28:13 -07001055 if (d.fClip->isEmpty()) {
1056 return;
1057 }
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001058
halcanary7a14b312015-10-01 07:28:13 -07001059 SkMatrix transform = matrix;
1060 transform.postConcat(*d.fMatrix);
halcanary989da4a2016-03-21 14:33:17 -07001061 const SkImage* image = fDocument->canon()->bitmapToImage(bitmap);
halcanary7a14b312015-10-01 07:28:13 -07001062 if (!image) {
1063 return;
1064 }
1065 this->internalDrawImage(transform, d.fClipStack, *d.fClip, image, nullptr,
1066 paint);
1067}
1068
1069void SkPDFDevice::drawSprite(const SkDraw& d,
1070 const SkBitmap& bitmap,
1071 int x,
1072 int y,
1073 const SkPaint& srcPaint) {
1074 SkPaint paint = srcPaint;
1075 if (bitmap.isOpaque()) {
1076 replace_srcmode_on_opaque_paint(&paint);
1077 }
1078
1079 if (d.fClip->isEmpty()) {
1080 return;
1081 }
1082
1083 SkMatrix matrix;
1084 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
halcanary989da4a2016-03-21 14:33:17 -07001085 const SkImage* image = fDocument->canon()->bitmapToImage(bitmap);
halcanary7a14b312015-10-01 07:28:13 -07001086 if (!image) {
1087 return;
1088 }
1089 this->internalDrawImage(matrix, d.fClipStack, *d.fClip, image, nullptr,
1090 paint);
1091}
1092
1093void SkPDFDevice::drawImage(const SkDraw& draw,
1094 const SkImage* image,
1095 SkScalar x,
1096 SkScalar y,
1097 const SkPaint& srcPaint) {
1098 SkPaint paint = srcPaint;
1099 if (!image) {
1100 return;
1101 }
1102 if (image->isOpaque()) {
1103 replace_srcmode_on_opaque_paint(&paint);
1104 }
1105 if (draw.fClip->isEmpty()) {
1106 return;
1107 }
1108 SkMatrix transform = SkMatrix::MakeTrans(x, y);
1109 transform.postConcat(*draw.fMatrix);
1110 this->internalDrawImage(transform, draw.fClipStack, *draw.fClip, image,
1111 nullptr, paint);
1112}
1113
1114void SkPDFDevice::drawImageRect(const SkDraw& draw,
1115 const SkImage* image,
1116 const SkRect* src,
1117 const SkRect& dst,
1118 const SkPaint& srcPaint,
1119 SkCanvas::SrcRectConstraint constraint) {
halcanary66be6262016-03-21 13:01:34 -07001120 SkASSERT(false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001121}
1122
halcanarybb264b72015-04-07 10:40:03 -07001123// Create a PDF string. Maximum length (in bytes) is 65,535.
1124// @param input A string value.
1125// @param len The length of the input array.
1126// @param wideChars True iff the upper byte in each uint16_t is
1127// significant and should be encoded and not
1128// discarded. If true, the upper byte is encoded
1129// first. Otherwise, we assert the upper byte is
1130// zero.
1131static SkString format_wide_string(const uint16_t* input,
1132 size_t len,
1133 bool wideChars) {
1134 if (wideChars) {
1135 SkASSERT(2 * len < 65535);
1136 static const char gHex[] = "0123456789ABCDEF";
1137 SkString result(4 * len + 2);
1138 result[0] = '<';
1139 for (size_t i = 0; i < len; i++) {
1140 result[4 * i + 1] = gHex[(input[i] >> 12) & 0xF];
1141 result[4 * i + 2] = gHex[(input[i] >> 8) & 0xF];
1142 result[4 * i + 3] = gHex[(input[i] >> 4) & 0xF];
1143 result[4 * i + 4] = gHex[(input[i] ) & 0xF];
1144 }
1145 result[4 * len + 1] = '>';
1146 return result;
1147 } else {
1148 SkASSERT(len <= 65535);
1149 SkString tmp(len);
1150 for (size_t i = 0; i < len; i++) {
1151 SkASSERT(0 == input[i] >> 8);
1152 tmp[i] = static_cast<uint8_t>(input[i]);
1153 }
halcanarybc4696b2015-05-06 10:56:04 -07001154 return SkPDFUtils::FormatString(tmp.c_str(), tmp.size());
halcanarybb264b72015-04-07 10:40:03 -07001155 }
1156}
1157
halcanary66a82f32015-10-12 13:05:04 -07001158static void draw_transparent_text(SkPDFDevice* device,
1159 const SkDraw& d,
1160 const void* text, size_t len,
1161 SkScalar x, SkScalar y,
1162 const SkPaint& srcPaint) {
1163
1164 SkPaint transparent;
1165 if (!SkPDFFont::CanEmbedTypeface(transparent.getTypeface(),
1166 device->getCanon())) {
1167 SkDEBUGFAIL("default typeface should be embeddable");
1168 return; // Avoid infinite loop in release.
1169 }
1170 transparent.setTextSize(srcPaint.getTextSize());
1171 transparent.setColor(SK_ColorTRANSPARENT);
1172 switch (srcPaint.getTextEncoding()) {
1173 case SkPaint::kGlyphID_TextEncoding: {
1174 // Since a glyphId<->Unicode mapping is typeface-specific,
1175 // map back to Unicode first.
1176 size_t glyphCount = len / 2;
1177 SkAutoTMalloc<SkUnichar> unichars(glyphCount);
1178 srcPaint.glyphsToUnichars(
1179 (const uint16_t*)text, SkToInt(glyphCount), &unichars[0]);
1180 transparent.setTextEncoding(SkPaint::kUTF32_TextEncoding);
1181 device->drawText(d, &unichars[0],
1182 glyphCount * sizeof(SkUnichar),
1183 x, y, transparent);
1184 break;
1185 }
1186 case SkPaint::kUTF8_TextEncoding:
1187 case SkPaint::kUTF16_TextEncoding:
1188 case SkPaint::kUTF32_TextEncoding:
1189 transparent.setTextEncoding(srcPaint.getTextEncoding());
1190 device->drawText(d, text, len, x, y, transparent);
1191 break;
1192 default:
1193 SkFAIL("unknown text encoding");
1194 }
1195}
1196
1197
halcanary682ee012016-01-28 10:59:34 -08001198void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
halcanarya6814332015-05-27 08:53:36 -07001199 SkScalar x, SkScalar y, const SkPaint& srcPaint) {
halcanary989da4a2016-03-21 14:33:17 -07001200 if (!SkPDFFont::CanEmbedTypeface(srcPaint.getTypeface(), fDocument->canon())) {
halcanary6950de62015-11-07 05:29:00 -08001201 // https://bug.skia.org/3866
halcanary66a82f32015-10-12 13:05:04 -07001202 SkPath path;
1203 srcPaint.getTextPath(text, len, x, y, &path);
1204 this->drawPath(d, path, srcPaint, &SkMatrix::I(), true);
1205 // Draw text transparently to make it copyable/searchable/accessable.
1206 draw_transparent_text(this, d, text, len, x, y, srcPaint);
1207 return;
1208 }
halcanarya6814332015-05-27 08:53:36 -07001209 SkPaint paint = srcPaint;
1210 replace_srcmode_on_opaque_paint(&paint);
1211
halcanary96fcdcc2015-08-27 07:41:13 -07001212 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1213 if (paint.getMaskFilter() != nullptr) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001214 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1215 // making text unreadable (e.g. same text twice when using CSS shadows).
1216 return;
1217 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001218 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001219 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001220 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001221 return;
1222 }
1223
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001224 SkGlyphStorage storage(0);
halcanary96fcdcc2015-08-27 07:41:13 -07001225 const uint16_t* glyphIDs = nullptr;
reed@google.comaec40662014-04-18 19:29:07 +00001226 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001227 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001228
benjaminwagnerd936f632016-02-23 10:44:31 -08001229 SkPaint::GlyphCacheProc glyphCacheProc = textPaint.getGlyphCacheProc(true);
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001230 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001231 content.entry()->fContent.writeText("BT\n");
1232 set_text_transform(x, y, textPaint.getTextSkewX(),
1233 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001234 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001235
1236 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1237
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001238 while (numGlyphs > consumedGlyphCount) {
robertphillips8e0c1502015-07-07 10:28:43 -07001239 this->updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001240 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001241
1242 int availableGlyphs = font->glyphsToPDFFontEncoding(
1243 glyphIDsCopy.begin() + consumedGlyphCount,
1244 numGlyphs - consumedGlyphCount);
1245 fFontGlyphUsage->noteGlyphUsage(
1246 font, glyphIDsCopy.begin() + consumedGlyphCount,
1247 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001248 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001249 format_wide_string(glyphIDsCopy.begin() + consumedGlyphCount,
1250 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001251 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001252 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001253 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001254 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001255 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001256}
1257
halcanary682ee012016-01-28 10:59:34 -08001258void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001259 const SkScalar pos[], int scalarsPerPos,
halcanary682ee012016-01-28 10:59:34 -08001260 const SkPoint& offset, const SkPaint& srcPaint) {
halcanary989da4a2016-03-21 14:33:17 -07001261 if (!SkPDFFont::CanEmbedTypeface(srcPaint.getTypeface(), fDocument->canon())) {
halcanary66a82f32015-10-12 13:05:04 -07001262 const SkPoint* positions = reinterpret_cast<const SkPoint*>(pos);
1263 SkAutoTMalloc<SkPoint> positionsBuffer;
1264 if (2 != scalarsPerPos) {
1265 int glyphCount = srcPaint.textToGlyphs(text, len, NULL);
1266 positionsBuffer.reset(glyphCount);
1267 for (int i = 0; i < glyphCount; ++i) {
1268 positionsBuffer[i].set(pos[i], 0.0f);
1269 }
1270 positions = &positionsBuffer[0];
1271 }
1272 SkPath path;
1273 srcPaint.getPosTextPath(text, len, positions, &path);
1274 SkMatrix matrix;
1275 matrix.setTranslate(offset);
1276 this->drawPath(d, path, srcPaint, &matrix, true);
1277 // Draw text transparently to make it copyable/searchable/accessable.
1278 draw_transparent_text(
1279 this, d, text, len, offset.x() + positions[0].x(),
1280 offset.y() + positions[0].y(), srcPaint);
1281 return;
1282 }
1283
halcanarya6814332015-05-27 08:53:36 -07001284 SkPaint paint = srcPaint;
1285 replace_srcmode_on_opaque_paint(&paint);
1286
halcanary96fcdcc2015-08-27 07:41:13 -07001287 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1288 if (paint.getMaskFilter() != nullptr) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001289 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1290 // making text unreadable (e.g. same text twice when using CSS shadows).
1291 return;
1292 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001293 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001294 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001295 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001296 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001297 return;
1298 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001299
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001300 SkGlyphStorage storage(0);
halcanary96fcdcc2015-08-27 07:41:13 -07001301 const uint16_t* glyphIDs = nullptr;
bungeman22edc832014-10-03 07:55:58 -07001302 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001303 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001304
benjaminwagnerd936f632016-02-23 10:44:31 -08001305 SkPaint::GlyphCacheProc glyphCacheProc = textPaint.getGlyphCacheProc(true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001306 content.entry()->fContent.writeText("BT\n");
robertphillips8e0c1502015-07-07 10:28:43 -07001307 this->updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001308 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001309 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001310 uint16_t encodedValue = glyphIDs[i];
1311 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001312 // The current pdf font cannot encode the current glyph.
1313 // Try to get a pdf font which can encode the current glyph.
robertphillips8e0c1502015-07-07 10:28:43 -07001314 this->updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001315 font = content.entry()->fState.fFont;
1316 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1317 SkDEBUGFAIL("PDF could not encode glyph.");
1318 continue;
1319 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001320 }
bungeman22edc832014-10-03 07:55:58 -07001321
vandebo@chromium.org98594282011-07-25 22:34:12 +00001322 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001323 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1324 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1325
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001326 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001327 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001328 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001329 format_wide_string(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001330 content.entry()->fContent.writeText(encodedString.c_str());
1331 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001332 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001333 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001334}
1335
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001336void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001337 int vertexCount, const SkPoint verts[],
1338 const SkPoint texs[], const SkColor colors[],
1339 SkXfermode* xmode, const uint16_t indices[],
1340 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001341 if (d.fClip->isEmpty()) {
1342 return;
1343 }
reed@google.com85e143c2013-12-30 15:51:25 +00001344 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001345}
1346
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001347void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1348 int x, int y, const SkPaint& paint) {
fmalita6987dca2014-11-13 08:33:37 -08001349 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001350 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001351
1352 SkScalar scalarX = SkIntToScalar(x);
1353 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001354 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1355 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001356 fLinkToURLs.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001357 }
halcanary91fcb3e2016-03-04 13:53:22 -08001358 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1359 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001360 fLinkToDestinations.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001361 }
halcanary91fcb3e2016-03-04 13:53:22 -08001362 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1363 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001364 fNamedDestinations.emplace_back(d.nameData.get(), p);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001365 }
1366
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001367 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001368 return;
1369 }
1370
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001371 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001372 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001373 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001374 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001375 return;
1376 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001377 if (content.needShape()) {
1378 SkPath shape;
1379 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001380 SkIntToScalar(device->width()),
1381 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001382 content.setShape(shape);
1383 }
1384 if (!content.needSource()) {
1385 return;
1386 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001387
halcanaryece83922016-03-08 08:32:12 -08001388 auto xObject = sk_make_sp<SkPDFFormXObject>(pdfDevice);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001389 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001390 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001391
1392 // Merge glyph sets from the drawn device.
1393 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001394}
1395
reed89443ab2014-06-27 11:34:19 -07001396SkImageInfo SkPDFDevice::imageInfo() const {
1397 return fLegacyBitmap.info();
1398}
1399
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001400void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1401 INHERITED::onAttachToCanvas(canvas);
1402
1403 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1404 fClipStack = canvas->getClipStack();
1405}
1406
1407void SkPDFDevice::onDetachFromCanvas() {
1408 INHERITED::onDetachFromCanvas();
1409
halcanary96fcdcc2015-08-27 07:41:13 -07001410 fClipStack = nullptr;
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001411}
1412
reede8f30622016-03-23 18:59:25 -07001413sk_sp<SkSurface> SkPDFDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1414 return SkSurface::MakeRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001415}
1416
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001417ContentEntry* SkPDFDevice::getLastContentEntry() {
1418 if (fDrawingArea == kContent_DrawingArea) {
1419 return fLastContentEntry;
1420 } else {
1421 return fLastMarginContentEntry;
1422 }
1423}
1424
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001425SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001426 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001427 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001428 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001429 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001430 }
1431}
1432
1433void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1434 if (fDrawingArea == kContent_DrawingArea) {
1435 fLastContentEntry = contentEntry;
1436 } else {
1437 fLastMarginContentEntry = contentEntry;
1438 }
1439}
1440
1441void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001442 // A ScopedContentEntry only exists during the course of a draw call, so
1443 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001444 fDrawingArea = drawingArea;
1445}
1446
halcanary8103a342016-03-08 15:10:16 -08001447sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001448 SkTDArray<SkPDFObject*> fonts;
1449 fonts.setReserve(fFontResources.count());
1450 for (SkPDFFont* font : fFontResources) {
1451 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001452 }
halcanary8103a342016-03-08 15:10:16 -08001453 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001454 &fGraphicStateResources,
1455 &fShaderResources,
1456 &fXObjectResources,
1457 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001458}
1459
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001460const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1461 return fFontResources;
1462}
1463
halcanary8103a342016-03-08 15:10:16 -08001464sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001465 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001466 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001467 mediaBox->appendInt(0);
1468 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001469 mediaBox->appendInt(fPageSize.width());
1470 mediaBox->appendInt(fPageSize.height());
1471 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001472}
1473
mtklein5f939ab2016-03-16 10:28:35 -07001474std::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001475 SkDynamicMemoryWStream buffer;
1476 this->writeContent(&buffer);
mtklein5f939ab2016-03-16 10:28:35 -07001477 return std::unique_ptr<SkStreamAsset>(
halcanary8103a342016-03-08 15:10:16 -08001478 buffer.bytesWritten() > 0
1479 ? buffer.detachAsStream()
1480 : new SkMemoryStream);
reed@google.com5667afc2011-06-27 14:42:15 +00001481}
1482
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001483void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1484 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001485 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1486 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001487 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
halcanary96fcdcc2015-08-27 07:41:13 -07001488 while (entry != nullptr) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001489 SkPoint translation;
1490 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001491 translation.negate();
1492 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1493 translation);
1494 gsState.updateMatrix(entry->fState.fMatrix);
1495 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001496
halcanary7af21502015-02-23 12:17:59 -08001497 entry->fContent.writeToStream(data);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001498 entry = entry->fNext.get();
1499 }
1500 gsState.drainStack();
1501}
1502
halcanary334fcbc2015-02-24 12:56:16 -08001503void SkPDFDevice::writeContent(SkWStream* out) const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001504 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanary334fcbc2015-02-24 12:56:16 -08001505 SkPDFUtils::AppendTransform(fInitialTransform, out);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001506 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001507
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001508 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1509 // colors the contentArea white before it starts drawing into it and
1510 // that currently acts as our clip.
1511 // Also, think about adding a transform here (or assume that the values
1512 // sent across account for that)
halcanary334fcbc2015-02-24 12:56:16 -08001513 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), out);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001514
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001515 // If the content area is the entire page, then we don't need to clip
1516 // the content area (PDF area clips to the page size). Otherwise,
1517 // we have to clip to the content area; we've already applied the
1518 // initial transform, so just clip to the device size.
1519 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001520 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1521 SkIntToScalar(this->height()));
halcanary96fcdcc2015-08-27 07:41:13 -07001522 emit_clip(nullptr, &r, out);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001523 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001524
halcanary334fcbc2015-02-24 12:56:16 -08001525 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), out);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001526}
1527
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001528/* Draws an inverse filled path by using Path Ops to compute the positive
1529 * inverse using the current clip as the inverse bounds.
1530 * Return true if this was an inverse path and was properly handled,
1531 * otherwise returns false and the normal drawing routine should continue,
1532 * either as a (incorrect) fallback or because the path was not inverse
1533 * in the first place.
1534 */
1535bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001536 const SkPaint& paint, bool pathIsMutable,
1537 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001538 if (!origPath.isInverseFillType()) {
1539 return false;
1540 }
1541
1542 if (d.fClip->isEmpty()) {
1543 return false;
1544 }
1545
1546 SkPath modifiedPath;
1547 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1548 SkPaint noInversePaint(paint);
1549
1550 // Merge stroking operations into final path.
1551 if (SkPaint::kStroke_Style == paint.getStyle() ||
1552 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1553 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1554 if (doFillPath) {
1555 noInversePaint.setStyle(SkPaint::kFill_Style);
1556 noInversePaint.setStrokeWidth(0);
1557 pathPtr = &modifiedPath;
1558 } else {
1559 // To be consistent with the raster output, hairline strokes
1560 // are rendered as non-inverted.
1561 modifiedPath.toggleInverseFillType();
halcanary96fcdcc2015-08-27 07:41:13 -07001562 drawPath(d, modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001563 return true;
1564 }
1565 }
1566
1567 // Get bounds of clip in current transform space
1568 // (clip bounds are given in device space).
1569 SkRect bounds;
1570 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001571 SkMatrix totalMatrix = *d.fMatrix;
1572 if (prePathMatrix) {
1573 totalMatrix.preConcat(*prePathMatrix);
1574 }
1575 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001576 return false;
1577 }
1578 bounds.set(d.fClip->getBounds());
1579 transformInverse.mapRect(&bounds);
1580
1581 // Extend the bounds by the line width (plus some padding)
1582 // so the edge doesn't cause a visible stroke.
1583 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1584 paint.getStrokeWidth() + SK_Scalar1);
1585
1586 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1587 return false;
1588 }
1589
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001590 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001591 return true;
1592}
1593
reedf70b5312016-03-04 16:36:20 -08001594void SkPDFDevice::handlePointAnnotation(const SkPoint& point,
epoger@google.comb58772f2013-03-08 09:09:10 +00001595 const SkMatrix& matrix,
reedf70b5312016-03-04 16:36:20 -08001596 const char key[], SkData* value) {
1597 if (!value) {
1598 return;
epoger@google.comb58772f2013-03-08 09:09:10 +00001599 }
reedf70b5312016-03-04 16:36:20 -08001600
1601 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
1602 SkPoint transformedPoint;
1603 matrix.mapXY(point.x(), point.y(), &transformedPoint);
1604 fNamedDestinations.emplace_back(value, transformedPoint);
1605 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001606}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001607
reedf70b5312016-03-04 16:36:20 -08001608void SkPDFDevice::handlePathAnnotation(const SkPath& path,
wangxianzhuef6c50a2015-09-17 20:38:02 -07001609 const SkDraw& d,
reedf70b5312016-03-04 16:36:20 -08001610 const char key[], SkData* value) {
1611 if (!value) {
1612 return;
1613 }
wangxianzhuef6c50a2015-09-17 20:38:02 -07001614
1615 SkPath transformedPath = path;
1616 transformedPath.transform(*d.fMatrix);
1617 SkRasterClip clip = *d.fRC;
senorblancoafc7cce2016-02-02 18:44:15 -08001618 clip.op(transformedPath, SkIRect::MakeWH(width(), height()), SkRegion::kIntersect_Op,
1619 false);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001620 SkRect transformedRect = SkRect::Make(clip.getBounds());
1621
reedf70b5312016-03-04 16:36:20 -08001622 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001623 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001624 fLinkToURLs.emplace_back(transformedRect, value);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001625 }
reedf70b5312016-03-04 16:36:20 -08001626 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
reed16108352016-03-03 09:14:36 -08001627 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001628 fLinkToDestinations.emplace_back(transformedRect, value);
reed16108352016-03-03 09:14:36 -08001629 }
reed16108352016-03-03 09:14:36 -08001630 }
halcanary438de492015-04-28 06:21:01 -07001631}
1632
wangxianzhuef6c50a2015-09-17 20:38:02 -07001633void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1634 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001635 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001636 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001637 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001638 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001639 }
halcanary91fcb3e2016-03-04 13:53:22 -08001640 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001641 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001642 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001643 array->appendObject(
1644 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001645 }
1646}
epoger@google.comb58772f2013-03-08 09:09:10 +00001647
halcanary6d622702015-03-25 08:45:42 -07001648void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001649 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001650 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001651 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001652 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001653 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001654 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001655 pdfDest->appendScalar(p.x());
1656 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001657 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001658 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001659 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001660 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001661}
1662
reed@google.comfc641d02012-09-20 17:52:20 +00001663SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
halcanary385fe4d2015-08-26 13:07:48 -07001664 SkPDFFormXObject* xobject = new SkPDFFormXObject(this);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001665 // We always draw the form xobjects that we create back into the device, so
1666 // we simply preserve the font usage instead of pulling it out and merging
1667 // it back in later.
1668 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001669 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001670 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001671}
1672
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001673void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1674 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001675 const SkClipStack* clipStack,
1676 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001677 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001678 bool invertClip) {
1679 if (clipRegion.isEmpty() && !invertClip) {
1680 return;
1681 }
1682
halcanary1437c1e2016-03-13 18:30:24 -07001683 auto sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
halcanary989da4a2016-03-21 14:33:17 -07001684 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode, fDocument->canon());
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001685
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001686 SkMatrix identity;
1687 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001688 SkPaint paint;
1689 paint.setXfermodeMode(mode);
1690 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001691 if (!content.entry()) {
1692 return;
1693 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001694 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001695 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001696 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001697
halcanary1437c1e2016-03-13 18:30:24 -07001698 // Call makeNoSmaskGraphicState() instead of
1699 // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1700 // can deduplicate.
halcanary989da4a2016-03-21 14:33:17 -07001701 sMaskGS = fDocument->canon()->makeNoSmaskGraphicState();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001702 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001703 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001704}
1705
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001706ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1707 const SkRegion& clipRegion,
1708 const SkMatrix& matrix,
1709 const SkPaint& paint,
1710 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001711 SkPDFFormXObject** dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001712 *dst = nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001713 if (clipRegion.isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -07001714 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001715 }
1716
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001717 // The clip stack can come from an SkDraw where it is technically optional.
1718 SkClipStack synthesizedClipStack;
halcanary96fcdcc2015-08-27 07:41:13 -07001719 if (clipStack == nullptr) {
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001720 if (clipRegion == fExistingClipRegion) {
1721 clipStack = &fExistingClipStack;
1722 } else {
1723 // GraphicStackState::updateClip expects the clip stack to have
1724 // fExistingClip as a prefix, so start there, then set the clip
1725 // to the passed region.
1726 synthesizedClipStack = fExistingClipStack;
1727 SkPath clipPath;
1728 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001729 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1730 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001731 clipStack = &synthesizedClipStack;
1732 }
1733 }
1734
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001735 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1736 if (paint.getXfermode()) {
1737 paint.getXfermode()->asMode(&xfermode);
1738 }
1739
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001740 // For the following modes, we want to handle source and destination
1741 // separately, so make an object of what's already there.
1742 if (xfermode == SkXfermode::kClear_Mode ||
1743 xfermode == SkXfermode::kSrc_Mode ||
1744 xfermode == SkXfermode::kSrcIn_Mode ||
1745 xfermode == SkXfermode::kDstIn_Mode ||
1746 xfermode == SkXfermode::kSrcOut_Mode ||
1747 xfermode == SkXfermode::kDstOut_Mode ||
1748 xfermode == SkXfermode::kSrcATop_Mode ||
1749 xfermode == SkXfermode::kDstATop_Mode ||
1750 xfermode == SkXfermode::kModulate_Mode) {
1751 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001752 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001753 SkASSERT(isContentEmpty());
1754 } else if (xfermode != SkXfermode::kSrc_Mode &&
1755 xfermode != SkXfermode::kSrcOut_Mode) {
1756 // Except for Src and SrcOut, if there isn't anything already there,
1757 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001758 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001759 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001760 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001761 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001762 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001763
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001764 // Dst xfer mode doesn't draw source at all.
1765 if (xfermode == SkXfermode::kDst_Mode) {
halcanary96fcdcc2015-08-27 07:41:13 -07001766 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001767 }
1768
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001769 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001770 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001771
1772 ContentEntry* lastContentEntry = getLastContentEntry();
1773 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1774 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001775 } else {
1776 newEntry.reset(new ContentEntry);
1777 entry = newEntry.get();
1778 }
1779
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001780 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001781 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001782 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1783 entry->fState.compareInitialState(lastContentEntry->fState)) {
1784 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001785 }
1786
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001787 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001788 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001789 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001790 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001791 } else if (xfermode == SkXfermode::kDstOver_Mode) {
mtklein18300a32016-03-16 13:53:35 -07001792 entry->fNext.reset(contentEntries->release());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001793 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001794 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001795 lastContentEntry->fNext.reset(entry);
1796 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001797 }
halcanaryfcad44b2016-03-06 14:47:10 -08001798 newEntry.release();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001799 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001800}
1801
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001802void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001803 SkPDFFormXObject* dst,
1804 SkPath* shape) {
1805 if (xfermode != SkXfermode::kClear_Mode &&
1806 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001807 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001808 xfermode != SkXfermode::kSrcIn_Mode &&
1809 xfermode != SkXfermode::kDstIn_Mode &&
1810 xfermode != SkXfermode::kSrcOut_Mode &&
1811 xfermode != SkXfermode::kDstOut_Mode &&
1812 xfermode != SkXfermode::kSrcATop_Mode &&
1813 xfermode != SkXfermode::kDstATop_Mode &&
1814 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001815 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001816 return;
1817 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001818 if (xfermode == SkXfermode::kDstOver_Mode) {
1819 SkASSERT(!dst);
1820 ContentEntry* firstContentEntry = getContentEntries()->get();
1821 if (firstContentEntry->fContent.getOffset() == 0) {
1822 // For DstOver, an empty content entry was inserted before the rest
1823 // of the content entries. If nothing was drawn, it needs to be
1824 // removed.
1825 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
mtklein18300a32016-03-16 13:53:35 -07001826 contentEntries->reset(firstContentEntry->fNext.release());
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001827 }
1828 return;
1829 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001830 if (!dst) {
1831 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1832 xfermode == SkXfermode::kSrcOut_Mode);
1833 return;
1834 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001835
1836 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001837 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001838 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001839 // Changing the current content into a form-xobject will destroy the clip
1840 // objects which is fine since the xobject will already be clipped. However
1841 // if source has shape, we need to clip it too, so a copy of the clip is
1842 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001843 SkClipStack clipStack = contentEntries->fState.fClipStack;
1844 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001845
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001846 SkMatrix identity;
1847 identity.reset();
1848 SkPaint stockPaint;
1849
halcanary48810a02016-03-07 14:57:50 -08001850 sk_sp<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001851 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001852 // If nothing was drawn and there's no shape, then the draw was a
1853 // no-op, but dst needs to be restored for that to be true.
1854 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1855 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1856 // reduces to Dst.
halcanary96fcdcc2015-08-27 07:41:13 -07001857 if (shape == nullptr || xfermode == SkXfermode::kDstOut_Mode ||
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001858 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001859 ScopedContentEntry content(this, &fExistingClipStack,
1860 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001861 stockPaint);
1862 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1863 &content.entry()->fContent);
1864 return;
1865 } else {
1866 xfermode = SkXfermode::kClear_Mode;
1867 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001868 } else {
1869 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001870 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001871 }
1872
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001873 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1874 // without alpha.
1875 if (xfermode == SkXfermode::kSrcATop_Mode) {
1876 // TODO(vandebo): In order to properly support SrcATop we have to track
1877 // the shape of what's been drawn at all times. It's the intersection of
1878 // the non-transparent parts of the device and the outlines (shape) of
1879 // all images and devices drawn.
1880 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001881 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001882 SkXfermode::kSrcOver_Mode, true);
1883 } else {
halcanary48810a02016-03-07 14:57:50 -08001884 sk_sp<SkPDFFormXObject> dstMaskStorage;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001885 SkPDFFormXObject* dstMask = srcFormXObject.get();
halcanary96fcdcc2015-08-27 07:41:13 -07001886 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001887 // Draw shape into a form-xobject.
1888 SkDraw d;
1889 d.fMatrix = &identity;
1890 d.fClip = &clipRegion;
1891 d.fClipStack = &clipStack;
1892 SkPaint filledPaint;
1893 filledPaint.setColor(SK_ColorBLACK);
1894 filledPaint.setStyle(SkPaint::kFill_Style);
halcanary96fcdcc2015-08-27 07:41:13 -07001895 this->drawPath(d, *shape, filledPaint, nullptr, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001896
1897 dstMaskStorage.reset(createFormXObjectFromDevice());
1898 dstMask = dstMaskStorage.get();
1899 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001900 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1901 &fExistingClipStack, fExistingClipRegion,
1902 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001903 }
1904
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001905 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001906 return;
1907 } else if (xfermode == SkXfermode::kSrc_Mode ||
1908 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001909 ScopedContentEntry content(this, &fExistingClipStack,
1910 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001911 if (content.entry()) {
1912 SkPDFUtils::DrawFormXObject(
1913 this->addXObjectResource(srcFormXObject.get()),
1914 &content.entry()->fContent);
1915 }
1916 if (xfermode == SkXfermode::kSrc_Mode) {
1917 return;
1918 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001919 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001920 ScopedContentEntry content(this, &fExistingClipStack,
1921 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001922 if (content.entry()) {
1923 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1924 &content.entry()->fContent);
1925 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001926 }
1927
1928 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1929 xfermode == SkXfermode::kDstIn_Mode ||
1930 xfermode == SkXfermode::kSrcOut_Mode ||
1931 xfermode == SkXfermode::kDstOut_Mode ||
1932 xfermode == SkXfermode::kSrcATop_Mode ||
1933 xfermode == SkXfermode::kDstATop_Mode ||
1934 xfermode == SkXfermode::kModulate_Mode);
1935
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001936 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001937 xfermode == SkXfermode::kSrcOut_Mode ||
1938 xfermode == SkXfermode::kSrcATop_Mode) {
1939 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001940 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001941 SkXfermode::kSrcOver_Mode,
1942 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001943 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001944 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1945 if (xfermode == SkXfermode::kModulate_Mode) {
1946 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001947 dst, &fExistingClipStack,
1948 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001949 SkXfermode::kSrcOver_Mode, false);
1950 mode = SkXfermode::kMultiply_Mode;
1951 }
1952 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001953 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001954 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001955 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001956}
1957
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001958bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001959 ContentEntry* contentEntries = getContentEntries()->get();
1960 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1961 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001962 return true;
1963 }
1964 return false;
1965}
1966
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001967void SkPDFDevice::populateGraphicStateEntryFromPaint(
1968 const SkMatrix& matrix,
1969 const SkClipStack& clipStack,
1970 const SkRegion& clipRegion,
1971 const SkPaint& paint,
1972 bool hasText,
1973 GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07001974 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
1975 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1976 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001977
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001978 entry->fMatrix = matrix;
1979 entry->fClipStack = clipStack;
1980 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001981 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1982 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001983
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001984 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08001985 sk_sp<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001986 const SkShader* shader = paint.getShader();
1987 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001988 if (shader) {
1989 // PDF positions patterns relative to the initial transform, so
1990 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001991 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001992 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001993
1994 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001995 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001996 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001997
1998 // We need to apply the initial transform to bounds in order to get
1999 // bounds in a consistent coordinate system.
2000 SkRect boundsTemp;
2001 boundsTemp.set(bounds);
2002 fInitialTransform.mapRect(&boundsTemp);
2003 boundsTemp.roundOut(&bounds);
2004
halcanary792c80f2015-02-20 07:21:05 -08002005 SkScalar rasterScale =
2006 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
2007 pdfShader.reset(SkPDFShader::GetPDFShader(
halcanary989da4a2016-03-21 14:33:17 -07002008 fDocument, fRasterDpi, *shader, transform, bounds, rasterScale));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002009
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002010 if (pdfShader.get()) {
2011 // pdfShader has been canonicalized so we can directly compare
2012 // pointers.
2013 int resourceIndex = fShaderResources.find(pdfShader.get());
2014 if (resourceIndex < 0) {
2015 resourceIndex = fShaderResources.count();
2016 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002017 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002018 }
2019 entry->fShaderIndex = resourceIndex;
2020 } else {
2021 // A color shader is treated as an invalid shader so we don't have
2022 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002023 SkShader::GradientInfo gradientInfo;
2024 SkColor gradientColor;
2025 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07002026 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002027 gradientInfo.fColorCount = 1;
2028 if (shader->asAGradient(&gradientInfo) ==
2029 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002030 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2031 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002032 }
2033 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002034 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002035
halcanary48810a02016-03-07 14:57:50 -08002036 sk_sp<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002037 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002038 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07002039 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002040 } else {
2041 SkPaint newPaint = paint;
2042 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002043 newGraphicState.reset(
halcanary989da4a2016-03-21 14:33:17 -07002044 SkPDFGraphicState::GetGraphicStateForPaint(fDocument->canon(), newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002045 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002046 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002047 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002048
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002049 if (hasText) {
2050 entry->fTextScaleX = paint.getTextScaleX();
2051 entry->fTextFill = paint.getStyle();
2052 } else {
2053 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002054 }
2055}
2056
halcanarybe27a112015-04-01 13:31:19 -07002057int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002058 // Assumes that gs has been canonicalized (so we can directly compare
2059 // pointers).
2060 int result = fGraphicStateResources.find(gs);
2061 if (result < 0) {
2062 result = fGraphicStateResources.count();
2063 fGraphicStateResources.push(gs);
2064 gs->ref();
2065 }
2066 return result;
2067}
2068
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002069int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2070 // Assumes that xobject has been canonicalized (so we can directly compare
2071 // pointers).
2072 int result = fXObjectResources.find(xObject);
2073 if (result < 0) {
2074 result = fXObjectResources.count();
2075 fXObjectResources.push(xObject);
2076 xObject->ref();
2077 }
2078 return result;
2079}
2080
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002081void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2082 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002083 SkTypeface* typeface = paint.getTypeface();
halcanary96fcdcc2015-08-27 07:41:13 -07002084 if (contentEntry->fState.fFont == nullptr ||
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002085 contentEntry->fState.fTextSize != paint.getTextSize() ||
2086 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002087 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002088 contentEntry->fContent.writeText("/");
2089 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2090 SkPDFResourceDict::kFont_ResourceType,
2091 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002092 contentEntry->fContent.writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -07002093 SkPDFUtils::AppendScalar(paint.getTextSize(), &contentEntry->fContent);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002094 contentEntry->fContent.writeText(" Tf\n");
2095 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002096 }
2097}
2098
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002099int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary48810a02016-03-07 14:57:50 -08002100 sk_sp<SkPDFFont> newFont(
halcanary989da4a2016-03-21 14:33:17 -07002101 SkPDFFont::GetFontResource(fDocument->canon(), typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002102 int resourceIndex = fFontResources.find(newFont.get());
2103 if (resourceIndex < 0) {
2104 resourceIndex = fFontResources.count();
2105 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002106 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002107 }
2108 return resourceIndex;
2109}
2110
halcanary7a14b312015-10-01 07:28:13 -07002111static SkSize rect_to_size(const SkRect& r) {
2112 return SkSize::Make(r.width(), r.height());
2113}
2114
reedd053ce92016-03-22 10:17:23 -07002115static const SkImage* color_filter(const SkImage* image, SkColorFilter* colorFilter) {
reede8f30622016-03-23 18:59:25 -07002116 auto surface(SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(image->dimensions())));
halcanary7a14b312015-10-01 07:28:13 -07002117 if (!surface) {
2118 return image;
2119 }
2120 SkCanvas* canvas = surface->getCanvas();
2121 canvas->clear(SK_ColorTRANSPARENT);
2122 SkPaint paint;
reedd053ce92016-03-22 10:17:23 -07002123 paint.setColorFilter(sk_ref_sp(colorFilter));
halcanary7a14b312015-10-01 07:28:13 -07002124 canvas->drawImage(image, 0, 0, &paint);
2125 canvas->flush();
reed9ce9d672016-03-17 10:51:11 -07002126 return surface->makeImageSnapshot().release();
halcanary7a14b312015-10-01 07:28:13 -07002127}
2128
2129////////////////////////////////////////////////////////////////////////////////
2130void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
2131 const SkClipStack* clipStack,
2132 const SkRegion& origClipRegion,
2133 const SkImage* image,
2134 const SkIRect* srcRect,
2135 const SkPaint& paint) {
2136 SkASSERT(image);
2137 #ifdef SK_PDF_IMAGE_STATS
2138 gDrawImageCalls.fetch_add(1);
2139 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002140 SkMatrix matrix = origMatrix;
2141 SkRegion perspectiveBounds;
2142 const SkRegion* clipRegion = &origClipRegion;
halcanary48810a02016-03-07 14:57:50 -08002143 sk_sp<const SkImage> autoImageUnref;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002144
halcanary7a14b312015-10-01 07:28:13 -07002145 if (srcRect) {
reed9ce9d672016-03-17 10:51:11 -07002146 autoImageUnref = image->makeSubset(*srcRect);
halcanary7a14b312015-10-01 07:28:13 -07002147 if (!autoImageUnref) {
2148 return;
2149 }
halcanaryfcad44b2016-03-06 14:47:10 -08002150 image = autoImageUnref.get();
halcanary7a14b312015-10-01 07:28:13 -07002151 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002152 // Rasterize the bitmap using perspective in a new bitmap.
2153 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002154 if (fRasterDpi == 0) {
2155 return;
2156 }
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002157 // Transform the bitmap in the new space, without taking into
2158 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002159 SkPath perspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002160 SkRect imageBounds = SkRect::Make(image->bounds());
2161 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002162 perspectiveOutline.transform(origMatrix);
2163
2164 // TODO(edisonn): perf - use current clip too.
2165 // Retrieve the bounds of the new shape.
2166 SkRect bounds = perspectiveOutline.getBounds();
2167
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002168 // Transform the bitmap in the new space, taking into
2169 // account the initial transform.
2170 SkMatrix total = origMatrix;
2171 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002172 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2173 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2174 total.postScale(dpiScale, dpiScale);
2175
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002176 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002177 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002178 physicalPerspectiveOutline.transform(total);
2179
halcanary7a14b312015-10-01 07:28:13 -07002180 SkRect physicalPerspectiveBounds =
2181 physicalPerspectiveOutline.getBounds();
2182 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2183 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002184
2185 // TODO(edisonn): A better approach would be to use a bitmap shader
2186 // (in clamp mode) and draw a rect over the entire bounding box. Then
2187 // intersect perspectiveOutline to the clip. That will avoid introducing
2188 // alpha to the image while still giving good behavior at the edge of
2189 // the image. Avoiding alpha will reduce the pdf size and generation
2190 // CPU time some.
2191
halcanary7a14b312015-10-01 07:28:13 -07002192 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2193
reede8f30622016-03-23 18:59:25 -07002194 auto surface(SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(wh)));
halcanary7a14b312015-10-01 07:28:13 -07002195 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002196 return;
2197 }
halcanary7a14b312015-10-01 07:28:13 -07002198 SkCanvas* canvas = surface->getCanvas();
2199 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002200
2201 SkScalar deltaX = bounds.left();
2202 SkScalar deltaY = bounds.top();
2203
2204 SkMatrix offsetMatrix = origMatrix;
2205 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002206 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002207
2208 // Translate the draw in the new canvas, so we perfectly fit the
2209 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002210 canvas->setMatrix(offsetMatrix);
2211 canvas->drawImage(image, 0, 0, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002212 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002213 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002214
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002215 // In the new space, we use the identity matrix translated
2216 // and scaled to reflect DPI.
2217 matrix.setScale(1 / scaleX, 1 / scaleY);
2218 matrix.postTranslate(deltaX, deltaY);
2219
halcanary7a14b312015-10-01 07:28:13 -07002220 perspectiveBounds.setRect(bounds.roundOut());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002221 clipRegion = &perspectiveBounds;
halcanary96fcdcc2015-08-27 07:41:13 -07002222 srcRect = nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002223
reed9ce9d672016-03-17 10:51:11 -07002224 autoImageUnref.reset(surface->makeImageSnapshot().release());
halcanaryfcad44b2016-03-06 14:47:10 -08002225 image = autoImageUnref.get();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002226 }
2227
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002228 SkMatrix scaled;
2229 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002230 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2231 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002232 // Scale the image up from 1x1 to WxH.
halcanary7a14b312015-10-01 07:28:13 -07002233 SkIRect subset = image->bounds();
2234 scaled.postScale(SkIntToScalar(image->width()),
2235 SkIntToScalar(image->height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002236 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002237 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002238 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2239 return;
2240 }
2241 if (content.needShape()) {
2242 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002243 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002244 shape.transform(matrix);
2245 content.setShape(shape);
2246 }
2247 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002248 return;
2249 }
2250
halcanary287d22d2015-09-24 10:20:05 -07002251 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002252 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002253 // draw calls. This code here works for all
2254 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2255 // rasterize a layer on this backend). Fortuanely, this seems
2256 // to be how Chromium impements most color-filters.
2257 autoImageUnref.reset(color_filter(image, colorFilter));
halcanaryfcad44b2016-03-06 14:47:10 -08002258 image = autoImageUnref.get();
halcanary7a14b312015-10-01 07:28:13 -07002259 // TODO(halcanary): de-dupe this by caching filtered images.
2260 // (maybe in the resource cache?)
2261 }
halcanary989da4a2016-03-21 14:33:17 -07002262 sk_sp<SkPDFObject> pdfimage(SkSafeRef(fDocument->canon()->findPDFBitmap(image)));
halcanary7a14b312015-10-01 07:28:13 -07002263 if (!pdfimage) {
halcanary712fdf72015-12-10 08:59:43 -08002264 pdfimage.reset(SkPDFCreateBitmapObject(
halcanary989da4a2016-03-21 14:33:17 -07002265 image, fDocument->canon()->getPixelSerializer()));
halcanary7a14b312015-10-01 07:28:13 -07002266 if (!pdfimage) {
2267 return;
halcanary287d22d2015-09-24 10:20:05 -07002268 }
halcanary989da4a2016-03-21 14:33:17 -07002269 #if SK_PDF_SERIALIZE_IMAGES_EARLY // TODO(halcanary): enable.
2270 sk_sp<SkData> encodedImage(image->refEncodedData());
2271 if (!encodedImage) {
2272 fDocument->serialize(pdfimage);
2273 }
2274 #endif
2275 fDocument->canon()->addPDFBitmap(image->uniqueID(), pdfimage.get());
halcanary287d22d2015-09-24 10:20:05 -07002276 }
halcanary3d8c33c2015-10-01 11:06:22 -07002277 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002278 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002279}