blob: aa6b521887a04e1a9dbb109315376d1f2ef98863 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
9
vandebo@chromium.org238be8c2012-07-13 20:06:02 +000010#include "SkAnnotation.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000011#include "SkColor.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000012#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000013#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000014#include "SkDraw.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000015#include "SkFontHost.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000016#include "SkGlyphCache.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000017#include "SkPaint.h"
vandebo@chromium.orga5180862010-10-26 19:48:49 +000018#include "SkPath.h"
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +000019#include "SkPathOps.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000020#include "SkPDFFont.h"
vandebo@chromium.orgeb6c7592010-10-26 19:54:45 +000021#include "SkPDFFormXObject.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000022#include "SkPDFGraphicState.h"
23#include "SkPDFImage.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000024#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000025#include "SkPDFShader.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000026#include "SkPDFStream.h"
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +000027#include "SkPDFTypes.h"
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +000028#include "SkPDFUtils.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000029#include "SkRect.h"
scroggo@google.coma8e33a92013-11-08 18:02:53 +000030#include "SkRRect.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000031#include "SkString.h"
reed89443ab2014-06-27 11:34:19 -070032#include "SkSurface.h"
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000033#include "SkTextFormatParams.h"
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +000034#include "SkTemplates.h"
reed@google.comfed86bd2013-03-14 15:04:57 +000035#include "SkTypefacePriv.h"
edisonn@google.com6addb192013-04-02 15:33:08 +000036#include "SkTSet.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000037
edisonn@google.com73a7ea32013-11-11 20:55:15 +000038#define DPI_FOR_RASTER_SCALE_ONE 72
39
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000040// Utility functions
41
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000042static void emit_pdf_color(SkColor color, SkWStream* result) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000043 SkASSERT(SkColorGetA(color) == 0xFF); // We handle alpha elsewhere.
44 SkScalar colorMax = SkIntToScalar(0xFF);
vandebo@chromium.org094316b2011-03-04 03:15:13 +000045 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000046 SkScalarDiv(SkIntToScalar(SkColorGetR(color)), colorMax), result);
47 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000048 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000049 SkScalarDiv(SkIntToScalar(SkColorGetG(color)), colorMax), result);
50 result->writeText(" ");
vandebo@chromium.org094316b2011-03-04 03:15:13 +000051 SkPDFScalar::Append(
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +000052 SkScalarDiv(SkIntToScalar(SkColorGetB(color)), colorMax), result);
53 result->writeText(" ");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000054}
55
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000056static SkPaint calculate_text_paint(const SkPaint& paint) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000057 SkPaint result = paint;
58 if (result.isFakeBoldText()) {
59 SkScalar fakeBoldScale = SkScalarInterpFunc(result.getTextSize(),
60 kStdFakeBoldInterpKeys,
61 kStdFakeBoldInterpValues,
62 kStdFakeBoldInterpLength);
63 SkScalar width = SkScalarMul(result.getTextSize(), fakeBoldScale);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000064 if (result.getStyle() == SkPaint::kFill_Style) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000065 result.setStyle(SkPaint::kStrokeAndFill_Style);
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000066 } else {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000067 width += result.getStrokeWidth();
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000068 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000069 result.setStrokeWidth(width);
70 }
71 return result;
72}
73
74// Stolen from measure_text in SkDraw.cpp and then tweaked.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000075static void align_text(SkDrawCacheProc glyphCacheProc, const SkPaint& paint,
bungeman@google.com9a87cee2011-08-23 17:02:18 +000076 const uint16_t* glyphs, size_t len,
77 SkScalar* x, SkScalar* y) {
78 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000079 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000080 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000081
82 SkMatrix ident;
83 ident.reset();
bungeman@google.com532470f2013-01-22 19:25:14 +000084 SkAutoGlyphCache autoCache(paint, NULL, &ident);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000085 SkGlyphCache* cache = autoCache.getCache();
86
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +000087 const char* start = reinterpret_cast<const char*>(glyphs);
88 const char* stop = reinterpret_cast<const char*>(glyphs + len);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000089 SkFixed xAdv = 0, yAdv = 0;
90
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000091 // TODO(vandebo): This probably needs to take kerning into account.
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000092 while (start < stop) {
93 const SkGlyph& glyph = glyphCacheProc(cache, &start, 0, 0);
94 xAdv += glyph.fAdvanceX;
95 yAdv += glyph.fAdvanceY;
96 };
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000097 if (paint.getTextAlign() == SkPaint::kLeft_Align) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +000098 return;
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +000099 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000100
101 SkScalar xAdj = SkFixedToScalar(xAdv);
102 SkScalar yAdj = SkFixedToScalar(yAdv);
103 if (paint.getTextAlign() == SkPaint::kCenter_Align) {
104 xAdj = SkScalarHalf(xAdj);
105 yAdj = SkScalarHalf(yAdj);
106 }
107 *x = *x - xAdj;
108 *y = *y - yAdj;
109}
110
robertphillips@google.coma4662862013-11-21 14:24:16 +0000111static int max_glyphid_for_typeface(SkTypeface* typeface) {
reed@google.comfed86bd2013-03-14 15:04:57 +0000112 SkAutoResolveDefaultTypeface autoResolve(typeface);
113 typeface = autoResolve.get();
commit-bot@chromium.org6a4ba5b2013-07-17 21:55:08 +0000114 return typeface->countGlyphs() - 1;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000115}
116
117typedef SkAutoSTMalloc<128, uint16_t> SkGlyphStorage;
118
reed@google.comaec40662014-04-18 19:29:07 +0000119static int force_glyph_encoding(const SkPaint& paint, const void* text,
120 size_t len, SkGlyphStorage* storage,
121 uint16_t** glyphIDs) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000122 // Make sure we have a glyph id encoding.
123 if (paint.getTextEncoding() != SkPaint::kGlyphID_TextEncoding) {
reed@google.comaec40662014-04-18 19:29:07 +0000124 int numGlyphs = paint.textToGlyphs(text, len, NULL);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000125 storage->reset(numGlyphs);
126 paint.textToGlyphs(text, len, storage->get());
127 *glyphIDs = storage->get();
128 return numGlyphs;
129 }
130
131 // For user supplied glyph ids we need to validate them.
132 SkASSERT((len & 1) == 0);
reed@google.comaec40662014-04-18 19:29:07 +0000133 int numGlyphs = SkToInt(len / 2);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000134 const uint16_t* input =
135 reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
136
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) {
145 *glyphIDs = reinterpret_cast<uint16_t*>(const_cast<void*>((text)));
146 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) {
bsalomon@google.come97f0852011-06-17 13:10:25 +0000571 SkMatrix initialTransform;
572 initialTransform.reset();
commit-bot@chromium.org15a14052014-02-16 00:59:25 +0000573 SkISize size = SkISize::Make(info.width(), info.height());
bsalomon@google.come97f0852011-06-17 13:10:25 +0000574 return SkNEW_ARGS(SkPDFDevice, (size, size, initialTransform));
575}
576
577
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000578struct ContentEntry {
579 GraphicStateEntry fState;
580 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000581 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000582
583 // If the stack is too deep we could get Stack Overflow.
584 // So we manually destruct the object.
585 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000586 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000587 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000588 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000589 // When the destructor is called, fNext is NULL and exits.
590 delete val;
591 val = valNext;
592 }
593 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000594};
595
596// A helper class to automatically finish a ContentEntry at the end of a
597// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000598class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000599public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000600 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
601 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000602 : fDevice(device),
603 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000604 fXfermode(SkXfermode::kSrcOver_Mode),
605 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000606 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
607 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000608 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
609 const SkRegion& clipRegion, const SkMatrix& matrix,
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(clipStack, clipRegion, matrix, paint, hasText);
616 }
617
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000618 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000619 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000620 SkPath* shape = &fShape;
621 if (shape->isEmpty()) {
622 shape = NULL;
623 }
624 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000625 }
reed@google.comfc641d02012-09-20 17:52:20 +0000626 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000627 }
628
629 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000630
631 /* Returns true when we explicitly need the shape of the drawing. */
632 bool needShape() {
633 switch (fXfermode) {
634 case SkXfermode::kClear_Mode:
635 case SkXfermode::kSrc_Mode:
636 case SkXfermode::kSrcIn_Mode:
637 case SkXfermode::kSrcOut_Mode:
638 case SkXfermode::kDstIn_Mode:
639 case SkXfermode::kDstOut_Mode:
640 case SkXfermode::kSrcATop_Mode:
641 case SkXfermode::kDstATop_Mode:
642 case SkXfermode::kModulate_Mode:
643 return true;
644 default:
645 return false;
646 }
647 }
648
649 /* Returns true unless we only need the shape of the drawing. */
650 bool needSource() {
651 if (fXfermode == SkXfermode::kClear_Mode) {
652 return false;
653 }
654 return true;
655 }
656
657 /* If the shape is different than the alpha component of the content, then
658 * setShape should be called with the shape. In particular, images and
659 * devices have rectangular shape.
660 */
661 void setShape(const SkPath& shape) {
662 fShape = shape;
663 }
664
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000665private:
666 SkPDFDevice* fDevice;
667 ContentEntry* fContentEntry;
668 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000669 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000670 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000671
672 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
673 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000674 // Shape has to be flatten before we get here.
675 if (matrix.hasPerspective()) {
676 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000677 return;
678 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000679 if (paint.getXfermode()) {
680 paint.getXfermode()->asMode(&fXfermode);
681 }
682 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
683 matrix, paint, hasText,
684 &fDstFormXObject);
685 }
686};
687
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000688////////////////////////////////////////////////////////////////////////////////
689
reed89443ab2014-06-27 11:34:19 -0700690static inline SkImageInfo make_content_info(const SkISize& contentSize,
691 const SkMatrix* initialTransform) {
reed@google.com900ecf22014-02-20 20:55:37 +0000692 SkImageInfo info;
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000693 if (initialTransform) {
694 // Compute the size of the drawing area.
695 SkVector drawingSize;
696 SkMatrix inverse;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000697 drawingSize.set(SkIntToScalar(contentSize.fWidth),
698 SkIntToScalar(contentSize.fHeight));
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000699 if (!initialTransform->invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000700 // This shouldn't happen, initial transform should be invertible.
701 SkASSERT(false);
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000702 inverse.reset();
703 }
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000704 inverse.mapVectors(&drawingSize, 1);
705 SkISize size = SkSize::Make(drawingSize.fX, drawingSize.fY).toRound();
reed@google.com900ecf22014-02-20 20:55:37 +0000706 info = SkImageInfo::MakeUnknown(abs(size.fWidth), abs(size.fHeight));
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000707 } else {
reed@google.com900ecf22014-02-20 20:55:37 +0000708 info = SkImageInfo::MakeUnknown(abs(contentSize.fWidth),
709 abs(contentSize.fHeight));
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000710 }
reed89443ab2014-06-27 11:34:19 -0700711 return info;
reed@android.comf2b98d62010-12-20 18:26:13 +0000712}
713
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000714// TODO(vandebo) change pageSize to SkSize.
ctguil@chromium.org15261292011-04-29 17:54:16 +0000715SkPDFDevice::SkPDFDevice(const SkISize& pageSize, const SkISize& contentSize,
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000716 const SkMatrix& initialTransform)
reed89443ab2014-06-27 11:34:19 -0700717 : fPageSize(pageSize)
718 , fContentSize(contentSize)
719 , fLastContentEntry(NULL)
720 , fLastMarginContentEntry(NULL)
721 , fClipStack(NULL)
722 , fEncoder(NULL)
723 , fRasterDpi(72.0f)
724{
725 const SkImageInfo info = make_content_info(contentSize, &initialTransform);
726
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000727 // Just report that PDF does not supports perspective in the
728 // initial transform.
edisonn@google.comaa6c4d22013-09-19 17:36:47 +0000729 NOT_IMPLEMENTED(initialTransform.hasPerspective(), true);
730
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000731 // Skia generally uses the top left as the origin but PDF natively has the
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000732 // origin at the bottom left. This matrix corrects for that. But that only
733 // needs to be done once, we don't do it when layering.
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000734 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
735 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000736 fInitialTransform.preConcat(initialTransform);
reed89443ab2014-06-27 11:34:19 -0700737 fLegacyBitmap.setInfo(info);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000738
reed89443ab2014-06-27 11:34:19 -0700739 SkIRect existingClip = SkIRect::MakeWH(info.width(), info.height());
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000740 fExistingClipRegion.setRect(existingClip);
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000741 this->init();
742}
743
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000744// TODO(vandebo) change layerSize to SkSize.
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000745SkPDFDevice::SkPDFDevice(const SkISize& layerSize,
746 const SkClipStack& existingClipStack,
747 const SkRegion& existingClipRegion)
reed89443ab2014-06-27 11:34:19 -0700748 : fPageSize(layerSize)
749 , fContentSize(layerSize)
750 , fExistingClipStack(existingClipStack)
751 , fExistingClipRegion(existingClipRegion)
752 , fLastContentEntry(NULL)
753 , fLastMarginContentEntry(NULL)
754 , fClipStack(NULL)
755 , fEncoder(NULL)
756 , fRasterDpi(72.0f)
757{
vandebo@chromium.orga0c7edb2011-05-09 07:58:08 +0000758 fInitialTransform.reset();
reed89443ab2014-06-27 11:34:19 -0700759 fLegacyBitmap.setInfo(make_content_info(layerSize, NULL));
760
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000761 this->init();
762}
763
764SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000765 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000766}
767
768void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000769 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000770 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000771 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000772 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000773 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000774 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000775 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000776 if (fFontGlyphUsage.get() == NULL) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000777 fFontGlyphUsage.reset(new SkPDFGlyphSetMap());
778 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000779}
780
vandebo@chromium.org98594282011-07-25 22:34:12 +0000781void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000782 fGraphicStateResources.unrefAll();
783 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000784 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000785 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000786 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000787 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000788 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000789
vandebo@chromium.org98594282011-07-25 22:34:12 +0000790 if (clearFontUsage) {
791 fFontGlyphUsage->reset();
792 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000793}
794
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000795void SkPDFDevice::clear(SkColor color) {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000796 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000797 this->init();
798
799 SkPaint paint;
800 paint.setColor(color);
801 paint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000802 SkMatrix identity;
803 identity.reset();
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000804 ScopedContentEntry content(this, &fExistingClipStack, fExistingClipRegion,
805 identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000806 internalDrawPaint(paint, content.entry());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000807}
808
809void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000810 SkPaint newPaint = paint;
811 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000812 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000813 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000814}
815
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000816void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
817 ContentEntry* contentEntry) {
818 if (!contentEntry) {
819 return;
820 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000821 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
822 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000823 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000824 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000825 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000826 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000827 inverse.mapRect(&bbox);
828
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000829 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000830 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000831 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000832}
833
834void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
835 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000836 const SkPaint& passedPaint) {
837 if (count == 0) {
838 return;
839 }
840
epoger@google.comb58772f2013-03-08 09:09:10 +0000841 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
842 return;
843 }
844
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000845 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
846 // We only use this when there's a path effect because of the overhead
847 // of multiple calls to setUpContentEntry it causes.
848 if (passedPaint.getPathEffect()) {
849 if (d.fClip->isEmpty()) {
850 return;
851 }
852 SkDraw pointDraw(d);
853 pointDraw.fDevice = this;
854 pointDraw.drawPoints(mode, count, points, passedPaint, true);
855 return;
856 }
857
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000858 const SkPaint* paint = &passedPaint;
859 SkPaint modifiedPaint;
860
861 if (mode == SkCanvas::kPoints_PointMode &&
862 paint->getStrokeCap() != SkPaint::kRound_Cap) {
863 modifiedPaint = *paint;
864 paint = &modifiedPaint;
865 if (paint->getStrokeWidth()) {
866 // PDF won't draw a single point with square/butt caps because the
867 // orientation is ambiguous. Draw a rectangle instead.
868 modifiedPaint.setStyle(SkPaint::kFill_Style);
869 SkScalar strokeWidth = paint->getStrokeWidth();
870 SkScalar halfStroke = SkScalarHalf(strokeWidth);
871 for (size_t i = 0; i < count; i++) {
872 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
873 r.inset(-halfStroke, -halfStroke);
874 drawRect(d, r, modifiedPaint);
875 }
876 return;
877 } else {
878 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
879 }
880 }
881
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000882 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000883 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000884 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000885 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000886
887 switch (mode) {
888 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000889 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000890 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000891 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000892 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000893 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000894 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000895 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000896 break;
897 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000898 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000899 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000900 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000901 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000902 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000903 &content.entry()->fContent);
904 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000905 }
906 break;
907 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000908 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
909 for (size_t i = 0; i < count; i++) {
910 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000911 &content.entry()->fContent);
912 SkPDFUtils::ClosePath(&content.entry()->fContent);
913 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000914 }
915 break;
916 default:
917 SkASSERT(false);
918 }
919}
920
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000921void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000922 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000923 SkRect r = rect;
924 r.sort();
925
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000926 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000927 if (d.fClip->isEmpty()) {
928 return;
929 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000930 SkPath path;
931 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000932 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000933 return;
934 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000935
epoger@google.comb58772f2013-03-08 09:09:10 +0000936 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000937 return;
938 }
939
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000940 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000941 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000942 return;
943 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000944 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000945 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000946 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000947}
948
reed89443ab2014-06-27 11:34:19 -0700949void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000950 SkPath path;
951 path.addRRect(rrect);
952 this->drawPath(draw, path, paint, NULL, true);
953}
954
reed89443ab2014-06-27 11:34:19 -0700955void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
956 SkPath path;
957 path.addOval(oval);
958 this->drawPath(draw, path, paint, NULL, true);
959}
960
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000961void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000962 const SkPaint& paint, const SkMatrix* prePathMatrix,
963 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000964 SkPath modifiedPath;
965 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
966
967 SkMatrix matrix = *d.fMatrix;
968 if (prePathMatrix) {
969 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
970 if (!pathIsMutable) {
971 pathPtr = &modifiedPath;
972 pathIsMutable = true;
973 }
974 origPath.transform(*prePathMatrix, pathPtr);
975 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000976 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000977 }
978 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000979
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000980 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000981 if (d.fClip->isEmpty()) {
982 return;
983 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000984 if (!pathIsMutable) {
985 pathPtr = &modifiedPath;
986 pathIsMutable = true;
987 }
988 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000989
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000990 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000991 noEffectPaint.setPathEffect(NULL);
992 if (fill) {
993 noEffectPaint.setStyle(SkPaint::kFill_Style);
994 } else {
995 noEffectPaint.setStyle(SkPaint::kStroke_Style);
996 noEffectPaint.setStrokeWidth(0);
997 }
998 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000999 return;
1000 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001001
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001002#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001003 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001004 return;
1005 }
1006#endif
1007
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001008 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001009 return;
1010 }
1011
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001012 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001013 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001014 return;
1015 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +00001016 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
1017 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +00001018 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001019 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001020}
1021
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001022void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
1023 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +00001024 const SkPaint& paint,
1025 SkCanvas::DrawBitmapRectFlags flags) {
1026 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001027 SkMatrix matrix;
1028 SkRect bitmapBounds, tmpSrc, tmpDst;
1029 SkBitmap tmpBitmap;
1030
1031 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
1032
1033 // Compute matrix from the two rectangles
1034 if (src) {
1035 tmpSrc = *src;
1036 } else {
1037 tmpSrc = bitmapBounds;
1038 }
1039 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1040
1041 const SkBitmap* bitmapPtr = &bitmap;
1042
1043 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
1044 // needed (if the src was clipped). No check needed if src==null.
1045 if (src) {
1046 if (!bitmapBounds.contains(*src)) {
1047 if (!tmpSrc.intersect(bitmapBounds)) {
1048 return; // nothing to draw
1049 }
1050 // recompute dst, based on the smaller tmpSrc
1051 matrix.mapRect(&tmpDst, tmpSrc);
1052 }
1053
1054 // since we may need to clamp to the borders of the src rect within
1055 // the bitmap, we extract a subset.
1056 // TODO: make sure this is handled in drawBitmap and remove from here.
1057 SkIRect srcIR;
1058 tmpSrc.roundOut(&srcIR);
1059 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1060 return;
1061 }
1062 bitmapPtr = &tmpBitmap;
1063
1064 // Since we did an extract, we need to adjust the matrix accordingly
1065 SkScalar dx = 0, dy = 0;
1066 if (srcIR.fLeft > 0) {
1067 dx = SkIntToScalar(srcIR.fLeft);
1068 }
1069 if (srcIR.fTop > 0) {
1070 dy = SkIntToScalar(srcIR.fTop);
1071 }
1072 if (dx || dy) {
1073 matrix.preTranslate(dx, dy);
1074 }
1075 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001076 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001077}
1078
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001079void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001080 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001081 if (d.fClip->isEmpty()) {
1082 return;
1083 }
1084
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001085 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001086 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001087 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1088 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001089}
1090
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001091void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001092 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001093 if (d.fClip->isEmpty()) {
1094 return;
1095 }
1096
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001097 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001098 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001099 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1100 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001101}
1102
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001103void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001104 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001105 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1106 if (paint.getMaskFilter() != NULL) {
1107 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1108 // making text unreadable (e.g. same text twice when using CSS shadows).
1109 return;
1110 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001111 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001112 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001113 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001114 return;
1115 }
1116
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001117 SkGlyphStorage storage(0);
1118 uint16_t* glyphIDs = NULL;
reed@google.comaec40662014-04-18 19:29:07 +00001119 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001120 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001121
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001122 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001123 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001124 content.entry()->fContent.writeText("BT\n");
1125 set_text_transform(x, y, textPaint.getTextSkewX(),
1126 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001127 int consumedGlyphCount = 0;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001128 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001129 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1130 SkPDFFont* font = content.entry()->fState.fFont;
reed@google.comaec40662014-04-18 19:29:07 +00001131 int availableGlyphs =
vandebo@chromium.org01294102011-02-28 19:52:18 +00001132 font->glyphsToPDFFontEncoding(glyphIDs + consumedGlyphCount,
1133 numGlyphs - consumedGlyphCount);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001134 fFontGlyphUsage->noteGlyphUsage(font, glyphIDs + consumedGlyphCount,
1135 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001136 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001137 SkPDFString::FormatString(glyphIDs + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001138 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001139 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001140 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001141 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001142 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001143 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001144}
1145
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001146void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001147 const SkScalar pos[], SkScalar constY,
1148 int scalarsPerPos, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001149 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1150 if (paint.getMaskFilter() != NULL) {
1151 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1152 // making text unreadable (e.g. same text twice when using CSS shadows).
1153 return;
1154 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001155 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001156 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001157 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001158 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001159 return;
1160 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001161
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001162 SkGlyphStorage storage(0);
1163 uint16_t* glyphIDs = NULL;
1164 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage,
1165 &glyphIDs);
1166 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001167
1168 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001169 content.entry()->fContent.writeText("BT\n");
1170 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001171 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001172 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001173 uint16_t encodedValue = glyphIDs[i];
1174 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001175 updateFont(textPaint, glyphIDs[i], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001176 i--;
1177 continue;
1178 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001179 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001180 SkScalar x = pos[i * scalarsPerPos];
1181 SkScalar y = scalarsPerPos == 1 ? constY : pos[i * scalarsPerPos + 1];
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001182 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001183 set_text_transform(x, y, textPaint.getTextSkewX(),
1184 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001185 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001186 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001187 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001188 content.entry()->fContent.writeText(encodedString.c_str());
1189 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001190 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001191 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001192}
1193
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001194void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001195 const SkPath& path, const SkMatrix* matrix,
1196 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001197 if (d.fClip->isEmpty()) {
1198 return;
1199 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001200 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001201}
1202
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001203void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001204 int vertexCount, const SkPoint verts[],
1205 const SkPoint texs[], const SkColor colors[],
1206 SkXfermode* xmode, const uint16_t indices[],
1207 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001208 if (d.fClip->isEmpty()) {
1209 return;
1210 }
reed@google.com85e143c2013-12-30 15:51:25 +00001211 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001212}
1213
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001214void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1215 int x, int y, const SkPaint& paint) {
commit-bot@chromium.org3da3b622014-03-13 19:38:10 +00001216 // our onCreateDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001217 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001218 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001219 return;
1220 }
1221
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001222 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001223 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001224 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001225 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001226 return;
1227 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001228 if (content.needShape()) {
1229 SkPath shape;
1230 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001231 SkIntToScalar(device->width()),
1232 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001233 content.setShape(shape);
1234 }
1235 if (!content.needSource()) {
1236 return;
1237 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001238
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001239 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1240 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001241 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001242
1243 // Merge glyph sets from the drawn device.
1244 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001245}
1246
reed89443ab2014-06-27 11:34:19 -07001247SkImageInfo SkPDFDevice::imageInfo() const {
1248 return fLegacyBitmap.info();
1249}
1250
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001251void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1252 INHERITED::onAttachToCanvas(canvas);
1253
1254 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1255 fClipStack = canvas->getClipStack();
1256}
1257
1258void SkPDFDevice::onDetachFromCanvas() {
1259 INHERITED::onDetachFromCanvas();
1260
1261 fClipStack = NULL;
1262}
1263
reed3716fd02014-09-21 09:39:55 -07001264SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1265 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001266}
1267
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001268ContentEntry* SkPDFDevice::getLastContentEntry() {
1269 if (fDrawingArea == kContent_DrawingArea) {
1270 return fLastContentEntry;
1271 } else {
1272 return fLastMarginContentEntry;
1273 }
1274}
1275
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001276SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001277 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001278 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001279 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001280 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001281 }
1282}
1283
1284void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1285 if (fDrawingArea == kContent_DrawingArea) {
1286 fLastContentEntry = contentEntry;
1287 } else {
1288 fLastMarginContentEntry = contentEntry;
1289 }
1290}
1291
1292void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001293 // A ScopedContentEntry only exists during the course of a draw call, so
1294 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001295 fDrawingArea = drawingArea;
1296}
1297
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001298SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001299 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001300 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001301
1302 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001303 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001304 fResourceDict->insertResourceAsReference(
1305 SkPDFResourceDict::kExtGState_ResourceType,
1306 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001307 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001308 }
1309
1310 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001311 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001312 fResourceDict->insertResourceAsReference(
1313 SkPDFResourceDict::kXObject_ResourceType,
1314 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001315 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001316 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001317
1318 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001319 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001320 fResourceDict->insertResourceAsReference(
1321 SkPDFResourceDict::kFont_ResourceType,
1322 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001323 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001324 }
1325
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001326 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001327 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001328 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001329 fResourceDict->insertResourceAsReference(
1330 SkPDFResourceDict::kPattern_ResourceType,
1331 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001332 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001333 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001334 }
1335 return fResourceDict;
1336}
1337
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001338const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1339 return fFontResources;
1340}
1341
reed@google.com2a006c12012-09-19 17:05:55 +00001342SkPDFArray* SkPDFDevice::copyMediaBox() const {
1343 // should this be a singleton?
1344 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001345
reed@google.com2a006c12012-09-19 17:05:55 +00001346 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001347 mediaBox->reserve(4);
1348 mediaBox->append(zero.get());
1349 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001350 mediaBox->appendInt(fPageSize.fWidth);
1351 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001352 return mediaBox;
1353}
1354
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001355SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001356 SkMemoryStream* result = new SkMemoryStream;
1357 result->setData(this->copyContentToData())->unref();
1358 return result;
1359}
1360
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001361void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1362 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001363 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1364 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001365 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001366 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001367 SkPoint translation;
1368 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001369 translation.negate();
1370 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1371 translation);
1372 gsState.updateMatrix(entry->fState.fMatrix);
1373 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001374
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001375 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001376 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001377 entry = entry->fNext.get();
1378 }
1379 gsState.drainStack();
1380}
1381
reed@google.com5667afc2011-06-27 14:42:15 +00001382SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001383 SkDynamicMemoryWStream data;
1384 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1385 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001386 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001387
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001388 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1389 // colors the contentArea white before it starts drawing into it and
1390 // that currently acts as our clip.
1391 // Also, think about adding a transform here (or assume that the values
1392 // sent across account for that)
1393 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001394
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001395 // If the content area is the entire page, then we don't need to clip
1396 // the content area (PDF area clips to the page size). Otherwise,
1397 // we have to clip to the content area; we've already applied the
1398 // initial transform, so just clip to the device size.
1399 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001400 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1401 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001402 emit_clip(NULL, &r, &data);
1403 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001404
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001405 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001406
reed@google.com5667afc2011-06-27 14:42:15 +00001407 // potentially we could cache this SkData, and only rebuild it if we
1408 // see that our state has changed.
1409 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001410}
1411
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001412#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001413/* Draws an inverse filled path by using Path Ops to compute the positive
1414 * inverse using the current clip as the inverse bounds.
1415 * Return true if this was an inverse path and was properly handled,
1416 * otherwise returns false and the normal drawing routine should continue,
1417 * either as a (incorrect) fallback or because the path was not inverse
1418 * in the first place.
1419 */
1420bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001421 const SkPaint& paint, bool pathIsMutable,
1422 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001423 if (!origPath.isInverseFillType()) {
1424 return false;
1425 }
1426
1427 if (d.fClip->isEmpty()) {
1428 return false;
1429 }
1430
1431 SkPath modifiedPath;
1432 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1433 SkPaint noInversePaint(paint);
1434
1435 // Merge stroking operations into final path.
1436 if (SkPaint::kStroke_Style == paint.getStyle() ||
1437 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1438 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1439 if (doFillPath) {
1440 noInversePaint.setStyle(SkPaint::kFill_Style);
1441 noInversePaint.setStrokeWidth(0);
1442 pathPtr = &modifiedPath;
1443 } else {
1444 // To be consistent with the raster output, hairline strokes
1445 // are rendered as non-inverted.
1446 modifiedPath.toggleInverseFillType();
1447 drawPath(d, modifiedPath, paint, NULL, true);
1448 return true;
1449 }
1450 }
1451
1452 // Get bounds of clip in current transform space
1453 // (clip bounds are given in device space).
1454 SkRect bounds;
1455 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001456 SkMatrix totalMatrix = *d.fMatrix;
1457 if (prePathMatrix) {
1458 totalMatrix.preConcat(*prePathMatrix);
1459 }
1460 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001461 return false;
1462 }
1463 bounds.set(d.fClip->getBounds());
1464 transformInverse.mapRect(&bounds);
1465
1466 // Extend the bounds by the line width (plus some padding)
1467 // so the edge doesn't cause a visible stroke.
1468 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1469 paint.getStrokeWidth() + SK_Scalar1);
1470
1471 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1472 return false;
1473 }
1474
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001475 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001476 return true;
1477}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001478#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001479
epoger@google.comb58772f2013-03-08 09:09:10 +00001480bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1481 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001482 SkAnnotation* annotationInfo = p.getAnnotation();
1483 if (!annotationInfo) {
1484 return false;
1485 }
1486 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001487 if (urlData) {
1488 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001489 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001490 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001491 SkData* linkToName = annotationInfo->find(
1492 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001493 if (linkToName) {
1494 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001495 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001496 }
1497 return false;
1498}
1499
1500bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1501 const SkMatrix& matrix,
1502 const SkPaint& paint) {
1503 SkAnnotation* annotationInfo = paint.getAnnotation();
1504 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001505 return false;
1506 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001507 SkData* nameData = annotationInfo->find(
1508 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001509 if (nameData) {
1510 for (size_t i = 0; i < count; i++) {
1511 defineNamedDestination(nameData, points[i], matrix);
1512 }
reed@google.com44699382013-10-31 17:28:30 +00001513 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001514 }
1515 return false;
1516}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001517
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001518SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1519 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001520 SkMatrix transform = matrix;
1521 transform.postConcat(fInitialTransform);
1522 SkRect translatedRect;
1523 transform.mapRect(&translatedRect, r);
1524
reed@google.com2a006c12012-09-19 17:05:55 +00001525 if (NULL == fAnnotations) {
1526 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001527 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001528 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001529 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001530 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001531
epoger@google.comb58772f2013-03-08 09:09:10 +00001532 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001533 border->reserve(3);
1534 border->appendInt(0); // Horizontal corner radius.
1535 border->appendInt(0); // Vertical corner radius.
1536 border->appendInt(0); // Width, 0 = no border.
1537 annotation->insert("Border", border.get());
1538
epoger@google.comb58772f2013-03-08 09:09:10 +00001539 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001540 rect->reserve(4);
1541 rect->appendScalar(translatedRect.fLeft);
1542 rect->appendScalar(translatedRect.fTop);
1543 rect->appendScalar(translatedRect.fRight);
1544 rect->appendScalar(translatedRect.fBottom);
1545 annotation->insert("Rect", rect.get());
1546
epoger@google.comb58772f2013-03-08 09:09:10 +00001547 return annotation;
1548}
epoger@google.com1cad8982013-03-06 00:05:13 +00001549
epoger@google.comb58772f2013-03-08 09:09:10 +00001550void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1551 const SkMatrix& matrix) {
1552 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1553
1554 SkString url(static_cast<const char *>(urlData->data()),
1555 urlData->size() - 1);
1556 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1557 action->insertName("S", "URI");
1558 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1559 annotation->insert("A", action.get());
1560}
1561
1562void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1563 const SkMatrix& matrix) {
1564 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1565 SkString name(static_cast<const char *>(nameData->data()),
1566 nameData->size() - 1);
1567 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1568}
1569
1570struct NamedDestination {
1571 const SkData* nameData;
1572 SkPoint point;
1573
1574 NamedDestination(const SkData* nameData, const SkPoint& point)
1575 : nameData(nameData), point(point) {
1576 nameData->ref();
1577 }
1578
1579 ~NamedDestination() {
1580 nameData->unref();
1581 }
1582};
1583
1584void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1585 const SkMatrix& matrix) {
1586 SkMatrix transform = matrix;
1587 transform.postConcat(fInitialTransform);
1588 SkPoint translatedPoint;
1589 transform.mapXY(point.x(), point.y(), &translatedPoint);
1590 fNamedDestinations.push(
1591 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1592}
1593
1594void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1595 int nDest = fNamedDestinations.count();
1596 for (int i = 0; i < nDest; i++) {
1597 NamedDestination* dest = fNamedDestinations[i];
1598 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1599 pdfDest->reserve(5);
1600 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1601 pdfDest->appendName("XYZ");
1602 pdfDest->appendScalar(dest->point.x());
1603 pdfDest->appendScalar(dest->point.y());
1604 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001605 dict->insert(static_cast<const char *>(dest->nameData->data()),
1606 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001607 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001608}
1609
reed@google.comfc641d02012-09-20 17:52:20 +00001610SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1611 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001612 // We always draw the form xobjects that we create back into the device, so
1613 // we simply preserve the font usage instead of pulling it out and merging
1614 // it back in later.
1615 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001616 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001617 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001618}
1619
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001620void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1621 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001622 const SkClipStack* clipStack,
1623 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001624 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001625 bool invertClip) {
1626 if (clipRegion.isEmpty() && !invertClip) {
1627 return;
1628 }
1629
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001630 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1631 SkPDFGraphicState::GetSMaskGraphicState(
1632 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1633
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001634 SkMatrix identity;
1635 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001636 SkPaint paint;
1637 paint.setXfermodeMode(mode);
1638 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001639 if (!content.entry()) {
1640 return;
1641 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001642 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001643 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001644 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001645
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001646 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001647 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001648 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001649}
1650
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001651ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1652 const SkRegion& clipRegion,
1653 const SkMatrix& matrix,
1654 const SkPaint& paint,
1655 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001656 SkPDFFormXObject** dst) {
1657 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001658 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001659 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001660 }
1661
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001662 // The clip stack can come from an SkDraw where it is technically optional.
1663 SkClipStack synthesizedClipStack;
1664 if (clipStack == NULL) {
1665 if (clipRegion == fExistingClipRegion) {
1666 clipStack = &fExistingClipStack;
1667 } else {
1668 // GraphicStackState::updateClip expects the clip stack to have
1669 // fExistingClip as a prefix, so start there, then set the clip
1670 // to the passed region.
1671 synthesizedClipStack = fExistingClipStack;
1672 SkPath clipPath;
1673 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001674 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1675 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001676 clipStack = &synthesizedClipStack;
1677 }
1678 }
1679
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001680 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1681 if (paint.getXfermode()) {
1682 paint.getXfermode()->asMode(&xfermode);
1683 }
1684
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001685 // For the following modes, we want to handle source and destination
1686 // separately, so make an object of what's already there.
1687 if (xfermode == SkXfermode::kClear_Mode ||
1688 xfermode == SkXfermode::kSrc_Mode ||
1689 xfermode == SkXfermode::kSrcIn_Mode ||
1690 xfermode == SkXfermode::kDstIn_Mode ||
1691 xfermode == SkXfermode::kSrcOut_Mode ||
1692 xfermode == SkXfermode::kDstOut_Mode ||
1693 xfermode == SkXfermode::kSrcATop_Mode ||
1694 xfermode == SkXfermode::kDstATop_Mode ||
1695 xfermode == SkXfermode::kModulate_Mode) {
1696 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001697 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001698 SkASSERT(isContentEmpty());
1699 } else if (xfermode != SkXfermode::kSrc_Mode &&
1700 xfermode != SkXfermode::kSrcOut_Mode) {
1701 // Except for Src and SrcOut, if there isn't anything already there,
1702 // then we're done.
1703 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001704 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001705 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001706 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001707 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001708
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001709 // Dst xfer mode doesn't draw source at all.
1710 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001711 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001712 }
1713
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001714 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001715 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001716
1717 ContentEntry* lastContentEntry = getLastContentEntry();
1718 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1719 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001720 } else {
1721 newEntry.reset(new ContentEntry);
1722 entry = newEntry.get();
1723 }
1724
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001725 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001726 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001727 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1728 entry->fState.compareInitialState(lastContentEntry->fState)) {
1729 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001730 }
1731
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001732 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001733 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001734 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001735 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001736 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001737 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001738 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001739 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001740 lastContentEntry->fNext.reset(entry);
1741 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001742 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001743 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001744 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001745}
1746
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001747void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001748 SkPDFFormXObject* dst,
1749 SkPath* shape) {
1750 if (xfermode != SkXfermode::kClear_Mode &&
1751 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001752 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001753 xfermode != SkXfermode::kSrcIn_Mode &&
1754 xfermode != SkXfermode::kDstIn_Mode &&
1755 xfermode != SkXfermode::kSrcOut_Mode &&
1756 xfermode != SkXfermode::kDstOut_Mode &&
1757 xfermode != SkXfermode::kSrcATop_Mode &&
1758 xfermode != SkXfermode::kDstATop_Mode &&
1759 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001760 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001761 return;
1762 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001763 if (xfermode == SkXfermode::kDstOver_Mode) {
1764 SkASSERT(!dst);
1765 ContentEntry* firstContentEntry = getContentEntries()->get();
1766 if (firstContentEntry->fContent.getOffset() == 0) {
1767 // For DstOver, an empty content entry was inserted before the rest
1768 // of the content entries. If nothing was drawn, it needs to be
1769 // removed.
1770 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1771 contentEntries->reset(firstContentEntry->fNext.detach());
1772 }
1773 return;
1774 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001775 if (!dst) {
1776 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1777 xfermode == SkXfermode::kSrcOut_Mode);
1778 return;
1779 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001780
1781 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001782 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001783 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001784 // Changing the current content into a form-xobject will destroy the clip
1785 // objects which is fine since the xobject will already be clipped. However
1786 // if source has shape, we need to clip it too, so a copy of the clip is
1787 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001788 SkClipStack clipStack = contentEntries->fState.fClipStack;
1789 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001790
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001791 SkMatrix identity;
1792 identity.reset();
1793 SkPaint stockPaint;
1794
reed@google.comfc641d02012-09-20 17:52:20 +00001795 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001796 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001797 // If nothing was drawn and there's no shape, then the draw was a
1798 // no-op, but dst needs to be restored for that to be true.
1799 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1800 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1801 // reduces to Dst.
1802 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1803 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001804 ScopedContentEntry content(this, &fExistingClipStack,
1805 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001806 stockPaint);
1807 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1808 &content.entry()->fContent);
1809 return;
1810 } else {
1811 xfermode = SkXfermode::kClear_Mode;
1812 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001813 } else {
1814 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001815 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001816 }
1817
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001818 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1819 // without alpha.
1820 if (xfermode == SkXfermode::kSrcATop_Mode) {
1821 // TODO(vandebo): In order to properly support SrcATop we have to track
1822 // the shape of what's been drawn at all times. It's the intersection of
1823 // the non-transparent parts of the device and the outlines (shape) of
1824 // all images and devices drawn.
1825 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001826 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001827 SkXfermode::kSrcOver_Mode, true);
1828 } else {
1829 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1830 SkPDFFormXObject* dstMask = srcFormXObject.get();
1831 if (shape != NULL) {
1832 // Draw shape into a form-xobject.
1833 SkDraw d;
1834 d.fMatrix = &identity;
1835 d.fClip = &clipRegion;
1836 d.fClipStack = &clipStack;
1837 SkPaint filledPaint;
1838 filledPaint.setColor(SK_ColorBLACK);
1839 filledPaint.setStyle(SkPaint::kFill_Style);
1840 this->drawPath(d, *shape, filledPaint, NULL, true);
1841
1842 dstMaskStorage.reset(createFormXObjectFromDevice());
1843 dstMask = dstMaskStorage.get();
1844 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001845 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1846 &fExistingClipStack, fExistingClipRegion,
1847 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001848 }
1849
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001850 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001851 return;
1852 } else if (xfermode == SkXfermode::kSrc_Mode ||
1853 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001854 ScopedContentEntry content(this, &fExistingClipStack,
1855 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001856 if (content.entry()) {
1857 SkPDFUtils::DrawFormXObject(
1858 this->addXObjectResource(srcFormXObject.get()),
1859 &content.entry()->fContent);
1860 }
1861 if (xfermode == SkXfermode::kSrc_Mode) {
1862 return;
1863 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001864 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001865 ScopedContentEntry content(this, &fExistingClipStack,
1866 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001867 if (content.entry()) {
1868 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1869 &content.entry()->fContent);
1870 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001871 }
1872
1873 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1874 xfermode == SkXfermode::kDstIn_Mode ||
1875 xfermode == SkXfermode::kSrcOut_Mode ||
1876 xfermode == SkXfermode::kDstOut_Mode ||
1877 xfermode == SkXfermode::kSrcATop_Mode ||
1878 xfermode == SkXfermode::kDstATop_Mode ||
1879 xfermode == SkXfermode::kModulate_Mode);
1880
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001881 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001882 xfermode == SkXfermode::kSrcOut_Mode ||
1883 xfermode == SkXfermode::kSrcATop_Mode) {
1884 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001885 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001886 SkXfermode::kSrcOver_Mode,
1887 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001888 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001889 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1890 if (xfermode == SkXfermode::kModulate_Mode) {
1891 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001892 dst, &fExistingClipStack,
1893 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001894 SkXfermode::kSrcOver_Mode, false);
1895 mode = SkXfermode::kMultiply_Mode;
1896 }
1897 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001898 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001899 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001900 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001901}
1902
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001903bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001904 ContentEntry* contentEntries = getContentEntries()->get();
1905 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1906 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001907 return true;
1908 }
1909 return false;
1910}
1911
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001912void SkPDFDevice::populateGraphicStateEntryFromPaint(
1913 const SkMatrix& matrix,
1914 const SkClipStack& clipStack,
1915 const SkRegion& clipRegion,
1916 const SkPaint& paint,
1917 bool hasText,
1918 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001919 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001920 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1921 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001922
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001923 entry->fMatrix = matrix;
1924 entry->fClipStack = clipStack;
1925 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001926 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1927 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001928
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001929 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001930 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001931 const SkShader* shader = paint.getShader();
1932 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001933 if (shader) {
1934 // PDF positions patterns relative to the initial transform, so
1935 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001936 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001937 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001938
1939 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001940 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001941 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001942
1943 // We need to apply the initial transform to bounds in order to get
1944 // bounds in a consistent coordinate system.
1945 SkRect boundsTemp;
1946 boundsTemp.set(bounds);
1947 fInitialTransform.mapRect(&boundsTemp);
1948 boundsTemp.roundOut(&bounds);
1949
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001950 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001951
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001952 if (pdfShader.get()) {
1953 // pdfShader has been canonicalized so we can directly compare
1954 // pointers.
1955 int resourceIndex = fShaderResources.find(pdfShader.get());
1956 if (resourceIndex < 0) {
1957 resourceIndex = fShaderResources.count();
1958 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001959 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001960 }
1961 entry->fShaderIndex = resourceIndex;
1962 } else {
1963 // A color shader is treated as an invalid shader so we don't have
1964 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001965 SkShader::GradientInfo gradientInfo;
1966 SkColor gradientColor;
1967 gradientInfo.fColors = &gradientColor;
1968 gradientInfo.fColorOffsets = NULL;
1969 gradientInfo.fColorCount = 1;
1970 if (shader->asAGradient(&gradientInfo) ==
1971 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001972 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1973 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001974 }
1975 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001976 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001977
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001978 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001979 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001980 newGraphicState.reset(
1981 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001982 } else {
1983 SkPaint newPaint = paint;
1984 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001985 newGraphicState.reset(
1986 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001987 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001988 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001989 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001990
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001991 if (hasText) {
1992 entry->fTextScaleX = paint.getTextScaleX();
1993 entry->fTextFill = paint.getStyle();
1994 } else {
1995 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001996 }
1997}
1998
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001999int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2000 // Assumes that gs has been canonicalized (so we can directly compare
2001 // pointers).
2002 int result = fGraphicStateResources.find(gs);
2003 if (result < 0) {
2004 result = fGraphicStateResources.count();
2005 fGraphicStateResources.push(gs);
2006 gs->ref();
2007 }
2008 return result;
2009}
2010
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002011int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2012 // Assumes that xobject has been canonicalized (so we can directly compare
2013 // pointers).
2014 int result = fXObjectResources.find(xObject);
2015 if (result < 0) {
2016 result = fXObjectResources.count();
2017 fXObjectResources.push(xObject);
2018 xObject->ref();
2019 }
2020 return result;
2021}
2022
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002023void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2024 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002025 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002026 if (contentEntry->fState.fFont == NULL ||
2027 contentEntry->fState.fTextSize != paint.getTextSize() ||
2028 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002029 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002030 contentEntry->fContent.writeText("/");
2031 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2032 SkPDFResourceDict::kFont_ResourceType,
2033 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002034 contentEntry->fContent.writeText(" ");
2035 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2036 contentEntry->fContent.writeText(" Tf\n");
2037 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002038 }
2039}
2040
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002041int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002042 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2043 glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002044 int resourceIndex = fFontResources.find(newFont.get());
2045 if (resourceIndex < 0) {
2046 resourceIndex = fFontResources.count();
2047 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002048 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002049 }
2050 return resourceIndex;
2051}
2052
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002053void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002054 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002055 const SkRegion& origClipRegion,
2056 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002057 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002058 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002059 SkMatrix matrix = origMatrix;
2060 SkRegion perspectiveBounds;
2061 const SkRegion* clipRegion = &origClipRegion;
2062 SkBitmap perspectiveBitmap;
2063 const SkBitmap* bitmap = &origBitmap;
2064 SkBitmap tmpSubsetBitmap;
2065
2066 // Rasterize the bitmap using perspective in a new bitmap.
2067 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002068 if (fRasterDpi == 0) {
2069 return;
2070 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002071 SkBitmap* subsetBitmap;
2072 if (srcRect) {
2073 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2074 return;
2075 }
2076 subsetBitmap = &tmpSubsetBitmap;
2077 } else {
2078 subsetBitmap = &tmpSubsetBitmap;
2079 *subsetBitmap = origBitmap;
2080 }
2081 srcRect = NULL;
2082
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002083 // Transform the bitmap in the new space, without taking into
2084 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002085 SkPath perspectiveOutline;
2086 perspectiveOutline.addRect(
2087 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2088 SkIntToScalar(subsetBitmap->height())));
2089 perspectiveOutline.transform(origMatrix);
2090
2091 // TODO(edisonn): perf - use current clip too.
2092 // Retrieve the bounds of the new shape.
2093 SkRect bounds = perspectiveOutline.getBounds();
2094
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002095 // Transform the bitmap in the new space, taking into
2096 // account the initial transform.
2097 SkMatrix total = origMatrix;
2098 total.postConcat(fInitialTransform);
2099 total.postScale(SkIntToScalar(fRasterDpi) /
2100 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2101 SkIntToScalar(fRasterDpi) /
2102 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2103 SkPath physicalPerspectiveOutline;
2104 physicalPerspectiveOutline.addRect(
2105 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2106 SkIntToScalar(subsetBitmap->height())));
2107 physicalPerspectiveOutline.transform(total);
2108
2109 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2110 bounds.width();
2111 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2112 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002113
2114 // TODO(edisonn): A better approach would be to use a bitmap shader
2115 // (in clamp mode) and draw a rect over the entire bounding box. Then
2116 // intersect perspectiveOutline to the clip. That will avoid introducing
2117 // alpha to the image while still giving good behavior at the edge of
2118 // the image. Avoiding alpha will reduce the pdf size and generation
2119 // CPU time some.
2120
reed@google.com9ebcac52014-01-24 18:53:42 +00002121 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2122 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002123 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002124 return;
2125 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002126 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2127
reed89443ab2014-06-27 11:34:19 -07002128 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002129
2130 SkScalar deltaX = bounds.left();
2131 SkScalar deltaY = bounds.top();
2132
2133 SkMatrix offsetMatrix = origMatrix;
2134 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002135 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002136
2137 // Translate the draw in the new canvas, so we perfectly fit the
2138 // shape in the bitmap.
2139 canvas.setMatrix(offsetMatrix);
2140
2141 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2142
2143 // Make sure the final bits are in the bitmap.
2144 canvas.flush();
2145
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002146 // In the new space, we use the identity matrix translated
2147 // and scaled to reflect DPI.
2148 matrix.setScale(1 / scaleX, 1 / scaleY);
2149 matrix.postTranslate(deltaX, deltaY);
2150
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002151 perspectiveBounds.setRect(
2152 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2153 SkScalarFloorToInt(bounds.y()),
2154 SkScalarCeilToInt(bounds.width()),
2155 SkScalarCeilToInt(bounds.height())));
2156 clipRegion = &perspectiveBounds;
2157 srcRect = NULL;
2158 bitmap = &perspectiveBitmap;
2159 }
2160
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002161 SkMatrix scaled;
2162 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002163 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2164 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002165 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002166 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002167 scaled.postScale(SkIntToScalar(subset.width()),
2168 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002169 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002170 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002171 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2172 return;
2173 }
2174 if (content.needShape()) {
2175 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002176 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2177 SkIntToScalar( subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002178 shape.transform(matrix);
2179 content.setShape(shape);
2180 }
2181 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002182 return;
2183 }
2184
halcanarydaefa5b2014-08-27 13:00:54 -07002185 SkAutoTUnref<SkPDFObject> image(
2186 SkPDFCreateImageObject(*bitmap, subset, fEncoder));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002187 if (!image) {
2188 return;
2189 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002190
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002191 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002192 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002193}
reed@google.com982cb872011-12-07 18:34:08 +00002194