blob: 315c84317d72c42abc3da60b7e388d463b3a9c22 [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
vandebo@chromium.org238be8c2012-07-13 20:06:02 +000010#include "SkAnnotation.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"
reed@google.com8a85d0c2011-06-24 19:12:12 +000014#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000015#include "SkDraw.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000016#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000017#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000018#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000019#include "SkPathOps.h"
halcanarydb0dcc72015-03-20 12:31:52 -070020#include "SkPDFBitmap.h"
halcanary7a14b312015-10-01 07:28:13 -070021#include "SkPDFCanon.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000022#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000023#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000024#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000025#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000026#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000027#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000028#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000029#include "SkPDFUtils.h"
wangxianzhuef6c50a2015-09-17 20:38:02 -070030#include "SkRasterClip.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000031#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000032#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000033#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070034#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000035#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000036#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000037#include "SkTypefacePriv.h"
halcanarya6814332015-05-27 08:53:36 -070038#include "SkXfermodeInterpretation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000039
edisonn@google.com73a7ea32013-11-11 20:55:15 +000040#define DPI_FOR_RASTER_SCALE_ONE 72
41
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000042// Utility functions
43
halcanarya6814332015-05-27 08:53:36 -070044// If the paint will definitely draw opaquely, replace kSrc_Mode with
45// kSrcOver_Mode. http://crbug.com/473572
46static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
47 if (kSrcOver_SkXfermodeInterpretation
48 == SkInterpretXfermode(*paint, false)) {
halcanary96fcdcc2015-08-27 07:41:13 -070049 paint->setXfermode(nullptr);
halcanarya6814332015-05-27 08:53:36 -070050 }
51}
52
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000053static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000054 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
reed80ea19c2015-05-12 10:37:34 -070055 SkScalar colorScale = SkScalarInvert(0xFF);
56 SkPDFUtils::AppendScalar(SkColorGetR(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000057 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070058 SkPDFUtils::AppendScalar(SkColorGetG(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000059 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070060 SkPDFUtils::AppendScalar(SkColorGetB(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000061 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000062}
63
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000064static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000065 SkPaint result = paint;
66 if (result.isFakeBoldText()) {
67 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
68 kStdFakeBoldInterpKeys,
69 kStdFakeBoldInterpValues,
70 kStdFakeBoldInterpLength);
71 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000072 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000073 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000074 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000075 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000076 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000077 result.setStrokeWidth(width);
78 }
79 return result;
80}
81
82// Stolen from measure_text in SkDraw.cpp and then tweaked.
benjaminwagnerd936f632016-02-23 10:44:31 -080083static void align_text(SkPaint::GlyphCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000084 const uint16_t* glyphs, size_t len,
85 SkScalar* x, SkScalar* y) {
86 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000087 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000088 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000089
90 SkMatrix ident;
91 ident.reset();
halcanary96fcdcc2015-08-27 07:41:13 -070092 SkAutoGlyphCache autoCache(paint, nullptr, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000093 SkGlyphCache* cache = autoCache.getCache();
94
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000095 const char* start = reinterpret_cast<const char*>(glyphs);
96 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000097 SkFixed xAdv = 0, yAdv = 0;
98
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000099 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000100 while (start < stop) {
benjaminwagnerd936f632016-02-23 10:44:31 -0800101 const SkGlyph& glyph = glyphCacheProc(cache, &start);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000102 xAdv += glyph.fAdvanceX;
103 yAdv += glyph.fAdvanceY;
104 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000105 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000106 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000107 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000108
109 SkScalar xAdj = SkFixedToScalar(xAdv);
110 SkScalar yAdj = SkFixedToScalar(yAdv);
111 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
112 xAdj = SkScalarHalf(xAdj);
113 yAdj = SkScalarHalf(yAdj);
114 }
115 *x = *x - xAdj;
116 *y = *y - yAdj;
117}
118
robertphillips@google.coma4662862013-11-21 14:24:16 +0000119static int max_glyphid_for_typeface(SkTypeface* typeface) {
reed@google.comfed86bd2013-03-14 15:04:57 +0000120 SkAutoResolveDefaultTypeface autoResolve(typeface);
121 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000122 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000123}
124
125typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
126
reed@google.comaec40662014-04-18 19:29:07 +0000127static int force_glyph_encoding(const SkPaint& paint, const void* text,
128 size_t len, SkGlyphStorage* storage,
bungeman22edc832014-10-03 07:55:58 -0700129 const uint16_t** glyphIDs) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000130 // Make sure we have a glyph id encoding.
131 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
halcanary96fcdcc2015-08-27 07:41:13 -0700132 int numGlyphs = paint.textToGlyphs(text, len, nullptr);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000133 storage->reset(numGlyphs);
134 paint.textToGlyphs(text, len, storage->get());
135 *glyphIDs = storage->get();
136 return numGlyphs;
137 }
138
139 // For user supplied glyph ids we need to validate them.
140 SkASSERT((len & 1) == 0);
reed@google.comaec40662014-04-18 19:29:07 +0000141 int numGlyphs = SkToInt(len / 2);
bungeman22edc832014-10-03 07:55:58 -0700142 const uint16_t* input = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000143
144 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
reed@google.comaec40662014-04-18 19:29:07 +0000145 int validated;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000146 for (validated = 0; validated < numGlyphs; ++validated) {
147 if (input[validated] > maxGlyphID) {
148 break;
149 }
150 }
151 if (validated >= numGlyphs) {
bungeman22edc832014-10-03 07:55:58 -0700152 *glyphIDs = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000153 return numGlyphs;
154 }
155
156 // Silently drop anything out of range.
157 storage->reset(numGlyphs);
158 if (validated > 0) {
159 memcpy(storage->get(), input, validated * sizeof(uint16_t));
160 }
161
reed@google.comaec40662014-04-18 19:29:07 +0000162 for (int i = validated; i < numGlyphs; ++i) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000163 storage->get()[i] = input[i];
164 if (input[i] > maxGlyphID) {
165 storage->get()[i] = 0;
166 }
167 }
168 *glyphIDs = storage->get();
169 return numGlyphs;
170}
171
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000172static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
173 SkWStream* content) {
174 // Flip the text about the x-axis to account for origin swap and include
175 // the passed parameters.
176 content->writeText("1 0 ");
halcanarybc4696b2015-05-06 10:56:04 -0700177 SkPDFUtils::AppendScalar(0 - textSkewX, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000178 content->writeText(" -1 ");
halcanarybc4696b2015-05-06 10:56:04 -0700179 SkPDFUtils::AppendScalar(x, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000180 content->writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -0700181 SkPDFUtils::AppendScalar(y, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000182 content->writeText(" Tm\n");
183}
184
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000185// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
186// later being our representation of an object in the PDF file.
187struct GraphicStateEntry {
188 GraphicStateEntry();
189
190 // Compare the fields we care about when setting up a new content entry.
191 bool compareInitialState(const GraphicStateEntry& b);
192
193 SkMatrix fMatrix;
194 // We can't do set operations on Paths, though PDF natively supports
195 // intersect. If the clip stack does anything other than intersect,
196 // we have to fall back to the region. Treat fClipStack as authoritative.
197 // See http://code.google.com/p/skia/issues/detail?id=221
198 SkClipStack fClipStack;
199 SkRegion fClipRegion;
200
201 // When emitting the content entry, we will ensure the graphic state
202 // is set to these values first.
203 SkColor fColor;
204 SkScalar fTextScaleX; // Zero means we don't care what the value is.
205 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
206 int fShaderIndex;
207 int fGraphicStateIndex;
208
209 // We may change the font (i.e. for Type1 support) within a
halcanary96fcdcc2015-08-27 07:41:13 -0700210 // ContentEntry. This is the one currently in effect, or nullptr if none.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000211 SkPDFFont* fFont;
212 // In PDF, text size has no default value. It is only valid if fFont is
halcanary96fcdcc2015-08-27 07:41:13 -0700213 // not nullptr.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000214 SkScalar fTextSize;
215};
216
217GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
218 fTextScaleX(SK_Scalar1),
219 fTextFill(SkPaint::kFill_Style),
220 fShaderIndex(-1),
221 fGraphicStateIndex(-1),
halcanary96fcdcc2015-08-27 07:41:13 -0700222 fFont(nullptr),
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000223 fTextSize(SK_ScalarNaN) {
224 fMatrix.reset();
225}
226
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000227bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
228 return fColor == cur.fColor &&
229 fShaderIndex == cur.fShaderIndex &&
230 fGraphicStateIndex == cur.fGraphicStateIndex &&
231 fMatrix == cur.fMatrix &&
232 fClipStack == cur.fClipStack &&
233 (fTextScaleX == 0 ||
234 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000235}
236
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000237class GraphicStackState {
238public:
239 GraphicStackState(const SkClipStack& existingClipStack,
240 const SkRegion& existingClipRegion,
241 SkWStream* contentStream)
242 : fStackDepth(0),
243 fContentStream(contentStream) {
244 fEntries[0].fClipStack = existingClipStack;
245 fEntries[0].fClipRegion = existingClipRegion;
246 }
247
248 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000249 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000250 void updateMatrix(const SkMatrix& matrix);
251 void updateDrawingState(const GraphicStateEntry& state);
252
253 void drainStack();
254
255private:
256 void push();
257 void pop();
258 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
259
260 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
261 static const int kMaxStackDepth = 12;
262 GraphicStateEntry fEntries[kMaxStackDepth + 1];
263 int fStackDepth;
264 SkWStream* fContentStream;
265};
266
267void GraphicStackState::drainStack() {
268 while (fStackDepth) {
269 pop();
270 }
271}
272
273void GraphicStackState::push() {
274 SkASSERT(fStackDepth < kMaxStackDepth);
275 fContentStream->writeText("q\n");
276 fStackDepth++;
277 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
278}
279
280void GraphicStackState::pop() {
281 SkASSERT(fStackDepth > 0);
282 fContentStream->writeText("Q\n");
283 fStackDepth--;
284}
285
robertphillips@google.com80214e22012-07-20 15:33:18 +0000286// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000287// and then skips over the leading entries as specified in prefix. It requires
288// and asserts that "prefix" will be a prefix to "stack."
289static void skip_clip_stack_prefix(const SkClipStack& prefix,
290 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000291 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000292 SkClipStack::B2TIter prefixIter(prefix);
293 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000294
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000295 const SkClipStack::Element* prefixEntry;
296 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000297
298 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000299 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000300 iterEntry = iter->next();
301 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000302 // Because of SkClipStack does internal intersection, the last clip
303 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000304 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000305 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
306 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
307 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000308 // back up the iterator by one
309 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000310 prefixEntry = prefixIter.next();
311 break;
312 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000313 }
314
halcanary96fcdcc2015-08-27 07:41:13 -0700315 SkASSERT(prefixEntry == nullptr);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000316}
317
318static void emit_clip(SkPath* clipPath, SkRect* clipRect,
319 SkWStream* contentStream) {
320 SkASSERT(clipPath || clipRect);
321
322 SkPath::FillType clipFill;
323 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000324 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000325 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000326 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000327 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
328 clipFill = SkPath::kWinding_FillType;
329 }
330
331 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
332 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
333 if (clipFill == SkPath::kEvenOdd_FillType) {
334 contentStream->writeText("W* n\n");
335 } else {
336 contentStream->writeText("W n\n");
337 }
338}
339
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000340/* Calculate an inverted path's equivalent non-inverted path, given the
341 * canvas bounds.
342 * outPath may alias with invPath (since this is supported by PathOps).
343 */
344static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
345 SkPath* outPath) {
346 SkASSERT(invPath.isInverseFillType());
347
348 SkPath clipPath;
349 clipPath.addRect(bounds);
350
reedcdb42bb2015-06-26 10:23:07 -0700351 return Op(clipPath, invPath, kIntersect_SkPathOp, outPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000352}
353
fmalita632e92f2015-04-22 15:02:03 -0700354#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000355// Sanity check the numerical values of the SkRegion ops and PathOps ops
356// enums so region_op_to_pathops_op can do a straight passthrough cast.
357// If these are failing, it may be necessary to make region_op_to_pathops_op
358// do more.
bungeman99fe8222015-08-20 07:57:51 -0700359static_assert(SkRegion::kDifference_Op == (int)kDifference_SkPathOp, "region_pathop_mismatch");
360static_assert(SkRegion::kIntersect_Op == (int)kIntersect_SkPathOp, "region_pathop_mismatch");
361static_assert(SkRegion::kUnion_Op == (int)kUnion_SkPathOp, "region_pathop_mismatch");
362static_assert(SkRegion::kXOR_Op == (int)kXOR_SkPathOp, "region_pathop_mismatch");
363static_assert(SkRegion::kReverseDifference_Op == (int)kReverseDifference_SkPathOp,
364 "region_pathop_mismatch");
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000365
366static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
367 SkASSERT(op >= 0);
368 SkASSERT(op <= SkRegion::kReverseDifference_Op);
369 return (SkPathOp)op;
370}
371
372/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
373 * Returns true if successful, or false if not successful.
374 * If successful, the resulting clip is stored in outClipPath.
375 * If not successful, outClipPath is undefined, and a fallback method
376 * should be used.
377 */
378static bool get_clip_stack_path(const SkMatrix& transform,
379 const SkClipStack& clipStack,
380 const SkRegion& clipRegion,
381 SkPath* outClipPath) {
382 outClipPath->reset();
383 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
384
385 const SkClipStack::Element* clipEntry;
386 SkClipStack::Iter iter;
387 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
388 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
389 SkPath entryPath;
390 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
391 outClipPath->reset();
392 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
393 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000394 } else {
395 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000396 }
397 entryPath.transform(transform);
398
399 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
400 *outClipPath = entryPath;
401 } else {
402 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
403 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
404 return false;
405 }
406 }
407 }
408
409 if (outClipPath->isInverseFillType()) {
410 // The bounds are slightly outset to ensure this is correct in the
411 // face of floating-point accuracy and possible SkRegion bitmap
412 // approximations.
413 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
414 clipBounds.outset(SK_Scalar1, SK_Scalar1);
415 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
416 return false;
417 }
418 }
419 return true;
420}
421#endif
422
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000423// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000424// graphic state stack, and the fact that we can know all the clips used
425// on the page to optimize this.
426void GraphicStackState::updateClip(const SkClipStack& clipStack,
427 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000428 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000429 if (clipStack == currentEntry()->fClipStack) {
430 return;
431 }
432
433 while (fStackDepth > 0) {
434 pop();
435 if (clipStack == currentEntry()->fClipStack) {
436 return;
437 }
438 }
439 push();
440
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000441 currentEntry()->fClipStack = clipStack;
442 currentEntry()->fClipRegion = clipRegion;
443
444 SkMatrix transform;
445 transform.setTranslate(translation.fX, translation.fY);
446
fmalita632e92f2015-04-22 15:02:03 -0700447#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000448 SkPath clipPath;
449 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700450 emit_clip(&clipPath, nullptr, fContentStream);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000451 return;
452 }
453#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000454 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
455 // already been applied. (If this is a top level device, then it specifies
456 // a clip to the content area. If this is a layer, then it specifies
457 // the clip in effect when the layer was created.) There's no need to
458 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
459 // initial clip on the parent layer. (This means there's a bug if the user
460 // expands the clip and then uses any xfer mode that uses dst:
461 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000462 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000463 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
464
465 // If the clip stack does anything other than intersect or if it uses
466 // an inverse fill type, we have to fall back to the clip region.
467 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000468 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000469 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000470 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
471 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000472 needRegion = true;
473 break;
474 }
475 }
476
477 if (needRegion) {
478 SkPath clipPath;
479 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
halcanary96fcdcc2015-08-27 07:41:13 -0700480 emit_clip(&clipPath, nullptr, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000481 } else {
482 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000483 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000484 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000485 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
486 switch (clipEntry->getType()) {
487 case SkClipStack::Element::kRect_Type: {
488 SkRect translatedClip;
489 transform.mapRect(&translatedClip, clipEntry->getRect());
halcanary96fcdcc2015-08-27 07:41:13 -0700490 emit_clip(nullptr, &translatedClip, fContentStream);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000491 break;
492 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000493 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000494 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000495 clipEntry->asPath(&translatedPath);
496 translatedPath.transform(transform, &translatedPath);
halcanary96fcdcc2015-08-27 07:41:13 -0700497 emit_clip(&translatedPath, nullptr, fContentStream);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000498 break;
499 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000500 }
501 }
502 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000503}
504
505void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
506 if (matrix == currentEntry()->fMatrix) {
507 return;
508 }
509
510 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
511 SkASSERT(fStackDepth > 0);
512 SkASSERT(fEntries[fStackDepth].fClipStack ==
513 fEntries[fStackDepth -1].fClipStack);
514 pop();
515
516 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
517 }
518 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
519 return;
520 }
521
522 push();
523 SkPDFUtils::AppendTransform(matrix, fContentStream);
524 currentEntry()->fMatrix = matrix;
525}
526
527void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
528 // PDF treats a shader as a color, so we only set one or the other.
529 if (state.fShaderIndex >= 0) {
530 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000531 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000532 currentEntry()->fShaderIndex = state.fShaderIndex;
533 }
534 } else {
535 if (state.fColor != currentEntry()->fColor ||
536 currentEntry()->fShaderIndex >= 0) {
537 emit_pdf_color(state.fColor, fContentStream);
538 fContentStream->writeText("RG ");
539 emit_pdf_color(state.fColor, fContentStream);
540 fContentStream->writeText("rg\n");
541 currentEntry()->fColor = state.fColor;
542 currentEntry()->fShaderIndex = -1;
543 }
544 }
545
546 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000547 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000548 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
549 }
550
551 if (state.fTextScaleX) {
552 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
553 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
554 SkIntToScalar(100));
halcanarybc4696b2015-05-06 10:56:04 -0700555 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000556 fContentStream->writeText(" Tz\n");
557 currentEntry()->fTextScaleX = state.fTextScaleX;
558 }
559 if (state.fTextFill != currentEntry()->fTextFill) {
bungeman99fe8222015-08-20 07:57:51 -0700560 static_assert(SkPaint::kFill_Style == 0, "enum_must_match_value");
561 static_assert(SkPaint::kStroke_Style == 1, "enum_must_match_value");
562 static_assert(SkPaint::kStrokeAndFill_Style == 2, "enum_must_match_value");
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000563 fContentStream->writeDecAsText(state.fTextFill);
564 fContentStream->writeText(" Tr\n");
565 currentEntry()->fTextFill = state.fTextFill;
566 }
567 }
568}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000569
reed76033be2015-03-14 10:54:31 -0700570static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700571 // PDF does not support image filters, so render them on CPU.
572 // Note that this rendering is done at "screen" resolution (100dpi), not
573 // printer resolution.
halcanary7a14b312015-10-01 07:28:13 -0700574 // TODO: It may be possible to express some filters natively using PDF
halcanary6950de62015-11-07 05:29:00 -0800575 // to improve quality and file size (https://bug.skia.org/3043)
reed76033be2015-03-14 10:54:31 -0700576
577 // TODO: should we return true if there is a colorfilter?
halcanary96fcdcc2015-08-27 07:41:13 -0700578 return layerPaint.getImageFilter() != nullptr;
reed76033be2015-03-14 10:54:31 -0700579}
580
581SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
halcanary00b7e5e2015-04-15 13:05:18 -0700582 if (cinfo.fForImageFilter ||
583 (layerPaint && not_supported_for_layers(*layerPaint))) {
halcanary96fcdcc2015-08-27 07:41:13 -0700584 return nullptr;
senorblancob0e89dc2014-10-20 14:03:12 -0700585 }
fmalita6987dca2014-11-13 08:33:37 -0800586 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanarya1f1ee92015-02-20 06:17:26 -0800587 return SkPDFDevice::Create(size, fRasterDpi, fCanon);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000588}
589
590
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000591struct ContentEntry {
592 GraphicStateEntry fState;
593 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000594 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000595
596 // If the stack is too deep we could get Stack Overflow.
597 // So we manually destruct the object.
598 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000599 ContentEntry* val = fNext.detach();
halcanary96fcdcc2015-08-27 07:41:13 -0700600 while (val != nullptr) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000601 ContentEntry* valNext = val->fNext.detach();
halcanary96fcdcc2015-08-27 07:41:13 -0700602 // When the destructor is called, fNext is nullptr and exits.
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000603 delete val;
604 val = valNext;
605 }
606 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000607};
608
609// A helper class to automatically finish a ContentEntry at the end of a
610// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000611class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000612public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000613 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
614 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000615 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700616 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000617 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700618 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000619 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
620 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000621 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
622 const SkRegion& clipRegion, const SkMatrix& matrix,
623 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000624 : fDevice(device),
halcanary96fcdcc2015-08-27 07:41:13 -0700625 fContentEntry(nullptr),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000626 fXfermode(SkXfermode::kSrcOver_Mode),
halcanary96fcdcc2015-08-27 07:41:13 -0700627 fDstFormXObject(nullptr) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000628 init(clipStack, clipRegion, matrix, paint, hasText);
629 }
630
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000631 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000632 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000633 SkPath* shape = &fShape;
634 if (shape->isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -0700635 shape = nullptr;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000636 }
637 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000638 }
reed@google.comfc641d02012-09-20 17:52:20 +0000639 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000640 }
641
642 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000643
644 /* Returns true when we explicitly need the shape of the drawing. */
645 bool needShape() {
646 switch (fXfermode) {
647 case SkXfermode::kClear_Mode:
648 case SkXfermode::kSrc_Mode:
649 case SkXfermode::kSrcIn_Mode:
650 case SkXfermode::kSrcOut_Mode:
651 case SkXfermode::kDstIn_Mode:
652 case SkXfermode::kDstOut_Mode:
653 case SkXfermode::kSrcATop_Mode:
654 case SkXfermode::kDstATop_Mode:
655 case SkXfermode::kModulate_Mode:
656 return true;
657 default:
658 return false;
659 }
660 }
661
662 /* Returns true unless we only need the shape of the drawing. */
663 bool needSource() {
664 if (fXfermode == SkXfermode::kClear_Mode) {
665 return false;
666 }
667 return true;
668 }
669
670 /* If the shape is different than the alpha component of the content, then
671 * setShape should be called with the shape. In particular, images and
672 * devices have rectangular shape.
673 */
674 void setShape(const SkPath& shape) {
675 fShape = shape;
676 }
677
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000678private:
679 SkPDFDevice* fDevice;
680 ContentEntry* fContentEntry;
681 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000682 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000683 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000684
685 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
686 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000687 // Shape has to be flatten before we get here.
688 if (matrix.hasPerspective()) {
689 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000690 return;
691 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000692 if (paint.getXfermode()) {
693 paint.getXfermode()->asMode(&fXfermode);
694 }
695 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
696 matrix, paint, hasText,
697 &fDstFormXObject);
698 }
699};
700
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000701////////////////////////////////////////////////////////////////////////////////
702
halcanary385fe4d2015-08-26 13:07:48 -0700703SkPDFDevice::SkPDFDevice(SkISize pageSize, SkScalar rasterDpi, SkPDFCanon* canon, bool flip)
robertphillips9a53fd72015-06-22 09:46:59 -0700704 : INHERITED(SkSurfaceProps(0, kUnknown_SkPixelGeometry))
705 , fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800706 , fContentSize(pageSize)
707 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
halcanary96fcdcc2015-08-27 07:41:13 -0700708 , fLastContentEntry(nullptr)
709 , fLastMarginContentEntry(nullptr)
halcanarya1f1ee92015-02-20 06:17:26 -0800710 , fDrawingArea(kContent_DrawingArea)
halcanary96fcdcc2015-08-27 07:41:13 -0700711 , fClipStack(nullptr)
halcanary385fe4d2015-08-26 13:07:48 -0700712 , fFontGlyphUsage(new SkPDFGlyphSetMap)
halcanarya1f1ee92015-02-20 06:17:26 -0800713 , fRasterDpi(rasterDpi)
714 , fCanon(canon) {
715 SkASSERT(pageSize.width() > 0);
716 SkASSERT(pageSize.height() > 0);
717 fLegacyBitmap.setInfo(
718 SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()));
719 if (flip) {
720 // Skia generally uses the top left as the origin but PDF
721 // natively has the origin at the bottom left. This matrix
722 // corrects for that. But that only needs to be done once, we
723 // don't do it when layering.
724 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
725 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
726 } else {
727 fInitialTransform.setIdentity();
728 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000729}
730
731SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000732 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000733}
734
735void SkPDFDevice::init() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000736 fContentEntries.free();
halcanary96fcdcc2015-08-27 07:41:13 -0700737 fLastContentEntry = nullptr;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000738 fMarginContentEntries.free();
halcanary96fcdcc2015-08-27 07:41:13 -0700739 fLastMarginContentEntry = nullptr;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000740 fDrawingArea = kContent_DrawingArea;
halcanary96fcdcc2015-08-27 07:41:13 -0700741 if (fFontGlyphUsage.get() == nullptr) {
halcanary385fe4d2015-08-26 13:07:48 -0700742 fFontGlyphUsage.reset(new SkPDFGlyphSetMap);
vandebo@chromium.org98594282011-07-25 22:34:12 +0000743 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000744}
745
vandebo@chromium.org98594282011-07-25 22:34:12 +0000746void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000747 fGraphicStateResources.unrefAll();
748 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000749 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000750 fShaderResources.unrefAll();
wangxianzhuef6c50a2015-09-17 20:38:02 -0700751 fLinkToURLs.deleteAll();
752 fLinkToDestinations.deleteAll();
epoger@google.comb58772f2013-03-08 09:09:10 +0000753 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000754
vandebo@chromium.org98594282011-07-25 22:34:12 +0000755 if (clearFontUsage) {
756 fFontGlyphUsage->reset();
757 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000758}
759
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000760void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000761 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700762 replace_srcmode_on_opaque_paint(&newPaint);
763
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000764 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000765 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000766 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000767}
768
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000769void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
770 ContentEntry* contentEntry) {
771 if (!contentEntry) {
772 return;
773 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000774 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
775 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000776 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000777 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000778 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000779 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000780 inverse.mapRect(&bbox);
781
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000782 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000783 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000784 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000785}
786
halcanary682ee012016-01-28 10:59:34 -0800787void SkPDFDevice::drawPoints(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700788 SkCanvas::PointMode mode,
789 size_t count,
790 const SkPoint* points,
791 const SkPaint& srcPaint) {
792 SkPaint passedPaint = srcPaint;
793 replace_srcmode_on_opaque_paint(&passedPaint);
794
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000795 if (count == 0) {
796 return;
797 }
798
wangxianzhud76665d2015-07-17 17:23:15 -0700799 if (SkAnnotation* annotation = passedPaint.getAnnotation()) {
halcanary682ee012016-01-28 10:59:34 -0800800 if (handlePointAnnotation(points, count, *d.fMatrix, annotation)) {
wangxianzhud76665d2015-07-17 17:23:15 -0700801 return;
802 }
epoger@google.comb58772f2013-03-08 09:09:10 +0000803 }
804
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000805 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
806 // We only use this when there's a path effect because of the overhead
807 // of multiple calls to setUpContentEntry it causes.
808 if (passedPaint.getPathEffect()) {
809 if (d.fClip->isEmpty()) {
810 return;
811 }
812 SkDraw pointDraw(d);
813 pointDraw.fDevice = this;
814 pointDraw.drawPoints(mode, count, points, passedPaint, true);
815 return;
816 }
817
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000818 const SkPaint* paint = &passedPaint;
819 SkPaint modifiedPaint;
820
821 if (mode == SkCanvas::kPoints_PointMode &&
822 paint->getStrokeCap() != SkPaint::kRound_Cap) {
823 modifiedPaint = *paint;
824 paint = &modifiedPaint;
825 if (paint->getStrokeWidth()) {
826 // PDF won't draw a single point with square/butt caps because the
827 // orientation is ambiguous. Draw a rectangle instead.
828 modifiedPaint.setStyle(SkPaint::kFill_Style);
829 SkScalar strokeWidth = paint->getStrokeWidth();
830 SkScalar halfStroke = SkScalarHalf(strokeWidth);
831 for (size_t i = 0; i < count; i++) {
832 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
833 r.inset(-halfStroke, -halfStroke);
834 drawRect(d, r, modifiedPaint);
835 }
836 return;
837 } else {
838 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
839 }
840 }
841
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000842 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000843 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000844 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000845 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000846
847 switch (mode) {
848 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000849 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000850 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000851 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000852 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000853 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000854 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000855 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000856 break;
857 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000858 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000859 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000860 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000861 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000862 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000863 &content.entry()->fContent);
864 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000865 }
866 break;
867 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000868 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
869 for (size_t i = 0; i < count; i++) {
870 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000871 &content.entry()->fContent);
872 SkPDFUtils::ClosePath(&content.entry()->fContent);
873 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000874 }
875 break;
876 default:
877 SkASSERT(false);
878 }
879}
880
wangxianzhud76665d2015-07-17 17:23:15 -0700881static SkPDFDict* create_link_annotation(const SkRect& translatedRect) {
halcanary385fe4d2015-08-26 13:07:48 -0700882 SkAutoTUnref<SkPDFDict> annotation(new SkPDFDict("Annot"));
wangxianzhud76665d2015-07-17 17:23:15 -0700883 annotation->insertName("Subtype", "Link");
884
halcanary385fe4d2015-08-26 13:07:48 -0700885 SkAutoTUnref<SkPDFArray> border(new SkPDFArray);
wangxianzhud76665d2015-07-17 17:23:15 -0700886 border->reserve(3);
887 border->appendInt(0); // Horizontal corner radius.
888 border->appendInt(0); // Vertical corner radius.
889 border->appendInt(0); // Width, 0 = no border.
890 annotation->insertObject("Border", border.detach());
891
halcanary385fe4d2015-08-26 13:07:48 -0700892 SkAutoTUnref<SkPDFArray> rect(new SkPDFArray);
wangxianzhud76665d2015-07-17 17:23:15 -0700893 rect->reserve(4);
894 rect->appendScalar(translatedRect.fLeft);
895 rect->appendScalar(translatedRect.fTop);
896 rect->appendScalar(translatedRect.fRight);
897 rect->appendScalar(translatedRect.fBottom);
898 annotation->insertObject("Rect", rect.detach());
899
900 return annotation.detach();
901}
902
wangxianzhuef6c50a2015-09-17 20:38:02 -0700903static SkPDFDict* create_link_to_url(const SkData* urlData, const SkRect& r) {
wangxianzhud76665d2015-07-17 17:23:15 -0700904 SkAutoTUnref<SkPDFDict> annotation(create_link_annotation(r));
905
906 SkString url(static_cast<const char *>(urlData->data()),
907 urlData->size() - 1);
halcanary385fe4d2015-08-26 13:07:48 -0700908 SkAutoTUnref<SkPDFDict> action(new SkPDFDict("Action"));
wangxianzhud76665d2015-07-17 17:23:15 -0700909 action->insertName("S", "URI");
910 action->insertString("URI", url);
911 annotation->insertObject("A", action.detach());
912 return annotation.detach();
913}
914
wangxianzhuef6c50a2015-09-17 20:38:02 -0700915static SkPDFDict* create_link_named_dest(const SkData* nameData,
916 const SkRect& r) {
wangxianzhud76665d2015-07-17 17:23:15 -0700917 SkAutoTUnref<SkPDFDict> annotation(create_link_annotation(r));
918 SkString name(static_cast<const char *>(nameData->data()),
919 nameData->size() - 1);
920 annotation->insertName("Dest", name);
921 return annotation.detach();
922}
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
wangxianzhud76665d2015-07-17 17:23:15 -0700942 if (SkAnnotation* annotation = paint.getAnnotation()) {
943 SkPath path;
944 path.addRect(rect);
wangxianzhuef6c50a2015-09-17 20:38:02 -0700945 if (handlePathAnnotation(path, d, annotation)) {
wangxianzhud76665d2015-07-17 17:23:15 -0700946 return;
947 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000948 }
949
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000950 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000951 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000952 return;
953 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000954 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000955 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000956 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000957}
958
halcanarya6814332015-05-27 08:53:36 -0700959void SkPDFDevice::drawRRect(const SkDraw& draw,
960 const SkRRect& rrect,
961 const SkPaint& srcPaint) {
962 SkPaint paint = srcPaint;
963 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000964 SkPath path;
965 path.addRRect(rrect);
halcanary96fcdcc2015-08-27 07:41:13 -0700966 this->drawPath(draw, path, paint, nullptr, true);
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000967}
968
halcanarya6814332015-05-27 08:53:36 -0700969void SkPDFDevice::drawOval(const SkDraw& draw,
970 const SkRect& oval,
971 const SkPaint& srcPaint) {
972 SkPaint paint = srcPaint;
973 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -0700974 SkPath path;
975 path.addOval(oval);
halcanary96fcdcc2015-08-27 07:41:13 -0700976 this->drawPath(draw, path, paint, nullptr, true);
reed89443ab2014-06-27 11:34:19 -0700977}
978
halcanary682ee012016-01-28 10:59:34 -0800979void SkPDFDevice::drawPath(const SkDraw& d,
halcanarya6814332015-05-27 08:53:36 -0700980 const SkPath& origPath,
981 const SkPaint& srcPaint,
982 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000983 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -0700984 SkPaint paint = srcPaint;
985 replace_srcmode_on_opaque_paint(&paint);
halcanary682ee012016-01-28 10:59:34 -0800986 SkPath modifiedPath;
987 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000988
989 SkMatrix matrix = *d.fMatrix;
990 if (prePathMatrix) {
991 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
halcanary682ee012016-01-28 10:59:34 -0800992 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000993 pathPtr = &modifiedPath;
994 pathIsMutable = true;
995 }
halcanary682ee012016-01-28 10:59:34 -0800996 origPath.transform(*prePathMatrix, pathPtr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000997 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000998 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000999 }
1000 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +00001001
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001002 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001003 if (d.fClip->isEmpty()) {
1004 return;
1005 }
halcanary682ee012016-01-28 10:59:34 -08001006 if (!pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001007 pathPtr = &modifiedPath;
1008 pathIsMutable = true;
1009 }
halcanary682ee012016-01-28 10:59:34 -08001010 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001011
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001012 SkPaint noEffectPaint(paint);
halcanary96fcdcc2015-08-27 07:41:13 -07001013 noEffectPaint.setPathEffect(nullptr);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001014 if (fill) {
1015 noEffectPaint.setStyle(SkPaint::kFill_Style);
1016 } else {
1017 noEffectPaint.setStyle(SkPaint::kStroke_Style);
1018 noEffectPaint.setStrokeWidth(0);
1019 }
halcanary96fcdcc2015-08-27 07:41:13 -07001020 drawPath(d, *pathPtr, noEffectPaint, nullptr, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001021 return;
1022 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001023
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001024 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001025 return;
1026 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001027
wangxianzhud76665d2015-07-17 17:23:15 -07001028 if (SkAnnotation* annotation = paint.getAnnotation()) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001029 if (handlePathAnnotation(*pathPtr, d, annotation)) {
wangxianzhud76665d2015-07-17 17:23:15 -07001030 return;
1031 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001032 }
1033
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001034 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001035 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001036 return;
1037 }
halcanary8b2bc252015-10-06 09:41:47 -07001038 bool consumeDegeratePathSegments =
1039 paint.getStyle() == SkPaint::kFill_Style ||
1040 (paint.getStrokeCap() != SkPaint::kRound_Cap &&
1041 paint.getStrokeCap() != SkPaint::kSquare_Cap);
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001042 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
halcanary8b2bc252015-10-06 09:41:47 -07001043 consumeDegeratePathSegments,
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001044 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001045 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001046 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001047}
1048
halcanary7a14b312015-10-01 07:28:13 -07001049void SkPDFDevice::drawBitmapRect(const SkDraw& draw,
1050 const SkBitmap& bitmap,
1051 const SkRect* src,
1052 const SkRect& dst,
1053 const SkPaint& srcPaint,
1054 SkCanvas::SrcRectConstraint constraint) {
1055 const SkImage* image = fCanon->bitmapToImage(bitmap);
1056 if (!image) {
1057 return;
1058 }
1059 // ownership of this image is retained by the canon.
1060 this->drawImageRect(draw, image, src, dst, srcPaint, constraint);
1061}
1062
1063void SkPDFDevice::drawBitmap(const SkDraw& d,
1064 const SkBitmap& bitmap,
1065 const SkMatrix& matrix,
1066 const SkPaint& srcPaint) {
halcanarya6814332015-05-27 08:53:36 -07001067 SkPaint paint = srcPaint;
1068 if (bitmap.isOpaque()) {
1069 replace_srcmode_on_opaque_paint(&paint);
1070 }
1071
halcanary7a14b312015-10-01 07:28:13 -07001072 if (d.fClip->isEmpty()) {
1073 return;
1074 }
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001075
halcanary7a14b312015-10-01 07:28:13 -07001076 SkMatrix transform = matrix;
1077 transform.postConcat(*d.fMatrix);
1078 const SkImage* image = fCanon->bitmapToImage(bitmap);
1079 if (!image) {
1080 return;
1081 }
1082 this->internalDrawImage(transform, d.fClipStack, *d.fClip, image, nullptr,
1083 paint);
1084}
1085
1086void SkPDFDevice::drawSprite(const SkDraw& d,
1087 const SkBitmap& bitmap,
1088 int x,
1089 int y,
1090 const SkPaint& srcPaint) {
1091 SkPaint paint = srcPaint;
1092 if (bitmap.isOpaque()) {
1093 replace_srcmode_on_opaque_paint(&paint);
1094 }
1095
1096 if (d.fClip->isEmpty()) {
1097 return;
1098 }
1099
1100 SkMatrix matrix;
1101 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
1102 const SkImage* image = fCanon->bitmapToImage(bitmap);
1103 if (!image) {
1104 return;
1105 }
1106 this->internalDrawImage(matrix, d.fClipStack, *d.fClip, image, nullptr,
1107 paint);
1108}
1109
1110void SkPDFDevice::drawImage(const SkDraw& draw,
1111 const SkImage* image,
1112 SkScalar x,
1113 SkScalar y,
1114 const SkPaint& srcPaint) {
1115 SkPaint paint = srcPaint;
1116 if (!image) {
1117 return;
1118 }
1119 if (image->isOpaque()) {
1120 replace_srcmode_on_opaque_paint(&paint);
1121 }
1122 if (draw.fClip->isEmpty()) {
1123 return;
1124 }
1125 SkMatrix transform = SkMatrix::MakeTrans(x, y);
1126 transform.postConcat(*draw.fMatrix);
1127 this->internalDrawImage(transform, draw.fClipStack, *draw.fClip, image,
1128 nullptr, paint);
1129}
1130
1131void SkPDFDevice::drawImageRect(const SkDraw& draw,
1132 const SkImage* image,
1133 const SkRect* src,
1134 const SkRect& dst,
1135 const SkPaint& srcPaint,
1136 SkCanvas::SrcRectConstraint constraint) {
1137 if (!image) {
1138 return;
1139 }
1140 if (draw.fClip->isEmpty()) {
1141 return;
1142 }
1143 SkPaint paint = srcPaint;
1144 if (image->isOpaque()) {
1145 replace_srcmode_on_opaque_paint(&paint);
1146 }
1147 // TODO: this code path must be updated to respect the flags parameter
1148 SkMatrix matrix;
1149 SkRect tmpSrc, tmpDst;
1150 SkRect imageBounds = SkRect::Make(image->bounds());
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001151
1152 // Compute matrix from the two rectangles
1153 if (src) {
1154 tmpSrc = *src;
1155 } else {
halcanary7a14b312015-10-01 07:28:13 -07001156 tmpSrc = imageBounds;
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001157 }
1158 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1159
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001160 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1161 // needed (if the src was clipped). No check needed if src==null.
halcanary7a14b312015-10-01 07:28:13 -07001162 SkAutoTUnref<const SkImage> autoImageUnref;
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001163 if (src) {
halcanary7a14b312015-10-01 07:28:13 -07001164 if (!imageBounds.contains(*src)) {
1165 if (!tmpSrc.intersect(imageBounds)) {
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001166 return; // nothing to draw
1167 }
1168 // recompute dst, based on the smaller tmpSrc
1169 matrix.mapRect(&tmpDst, tmpSrc);
1170 }
1171
1172 // since we may need to clamp to the borders of the src rect within
1173 // the bitmap, we extract a subset.
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001174 SkIRect srcIR;
1175 tmpSrc.roundOut(&srcIR);
halcanary7a14b312015-10-01 07:28:13 -07001176
1177 autoImageUnref.reset(image->newSubset(srcIR));
1178 if (!autoImageUnref) {
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001179 return;
1180 }
halcanary7a14b312015-10-01 07:28:13 -07001181 image = autoImageUnref;
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001182 // Since we did an extract, we need to adjust the matrix accordingly
1183 SkScalar dx = 0, dy = 0;
1184 if (srcIR.fLeft > 0) {
1185 dx = SkIntToScalar(srcIR.fLeft);
1186 }
1187 if (srcIR.fTop > 0) {
1188 dy = SkIntToScalar(srcIR.fTop);
1189 }
1190 if (dx || dy) {
1191 matrix.preTranslate(dx, dy);
1192 }
1193 }
halcanary7a14b312015-10-01 07:28:13 -07001194 matrix.postConcat(*draw.fMatrix);
1195 this->internalDrawImage(matrix, draw.fClipStack, *draw.fClip, image,
1196 nullptr, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001197}
1198
halcanarybb264b72015-04-07 10:40:03 -07001199// Create a PDF string. Maximum length (in bytes) is 65,535.
1200// @param input A string value.
1201// @param len The length of the input array.
1202// @param wideChars True iff the upper byte in each uint16_t is
1203// significant and should be encoded and not
1204// discarded. If true, the upper byte is encoded
1205// first. Otherwise, we assert the upper byte is
1206// zero.
1207static SkString format_wide_string(const uint16_t* input,
1208 size_t len,
1209 bool wideChars) {
1210 if (wideChars) {
1211 SkASSERT(2 * len < 65535);
1212 static const char gHex[] = "0123456789ABCDEF";
1213 SkString result(4 * len + 2);
1214 result[0] = '<';
1215 for (size_t i = 0; i < len; i++) {
1216 result[4 * i + 1] = gHex[(input[i] >> 12) & 0xF];
1217 result[4 * i + 2] = gHex[(input[i] >> 8) & 0xF];
1218 result[4 * i + 3] = gHex[(input[i] >> 4) & 0xF];
1219 result[4 * i + 4] = gHex[(input[i] ) & 0xF];
1220 }
1221 result[4 * len + 1] = '>';
1222 return result;
1223 } else {
1224 SkASSERT(len <= 65535);
1225 SkString tmp(len);
1226 for (size_t i = 0; i < len; i++) {
1227 SkASSERT(0 == input[i] >> 8);
1228 tmp[i] = static_cast<uint8_t>(input[i]);
1229 }
halcanarybc4696b2015-05-06 10:56:04 -07001230 return SkPDFUtils::FormatString(tmp.c_str(), tmp.size());
halcanarybb264b72015-04-07 10:40:03 -07001231 }
1232}
1233
halcanary66a82f32015-10-12 13:05:04 -07001234static void draw_transparent_text(SkPDFDevice* device,
1235 const SkDraw& d,
1236 const void* text, size_t len,
1237 SkScalar x, SkScalar y,
1238 const SkPaint& srcPaint) {
1239
1240 SkPaint transparent;
1241 if (!SkPDFFont::CanEmbedTypeface(transparent.getTypeface(),
1242 device->getCanon())) {
1243 SkDEBUGFAIL("default typeface should be embeddable");
1244 return; // Avoid infinite loop in release.
1245 }
1246 transparent.setTextSize(srcPaint.getTextSize());
1247 transparent.setColor(SK_ColorTRANSPARENT);
1248 switch (srcPaint.getTextEncoding()) {
1249 case SkPaint::kGlyphID_TextEncoding: {
1250 // Since a glyphId<->Unicode mapping is typeface-specific,
1251 // map back to Unicode first.
1252 size_t glyphCount = len / 2;
1253 SkAutoTMalloc<SkUnichar> unichars(glyphCount);
1254 srcPaint.glyphsToUnichars(
1255 (const uint16_t*)text, SkToInt(glyphCount), &unichars[0]);
1256 transparent.setTextEncoding(SkPaint::kUTF32_TextEncoding);
1257 device->drawText(d, &unichars[0],
1258 glyphCount * sizeof(SkUnichar),
1259 x, y, transparent);
1260 break;
1261 }
1262 case SkPaint::kUTF8_TextEncoding:
1263 case SkPaint::kUTF16_TextEncoding:
1264 case SkPaint::kUTF32_TextEncoding:
1265 transparent.setTextEncoding(srcPaint.getTextEncoding());
1266 device->drawText(d, text, len, x, y, transparent);
1267 break;
1268 default:
1269 SkFAIL("unknown text encoding");
1270 }
1271}
1272
1273
halcanary682ee012016-01-28 10:59:34 -08001274void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
halcanarya6814332015-05-27 08:53:36 -07001275 SkScalar x, SkScalar y, const SkPaint& srcPaint) {
halcanary66a82f32015-10-12 13:05:04 -07001276 if (!SkPDFFont::CanEmbedTypeface(srcPaint.getTypeface(), fCanon)) {
halcanary6950de62015-11-07 05:29:00 -08001277 // https://bug.skia.org/3866
halcanary66a82f32015-10-12 13:05:04 -07001278 SkPath path;
1279 srcPaint.getTextPath(text, len, x, y, &path);
1280 this->drawPath(d, path, srcPaint, &SkMatrix::I(), true);
1281 // Draw text transparently to make it copyable/searchable/accessable.
1282 draw_transparent_text(this, d, text, len, x, y, srcPaint);
1283 return;
1284 }
halcanarya6814332015-05-27 08:53:36 -07001285 SkPaint paint = srcPaint;
1286 replace_srcmode_on_opaque_paint(&paint);
1287
halcanary96fcdcc2015-08-27 07:41:13 -07001288 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1289 if (paint.getMaskFilter() != nullptr) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001290 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1291 // making text unreadable (e.g. same text twice when using CSS shadows).
1292 return;
1293 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001294 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001295 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001296 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001297 return;
1298 }
1299
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001300 SkGlyphStorage storage(0);
halcanary96fcdcc2015-08-27 07:41:13 -07001301 const uint16_t* glyphIDs = nullptr;
reed@google.comaec40662014-04-18 19:29:07 +00001302 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001303 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001304
benjaminwagnerd936f632016-02-23 10:44:31 -08001305 SkPaint::GlyphCacheProc glyphCacheProc = textPaint.getGlyphCacheProc(true);
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001306 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001307 content.entry()->fContent.writeText("BT\n");
1308 set_text_transform(x, y, textPaint.getTextSkewX(),
1309 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001310 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001311
1312 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1313
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001314 while (numGlyphs > consumedGlyphCount) {
robertphillips8e0c1502015-07-07 10:28:43 -07001315 this->updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001316 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001317
1318 int availableGlyphs = font->glyphsToPDFFontEncoding(
1319 glyphIDsCopy.begin() + consumedGlyphCount,
1320 numGlyphs - consumedGlyphCount);
1321 fFontGlyphUsage->noteGlyphUsage(
1322 font, glyphIDsCopy.begin() + consumedGlyphCount,
1323 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001324 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001325 format_wide_string(glyphIDsCopy.begin() + consumedGlyphCount,
1326 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001327 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001328 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001329 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001330 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001331 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001332}
1333
halcanary682ee012016-01-28 10:59:34 -08001334void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001335 const SkScalar pos[], int scalarsPerPos,
halcanary682ee012016-01-28 10:59:34 -08001336 const SkPoint& offset, const SkPaint& srcPaint) {
halcanary66a82f32015-10-12 13:05:04 -07001337 if (!SkPDFFont::CanEmbedTypeface(srcPaint.getTypeface(), fCanon)) {
1338 const SkPoint* positions = reinterpret_cast<const SkPoint*>(pos);
1339 SkAutoTMalloc<SkPoint> positionsBuffer;
1340 if (2 != scalarsPerPos) {
1341 int glyphCount = srcPaint.textToGlyphs(text, len, NULL);
1342 positionsBuffer.reset(glyphCount);
1343 for (int i = 0; i < glyphCount; ++i) {
1344 positionsBuffer[i].set(pos[i], 0.0f);
1345 }
1346 positions = &positionsBuffer[0];
1347 }
1348 SkPath path;
1349 srcPaint.getPosTextPath(text, len, positions, &path);
1350 SkMatrix matrix;
1351 matrix.setTranslate(offset);
1352 this->drawPath(d, path, srcPaint, &matrix, true);
1353 // Draw text transparently to make it copyable/searchable/accessable.
1354 draw_transparent_text(
1355 this, d, text, len, offset.x() + positions[0].x(),
1356 offset.y() + positions[0].y(), srcPaint);
1357 return;
1358 }
1359
halcanarya6814332015-05-27 08:53:36 -07001360 SkPaint paint = srcPaint;
1361 replace_srcmode_on_opaque_paint(&paint);
1362
halcanary96fcdcc2015-08-27 07:41:13 -07001363 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
1364 if (paint.getMaskFilter() != nullptr) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001365 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1366 // making text unreadable (e.g. same text twice when using CSS shadows).
1367 return;
1368 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001369 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001370 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001371 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001372 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001373 return;
1374 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001375
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001376 SkGlyphStorage storage(0);
halcanary96fcdcc2015-08-27 07:41:13 -07001377 const uint16_t* glyphIDs = nullptr;
bungeman22edc832014-10-03 07:55:58 -07001378 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001379 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001380
benjaminwagnerd936f632016-02-23 10:44:31 -08001381 SkPaint::GlyphCacheProc glyphCacheProc = textPaint.getGlyphCacheProc(true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001382 content.entry()->fContent.writeText("BT\n");
robertphillips8e0c1502015-07-07 10:28:43 -07001383 this->updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001384 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001385 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001386 uint16_t encodedValue = glyphIDs[i];
1387 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001388 // The current pdf font cannot encode the current glyph.
1389 // Try to get a pdf font which can encode the current glyph.
robertphillips8e0c1502015-07-07 10:28:43 -07001390 this->updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001391 font = content.entry()->fState.fFont;
1392 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1393 SkDEBUGFAIL("PDF could not encode glyph.");
1394 continue;
1395 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001396 }
bungeman22edc832014-10-03 07:55:58 -07001397
vandebo@chromium.org98594282011-07-25 22:34:12 +00001398 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001399 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1400 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1401
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001402 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001403 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001404 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001405 format_wide_string(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001406 content.entry()->fContent.writeText(encodedString.c_str());
1407 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001408 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001409 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001410}
1411
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001412void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001413 int vertexCount, const SkPoint verts[],
1414 const SkPoint texs[], const SkColor colors[],
1415 SkXfermode* xmode, const uint16_t indices[],
1416 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001417 if (d.fClip->isEmpty()) {
1418 return;
1419 }
reed@google.com85e143c2013-12-30 15:51:25 +00001420 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001421}
1422
wangxianzhuef6c50a2015-09-17 20:38:02 -07001423struct RectWithData {
1424 SkRect rect;
1425 SkAutoTUnref<const SkData> data;
1426
1427 RectWithData(const SkRect& rect, const SkData* data)
1428 : rect(rect), data(SkRef(data)) {}
1429};
1430
1431struct NamedDestination {
1432 SkAutoTUnref<const SkData> nameData;
1433 SkPoint point;
1434
1435 NamedDestination(const SkData* nameData, const SkPoint& point)
1436 : nameData(SkRef(nameData)), point(point) {}
1437};
1438
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001439void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1440 int x, int y, const SkPaint& paint) {
fmalita6987dca2014-11-13 08:33:37 -08001441 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001442 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001443
1444 SkScalar scalarX = SkIntToScalar(x);
1445 SkScalar scalarY = SkIntToScalar(y);
1446 for (RectWithData* link : pdfDevice->fLinkToURLs) {
1447 fLinkToURLs.push(new RectWithData(
1448 link->rect.makeOffset(scalarX, scalarY), link->data));
1449 }
1450 for (RectWithData* link : pdfDevice->fLinkToDestinations) {
1451 fLinkToDestinations.push(new RectWithData(
1452 link->rect.makeOffset(scalarX, scalarY), link->data));
1453 }
1454 for (NamedDestination* d : pdfDevice->fNamedDestinations) {
1455 fNamedDestinations.push(new NamedDestination(
1456 d->nameData, d->point + SkPoint::Make(scalarX, scalarY)));
1457 }
1458
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001459 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001460 return;
1461 }
1462
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001463 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001464 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001465 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001466 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001467 return;
1468 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001469 if (content.needShape()) {
1470 SkPath shape;
1471 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001472 SkIntToScalar(device->width()),
1473 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001474 content.setShape(shape);
1475 }
1476 if (!content.needSource()) {
1477 return;
1478 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001479
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001480 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1481 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001482 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001483
1484 // Merge glyph sets from the drawn device.
1485 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001486}
1487
reed89443ab2014-06-27 11:34:19 -07001488SkImageInfo SkPDFDevice::imageInfo() const {
1489 return fLegacyBitmap.info();
1490}
1491
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001492void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1493 INHERITED::onAttachToCanvas(canvas);
1494
1495 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1496 fClipStack = canvas->getClipStack();
1497}
1498
1499void SkPDFDevice::onDetachFromCanvas() {
1500 INHERITED::onDetachFromCanvas();
1501
halcanary96fcdcc2015-08-27 07:41:13 -07001502 fClipStack = nullptr;
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001503}
1504
reed4a8126e2014-09-22 07:29:03 -07001505SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1506 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001507}
1508
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001509ContentEntry* SkPDFDevice::getLastContentEntry() {
1510 if (fDrawingArea == kContent_DrawingArea) {
1511 return fLastContentEntry;
1512 } else {
1513 return fLastMarginContentEntry;
1514 }
1515}
1516
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001517SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001518 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001519 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001520 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001521 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001522 }
1523}
1524
1525void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1526 if (fDrawingArea == kContent_DrawingArea) {
1527 fLastContentEntry = contentEntry;
1528 } else {
1529 fLastMarginContentEntry = contentEntry;
1530 }
1531}
1532
1533void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001534 // A ScopedContentEntry only exists during the course of a draw call, so
1535 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001536 fDrawingArea = drawingArea;
1537}
1538
halcanary2b861552015-04-09 13:27:40 -07001539SkPDFDict* SkPDFDevice::createResourceDict() const {
1540 SkTDArray<SkPDFObject*> fonts;
1541 fonts.setReserve(fFontResources.count());
1542 for (SkPDFFont* font : fFontResources) {
1543 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001544 }
halcanary2b861552015-04-09 13:27:40 -07001545 return SkPDFResourceDict::Create(
1546 &fGraphicStateResources,
1547 &fShaderResources,
1548 &fXObjectResources,
1549 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001550}
1551
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001552const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1553 return fFontResources;
1554}
1555
reed@google.com2a006c12012-09-19 17:05:55 +00001556SkPDFArray* SkPDFDevice::copyMediaBox() const {
1557 // should this be a singleton?
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001558
halcanary385fe4d2015-08-26 13:07:48 -07001559 SkAutoTUnref<SkPDFArray> mediaBox(new SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001560 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001561 mediaBox->appendInt(0);
1562 mediaBox->appendInt(0);
reed@google.comc789cf12011-07-20 12:14:33 +00001563 mediaBox->appendInt(fPageSize.fWidth);
1564 mediaBox->appendInt(fPageSize.fHeight);
halcanary130444f2015-04-25 06:45:07 -07001565 return mediaBox.detach();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001566}
1567
halcanary334fcbc2015-02-24 12:56:16 -08001568SkStreamAsset* SkPDFDevice::content() const {
1569 SkDynamicMemoryWStream buffer;
1570 this->writeContent(&buffer);
halcanary7a14b312015-10-01 07:28:13 -07001571 return buffer.bytesWritten() > 0
1572 ? buffer.detachAsStream()
1573 : new SkMemoryStream;
reed@google.com5667afc2011-06-27 14:42:15 +00001574}
1575
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001576void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1577 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001578 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1579 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001580 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
halcanary96fcdcc2015-08-27 07:41:13 -07001581 while (entry != nullptr) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001582 SkPoint translation;
1583 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001584 translation.negate();
1585 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1586 translation);
1587 gsState.updateMatrix(entry->fState.fMatrix);
1588 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001589
halcanary7af21502015-02-23 12:17:59 -08001590 entry->fContent.writeToStream(data);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001591 entry = entry->fNext.get();
1592 }
1593 gsState.drainStack();
1594}
1595
halcanary334fcbc2015-02-24 12:56:16 -08001596void SkPDFDevice::writeContent(SkWStream* out) const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001597 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanary334fcbc2015-02-24 12:56:16 -08001598 SkPDFUtils::AppendTransform(fInitialTransform, out);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001599 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001600
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001601 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1602 // colors the contentArea white before it starts drawing into it and
1603 // that currently acts as our clip.
1604 // Also, think about adding a transform here (or assume that the values
1605 // sent across account for that)
halcanary334fcbc2015-02-24 12:56:16 -08001606 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), out);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001607
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001608 // If the content area is the entire page, then we don't need to clip
1609 // the content area (PDF area clips to the page size). Otherwise,
1610 // we have to clip to the content area; we've already applied the
1611 // initial transform, so just clip to the device size.
1612 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001613 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1614 SkIntToScalar(this->height()));
halcanary96fcdcc2015-08-27 07:41:13 -07001615 emit_clip(nullptr, &r, out);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001616 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001617
halcanary334fcbc2015-02-24 12:56:16 -08001618 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), out);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001619}
1620
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001621/* Draws an inverse filled path by using Path Ops to compute the positive
1622 * inverse using the current clip as the inverse bounds.
1623 * Return true if this was an inverse path and was properly handled,
1624 * otherwise returns false and the normal drawing routine should continue,
1625 * either as a (incorrect) fallback or because the path was not inverse
1626 * in the first place.
1627 */
1628bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001629 const SkPaint& paint, bool pathIsMutable,
1630 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001631 if (!origPath.isInverseFillType()) {
1632 return false;
1633 }
1634
1635 if (d.fClip->isEmpty()) {
1636 return false;
1637 }
1638
1639 SkPath modifiedPath;
1640 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1641 SkPaint noInversePaint(paint);
1642
1643 // Merge stroking operations into final path.
1644 if (SkPaint::kStroke_Style == paint.getStyle() ||
1645 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1646 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1647 if (doFillPath) {
1648 noInversePaint.setStyle(SkPaint::kFill_Style);
1649 noInversePaint.setStrokeWidth(0);
1650 pathPtr = &modifiedPath;
1651 } else {
1652 // To be consistent with the raster output, hairline strokes
1653 // are rendered as non-inverted.
1654 modifiedPath.toggleInverseFillType();
halcanary96fcdcc2015-08-27 07:41:13 -07001655 drawPath(d, modifiedPath, paint, nullptr, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001656 return true;
1657 }
1658 }
1659
1660 // Get bounds of clip in current transform space
1661 // (clip bounds are given in device space).
1662 SkRect bounds;
1663 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001664 SkMatrix totalMatrix = *d.fMatrix;
1665 if (prePathMatrix) {
1666 totalMatrix.preConcat(*prePathMatrix);
1667 }
1668 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001669 return false;
1670 }
1671 bounds.set(d.fClip->getBounds());
1672 transformInverse.mapRect(&bounds);
1673
1674 // Extend the bounds by the line width (plus some padding)
1675 // so the edge doesn't cause a visible stroke.
1676 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1677 paint.getStrokeWidth() + SK_Scalar1);
1678
1679 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1680 return false;
1681 }
1682
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001683 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001684 return true;
1685}
1686
epoger@google.comb58772f2013-03-08 09:09:10 +00001687bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1688 const SkMatrix& matrix,
wangxianzhud76665d2015-07-17 17:23:15 -07001689 SkAnnotation* annotationInfo) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001690 SkData* nameData = annotationInfo->find(
1691 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001692 if (nameData) {
1693 for (size_t i = 0; i < count; i++) {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001694 SkPoint transformedPoint;
1695 matrix.mapXY(points[i].x(), points[i].y(), &transformedPoint);
1696 fNamedDestinations.push(new NamedDestination(nameData, transformedPoint));
epoger@google.comb58772f2013-03-08 09:09:10 +00001697 }
wangxianzhud76665d2015-07-17 17:23:15 -07001698 return true;
epoger@google.comb58772f2013-03-08 09:09:10 +00001699 }
1700 return false;
1701}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001702
wangxianzhuef6c50a2015-09-17 20:38:02 -07001703bool SkPDFDevice::handlePathAnnotation(const SkPath& path,
1704 const SkDraw& d,
1705 SkAnnotation* annotation) {
1706 SkASSERT(annotation);
1707
1708 SkPath transformedPath = path;
1709 transformedPath.transform(*d.fMatrix);
1710 SkRasterClip clip = *d.fRC;
senorblancoafc7cce2016-02-02 18:44:15 -08001711 clip.op(transformedPath, SkIRect::MakeWH(width(), height()), SkRegion::kIntersect_Op,
1712 false);
wangxianzhuef6c50a2015-09-17 20:38:02 -07001713 SkRect transformedRect = SkRect::Make(clip.getBounds());
1714
1715 SkData* urlData = annotation->find(SkAnnotationKeys::URL_Key());
1716 if (urlData) {
1717 if (!transformedRect.isEmpty()) {
1718 fLinkToURLs.push(new RectWithData(transformedRect, urlData));
1719 }
1720 return true;
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001721 }
wangxianzhuef6c50a2015-09-17 20:38:02 -07001722
1723 SkData* linkToDestination =
1724 annotation->find(SkAnnotationKeys::Link_Named_Dest_Key());
1725 if (linkToDestination) {
1726 if (!transformedRect.isEmpty()) {
1727 fLinkToDestinations.push(new RectWithData(transformedRect, linkToDestination));
1728 }
1729 return true;
1730 }
1731
1732 return false;
halcanary438de492015-04-28 06:21:01 -07001733}
1734
wangxianzhuef6c50a2015-09-17 20:38:02 -07001735void SkPDFDevice::appendAnnotations(SkPDFArray* array) const {
1736 array->reserve(fLinkToURLs.count() + fLinkToDestinations.count());
1737 for (RectWithData* rectWithURL : fLinkToURLs) {
1738 SkRect r;
1739 fInitialTransform.mapRect(&r, rectWithURL->rect);
1740 array->appendObject(create_link_to_url(rectWithURL->data, r));
1741 }
1742 for (RectWithData* linkToDestination : fLinkToDestinations) {
1743 SkRect r;
1744 fInitialTransform.mapRect(&r, linkToDestination->rect);
1745 array->appendObject(create_link_named_dest(linkToDestination->data, r));
1746 }
1747}
epoger@google.comb58772f2013-03-08 09:09:10 +00001748
halcanary6d622702015-03-25 08:45:42 -07001749void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
wangxianzhuef6c50a2015-09-17 20:38:02 -07001750 for (NamedDestination* dest : fNamedDestinations) {
halcanary385fe4d2015-08-26 13:07:48 -07001751 SkAutoTUnref<SkPDFArray> pdfDest(new SkPDFArray);
epoger@google.comb58772f2013-03-08 09:09:10 +00001752 pdfDest->reserve(5);
halcanary130444f2015-04-25 06:45:07 -07001753 pdfDest->appendObjRef(SkRef(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001754 pdfDest->appendName("XYZ");
wangxianzhuef6c50a2015-09-17 20:38:02 -07001755 SkPoint p = fInitialTransform.mapXY(dest->point.x(), dest->point.y());
1756 pdfDest->appendScalar(p.x());
1757 pdfDest->appendScalar(p.y());
epoger@google.comb58772f2013-03-08 09:09:10 +00001758 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary130444f2015-04-25 06:45:07 -07001759 SkString name(static_cast<const char*>(dest->nameData->data()));
1760 dict->insertObject(name, pdfDest.detach());
epoger@google.comb58772f2013-03-08 09:09:10 +00001761 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001762}
1763
reed@google.comfc641d02012-09-20 17:52:20 +00001764SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
halcanary385fe4d2015-08-26 13:07:48 -07001765 SkPDFFormXObject* xobject = new SkPDFFormXObject(this);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001766 // We always draw the form xobjects that we create back into the device, so
1767 // we simply preserve the font usage instead of pulling it out and merging
1768 // it back in later.
1769 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001770 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001771 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001772}
1773
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001774void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1775 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001776 const SkClipStack* clipStack,
1777 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001778 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001779 bool invertClip) {
1780 if (clipRegion.isEmpty() && !invertClip) {
1781 return;
1782 }
1783
halcanarybe27a112015-04-01 13:31:19 -07001784 SkAutoTUnref<SkPDFObject> sMaskGS(SkPDFGraphicState::GetSMaskGraphicState(
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001785 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1786
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001787 SkMatrix identity;
1788 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001789 SkPaint paint;
1790 paint.setXfermodeMode(mode);
1791 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001792 if (!content.entry()) {
1793 return;
1794 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001795 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001796 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001797 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001798
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001799 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001800 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001801 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001802}
1803
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001804ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1805 const SkRegion& clipRegion,
1806 const SkMatrix& matrix,
1807 const SkPaint& paint,
1808 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001809 SkPDFFormXObject** dst) {
halcanary96fcdcc2015-08-27 07:41:13 -07001810 *dst = nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001811 if (clipRegion.isEmpty()) {
halcanary96fcdcc2015-08-27 07:41:13 -07001812 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001813 }
1814
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001815 // The clip stack can come from an SkDraw where it is technically optional.
1816 SkClipStack synthesizedClipStack;
halcanary96fcdcc2015-08-27 07:41:13 -07001817 if (clipStack == nullptr) {
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001818 if (clipRegion == fExistingClipRegion) {
1819 clipStack = &fExistingClipStack;
1820 } else {
1821 // GraphicStackState::updateClip expects the clip stack to have
1822 // fExistingClip as a prefix, so start there, then set the clip
1823 // to the passed region.
1824 synthesizedClipStack = fExistingClipStack;
1825 SkPath clipPath;
1826 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001827 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1828 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001829 clipStack = &synthesizedClipStack;
1830 }
1831 }
1832
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001833 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1834 if (paint.getXfermode()) {
1835 paint.getXfermode()->asMode(&xfermode);
1836 }
1837
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001838 // For the following modes, we want to handle source and destination
1839 // separately, so make an object of what's already there.
1840 if (xfermode == SkXfermode::kClear_Mode ||
1841 xfermode == SkXfermode::kSrc_Mode ||
1842 xfermode == SkXfermode::kSrcIn_Mode ||
1843 xfermode == SkXfermode::kDstIn_Mode ||
1844 xfermode == SkXfermode::kSrcOut_Mode ||
1845 xfermode == SkXfermode::kDstOut_Mode ||
1846 xfermode == SkXfermode::kSrcATop_Mode ||
1847 xfermode == SkXfermode::kDstATop_Mode ||
1848 xfermode == SkXfermode::kModulate_Mode) {
1849 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001850 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001851 SkASSERT(isContentEmpty());
1852 } else if (xfermode != SkXfermode::kSrc_Mode &&
1853 xfermode != SkXfermode::kSrcOut_Mode) {
1854 // Except for Src and SrcOut, if there isn't anything already there,
1855 // then we're done.
halcanary96fcdcc2015-08-27 07:41:13 -07001856 return nullptr;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001857 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001858 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001859 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001860 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001861
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001862 // Dst xfer mode doesn't draw source at all.
1863 if (xfermode == SkXfermode::kDst_Mode) {
halcanary96fcdcc2015-08-27 07:41:13 -07001864 return nullptr;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001865 }
1866
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001867 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001868 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001869
1870 ContentEntry* lastContentEntry = getLastContentEntry();
1871 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1872 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001873 } else {
1874 newEntry.reset(new ContentEntry);
1875 entry = newEntry.get();
1876 }
1877
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001878 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001879 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001880 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1881 entry->fState.compareInitialState(lastContentEntry->fState)) {
1882 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001883 }
1884
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001885 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001886 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001887 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001888 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001889 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001890 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001891 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001892 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001893 lastContentEntry->fNext.reset(entry);
1894 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001895 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001896 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001897 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001898}
1899
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001900void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001901 SkPDFFormXObject* dst,
1902 SkPath* shape) {
1903 if (xfermode != SkXfermode::kClear_Mode &&
1904 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001905 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001906 xfermode != SkXfermode::kSrcIn_Mode &&
1907 xfermode != SkXfermode::kDstIn_Mode &&
1908 xfermode != SkXfermode::kSrcOut_Mode &&
1909 xfermode != SkXfermode::kDstOut_Mode &&
1910 xfermode != SkXfermode::kSrcATop_Mode &&
1911 xfermode != SkXfermode::kDstATop_Mode &&
1912 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001913 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001914 return;
1915 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001916 if (xfermode == SkXfermode::kDstOver_Mode) {
1917 SkASSERT(!dst);
1918 ContentEntry* firstContentEntry = getContentEntries()->get();
1919 if (firstContentEntry->fContent.getOffset() == 0) {
1920 // For DstOver, an empty content entry was inserted before the rest
1921 // of the content entries. If nothing was drawn, it needs to be
1922 // removed.
1923 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1924 contentEntries->reset(firstContentEntry->fNext.detach());
1925 }
1926 return;
1927 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001928 if (!dst) {
1929 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1930 xfermode == SkXfermode::kSrcOut_Mode);
1931 return;
1932 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001933
1934 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001935 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001936 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001937 // Changing the current content into a form-xobject will destroy the clip
1938 // objects which is fine since the xobject will already be clipped. However
1939 // if source has shape, we need to clip it too, so a copy of the clip is
1940 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001941 SkClipStack clipStack = contentEntries->fState.fClipStack;
1942 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001943
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001944 SkMatrix identity;
1945 identity.reset();
1946 SkPaint stockPaint;
1947
reed@google.comfc641d02012-09-20 17:52:20 +00001948 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001949 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001950 // If nothing was drawn and there's no shape, then the draw was a
1951 // no-op, but dst needs to be restored for that to be true.
1952 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1953 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1954 // reduces to Dst.
halcanary96fcdcc2015-08-27 07:41:13 -07001955 if (shape == nullptr || xfermode == SkXfermode::kDstOut_Mode ||
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001956 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001957 ScopedContentEntry content(this, &fExistingClipStack,
1958 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001959 stockPaint);
1960 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1961 &content.entry()->fContent);
1962 return;
1963 } else {
1964 xfermode = SkXfermode::kClear_Mode;
1965 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001966 } else {
1967 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001968 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001969 }
1970
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001971 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1972 // without alpha.
1973 if (xfermode == SkXfermode::kSrcATop_Mode) {
1974 // TODO(vandebo): In order to properly support SrcATop we have to track
1975 // the shape of what's been drawn at all times. It's the intersection of
1976 // the non-transparent parts of the device and the outlines (shape) of
1977 // all images and devices drawn.
1978 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001979 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001980 SkXfermode::kSrcOver_Mode, true);
1981 } else {
1982 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1983 SkPDFFormXObject* dstMask = srcFormXObject.get();
halcanary96fcdcc2015-08-27 07:41:13 -07001984 if (shape != nullptr) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001985 // Draw shape into a form-xobject.
1986 SkDraw d;
1987 d.fMatrix = &identity;
1988 d.fClip = &clipRegion;
1989 d.fClipStack = &clipStack;
1990 SkPaint filledPaint;
1991 filledPaint.setColor(SK_ColorBLACK);
1992 filledPaint.setStyle(SkPaint::kFill_Style);
halcanary96fcdcc2015-08-27 07:41:13 -07001993 this->drawPath(d, *shape, filledPaint, nullptr, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001994
1995 dstMaskStorage.reset(createFormXObjectFromDevice());
1996 dstMask = dstMaskStorage.get();
1997 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001998 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1999 &fExistingClipStack, fExistingClipRegion,
2000 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002001 }
2002
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002003 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002004 return;
2005 } else if (xfermode == SkXfermode::kSrc_Mode ||
2006 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002007 ScopedContentEntry content(this, &fExistingClipStack,
2008 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002009 if (content.entry()) {
2010 SkPDFUtils::DrawFormXObject(
2011 this->addXObjectResource(srcFormXObject.get()),
2012 &content.entry()->fContent);
2013 }
2014 if (xfermode == SkXfermode::kSrc_Mode) {
2015 return;
2016 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002017 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002018 ScopedContentEntry content(this, &fExistingClipStack,
2019 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00002020 if (content.entry()) {
2021 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
2022 &content.entry()->fContent);
2023 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002024 }
2025
2026 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
2027 xfermode == SkXfermode::kDstIn_Mode ||
2028 xfermode == SkXfermode::kSrcOut_Mode ||
2029 xfermode == SkXfermode::kDstOut_Mode ||
2030 xfermode == SkXfermode::kSrcATop_Mode ||
2031 xfermode == SkXfermode::kDstATop_Mode ||
2032 xfermode == SkXfermode::kModulate_Mode);
2033
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002034 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002035 xfermode == SkXfermode::kSrcOut_Mode ||
2036 xfermode == SkXfermode::kSrcATop_Mode) {
2037 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002038 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002039 SkXfermode::kSrcOver_Mode,
2040 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002041 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002042 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
2043 if (xfermode == SkXfermode::kModulate_Mode) {
2044 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002045 dst, &fExistingClipStack,
2046 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002047 SkXfermode::kSrcOver_Mode, false);
2048 mode = SkXfermode::kMultiply_Mode;
2049 }
2050 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00002051 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002052 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002053 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002054}
2055
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002056bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00002057 ContentEntry* contentEntries = getContentEntries()->get();
2058 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
2059 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00002060 return true;
2061 }
2062 return false;
2063}
2064
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002065void SkPDFDevice::populateGraphicStateEntryFromPaint(
2066 const SkMatrix& matrix,
2067 const SkClipStack& clipStack,
2068 const SkRegion& clipRegion,
2069 const SkPaint& paint,
2070 bool hasText,
2071 GraphicStateEntry* entry) {
halcanary96fcdcc2015-08-27 07:41:13 -07002072 NOT_IMPLEMENTED(paint.getPathEffect() != nullptr, false);
2073 NOT_IMPLEMENTED(paint.getMaskFilter() != nullptr, false);
2074 NOT_IMPLEMENTED(paint.getColorFilter() != nullptr, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002075
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002076 entry->fMatrix = matrix;
2077 entry->fClipStack = clipStack;
2078 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00002079 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
2080 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00002081
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002082 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002083 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002084 const SkShader* shader = paint.getShader();
2085 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002086 if (shader) {
2087 // PDF positions patterns relative to the initial transform, so
2088 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002089 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00002090 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002091
2092 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002093 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002094 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00002095
2096 // We need to apply the initial transform to bounds in order to get
2097 // bounds in a consistent coordinate system.
2098 SkRect boundsTemp;
2099 boundsTemp.set(bounds);
2100 fInitialTransform.mapRect(&boundsTemp);
2101 boundsTemp.roundOut(&bounds);
2102
halcanary792c80f2015-02-20 07:21:05 -08002103 SkScalar rasterScale =
2104 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
2105 pdfShader.reset(SkPDFShader::GetPDFShader(
2106 fCanon, fRasterDpi, *shader, transform, bounds, rasterScale));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002107
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002108 if (pdfShader.get()) {
2109 // pdfShader has been canonicalized so we can directly compare
2110 // pointers.
2111 int resourceIndex = fShaderResources.find(pdfShader.get());
2112 if (resourceIndex < 0) {
2113 resourceIndex = fShaderResources.count();
2114 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002115 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00002116 }
2117 entry->fShaderIndex = resourceIndex;
2118 } else {
2119 // A color shader is treated as an invalid shader so we don't have
2120 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002121 SkShader::GradientInfo gradientInfo;
2122 SkColor gradientColor;
2123 gradientInfo.fColors = &gradientColor;
halcanary96fcdcc2015-08-27 07:41:13 -07002124 gradientInfo.fColorOffsets = nullptr;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002125 gradientInfo.fColorCount = 1;
2126 if (shader->asAGradient(&gradientInfo) ==
2127 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002128 entry->fColor = SkColorSetA(gradientColor, 0xFF);
2129 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002130 }
2131 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002132 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002133
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002134 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002135 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002136 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08002137 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002138 } else {
2139 SkPaint newPaint = paint;
2140 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002141 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08002142 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002143 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002144 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002145 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002146
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002147 if (hasText) {
2148 entry->fTextScaleX = paint.getTextScaleX();
2149 entry->fTextFill = paint.getStyle();
2150 } else {
2151 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002152 }
2153}
2154
halcanarybe27a112015-04-01 13:31:19 -07002155int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002156 // Assumes that gs has been canonicalized (so we can directly compare
2157 // pointers).
2158 int result = fGraphicStateResources.find(gs);
2159 if (result < 0) {
2160 result = fGraphicStateResources.count();
2161 fGraphicStateResources.push(gs);
2162 gs->ref();
2163 }
2164 return result;
2165}
2166
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002167int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2168 // Assumes that xobject has been canonicalized (so we can directly compare
2169 // pointers).
2170 int result = fXObjectResources.find(xObject);
2171 if (result < 0) {
2172 result = fXObjectResources.count();
2173 fXObjectResources.push(xObject);
2174 xObject->ref();
2175 }
2176 return result;
2177}
2178
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002179void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2180 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002181 SkTypeface* typeface = paint.getTypeface();
halcanary96fcdcc2015-08-27 07:41:13 -07002182 if (contentEntry->fState.fFont == nullptr ||
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002183 contentEntry->fState.fTextSize != paint.getTextSize() ||
2184 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002185 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002186 contentEntry->fContent.writeText("/");
2187 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2188 SkPDFResourceDict::kFont_ResourceType,
2189 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002190 contentEntry->fContent.writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -07002191 SkPDFUtils::AppendScalar(paint.getTextSize(), &contentEntry->fContent);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002192 contentEntry->fContent.writeText(" Tf\n");
2193 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002194 }
2195}
2196
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002197int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary792c80f2015-02-20 07:21:05 -08002198 SkAutoTUnref<SkPDFFont> newFont(
2199 SkPDFFont::GetFontResource(fCanon, typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002200 int resourceIndex = fFontResources.find(newFont.get());
2201 if (resourceIndex < 0) {
2202 resourceIndex = fFontResources.count();
2203 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002204 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002205 }
2206 return resourceIndex;
2207}
2208
halcanary7a14b312015-10-01 07:28:13 -07002209static SkSize rect_to_size(const SkRect& r) {
2210 return SkSize::Make(r.width(), r.height());
2211}
2212
2213static const SkImage* color_filter(const SkImage* image,
2214 SkColorFilter* colorFilter) {
2215 SkAutoTUnref<SkSurface> surface(SkSurface::NewRaster(
2216 SkImageInfo::MakeN32Premul(image->dimensions())));
2217 if (!surface) {
2218 return image;
2219 }
2220 SkCanvas* canvas = surface->getCanvas();
2221 canvas->clear(SK_ColorTRANSPARENT);
2222 SkPaint paint;
2223 paint.setColorFilter(colorFilter);
2224 canvas->drawImage(image, 0, 0, &paint);
2225 canvas->flush();
2226 return surface->newImageSnapshot();
2227}
2228
2229////////////////////////////////////////////////////////////////////////////////
2230void SkPDFDevice::internalDrawImage(const SkMatrix& origMatrix,
2231 const SkClipStack* clipStack,
2232 const SkRegion& origClipRegion,
2233 const SkImage* image,
2234 const SkIRect* srcRect,
2235 const SkPaint& paint) {
2236 SkASSERT(image);
2237 #ifdef SK_PDF_IMAGE_STATS
2238 gDrawImageCalls.fetch_add(1);
2239 #endif
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002240 SkMatrix matrix = origMatrix;
2241 SkRegion perspectiveBounds;
2242 const SkRegion* clipRegion = &origClipRegion;
halcanary7a14b312015-10-01 07:28:13 -07002243 SkAutoTUnref<const SkImage> autoImageUnref;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002244
halcanary7a14b312015-10-01 07:28:13 -07002245 if (srcRect) {
2246 autoImageUnref.reset(image->newSubset(*srcRect));
2247 if (!autoImageUnref) {
2248 return;
2249 }
2250 image = autoImageUnref;
2251 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002252 // Rasterize the bitmap using perspective in a new bitmap.
2253 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002254 if (fRasterDpi == 0) {
2255 return;
2256 }
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002257 // Transform the bitmap in the new space, without taking into
2258 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002259 SkPath perspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002260 SkRect imageBounds = SkRect::Make(image->bounds());
2261 perspectiveOutline.addRect(imageBounds);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002262 perspectiveOutline.transform(origMatrix);
2263
2264 // TODO(edisonn): perf - use current clip too.
2265 // Retrieve the bounds of the new shape.
2266 SkRect bounds = perspectiveOutline.getBounds();
2267
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002268 // Transform the bitmap in the new space, taking into
2269 // account the initial transform.
2270 SkMatrix total = origMatrix;
2271 total.postConcat(fInitialTransform);
halcanary7a14b312015-10-01 07:28:13 -07002272 SkScalar dpiScale = SkIntToScalar(fRasterDpi) /
2273 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE);
2274 total.postScale(dpiScale, dpiScale);
2275
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002276 SkPath physicalPerspectiveOutline;
halcanary7a14b312015-10-01 07:28:13 -07002277 physicalPerspectiveOutline.addRect(imageBounds);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002278 physicalPerspectiveOutline.transform(total);
2279
halcanary7a14b312015-10-01 07:28:13 -07002280 SkRect physicalPerspectiveBounds =
2281 physicalPerspectiveOutline.getBounds();
2282 SkScalar scaleX = physicalPerspectiveBounds.width() / bounds.width();
2283 SkScalar scaleY = physicalPerspectiveBounds.height() / bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002284
2285 // TODO(edisonn): A better approach would be to use a bitmap shader
2286 // (in clamp mode) and draw a rect over the entire bounding box. Then
2287 // intersect perspectiveOutline to the clip. That will avoid introducing
2288 // alpha to the image while still giving good behavior at the edge of
2289 // the image. Avoiding alpha will reduce the pdf size and generation
2290 // CPU time some.
2291
halcanary7a14b312015-10-01 07:28:13 -07002292 SkISize wh = rect_to_size(physicalPerspectiveBounds).toCeil();
2293
2294 SkAutoTUnref<SkSurface> surface(
2295 SkSurface::NewRaster(SkImageInfo::MakeN32Premul(wh)));
2296 if (!surface) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002297 return;
2298 }
halcanary7a14b312015-10-01 07:28:13 -07002299 SkCanvas* canvas = surface->getCanvas();
2300 canvas->clear(SK_ColorTRANSPARENT);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002301
2302 SkScalar deltaX = bounds.left();
2303 SkScalar deltaY = bounds.top();
2304
2305 SkMatrix offsetMatrix = origMatrix;
2306 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002307 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002308
2309 // Translate the draw in the new canvas, so we perfectly fit the
2310 // shape in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002311 canvas->setMatrix(offsetMatrix);
2312 canvas->drawImage(image, 0, 0, nullptr);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002313 // Make sure the final bits are in the bitmap.
halcanary7a14b312015-10-01 07:28:13 -07002314 canvas->flush();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002315
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002316 // In the new space, we use the identity matrix translated
2317 // and scaled to reflect DPI.
2318 matrix.setScale(1 / scaleX, 1 / scaleY);
2319 matrix.postTranslate(deltaX, deltaY);
2320
halcanary7a14b312015-10-01 07:28:13 -07002321 perspectiveBounds.setRect(bounds.roundOut());
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002322 clipRegion = &perspectiveBounds;
halcanary96fcdcc2015-08-27 07:41:13 -07002323 srcRect = nullptr;
halcanary7a14b312015-10-01 07:28:13 -07002324
2325 autoImageUnref.reset(surface->newImageSnapshot());
2326 image = autoImageUnref;
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002327 }
2328
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002329 SkMatrix scaled;
2330 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002331 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2332 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002333 // Scale the image up from 1x1 to WxH.
halcanary7a14b312015-10-01 07:28:13 -07002334 SkIRect subset = image->bounds();
2335 scaled.postScale(SkIntToScalar(image->width()),
2336 SkIntToScalar(image->height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002337 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002338 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002339 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2340 return;
2341 }
2342 if (content.needShape()) {
2343 SkPath shape;
halcanary7a14b312015-10-01 07:28:13 -07002344 shape.addRect(SkRect::Make(subset));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002345 shape.transform(matrix);
2346 content.setShape(shape);
2347 }
2348 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002349 return;
2350 }
2351
halcanary287d22d2015-09-24 10:20:05 -07002352 if (SkColorFilter* colorFilter = paint.getColorFilter()) {
halcanary6950de62015-11-07 05:29:00 -08002353 // TODO(https://bug.skia.org/4378): implement colorfilter on other
halcanary7a14b312015-10-01 07:28:13 -07002354 // draw calls. This code here works for all
2355 // drawBitmap*()/drawImage*() calls amd ImageFilters (which
2356 // rasterize a layer on this backend). Fortuanely, this seems
2357 // to be how Chromium impements most color-filters.
2358 autoImageUnref.reset(color_filter(image, colorFilter));
2359 image = autoImageUnref;
2360 // TODO(halcanary): de-dupe this by caching filtered images.
2361 // (maybe in the resource cache?)
2362 }
halcanary3d8c33c2015-10-01 11:06:22 -07002363 SkAutoTUnref<SkPDFObject> pdfimage(SkSafeRef(fCanon->findPDFBitmap(image)));
halcanary7a14b312015-10-01 07:28:13 -07002364 if (!pdfimage) {
halcanary712fdf72015-12-10 08:59:43 -08002365 pdfimage.reset(SkPDFCreateBitmapObject(
2366 image, fCanon->fPixelSerializer));
halcanary7a14b312015-10-01 07:28:13 -07002367 if (!pdfimage) {
2368 return;
halcanary287d22d2015-09-24 10:20:05 -07002369 }
halcanary7a14b312015-10-01 07:28:13 -07002370 fCanon->addPDFBitmap(image->uniqueID(), pdfimage);
halcanary287d22d2015-09-24 10:20:05 -07002371 }
halcanary3d8c33c2015-10-01 11:06:22 -07002372 SkPDFUtils::DrawFormXObject(this->addXObjectResource(pdfimage.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002373 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002374}