blob: bd9b1d7f7e79ae93ca1f6d66fda0053a15e7b27d [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,
fmalita05c4a432014-09-29 06:29:53 -07001147 const SkScalar pos[], int scalarsPerPos,
1148 const SkPoint& offset, 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);
fmalita05c4a432014-09-29 06:29:53 -07001180 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1181 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1182
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001183 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001184 set_text_transform(x, y, textPaint.getTextSkewX(),
1185 &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001186 SkString encodedString =
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001187 SkPDFString::FormatString(&encodedValue, 1,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001188 font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001189 content.entry()->fContent.writeText(encodedString.c_str());
1190 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001191 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001192 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001193}
1194
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001195void SkPDFDevice::drawTextOnPath(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001196 const SkPath& path, const SkMatrix* matrix,
1197 const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001198 if (d.fClip->isEmpty()) {
1199 return;
1200 }
vandebo@chromium.org290e3bb2011-11-08 23:42:53 +00001201 d.drawTextOnPath((const char*)text, len, path, matrix, paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001202}
1203
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001204void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001205 int vertexCount, const SkPoint verts[],
1206 const SkPoint texs[], const SkColor colors[],
1207 SkXfermode* xmode, const uint16_t indices[],
1208 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001209 if (d.fClip->isEmpty()) {
1210 return;
1211 }
reed@google.com85e143c2013-12-30 15:51:25 +00001212 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001213}
1214
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001215void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1216 int x, int y, const SkPaint& paint) {
commit-bot@chromium.org3da3b622014-03-13 19:38:10 +00001217 // our onCreateDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001218 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001219 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001220 return;
1221 }
1222
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001223 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001224 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001225 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001226 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001227 return;
1228 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001229 if (content.needShape()) {
1230 SkPath shape;
1231 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001232 SkIntToScalar(device->width()),
1233 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001234 content.setShape(shape);
1235 }
1236 if (!content.needSource()) {
1237 return;
1238 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001239
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001240 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1241 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001242 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001243
1244 // Merge glyph sets from the drawn device.
1245 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001246}
1247
reed89443ab2014-06-27 11:34:19 -07001248SkImageInfo SkPDFDevice::imageInfo() const {
1249 return fLegacyBitmap.info();
1250}
1251
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001252void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1253 INHERITED::onAttachToCanvas(canvas);
1254
1255 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1256 fClipStack = canvas->getClipStack();
1257}
1258
1259void SkPDFDevice::onDetachFromCanvas() {
1260 INHERITED::onDetachFromCanvas();
1261
1262 fClipStack = NULL;
1263}
1264
reed4a8126e2014-09-22 07:29:03 -07001265SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1266 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001267}
1268
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001269ContentEntry* SkPDFDevice::getLastContentEntry() {
1270 if (fDrawingArea == kContent_DrawingArea) {
1271 return fLastContentEntry;
1272 } else {
1273 return fLastMarginContentEntry;
1274 }
1275}
1276
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001277SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001278 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001279 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001280 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001281 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001282 }
1283}
1284
1285void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1286 if (fDrawingArea == kContent_DrawingArea) {
1287 fLastContentEntry = contentEntry;
1288 } else {
1289 fLastMarginContentEntry = contentEntry;
1290 }
1291}
1292
1293void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001294 // A ScopedContentEntry only exists during the course of a draw call, so
1295 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001296 fDrawingArea = drawingArea;
1297}
1298
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001299SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001300 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001301 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001302
1303 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001304 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001305 fResourceDict->insertResourceAsReference(
1306 SkPDFResourceDict::kExtGState_ResourceType,
1307 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001308 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001309 }
1310
1311 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001312 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001313 fResourceDict->insertResourceAsReference(
1314 SkPDFResourceDict::kXObject_ResourceType,
1315 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001316 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001317 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001318
1319 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001320 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001321 fResourceDict->insertResourceAsReference(
1322 SkPDFResourceDict::kFont_ResourceType,
1323 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001324 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001325 }
1326
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001327 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001328 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001329 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001330 fResourceDict->insertResourceAsReference(
1331 SkPDFResourceDict::kPattern_ResourceType,
1332 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001333 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001334 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001335 }
1336 return fResourceDict;
1337}
1338
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001339const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1340 return fFontResources;
1341}
1342
reed@google.com2a006c12012-09-19 17:05:55 +00001343SkPDFArray* SkPDFDevice::copyMediaBox() const {
1344 // should this be a singleton?
1345 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001346
reed@google.com2a006c12012-09-19 17:05:55 +00001347 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001348 mediaBox->reserve(4);
1349 mediaBox->append(zero.get());
1350 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001351 mediaBox->appendInt(fPageSize.fWidth);
1352 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001353 return mediaBox;
1354}
1355
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001356SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001357 SkMemoryStream* result = new SkMemoryStream;
1358 result->setData(this->copyContentToData())->unref();
1359 return result;
1360}
1361
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001362void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1363 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001364 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1365 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001366 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001367 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001368 SkPoint translation;
1369 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001370 translation.negate();
1371 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1372 translation);
1373 gsState.updateMatrix(entry->fState.fMatrix);
1374 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001375
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001376 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001377 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001378 entry = entry->fNext.get();
1379 }
1380 gsState.drainStack();
1381}
1382
reed@google.com5667afc2011-06-27 14:42:15 +00001383SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001384 SkDynamicMemoryWStream data;
1385 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1386 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001387 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001388
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001389 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1390 // colors the contentArea white before it starts drawing into it and
1391 // that currently acts as our clip.
1392 // Also, think about adding a transform here (or assume that the values
1393 // sent across account for that)
1394 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001395
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001396 // If the content area is the entire page, then we don't need to clip
1397 // the content area (PDF area clips to the page size). Otherwise,
1398 // we have to clip to the content area; we've already applied the
1399 // initial transform, so just clip to the device size.
1400 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001401 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1402 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001403 emit_clip(NULL, &r, &data);
1404 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001405
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001406 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001407
reed@google.com5667afc2011-06-27 14:42:15 +00001408 // potentially we could cache this SkData, and only rebuild it if we
1409 // see that our state has changed.
1410 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001411}
1412
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001413#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001414/* Draws an inverse filled path by using Path Ops to compute the positive
1415 * inverse using the current clip as the inverse bounds.
1416 * Return true if this was an inverse path and was properly handled,
1417 * otherwise returns false and the normal drawing routine should continue,
1418 * either as a (incorrect) fallback or because the path was not inverse
1419 * in the first place.
1420 */
1421bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001422 const SkPaint& paint, bool pathIsMutable,
1423 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001424 if (!origPath.isInverseFillType()) {
1425 return false;
1426 }
1427
1428 if (d.fClip->isEmpty()) {
1429 return false;
1430 }
1431
1432 SkPath modifiedPath;
1433 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1434 SkPaint noInversePaint(paint);
1435
1436 // Merge stroking operations into final path.
1437 if (SkPaint::kStroke_Style == paint.getStyle() ||
1438 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1439 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1440 if (doFillPath) {
1441 noInversePaint.setStyle(SkPaint::kFill_Style);
1442 noInversePaint.setStrokeWidth(0);
1443 pathPtr = &modifiedPath;
1444 } else {
1445 // To be consistent with the raster output, hairline strokes
1446 // are rendered as non-inverted.
1447 modifiedPath.toggleInverseFillType();
1448 drawPath(d, modifiedPath, paint, NULL, true);
1449 return true;
1450 }
1451 }
1452
1453 // Get bounds of clip in current transform space
1454 // (clip bounds are given in device space).
1455 SkRect bounds;
1456 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001457 SkMatrix totalMatrix = *d.fMatrix;
1458 if (prePathMatrix) {
1459 totalMatrix.preConcat(*prePathMatrix);
1460 }
1461 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001462 return false;
1463 }
1464 bounds.set(d.fClip->getBounds());
1465 transformInverse.mapRect(&bounds);
1466
1467 // Extend the bounds by the line width (plus some padding)
1468 // so the edge doesn't cause a visible stroke.
1469 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1470 paint.getStrokeWidth() + SK_Scalar1);
1471
1472 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1473 return false;
1474 }
1475
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001476 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001477 return true;
1478}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001479#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001480
epoger@google.comb58772f2013-03-08 09:09:10 +00001481bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1482 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001483 SkAnnotation* annotationInfo = p.getAnnotation();
1484 if (!annotationInfo) {
1485 return false;
1486 }
1487 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001488 if (urlData) {
1489 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001490 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001491 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001492 SkData* linkToName = annotationInfo->find(
1493 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001494 if (linkToName) {
1495 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001496 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001497 }
1498 return false;
1499}
1500
1501bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1502 const SkMatrix& matrix,
1503 const SkPaint& paint) {
1504 SkAnnotation* annotationInfo = paint.getAnnotation();
1505 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001506 return false;
1507 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001508 SkData* nameData = annotationInfo->find(
1509 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001510 if (nameData) {
1511 for (size_t i = 0; i < count; i++) {
1512 defineNamedDestination(nameData, points[i], matrix);
1513 }
reed@google.com44699382013-10-31 17:28:30 +00001514 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001515 }
1516 return false;
1517}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001518
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001519SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1520 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001521 SkMatrix transform = matrix;
1522 transform.postConcat(fInitialTransform);
1523 SkRect translatedRect;
1524 transform.mapRect(&translatedRect, r);
1525
reed@google.com2a006c12012-09-19 17:05:55 +00001526 if (NULL == fAnnotations) {
1527 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001528 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001529 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001530 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001531 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001532
epoger@google.comb58772f2013-03-08 09:09:10 +00001533 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001534 border->reserve(3);
1535 border->appendInt(0); // Horizontal corner radius.
1536 border->appendInt(0); // Vertical corner radius.
1537 border->appendInt(0); // Width, 0 = no border.
1538 annotation->insert("Border", border.get());
1539
epoger@google.comb58772f2013-03-08 09:09:10 +00001540 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001541 rect->reserve(4);
1542 rect->appendScalar(translatedRect.fLeft);
1543 rect->appendScalar(translatedRect.fTop);
1544 rect->appendScalar(translatedRect.fRight);
1545 rect->appendScalar(translatedRect.fBottom);
1546 annotation->insert("Rect", rect.get());
1547
epoger@google.comb58772f2013-03-08 09:09:10 +00001548 return annotation;
1549}
epoger@google.com1cad8982013-03-06 00:05:13 +00001550
epoger@google.comb58772f2013-03-08 09:09:10 +00001551void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1552 const SkMatrix& matrix) {
1553 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1554
1555 SkString url(static_cast<const char *>(urlData->data()),
1556 urlData->size() - 1);
1557 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1558 action->insertName("S", "URI");
1559 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1560 annotation->insert("A", action.get());
1561}
1562
1563void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1564 const SkMatrix& matrix) {
1565 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1566 SkString name(static_cast<const char *>(nameData->data()),
1567 nameData->size() - 1);
1568 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1569}
1570
1571struct NamedDestination {
1572 const SkData* nameData;
1573 SkPoint point;
1574
1575 NamedDestination(const SkData* nameData, const SkPoint& point)
1576 : nameData(nameData), point(point) {
1577 nameData->ref();
1578 }
1579
1580 ~NamedDestination() {
1581 nameData->unref();
1582 }
1583};
1584
1585void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1586 const SkMatrix& matrix) {
1587 SkMatrix transform = matrix;
1588 transform.postConcat(fInitialTransform);
1589 SkPoint translatedPoint;
1590 transform.mapXY(point.x(), point.y(), &translatedPoint);
1591 fNamedDestinations.push(
1592 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1593}
1594
1595void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1596 int nDest = fNamedDestinations.count();
1597 for (int i = 0; i < nDest; i++) {
1598 NamedDestination* dest = fNamedDestinations[i];
1599 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1600 pdfDest->reserve(5);
1601 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1602 pdfDest->appendName("XYZ");
1603 pdfDest->appendScalar(dest->point.x());
1604 pdfDest->appendScalar(dest->point.y());
1605 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001606 dict->insert(static_cast<const char *>(dest->nameData->data()),
1607 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001608 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001609}
1610
reed@google.comfc641d02012-09-20 17:52:20 +00001611SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1612 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001613 // We always draw the form xobjects that we create back into the device, so
1614 // we simply preserve the font usage instead of pulling it out and merging
1615 // it back in later.
1616 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001617 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001618 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001619}
1620
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001621void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1622 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001623 const SkClipStack* clipStack,
1624 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001625 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001626 bool invertClip) {
1627 if (clipRegion.isEmpty() && !invertClip) {
1628 return;
1629 }
1630
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001631 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1632 SkPDFGraphicState::GetSMaskGraphicState(
1633 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1634
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001635 SkMatrix identity;
1636 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001637 SkPaint paint;
1638 paint.setXfermodeMode(mode);
1639 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001640 if (!content.entry()) {
1641 return;
1642 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001643 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001644 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001645 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001646
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001647 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001648 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001649 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001650}
1651
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001652ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1653 const SkRegion& clipRegion,
1654 const SkMatrix& matrix,
1655 const SkPaint& paint,
1656 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001657 SkPDFFormXObject** dst) {
1658 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001659 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001660 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001661 }
1662
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001663 // The clip stack can come from an SkDraw where it is technically optional.
1664 SkClipStack synthesizedClipStack;
1665 if (clipStack == NULL) {
1666 if (clipRegion == fExistingClipRegion) {
1667 clipStack = &fExistingClipStack;
1668 } else {
1669 // GraphicStackState::updateClip expects the clip stack to have
1670 // fExistingClip as a prefix, so start there, then set the clip
1671 // to the passed region.
1672 synthesizedClipStack = fExistingClipStack;
1673 SkPath clipPath;
1674 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001675 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1676 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001677 clipStack = &synthesizedClipStack;
1678 }
1679 }
1680
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001681 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1682 if (paint.getXfermode()) {
1683 paint.getXfermode()->asMode(&xfermode);
1684 }
1685
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001686 // For the following modes, we want to handle source and destination
1687 // separately, so make an object of what's already there.
1688 if (xfermode == SkXfermode::kClear_Mode ||
1689 xfermode == SkXfermode::kSrc_Mode ||
1690 xfermode == SkXfermode::kSrcIn_Mode ||
1691 xfermode == SkXfermode::kDstIn_Mode ||
1692 xfermode == SkXfermode::kSrcOut_Mode ||
1693 xfermode == SkXfermode::kDstOut_Mode ||
1694 xfermode == SkXfermode::kSrcATop_Mode ||
1695 xfermode == SkXfermode::kDstATop_Mode ||
1696 xfermode == SkXfermode::kModulate_Mode) {
1697 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001698 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001699 SkASSERT(isContentEmpty());
1700 } else if (xfermode != SkXfermode::kSrc_Mode &&
1701 xfermode != SkXfermode::kSrcOut_Mode) {
1702 // Except for Src and SrcOut, if there isn't anything already there,
1703 // then we're done.
1704 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001705 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001706 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001707 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001708 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001709
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001710 // Dst xfer mode doesn't draw source at all.
1711 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001712 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001713 }
1714
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001715 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001716 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001717
1718 ContentEntry* lastContentEntry = getLastContentEntry();
1719 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1720 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001721 } else {
1722 newEntry.reset(new ContentEntry);
1723 entry = newEntry.get();
1724 }
1725
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001726 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001727 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001728 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1729 entry->fState.compareInitialState(lastContentEntry->fState)) {
1730 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001731 }
1732
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001733 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001734 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001735 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001736 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001737 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001738 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001739 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001740 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001741 lastContentEntry->fNext.reset(entry);
1742 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001743 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001744 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001745 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001746}
1747
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001748void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001749 SkPDFFormXObject* dst,
1750 SkPath* shape) {
1751 if (xfermode != SkXfermode::kClear_Mode &&
1752 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001753 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001754 xfermode != SkXfermode::kSrcIn_Mode &&
1755 xfermode != SkXfermode::kDstIn_Mode &&
1756 xfermode != SkXfermode::kSrcOut_Mode &&
1757 xfermode != SkXfermode::kDstOut_Mode &&
1758 xfermode != SkXfermode::kSrcATop_Mode &&
1759 xfermode != SkXfermode::kDstATop_Mode &&
1760 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001761 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001762 return;
1763 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001764 if (xfermode == SkXfermode::kDstOver_Mode) {
1765 SkASSERT(!dst);
1766 ContentEntry* firstContentEntry = getContentEntries()->get();
1767 if (firstContentEntry->fContent.getOffset() == 0) {
1768 // For DstOver, an empty content entry was inserted before the rest
1769 // of the content entries. If nothing was drawn, it needs to be
1770 // removed.
1771 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1772 contentEntries->reset(firstContentEntry->fNext.detach());
1773 }
1774 return;
1775 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001776 if (!dst) {
1777 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1778 xfermode == SkXfermode::kSrcOut_Mode);
1779 return;
1780 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001781
1782 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001783 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001784 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001785 // Changing the current content into a form-xobject will destroy the clip
1786 // objects which is fine since the xobject will already be clipped. However
1787 // if source has shape, we need to clip it too, so a copy of the clip is
1788 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001789 SkClipStack clipStack = contentEntries->fState.fClipStack;
1790 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001791
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001792 SkMatrix identity;
1793 identity.reset();
1794 SkPaint stockPaint;
1795
reed@google.comfc641d02012-09-20 17:52:20 +00001796 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001797 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001798 // If nothing was drawn and there's no shape, then the draw was a
1799 // no-op, but dst needs to be restored for that to be true.
1800 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1801 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1802 // reduces to Dst.
1803 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1804 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001805 ScopedContentEntry content(this, &fExistingClipStack,
1806 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001807 stockPaint);
1808 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1809 &content.entry()->fContent);
1810 return;
1811 } else {
1812 xfermode = SkXfermode::kClear_Mode;
1813 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001814 } else {
1815 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001816 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001817 }
1818
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001819 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1820 // without alpha.
1821 if (xfermode == SkXfermode::kSrcATop_Mode) {
1822 // TODO(vandebo): In order to properly support SrcATop we have to track
1823 // the shape of what's been drawn at all times. It's the intersection of
1824 // the non-transparent parts of the device and the outlines (shape) of
1825 // all images and devices drawn.
1826 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001827 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001828 SkXfermode::kSrcOver_Mode, true);
1829 } else {
1830 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1831 SkPDFFormXObject* dstMask = srcFormXObject.get();
1832 if (shape != NULL) {
1833 // Draw shape into a form-xobject.
1834 SkDraw d;
1835 d.fMatrix = &identity;
1836 d.fClip = &clipRegion;
1837 d.fClipStack = &clipStack;
1838 SkPaint filledPaint;
1839 filledPaint.setColor(SK_ColorBLACK);
1840 filledPaint.setStyle(SkPaint::kFill_Style);
1841 this->drawPath(d, *shape, filledPaint, NULL, true);
1842
1843 dstMaskStorage.reset(createFormXObjectFromDevice());
1844 dstMask = dstMaskStorage.get();
1845 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001846 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1847 &fExistingClipStack, fExistingClipRegion,
1848 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001849 }
1850
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001851 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001852 return;
1853 } else if (xfermode == SkXfermode::kSrc_Mode ||
1854 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001855 ScopedContentEntry content(this, &fExistingClipStack,
1856 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001857 if (content.entry()) {
1858 SkPDFUtils::DrawFormXObject(
1859 this->addXObjectResource(srcFormXObject.get()),
1860 &content.entry()->fContent);
1861 }
1862 if (xfermode == SkXfermode::kSrc_Mode) {
1863 return;
1864 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001865 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001866 ScopedContentEntry content(this, &fExistingClipStack,
1867 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001868 if (content.entry()) {
1869 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1870 &content.entry()->fContent);
1871 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001872 }
1873
1874 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1875 xfermode == SkXfermode::kDstIn_Mode ||
1876 xfermode == SkXfermode::kSrcOut_Mode ||
1877 xfermode == SkXfermode::kDstOut_Mode ||
1878 xfermode == SkXfermode::kSrcATop_Mode ||
1879 xfermode == SkXfermode::kDstATop_Mode ||
1880 xfermode == SkXfermode::kModulate_Mode);
1881
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001882 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001883 xfermode == SkXfermode::kSrcOut_Mode ||
1884 xfermode == SkXfermode::kSrcATop_Mode) {
1885 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001886 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001887 SkXfermode::kSrcOver_Mode,
1888 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001889 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001890 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1891 if (xfermode == SkXfermode::kModulate_Mode) {
1892 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001893 dst, &fExistingClipStack,
1894 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001895 SkXfermode::kSrcOver_Mode, false);
1896 mode = SkXfermode::kMultiply_Mode;
1897 }
1898 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001899 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001900 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001901 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001902}
1903
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001904bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001905 ContentEntry* contentEntries = getContentEntries()->get();
1906 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1907 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001908 return true;
1909 }
1910 return false;
1911}
1912
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001913void SkPDFDevice::populateGraphicStateEntryFromPaint(
1914 const SkMatrix& matrix,
1915 const SkClipStack& clipStack,
1916 const SkRegion& clipRegion,
1917 const SkPaint& paint,
1918 bool hasText,
1919 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001920 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001921 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1922 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001923
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001924 entry->fMatrix = matrix;
1925 entry->fClipStack = clipStack;
1926 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001927 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1928 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001929
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001930 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001931 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001932 const SkShader* shader = paint.getShader();
1933 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001934 if (shader) {
1935 // PDF positions patterns relative to the initial transform, so
1936 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001937 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001938 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001939
1940 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001941 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001942 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001943
1944 // We need to apply the initial transform to bounds in order to get
1945 // bounds in a consistent coordinate system.
1946 SkRect boundsTemp;
1947 boundsTemp.set(bounds);
1948 fInitialTransform.mapRect(&boundsTemp);
1949 boundsTemp.roundOut(&bounds);
1950
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001951 pdfShader.reset(SkPDFShader::GetPDFShader(*shader, transform, bounds));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001952
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001953 if (pdfShader.get()) {
1954 // pdfShader has been canonicalized so we can directly compare
1955 // pointers.
1956 int resourceIndex = fShaderResources.find(pdfShader.get());
1957 if (resourceIndex < 0) {
1958 resourceIndex = fShaderResources.count();
1959 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001960 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001961 }
1962 entry->fShaderIndex = resourceIndex;
1963 } else {
1964 // A color shader is treated as an invalid shader so we don't have
1965 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001966 SkShader::GradientInfo gradientInfo;
1967 SkColor gradientColor;
1968 gradientInfo.fColors = &gradientColor;
1969 gradientInfo.fColorOffsets = NULL;
1970 gradientInfo.fColorCount = 1;
1971 if (shader->asAGradient(&gradientInfo) ==
1972 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001973 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1974 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001975 }
1976 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001977 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001978
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001979 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001980 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001981 newGraphicState.reset(
1982 SkPDFGraphicState::GetGraphicStateForPaint(paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001983 } else {
1984 SkPaint newPaint = paint;
1985 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001986 newGraphicState.reset(
1987 SkPDFGraphicState::GetGraphicStateForPaint(newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001988 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001989 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001990 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001991
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001992 if (hasText) {
1993 entry->fTextScaleX = paint.getTextScaleX();
1994 entry->fTextFill = paint.getStyle();
1995 } else {
1996 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001997 }
1998}
1999
vandebo@chromium.org6112c212011-05-13 03:50:38 +00002000int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
2001 // Assumes that gs has been canonicalized (so we can directly compare
2002 // pointers).
2003 int result = fGraphicStateResources.find(gs);
2004 if (result < 0) {
2005 result = fGraphicStateResources.count();
2006 fGraphicStateResources.push(gs);
2007 gs->ref();
2008 }
2009 return result;
2010}
2011
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002012int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
2013 // Assumes that xobject has been canonicalized (so we can directly compare
2014 // pointers).
2015 int result = fXObjectResources.find(xObject);
2016 if (result < 0) {
2017 result = fXObjectResources.count();
2018 fXObjectResources.push(xObject);
2019 xObject->ref();
2020 }
2021 return result;
2022}
2023
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002024void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
2025 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002026 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002027 if (contentEntry->fState.fFont == NULL ||
2028 contentEntry->fState.fTextSize != paint.getTextSize() ||
2029 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002030 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00002031 contentEntry->fContent.writeText("/");
2032 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
2033 SkPDFResourceDict::kFont_ResourceType,
2034 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002035 contentEntry->fContent.writeText(" ");
2036 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
2037 contentEntry->fContent.writeText(" Tf\n");
2038 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00002039 }
2040}
2041
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00002042int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002043 SkAutoTUnref<SkPDFFont> newFont(SkPDFFont::GetFontResource(typeface,
2044 glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002045 int resourceIndex = fFontResources.find(newFont.get());
2046 if (resourceIndex < 0) {
2047 resourceIndex = fFontResources.count();
2048 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002049 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002050 }
2051 return resourceIndex;
2052}
2053
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002054void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002055 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002056 const SkRegion& origClipRegion,
2057 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002058 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002059 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002060 SkMatrix matrix = origMatrix;
2061 SkRegion perspectiveBounds;
2062 const SkRegion* clipRegion = &origClipRegion;
2063 SkBitmap perspectiveBitmap;
2064 const SkBitmap* bitmap = &origBitmap;
2065 SkBitmap tmpSubsetBitmap;
2066
2067 // Rasterize the bitmap using perspective in a new bitmap.
2068 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002069 if (fRasterDpi == 0) {
2070 return;
2071 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002072 SkBitmap* subsetBitmap;
2073 if (srcRect) {
2074 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2075 return;
2076 }
2077 subsetBitmap = &tmpSubsetBitmap;
2078 } else {
2079 subsetBitmap = &tmpSubsetBitmap;
2080 *subsetBitmap = origBitmap;
2081 }
2082 srcRect = NULL;
2083
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002084 // Transform the bitmap in the new space, without taking into
2085 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002086 SkPath perspectiveOutline;
2087 perspectiveOutline.addRect(
2088 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2089 SkIntToScalar(subsetBitmap->height())));
2090 perspectiveOutline.transform(origMatrix);
2091
2092 // TODO(edisonn): perf - use current clip too.
2093 // Retrieve the bounds of the new shape.
2094 SkRect bounds = perspectiveOutline.getBounds();
2095
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002096 // Transform the bitmap in the new space, taking into
2097 // account the initial transform.
2098 SkMatrix total = origMatrix;
2099 total.postConcat(fInitialTransform);
2100 total.postScale(SkIntToScalar(fRasterDpi) /
2101 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2102 SkIntToScalar(fRasterDpi) /
2103 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2104 SkPath physicalPerspectiveOutline;
2105 physicalPerspectiveOutline.addRect(
2106 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2107 SkIntToScalar(subsetBitmap->height())));
2108 physicalPerspectiveOutline.transform(total);
2109
2110 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2111 bounds.width();
2112 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2113 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002114
2115 // TODO(edisonn): A better approach would be to use a bitmap shader
2116 // (in clamp mode) and draw a rect over the entire bounding box. Then
2117 // intersect perspectiveOutline to the clip. That will avoid introducing
2118 // alpha to the image while still giving good behavior at the edge of
2119 // the image. Avoiding alpha will reduce the pdf size and generation
2120 // CPU time some.
2121
reed@google.com9ebcac52014-01-24 18:53:42 +00002122 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2123 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002124 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002125 return;
2126 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002127 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2128
reed89443ab2014-06-27 11:34:19 -07002129 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002130
2131 SkScalar deltaX = bounds.left();
2132 SkScalar deltaY = bounds.top();
2133
2134 SkMatrix offsetMatrix = origMatrix;
2135 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002136 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002137
2138 // Translate the draw in the new canvas, so we perfectly fit the
2139 // shape in the bitmap.
2140 canvas.setMatrix(offsetMatrix);
2141
2142 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2143
2144 // Make sure the final bits are in the bitmap.
2145 canvas.flush();
2146
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002147 // In the new space, we use the identity matrix translated
2148 // and scaled to reflect DPI.
2149 matrix.setScale(1 / scaleX, 1 / scaleY);
2150 matrix.postTranslate(deltaX, deltaY);
2151
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002152 perspectiveBounds.setRect(
2153 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2154 SkScalarFloorToInt(bounds.y()),
2155 SkScalarCeilToInt(bounds.width()),
2156 SkScalarCeilToInt(bounds.height())));
2157 clipRegion = &perspectiveBounds;
2158 srcRect = NULL;
2159 bitmap = &perspectiveBitmap;
2160 }
2161
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002162 SkMatrix scaled;
2163 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002164 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2165 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002166 // Scale the image up from 1x1 to WxH.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002167 SkIRect subset = SkIRect::MakeWH(bitmap->width(), bitmap->height());
reed@google.coma6d59f62011-03-07 21:29:21 +00002168 scaled.postScale(SkIntToScalar(subset.width()),
2169 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002170 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002171 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002172 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2173 return;
2174 }
2175 if (content.needShape()) {
2176 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002177 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2178 SkIntToScalar( subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002179 shape.transform(matrix);
2180 content.setShape(shape);
2181 }
2182 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002183 return;
2184 }
2185
halcanarydaefa5b2014-08-27 13:00:54 -07002186 SkAutoTUnref<SkPDFObject> image(
2187 SkPDFCreateImageObject(*bitmap, subset, fEncoder));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002188 if (!image) {
2189 return;
2190 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002191
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002192 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002193 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002194}
reed@google.com982cb872011-12-07 18:34:08 +00002195