blob: c1c77e2031345f02e325763d7eafeb35c66b0b2c [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"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000012#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000013#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000014#include "SkDraw.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000015#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000016#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000017#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000018#include "SkPathOps.h"
halcanarydb0dcc72015-03-20 12:31:52 -070019#include "SkPDFBitmap.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000021#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000022#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000023#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000024#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000025#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000026#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000027#include "SkPDFUtils.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000028#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000029#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000030#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070031#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000032#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000033#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000034#include "SkTypefacePriv.h"
halcanarya6814332015-05-27 08:53:36 -070035#include "SkXfermodeInterpretation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000036
edisonn@google.com73a7ea32013-11-11 20:55:15 +000037#define DPI_FOR_RASTER_SCALE_ONE 72
38
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000039// Utility functions
40
halcanarya6814332015-05-27 08:53:36 -070041// If the paint will definitely draw opaquely, replace kSrc_Mode with
42// kSrcOver_Mode. http://crbug.com/473572
43static void replace_srcmode_on_opaque_paint(SkPaint* paint) {
44 if (kSrcOver_SkXfermodeInterpretation
45 == SkInterpretXfermode(*paint, false)) {
46 paint->setXfermode(NULL);
47 }
48}
49
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000050static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000051 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
reed80ea19c2015-05-12 10:37:34 -070052 SkScalar colorScale = SkScalarInvert(0xFF);
53 SkPDFUtils::AppendScalar(SkColorGetR(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000054 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070055 SkPDFUtils::AppendScalar(SkColorGetG(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000056 result->writeText(" ");
reed80ea19c2015-05-12 10:37:34 -070057 SkPDFUtils::AppendScalar(SkColorGetB(color) * colorScale, result);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000058 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000059}
60
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000061static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000062 SkPaint result = paint;
63 if (result.isFakeBoldText()) {
64 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
65 kStdFakeBoldInterpKeys,
66 kStdFakeBoldInterpValues,
67 kStdFakeBoldInterpLength);
68 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000069 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000070 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000071 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000072 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000073 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000074 result.setStrokeWidth(width);
75 }
76 return result;
77}
78
79// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000080static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000081 const uint16_t* glyphs, size_t len,
82 SkScalar* x, SkScalar* y) {
83 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000084 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000085 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000086
87 SkMatrix ident;
88 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000089 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000090 SkGlyphCache* cache = autoCache.getCache();
91
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000092 const char* start = reinterpret_cast<const char*>(glyphs);
93 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000094 SkFixed xAdv = 0, yAdv = 0;
95
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000096 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000097 while (start < stop) {
98 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
99 xAdv += glyph.fAdvanceX;
100 yAdv += glyph.fAdvanceY;
101 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000102 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000103 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000104 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000105
106 SkScalar xAdj = SkFixedToScalar(xAdv);
107 SkScalar yAdj = SkFixedToScalar(yAdv);
108 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
109 xAdj = SkScalarHalf(xAdj);
110 yAdj = SkScalarHalf(yAdj);
111 }
112 *x = *x - xAdj;
113 *y = *y - yAdj;
114}
115
robertphillips@google.coma4662862013-11-21 14:24:16 +0000116static int max_glyphid_for_typeface(SkTypeface* typeface) {
reed@google.comfed86bd2013-03-14 15:04:57 +0000117 SkAutoResolveDefaultTypeface autoResolve(typeface);
118 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000119 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000120}
121
122typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
123
reed@google.comaec40662014-04-18 19:29:07 +0000124static int force_glyph_encoding(const SkPaint& paint, const void* text,
125 size_t len, SkGlyphStorage* storage,
bungeman22edc832014-10-03 07:55:58 -0700126 const uint16_t** glyphIDs) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000127 // Make sure we have a glyph id encoding.
128 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
reed@google.comaec40662014-04-18 19:29:07 +0000129 int numGlyphs = paint.textToGlyphs(text, len, NULL);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000130 storage->reset(numGlyphs);
131 paint.textToGlyphs(text, len, storage->get());
132 *glyphIDs = storage->get();
133 return numGlyphs;
134 }
135
136 // For user supplied glyph ids we need to validate them.
137 SkASSERT((len & 1) == 0);
reed@google.comaec40662014-04-18 19:29:07 +0000138 int numGlyphs = SkToInt(len / 2);
bungeman22edc832014-10-03 07:55:58 -0700139 const uint16_t* input = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000140
141 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
reed@google.comaec40662014-04-18 19:29:07 +0000142 int validated;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000143 for (validated = 0; validated < numGlyphs; ++validated) {
144 if (input[validated] > maxGlyphID) {
145 break;
146 }
147 }
148 if (validated >= numGlyphs) {
bungeman22edc832014-10-03 07:55:58 -0700149 *glyphIDs = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000150 return numGlyphs;
151 }
152
153 // Silently drop anything out of range.
154 storage->reset(numGlyphs);
155 if (validated > 0) {
156 memcpy(storage->get(), input, validated * sizeof(uint16_t));
157 }
158
reed@google.comaec40662014-04-18 19:29:07 +0000159 for (int i = validated; i < numGlyphs; ++i) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000160 storage->get()[i] = input[i];
161 if (input[i] > maxGlyphID) {
162 storage->get()[i] = 0;
163 }
164 }
165 *glyphIDs = storage->get();
166 return numGlyphs;
167}
168
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000169static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
170 SkWStream* content) {
171 // Flip the text about the x-axis to account for origin swap and include
172 // the passed parameters.
173 content->writeText("1 0 ");
halcanarybc4696b2015-05-06 10:56:04 -0700174 SkPDFUtils::AppendScalar(0 - textSkewX, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000175 content->writeText(" -1 ");
halcanarybc4696b2015-05-06 10:56:04 -0700176 SkPDFUtils::AppendScalar(x, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000177 content->writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -0700178 SkPDFUtils::AppendScalar(y, content);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000179 content->writeText(" Tm\n");
180}
181
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000182// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
183// later being our representation of an object in the PDF file.
184struct GraphicStateEntry {
185 GraphicStateEntry();
186
187 // Compare the fields we care about when setting up a new content entry.
188 bool compareInitialState(const GraphicStateEntry& b);
189
190 SkMatrix fMatrix;
191 // We can't do set operations on Paths, though PDF natively supports
192 // intersect. If the clip stack does anything other than intersect,
193 // we have to fall back to the region. Treat fClipStack as authoritative.
194 // See http://code.google.com/p/skia/issues/detail?id=221
195 SkClipStack fClipStack;
196 SkRegion fClipRegion;
197
198 // When emitting the content entry, we will ensure the graphic state
199 // is set to these values first.
200 SkColor fColor;
201 SkScalar fTextScaleX; // Zero means we don't care what the value is.
202 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
203 int fShaderIndex;
204 int fGraphicStateIndex;
205
206 // We may change the font (i.e. for Type1 support) within a
207 // ContentEntry. This is the one currently in effect, or NULL if none.
208 SkPDFFont* fFont;
209 // In PDF, text size has no default value. It is only valid if fFont is
210 // not NULL.
211 SkScalar fTextSize;
212};
213
214GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
215 fTextScaleX(SK_Scalar1),
216 fTextFill(SkPaint::kFill_Style),
217 fShaderIndex(-1),
218 fGraphicStateIndex(-1),
219 fFont(NULL),
220 fTextSize(SK_ScalarNaN) {
221 fMatrix.reset();
222}
223
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000224bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
225 return fColor == cur.fColor &&
226 fShaderIndex == cur.fShaderIndex &&
227 fGraphicStateIndex == cur.fGraphicStateIndex &&
228 fMatrix == cur.fMatrix &&
229 fClipStack == cur.fClipStack &&
230 (fTextScaleX == 0 ||
231 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000232}
233
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000234class GraphicStackState {
235public:
236 GraphicStackState(const SkClipStack& existingClipStack,
237 const SkRegion& existingClipRegion,
238 SkWStream* contentStream)
239 : fStackDepth(0),
240 fContentStream(contentStream) {
241 fEntries[0].fClipStack = existingClipStack;
242 fEntries[0].fClipRegion = existingClipRegion;
243 }
244
245 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000246 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000247 void updateMatrix(const SkMatrix& matrix);
248 void updateDrawingState(const GraphicStateEntry& state);
249
250 void drainStack();
251
252private:
253 void push();
254 void pop();
255 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
256
257 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
258 static const int kMaxStackDepth = 12;
259 GraphicStateEntry fEntries[kMaxStackDepth + 1];
260 int fStackDepth;
261 SkWStream* fContentStream;
262};
263
264void GraphicStackState::drainStack() {
265 while (fStackDepth) {
266 pop();
267 }
268}
269
270void GraphicStackState::push() {
271 SkASSERT(fStackDepth < kMaxStackDepth);
272 fContentStream->writeText("q\n");
273 fStackDepth++;
274 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
275}
276
277void GraphicStackState::pop() {
278 SkASSERT(fStackDepth > 0);
279 fContentStream->writeText("Q\n");
280 fStackDepth--;
281}
282
robertphillips@google.com80214e22012-07-20 15:33:18 +0000283// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000284// and then skips over the leading entries as specified in prefix. It requires
285// and asserts that "prefix" will be a prefix to "stack."
286static void skip_clip_stack_prefix(const SkClipStack& prefix,
287 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000288 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000289 SkClipStack::B2TIter prefixIter(prefix);
290 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000291
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000292 const SkClipStack::Element* prefixEntry;
293 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000294
295 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000296 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000297 iterEntry = iter->next();
298 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000299 // Because of SkClipStack does internal intersection, the last clip
300 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000301 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000302 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
303 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
304 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000305 // back up the iterator by one
306 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000307 prefixEntry = prefixIter.next();
308 break;
309 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000310 }
311
312 SkASSERT(prefixEntry == NULL);
313}
314
315static void emit_clip(SkPath* clipPath, SkRect* clipRect,
316 SkWStream* contentStream) {
317 SkASSERT(clipPath || clipRect);
318
319 SkPath::FillType clipFill;
320 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000321 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000322 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000323 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000324 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
325 clipFill = SkPath::kWinding_FillType;
326 }
327
328 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
329 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
330 if (clipFill == SkPath::kEvenOdd_FillType) {
331 contentStream->writeText("W* n\n");
332 } else {
333 contentStream->writeText("W n\n");
334 }
335}
336
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000337/* Calculate an inverted path's equivalent non-inverted path, given the
338 * canvas bounds.
339 * outPath may alias with invPath (since this is supported by PathOps).
340 */
341static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
342 SkPath* outPath) {
343 SkASSERT(invPath.isInverseFillType());
344
345 SkPath clipPath;
346 clipPath.addRect(bounds);
347
348 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
349}
350
fmalita632e92f2015-04-22 15:02:03 -0700351#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000352// Sanity check the numerical values of the SkRegion ops and PathOps ops
353// enums so region_op_to_pathops_op can do a straight passthrough cast.
354// If these are failing, it may be necessary to make region_op_to_pathops_op
355// do more.
356SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
357 region_pathop_mismatch);
358SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
359 region_pathop_mismatch);
360SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
361 region_pathop_mismatch);
362SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
363 region_pathop_mismatch);
364SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
365 (int)kReverseDifference_PathOp,
366 region_pathop_mismatch);
367
368static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
369 SkASSERT(op >= 0);
370 SkASSERT(op <= SkRegion::kReverseDifference_Op);
371 return (SkPathOp)op;
372}
373
374/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
375 * Returns true if successful, or false if not successful.
376 * If successful, the resulting clip is stored in outClipPath.
377 * If not successful, outClipPath is undefined, and a fallback method
378 * should be used.
379 */
380static bool get_clip_stack_path(const SkMatrix& transform,
381 const SkClipStack& clipStack,
382 const SkRegion& clipRegion,
383 SkPath* outClipPath) {
384 outClipPath->reset();
385 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
386
387 const SkClipStack::Element* clipEntry;
388 SkClipStack::Iter iter;
389 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
390 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
391 SkPath entryPath;
392 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
393 outClipPath->reset();
394 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
395 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000396 } else {
397 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000398 }
399 entryPath.transform(transform);
400
401 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
402 *outClipPath = entryPath;
403 } else {
404 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
405 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
406 return false;
407 }
408 }
409 }
410
411 if (outClipPath->isInverseFillType()) {
412 // The bounds are slightly outset to ensure this is correct in the
413 // face of floating-point accuracy and possible SkRegion bitmap
414 // approximations.
415 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
416 clipBounds.outset(SK_Scalar1, SK_Scalar1);
417 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
418 return false;
419 }
420 }
421 return true;
422}
423#endif
424
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000425// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000426// graphic state stack, and the fact that we can know all the clips used
427// on the page to optimize this.
428void GraphicStackState::updateClip(const SkClipStack& clipStack,
429 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000430 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000431 if (clipStack == currentEntry()->fClipStack) {
432 return;
433 }
434
435 while (fStackDepth > 0) {
436 pop();
437 if (clipStack == currentEntry()->fClipStack) {
438 return;
439 }
440 }
441 push();
442
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000443 currentEntry()->fClipStack = clipStack;
444 currentEntry()->fClipRegion = clipRegion;
445
446 SkMatrix transform;
447 transform.setTranslate(translation.fX, translation.fY);
448
fmalita632e92f2015-04-22 15:02:03 -0700449#ifdef SK_PDF_USE_PATHOPS_CLIPPING
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000450 SkPath clipPath;
451 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
452 emit_clip(&clipPath, NULL, fContentStream);
453 return;
454 }
455#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000456 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
457 // already been applied. (If this is a top level device, then it specifies
458 // a clip to the content area. If this is a layer, then it specifies
459 // the clip in effect when the layer was created.) There's no need to
460 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
461 // initial clip on the parent layer. (This means there's a bug if the user
462 // expands the clip and then uses any xfer mode that uses dst:
463 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000464 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000465 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
466
467 // If the clip stack does anything other than intersect or if it uses
468 // an inverse fill type, we have to fall back to the clip region.
469 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000470 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000471 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000472 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
473 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000474 needRegion = true;
475 break;
476 }
477 }
478
479 if (needRegion) {
480 SkPath clipPath;
481 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
482 emit_clip(&clipPath, NULL, fContentStream);
483 } else {
484 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000485 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000486 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000487 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
488 switch (clipEntry->getType()) {
489 case SkClipStack::Element::kRect_Type: {
490 SkRect translatedClip;
491 transform.mapRect(&translatedClip, clipEntry->getRect());
492 emit_clip(NULL, &translatedClip, fContentStream);
493 break;
494 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000495 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000496 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000497 clipEntry->asPath(&translatedPath);
498 translatedPath.transform(transform, &translatedPath);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000499 emit_clip(&translatedPath, NULL, fContentStream);
500 break;
501 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000502 }
503 }
504 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000505}
506
507void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
508 if (matrix == currentEntry()->fMatrix) {
509 return;
510 }
511
512 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
513 SkASSERT(fStackDepth > 0);
514 SkASSERT(fEntries[fStackDepth].fClipStack ==
515 fEntries[fStackDepth -1].fClipStack);
516 pop();
517
518 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
519 }
520 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
521 return;
522 }
523
524 push();
525 SkPDFUtils::AppendTransform(matrix, fContentStream);
526 currentEntry()->fMatrix = matrix;
527}
528
529void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
530 // PDF treats a shader as a color, so we only set one or the other.
531 if (state.fShaderIndex >= 0) {
532 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000533 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000534 currentEntry()->fShaderIndex = state.fShaderIndex;
535 }
536 } else {
537 if (state.fColor != currentEntry()->fColor ||
538 currentEntry()->fShaderIndex >= 0) {
539 emit_pdf_color(state.fColor, fContentStream);
540 fContentStream->writeText("RG ");
541 emit_pdf_color(state.fColor, fContentStream);
542 fContentStream->writeText("rg\n");
543 currentEntry()->fColor = state.fColor;
544 currentEntry()->fShaderIndex = -1;
545 }
546 }
547
548 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000549 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000550 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
551 }
552
553 if (state.fTextScaleX) {
554 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
555 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
556 SkIntToScalar(100));
halcanarybc4696b2015-05-06 10:56:04 -0700557 SkPDFUtils::AppendScalar(pdfScale, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000558 fContentStream->writeText(" Tz\n");
559 currentEntry()->fTextScaleX = state.fTextScaleX;
560 }
561 if (state.fTextFill != currentEntry()->fTextFill) {
562 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
563 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
564 enum_must_match_value);
565 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
566 enum_must_match_value);
567 fContentStream->writeDecAsText(state.fTextFill);
568 fContentStream->writeText(" Tr\n");
569 currentEntry()->fTextFill = state.fTextFill;
570 }
571 }
572}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000573
reed76033be2015-03-14 10:54:31 -0700574static bool not_supported_for_layers(const SkPaint& layerPaint) {
senorblancob0e89dc2014-10-20 14:03:12 -0700575 // PDF does not support image filters, so render them on CPU.
576 // Note that this rendering is done at "screen" resolution (100dpi), not
577 // printer resolution.
578 // FIXME: It may be possible to express some filters natively using PDF
579 // to improve quality and file size (http://skbug.com/3043)
reed76033be2015-03-14 10:54:31 -0700580
581 // TODO: should we return true if there is a colorfilter?
582 return layerPaint.getImageFilter() != NULL;
583}
584
585SkBaseDevice* SkPDFDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint* layerPaint) {
halcanary00b7e5e2015-04-15 13:05:18 -0700586 if (cinfo.fForImageFilter ||
587 (layerPaint && not_supported_for_layers(*layerPaint))) {
reed61f501f2015-04-29 08:34:00 -0700588 return NULL;
senorblancob0e89dc2014-10-20 14:03:12 -0700589 }
fmalita6987dca2014-11-13 08:33:37 -0800590 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanarya1f1ee92015-02-20 06:17:26 -0800591 return SkPDFDevice::Create(size, fRasterDpi, fCanon);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000592}
593
594
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000595struct ContentEntry {
596 GraphicStateEntry fState;
597 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000598 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000599
600 // If the stack is too deep we could get Stack Overflow.
601 // So we manually destruct the object.
602 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000603 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000604 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000605 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000606 // When the destructor is called, fNext is NULL and exits.
607 delete val;
608 val = valNext;
609 }
610 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000611};
612
613// A helper class to automatically finish a ContentEntry at the end of a
614// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000615class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000616public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000617 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
618 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000619 : fDevice(device),
620 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000621 fXfermode(SkXfermode::kSrcOver_Mode),
622 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000623 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
624 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000625 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
626 const SkRegion& clipRegion, const SkMatrix& matrix,
627 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000628 : fDevice(device),
629 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000630 fXfermode(SkXfermode::kSrcOver_Mode),
631 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000632 init(clipStack, clipRegion, matrix, paint, hasText);
633 }
634
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000635 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000636 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000637 SkPath* shape = &fShape;
638 if (shape->isEmpty()) {
639 shape = NULL;
640 }
641 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000642 }
reed@google.comfc641d02012-09-20 17:52:20 +0000643 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000644 }
645
646 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000647
648 /* Returns true when we explicitly need the shape of the drawing. */
649 bool needShape() {
650 switch (fXfermode) {
651 case SkXfermode::kClear_Mode:
652 case SkXfermode::kSrc_Mode:
653 case SkXfermode::kSrcIn_Mode:
654 case SkXfermode::kSrcOut_Mode:
655 case SkXfermode::kDstIn_Mode:
656 case SkXfermode::kDstOut_Mode:
657 case SkXfermode::kSrcATop_Mode:
658 case SkXfermode::kDstATop_Mode:
659 case SkXfermode::kModulate_Mode:
660 return true;
661 default:
662 return false;
663 }
664 }
665
666 /* Returns true unless we only need the shape of the drawing. */
667 bool needSource() {
668 if (fXfermode == SkXfermode::kClear_Mode) {
669 return false;
670 }
671 return true;
672 }
673
674 /* If the shape is different than the alpha component of the content, then
675 * setShape should be called with the shape. In particular, images and
676 * devices have rectangular shape.
677 */
678 void setShape(const SkPath& shape) {
679 fShape = shape;
680 }
681
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000682private:
683 SkPDFDevice* fDevice;
684 ContentEntry* fContentEntry;
685 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000686 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000687 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000688
689 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
690 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000691 // Shape has to be flatten before we get here.
692 if (matrix.hasPerspective()) {
693 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000694 return;
695 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000696 if (paint.getXfermode()) {
697 paint.getXfermode()->asMode(&fXfermode);
698 }
699 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
700 matrix, paint, hasText,
701 &fDstFormXObject);
702 }
703};
704
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000705////////////////////////////////////////////////////////////////////////////////
706
halcanarya1f1ee92015-02-20 06:17:26 -0800707SkPDFDevice::SkPDFDevice(SkISize pageSize,
708 SkScalar rasterDpi,
709 SkPDFCanon* canon,
710 bool flip)
robertphillips9a53fd72015-06-22 09:46:59 -0700711 : INHERITED(SkSurfaceProps(0, kUnknown_SkPixelGeometry))
712 , fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800713 , fContentSize(pageSize)
714 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
715 , fAnnotations(NULL)
reed89443ab2014-06-27 11:34:19 -0700716 , fLastContentEntry(NULL)
717 , fLastMarginContentEntry(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800718 , fDrawingArea(kContent_DrawingArea)
reed89443ab2014-06-27 11:34:19 -0700719 , fClipStack(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800720 , fFontGlyphUsage(SkNEW(SkPDFGlyphSetMap))
721 , fRasterDpi(rasterDpi)
722 , fCanon(canon) {
723 SkASSERT(pageSize.width() > 0);
724 SkASSERT(pageSize.height() > 0);
725 fLegacyBitmap.setInfo(
726 SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()));
727 if (flip) {
728 // Skia generally uses the top left as the origin but PDF
729 // natively has the origin at the bottom left. This matrix
730 // corrects for that. But that only needs to be done once, we
731 // don't do it when layering.
732 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
733 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
734 } else {
735 fInitialTransform.setIdentity();
736 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000737}
738
739SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000740 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000741}
742
743void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000744 fAnnotations = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000745 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000746 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000747 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000748 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000749 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000750 if (fFontGlyphUsage.get() == NULL) {
halcanary792c80f2015-02-20 07:21:05 -0800751 fFontGlyphUsage.reset(SkNEW(SkPDFGlyphSetMap));
vandebo@chromium.org98594282011-07-25 22:34:12 +0000752 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000753}
754
vandebo@chromium.org98594282011-07-25 22:34:12 +0000755void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000756 fGraphicStateResources.unrefAll();
757 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000758 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000759 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000760 SkSafeUnref(fAnnotations);
epoger@google.comb58772f2013-03-08 09:09:10 +0000761 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000762
vandebo@chromium.org98594282011-07-25 22:34:12 +0000763 if (clearFontUsage) {
764 fFontGlyphUsage->reset();
765 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000766}
767
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000768void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000769 SkPaint newPaint = paint;
halcanarya6814332015-05-27 08:53:36 -0700770 replace_srcmode_on_opaque_paint(&newPaint);
771
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000772 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000773 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000774 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000775}
776
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000777void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
778 ContentEntry* contentEntry) {
779 if (!contentEntry) {
780 return;
781 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000782 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
783 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000784 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000785 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000786 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000787 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000788 inverse.mapRect(&bbox);
789
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000790 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000791 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000792 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000793}
794
halcanarya6814332015-05-27 08:53:36 -0700795void SkPDFDevice::drawPoints(const SkDraw& d,
796 SkCanvas::PointMode mode,
797 size_t count,
798 const SkPoint* points,
799 const SkPaint& srcPaint) {
800 SkPaint passedPaint = srcPaint;
801 replace_srcmode_on_opaque_paint(&passedPaint);
802
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000803 if (count == 0) {
804 return;
805 }
806
halcanaryeee0e4e2015-06-14 11:04:58 -0700807 if (SkAnnotation* annotation = passedPaint.getAnnotation()) {
808 if (handlePointAnnotation(points, count, *d.fMatrix, annotation)) {
809 return;
810 }
epoger@google.comb58772f2013-03-08 09:09:10 +0000811 }
812
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000813 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
814 // We only use this when there's a path effect because of the overhead
815 // of multiple calls to setUpContentEntry it causes.
816 if (passedPaint.getPathEffect()) {
817 if (d.fClip->isEmpty()) {
818 return;
819 }
820 SkDraw pointDraw(d);
821 pointDraw.fDevice = this;
822 pointDraw.drawPoints(mode, count, points, passedPaint, true);
823 return;
824 }
825
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000826 const SkPaint* paint = &passedPaint;
827 SkPaint modifiedPaint;
828
829 if (mode == SkCanvas::kPoints_PointMode &&
830 paint->getStrokeCap() != SkPaint::kRound_Cap) {
831 modifiedPaint = *paint;
832 paint = &modifiedPaint;
833 if (paint->getStrokeWidth()) {
834 // PDF won't draw a single point with square/butt caps because the
835 // orientation is ambiguous. Draw a rectangle instead.
836 modifiedPaint.setStyle(SkPaint::kFill_Style);
837 SkScalar strokeWidth = paint->getStrokeWidth();
838 SkScalar halfStroke = SkScalarHalf(strokeWidth);
839 for (size_t i = 0; i < count; i++) {
840 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
841 r.inset(-halfStroke, -halfStroke);
842 drawRect(d, r, modifiedPaint);
843 }
844 return;
845 } else {
846 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
847 }
848 }
849
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000850 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000851 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000852 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000853 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000854
855 switch (mode) {
856 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000857 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000858 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000859 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000860 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000861 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000862 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000863 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000864 break;
865 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000866 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000867 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000868 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000869 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000870 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000871 &content.entry()->fContent);
872 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000873 }
874 break;
875 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000876 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
877 for (size_t i = 0; i < count; i++) {
878 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000879 &content.entry()->fContent);
880 SkPDFUtils::ClosePath(&content.entry()->fContent);
881 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000882 }
883 break;
884 default:
885 SkASSERT(false);
886 }
887}
888
halcanaryeee0e4e2015-06-14 11:04:58 -0700889static SkPath transform_and_clip_path(const SkDraw& d,
890 const SkPath& region,
891 const SkMatrix& initialTransform) {
892 SkPath path = region;
893 SkMatrix transform = *d.fMatrix;
894 transform.postConcat(initialTransform);
895 path.transform(transform);
896 if (const SkClipStack* clipStack = d.fClipStack) {
897 SkPath clip;
898 (void)clipStack->asPath(&clip);
899 Op(clip, path, SkPathOp::kIntersect_SkPathOp, &path);
900 }
901 return path;
902}
903
904static SkPDFDict* create_link_annotation(const SkRect& translatedRect) {
905 SkAutoTUnref<SkPDFDict> annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
906 annotation->insertName("Subtype", "Link");
907
908 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
909 border->reserve(3);
910 border->appendInt(0); // Horizontal corner radius.
911 border->appendInt(0); // Vertical corner radius.
912 border->appendInt(0); // Width, 0 = no border.
913 annotation->insertObject("Border", border.detach());
914
915 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
916 rect->reserve(4);
917 rect->appendScalar(translatedRect.fLeft);
918 rect->appendScalar(translatedRect.fTop);
919 rect->appendScalar(translatedRect.fRight);
920 rect->appendScalar(translatedRect.fBottom);
921 annotation->insertObject("Rect", rect.detach());
922
923 return annotation.detach();
924}
925
926static SkPDFDict* create_link_to_url(SkData* urlData, const SkRect& r) {
927 SkAutoTUnref<SkPDFDict> annotation(create_link_annotation(r));
928
929 SkString url(static_cast<const char *>(urlData->data()),
930 urlData->size() - 1);
931 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
932 action->insertName("S", "URI");
933 action->insertString("URI", url);
934 annotation->insertObject("A", action.detach());
935 return annotation.detach();
936}
937
938static SkPDFDict* create_link_named_dest(SkData* nameData, const SkRect& r) {
939 SkAutoTUnref<SkPDFDict> annotation(create_link_annotation(r));
940 SkString name(static_cast<const char *>(nameData->data()),
941 nameData->size() - 1);
942 annotation->insertName("Dest", name);
943 return annotation.detach();
944}
945
946static SkPDFDict* create_rect_annotation(const SkRect& r,
947 SkAnnotation* annotation) {
948 SkASSERT(annotation);
949 SkData* urlData = annotation->find(SkAnnotationKeys::URL_Key());
950 if (urlData) {
951 return create_link_to_url(urlData, r);
952 }
953 SkData* linkToName =
954 annotation->find(SkAnnotationKeys::Link_Named_Dest_Key());
955 if (linkToName) {
956 return create_link_named_dest(linkToName, r);
957 }
958 return NULL;
959}
960
halcanarya6814332015-05-27 08:53:36 -0700961void SkPDFDevice::drawRect(const SkDraw& d,
962 const SkRect& rect,
963 const SkPaint& srcPaint) {
964 SkPaint paint = srcPaint;
965 replace_srcmode_on_opaque_paint(&paint);
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000966 SkRect r = rect;
967 r.sort();
968
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000969 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000970 if (d.fClip->isEmpty()) {
971 return;
972 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000973 SkPath path;
974 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000975 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000976 return;
977 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000978
halcanaryeee0e4e2015-06-14 11:04:58 -0700979 if (SkAnnotation* annotation = paint.getAnnotation()) {
980 SkPath path;
981 path.addRect(rect);
982 SkRect transformedRect =
983 transform_and_clip_path(d, path, fInitialTransform).getBounds();
984 SkAutoTUnref<SkPDFDict> annot(
985 create_rect_annotation(transformedRect, annotation));
986 if (annot) {
987 this->addAnnotation(annot.detach());
988 return;
989 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000990 }
991
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000992 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000993 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000994 return;
995 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000996 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000997 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000998 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000999}
1000
halcanarya6814332015-05-27 08:53:36 -07001001void SkPDFDevice::drawRRect(const SkDraw& draw,
1002 const SkRRect& rrect,
1003 const SkPaint& srcPaint) {
1004 SkPaint paint = srcPaint;
1005 replace_srcmode_on_opaque_paint(&paint);
scroggo@google.coma8e33a92013-11-08 18:02:53 +00001006 SkPath path;
1007 path.addRRect(rrect);
1008 this->drawPath(draw, path, paint, NULL, true);
1009}
1010
halcanarya6814332015-05-27 08:53:36 -07001011void SkPDFDevice::drawOval(const SkDraw& draw,
1012 const SkRect& oval,
1013 const SkPaint& srcPaint) {
1014 SkPaint paint = srcPaint;
1015 replace_srcmode_on_opaque_paint(&paint);
reed89443ab2014-06-27 11:34:19 -07001016 SkPath path;
1017 path.addOval(oval);
1018 this->drawPath(draw, path, paint, NULL, true);
1019}
1020
halcanarya6814332015-05-27 08:53:36 -07001021void SkPDFDevice::drawPath(const SkDraw& d,
1022 const SkPath& origPath,
1023 const SkPaint& srcPaint,
1024 const SkMatrix* prePathMatrix,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +00001025 bool pathIsMutable) {
halcanarya6814332015-05-27 08:53:36 -07001026 SkPaint paint = srcPaint;
1027 replace_srcmode_on_opaque_paint(&paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001028 SkPath modifiedPath;
1029 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1030
1031 SkMatrix matrix = *d.fMatrix;
1032 if (prePathMatrix) {
1033 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
1034 if (!pathIsMutable) {
1035 pathPtr = &modifiedPath;
1036 pathIsMutable = true;
1037 }
1038 origPath.transform(*prePathMatrix, pathPtr);
1039 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +00001040 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001041 }
1042 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +00001043
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001044 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001045 if (d.fClip->isEmpty()) {
1046 return;
1047 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001048 if (!pathIsMutable) {
1049 pathPtr = &modifiedPath;
1050 pathIsMutable = true;
1051 }
1052 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001053
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001054 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001055 noEffectPaint.setPathEffect(NULL);
1056 if (fill) {
1057 noEffectPaint.setStyle(SkPaint::kFill_Style);
1058 } else {
1059 noEffectPaint.setStyle(SkPaint::kStroke_Style);
1060 noEffectPaint.setStrokeWidth(0);
1061 }
1062 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001063 return;
1064 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001065
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001066 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001067 return;
1068 }
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001069
halcanaryeee0e4e2015-06-14 11:04:58 -07001070 if (SkAnnotation* annotation = paint.getAnnotation()) {
1071 SkRect transformedRect =
1072 transform_and_clip_path(d, *pathPtr, fInitialTransform)
1073 .getBounds();
1074 SkAutoTUnref<SkPDFDict> annot(
1075 create_rect_annotation(transformedRect, annotation));
1076 if (annot) {
1077 this->addAnnotation(annot.detach());
1078 return;
1079 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001080 }
1081
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001082 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001083 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001084 return;
1085 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001086 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1087 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001088 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001089 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001090}
1091
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001092void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1093 const SkRect* src, const SkRect& dst,
halcanarya6814332015-05-27 08:53:36 -07001094 const SkPaint& srcPaint,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001095 SkCanvas::DrawBitmapRectFlags flags) {
halcanarya6814332015-05-27 08:53:36 -07001096 SkPaint paint = srcPaint;
1097 if (bitmap.isOpaque()) {
1098 replace_srcmode_on_opaque_paint(&paint);
1099 }
1100
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001101 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001102 SkMatrix matrix;
1103 SkRect bitmapBounds, tmpSrc, tmpDst;
1104 SkBitmap tmpBitmap;
1105
1106 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1107
1108 // Compute matrix from the two rectangles
1109 if (src) {
1110 tmpSrc = *src;
1111 } else {
1112 tmpSrc = bitmapBounds;
1113 }
1114 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1115
1116 const SkBitmap* bitmapPtr = &bitmap;
1117
1118 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1119 // needed (if the src was clipped). No check needed if src==null.
1120 if (src) {
1121 if (!bitmapBounds.contains(*src)) {
1122 if (!tmpSrc.intersect(bitmapBounds)) {
1123 return; // nothing to draw
1124 }
1125 // recompute dst, based on the smaller tmpSrc
1126 matrix.mapRect(&tmpDst, tmpSrc);
1127 }
1128
1129 // since we may need to clamp to the borders of the src rect within
1130 // the bitmap, we extract a subset.
1131 // TODO: make sure this is handled in drawBitmap and remove from here.
1132 SkIRect srcIR;
1133 tmpSrc.roundOut(&srcIR);
1134 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1135 return;
1136 }
1137 bitmapPtr = &tmpBitmap;
1138
1139 // Since we did an extract, we need to adjust the matrix accordingly
1140 SkScalar dx = 0, dy = 0;
1141 if (srcIR.fLeft > 0) {
1142 dx = SkIntToScalar(srcIR.fLeft);
1143 }
1144 if (srcIR.fTop > 0) {
1145 dy = SkIntToScalar(srcIR.fTop);
1146 }
1147 if (dx || dy) {
1148 matrix.preTranslate(dx, dy);
1149 }
1150 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001151 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001152}
1153
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001154void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
halcanarya6814332015-05-27 08:53:36 -07001155 const SkMatrix& matrix, const SkPaint& srcPaint) {
1156 SkPaint paint = srcPaint;
1157 if (bitmap.isOpaque()) {
1158 replace_srcmode_on_opaque_paint(&paint);
1159 }
1160
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001161 if (d.fClip->isEmpty()) {
1162 return;
1163 }
1164
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001165 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001166 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001167 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1168 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001169}
1170
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001171void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
halcanarya6814332015-05-27 08:53:36 -07001172 int x, int y, const SkPaint& srcPaint) {
1173 SkPaint paint = srcPaint;
1174 if (bitmap.isOpaque()) {
1175 replace_srcmode_on_opaque_paint(&paint);
1176 }
1177
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001178 if (d.fClip->isEmpty()) {
1179 return;
1180 }
1181
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001182 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001183 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001184 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1185 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001186}
1187
halcanarybb264b72015-04-07 10:40:03 -07001188// Create a PDF string. Maximum length (in bytes) is 65,535.
1189// @param input A string value.
1190// @param len The length of the input array.
1191// @param wideChars True iff the upper byte in each uint16_t is
1192// significant and should be encoded and not
1193// discarded. If true, the upper byte is encoded
1194// first. Otherwise, we assert the upper byte is
1195// zero.
1196static SkString format_wide_string(const uint16_t* input,
1197 size_t len,
1198 bool wideChars) {
1199 if (wideChars) {
1200 SkASSERT(2 * len < 65535);
1201 static const char gHex[] = "0123456789ABCDEF";
1202 SkString result(4 * len + 2);
1203 result[0] = '<';
1204 for (size_t i = 0; i < len; i++) {
1205 result[4 * i + 1] = gHex[(input[i] >> 12) & 0xF];
1206 result[4 * i + 2] = gHex[(input[i] >> 8) & 0xF];
1207 result[4 * i + 3] = gHex[(input[i] >> 4) & 0xF];
1208 result[4 * i + 4] = gHex[(input[i] ) & 0xF];
1209 }
1210 result[4 * len + 1] = '>';
1211 return result;
1212 } else {
1213 SkASSERT(len <= 65535);
1214 SkString tmp(len);
1215 for (size_t i = 0; i < len; i++) {
1216 SkASSERT(0 == input[i] >> 8);
1217 tmp[i] = static_cast<uint8_t>(input[i]);
1218 }
halcanarybc4696b2015-05-06 10:56:04 -07001219 return SkPDFUtils::FormatString(tmp.c_str(), tmp.size());
halcanarybb264b72015-04-07 10:40:03 -07001220 }
1221}
1222
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001223void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
halcanarya6814332015-05-27 08:53:36 -07001224 SkScalar x, SkScalar y, const SkPaint& srcPaint) {
1225 SkPaint paint = srcPaint;
1226 replace_srcmode_on_opaque_paint(&paint);
1227
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001228 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1229 if (paint.getMaskFilter() != NULL) {
1230 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1231 // making text unreadable (e.g. same text twice when using CSS shadows).
1232 return;
1233 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001234 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001235 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001236 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001237 return;
1238 }
1239
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001240 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001241 const uint16_t* glyphIDs = NULL;
reed@google.comaec40662014-04-18 19:29:07 +00001242 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001243 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001244
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001245 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001246 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001247 content.entry()->fContent.writeText("BT\n");
1248 set_text_transform(x, y, textPaint.getTextSkewX(),
1249 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001250 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001251
1252 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1253
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001254 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001255 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1256 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001257
1258 int availableGlyphs = font->glyphsToPDFFontEncoding(
1259 glyphIDsCopy.begin() + consumedGlyphCount,
1260 numGlyphs - consumedGlyphCount);
1261 fFontGlyphUsage->noteGlyphUsage(
1262 font, glyphIDsCopy.begin() + consumedGlyphCount,
1263 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001264 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001265 format_wide_string(glyphIDsCopy.begin() + consumedGlyphCount,
1266 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001267 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001268 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001269 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001270 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001271 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001272}
1273
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001274void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001275 const SkScalar pos[], int scalarsPerPos,
halcanarya6814332015-05-27 08:53:36 -07001276 const SkPoint& offset, const SkPaint& srcPaint) {
1277 SkPaint paint = srcPaint;
1278 replace_srcmode_on_opaque_paint(&paint);
1279
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001280 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1281 if (paint.getMaskFilter() != NULL) {
1282 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1283 // making text unreadable (e.g. same text twice when using CSS shadows).
1284 return;
1285 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001286 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001287 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001288 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001289 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001290 return;
1291 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001292
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001293 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001294 const uint16_t* glyphIDs = NULL;
1295 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001296 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001297
1298 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001299 content.entry()->fContent.writeText("BT\n");
1300 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001301 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001302 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001303 uint16_t encodedValue = glyphIDs[i];
1304 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001305 // The current pdf font cannot encode the current glyph.
1306 // Try to get a pdf font which can encode the current glyph.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001307 updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001308 font = content.entry()->fState.fFont;
1309 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1310 SkDEBUGFAIL("PDF could not encode glyph.");
1311 continue;
1312 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001313 }
bungeman22edc832014-10-03 07:55:58 -07001314
vandebo@chromium.org98594282011-07-25 22:34:12 +00001315 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001316 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1317 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1318
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001319 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001320 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001321 SkString encodedString =
halcanarybb264b72015-04-07 10:40:03 -07001322 format_wide_string(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001323 content.entry()->fContent.writeText(encodedString.c_str());
1324 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001325 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001326 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001327}
1328
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001329void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001330 int vertexCount, const SkPoint verts[],
1331 const SkPoint texs[], const SkColor colors[],
1332 SkXfermode* xmode, const uint16_t indices[],
1333 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001334 if (d.fClip->isEmpty()) {
1335 return;
1336 }
reed@google.com85e143c2013-12-30 15:51:25 +00001337 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001338}
1339
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001340void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1341 int x, int y, const SkPaint& paint) {
fmalita6987dca2014-11-13 08:33:37 -08001342 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001343 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001344 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001345 return;
1346 }
1347
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001348 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001349 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001350 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001351 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001352 return;
1353 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001354 if (content.needShape()) {
1355 SkPath shape;
1356 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001357 SkIntToScalar(device->width()),
1358 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001359 content.setShape(shape);
1360 }
1361 if (!content.needSource()) {
1362 return;
1363 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001364
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001365 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1366 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001367 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001368
1369 // Merge glyph sets from the drawn device.
1370 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001371}
1372
reed89443ab2014-06-27 11:34:19 -07001373SkImageInfo SkPDFDevice::imageInfo() const {
1374 return fLegacyBitmap.info();
1375}
1376
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001377void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1378 INHERITED::onAttachToCanvas(canvas);
1379
1380 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1381 fClipStack = canvas->getClipStack();
1382}
1383
1384void SkPDFDevice::onDetachFromCanvas() {
1385 INHERITED::onDetachFromCanvas();
1386
1387 fClipStack = NULL;
1388}
1389
reed4a8126e2014-09-22 07:29:03 -07001390SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1391 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001392}
1393
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001394ContentEntry* SkPDFDevice::getLastContentEntry() {
1395 if (fDrawingArea == kContent_DrawingArea) {
1396 return fLastContentEntry;
1397 } else {
1398 return fLastMarginContentEntry;
1399 }
1400}
1401
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001402SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001403 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001404 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001405 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001406 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001407 }
1408}
1409
1410void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1411 if (fDrawingArea == kContent_DrawingArea) {
1412 fLastContentEntry = contentEntry;
1413 } else {
1414 fLastMarginContentEntry = contentEntry;
1415 }
1416}
1417
1418void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001419 // A ScopedContentEntry only exists during the course of a draw call, so
1420 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001421 fDrawingArea = drawingArea;
1422}
1423
halcanary2b861552015-04-09 13:27:40 -07001424SkPDFDict* SkPDFDevice::createResourceDict() const {
1425 SkTDArray<SkPDFObject*> fonts;
1426 fonts.setReserve(fFontResources.count());
1427 for (SkPDFFont* font : fFontResources) {
1428 fonts.push(font);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001429 }
halcanary2b861552015-04-09 13:27:40 -07001430 return SkPDFResourceDict::Create(
1431 &fGraphicStateResources,
1432 &fShaderResources,
1433 &fXObjectResources,
1434 &fonts);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001435}
1436
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001437const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1438 return fFontResources;
1439}
1440
reed@google.com2a006c12012-09-19 17:05:55 +00001441SkPDFArray* SkPDFDevice::copyMediaBox() const {
1442 // should this be a singleton?
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001443
halcanary130444f2015-04-25 06:45:07 -07001444 SkAutoTUnref<SkPDFArray> mediaBox(SkNEW(SkPDFArray));
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001445 mediaBox->reserve(4);
halcanary130444f2015-04-25 06:45:07 -07001446 mediaBox->appendInt(0);
1447 mediaBox->appendInt(0);
reed@google.comc789cf12011-07-20 12:14:33 +00001448 mediaBox->appendInt(fPageSize.fWidth);
1449 mediaBox->appendInt(fPageSize.fHeight);
halcanary130444f2015-04-25 06:45:07 -07001450 return mediaBox.detach();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001451}
1452
halcanary334fcbc2015-02-24 12:56:16 -08001453SkStreamAsset* SkPDFDevice::content() const {
1454 SkDynamicMemoryWStream buffer;
1455 this->writeContent(&buffer);
1456 return buffer.detachAsStream();
reed@google.com5667afc2011-06-27 14:42:15 +00001457}
1458
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001459void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1460 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001461 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1462 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001463 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001464 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001465 SkPoint translation;
1466 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001467 translation.negate();
1468 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1469 translation);
1470 gsState.updateMatrix(entry->fState.fMatrix);
1471 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001472
halcanary7af21502015-02-23 12:17:59 -08001473 entry->fContent.writeToStream(data);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001474 entry = entry->fNext.get();
1475 }
1476 gsState.drainStack();
1477}
1478
halcanary334fcbc2015-02-24 12:56:16 -08001479void SkPDFDevice::writeContent(SkWStream* out) const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001480 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
halcanary334fcbc2015-02-24 12:56:16 -08001481 SkPDFUtils::AppendTransform(fInitialTransform, out);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001482 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001483
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001484 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1485 // colors the contentArea white before it starts drawing into it and
1486 // that currently acts as our clip.
1487 // Also, think about adding a transform here (or assume that the values
1488 // sent across account for that)
halcanary334fcbc2015-02-24 12:56:16 -08001489 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), out);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001490
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001491 // If the content area is the entire page, then we don't need to clip
1492 // the content area (PDF area clips to the page size). Otherwise,
1493 // we have to clip to the content area; we've already applied the
1494 // initial transform, so just clip to the device size.
1495 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001496 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1497 SkIntToScalar(this->height()));
halcanary334fcbc2015-02-24 12:56:16 -08001498 emit_clip(NULL, &r, out);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001499 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001500
halcanary334fcbc2015-02-24 12:56:16 -08001501 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), out);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001502}
1503
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001504/* Draws an inverse filled path by using Path Ops to compute the positive
1505 * inverse using the current clip as the inverse bounds.
1506 * Return true if this was an inverse path and was properly handled,
1507 * otherwise returns false and the normal drawing routine should continue,
1508 * either as a (incorrect) fallback or because the path was not inverse
1509 * in the first place.
1510 */
1511bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001512 const SkPaint& paint, bool pathIsMutable,
1513 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001514 if (!origPath.isInverseFillType()) {
1515 return false;
1516 }
1517
1518 if (d.fClip->isEmpty()) {
1519 return false;
1520 }
1521
1522 SkPath modifiedPath;
1523 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1524 SkPaint noInversePaint(paint);
1525
1526 // Merge stroking operations into final path.
1527 if (SkPaint::kStroke_Style == paint.getStyle() ||
1528 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1529 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1530 if (doFillPath) {
1531 noInversePaint.setStyle(SkPaint::kFill_Style);
1532 noInversePaint.setStrokeWidth(0);
1533 pathPtr = &modifiedPath;
1534 } else {
1535 // To be consistent with the raster output, hairline strokes
1536 // are rendered as non-inverted.
1537 modifiedPath.toggleInverseFillType();
1538 drawPath(d, modifiedPath, paint, NULL, true);
1539 return true;
1540 }
1541 }
1542
1543 // Get bounds of clip in current transform space
1544 // (clip bounds are given in device space).
1545 SkRect bounds;
1546 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001547 SkMatrix totalMatrix = *d.fMatrix;
1548 if (prePathMatrix) {
1549 totalMatrix.preConcat(*prePathMatrix);
1550 }
1551 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001552 return false;
1553 }
1554 bounds.set(d.fClip->getBounds());
1555 transformInverse.mapRect(&bounds);
1556
1557 // Extend the bounds by the line width (plus some padding)
1558 // so the edge doesn't cause a visible stroke.
1559 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1560 paint.getStrokeWidth() + SK_Scalar1);
1561
1562 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1563 return false;
1564 }
1565
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001566 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001567 return true;
1568}
1569
halcanaryeee0e4e2015-06-14 11:04:58 -07001570struct NamedDestination {
1571 SkAutoTUnref<const SkData> nameData;
1572 SkPoint point;
1573
1574 NamedDestination(const SkData* nameData, const SkPoint& point)
1575 : nameData(SkRef(nameData)), point(point) {}
1576};
epoger@google.comb58772f2013-03-08 09:09:10 +00001577
1578bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1579 const SkMatrix& matrix,
halcanaryeee0e4e2015-06-14 11:04:58 -07001580 SkAnnotation* annotationInfo) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001581 SkData* nameData = annotationInfo->find(
1582 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001583 if (nameData) {
halcanaryeee0e4e2015-06-14 11:04:58 -07001584 SkMatrix transform = matrix;
1585 transform.postConcat(fInitialTransform);
epoger@google.comb58772f2013-03-08 09:09:10 +00001586 for (size_t i = 0; i < count; i++) {
halcanaryeee0e4e2015-06-14 11:04:58 -07001587 SkPoint translatedPoint;
1588 transform.mapXY(points[i].x(), points[i].y(), &translatedPoint);
1589 fNamedDestinations.push(
1590 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1591
epoger@google.comb58772f2013-03-08 09:09:10 +00001592 }
halcanaryeee0e4e2015-06-14 11:04:58 -07001593 return true;
epoger@google.comb58772f2013-03-08 09:09:10 +00001594 }
1595 return false;
1596}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001597
halcanary438de492015-04-28 06:21:01 -07001598void SkPDFDevice::addAnnotation(SkPDFDict* annotation) {
reed@google.com2a006c12012-09-19 17:05:55 +00001599 if (NULL == fAnnotations) {
1600 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001601 }
halcanary438de492015-04-28 06:21:01 -07001602 fAnnotations->appendObject(annotation);
1603}
1604
epoger@google.comb58772f2013-03-08 09:09:10 +00001605
halcanary6d622702015-03-25 08:45:42 -07001606void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) const {
epoger@google.comb58772f2013-03-08 09:09:10 +00001607 int nDest = fNamedDestinations.count();
1608 for (int i = 0; i < nDest; i++) {
1609 NamedDestination* dest = fNamedDestinations[i];
1610 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1611 pdfDest->reserve(5);
halcanary130444f2015-04-25 06:45:07 -07001612 pdfDest->appendObjRef(SkRef(page));
epoger@google.comb58772f2013-03-08 09:09:10 +00001613 pdfDest->appendName("XYZ");
1614 pdfDest->appendScalar(dest->point.x());
1615 pdfDest->appendScalar(dest->point.y());
1616 pdfDest->appendInt(0); // Leave zoom unchanged
halcanary130444f2015-04-25 06:45:07 -07001617 SkString name(static_cast<const char*>(dest->nameData->data()));
1618 dict->insertObject(name, pdfDest.detach());
epoger@google.comb58772f2013-03-08 09:09:10 +00001619 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001620}
1621
reed@google.comfc641d02012-09-20 17:52:20 +00001622SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1623 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001624 // We always draw the form xobjects that we create back into the device, so
1625 // we simply preserve the font usage instead of pulling it out and merging
1626 // it back in later.
1627 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001628 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001629 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001630}
1631
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001632void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1633 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001634 const SkClipStack* clipStack,
1635 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001636 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001637 bool invertClip) {
1638 if (clipRegion.isEmpty() && !invertClip) {
1639 return;
1640 }
1641
halcanarybe27a112015-04-01 13:31:19 -07001642 SkAutoTUnref<SkPDFObject> sMaskGS(SkPDFGraphicState::GetSMaskGraphicState(
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001643 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1644
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001645 SkMatrix identity;
1646 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001647 SkPaint paint;
1648 paint.setXfermodeMode(mode);
1649 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001650 if (!content.entry()) {
1651 return;
1652 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001653 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001654 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001655 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001656
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001657 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001658 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001659 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001660}
1661
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001662ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1663 const SkRegion& clipRegion,
1664 const SkMatrix& matrix,
1665 const SkPaint& paint,
1666 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001667 SkPDFFormXObject** dst) {
1668 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001669 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001670 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001671 }
1672
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001673 // The clip stack can come from an SkDraw where it is technically optional.
1674 SkClipStack synthesizedClipStack;
1675 if (clipStack == NULL) {
1676 if (clipRegion == fExistingClipRegion) {
1677 clipStack = &fExistingClipStack;
1678 } else {
1679 // GraphicStackState::updateClip expects the clip stack to have
1680 // fExistingClip as a prefix, so start there, then set the clip
1681 // to the passed region.
1682 synthesizedClipStack = fExistingClipStack;
1683 SkPath clipPath;
1684 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001685 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1686 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001687 clipStack = &synthesizedClipStack;
1688 }
1689 }
1690
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001691 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1692 if (paint.getXfermode()) {
1693 paint.getXfermode()->asMode(&xfermode);
1694 }
1695
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001696 // For the following modes, we want to handle source and destination
1697 // separately, so make an object of what's already there.
1698 if (xfermode == SkXfermode::kClear_Mode ||
1699 xfermode == SkXfermode::kSrc_Mode ||
1700 xfermode == SkXfermode::kSrcIn_Mode ||
1701 xfermode == SkXfermode::kDstIn_Mode ||
1702 xfermode == SkXfermode::kSrcOut_Mode ||
1703 xfermode == SkXfermode::kDstOut_Mode ||
1704 xfermode == SkXfermode::kSrcATop_Mode ||
1705 xfermode == SkXfermode::kDstATop_Mode ||
1706 xfermode == SkXfermode::kModulate_Mode) {
1707 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001708 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001709 SkASSERT(isContentEmpty());
1710 } else if (xfermode != SkXfermode::kSrc_Mode &&
1711 xfermode != SkXfermode::kSrcOut_Mode) {
1712 // Except for Src and SrcOut, if there isn't anything already there,
1713 // then we're done.
1714 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001715 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001716 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001717 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001718 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001719
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001720 // Dst xfer mode doesn't draw source at all.
1721 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001722 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001723 }
1724
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001725 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001726 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001727
1728 ContentEntry* lastContentEntry = getLastContentEntry();
1729 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1730 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001731 } else {
1732 newEntry.reset(new ContentEntry);
1733 entry = newEntry.get();
1734 }
1735
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001736 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001737 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001738 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1739 entry->fState.compareInitialState(lastContentEntry->fState)) {
1740 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001741 }
1742
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001743 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001744 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001745 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001746 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001747 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001748 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001749 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001750 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001751 lastContentEntry->fNext.reset(entry);
1752 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001753 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001754 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001755 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001756}
1757
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001758void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001759 SkPDFFormXObject* dst,
1760 SkPath* shape) {
1761 if (xfermode != SkXfermode::kClear_Mode &&
1762 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001763 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001764 xfermode != SkXfermode::kSrcIn_Mode &&
1765 xfermode != SkXfermode::kDstIn_Mode &&
1766 xfermode != SkXfermode::kSrcOut_Mode &&
1767 xfermode != SkXfermode::kDstOut_Mode &&
1768 xfermode != SkXfermode::kSrcATop_Mode &&
1769 xfermode != SkXfermode::kDstATop_Mode &&
1770 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001771 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001772 return;
1773 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001774 if (xfermode == SkXfermode::kDstOver_Mode) {
1775 SkASSERT(!dst);
1776 ContentEntry* firstContentEntry = getContentEntries()->get();
1777 if (firstContentEntry->fContent.getOffset() == 0) {
1778 // For DstOver, an empty content entry was inserted before the rest
1779 // of the content entries. If nothing was drawn, it needs to be
1780 // removed.
1781 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1782 contentEntries->reset(firstContentEntry->fNext.detach());
1783 }
1784 return;
1785 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001786 if (!dst) {
1787 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1788 xfermode == SkXfermode::kSrcOut_Mode);
1789 return;
1790 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001791
1792 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001793 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001794 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001795 // Changing the current content into a form-xobject will destroy the clip
1796 // objects which is fine since the xobject will already be clipped. However
1797 // if source has shape, we need to clip it too, so a copy of the clip is
1798 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001799 SkClipStack clipStack = contentEntries->fState.fClipStack;
1800 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001801
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001802 SkMatrix identity;
1803 identity.reset();
1804 SkPaint stockPaint;
1805
reed@google.comfc641d02012-09-20 17:52:20 +00001806 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001807 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001808 // If nothing was drawn and there's no shape, then the draw was a
1809 // no-op, but dst needs to be restored for that to be true.
1810 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1811 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1812 // reduces to Dst.
1813 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1814 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001815 ScopedContentEntry content(this, &fExistingClipStack,
1816 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001817 stockPaint);
1818 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1819 &content.entry()->fContent);
1820 return;
1821 } else {
1822 xfermode = SkXfermode::kClear_Mode;
1823 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001824 } else {
1825 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001826 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001827 }
1828
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001829 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1830 // without alpha.
1831 if (xfermode == SkXfermode::kSrcATop_Mode) {
1832 // TODO(vandebo): In order to properly support SrcATop we have to track
1833 // the shape of what's been drawn at all times. It's the intersection of
1834 // the non-transparent parts of the device and the outlines (shape) of
1835 // all images and devices drawn.
1836 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001837 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001838 SkXfermode::kSrcOver_Mode, true);
1839 } else {
1840 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1841 SkPDFFormXObject* dstMask = srcFormXObject.get();
1842 if (shape != NULL) {
1843 // Draw shape into a form-xobject.
1844 SkDraw d;
1845 d.fMatrix = &identity;
1846 d.fClip = &clipRegion;
1847 d.fClipStack = &clipStack;
1848 SkPaint filledPaint;
1849 filledPaint.setColor(SK_ColorBLACK);
1850 filledPaint.setStyle(SkPaint::kFill_Style);
1851 this->drawPath(d, *shape, filledPaint, NULL, true);
1852
1853 dstMaskStorage.reset(createFormXObjectFromDevice());
1854 dstMask = dstMaskStorage.get();
1855 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001856 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1857 &fExistingClipStack, fExistingClipRegion,
1858 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001859 }
1860
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001861 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001862 return;
1863 } else if (xfermode == SkXfermode::kSrc_Mode ||
1864 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001865 ScopedContentEntry content(this, &fExistingClipStack,
1866 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001867 if (content.entry()) {
1868 SkPDFUtils::DrawFormXObject(
1869 this->addXObjectResource(srcFormXObject.get()),
1870 &content.entry()->fContent);
1871 }
1872 if (xfermode == SkXfermode::kSrc_Mode) {
1873 return;
1874 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001875 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001876 ScopedContentEntry content(this, &fExistingClipStack,
1877 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001878 if (content.entry()) {
1879 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1880 &content.entry()->fContent);
1881 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001882 }
1883
1884 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1885 xfermode == SkXfermode::kDstIn_Mode ||
1886 xfermode == SkXfermode::kSrcOut_Mode ||
1887 xfermode == SkXfermode::kDstOut_Mode ||
1888 xfermode == SkXfermode::kSrcATop_Mode ||
1889 xfermode == SkXfermode::kDstATop_Mode ||
1890 xfermode == SkXfermode::kModulate_Mode);
1891
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001892 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001893 xfermode == SkXfermode::kSrcOut_Mode ||
1894 xfermode == SkXfermode::kSrcATop_Mode) {
1895 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001896 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001897 SkXfermode::kSrcOver_Mode,
1898 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001899 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001900 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1901 if (xfermode == SkXfermode::kModulate_Mode) {
1902 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001903 dst, &fExistingClipStack,
1904 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001905 SkXfermode::kSrcOver_Mode, false);
1906 mode = SkXfermode::kMultiply_Mode;
1907 }
1908 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001909 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001910 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001911 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001912}
1913
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001914bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001915 ContentEntry* contentEntries = getContentEntries()->get();
1916 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1917 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001918 return true;
1919 }
1920 return false;
1921}
1922
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001923void SkPDFDevice::populateGraphicStateEntryFromPaint(
1924 const SkMatrix& matrix,
1925 const SkClipStack& clipStack,
1926 const SkRegion& clipRegion,
1927 const SkPaint& paint,
1928 bool hasText,
1929 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001930 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001931 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1932 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001933
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001934 entry->fMatrix = matrix;
1935 entry->fClipStack = clipStack;
1936 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001937 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1938 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001939
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001940 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001941 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001942 const SkShader* shader = paint.getShader();
1943 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001944 if (shader) {
1945 // PDF positions patterns relative to the initial transform, so
1946 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001947 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001948 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001949
1950 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001951 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001952 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001953
1954 // We need to apply the initial transform to bounds in order to get
1955 // bounds in a consistent coordinate system.
1956 SkRect boundsTemp;
1957 boundsTemp.set(bounds);
1958 fInitialTransform.mapRect(&boundsTemp);
1959 boundsTemp.roundOut(&bounds);
1960
halcanary792c80f2015-02-20 07:21:05 -08001961 SkScalar rasterScale =
1962 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
1963 pdfShader.reset(SkPDFShader::GetPDFShader(
1964 fCanon, fRasterDpi, *shader, transform, bounds, rasterScale));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001965
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001966 if (pdfShader.get()) {
1967 // pdfShader has been canonicalized so we can directly compare
1968 // pointers.
1969 int resourceIndex = fShaderResources.find(pdfShader.get());
1970 if (resourceIndex < 0) {
1971 resourceIndex = fShaderResources.count();
1972 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001973 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001974 }
1975 entry->fShaderIndex = resourceIndex;
1976 } else {
1977 // A color shader is treated as an invalid shader so we don't have
1978 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001979 SkShader::GradientInfo gradientInfo;
1980 SkColor gradientColor;
1981 gradientInfo.fColors = &gradientColor;
1982 gradientInfo.fColorOffsets = NULL;
1983 gradientInfo.fColorCount = 1;
1984 if (shader->asAGradient(&gradientInfo) ==
1985 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001986 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1987 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001988 }
1989 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001990 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001991
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001992 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001993 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001994 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001995 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001996 } else {
1997 SkPaint newPaint = paint;
1998 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001999 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08002000 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002001 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002002 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002003 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002004
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002005 if (hasText) {
2006 entry->fTextScaleX = paint.getTextScaleX();
2007 entry->fTextFill = paint.getStyle();
2008 } else {
2009 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002010 }
2011}
2012
halcanarybe27a112015-04-01 13:31:19 -07002013int SkPDFDevice::addGraphicStateResource(SkPDFObject* gs) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002014 // Assumes that gs has been canonicalized (so we can directly compare
2015 // pointers).
2016 int result = fGraphicStateResources.find(gs);
2017 if (result < 0) {
2018 result = fGraphicStateResources.count();
2019 fGraphicStateResources.push(gs);
2020 gs->ref();
2021 }
2022 return result;
2023}
2024
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002025int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2026 // Assumes that xobject has been canonicalized (so we can directly compare
2027 // pointers).
2028 int result = fXObjectResources.find(xObject);
2029 if (result < 0) {
2030 result = fXObjectResources.count();
2031 fXObjectResources.push(xObject);
2032 xObject->ref();
2033 }
2034 return result;
2035}
2036
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002037void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2038 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002039 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002040 if (contentEntry->fState.fFont == NULL ||
2041 contentEntry->fState.fTextSize != paint.getTextSize() ||
2042 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002043 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002044 contentEntry->fContent.writeText("/");
2045 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2046 SkPDFResourceDict::kFont_ResourceType,
2047 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002048 contentEntry->fContent.writeText(" ");
halcanarybc4696b2015-05-06 10:56:04 -07002049 SkPDFUtils::AppendScalar(paint.getTextSize(), &contentEntry->fContent);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002050 contentEntry->fContent.writeText(" Tf\n");
2051 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002052 }
2053}
2054
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002055int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary792c80f2015-02-20 07:21:05 -08002056 SkAutoTUnref<SkPDFFont> newFont(
2057 SkPDFFont::GetFontResource(fCanon, typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002058 int resourceIndex = fFontResources.find(newFont.get());
2059 if (resourceIndex < 0) {
2060 resourceIndex = fFontResources.count();
2061 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002062 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002063 }
2064 return resourceIndex;
2065}
2066
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002067void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002068 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002069 const SkRegion& origClipRegion,
2070 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002071 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002072 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002073 SkMatrix matrix = origMatrix;
2074 SkRegion perspectiveBounds;
2075 const SkRegion* clipRegion = &origClipRegion;
2076 SkBitmap perspectiveBitmap;
2077 const SkBitmap* bitmap = &origBitmap;
2078 SkBitmap tmpSubsetBitmap;
2079
2080 // Rasterize the bitmap using perspective in a new bitmap.
2081 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002082 if (fRasterDpi == 0) {
2083 return;
2084 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002085 SkBitmap* subsetBitmap;
2086 if (srcRect) {
2087 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2088 return;
2089 }
2090 subsetBitmap = &tmpSubsetBitmap;
2091 } else {
2092 subsetBitmap = &tmpSubsetBitmap;
2093 *subsetBitmap = origBitmap;
2094 }
2095 srcRect = NULL;
2096
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002097 // Transform the bitmap in the new space, without taking into
2098 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002099 SkPath perspectiveOutline;
2100 perspectiveOutline.addRect(
2101 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2102 SkIntToScalar(subsetBitmap->height())));
2103 perspectiveOutline.transform(origMatrix);
2104
2105 // TODO(edisonn): perf - use current clip too.
2106 // Retrieve the bounds of the new shape.
2107 SkRect bounds = perspectiveOutline.getBounds();
2108
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002109 // Transform the bitmap in the new space, taking into
2110 // account the initial transform.
2111 SkMatrix total = origMatrix;
2112 total.postConcat(fInitialTransform);
2113 total.postScale(SkIntToScalar(fRasterDpi) /
2114 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2115 SkIntToScalar(fRasterDpi) /
2116 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2117 SkPath physicalPerspectiveOutline;
2118 physicalPerspectiveOutline.addRect(
2119 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2120 SkIntToScalar(subsetBitmap->height())));
2121 physicalPerspectiveOutline.transform(total);
2122
2123 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2124 bounds.width();
2125 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2126 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002127
2128 // TODO(edisonn): A better approach would be to use a bitmap shader
2129 // (in clamp mode) and draw a rect over the entire bounding box. Then
2130 // intersect perspectiveOutline to the clip. That will avoid introducing
2131 // alpha to the image while still giving good behavior at the edge of
2132 // the image. Avoiding alpha will reduce the pdf size and generation
2133 // CPU time some.
2134
reed@google.com9ebcac52014-01-24 18:53:42 +00002135 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2136 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002137 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002138 return;
2139 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002140 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2141
reed89443ab2014-06-27 11:34:19 -07002142 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002143
2144 SkScalar deltaX = bounds.left();
2145 SkScalar deltaY = bounds.top();
2146
2147 SkMatrix offsetMatrix = origMatrix;
2148 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002149 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002150
2151 // Translate the draw in the new canvas, so we perfectly fit the
2152 // shape in the bitmap.
2153 canvas.setMatrix(offsetMatrix);
2154
2155 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2156
2157 // Make sure the final bits are in the bitmap.
2158 canvas.flush();
2159
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002160 // In the new space, we use the identity matrix translated
2161 // and scaled to reflect DPI.
2162 matrix.setScale(1 / scaleX, 1 / scaleY);
2163 matrix.postTranslate(deltaX, deltaY);
2164
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002165 perspectiveBounds.setRect(
2166 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2167 SkScalarFloorToInt(bounds.y()),
2168 SkScalarCeilToInt(bounds.width()),
2169 SkScalarCeilToInt(bounds.height())));
2170 clipRegion = &perspectiveBounds;
2171 srcRect = NULL;
2172 bitmap = &perspectiveBitmap;
2173 }
2174
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002175 SkMatrix scaled;
2176 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002177 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2178 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002179 // Scale the image up from 1x1 to WxH.
halcanaryf622a6c2014-10-24 12:54:53 -07002180 SkIRect subset = bitmap->bounds();
reed@google.coma6d59f62011-03-07 21:29:21 +00002181 scaled.postScale(SkIntToScalar(subset.width()),
2182 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002183 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002184 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002185 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2186 return;
2187 }
2188 if (content.needShape()) {
2189 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002190 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
halcanarydb0dcc72015-03-20 12:31:52 -07002191 SkIntToScalar(subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002192 shape.transform(matrix);
2193 content.setShape(shape);
2194 }
2195 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002196 return;
2197 }
2198
halcanarydb0dcc72015-03-20 12:31:52 -07002199 SkBitmap subsetBitmap;
2200 // Should extractSubset be done by the SkPDFDevice?
2201 if (!bitmap->extractSubset(&subsetBitmap, subset)) {
2202 return;
2203 }
2204 SkAutoTUnref<SkPDFObject> image(SkPDFBitmap::Create(fCanon, subsetBitmap));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002205 if (!image) {
2206 return;
2207 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002208
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002209 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002210 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002211}