blob: 8509de86fc01669fee2b43ab0298286fdb8a50b1 [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"
senorblancob0e89dc2014-10-20 14:03:12 -070011#include "SkBitmapDevice.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000012#include "SkColor.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000013#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000014#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000015#include "SkDraw.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000016#include "SkFontHost.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000017#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000018#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000019#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000020#include "SkPathOps.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000021#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000022#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000023#include "SkPDFGraphicState.h"
24#include "SkPDFImage.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000025#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000026#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000027#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000028#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000029#include "SkPDFUtils.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000030#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000031#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000032#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070033#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000034#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000035#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000036#include "SkTypefacePriv.h"
edisonn@google.com6addb192013-04-02 15:33:08 +000037#include "SkTSet.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000038
edisonn@google.com73a7ea32013-11-11 20:55:15 +000039#define DPI_FOR_RASTER_SCALE_ONE 72
40
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000041// Utility functions
42
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000043static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000044 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
45 SkScalar colorMax = SkIntToScalar(0xFF);
vandebo@chromium.org094316b2011-03-04 03:15:13 +000046 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000047 SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
48 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000049 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000050 SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
51 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000052 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000053 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
54 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000055}
56
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000057static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000058 SkPaint result = paint;
59 if (result.isFakeBoldText()) {
60 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
61 kStdFakeBoldInterpKeys,
62 kStdFakeBoldInterpValues,
63 kStdFakeBoldInterpLength);
64 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000065 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000066 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000067 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000068 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000069 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000070 result.setStrokeWidth(width);
71 }
72 return result;
73}
74
75// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000076static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000077 const uint16_t* glyphs, size_t len,
78 SkScalar* x, SkScalar* y) {
79 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000080 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000081 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000082
83 SkMatrix ident;
84 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000085 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000086 SkGlyphCache* cache = autoCache.getCache();
87
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000088 const char* start = reinterpret_cast<const char*>(glyphs);
89 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000090 SkFixed xAdv = 0, yAdv = 0;
91
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000092 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000093 while (start < stop) {
94 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
95 xAdv += glyph.fAdvanceX;
96 yAdv += glyph.fAdvanceY;
97 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000098 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000099 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000100 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000101
102 SkScalar xAdj = SkFixedToScalar(xAdv);
103 SkScalar yAdj = SkFixedToScalar(yAdv);
104 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
105 xAdj = SkScalarHalf(xAdj);
106 yAdj = SkScalarHalf(yAdj);
107 }
108 *x = *x - xAdj;
109 *y = *y - yAdj;
110}
111
robertphillips@google.coma4662862013-11-21 14:24:16 +0000112static int max_glyphid_for_typeface(SkTypeface* typeface) {
reed@google.comfed86bd2013-03-14 15:04:57 +0000113 SkAutoResolveDefaultTypeface autoResolve(typeface);
114 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000115 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000116}
117
118typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
119
reed@google.comaec40662014-04-18 19:29:07 +0000120static int force_glyph_encoding(const SkPaint& paint, const void* text,
121 size_t len, SkGlyphStorage* storage,
bungeman22edc832014-10-03 07:55:58 -0700122 const uint16_t** glyphIDs) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000123 // Make sure we have a glyph id encoding.
124 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
reed@google.comaec40662014-04-18 19:29:07 +0000125 int numGlyphs = paint.textToGlyphs(text, len, NULL);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000126 storage->reset(numGlyphs);
127 paint.textToGlyphs(text, len, storage->get());
128 *glyphIDs = storage->get();
129 return numGlyphs;
130 }
131
132 // For user supplied glyph ids we need to validate them.
133 SkASSERT((len & 1) == 0);
reed@google.comaec40662014-04-18 19:29:07 +0000134 int numGlyphs = SkToInt(len / 2);
bungeman22edc832014-10-03 07:55:58 -0700135 const uint16_t* input = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000136
137 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
reed@google.comaec40662014-04-18 19:29:07 +0000138 int validated;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000139 for (validated = 0; validated < numGlyphs; ++validated) {
140 if (input[validated] > maxGlyphID) {
141 break;
142 }
143 }
144 if (validated >= numGlyphs) {
bungeman22edc832014-10-03 07:55:58 -0700145 *glyphIDs = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000146 return numGlyphs;
147 }
148
149 // Silently drop anything out of range.
150 storage->reset(numGlyphs);
151 if (validated > 0) {
152 memcpy(storage->get(), input, validated * sizeof(uint16_t));
153 }
154
reed@google.comaec40662014-04-18 19:29:07 +0000155 for (int i = validated; i < numGlyphs; ++i) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000156 storage->get()[i] = input[i];
157 if (input[i] > maxGlyphID) {
158 storage->get()[i] = 0;
159 }
160 }
161 *glyphIDs = storage->get();
162 return numGlyphs;
163}
164
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000165static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
166 SkWStream* content) {
167 // Flip the text about the x-axis to account for origin swap and include
168 // the passed parameters.
169 content->writeText("1 0 ");
170 SkPDFScalar::Append(0 - textSkewX, content);
171 content->writeText(" -1 ");
172 SkPDFScalar::Append(x, content);
173 content->writeText(" ");
174 SkPDFScalar::Append(y, content);
175 content->writeText(" Tm\n");
176}
177
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000178// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
179// later being our representation of an object in the PDF file.
180struct GraphicStateEntry {
181 GraphicStateEntry();
182
183 // Compare the fields we care about when setting up a new content entry.
184 bool compareInitialState(const GraphicStateEntry& b);
185
186 SkMatrix fMatrix;
187 // We can't do set operations on Paths, though PDF natively supports
188 // intersect. If the clip stack does anything other than intersect,
189 // we have to fall back to the region. Treat fClipStack as authoritative.
190 // See http://code.google.com/p/skia/issues/detail?id=221
191 SkClipStack fClipStack;
192 SkRegion fClipRegion;
193
194 // When emitting the content entry, we will ensure the graphic state
195 // is set to these values first.
196 SkColor fColor;
197 SkScalar fTextScaleX; // Zero means we don't care what the value is.
198 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
199 int fShaderIndex;
200 int fGraphicStateIndex;
201
202 // We may change the font (i.e. for Type1 support) within a
203 // ContentEntry. This is the one currently in effect, or NULL if none.
204 SkPDFFont* fFont;
205 // In PDF, text size has no default value. It is only valid if fFont is
206 // not NULL.
207 SkScalar fTextSize;
208};
209
210GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
211 fTextScaleX(SK_Scalar1),
212 fTextFill(SkPaint::kFill_Style),
213 fShaderIndex(-1),
214 fGraphicStateIndex(-1),
215 fFont(NULL),
216 fTextSize(SK_ScalarNaN) {
217 fMatrix.reset();
218}
219
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000220bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
221 return fColor == cur.fColor &&
222 fShaderIndex == cur.fShaderIndex &&
223 fGraphicStateIndex == cur.fGraphicStateIndex &&
224 fMatrix == cur.fMatrix &&
225 fClipStack == cur.fClipStack &&
226 (fTextScaleX == 0 ||
227 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000228}
229
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000230class GraphicStackState {
231public:
232 GraphicStackState(const SkClipStack& existingClipStack,
233 const SkRegion& existingClipRegion,
234 SkWStream* contentStream)
235 : fStackDepth(0),
236 fContentStream(contentStream) {
237 fEntries[0].fClipStack = existingClipStack;
238 fEntries[0].fClipRegion = existingClipRegion;
239 }
240
241 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000242 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000243 void updateMatrix(const SkMatrix& matrix);
244 void updateDrawingState(const GraphicStateEntry& state);
245
246 void drainStack();
247
248private:
249 void push();
250 void pop();
251 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
252
253 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
254 static const int kMaxStackDepth = 12;
255 GraphicStateEntry fEntries[kMaxStackDepth + 1];
256 int fStackDepth;
257 SkWStream* fContentStream;
258};
259
260void GraphicStackState::drainStack() {
261 while (fStackDepth) {
262 pop();
263 }
264}
265
266void GraphicStackState::push() {
267 SkASSERT(fStackDepth < kMaxStackDepth);
268 fContentStream->writeText("q\n");
269 fStackDepth++;
270 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
271}
272
273void GraphicStackState::pop() {
274 SkASSERT(fStackDepth > 0);
275 fContentStream->writeText("Q\n");
276 fStackDepth--;
277}
278
robertphillips@google.com80214e22012-07-20 15:33:18 +0000279// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000280// and then skips over the leading entries as specified in prefix. It requires
281// and asserts that "prefix" will be a prefix to "stack."
282static void skip_clip_stack_prefix(const SkClipStack& prefix,
283 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000284 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000285 SkClipStack::B2TIter prefixIter(prefix);
286 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000287
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000288 const SkClipStack::Element* prefixEntry;
289 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000290
291 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000292 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000293 iterEntry = iter->next();
294 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000295 // Because of SkClipStack does internal intersection, the last clip
296 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000297 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000298 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
299 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
300 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000301 // back up the iterator by one
302 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000303 prefixEntry = prefixIter.next();
304 break;
305 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000306 }
307
308 SkASSERT(prefixEntry == NULL);
309}
310
311static void emit_clip(SkPath* clipPath, SkRect* clipRect,
312 SkWStream* contentStream) {
313 SkASSERT(clipPath || clipRect);
314
315 SkPath::FillType clipFill;
316 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000317 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000318 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000319 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000320 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
321 clipFill = SkPath::kWinding_FillType;
322 }
323
324 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
325 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
326 if (clipFill == SkPath::kEvenOdd_FillType) {
327 contentStream->writeText("W* n\n");
328 } else {
329 contentStream->writeText("W n\n");
330 }
331}
332
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000333#ifdef SK_PDF_USE_PATHOPS
334/* Calculate an inverted path's equivalent non-inverted path, given the
335 * canvas bounds.
336 * outPath may alias with invPath (since this is supported by PathOps).
337 */
338static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
339 SkPath* outPath) {
340 SkASSERT(invPath.isInverseFillType());
341
342 SkPath clipPath;
343 clipPath.addRect(bounds);
344
345 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
346}
347
348// Sanity check the numerical values of the SkRegion ops and PathOps ops
349// enums so region_op_to_pathops_op can do a straight passthrough cast.
350// If these are failing, it may be necessary to make region_op_to_pathops_op
351// do more.
352SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
353 region_pathop_mismatch);
354SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
355 region_pathop_mismatch);
356SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
357 region_pathop_mismatch);
358SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
359 region_pathop_mismatch);
360SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
361 (int)kReverseDifference_PathOp,
362 region_pathop_mismatch);
363
364static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
365 SkASSERT(op >= 0);
366 SkASSERT(op <= SkRegion::kReverseDifference_Op);
367 return (SkPathOp)op;
368}
369
370/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
371 * Returns true if successful, or false if not successful.
372 * If successful, the resulting clip is stored in outClipPath.
373 * If not successful, outClipPath is undefined, and a fallback method
374 * should be used.
375 */
376static bool get_clip_stack_path(const SkMatrix& transform,
377 const SkClipStack& clipStack,
378 const SkRegion& clipRegion,
379 SkPath* outClipPath) {
380 outClipPath->reset();
381 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
382
383 const SkClipStack::Element* clipEntry;
384 SkClipStack::Iter iter;
385 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
386 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
387 SkPath entryPath;
388 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
389 outClipPath->reset();
390 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
391 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000392 } else {
393 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000394 }
395 entryPath.transform(transform);
396
397 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
398 *outClipPath = entryPath;
399 } else {
400 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
401 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
402 return false;
403 }
404 }
405 }
406
407 if (outClipPath->isInverseFillType()) {
408 // The bounds are slightly outset to ensure this is correct in the
409 // face of floating-point accuracy and possible SkRegion bitmap
410 // approximations.
411 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
412 clipBounds.outset(SK_Scalar1, SK_Scalar1);
413 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
414 return false;
415 }
416 }
417 return true;
418}
419#endif
420
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000421// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000422// graphic state stack, and the fact that we can know all the clips used
423// on the page to optimize this.
424void GraphicStackState::updateClip(const SkClipStack& clipStack,
425 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000426 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000427 if (clipStack == currentEntry()->fClipStack) {
428 return;
429 }
430
431 while (fStackDepth > 0) {
432 pop();
433 if (clipStack == currentEntry()->fClipStack) {
434 return;
435 }
436 }
437 push();
438
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000439 currentEntry()->fClipStack = clipStack;
440 currentEntry()->fClipRegion = clipRegion;
441
442 SkMatrix transform;
443 transform.setTranslate(translation.fX, translation.fY);
444
445#ifdef SK_PDF_USE_PATHOPS
446 SkPath clipPath;
447 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
448 emit_clip(&clipPath, NULL, fContentStream);
449 return;
450 }
451#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000452 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
453 // already been applied. (If this is a top level device, then it specifies
454 // a clip to the content area. If this is a layer, then it specifies
455 // the clip in effect when the layer was created.) There's no need to
456 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
457 // initial clip on the parent layer. (This means there's a bug if the user
458 // expands the clip and then uses any xfer mode that uses dst:
459 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000460 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000461 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
462
463 // If the clip stack does anything other than intersect or if it uses
464 // an inverse fill type, we have to fall back to the clip region.
465 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000466 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000467 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000468 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
469 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000470 needRegion = true;
471 break;
472 }
473 }
474
475 if (needRegion) {
476 SkPath clipPath;
477 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
478 emit_clip(&clipPath, NULL, fContentStream);
479 } else {
480 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000481 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000482 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000483 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
484 switch (clipEntry->getType()) {
485 case SkClipStack::Element::kRect_Type: {
486 SkRect translatedClip;
487 transform.mapRect(&translatedClip, clipEntry->getRect());
488 emit_clip(NULL, &translatedClip, fContentStream);
489 break;
490 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000491 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000492 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000493 clipEntry->asPath(&translatedPath);
494 translatedPath.transform(transform, &translatedPath);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000495 emit_clip(&translatedPath, NULL, fContentStream);
496 break;
497 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000498 }
499 }
500 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000501}
502
503void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
504 if (matrix == currentEntry()->fMatrix) {
505 return;
506 }
507
508 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
509 SkASSERT(fStackDepth > 0);
510 SkASSERT(fEntries[fStackDepth].fClipStack ==
511 fEntries[fStackDepth -1].fClipStack);
512 pop();
513
514 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
515 }
516 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
517 return;
518 }
519
520 push();
521 SkPDFUtils::AppendTransform(matrix, fContentStream);
522 currentEntry()->fMatrix = matrix;
523}
524
525void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
526 // PDF treats a shader as a color, so we only set one or the other.
527 if (state.fShaderIndex >= 0) {
528 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000529 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000530 currentEntry()->fShaderIndex = state.fShaderIndex;
531 }
532 } else {
533 if (state.fColor != currentEntry()->fColor ||
534 currentEntry()->fShaderIndex >= 0) {
535 emit_pdf_color(state.fColor, fContentStream);
536 fContentStream->writeText("RG ");
537 emit_pdf_color(state.fColor, fContentStream);
538 fContentStream->writeText("rg\n");
539 currentEntry()->fColor = state.fColor;
540 currentEntry()->fShaderIndex = -1;
541 }
542 }
543
544 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000545 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000546 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
547 }
548
549 if (state.fTextScaleX) {
550 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
551 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
552 SkIntToScalar(100));
553 SkPDFScalar::Append(pdfScale, fContentStream);
554 fContentStream->writeText(" Tz\n");
555 currentEntry()->fTextScaleX = state.fTextScaleX;
556 }
557 if (state.fTextFill != currentEntry()->fTextFill) {
558 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
559 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
560 enum_must_match_value);
561 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
562 enum_must_match_value);
563 fContentStream->writeDecAsText(state.fTextFill);
564 fContentStream->writeText(" Tr\n");
565 currentEntry()->fTextFill = state.fTextFill;
566 }
567 }
568}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000569
commit-bot@chromium.org15a14052014-02-16 00:59:25 +0000570SkBaseDevice* SkPDFDevice::onCreateDevice(const SkImageInfo& info, Usage usage) {
senorblancob0e89dc2014-10-20 14:03:12 -0700571 // PDF does not support image filters, so render them on CPU.
572 // Note that this rendering is done at "screen" resolution (100dpi), not
573 // printer resolution.
574 // FIXME: It may be possible to express some filters natively using PDF
575 // to improve quality and file size (http://skbug.com/3043)
576 if (kImageFilter_Usage == usage) {
577 return SkBitmapDevice::Create(info);
578 }
579
bsalomon@google.come97f0852011-06-17 13:10:25 +0000580 SkMatrix initialTransform;
581 initialTransform.reset();
commit-bot@chromium.org15a14052014-02-16 00:59:25 +0000582 SkISize size = SkISize::Make(info.width(), info.height());
bsalomon@google.come97f0852011-06-17 13:10:25 +0000583 return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
584}
585
586
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000587struct ContentEntry {
588 GraphicStateEntry fState;
589 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000590 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000591
592 // If the stack is too deep we could get Stack Overflow.
593 // So we manually destruct the object.
594 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000595 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000596 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000597 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000598 // When the destructor is called, fNext is NULL and exits.
599 delete val;
600 val = valNext;
601 }
602 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000603};
604
605// A helper class to automatically finish a ContentEntry at the end of a
606// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000607class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000608public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000609 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
610 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000611 : fDevice(device),
612 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000613 fXfermode(SkXfermode::kSrcOver_Mode),
614 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000615 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
616 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000617 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
618 const SkRegion& clipRegion, const SkMatrix& matrix,
619 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000620 : fDevice(device),
621 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000622 fXfermode(SkXfermode::kSrcOver_Mode),
623 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000624 init(clipStack, clipRegion, matrix, paint, hasText);
625 }
626
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000627 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000628 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000629 SkPath* shape = &fShape;
630 if (shape->isEmpty()) {
631 shape = NULL;
632 }
633 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000634 }
reed@google.comfc641d02012-09-20 17:52:20 +0000635 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000636 }
637
638 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000639
640 /* Returns true when we explicitly need the shape of the drawing. */
641 bool needShape() {
642 switch (fXfermode) {
643 case SkXfermode::kClear_Mode:
644 case SkXfermode::kSrc_Mode:
645 case SkXfermode::kSrcIn_Mode:
646 case SkXfermode::kSrcOut_Mode:
647 case SkXfermode::kDstIn_Mode:
648 case SkXfermode::kDstOut_Mode:
649 case SkXfermode::kSrcATop_Mode:
650 case SkXfermode::kDstATop_Mode:
651 case SkXfermode::kModulate_Mode:
652 return true;
653 default:
654 return false;
655 }
656 }
657
658 /* Returns true unless we only need the shape of the drawing. */
659 bool needSource() {
660 if (fXfermode == SkXfermode::kClear_Mode) {
661 return false;
662 }
663 return true;
664 }
665
666 /* If the shape is different than the alpha component of the content, then
667 * setShape should be called with the shape. In particular, images and
668 * devices have rectangular shape.
669 */
670 void setShape(const SkPath& shape) {
671 fShape = shape;
672 }
673
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000674private:
675 SkPDFDevice* fDevice;
676 ContentEntry* fContentEntry;
677 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000678 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000679 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000680
681 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
682 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000683 // Shape has to be flatten before we get here.
684 if (matrix.hasPerspective()) {
685 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000686 return;
687 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000688 if (paint.getXfermode()) {
689 paint.getXfermode()->asMode(&fXfermode);
690 }
691 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
692 matrix, paint, hasText,
693 &fDstFormXObject);
694 }
695};
696
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000697////////////////////////////////////////////////////////////////////////////////
698
reed89443ab2014-06-27 11:34:19 -0700699static inline SkImageInfo make_content_info(const SkISize& contentSize,
700 const SkMatrix* initialTransform) {
reed@google.com900ecf22014-02-20 20:55:37 +0000701 SkImageInfo info;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000702 if (initialTransform) {
703 // Compute the size of the drawing area.
704 SkVector drawingSize;
705 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000706 drawingSize.set(SkIntToScalar(contentSize.fWidth),
707 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000708 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000709 // This shouldn't happen, initial transform should be invertible.
710 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000711 inverse.reset();
712 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000713 inverse.mapVectors(&drawingSize, 1);
714 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
reed@google.com900ecf22014-02-20 20:55:37 +0000715 info = SkImageInfo::MakeUnknown(abs(size.fWidth), abs(size.fHeight));
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000716 } else {
reed@google.com900ecf22014-02-20 20:55:37 +0000717 info = SkImageInfo::MakeUnknown(abs(contentSize.fWidth),
718 abs(contentSize.fHeight));
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000719 }
reed89443ab2014-06-27 11:34:19 -0700720 return info;
reed@android.comf2b98d62010-12-20 18:26:13 +0000721}
722
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000723// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000724SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000725 const SkMatrix& initialTransform)
reed89443ab2014-06-27 11:34:19 -0700726 : fPageSize(pageSize)
727 , fContentSize(contentSize)
728 , fLastContentEntry(NULL)
729 , fLastMarginContentEntry(NULL)
730 , fClipStack(NULL)
731 , fEncoder(NULL)
732 , fRasterDpi(72.0f)
733{
734 const SkImageInfo info = make_content_info(contentSize, &initialTransform);
735
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000736 // Just report that PDF does not supports perspective in the
737 // initial transform.
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000738 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
739
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000740 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000741 // origin at the bottom left. This matrix corrects for that. But that only
742 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000743 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
744 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000745 fInitialTransform.preConcat(initialTransform);
reed89443ab2014-06-27 11:34:19 -0700746 fLegacyBitmap.setInfo(info);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000747
reed89443ab2014-06-27 11:34:19 -0700748 SkIRect existingClip = SkIRect::MakeWH(info.width(), info.height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000749 fExistingClipRegion.setRect(existingClip);
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000750 this->init();
751}
752
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000753// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000754SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
755 const SkClipStack& existingClipStack,
756 const SkRegion& existingClipRegion)
reed89443ab2014-06-27 11:34:19 -0700757 : fPageSize(layerSize)
758 , fContentSize(layerSize)
759 , fExistingClipStack(existingClipStack)
760 , fExistingClipRegion(existingClipRegion)
761 , fLastContentEntry(NULL)
762 , fLastMarginContentEntry(NULL)
763 , fClipStack(NULL)
764 , fEncoder(NULL)
765 , fRasterDpi(72.0f)
766{
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000767 fInitialTransform.reset();
reed89443ab2014-06-27 11:34:19 -0700768 fLegacyBitmap.setInfo(make_content_info(layerSize, NULL));
769
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000770 this->init();
771}
772
773SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000774 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000775}
776
777void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000778 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000779 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000780 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000781 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000782 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000783 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000784 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000785 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000786 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
787 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000788}
789
vandebo@chromium.org98594282011-07-25 22:34:12 +0000790void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000791 fGraphicStateResources.unrefAll();
792 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000793 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000794 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000795 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000796 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000797 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000798
vandebo@chromium.org98594282011-07-25 22:34:12 +0000799 if (clearFontUsage) {
800 fFontGlyphUsage->reset();
801 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000802}
803
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000804void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000805 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000806 this->init();
807
808 SkPaint paint;
809 paint.setColor(color);
810 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000811 SkMatrix identity;
812 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000813 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
814 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000815 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000816}
817
818void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000819 SkPaint newPaint = paint;
820 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000821 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000822 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000823}
824
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000825void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
826 ContentEntry* contentEntry) {
827 if (!contentEntry) {
828 return;
829 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000830 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
831 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000832 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000833 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000834 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000835 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000836 inverse.mapRect(&bbox);
837
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000838 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000839 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000840 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000841}
842
843void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
844 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000845 const SkPaint& passedPaint) {
846 if (count == 0) {
847 return;
848 }
849
epoger@google.comb58772f2013-03-08 09:09:10 +0000850 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
851 return;
852 }
853
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000854 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
855 // We only use this when there's a path effect because of the overhead
856 // of multiple calls to setUpContentEntry it causes.
857 if (passedPaint.getPathEffect()) {
858 if (d.fClip->isEmpty()) {
859 return;
860 }
861 SkDraw pointDraw(d);
862 pointDraw.fDevice = this;
863 pointDraw.drawPoints(mode, count, points, passedPaint, true);
864 return;
865 }
866
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000867 const SkPaint* paint = &passedPaint;
868 SkPaint modifiedPaint;
869
870 if (mode == SkCanvas::kPoints_PointMode &&
871 paint->getStrokeCap() != SkPaint::kRound_Cap) {
872 modifiedPaint = *paint;
873 paint = &modifiedPaint;
874 if (paint->getStrokeWidth()) {
875 // PDF won't draw a single point with square/butt caps because the
876 // orientation is ambiguous. Draw a rectangle instead.
877 modifiedPaint.setStyle(SkPaint::kFill_Style);
878 SkScalar strokeWidth = paint->getStrokeWidth();
879 SkScalar halfStroke = SkScalarHalf(strokeWidth);
880 for (size_t i = 0; i < count; i++) {
881 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
882 r.inset(-halfStroke, -halfStroke);
883 drawRect(d, r, modifiedPaint);
884 }
885 return;
886 } else {
887 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
888 }
889 }
890
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000891 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000892 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000893 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000894 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000895
896 switch (mode) {
897 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000898 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000899 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000900 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000901 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000902 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000903 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000904 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000905 break;
906 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000907 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000908 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000909 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000910 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000911 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000912 &content.entry()->fContent);
913 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000914 }
915 break;
916 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000917 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
918 for (size_t i = 0; i < count; i++) {
919 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000920 &content.entry()->fContent);
921 SkPDFUtils::ClosePath(&content.entry()->fContent);
922 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000923 }
924 break;
925 default:
926 SkASSERT(false);
927 }
928}
929
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000930void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000931 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000932 SkRect r = rect;
933 r.sort();
934
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000935 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000936 if (d.fClip->isEmpty()) {
937 return;
938 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000939 SkPath path;
940 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000941 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000942 return;
943 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000944
epoger@google.comb58772f2013-03-08 09:09:10 +0000945 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000946 return;
947 }
948
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000949 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000950 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000951 return;
952 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000953 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000954 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000955 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000956}
957
reed89443ab2014-06-27 11:34:19 -0700958void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000959 SkPath path;
960 path.addRRect(rrect);
961 this->drawPath(draw, path, paint, NULL, true);
962}
963
reed89443ab2014-06-27 11:34:19 -0700964void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
965 SkPath path;
966 path.addOval(oval);
967 this->drawPath(draw, path, paint, NULL, true);
968}
969
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000970void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000971 const SkPaint& paint, const SkMatrix* prePathMatrix,
972 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000973 SkPath modifiedPath;
974 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
975
976 SkMatrix matrix = *d.fMatrix;
977 if (prePathMatrix) {
978 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
979 if (!pathIsMutable) {
980 pathPtr = &modifiedPath;
981 pathIsMutable = true;
982 }
983 origPath.transform(*prePathMatrix, pathPtr);
984 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000985 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000986 }
987 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000988
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000989 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000990 if (d.fClip->isEmpty()) {
991 return;
992 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000993 if (!pathIsMutable) {
994 pathPtr = &modifiedPath;
995 pathIsMutable = true;
996 }
997 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000998
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000999 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001000 noEffectPaint.setPathEffect(NULL);
1001 if (fill) {
1002 noEffectPaint.setStyle(SkPaint::kFill_Style);
1003 } else {
1004 noEffectPaint.setStyle(SkPaint::kStroke_Style);
1005 noEffectPaint.setStrokeWidth(0);
1006 }
1007 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +00001008 return;
1009 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001010
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001011#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001012 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001013 return;
1014 }
1015#endif
1016
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001017 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001018 return;
1019 }
1020
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001021 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001022 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001023 return;
1024 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001025 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1026 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001027 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001028 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001029}
1030
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001031void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1032 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001033 const SkPaint& paint,
1034 SkCanvas::DrawBitmapRectFlags flags) {
1035 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001036 SkMatrix matrix;
1037 SkRect bitmapBounds, tmpSrc, tmpDst;
1038 SkBitmap tmpBitmap;
1039
1040 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1041
1042 // Compute matrix from the two rectangles
1043 if (src) {
1044 tmpSrc = *src;
1045 } else {
1046 tmpSrc = bitmapBounds;
1047 }
1048 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1049
1050 const SkBitmap* bitmapPtr = &bitmap;
1051
1052 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1053 // needed (if the src was clipped). No check needed if src==null.
1054 if (src) {
1055 if (!bitmapBounds.contains(*src)) {
1056 if (!tmpSrc.intersect(bitmapBounds)) {
1057 return; // nothing to draw
1058 }
1059 // recompute dst, based on the smaller tmpSrc
1060 matrix.mapRect(&tmpDst, tmpSrc);
1061 }
1062
1063 // since we may need to clamp to the borders of the src rect within
1064 // the bitmap, we extract a subset.
1065 // TODO: make sure this is handled in drawBitmap and remove from here.
1066 SkIRect srcIR;
1067 tmpSrc.roundOut(&srcIR);
1068 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1069 return;
1070 }
1071 bitmapPtr = &tmpBitmap;
1072
1073 // Since we did an extract, we need to adjust the matrix accordingly
1074 SkScalar dx = 0, dy = 0;
1075 if (srcIR.fLeft > 0) {
1076 dx = SkIntToScalar(srcIR.fLeft);
1077 }
1078 if (srcIR.fTop > 0) {
1079 dy = SkIntToScalar(srcIR.fTop);
1080 }
1081 if (dx || dy) {
1082 matrix.preTranslate(dx, dy);
1083 }
1084 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001085 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001086}
1087
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001088void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001089 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001090 if (d.fClip->isEmpty()) {
1091 return;
1092 }
1093
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001094 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001095 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001096 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1097 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001098}
1099
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001100void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001101 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001102 if (d.fClip->isEmpty()) {
1103 return;
1104 }
1105
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001106 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001107 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001108 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1109 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001110}
1111
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001112void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001113 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001114 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1115 if (paint.getMaskFilter() != NULL) {
1116 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1117 // making text unreadable (e.g. same text twice when using CSS shadows).
1118 return;
1119 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001120 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001121 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001122 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001123 return;
1124 }
1125
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001126 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001127 const uint16_t* glyphIDs = NULL;
reed@google.comaec40662014-04-18 19:29:07 +00001128 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001129 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001130
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001131 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001132 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001133 content.entry()->fContent.writeText("BT\n");
1134 set_text_transform(x, y, textPaint.getTextSkewX(),
1135 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001136 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001137
1138 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1139
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001140 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001141 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1142 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001143
1144 int availableGlyphs = font->glyphsToPDFFontEncoding(
1145 glyphIDsCopy.begin() + consumedGlyphCount,
1146 numGlyphs - consumedGlyphCount);
1147 fFontGlyphUsage->noteGlyphUsage(
1148 font, glyphIDsCopy.begin() + consumedGlyphCount,
1149 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001150 SkString encodedString =
halcanary2f912f32014-10-16 09:53:20 -07001151 SkPDFString::FormatString(glyphIDsCopy.begin() + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001152 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001153 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001154 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001155 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001156 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001157 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001158}
1159
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001160void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001161 const SkScalar pos[], int scalarsPerPos,
1162 const SkPoint& offset, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001163 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1164 if (paint.getMaskFilter() != NULL) {
1165 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1166 // making text unreadable (e.g. same text twice when using CSS shadows).
1167 return;
1168 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001169 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001170 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001171 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001172 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001173 return;
1174 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001175
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001176 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001177 const uint16_t* glyphIDs = NULL;
1178 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001179 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001180
1181 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001182 content.entry()->fContent.writeText("BT\n");
1183 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001184 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001185 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001186 uint16_t encodedValue = glyphIDs[i];
1187 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001188 // The current pdf font cannot encode the current glyph.
1189 // Try to get a pdf font which can encode the current glyph.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001190 updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001191 font = content.entry()->fState.fFont;
1192 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1193 SkDEBUGFAIL("PDF could not encode glyph.");
1194 continue;
1195 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001196 }
bungeman22edc832014-10-03 07:55:58 -07001197
vandebo@chromium.org98594282011-07-25 22:34:12 +00001198 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001199 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1200 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1201
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001202 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001203 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001204 SkString encodedString =
bungeman22edc832014-10-03 07:55:58 -07001205 SkPDFString::FormatString(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001206 content.entry()->fContent.writeText(encodedString.c_str());
1207 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001208 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001209 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001210}
1211
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001212void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001213 const SkPath& path, const SkMatrix* matrix,
1214 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001215 if (d.fClip->isEmpty()) {
1216 return;
1217 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001218 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001219}
1220
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001221void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001222 int vertexCount, const SkPoint verts[],
1223 const SkPoint texs[], const SkColor colors[],
1224 SkXfermode* xmode, const uint16_t indices[],
1225 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001226 if (d.fClip->isEmpty()) {
1227 return;
1228 }
reed@google.com85e143c2013-12-30 15:51:25 +00001229 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001230}
1231
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001232void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1233 int x, int y, const SkPaint& paint) {
commit-bot@chromium.org3da3b622014-03-13 19:38:10 +00001234 // our onCreateDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001235 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001236 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001237 return;
1238 }
1239
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001240 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001241 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001242 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001243 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001244 return;
1245 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001246 if (content.needShape()) {
1247 SkPath shape;
1248 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001249 SkIntToScalar(device->width()),
1250 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001251 content.setShape(shape);
1252 }
1253 if (!content.needSource()) {
1254 return;
1255 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001256
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001257 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1258 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001259 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001260
1261 // Merge glyph sets from the drawn device.
1262 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001263}
1264
reed89443ab2014-06-27 11:34:19 -07001265SkImageInfo SkPDFDevice::imageInfo() const {
1266 return fLegacyBitmap.info();
1267}
1268
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001269void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1270 INHERITED::onAttachToCanvas(canvas);
1271
1272 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1273 fClipStack = canvas->getClipStack();
1274}
1275
1276void SkPDFDevice::onDetachFromCanvas() {
1277 INHERITED::onDetachFromCanvas();
1278
1279 fClipStack = NULL;
1280}
1281
reed4a8126e2014-09-22 07:29:03 -07001282SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1283 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001284}
1285
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001286ContentEntry* SkPDFDevice::getLastContentEntry() {
1287 if (fDrawingArea == kContent_DrawingArea) {
1288 return fLastContentEntry;
1289 } else {
1290 return fLastMarginContentEntry;
1291 }
1292}
1293
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001294SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001295 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001296 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001297 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001298 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001299 }
1300}
1301
1302void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1303 if (fDrawingArea == kContent_DrawingArea) {
1304 fLastContentEntry = contentEntry;
1305 } else {
1306 fLastMarginContentEntry = contentEntry;
1307 }
1308}
1309
1310void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001311 // A ScopedContentEntry only exists during the course of a draw call, so
1312 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001313 fDrawingArea = drawingArea;
1314}
1315
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001316SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001317 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001318 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001319
1320 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001321 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001322 fResourceDict->insertResourceAsReference(
1323 SkPDFResourceDict::kExtGState_ResourceType,
1324 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001325 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001326 }
1327
1328 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001329 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001330 fResourceDict->insertResourceAsReference(
1331 SkPDFResourceDict::kXObject_ResourceType,
1332 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001333 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001334 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001335
1336 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001337 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001338 fResourceDict->insertResourceAsReference(
1339 SkPDFResourceDict::kFont_ResourceType,
1340 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001341 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001342 }
1343
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001344 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001345 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001346 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001347 fResourceDict->insertResourceAsReference(
1348 SkPDFResourceDict::kPattern_ResourceType,
1349 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001350 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001351 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001352 }
1353 return fResourceDict;
1354}
1355
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001356const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1357 return fFontResources;
1358}
1359
reed@google.com2a006c12012-09-19 17:05:55 +00001360SkPDFArray* SkPDFDevice::copyMediaBox() const {
1361 // should this be a singleton?
1362 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001363
reed@google.com2a006c12012-09-19 17:05:55 +00001364 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001365 mediaBox->reserve(4);
1366 mediaBox->append(zero.get());
1367 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001368 mediaBox->appendInt(fPageSize.fWidth);
1369 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001370 return mediaBox;
1371}
1372
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001373SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001374 SkMemoryStream* result = new SkMemoryStream;
1375 result->setData(this->copyContentToData())->unref();
1376 return result;
1377}
1378
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001379void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1380 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001381 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1382 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001383 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001384 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001385 SkPoint translation;
1386 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001387 translation.negate();
1388 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1389 translation);
1390 gsState.updateMatrix(entry->fState.fMatrix);
1391 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001392
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001393 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001394 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001395 entry = entry->fNext.get();
1396 }
1397 gsState.drainStack();
1398}
1399
reed@google.com5667afc2011-06-27 14:42:15 +00001400SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001401 SkDynamicMemoryWStream data;
1402 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1403 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001404 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001405
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001406 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1407 // colors the contentArea white before it starts drawing into it and
1408 // that currently acts as our clip.
1409 // Also, think about adding a transform here (or assume that the values
1410 // sent across account for that)
1411 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001412
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001413 // If the content area is the entire page, then we don't need to clip
1414 // the content area (PDF area clips to the page size). Otherwise,
1415 // we have to clip to the content area; we've already applied the
1416 // initial transform, so just clip to the device size.
1417 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001418 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1419 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001420 emit_clip(NULL, &r, &data);
1421 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001422
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001423 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001424
reed@google.com5667afc2011-06-27 14:42:15 +00001425 // potentially we could cache this SkData, and only rebuild it if we
1426 // see that our state has changed.
1427 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001428}
1429
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001430#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001431/* Draws an inverse filled path by using Path Ops to compute the positive
1432 * inverse using the current clip as the inverse bounds.
1433 * Return true if this was an inverse path and was properly handled,
1434 * otherwise returns false and the normal drawing routine should continue,
1435 * either as a (incorrect) fallback or because the path was not inverse
1436 * in the first place.
1437 */
1438bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001439 const SkPaint& paint, bool pathIsMutable,
1440 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001441 if (!origPath.isInverseFillType()) {
1442 return false;
1443 }
1444
1445 if (d.fClip->isEmpty()) {
1446 return false;
1447 }
1448
1449 SkPath modifiedPath;
1450 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1451 SkPaint noInversePaint(paint);
1452
1453 // Merge stroking operations into final path.
1454 if (SkPaint::kStroke_Style == paint.getStyle() ||
1455 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1456 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1457 if (doFillPath) {
1458 noInversePaint.setStyle(SkPaint::kFill_Style);
1459 noInversePaint.setStrokeWidth(0);
1460 pathPtr = &modifiedPath;
1461 } else {
1462 // To be consistent with the raster output, hairline strokes
1463 // are rendered as non-inverted.
1464 modifiedPath.toggleInverseFillType();
1465 drawPath(d, modifiedPath, paint, NULL, true);
1466 return true;
1467 }
1468 }
1469
1470 // Get bounds of clip in current transform space
1471 // (clip bounds are given in device space).
1472 SkRect bounds;
1473 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001474 SkMatrix totalMatrix = *d.fMatrix;
1475 if (prePathMatrix) {
1476 totalMatrix.preConcat(*prePathMatrix);
1477 }
1478 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001479 return false;
1480 }
1481 bounds.set(d.fClip->getBounds());
1482 transformInverse.mapRect(&bounds);
1483
1484 // Extend the bounds by the line width (plus some padding)
1485 // so the edge doesn't cause a visible stroke.
1486 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1487 paint.getStrokeWidth() + SK_Scalar1);
1488
1489 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1490 return false;
1491 }
1492
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001493 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001494 return true;
1495}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001496#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001497
epoger@google.comb58772f2013-03-08 09:09:10 +00001498bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1499 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001500 SkAnnotation* annotationInfo = p.getAnnotation();
1501 if (!annotationInfo) {
1502 return false;
1503 }
1504 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001505 if (urlData) {
1506 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001507 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001508 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001509 SkData* linkToName = annotationInfo->find(
1510 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001511 if (linkToName) {
1512 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001513 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001514 }
1515 return false;
1516}
1517
1518bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1519 const SkMatrix& matrix,
1520 const SkPaint& paint) {
1521 SkAnnotation* annotationInfo = paint.getAnnotation();
1522 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001523 return false;
1524 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001525 SkData* nameData = annotationInfo->find(
1526 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001527 if (nameData) {
1528 for (size_t i = 0; i < count; i++) {
1529 defineNamedDestination(nameData, points[i], matrix);
1530 }
reed@google.com44699382013-10-31 17:28:30 +00001531 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001532 }
1533 return false;
1534}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001535
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001536SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1537 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001538 SkMatrix transform = matrix;
1539 transform.postConcat(fInitialTransform);
1540 SkRect translatedRect;
1541 transform.mapRect(&translatedRect, r);
1542
reed@google.com2a006c12012-09-19 17:05:55 +00001543 if (NULL == fAnnotations) {
1544 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001545 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001546 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001547 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001548 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001549
epoger@google.comb58772f2013-03-08 09:09:10 +00001550 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001551 border->reserve(3);
1552 border->appendInt(0); // Horizontal corner radius.
1553 border->appendInt(0); // Vertical corner radius.
1554 border->appendInt(0); // Width, 0 = no border.
1555 annotation->insert("Border", border.get());
1556
epoger@google.comb58772f2013-03-08 09:09:10 +00001557 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001558 rect->reserve(4);
1559 rect->appendScalar(translatedRect.fLeft);
1560 rect->appendScalar(translatedRect.fTop);
1561 rect->appendScalar(translatedRect.fRight);
1562 rect->appendScalar(translatedRect.fBottom);
1563 annotation->insert("Rect", rect.get());
1564
epoger@google.comb58772f2013-03-08 09:09:10 +00001565 return annotation;
1566}
epoger@google.com1cad8982013-03-06 00:05:13 +00001567
epoger@google.comb58772f2013-03-08 09:09:10 +00001568void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1569 const SkMatrix& matrix) {
1570 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1571
1572 SkString url(static_cast<const char *>(urlData->data()),
1573 urlData->size() - 1);
1574 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1575 action->insertName("S", "URI");
1576 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1577 annotation->insert("A", action.get());
1578}
1579
1580void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1581 const SkMatrix& matrix) {
1582 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1583 SkString name(static_cast<const char *>(nameData->data()),
1584 nameData->size() - 1);
1585 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1586}
1587
1588struct NamedDestination {
1589 const SkData* nameData;
1590 SkPoint point;
1591
1592 NamedDestination(const SkData* nameData, const SkPoint& point)
1593 : nameData(nameData), point(point) {
1594 nameData->ref();
1595 }
1596
1597 ~NamedDestination() {
1598 nameData->unref();
1599 }
1600};
1601
1602void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1603 const SkMatrix& matrix) {
1604 SkMatrix transform = matrix;
1605 transform.postConcat(fInitialTransform);
1606 SkPoint translatedPoint;
1607 transform.mapXY(point.x(), point.y(), &translatedPoint);
1608 fNamedDestinations.push(
1609 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1610}
1611
1612void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1613 int nDest = fNamedDestinations.count();
1614 for (int i = 0; i < nDest; i++) {
1615 NamedDestination* dest = fNamedDestinations[i];
1616 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1617 pdfDest->reserve(5);
1618 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1619 pdfDest->appendName("XYZ");
1620 pdfDest->appendScalar(dest->point.x());
1621 pdfDest->appendScalar(dest->point.y());
1622 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001623 dict->insert(static_cast<const char *>(dest->nameData->data()),
1624 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001625 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001626}
1627
reed@google.comfc641d02012-09-20 17:52:20 +00001628SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1629 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001630 // We always draw the form xobjects that we create back into the device, so
1631 // we simply preserve the font usage instead of pulling it out and merging
1632 // it back in later.
1633 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001634 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001635 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001636}
1637
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001638void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1639 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001640 const SkClipStack* clipStack,
1641 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001642 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001643 bool invertClip) {
1644 if (clipRegion.isEmpty() && !invertClip) {
1645 return;
1646 }
1647
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001648 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1649 SkPDFGraphicState::GetSMaskGraphicState(
1650 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1651
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001652 SkMatrix identity;
1653 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001654 SkPaint paint;
1655 paint.setXfermodeMode(mode);
1656 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001657 if (!content.entry()) {
1658 return;
1659 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001660 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001661 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001662 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001663
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001664 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001665 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001666 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001667}
1668
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001669ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1670 const SkRegion& clipRegion,
1671 const SkMatrix& matrix,
1672 const SkPaint& paint,
1673 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001674 SkPDFFormXObject** dst) {
1675 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001676 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001677 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001678 }
1679
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001680 // The clip stack can come from an SkDraw where it is technically optional.
1681 SkClipStack synthesizedClipStack;
1682 if (clipStack == NULL) {
1683 if (clipRegion == fExistingClipRegion) {
1684 clipStack = &fExistingClipStack;
1685 } else {
1686 // GraphicStackState::updateClip expects the clip stack to have
1687 // fExistingClip as a prefix, so start there, then set the clip
1688 // to the passed region.
1689 synthesizedClipStack = fExistingClipStack;
1690 SkPath clipPath;
1691 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001692 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1693 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001694 clipStack = &synthesizedClipStack;
1695 }
1696 }
1697
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001698 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1699 if (paint.getXfermode()) {
1700 paint.getXfermode()->asMode(&xfermode);
1701 }
1702
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001703 // For the following modes, we want to handle source and destination
1704 // separately, so make an object of what's already there.
1705 if (xfermode == SkXfermode::kClear_Mode ||
1706 xfermode == SkXfermode::kSrc_Mode ||
1707 xfermode == SkXfermode::kSrcIn_Mode ||
1708 xfermode == SkXfermode::kDstIn_Mode ||
1709 xfermode == SkXfermode::kSrcOut_Mode ||
1710 xfermode == SkXfermode::kDstOut_Mode ||
1711 xfermode == SkXfermode::kSrcATop_Mode ||
1712 xfermode == SkXfermode::kDstATop_Mode ||
1713 xfermode == SkXfermode::kModulate_Mode) {
1714 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001715 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001716 SkASSERT(isContentEmpty());
1717 } else if (xfermode != SkXfermode::kSrc_Mode &&
1718 xfermode != SkXfermode::kSrcOut_Mode) {
1719 // Except for Src and SrcOut, if there isn't anything already there,
1720 // then we're done.
1721 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001722 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001723 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001724 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001725 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001726
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001727 // Dst xfer mode doesn't draw source at all.
1728 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001729 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001730 }
1731
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001732 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001733 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001734
1735 ContentEntry* lastContentEntry = getLastContentEntry();
1736 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1737 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001738 } else {
1739 newEntry.reset(new ContentEntry);
1740 entry = newEntry.get();
1741 }
1742
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001743 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001744 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001745 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1746 entry->fState.compareInitialState(lastContentEntry->fState)) {
1747 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001748 }
1749
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001750 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001751 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001752 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001753 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001754 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001755 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001756 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001757 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001758 lastContentEntry->fNext.reset(entry);
1759 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001760 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001761 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001762 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001763}
1764
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001765void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001766 SkPDFFormXObject* dst,
1767 SkPath* shape) {
1768 if (xfermode != SkXfermode::kClear_Mode &&
1769 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001770 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001771 xfermode != SkXfermode::kSrcIn_Mode &&
1772 xfermode != SkXfermode::kDstIn_Mode &&
1773 xfermode != SkXfermode::kSrcOut_Mode &&
1774 xfermode != SkXfermode::kDstOut_Mode &&
1775 xfermode != SkXfermode::kSrcATop_Mode &&
1776 xfermode != SkXfermode::kDstATop_Mode &&
1777 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001778 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001779 return;
1780 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001781 if (xfermode == SkXfermode::kDstOver_Mode) {
1782 SkASSERT(!dst);
1783 ContentEntry* firstContentEntry = getContentEntries()->get();
1784 if (firstContentEntry->fContent.getOffset() == 0) {
1785 // For DstOver, an empty content entry was inserted before the rest
1786 // of the content entries. If nothing was drawn, it needs to be
1787 // removed.
1788 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1789 contentEntries->reset(firstContentEntry->fNext.detach());
1790 }
1791 return;
1792 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001793 if (!dst) {
1794 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1795 xfermode == SkXfermode::kSrcOut_Mode);
1796 return;
1797 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001798
1799 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001800 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001801 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001802 // Changing the current content into a form-xobject will destroy the clip
1803 // objects which is fine since the xobject will already be clipped. However
1804 // if source has shape, we need to clip it too, so a copy of the clip is
1805 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001806 SkClipStack clipStack = contentEntries->fState.fClipStack;
1807 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001808
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001809 SkMatrix identity;
1810 identity.reset();
1811 SkPaint stockPaint;
1812
reed@google.comfc641d02012-09-20 17:52:20 +00001813 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001814 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001815 // If nothing was drawn and there's no shape, then the draw was a
1816 // no-op, but dst needs to be restored for that to be true.
1817 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1818 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1819 // reduces to Dst.
1820 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1821 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001822 ScopedContentEntry content(this, &fExistingClipStack,
1823 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001824 stockPaint);
1825 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1826 &content.entry()->fContent);
1827 return;
1828 } else {
1829 xfermode = SkXfermode::kClear_Mode;
1830 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001831 } else {
1832 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001833 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001834 }
1835
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001836 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1837 // without alpha.
1838 if (xfermode == SkXfermode::kSrcATop_Mode) {
1839 // TODO(vandebo): In order to properly support SrcATop we have to track
1840 // the shape of what's been drawn at all times. It's the intersection of
1841 // the non-transparent parts of the device and the outlines (shape) of
1842 // all images and devices drawn.
1843 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001844 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001845 SkXfermode::kSrcOver_Mode, true);
1846 } else {
1847 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1848 SkPDFFormXObject* dstMask = srcFormXObject.get();
1849 if (shape != NULL) {
1850 // Draw shape into a form-xobject.
1851 SkDraw d;
1852 d.fMatrix = &identity;
1853 d.fClip = &clipRegion;
1854 d.fClipStack = &clipStack;
1855 SkPaint filledPaint;
1856 filledPaint.setColor(SK_ColorBLACK);
1857 filledPaint.setStyle(SkPaint::kFill_Style);
1858 this->drawPath(d, *shape, filledPaint, NULL, true);
1859
1860 dstMaskStorage.reset(createFormXObjectFromDevice());
1861 dstMask = dstMaskStorage.get();
1862 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001863 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1864 &fExistingClipStack, fExistingClipRegion,
1865 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001866 }
1867
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001868 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001869 return;
1870 } else if (xfermode == SkXfermode::kSrc_Mode ||
1871 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001872 ScopedContentEntry content(this, &fExistingClipStack,
1873 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001874 if (content.entry()) {
1875 SkPDFUtils::DrawFormXObject(
1876 this->addXObjectResource(srcFormXObject.get()),
1877 &content.entry()->fContent);
1878 }
1879 if (xfermode == SkXfermode::kSrc_Mode) {
1880 return;
1881 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001882 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001883 ScopedContentEntry content(this, &fExistingClipStack,
1884 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001885 if (content.entry()) {
1886 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1887 &content.entry()->fContent);
1888 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001889 }
1890
1891 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1892 xfermode == SkXfermode::kDstIn_Mode ||
1893 xfermode == SkXfermode::kSrcOut_Mode ||
1894 xfermode == SkXfermode::kDstOut_Mode ||
1895 xfermode == SkXfermode::kSrcATop_Mode ||
1896 xfermode == SkXfermode::kDstATop_Mode ||
1897 xfermode == SkXfermode::kModulate_Mode);
1898
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001899 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001900 xfermode == SkXfermode::kSrcOut_Mode ||
1901 xfermode == SkXfermode::kSrcATop_Mode) {
1902 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001903 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001904 SkXfermode::kSrcOver_Mode,
1905 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001906 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001907 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1908 if (xfermode == SkXfermode::kModulate_Mode) {
1909 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001910 dst, &fExistingClipStack,
1911 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001912 SkXfermode::kSrcOver_Mode, false);
1913 mode = SkXfermode::kMultiply_Mode;
1914 }
1915 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001916 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001917 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001918 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001919}
1920
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001921bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001922 ContentEntry* contentEntries = getContentEntries()->get();
1923 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1924 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001925 return true;
1926 }
1927 return false;
1928}
1929
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001930void SkPDFDevice::populateGraphicStateEntryFromPaint(
1931 const SkMatrix& matrix,
1932 const SkClipStack& clipStack,
1933 const SkRegion& clipRegion,
1934 const SkPaint& paint,
1935 bool hasText,
1936 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001937 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001938 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1939 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001940
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001941 entry->fMatrix = matrix;
1942 entry->fClipStack = clipStack;
1943 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001944 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1945 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001946
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001947 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001948 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001949 const SkShader* shader = paint.getShader();
1950 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001951 if (shader) {
1952 // PDF positions patterns relative to the initial transform, so
1953 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001954 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001955 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001956
1957 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001958 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001959 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001960
1961 // We need to apply the initial transform to bounds in order to get
1962 // bounds in a consistent coordinate system.
1963 SkRect boundsTemp;
1964 boundsTemp.set(bounds);
1965 fInitialTransform.mapRect(&boundsTemp);
1966 boundsTemp.roundOut(&bounds);
1967
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001968 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001969
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001970 if (pdfShader.get()) {
1971 // pdfShader has been canonicalized so we can directly compare
1972 // pointers.
1973 int resourceIndex = fShaderResources.find(pdfShader.get());
1974 if (resourceIndex < 0) {
1975 resourceIndex = fShaderResources.count();
1976 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001977 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001978 }
1979 entry->fShaderIndex = resourceIndex;
1980 } else {
1981 // A color shader is treated as an invalid shader so we don't have
1982 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001983 SkShader::GradientInfo gradientInfo;
1984 SkColor gradientColor;
1985 gradientInfo.fColors = &gradientColor;
1986 gradientInfo.fColorOffsets = NULL;
1987 gradientInfo.fColorCount = 1;
1988 if (shader->asAGradient(&gradientInfo) ==
1989 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001990 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1991 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001992 }
1993 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001994 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001995
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001996 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001997 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001998 newGraphicState.reset(
1999 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002000 } else {
2001 SkPaint newPaint = paint;
2002 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002003 newGraphicState.reset(
2004 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002005 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002006 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002007 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002008
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00002009 if (hasText) {
2010 entry->fTextScaleX = paint.getTextScaleX();
2011 entry->fTextFill = paint.getStyle();
2012 } else {
2013 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002014 }
2015}
2016
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002017int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2018 // Assumes that gs has been canonicalized (so we can directly compare
2019 // pointers).
2020 int result = fGraphicStateResources.find(gs);
2021 if (result < 0) {
2022 result = fGraphicStateResources.count();
2023 fGraphicStateResources.push(gs);
2024 gs->ref();
2025 }
2026 return result;
2027}
2028
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002029int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2030 // Assumes that xobject has been canonicalized (so we can directly compare
2031 // pointers).
2032 int result = fXObjectResources.find(xObject);
2033 if (result < 0) {
2034 result = fXObjectResources.count();
2035 fXObjectResources.push(xObject);
2036 xObject->ref();
2037 }
2038 return result;
2039}
2040
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002041void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2042 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002043 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002044 if (contentEntry->fState.fFont == NULL ||
2045 contentEntry->fState.fTextSize != paint.getTextSize() ||
2046 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002047 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002048 contentEntry->fContent.writeText("/");
2049 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2050 SkPDFResourceDict::kFont_ResourceType,
2051 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002052 contentEntry->fContent.writeText(" ");
2053 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2054 contentEntry->fContent.writeText(" Tf\n");
2055 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002056 }
2057}
2058
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002059int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002060 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2061 glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002062 int resourceIndex = fFontResources.find(newFont.get());
2063 if (resourceIndex < 0) {
2064 resourceIndex = fFontResources.count();
2065 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002066 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002067 }
2068 return resourceIndex;
2069}
2070
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002071void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002072 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002073 const SkRegion& origClipRegion,
2074 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002075 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002076 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002077 SkMatrix matrix = origMatrix;
2078 SkRegion perspectiveBounds;
2079 const SkRegion* clipRegion = &origClipRegion;
2080 SkBitmap perspectiveBitmap;
2081 const SkBitmap* bitmap = &origBitmap;
2082 SkBitmap tmpSubsetBitmap;
2083
2084 // Rasterize the bitmap using perspective in a new bitmap.
2085 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002086 if (fRasterDpi == 0) {
2087 return;
2088 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002089 SkBitmap* subsetBitmap;
2090 if (srcRect) {
2091 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2092 return;
2093 }
2094 subsetBitmap = &tmpSubsetBitmap;
2095 } else {
2096 subsetBitmap = &tmpSubsetBitmap;
2097 *subsetBitmap = origBitmap;
2098 }
2099 srcRect = NULL;
2100
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002101 // Transform the bitmap in the new space, without taking into
2102 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002103 SkPath perspectiveOutline;
2104 perspectiveOutline.addRect(
2105 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2106 SkIntToScalar(subsetBitmap->height())));
2107 perspectiveOutline.transform(origMatrix);
2108
2109 // TODO(edisonn): perf - use current clip too.
2110 // Retrieve the bounds of the new shape.
2111 SkRect bounds = perspectiveOutline.getBounds();
2112
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002113 // Transform the bitmap in the new space, taking into
2114 // account the initial transform.
2115 SkMatrix total = origMatrix;
2116 total.postConcat(fInitialTransform);
2117 total.postScale(SkIntToScalar(fRasterDpi) /
2118 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2119 SkIntToScalar(fRasterDpi) /
2120 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2121 SkPath physicalPerspectiveOutline;
2122 physicalPerspectiveOutline.addRect(
2123 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2124 SkIntToScalar(subsetBitmap->height())));
2125 physicalPerspectiveOutline.transform(total);
2126
2127 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2128 bounds.width();
2129 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2130 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002131
2132 // TODO(edisonn): A better approach would be to use a bitmap shader
2133 // (in clamp mode) and draw a rect over the entire bounding box. Then
2134 // intersect perspectiveOutline to the clip. That will avoid introducing
2135 // alpha to the image while still giving good behavior at the edge of
2136 // the image. Avoiding alpha will reduce the pdf size and generation
2137 // CPU time some.
2138
reed@google.com9ebcac52014-01-24 18:53:42 +00002139 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2140 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002141 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002142 return;
2143 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002144 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2145
reed89443ab2014-06-27 11:34:19 -07002146 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002147
2148 SkScalar deltaX = bounds.left();
2149 SkScalar deltaY = bounds.top();
2150
2151 SkMatrix offsetMatrix = origMatrix;
2152 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002153 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002154
2155 // Translate the draw in the new canvas, so we perfectly fit the
2156 // shape in the bitmap.
2157 canvas.setMatrix(offsetMatrix);
2158
2159 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2160
2161 // Make sure the final bits are in the bitmap.
2162 canvas.flush();
2163
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002164 // In the new space, we use the identity matrix translated
2165 // and scaled to reflect DPI.
2166 matrix.setScale(1 / scaleX, 1 / scaleY);
2167 matrix.postTranslate(deltaX, deltaY);
2168
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002169 perspectiveBounds.setRect(
2170 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2171 SkScalarFloorToInt(bounds.y()),
2172 SkScalarCeilToInt(bounds.width()),
2173 SkScalarCeilToInt(bounds.height())));
2174 clipRegion = &perspectiveBounds;
2175 srcRect = NULL;
2176 bitmap = &perspectiveBitmap;
2177 }
2178
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002179 SkMatrix scaled;
2180 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002181 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2182 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002183 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002184 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002185 scaled.postScale(SkIntToScalar(subset.width()),
2186 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002187 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002188 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002189 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2190 return;
2191 }
2192 if (content.needShape()) {
2193 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002194 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2195 SkIntToScalar( subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002196 shape.transform(matrix);
2197 content.setShape(shape);
2198 }
2199 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002200 return;
2201 }
2202
halcanarydaefa5b2014-08-27 13:00:54 -07002203 SkAutoTUnref<SkPDFObject> image(
2204 SkPDFCreateImageObject(*bitmap, subset, fEncoder));
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}
reed@google.com982cb872011-12-07 18:34:08 +00002212