blob: e349ce42fb843ad0c5172547a8cd633fbe1abd6a [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"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000018#include "SkPathOps.h"
halcanarydb0dcc72015-03-20 12:31:52 -070019#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070020#include "SkPDFCanon.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000021#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000022#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000023#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000024#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000025#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000026#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000027#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000028#include "SkPDFUtils.h"
wangxianzhuef6c50a2015-09-17 20:38:02 -070029#include "SkRasterClip.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000030#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000031#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000032#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070033#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000034#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000035#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000036#include "SkTypefacePriv.h"
halcanarya6814332015-05-27 08:53:36 -070037#include "SkXfermodeInterpretation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000038
edisonn@google.com73a7ea32013-11-11 20:55:15 +000039#define DPI_FOR_RASTER_SCALE_ONE 72
40
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000041// Utility functions
42
halcanarya6814332015-05-27 08:53:36 -070043// If the paint will definitely draw opaquely, replace kSrc_Mode with
44// kSrcOver_Mode. http://crbug.com/473572
45static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
46 if (kSrcOver_SkXfermodeInterpretation
47 == SkInterpretXfermode(*paint, false)) {
halcanary96fcdcc2015-08-27 07:41:13 -070048 paint->setXfermode(nullptr);
halcanarya6814332015-05-27 08:53:36 -070049 }
50}
51
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000052static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000053 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
reed80ea19c2015-05-12 10:37:34 -070054 SkScalar colorScale = SkScalarInvert(0xFF);
55 SkPDFUtils::AppendScalar(SkColorGetR(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000056 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070057 SkPDFUtils::AppendScalar(SkColorGetG(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000058 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070059 SkPDFUtils::AppendScalar(SkColorGetB(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000060 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000061}
62
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000063static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000064 SkPaint result = paint;
65 if (result.isFakeBoldText()) {
66 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
67 kStdFakeBoldInterpKeys,
68 kStdFakeBoldInterpValues,
69 kStdFakeBoldInterpLength);
70 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000071 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000072 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000073 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000074 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000075 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000076 result.setStrokeWidth(width);
77 }
78 return result;
79}
80
81// Stolen from measure_text in SkDraw.cpp and then tweaked.
benjaminwagnerd936f632016-02-23 10:44:31 -080082static void align_text(SkPaint::GlyphCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000083 const uint16_t* glyphs, size_t len,
84 SkScalar* x, SkScalar* y) {
85 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000086 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000087 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000088
89 SkMatrix ident;
90 ident.reset();
halcanary96fcdcc2015-08-27 07:41:13 -070091 SkAutoGlyphCache autoCache(paint, nullptr, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000092 SkGlyphCache* cache = autoCache.getCache();
93
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000094 const char* start = reinterpret_cast<const char*>(glyphs);
95 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000096 SkFixed xAdv = 0, yAdv = 0;
97
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000098 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000099 while (start < stop) {
benjaminwagnerd936f632016-02-23 10:44:31 -0800100 const SkGlyph& glyph = glyphCacheProc(cache, &start);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000101 xAdv += glyph.fAdvanceX;
102 yAdv += glyph.fAdvanceY;
103 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000104 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000105 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000106 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000107
108 SkScalar xAdj = SkFixedToScalar(xAdv);
109 SkScalar yAdj = SkFixedToScalar(yAdv);
110 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
111 xAdj = SkScalarHalf(xAdj);
112 yAdj = SkScalarHalf(yAdj);
113 }
114 *x = *x - xAdj;
115 *y = *y - yAdj;
116}
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());
halcanarya1f1ee92015-02-20 06:17:26 -0800586 return SkPDFDevice::Create(size, fRasterDpi, fCanon);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000587}
588
589
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000590struct ContentEntry {
591 GraphicStateEntry fState;
592 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000593 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000594
595 // If the stack is too deep we could get Stack Overflow.
596 // So we manually destruct the object.
597 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000598 ContentEntry* val = fNext.detach();
halcanary96fcdcc2015-08-27 07:41:13 -0700599 while (val != nullptr) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000600 ContentEntry* valNext = val->fNext.detach();
halcanary96fcdcc2015-08-27 07:41:13 -0700601 // When the destructor is called, fNext is nullptr and exits.
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000602 delete val;
603 val = valNext;
604 }
605 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000606};
607
608// A helper class to automatically finish a ContentEntry at the end of a
609// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000610class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000611public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000612 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
613 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000614 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700615 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000616 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700617 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000618 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
619 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000620 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
621 const SkRegion& clipRegion, const SkMatrix& matrix,
622 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000623 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700624 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000625 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700626 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000627 init(clipStack, clipRegion, matrix, paint, hasText);
628 }
629
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000630 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000631 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000632 SkPath* shape = &fShape;
633 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700634 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000635 }
636 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000637 }
reed@google.comfc641d02012-09-20 17:52:20 +0000638 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000639 }
640
641 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000642
643 /* Returns true when we explicitly need the shape of the drawing. */
644 bool needShape() {
645 switch (fXfermode) {
646 case SkXfermode::kClear_Mode:
647 case SkXfermode::kSrc_Mode:
648 case SkXfermode::kSrcIn_Mode:
649 case SkXfermode::kSrcOut_Mode:
650 case SkXfermode::kDstIn_Mode:
651 case SkXfermode::kDstOut_Mode:
652 case SkXfermode::kSrcATop_Mode:
653 case SkXfermode::kDstATop_Mode:
654 case SkXfermode::kModulate_Mode:
655 return true;
656 default:
657 return false;
658 }
659 }
660
661 /* Returns true unless we only need the shape of the drawing. */
662 bool needSource() {
663 if (fXfermode == SkXfermode::kClear_Mode) {
664 return false;
665 }
666 return true;
667 }
668
669 /* If the shape is different than the alpha component of the content, then
670 * setShape should be called with the shape. In particular, images and
671 * devices have rectangular shape.
672 */
673 void setShape(const SkPath& shape) {
674 fShape = shape;
675 }
676
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000677private:
678 SkPDFDevice* fDevice;
679 ContentEntry* fContentEntry;
680 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000681 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000682 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000683
684 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
685 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000686 // Shape has to be flatten before we get here.
687 if (matrix.hasPerspective()) {
688 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000689 return;
690 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000691 if (paint.getXfermode()) {
692 paint.getXfermode()->asMode(&fXfermode);
693 }
694 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
695 matrix, paint, hasText,
696 &fDstFormXObject);
697 }
698};
699
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000700////////////////////////////////////////////////////////////////////////////////
701
halcanary385fe4d2015-08-26 13:07:48 -0700702SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFCanon* canon, bool flip)
robertphillips9a53fd72015-06-22 09:46:59 -0700703 : INHERITED(SkSurfaceProps(0, kUnknown_SkPixelGeometry))
704 , fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800705 , fContentSize(pageSize)
706 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
halcanary96fcdcc2015-08-27 07:41:13 -0700707 , fLastContentEntry(nullptr)
708 , fLastMarginContentEntry(nullptr)
halcanarya1f1ee92015-02-20 06:17:26 -0800709 , fDrawingArea(kContent_DrawingArea)
halcanary96fcdcc2015-08-27 07:41:13 -0700710 , fClipStack(nullptr)
halcanary385fe4d2015-08-26 13:07:48 -0700711 , fFontGlyphUsage(new SkPDFGlyphSetMap)
halcanarya1f1ee92015-02-20 06:17:26 -0800712 , fRasterDpi(rasterDpi)
713 , fCanon(canon) {
714 SkASSERT(pageSize.width() > 0);
715 SkASSERT(pageSize.height() > 0);
716 fLegacyBitmap.setInfo(
717 SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()));
718 if (flip) {
719 // Skia generally uses the top left as the origin but PDF
720 // natively has the origin at the bottom left. This matrix
721 // corrects for that. But that only needs to be done once, we
722 // don't do it when layering.
723 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
724 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
725 } else {
726 fInitialTransform.setIdentity();
727 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000728}
729
730SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000731 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000732}
733
734void SkPDFDevice::init() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000735 fContentEntries.free();
halcanary96fcdcc2015-08-27 07:41:13 -0700736 fLastContentEntry = nullptr;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000737 fMarginContentEntries.free();
halcanary96fcdcc2015-08-27 07:41:13 -0700738 fLastMarginContentEntry = nullptr;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000739 fDrawingArea = kContent_DrawingArea;
halcanary96fcdcc2015-08-27 07:41:13 -0700740 if (fFontGlyphUsage.get() == nullptr) {
halcanary385fe4d2015-08-26 13:07:48 -0700741 fFontGlyphUsage.reset(new SkPDFGlyphSetMap);
vandebo@chromium.org98594282011-07-25 22:34:12 +0000742 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000743}
744
vandebo@chromium.org98594282011-07-25 22:34:12 +0000745void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000746 fGraphicStateResources.unrefAll();
747 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000748 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000749 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000750
vandebo@chromium.org98594282011-07-25 22:34:12 +0000751 if (clearFontUsage) {
752 fFontGlyphUsage->reset();
753 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000754}
755
reedf70b5312016-03-04 16:36:20 -0800756void SkPDFDevice::drawAnnotation(const SkDraw& d, const SkRect& rect, const char key[],
757 SkData* value) {
758 if (0 == rect.width() && 0 == rect.height()) {
759 handlePointAnnotation({ rect.x(), rect.y() }, *d.fMatrix, key, value);
760 } else {
761 SkPath path;
762 path.addRect(rect);
763 handlePathAnnotation(path, d, key, value);
764 }
765}
766
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000767void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000768 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700769 replace_srcmode_on_opaque_paint(&newPaint);
770
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000771 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000772 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000773 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000774}
775
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000776void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
777 ContentEntry* contentEntry) {
778 if (!contentEntry) {
779 return;
780 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000781 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
782 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000783 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000784 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000785 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000786 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000787 inverse.mapRect(&bbox);
788
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000789 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000790 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000791 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000792}
793
halcanary682ee012016-01-28 10:59:34 -0800794void SkPDFDevice::drawPoints(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700795 SkCanvas::PointMode mode,
796 size_t count,
797 const SkPoint* points,
798 const SkPaint& srcPaint) {
799 SkPaint passedPaint = srcPaint;
800 replace_srcmode_on_opaque_paint(&passedPaint);
801
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000802 if (count == 0) {
803 return;
804 }
805
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000806 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
807 // We only use this when there's a path effect because of the overhead
808 // of multiple calls to setUpContentEntry it causes.
809 if (passedPaint.getPathEffect()) {
810 if (d.fClip->isEmpty()) {
811 return;
812 }
813 SkDraw pointDraw(d);
814 pointDraw.fDevice = this;
815 pointDraw.drawPoints(mode, count, points, passedPaint, true);
816 return;
817 }
818
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000819 const SkPaint* paint = &passedPaint;
820 SkPaint modifiedPaint;
821
822 if (mode == SkCanvas::kPoints_PointMode &&
823 paint->getStrokeCap() != SkPaint::kRound_Cap) {
824 modifiedPaint = *paint;
825 paint = &modifiedPaint;
826 if (paint->getStrokeWidth()) {
827 // PDF won't draw a single point with square/butt caps because the
828 // orientation is ambiguous. Draw a rectangle instead.
829 modifiedPaint.setStyle(SkPaint::kFill_Style);
830 SkScalar strokeWidth = paint->getStrokeWidth();
831 SkScalar halfStroke = SkScalarHalf(strokeWidth);
832 for (size_t i = 0; i < count; i++) {
833 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
834 r.inset(-halfStroke, -halfStroke);
835 drawRect(d, r, modifiedPaint);
836 }
837 return;
838 } else {
839 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
840 }
841 }
842
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000843 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000844 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000845 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000846 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000847
848 switch (mode) {
849 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000850 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000851 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000852 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000853 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000854 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000855 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000856 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000857 break;
858 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000859 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000860 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000861 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000862 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000863 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000864 &content.entry()->fContent);
865 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000866 }
867 break;
868 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000869 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
870 for (size_t i = 0; i < count; i++) {
871 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000872 &content.entry()->fContent);
873 SkPDFUtils::ClosePath(&content.entry()->fContent);
874 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000875 }
876 break;
877 default:
878 SkASSERT(false);
879 }
880}
881
halcanary8103a342016-03-08 15:10:16 -0800882static sk_sp<SkPDFDict> create_link_annotation(const SkRect& translatedRect) {
halcanaryece83922016-03-08 08:32:12 -0800883 auto annotation = sk_make_sp<SkPDFDict>("Annot");
wangxianzhud76665d2015-07-17 17:23:15 -0700884 annotation->insertName("Subtype", "Link");
885
halcanaryece83922016-03-08 08:32:12 -0800886 auto border = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700887 border->reserve(3);
888 border->appendInt(0); // Horizontal corner radius.
889 border->appendInt(0); // Vertical corner radius.
890 border->appendInt(0); // Width, 0 = no border.
halcanary8103a342016-03-08 15:10:16 -0800891 annotation->insertObject("Border", std::move(border));
wangxianzhud76665d2015-07-17 17:23:15 -0700892
halcanaryece83922016-03-08 08:32:12 -0800893 auto rect = sk_make_sp<SkPDFArray>();
wangxianzhud76665d2015-07-17 17:23:15 -0700894 rect->reserve(4);
895 rect->appendScalar(translatedRect.fLeft);
896 rect->appendScalar(translatedRect.fTop);
897 rect->appendScalar(translatedRect.fRight);
898 rect->appendScalar(translatedRect.fBottom);
halcanary8103a342016-03-08 15:10:16 -0800899 annotation->insertObject("Rect", std::move(rect));
wangxianzhud76665d2015-07-17 17:23:15 -0700900
halcanary8103a342016-03-08 15:10:16 -0800901 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700902}
903
halcanary8103a342016-03-08 15:10:16 -0800904static sk_sp<SkPDFDict> create_link_to_url(const SkData* urlData, const SkRect& r) {
905 auto annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700906 SkString url(static_cast<const char *>(urlData->data()),
907 urlData->size() - 1);
halcanaryece83922016-03-08 08:32:12 -0800908 auto action = sk_make_sp<SkPDFDict>("Action");
wangxianzhud76665d2015-07-17 17:23:15 -0700909 action->insertName("S", "URI");
910 action->insertString("URI", url);
halcanary8103a342016-03-08 15:10:16 -0800911 annotation->insertObject("A", std::move(action));
912 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700913}
914
halcanary8103a342016-03-08 15:10:16 -0800915static sk_sp<SkPDFDict> create_link_named_dest(const SkData* nameData,
916 const SkRect& r) {
917 auto annotation = create_link_annotation(r);
wangxianzhud76665d2015-07-17 17:23:15 -0700918 SkString name(static_cast<const char *>(nameData->data()),
919 nameData->size() - 1);
920 annotation->insertName("Dest", name);
halcanary8103a342016-03-08 15:10:16 -0800921 return annotation;
wangxianzhud76665d2015-07-17 17:23:15 -0700922}
923
halcanary682ee012016-01-28 10:59:34 -0800924void SkPDFDevice::drawRect(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700925 const SkRect& rect,
926 const SkPaint& srcPaint) {
927 SkPaint paint = srcPaint;
928 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000929 SkRect r = rect;
930 r.sort();
931
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000932 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000933 if (d.fClip->isEmpty()) {
934 return;
935 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000936 SkPath path;
937 path.addRect(r);
halcanary96fcdcc2015-08-27 07:41:13 -0700938 drawPath(d, path, paint, nullptr, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000939 return;
940 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000941
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000942 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000943 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000944 return;
945 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000946 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000947 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000948 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000949}
950
halcanarya6814332015-05-27 08:53:36 -0700951void SkPDFDevice::drawRRect(const SkDraw& draw,
952 const SkRRect& rrect,
953 const SkPaint& srcPaint) {
954 SkPaint paint = srcPaint;
955 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000956 SkPath path;
957 path.addRRect(rrect);
halcanary96fcdcc2015-08-27 07:41:13 -0700958 this->drawPath(draw, path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000959}
960
halcanarya6814332015-05-27 08:53:36 -0700961void SkPDFDevice::drawOval(const SkDraw& draw,
962 const SkRect& oval,
963 const SkPaint& srcPaint) {
964 SkPaint paint = srcPaint;
965 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700966 SkPath path;
967 path.addOval(oval);
halcanary96fcdcc2015-08-27 07:41:13 -0700968 this->drawPath(draw, path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700969}
970
halcanary682ee012016-01-28 10:59:34 -0800971void SkPDFDevice::drawPath(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700972 const SkPath& origPath,
973 const SkPaint& srcPaint,
974 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000975 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700976 SkPaint paint = srcPaint;
977 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800978 SkPath modifiedPath;
979 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000980
981 SkMatrix matrix = *d.fMatrix;
982 if (prePathMatrix) {
983 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800984 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000985 pathPtr = &modifiedPath;
986 pathIsMutable = true;
987 }
halcanary682ee012016-01-28 10:59:34 -0800988 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000989 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000990 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000991 }
992 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000993
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000994 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000995 if (d.fClip->isEmpty()) {
996 return;
997 }
halcanary682ee012016-01-28 10:59:34 -0800998 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000999 pathPtr = &modifiedPath;
1000 pathIsMutable = true;
1001 }
halcanary682ee012016-01-28 10:59:34 -08001002 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001003
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001004 SkPaint noEffectPaint(paint);
halcanary96fcdcc2015-08-27 07:41:13 -07001005 noEffectPaint.setPathEffect(nullptr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001006 if (fill) {
1007 noEffectPaint.setStyle(SkPaint::kFill_Style);
1008 } else {
1009 noEffectPaint.setStyle(SkPaint::kStroke_Style);
1010 noEffectPaint.setStrokeWidth(0);
1011 }
halcanary96fcdcc2015-08-27 07:41:13 -07001012 drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001013 return;
1014 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001015
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001016 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001017 return;
1018 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001019
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001020 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001021 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001022 return;
1023 }
halcanary8b2bc252015-10-06 09:41:47 -07001024 bool consumeDegeratePathSegments =
1025 paint.getStyle() == SkPaint::kFill_Style ||
1026 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
1027 paint.getStrokeCap() != SkPaint::kSquare_Cap);
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001028 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
halcanary8b2bc252015-10-06 09:41:47 -07001029 consumeDegeratePathSegments,
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001030 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001031 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001032 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001033}
1034
halcanary7a14b312015-10-01 07:28:13 -07001035void SkPDFDevice::drawBitmapRect(const SkDraw& draw,
1036 const SkBitmap& bitmap,
1037 const SkRect* src,
1038 const SkRect& dst,
1039 const SkPaint& srcPaint,
1040 SkCanvas::SrcRectConstraint constraint) {
1041 const SkImage* image = fCanon->bitmapToImage(bitmap);
1042 if (!image) {
1043 return;
1044 }
1045 // ownership of this image is retained by the canon.
1046 this->drawImageRect(draw, image, src, dst, srcPaint, constraint);
1047}
1048
1049void SkPDFDevice::drawBitmap(const SkDraw& d,
1050 const SkBitmap& bitmap,
1051 const SkMatrix& matrix,
1052 const SkPaint& srcPaint) {
halcanarya6814332015-05-27 08:53:36 -07001053 SkPaint paint = srcPaint;
1054 if (bitmap.isOpaque()) {
1055 replace_srcmode_on_opaque_paint(&paint);
1056 }
1057
halcanary7a14b312015-10-01 07:28:13 -07001058 if (d.fClip->isEmpty()) {
1059 return;
1060 }
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001061
halcanary7a14b312015-10-01 07:28:13 -07001062 SkMatrix transform = matrix;
1063 transform.postConcat(*d.fMatrix);
1064 const SkImage* image = fCanon->bitmapToImage(bitmap);
1065 if (!image) {
1066 return;
1067 }
1068 this->internalDrawImage(transform, d.fClipStack, *d.fClip, image, nullptr,
1069 paint);
1070}
1071
1072void SkPDFDevice::drawSprite(const SkDraw& d,
1073 const SkBitmap& bitmap,
1074 int x,
1075 int y,
1076 const SkPaint& srcPaint) {
1077 SkPaint paint = srcPaint;
1078 if (bitmap.isOpaque()) {
1079 replace_srcmode_on_opaque_paint(&paint);
1080 }
1081
1082 if (d.fClip->isEmpty()) {
1083 return;
1084 }
1085
1086 SkMatrix matrix;
1087 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
1088 const SkImage* image = fCanon->bitmapToImage(bitmap);
1089 if (!image) {
1090 return;
1091 }
1092 this->internalDrawImage(matrix, d.fClipStack, *d.fClip, image, nullptr,
1093 paint);
1094}
1095
1096void SkPDFDevice::drawImage(const SkDraw& draw,
1097 const SkImage* image,
1098 SkScalar x,
1099 SkScalar y,
1100 const SkPaint& srcPaint) {
1101 SkPaint paint = srcPaint;
1102 if (!image) {
1103 return;
1104 }
1105 if (image->isOpaque()) {
1106 replace_srcmode_on_opaque_paint(&paint);
1107 }
1108 if (draw.fClip->isEmpty()) {
1109 return;
1110 }
1111 SkMatrix transform = SkMatrix::MakeTrans(x, y);
1112 transform.postConcat(*draw.fMatrix);
1113 this->internalDrawImage(transform, draw.fClipStack, *draw.fClip, image,
1114 nullptr, paint);
1115}
1116
1117void SkPDFDevice::drawImageRect(const SkDraw& draw,
1118 const SkImage* image,
1119 const SkRect* src,
1120 const SkRect& dst,
1121 const SkPaint& srcPaint,
1122 SkCanvas::SrcRectConstraint constraint) {
1123 if (!image) {
1124 return;
1125 }
1126 if (draw.fClip->isEmpty()) {
1127 return;
1128 }
1129 SkPaint paint = srcPaint;
1130 if (image->isOpaque()) {
1131 replace_srcmode_on_opaque_paint(&paint);
1132 }
1133 // TODO: this code path must be updated to respect the flags parameter
1134 SkMatrix matrix;
1135 SkRect tmpSrc, tmpDst;
1136 SkRect imageBounds = SkRect::Make(image->bounds());
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001137
1138 // Compute matrix from the two rectangles
1139 if (src) {
1140 tmpSrc = *src;
1141 } else {
halcanary7a14b312015-10-01 07:28:13 -07001142 tmpSrc = imageBounds;
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001143 }
1144 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1145
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001146 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1147 // needed (if the src was clipped). No check needed if src==null.
halcanary48810a02016-03-07 14:57:50 -08001148 sk_sp<const SkImage> autoImageUnref;
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001149 if (src) {
halcanary7a14b312015-10-01 07:28:13 -07001150 if (!imageBounds.contains(*src)) {
1151 if (!tmpSrc.intersect(imageBounds)) {
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001152 return; // nothing to draw
1153 }
1154 // recompute dst, based on the smaller tmpSrc
1155 matrix.mapRect(&tmpDst, tmpSrc);
1156 }
1157
1158 // since we may need to clamp to the borders of the src rect within
1159 // the bitmap, we extract a subset.
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001160 SkIRect srcIR;
1161 tmpSrc.roundOut(&srcIR);
halcanary7a14b312015-10-01 07:28:13 -07001162
1163 autoImageUnref.reset(image->newSubset(srcIR));
1164 if (!autoImageUnref) {
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001165 return;
1166 }
halcanaryfcad44b2016-03-06 14:47:10 -08001167 image = autoImageUnref.get();
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001168 // Since we did an extract, we need to adjust the matrix accordingly
1169 SkScalar dx = 0, dy = 0;
1170 if (srcIR.fLeft > 0) {
1171 dx = SkIntToScalar(srcIR.fLeft);
1172 }
1173 if (srcIR.fTop > 0) {
1174 dy = SkIntToScalar(srcIR.fTop);
1175 }
1176 if (dx || dy) {
1177 matrix.preTranslate(dx, dy);
1178 }
1179 }
halcanary7a14b312015-10-01 07:28:13 -07001180 matrix.postConcat(*draw.fMatrix);
1181 this->internalDrawImage(matrix, draw.fClipStack, *draw.fClip, image,
1182 nullptr, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001183}
1184
halcanarybb264b72015-04-07 10:40:03 -07001185// Create a PDF string. Maximum length (in bytes) is 65,535.
1186// @param input A string value.
1187// @param len The length of the input array.
1188// @param wideChars True iff the upper byte in each uint16_t is
1189// significant and should be encoded and not
1190// discarded. If true, the upper byte is encoded
1191// first. Otherwise, we assert the upper byte is
1192// zero.
1193static SkString format_wide_string(const uint16_t* input,
1194 size_t len,
1195 bool wideChars) {
1196 if (wideChars) {
1197 SkASSERT(2 * len < 65535);
1198 static const char gHex[] = "0123456789ABCDEF";
1199 SkString result(4 * len + 2);
1200 result[0] = '<';
1201 for (size_t i = 0; i < len; i++) {
1202 result[4 * i + 1] = gHex[(input[i] >> 12) & 0xF];
1203 result[4 * i + 2] = gHex[(input[i] >> 8) & 0xF];
1204 result[4 * i + 3] = gHex[(input[i] >> 4) & 0xF];
1205 result[4 * i + 4] = gHex[(input[i] ) & 0xF];
1206 }
1207 result[4 * len + 1] = '>';
1208 return result;
1209 } else {
1210 SkASSERT(len <= 65535);
1211 SkString tmp(len);
1212 for (size_t i = 0; i < len; i++) {
1213 SkASSERT(0 == input[i] >> 8);
1214 tmp[i] = static_cast<uint8_t>(input[i]);
1215 }
halcanarybc4696b2015-05-06 10:56:04 -07001216 return SkPDFUtils::FormatString(tmp.c_str(), tmp.size());
halcanarybb264b72015-04-07 10:40:03 -07001217 }
1218}
1219
halcanary66a82f32015-10-12 13:05:04 -07001220static void draw_transparent_text(SkPDFDevice* device,
1221 const SkDraw& d,
1222 const void* text, size_t len,
1223 SkScalar x, SkScalar y,
1224 const SkPaint& srcPaint) {
1225
1226 SkPaint transparent;
1227 if (!SkPDFFont::CanEmbedTypeface(transparent.getTypeface(),
1228 device->getCanon())) {
1229 SkDEBUGFAIL("default typeface should be embeddable");
1230 return; // Avoid infinite loop in release.
1231 }
1232 transparent.setTextSize(srcPaint.getTextSize());
1233 transparent.setColor(SK_ColorTRANSPARENT);
1234 switch (srcPaint.getTextEncoding()) {
1235 case SkPaint::kGlyphID_TextEncoding: {
1236 // Since a glyphId<->Unicode mapping is typeface-specific,
1237 // map back to Unicode first.
1238 size_t glyphCount = len / 2;
1239 SkAutoTMalloc<SkUnichar> unichars(glyphCount);
1240 srcPaint.glyphsToUnichars(
1241 (const uint16_t*)text, SkToInt(glyphCount), &unichars[0]);
1242 transparent.setTextEncoding(SkPaint::kUTF32_TextEncoding);
1243 device->drawText(d, &unichars[0],
1244 glyphCount * sizeof(SkUnichar),
1245 x, y, transparent);
1246 break;
1247 }
1248 case SkPaint::kUTF8_TextEncoding:
1249 case SkPaint::kUTF16_TextEncoding:
1250 case SkPaint::kUTF32_TextEncoding:
1251 transparent.setTextEncoding(srcPaint.getTextEncoding());
1252 device->drawText(d, text, len, x, y, transparent);
1253 break;
1254 default:
1255 SkFAIL("unknown text encoding");
1256 }
1257}
1258
1259
halcanary682ee012016-01-28 10:59:34 -08001260void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
halcanarya6814332015-05-27 08:53:36 -07001261 SkScalar x, SkScalar y, const SkPaint& srcPaint) {
halcanary66a82f32015-10-12 13:05:04 -07001262 if (!SkPDFFont::CanEmbedTypeface(srcPaint.getTypeface(), fCanon)) {
halcanary6950de62015-11-07 05:29:00 -08001263 // https://bug.skia.org/3866
halcanary66a82f32015-10-12 13:05:04 -07001264 SkPath path;
1265 srcPaint.getTextPath(text, len, x, y, &path);
1266 this->drawPath(d, path, srcPaint, &SkMatrix::I(), true);
1267 // Draw text transparently to make it copyable/searchable/accessable.
1268 draw_transparent_text(this, d, text, len, x, y, srcPaint);
1269 return;
1270 }
halcanarya6814332015-05-27 08:53:36 -07001271 SkPaint paint = srcPaint;
1272 replace_srcmode_on_opaque_paint(&paint);
1273
halcanary96fcdcc2015-08-27 07:41:13 -07001274 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1275 if (paint.getMaskFilter() != nullptr) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001276 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1277 // making text unreadable (e.g. same text twice when using CSS shadows).
1278 return;
1279 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001280 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001281 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001282 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001283 return;
1284 }
1285
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001286 SkGlyphStorage storage(0);
halcanary96fcdcc2015-08-27 07:41:13 -07001287 const uint16_t* glyphIDs = nullptr;
reed@google.comaec40662014-04-18 19:29:07 +00001288 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001289 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001290
benjaminwagnerd936f632016-02-23 10:44:31 -08001291 SkPaint::GlyphCacheProc glyphCacheProc = textPaint.getGlyphCacheProc(true);
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001292 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001293 content.entry()->fContent.writeText("BT\n");
1294 set_text_transform(x, y, textPaint.getTextSkewX(),
1295 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001296 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001297
1298 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1299
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001300 while (numGlyphs > consumedGlyphCount) {
robertphillips8e0c1502015-07-07 10:28:43 -07001301 this->updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001302 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001303
1304 int availableGlyphs = font->glyphsToPDFFontEncoding(
1305 glyphIDsCopy.begin() + consumedGlyphCount,
1306 numGlyphs - consumedGlyphCount);
1307 fFontGlyphUsage->noteGlyphUsage(
1308 font, glyphIDsCopy.begin() + consumedGlyphCount,
1309 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001310 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001311 format_wide_string(glyphIDsCopy.begin() + consumedGlyphCount,
1312 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001313 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001314 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001315 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001316 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001317 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001318}
1319
halcanary682ee012016-01-28 10:59:34 -08001320void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001321 const SkScalar pos[], int scalarsPerPos,
halcanary682ee012016-01-28 10:59:34 -08001322 const SkPoint& offset, const SkPaint& srcPaint) {
halcanary66a82f32015-10-12 13:05:04 -07001323 if (!SkPDFFont::CanEmbedTypeface(srcPaint.getTypeface(), fCanon)) {
1324 const SkPoint* positions = reinterpret_cast<const SkPoint*>(pos);
1325 SkAutoTMalloc<SkPoint> positionsBuffer;
1326 if (2 != scalarsPerPos) {
1327 int glyphCount = srcPaint.textToGlyphs(text, len, NULL);
1328 positionsBuffer.reset(glyphCount);
1329 for (int i = 0; i < glyphCount; ++i) {
1330 positionsBuffer[i].set(pos[i], 0.0f);
1331 }
1332 positions = &positionsBuffer[0];
1333 }
1334 SkPath path;
1335 srcPaint.getPosTextPath(text, len, positions, &path);
1336 SkMatrix matrix;
1337 matrix.setTranslate(offset);
1338 this->drawPath(d, path, srcPaint, &matrix, true);
1339 // Draw text transparently to make it copyable/searchable/accessable.
1340 draw_transparent_text(
1341 this, d, text, len, offset.x() + positions[0].x(),
1342 offset.y() + positions[0].y(), srcPaint);
1343 return;
1344 }
1345
halcanarya6814332015-05-27 08:53:36 -07001346 SkPaint paint = srcPaint;
1347 replace_srcmode_on_opaque_paint(&paint);
1348
halcanary96fcdcc2015-08-27 07:41:13 -07001349 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1350 if (paint.getMaskFilter() != nullptr) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001351 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1352 // making text unreadable (e.g. same text twice when using CSS shadows).
1353 return;
1354 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001355 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001356 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001357 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001358 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001359 return;
1360 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001361
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001362 SkGlyphStorage storage(0);
halcanary96fcdcc2015-08-27 07:41:13 -07001363 const uint16_t* glyphIDs = nullptr;
bungeman22edc832014-10-03 07:55:58 -07001364 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001365 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001366
benjaminwagnerd936f632016-02-23 10:44:31 -08001367 SkPaint::GlyphCacheProc glyphCacheProc = textPaint.getGlyphCacheProc(true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001368 content.entry()->fContent.writeText("BT\n");
robertphillips8e0c1502015-07-07 10:28:43 -07001369 this->updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001370 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001371 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001372 uint16_t encodedValue = glyphIDs[i];
1373 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001374 // The current pdf font cannot encode the current glyph.
1375 // Try to get a pdf font which can encode the current glyph.
robertphillips8e0c1502015-07-07 10:28:43 -07001376 this->updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001377 font = content.entry()->fState.fFont;
1378 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1379 SkDEBUGFAIL("PDF could not encode glyph.");
1380 continue;
1381 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001382 }
bungeman22edc832014-10-03 07:55:58 -07001383
vandebo@chromium.org98594282011-07-25 22:34:12 +00001384 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001385 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1386 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1387
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001388 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001389 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001390 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001391 format_wide_string(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001392 content.entry()->fContent.writeText(encodedString.c_str());
1393 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001394 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001395 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001396}
1397
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001398void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001399 int vertexCount, const SkPoint verts[],
1400 const SkPoint texs[], const SkColor colors[],
1401 SkXfermode* xmode, const uint16_t indices[],
1402 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001403 if (d.fClip->isEmpty()) {
1404 return;
1405 }
reed@google.com85e143c2013-12-30 15:51:25 +00001406 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001407}
1408
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001409void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1410 int x, int y, const SkPaint& paint) {
fmalita6987dca2014-11-13 08:33:37 -08001411 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001412 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001413
1414 SkScalar scalarX = SkIntToScalar(x);
1415 SkScalar scalarY = SkIntToScalar(y);
halcanary91fcb3e2016-03-04 13:53:22 -08001416 for (const RectWithData& l : pdfDevice->fLinkToURLs) {
1417 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001418 fLinkToURLs.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001419 }
halcanary91fcb3e2016-03-04 13:53:22 -08001420 for (const RectWithData& l : pdfDevice->fLinkToDestinations) {
1421 SkRect r = l.rect.makeOffset(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001422 fLinkToDestinations.emplace_back(r, l.data.get());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001423 }
halcanary91fcb3e2016-03-04 13:53:22 -08001424 for (const NamedDestination& d : pdfDevice->fNamedDestinations) {
1425 SkPoint p = d.point + SkPoint::Make(scalarX, scalarY);
halcanaryd7b28852016-03-07 12:39:14 -08001426 fNamedDestinations.emplace_back(d.nameData.get(), p);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001427 }
1428
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001429 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001430 return;
1431 }
1432
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001433 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001434 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001435 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001436 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001437 return;
1438 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001439 if (content.needShape()) {
1440 SkPath shape;
1441 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001442 SkIntToScalar(device->width()),
1443 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001444 content.setShape(shape);
1445 }
1446 if (!content.needSource()) {
1447 return;
1448 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001449
halcanaryece83922016-03-08 08:32:12 -08001450 auto xObject = sk_make_sp<SkPDFFormXObject>(pdfDevice);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001451 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001452 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001453
1454 // Merge glyph sets from the drawn device.
1455 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001456}
1457
reed89443ab2014-06-27 11:34:19 -07001458SkImageInfo SkPDFDevice::imageInfo() const {
1459 return fLegacyBitmap.info();
1460}
1461
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001462void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1463 INHERITED::onAttachToCanvas(canvas);
1464
1465 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1466 fClipStack = canvas->getClipStack();
1467}
1468
1469void SkPDFDevice::onDetachFromCanvas() {
1470 INHERITED::onDetachFromCanvas();
1471
halcanary96fcdcc2015-08-27 07:41:13 -07001472 fClipStack = nullptr;
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001473}
1474
reed4a8126e2014-09-22 07:29:03 -07001475SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1476 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001477}
1478
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001479ContentEntry* SkPDFDevice::getLastContentEntry() {
1480 if (fDrawingArea == kContent_DrawingArea) {
1481 return fLastContentEntry;
1482 } else {
1483 return fLastMarginContentEntry;
1484 }
1485}
1486
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001487SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001488 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001489 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001490 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001491 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001492 }
1493}
1494
1495void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1496 if (fDrawingArea == kContent_DrawingArea) {
1497 fLastContentEntry = contentEntry;
1498 } else {
1499 fLastMarginContentEntry = contentEntry;
1500 }
1501}
1502
1503void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001504 // A ScopedContentEntry only exists during the course of a draw call, so
1505 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001506 fDrawingArea = drawingArea;
1507}
1508
halcanary8103a342016-03-08 15:10:16 -08001509sk_sp<SkPDFDict> SkPDFDevice::makeResourceDict() const {
halcanary2b861552015-04-09 13:27:40 -07001510 SkTDArray<SkPDFObject*> fonts;
1511 fonts.setReserve(fFontResources.count());
1512 for (SkPDFFont* font : fFontResources) {
1513 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001514 }
halcanary8103a342016-03-08 15:10:16 -08001515 return SkPDFResourceDict::Make(
halcanary2b861552015-04-09 13:27:40 -07001516 &fGraphicStateResources,
1517 &fShaderResources,
1518 &fXObjectResources,
1519 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001520}
1521
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001522const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1523 return fFontResources;
1524}
1525
halcanary8103a342016-03-08 15:10:16 -08001526sk_sp<SkPDFArray> SkPDFDevice::copyMediaBox() const {
halcanaryece83922016-03-08 08:32:12 -08001527 auto mediaBox = sk_make_sp<SkPDFArray>();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001528 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001529 mediaBox->appendInt(0);
1530 mediaBox->appendInt(0);
halcanary8103a342016-03-08 15:10:16 -08001531 mediaBox->appendInt(fPageSize.width());
1532 mediaBox->appendInt(fPageSize.height());
1533 return mediaBox;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001534}
1535
mtklein218c8462016-03-11 06:10:30 -08001536skstd::unique_ptr<SkStreamAsset> SkPDFDevice::content() const {
halcanary334fcbc2015-02-24 12:56:16 -08001537 SkDynamicMemoryWStream buffer;
1538 this->writeContent(&buffer);
mtklein218c8462016-03-11 06:10:30 -08001539 return skstd::unique_ptr<SkStreamAsset>(
halcanary8103a342016-03-08 15:10:16 -08001540 buffer.bytesWritten() > 0
1541 ? buffer.detachAsStream()
1542 : new SkMemoryStream);
reed@google.com5667afc2011-06-27 14:42:15 +00001543}
1544
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001545void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1546 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001547 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1548 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001549 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
halcanary96fcdcc2015-08-27 07:41:13 -07001550 while (entry != nullptr) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001551 SkPoint translation;
1552 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001553 translation.negate();
1554 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1555 translation);
1556 gsState.updateMatrix(entry->fState.fMatrix);
1557 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001558
halcanary7af21502015-02-23 12:17:59 -08001559 entry->fContent.writeToStream(data);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001560 entry = entry->fNext.get();
1561 }
1562 gsState.drainStack();
1563}
1564
halcanary334fcbc2015-02-24 12:56:16 -08001565void SkPDFDevice::writeContent(SkWStream* out) const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001566 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanary334fcbc2015-02-24 12:56:16 -08001567 SkPDFUtils::AppendTransform(fInitialTransform, out);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001568 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001569
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001570 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1571 // colors the contentArea white before it starts drawing into it and
1572 // that currently acts as our clip.
1573 // Also, think about adding a transform here (or assume that the values
1574 // sent across account for that)
halcanary334fcbc2015-02-24 12:56:16 -08001575 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), out);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001576
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001577 // If the content area is the entire page, then we don't need to clip
1578 // the content area (PDF area clips to the page size). Otherwise,
1579 // we have to clip to the content area; we've already applied the
1580 // initial transform, so just clip to the device size.
1581 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001582 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1583 SkIntToScalar(this->height()));
halcanary96fcdcc2015-08-27 07:41:13 -07001584 emit_clip(nullptr, &r, out);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001585 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001586
halcanary334fcbc2015-02-24 12:56:16 -08001587 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), out);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001588}
1589
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001590/* Draws an inverse filled path by using Path Ops to compute the positive
1591 * inverse using the current clip as the inverse bounds.
1592 * Return true if this was an inverse path and was properly handled,
1593 * otherwise returns false and the normal drawing routine should continue,
1594 * either as a (incorrect) fallback or because the path was not inverse
1595 * in the first place.
1596 */
1597bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001598 const SkPaint& paint, bool pathIsMutable,
1599 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001600 if (!origPath.isInverseFillType()) {
1601 return false;
1602 }
1603
1604 if (d.fClip->isEmpty()) {
1605 return false;
1606 }
1607
1608 SkPath modifiedPath;
1609 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1610 SkPaint noInversePaint(paint);
1611
1612 // Merge stroking operations into final path.
1613 if (SkPaint::kStroke_Style == paint.getStyle() ||
1614 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1615 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1616 if (doFillPath) {
1617 noInversePaint.setStyle(SkPaint::kFill_Style);
1618 noInversePaint.setStrokeWidth(0);
1619 pathPtr = &modifiedPath;
1620 } else {
1621 // To be consistent with the raster output, hairline strokes
1622 // are rendered as non-inverted.
1623 modifiedPath.toggleInverseFillType();
halcanary96fcdcc2015-08-27 07:41:13 -07001624 drawPath(d, modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001625 return true;
1626 }
1627 }
1628
1629 // Get bounds of clip in current transform space
1630 // (clip bounds are given in device space).
1631 SkRect bounds;
1632 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001633 SkMatrix totalMatrix = *d.fMatrix;
1634 if (prePathMatrix) {
1635 totalMatrix.preConcat(*prePathMatrix);
1636 }
1637 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001638 return false;
1639 }
1640 bounds.set(d.fClip->getBounds());
1641 transformInverse.mapRect(&bounds);
1642
1643 // Extend the bounds by the line width (plus some padding)
1644 // so the edge doesn't cause a visible stroke.
1645 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1646 paint.getStrokeWidth() + SK_Scalar1);
1647
1648 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1649 return false;
1650 }
1651
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001652 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001653 return true;
1654}
1655
reedf70b5312016-03-04 16:36:20 -08001656void SkPDFDevice::handlePointAnnotation(const SkPoint& point,
epoger@google.comb58772f2013-03-08 09:09:10 +00001657 const SkMatrix& matrix,
reedf70b5312016-03-04 16:36:20 -08001658 const char key[], SkData* value) {
1659 if (!value) {
1660 return;
epoger@google.comb58772f2013-03-08 09:09:10 +00001661 }
reedf70b5312016-03-04 16:36:20 -08001662
1663 if (!strcmp(SkAnnotationKeys::Define_Named_Dest_Key(), key)) {
1664 SkPoint transformedPoint;
1665 matrix.mapXY(point.x(), point.y(), &transformedPoint);
1666 fNamedDestinations.emplace_back(value, transformedPoint);
1667 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001668}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001669
reedf70b5312016-03-04 16:36:20 -08001670void SkPDFDevice::handlePathAnnotation(const SkPath& path,
wangxianzhuef6c50a2015-09-17 20:38:02 -07001671 const SkDraw& d,
reedf70b5312016-03-04 16:36:20 -08001672 const char key[], SkData* value) {
1673 if (!value) {
1674 return;
1675 }
wangxianzhuef6c50a2015-09-17 20:38:02 -07001676
1677 SkPath transformedPath = path;
1678 transformedPath.transform(*d.fMatrix);
1679 SkRasterClip clip = *d.fRC;
senorblancoafc7cce2016-02-02 18:44:15 -08001680 clip.op(transformedPath, SkIRect::MakeWH(width(), height()), SkRegion::kIntersect_Op,
1681 false);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001682 SkRect transformedRect = SkRect::Make(clip.getBounds());
1683
reedf70b5312016-03-04 16:36:20 -08001684 if (!strcmp(SkAnnotationKeys::URL_Key(), key)) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001685 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001686 fLinkToURLs.emplace_back(transformedRect, value);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001687 }
reedf70b5312016-03-04 16:36:20 -08001688 } else if (!strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) {
reed16108352016-03-03 09:14:36 -08001689 if (!transformedRect.isEmpty()) {
reedf70b5312016-03-04 16:36:20 -08001690 fLinkToDestinations.emplace_back(transformedRect, value);
reed16108352016-03-03 09:14:36 -08001691 }
reed16108352016-03-03 09:14:36 -08001692 }
halcanary438de492015-04-28 06:21:01 -07001693}
1694
wangxianzhuef6c50a2015-09-17 20:38:02 -07001695void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1696 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
halcanary91fcb3e2016-03-04 13:53:22 -08001697 for (const RectWithData& rectWithURL : fLinkToURLs) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001698 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001699 fInitialTransform.mapRect(&r, rectWithURL.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001700 array->appendObject(create_link_to_url(rectWithURL.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001701 }
halcanary91fcb3e2016-03-04 13:53:22 -08001702 for (const RectWithData& linkToDestination : fLinkToDestinations) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001703 SkRect r;
halcanary91fcb3e2016-03-04 13:53:22 -08001704 fInitialTransform.mapRect(&r, linkToDestination.rect);
halcanaryd7b28852016-03-07 12:39:14 -08001705 array->appendObject(
1706 create_link_named_dest(linkToDestination.data.get(), r));
wangxianzhuef6c50a2015-09-17 20:38:02 -07001707 }
1708}
epoger@google.comb58772f2013-03-08 09:09:10 +00001709
halcanary6d622702015-03-25 08:45:42 -07001710void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
halcanary91fcb3e2016-03-04 13:53:22 -08001711 for (const NamedDestination& dest : fNamedDestinations) {
halcanaryece83922016-03-08 08:32:12 -08001712 auto pdfDest = sk_make_sp<SkPDFArray>();
epoger@google.comb58772f2013-03-08 09:09:10 +00001713 pdfDest->reserve(5);
halcanarye94ea622016-03-09 07:52:09 -08001714 pdfDest->appendObjRef(sk_ref_sp(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001715 pdfDest->appendName("XYZ");
halcanary91fcb3e2016-03-04 13:53:22 -08001716 SkPoint p = fInitialTransform.mapXY(dest.point.x(), dest.point.y());
wangxianzhuef6c50a2015-09-17 20:38:02 -07001717 pdfDest->appendScalar(p.x());
1718 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001719 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary91fcb3e2016-03-04 13:53:22 -08001720 SkString name(static_cast<const char*>(dest.nameData->data()));
halcanary8103a342016-03-08 15:10:16 -08001721 dict->insertObject(name, std::move(pdfDest));
epoger@google.comb58772f2013-03-08 09:09:10 +00001722 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001723}
1724
reed@google.comfc641d02012-09-20 17:52:20 +00001725SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
halcanary385fe4d2015-08-26 13:07:48 -07001726 SkPDFFormXObject* xobject = new SkPDFFormXObject(this);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001727 // We always draw the form xobjects that we create back into the device, so
1728 // we simply preserve the font usage instead of pulling it out and merging
1729 // it back in later.
1730 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001731 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001732 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001733}
1734
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001735void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1736 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001737 const SkClipStack* clipStack,
1738 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001739 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001740 bool invertClip) {
1741 if (clipRegion.isEmpty() && !invertClip) {
1742 return;
1743 }
1744
halcanary1437c1e2016-03-13 18:30:24 -07001745 auto sMaskGS = SkPDFGraphicState::GetSMaskGraphicState(
1746 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode, fCanon);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001747
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001748 SkMatrix identity;
1749 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001750 SkPaint paint;
1751 paint.setXfermodeMode(mode);
1752 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001753 if (!content.entry()) {
1754 return;
1755 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001756 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001757 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001758 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001759
halcanary1437c1e2016-03-13 18:30:24 -07001760 // Call makeNoSmaskGraphicState() instead of
1761 // SkPDFGraphicState::MakeNoSmaskGraphicState so that the canon
1762 // can deduplicate.
1763 sMaskGS = fCanon->makeNoSmaskGraphicState();
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001764 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001765 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001766}
1767
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001768ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1769 const SkRegion& clipRegion,
1770 const SkMatrix& matrix,
1771 const SkPaint& paint,
1772 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001773 SkPDFFormXObject** dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001774 *dst = nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001775 if (clipRegion.isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -07001776 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001777 }
1778
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001779 // The clip stack can come from an SkDraw where it is technically optional.
1780 SkClipStack synthesizedClipStack;
halcanary96fcdcc2015-08-27 07:41:13 -07001781 if (clipStack == nullptr) {
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001782 if (clipRegion == fExistingClipRegion) {
1783 clipStack = &fExistingClipStack;
1784 } else {
1785 // GraphicStackState::updateClip expects the clip stack to have
1786 // fExistingClip as a prefix, so start there, then set the clip
1787 // to the passed region.
1788 synthesizedClipStack = fExistingClipStack;
1789 SkPath clipPath;
1790 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001791 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1792 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001793 clipStack = &synthesizedClipStack;
1794 }
1795 }
1796
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001797 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1798 if (paint.getXfermode()) {
1799 paint.getXfermode()->asMode(&xfermode);
1800 }
1801
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001802 // For the following modes, we want to handle source and destination
1803 // separately, so make an object of what's already there.
1804 if (xfermode == SkXfermode::kClear_Mode ||
1805 xfermode == SkXfermode::kSrc_Mode ||
1806 xfermode == SkXfermode::kSrcIn_Mode ||
1807 xfermode == SkXfermode::kDstIn_Mode ||
1808 xfermode == SkXfermode::kSrcOut_Mode ||
1809 xfermode == SkXfermode::kDstOut_Mode ||
1810 xfermode == SkXfermode::kSrcATop_Mode ||
1811 xfermode == SkXfermode::kDstATop_Mode ||
1812 xfermode == SkXfermode::kModulate_Mode) {
1813 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001814 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001815 SkASSERT(isContentEmpty());
1816 } else if (xfermode != SkXfermode::kSrc_Mode &&
1817 xfermode != SkXfermode::kSrcOut_Mode) {
1818 // Except for Src and SrcOut, if there isn't anything already there,
1819 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001820 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001821 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001822 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001823 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001824 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001825
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001826 // Dst xfer mode doesn't draw source at all.
1827 if (xfermode == SkXfermode::kDst_Mode) {
halcanary96fcdcc2015-08-27 07:41:13 -07001828 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001829 }
1830
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001831 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001832 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001833
1834 ContentEntry* lastContentEntry = getLastContentEntry();
1835 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1836 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001837 } else {
1838 newEntry.reset(new ContentEntry);
1839 entry = newEntry.get();
1840 }
1841
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001842 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001843 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001844 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1845 entry->fState.compareInitialState(lastContentEntry->fState)) {
1846 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001847 }
1848
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001849 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001850 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001851 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001852 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001853 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001854 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001855 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001856 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001857 lastContentEntry->fNext.reset(entry);
1858 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001859 }
halcanaryfcad44b2016-03-06 14:47:10 -08001860 newEntry.release();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001861 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001862}
1863
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001864void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001865 SkPDFFormXObject* dst,
1866 SkPath* shape) {
1867 if (xfermode != SkXfermode::kClear_Mode &&
1868 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001869 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001870 xfermode != SkXfermode::kSrcIn_Mode &&
1871 xfermode != SkXfermode::kDstIn_Mode &&
1872 xfermode != SkXfermode::kSrcOut_Mode &&
1873 xfermode != SkXfermode::kDstOut_Mode &&
1874 xfermode != SkXfermode::kSrcATop_Mode &&
1875 xfermode != SkXfermode::kDstATop_Mode &&
1876 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001877 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001878 return;
1879 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001880 if (xfermode == SkXfermode::kDstOver_Mode) {
1881 SkASSERT(!dst);
1882 ContentEntry* firstContentEntry = getContentEntries()->get();
1883 if (firstContentEntry->fContent.getOffset() == 0) {
1884 // For DstOver, an empty content entry was inserted before the rest
1885 // of the content entries. If nothing was drawn, it needs to be
1886 // removed.
1887 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1888 contentEntries->reset(firstContentEntry->fNext.detach());
1889 }
1890 return;
1891 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001892 if (!dst) {
1893 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1894 xfermode == SkXfermode::kSrcOut_Mode);
1895 return;
1896 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001897
1898 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001899 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001900 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001901 // Changing the current content into a form-xobject will destroy the clip
1902 // objects which is fine since the xobject will already be clipped. However
1903 // if source has shape, we need to clip it too, so a copy of the clip is
1904 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001905 SkClipStack clipStack = contentEntries->fState.fClipStack;
1906 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001907
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001908 SkMatrix identity;
1909 identity.reset();
1910 SkPaint stockPaint;
1911
halcanary48810a02016-03-07 14:57:50 -08001912 sk_sp<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001913 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001914 // If nothing was drawn and there's no shape, then the draw was a
1915 // no-op, but dst needs to be restored for that to be true.
1916 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1917 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1918 // reduces to Dst.
halcanary96fcdcc2015-08-27 07:41:13 -07001919 if (shape == nullptr || xfermode == SkXfermode::kDstOut_Mode ||
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001920 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001921 ScopedContentEntry content(this, &fExistingClipStack,
1922 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001923 stockPaint);
1924 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1925 &content.entry()->fContent);
1926 return;
1927 } else {
1928 xfermode = SkXfermode::kClear_Mode;
1929 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001930 } else {
1931 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001932 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001933 }
1934
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001935 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1936 // without alpha.
1937 if (xfermode == SkXfermode::kSrcATop_Mode) {
1938 // TODO(vandebo): In order to properly support SrcATop we have to track
1939 // the shape of what's been drawn at all times. It's the intersection of
1940 // the non-transparent parts of the device and the outlines (shape) of
1941 // all images and devices drawn.
1942 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001943 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001944 SkXfermode::kSrcOver_Mode, true);
1945 } else {
halcanary48810a02016-03-07 14:57:50 -08001946 sk_sp<SkPDFFormXObject> dstMaskStorage;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001947 SkPDFFormXObject* dstMask = srcFormXObject.get();
halcanary96fcdcc2015-08-27 07:41:13 -07001948 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001949 // Draw shape into a form-xobject.
1950 SkDraw d;
1951 d.fMatrix = &identity;
1952 d.fClip = &clipRegion;
1953 d.fClipStack = &clipStack;
1954 SkPaint filledPaint;
1955 filledPaint.setColor(SK_ColorBLACK);
1956 filledPaint.setStyle(SkPaint::kFill_Style);
halcanary96fcdcc2015-08-27 07:41:13 -07001957 this->drawPath(d, *shape, filledPaint, nullptr, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001958
1959 dstMaskStorage.reset(createFormXObjectFromDevice());
1960 dstMask = dstMaskStorage.get();
1961 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001962 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1963 &fExistingClipStack, fExistingClipRegion,
1964 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001965 }
1966
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001967 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001968 return;
1969 } else if (xfermode == SkXfermode::kSrc_Mode ||
1970 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001971 ScopedContentEntry content(this, &fExistingClipStack,
1972 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001973 if (content.entry()) {
1974 SkPDFUtils::DrawFormXObject(
1975 this->addXObjectResource(srcFormXObject.get()),
1976 &content.entry()->fContent);
1977 }
1978 if (xfermode == SkXfermode::kSrc_Mode) {
1979 return;
1980 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001981 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001982 ScopedContentEntry content(this, &fExistingClipStack,
1983 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001984 if (content.entry()) {
1985 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1986 &content.entry()->fContent);
1987 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001988 }
1989
1990 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1991 xfermode == SkXfermode::kDstIn_Mode ||
1992 xfermode == SkXfermode::kSrcOut_Mode ||
1993 xfermode == SkXfermode::kDstOut_Mode ||
1994 xfermode == SkXfermode::kSrcATop_Mode ||
1995 xfermode == SkXfermode::kDstATop_Mode ||
1996 xfermode == SkXfermode::kModulate_Mode);
1997
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001998 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001999 xfermode == SkXfermode::kSrcOut_Mode ||
2000 xfermode == SkXfermode::kSrcATop_Mode) {
2001 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002002 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002003 SkXfermode::kSrcOver_Mode,
2004 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002005 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002006 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
2007 if (xfermode == SkXfermode::kModulate_Mode) {
2008 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002009 dst, &fExistingClipStack,
2010 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002011 SkXfermode::kSrcOver_Mode, false);
2012 mode = SkXfermode::kMultiply_Mode;
2013 }
2014 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002015 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002016 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002017 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002018}
2019
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002020bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002021 ContentEntry* contentEntries = getContentEntries()->get();
2022 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
2023 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002024 return true;
2025 }
2026 return false;
2027}
2028
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002029void SkPDFDevice::populateGraphicStateEntryFromPaint(
2030 const SkMatrix& matrix,
2031 const SkClipStack& clipStack,
2032 const SkRegion& clipRegion,
2033 const SkPaint& paint,
2034 bool hasText,
2035 GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07002036 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
2037 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
2038 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002039
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002040 entry->fMatrix = matrix;
2041 entry->fClipStack = clipStack;
2042 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002043 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2044 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002045
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002046 // PDF treats a shader as a color, so we only set one or the other.
halcanary48810a02016-03-07 14:57:50 -08002047 sk_sp<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002048 const SkShader* shader = paint.getShader();
2049 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002050 if (shader) {
2051 // PDF positions patterns relative to the initial transform, so
2052 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002053 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00002054 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002055
2056 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002057 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002058 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00002059
2060 // We need to apply the initial transform to bounds in order to get
2061 // bounds in a consistent coordinate system.
2062 SkRect boundsTemp;
2063 boundsTemp.set(bounds);
2064 fInitialTransform.mapRect(&boundsTemp);
2065 boundsTemp.roundOut(&bounds);
2066
halcanary792c80f2015-02-20 07:21:05 -08002067 SkScalar rasterScale =
2068 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
2069 pdfShader.reset(SkPDFShader::GetPDFShader(
2070 fCanon, fRasterDpi, *shader, transform, bounds, rasterScale));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002071
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002072 if (pdfShader.get()) {
2073 // pdfShader has been canonicalized so we can directly compare
2074 // pointers.
2075 int resourceIndex = fShaderResources.find(pdfShader.get());
2076 if (resourceIndex < 0) {
2077 resourceIndex = fShaderResources.count();
2078 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002079 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002080 }
2081 entry->fShaderIndex = resourceIndex;
2082 } else {
2083 // A color shader is treated as an invalid shader so we don't have
2084 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002085 SkShader::GradientInfo gradientInfo;
2086 SkColor gradientColor;
2087 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07002088 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002089 gradientInfo.fColorCount = 1;
2090 if (shader->asAGradient(&gradientInfo) ==
2091 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002092 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2093 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002094 }
2095 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002096 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002097
halcanary48810a02016-03-07 14:57:50 -08002098 sk_sp<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002099 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002100 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08002101 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002102 } else {
2103 SkPaint newPaint = paint;
2104 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002105 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08002106 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002107 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002108 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002109 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002110
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002111 if (hasText) {
2112 entry->fTextScaleX = paint.getTextScaleX();
2113 entry->fTextFill = paint.getStyle();
2114 } else {
2115 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002116 }
2117}
2118
halcanarybe27a112015-04-01 13:31:19 -07002119int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002120 // Assumes that gs has been canonicalized (so we can directly compare
2121 // pointers).
2122 int result = fGraphicStateResources.find(gs);
2123 if (result < 0) {
2124 result = fGraphicStateResources.count();
2125 fGraphicStateResources.push(gs);
2126 gs->ref();
2127 }
2128 return result;
2129}
2130
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002131int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2132 // Assumes that xobject has been canonicalized (so we can directly compare
2133 // pointers).
2134 int result = fXObjectResources.find(xObject);
2135 if (result < 0) {
2136 result = fXObjectResources.count();
2137 fXObjectResources.push(xObject);
2138 xObject->ref();
2139 }
2140 return result;
2141}
2142
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002143void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2144 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002145 SkTypeface* typeface = paint.getTypeface();
halcanary96fcdcc2015-08-27 07:41:13 -07002146 if (contentEntry->fState.fFont == nullptr ||
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002147 contentEntry->fState.fTextSize != paint.getTextSize() ||
2148 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002149 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002150 contentEntry->fContent.writeText("/");
2151 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2152 SkPDFResourceDict::kFont_ResourceType,
2153 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002154 contentEntry->fContent.writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -07002155 SkPDFUtils::AppendScalar(paint.getTextSize(), &contentEntry->fContent);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002156 contentEntry->fContent.writeText(" Tf\n");
2157 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002158 }
2159}
2160
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002161int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary48810a02016-03-07 14:57:50 -08002162 sk_sp<SkPDFFont> newFont(
halcanary792c80f2015-02-20 07:21:05 -08002163 SkPDFFont::GetFontResource(fCanon, typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002164 int resourceIndex = fFontResources.find(newFont.get());
2165 if (resourceIndex < 0) {
2166 resourceIndex = fFontResources.count();
2167 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002168 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002169 }
2170 return resourceIndex;
2171}
2172
halcanary7a14b312015-10-01 07:28:13 -07002173static SkSize rect_to_size(const SkRect& r) {
2174 return SkSize::Make(r.width(), r.height());
2175}
2176
2177static const SkImage* color_filter(const SkImage* image,
2178 SkColorFilter* colorFilter) {
halcanary48810a02016-03-07 14:57:50 -08002179 sk_sp<SkSurface> surface(SkSurface::NewRaster(
halcanary7a14b312015-10-01 07:28:13 -07002180 SkImageInfo::MakeN32Premul(image->dimensions())));
2181 if (!surface) {
2182 return image;
2183 }
2184 SkCanvas* canvas = surface->getCanvas();
2185 canvas->clear(SK_ColorTRANSPARENT);
2186 SkPaint paint;
2187 paint.setColorFilter(colorFilter);
2188 canvas->drawImage(image, 0, 0, &paint);
2189 canvas->flush();
2190 return surface->newImageSnapshot();
2191}
2192
2193////////////////////////////////////////////////////////////////////////////////
2194void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
2195 const SkClipStack* clipStack,
2196 const SkRegion& origClipRegion,
2197 const SkImage* image,
2198 const SkIRect* srcRect,
2199 const SkPaint& paint) {
2200 SkASSERT(image);
2201 #ifdef SK_PDF_IMAGE_STATS
2202 gDrawImageCalls.fetch_add(1);
2203 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002204 SkMatrix matrix = origMatrix;
2205 SkRegion perspectiveBounds;
2206 const SkRegion* clipRegion = &origClipRegion;
halcanary48810a02016-03-07 14:57:50 -08002207 sk_sp<const SkImage> autoImageUnref;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002208
halcanary7a14b312015-10-01 07:28:13 -07002209 if (srcRect) {
2210 autoImageUnref.reset(image->newSubset(*srcRect));
2211 if (!autoImageUnref) {
2212 return;
2213 }
halcanaryfcad44b2016-03-06 14:47:10 -08002214 image = autoImageUnref.get();
halcanary7a14b312015-10-01 07:28:13 -07002215 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002216 // Rasterize the bitmap using perspective in a new bitmap.
2217 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002218 if (fRasterDpi == 0) {
2219 return;
2220 }
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002221 // Transform the bitmap in the new space, without taking into
2222 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002223 SkPath perspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002224 SkRect imageBounds = SkRect::Make(image->bounds());
2225 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002226 perspectiveOutline.transform(origMatrix);
2227
2228 // TODO(edisonn): perf - use current clip too.
2229 // Retrieve the bounds of the new shape.
2230 SkRect bounds = perspectiveOutline.getBounds();
2231
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002232 // Transform the bitmap in the new space, taking into
2233 // account the initial transform.
2234 SkMatrix total = origMatrix;
2235 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002236 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2237 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2238 total.postScale(dpiScale, dpiScale);
2239
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002240 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002241 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002242 physicalPerspectiveOutline.transform(total);
2243
halcanary7a14b312015-10-01 07:28:13 -07002244 SkRect physicalPerspectiveBounds =
2245 physicalPerspectiveOutline.getBounds();
2246 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2247 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002248
2249 // TODO(edisonn): A better approach would be to use a bitmap shader
2250 // (in clamp mode) and draw a rect over the entire bounding box. Then
2251 // intersect perspectiveOutline to the clip. That will avoid introducing
2252 // alpha to the image while still giving good behavior at the edge of
2253 // the image. Avoiding alpha will reduce the pdf size and generation
2254 // CPU time some.
2255
halcanary7a14b312015-10-01 07:28:13 -07002256 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2257
halcanary48810a02016-03-07 14:57:50 -08002258 sk_sp<SkSurface> surface(
halcanary7a14b312015-10-01 07:28:13 -07002259 SkSurface::NewRaster(SkImageInfo::MakeN32Premul(wh)));
2260 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002261 return;
2262 }
halcanary7a14b312015-10-01 07:28:13 -07002263 SkCanvas* canvas = surface->getCanvas();
2264 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002265
2266 SkScalar deltaX = bounds.left();
2267 SkScalar deltaY = bounds.top();
2268
2269 SkMatrix offsetMatrix = origMatrix;
2270 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002271 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002272
2273 // Translate the draw in the new canvas, so we perfectly fit the
2274 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002275 canvas->setMatrix(offsetMatrix);
2276 canvas->drawImage(image, 0, 0, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002277 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002278 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002279
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002280 // In the new space, we use the identity matrix translated
2281 // and scaled to reflect DPI.
2282 matrix.setScale(1 / scaleX, 1 / scaleY);
2283 matrix.postTranslate(deltaX, deltaY);
2284
halcanary7a14b312015-10-01 07:28:13 -07002285 perspectiveBounds.setRect(bounds.roundOut());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002286 clipRegion = &perspectiveBounds;
halcanary96fcdcc2015-08-27 07:41:13 -07002287 srcRect = nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002288
2289 autoImageUnref.reset(surface->newImageSnapshot());
halcanaryfcad44b2016-03-06 14:47:10 -08002290 image = autoImageUnref.get();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002291 }
2292
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002293 SkMatrix scaled;
2294 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002295 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2296 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002297 // Scale the image up from 1x1 to WxH.
halcanary7a14b312015-10-01 07:28:13 -07002298 SkIRect subset = image->bounds();
2299 scaled.postScale(SkIntToScalar(image->width()),
2300 SkIntToScalar(image->height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002301 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002302 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002303 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2304 return;
2305 }
2306 if (content.needShape()) {
2307 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002308 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002309 shape.transform(matrix);
2310 content.setShape(shape);
2311 }
2312 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002313 return;
2314 }
2315
halcanary287d22d2015-09-24 10:20:05 -07002316 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002317 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002318 // draw calls. This code here works for all
2319 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2320 // rasterize a layer on this backend). Fortuanely, this seems
2321 // to be how Chromium impements most color-filters.
2322 autoImageUnref.reset(color_filter(image, colorFilter));
halcanaryfcad44b2016-03-06 14:47:10 -08002323 image = autoImageUnref.get();
halcanary7a14b312015-10-01 07:28:13 -07002324 // TODO(halcanary): de-dupe this by caching filtered images.
2325 // (maybe in the resource cache?)
2326 }
halcanary48810a02016-03-07 14:57:50 -08002327 sk_sp<SkPDFObject> pdfimage(SkSafeRef(fCanon->findPDFBitmap(image)));
halcanary7a14b312015-10-01 07:28:13 -07002328 if (!pdfimage) {
halcanary712fdf72015-12-10 08:59:43 -08002329 pdfimage.reset(SkPDFCreateBitmapObject(
halcanaryfcad44b2016-03-06 14:47:10 -08002330 image, fCanon->getPixelSerializer()));
halcanary7a14b312015-10-01 07:28:13 -07002331 if (!pdfimage) {
2332 return;
halcanary287d22d2015-09-24 10:20:05 -07002333 }
halcanaryfcad44b2016-03-06 14:47:10 -08002334 fCanon->addPDFBitmap(image->uniqueID(), pdfimage.get());
halcanary287d22d2015-09-24 10:20:05 -07002335 }
halcanary3d8c33c2015-10-01 11:06:22 -07002336 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002337 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002338}