blob: 90f0a4a7c8a448b7280510c24507164c1e811e92 [file] [log] [blame]
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2011 Google Inc.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00003 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00004 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00006 */
7
8#include "SkPDFDevice.h"
9
vandebo@chromium.org238be8c2012-07-13 20:06:02 +000010#include "SkAnnotation.h"
senorblancob0e89dc2014-10-20 14:03:12 -070011#include "SkBitmapDevice.h"
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +000012#include "SkColor.h"
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +000013#include "SkClipStack.h"
reed@google.com8a85d0c2011-06-24 19:12:12 +000014#include "SkData.h"
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +000015#include "SkDraw.h"
vandebo@chromium.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,
bungeman22edc832014-10-03 07:55:58 -0700121 const 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);
bungeman22edc832014-10-03 07:55:58 -0700134 const uint16_t* input = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000135
136 int maxGlyphID = max_glyphid_for_typeface(paint.getTypeface());
reed@google.comaec40662014-04-18 19:29:07 +0000137 int validated;
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000138 for (validated = 0; validated < numGlyphs; ++validated) {
139 if (input[validated] > maxGlyphID) {
140 break;
141 }
142 }
143 if (validated >= numGlyphs) {
bungeman22edc832014-10-03 07:55:58 -0700144 *glyphIDs = static_cast<const uint16_t*>(text);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000145 return numGlyphs;
146 }
147
148 // Silently drop anything out of range.
149 storage->reset(numGlyphs);
150 if (validated > 0) {
151 memcpy(storage->get(), input, validated * sizeof(uint16_t));
152 }
153
reed@google.comaec40662014-04-18 19:29:07 +0000154 for (int i = validated; i < numGlyphs; ++i) {
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +0000155 storage->get()[i] = input[i];
156 if (input[i] > maxGlyphID) {
157 storage->get()[i] = 0;
158 }
159 }
160 *glyphIDs = storage->get();
161 return numGlyphs;
162}
163
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000164static void set_text_transform(SkScalar x, SkScalar y, SkScalar textSkewX,
165 SkWStream* content) {
166 // Flip the text about the x-axis to account for origin swap and include
167 // the passed parameters.
168 content->writeText("1 0 ");
169 SkPDFScalar::Append(0 - textSkewX, content);
170 content->writeText(" -1 ");
171 SkPDFScalar::Append(x, content);
172 content->writeText(" ");
173 SkPDFScalar::Append(y, content);
174 content->writeText(" Tm\n");
175}
176
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000177// It is important to not confuse GraphicStateEntry with SkPDFGraphicState, the
178// later being our representation of an object in the PDF file.
179struct GraphicStateEntry {
180 GraphicStateEntry();
181
182 // Compare the fields we care about when setting up a new content entry.
183 bool compareInitialState(const GraphicStateEntry& b);
184
185 SkMatrix fMatrix;
186 // We can't do set operations on Paths, though PDF natively supports
187 // intersect. If the clip stack does anything other than intersect,
188 // we have to fall back to the region. Treat fClipStack as authoritative.
189 // See http://code.google.com/p/skia/issues/detail?id=221
190 SkClipStack fClipStack;
191 SkRegion fClipRegion;
192
193 // When emitting the content entry, we will ensure the graphic state
194 // is set to these values first.
195 SkColor fColor;
196 SkScalar fTextScaleX; // Zero means we don't care what the value is.
197 SkPaint::Style fTextFill; // Only if TextScaleX is non-zero.
198 int fShaderIndex;
199 int fGraphicStateIndex;
200
201 // We may change the font (i.e. for Type1 support) within a
202 // ContentEntry. This is the one currently in effect, or NULL if none.
203 SkPDFFont* fFont;
204 // In PDF, text size has no default value. It is only valid if fFont is
205 // not NULL.
206 SkScalar fTextSize;
207};
208
209GraphicStateEntry::GraphicStateEntry() : fColor(SK_ColorBLACK),
210 fTextScaleX(SK_Scalar1),
211 fTextFill(SkPaint::kFill_Style),
212 fShaderIndex(-1),
213 fGraphicStateIndex(-1),
214 fFont(NULL),
215 fTextSize(SK_ScalarNaN) {
216 fMatrix.reset();
217}
218
commit-bot@chromium.orgb000d762014-02-07 19:39:57 +0000219bool GraphicStateEntry::compareInitialState(const GraphicStateEntry& cur) {
220 return fColor == cur.fColor &&
221 fShaderIndex == cur.fShaderIndex &&
222 fGraphicStateIndex == cur.fGraphicStateIndex &&
223 fMatrix == cur.fMatrix &&
224 fClipStack == cur.fClipStack &&
225 (fTextScaleX == 0 ||
226 (fTextScaleX == cur.fTextScaleX && fTextFill == cur.fTextFill));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000227}
228
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000229class GraphicStackState {
230public:
231 GraphicStackState(const SkClipStack& existingClipStack,
232 const SkRegion& existingClipRegion,
233 SkWStream* contentStream)
234 : fStackDepth(0),
235 fContentStream(contentStream) {
236 fEntries[0].fClipStack = existingClipStack;
237 fEntries[0].fClipRegion = existingClipRegion;
238 }
239
240 void updateClip(const SkClipStack& clipStack, const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000241 const SkPoint& translation);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000242 void updateMatrix(const SkMatrix& matrix);
243 void updateDrawingState(const GraphicStateEntry& state);
244
245 void drainStack();
246
247private:
248 void push();
249 void pop();
250 GraphicStateEntry* currentEntry() { return &fEntries[fStackDepth]; }
251
252 // Conservative limit on save depth, see impl. notes in PDF 1.4 spec.
253 static const int kMaxStackDepth = 12;
254 GraphicStateEntry fEntries[kMaxStackDepth + 1];
255 int fStackDepth;
256 SkWStream* fContentStream;
257};
258
259void GraphicStackState::drainStack() {
260 while (fStackDepth) {
261 pop();
262 }
263}
264
265void GraphicStackState::push() {
266 SkASSERT(fStackDepth < kMaxStackDepth);
267 fContentStream->writeText("q\n");
268 fStackDepth++;
269 fEntries[fStackDepth] = fEntries[fStackDepth - 1];
270}
271
272void GraphicStackState::pop() {
273 SkASSERT(fStackDepth > 0);
274 fContentStream->writeText("Q\n");
275 fStackDepth--;
276}
277
robertphillips@google.com80214e22012-07-20 15:33:18 +0000278// This function initializes iter to be an iterator on the "stack" argument
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000279// and then skips over the leading entries as specified in prefix. It requires
280// and asserts that "prefix" will be a prefix to "stack."
281static void skip_clip_stack_prefix(const SkClipStack& prefix,
282 const SkClipStack& stack,
robertphillips@google.comc0290622012-07-16 21:20:03 +0000283 SkClipStack::Iter* iter) {
robertphillips@google.com80214e22012-07-20 15:33:18 +0000284 SkClipStack::B2TIter prefixIter(prefix);
285 iter->reset(stack, SkClipStack::Iter::kBottom_IterStart);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000286
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000287 const SkClipStack::Element* prefixEntry;
288 const SkClipStack::Element* iterEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000289
290 for (prefixEntry = prefixIter.next(); prefixEntry;
robertphillips@google.comc0290622012-07-16 21:20:03 +0000291 prefixEntry = prefixIter.next()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000292 iterEntry = iter->next();
293 SkASSERT(iterEntry);
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000294 // Because of SkClipStack does internal intersection, the last clip
295 // entry may differ.
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +0000296 if (*prefixEntry != *iterEntry) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000297 SkASSERT(prefixEntry->getOp() == SkRegion::kIntersect_Op);
298 SkASSERT(iterEntry->getOp() == SkRegion::kIntersect_Op);
299 SkASSERT(iterEntry->getType() == prefixEntry->getType());
robertphillips@google.comc0290622012-07-16 21:20:03 +0000300 // back up the iterator by one
301 iter->prev();
vandebo@chromium.org8887ede2011-05-25 01:27:52 +0000302 prefixEntry = prefixIter.next();
303 break;
304 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000305 }
306
307 SkASSERT(prefixEntry == NULL);
308}
309
310static void emit_clip(SkPath* clipPath, SkRect* clipRect,
311 SkWStream* contentStream) {
312 SkASSERT(clipPath || clipRect);
313
314 SkPath::FillType clipFill;
315 if (clipPath) {
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000316 SkPDFUtils::EmitPath(*clipPath, SkPaint::kFill_Style, contentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000317 clipFill = clipPath->getFillType();
vandebo@chromium.org3e7b2802011-06-27 18:12:31 +0000318 } else {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000319 SkPDFUtils::AppendRectangle(*clipRect, contentStream);
320 clipFill = SkPath::kWinding_FillType;
321 }
322
323 NOT_IMPLEMENTED(clipFill == SkPath::kInverseEvenOdd_FillType, false);
324 NOT_IMPLEMENTED(clipFill == SkPath::kInverseWinding_FillType, false);
325 if (clipFill == SkPath::kEvenOdd_FillType) {
326 contentStream->writeText("W* n\n");
327 } else {
328 contentStream->writeText("W n\n");
329 }
330}
331
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000332#ifdef SK_PDF_USE_PATHOPS
333/* Calculate an inverted path's equivalent non-inverted path, given the
334 * canvas bounds.
335 * outPath may alias with invPath (since this is supported by PathOps).
336 */
337static bool calculate_inverse_path(const SkRect& bounds, const SkPath& invPath,
338 SkPath* outPath) {
339 SkASSERT(invPath.isInverseFillType());
340
341 SkPath clipPath;
342 clipPath.addRect(bounds);
343
344 return Op(clipPath, invPath, kIntersect_PathOp, outPath);
345}
346
347// Sanity check the numerical values of the SkRegion ops and PathOps ops
348// enums so region_op_to_pathops_op can do a straight passthrough cast.
349// If these are failing, it may be necessary to make region_op_to_pathops_op
350// do more.
351SK_COMPILE_ASSERT(SkRegion::kDifference_Op == (int)kDifference_PathOp,
352 region_pathop_mismatch);
353SK_COMPILE_ASSERT(SkRegion::kIntersect_Op == (int)kIntersect_PathOp,
354 region_pathop_mismatch);
355SK_COMPILE_ASSERT(SkRegion::kUnion_Op == (int)kUnion_PathOp,
356 region_pathop_mismatch);
357SK_COMPILE_ASSERT(SkRegion::kXOR_Op == (int)kXOR_PathOp,
358 region_pathop_mismatch);
359SK_COMPILE_ASSERT(SkRegion::kReverseDifference_Op ==
360 (int)kReverseDifference_PathOp,
361 region_pathop_mismatch);
362
363static SkPathOp region_op_to_pathops_op(SkRegion::Op op) {
364 SkASSERT(op >= 0);
365 SkASSERT(op <= SkRegion::kReverseDifference_Op);
366 return (SkPathOp)op;
367}
368
369/* Uses Path Ops to calculate a vector SkPath clip from a clip stack.
370 * Returns true if successful, or false if not successful.
371 * If successful, the resulting clip is stored in outClipPath.
372 * If not successful, outClipPath is undefined, and a fallback method
373 * should be used.
374 */
375static bool get_clip_stack_path(const SkMatrix& transform,
376 const SkClipStack& clipStack,
377 const SkRegion& clipRegion,
378 SkPath* outClipPath) {
379 outClipPath->reset();
380 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
381
382 const SkClipStack::Element* clipEntry;
383 SkClipStack::Iter iter;
384 iter.reset(clipStack, SkClipStack::Iter::kBottom_IterStart);
385 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
386 SkPath entryPath;
387 if (SkClipStack::Element::kEmpty_Type == clipEntry->getType()) {
388 outClipPath->reset();
389 outClipPath->setFillType(SkPath::kInverseWinding_FillType);
390 continue;
commit-bot@chromium.orge5b2af92014-02-16 13:25:24 +0000391 } else {
392 clipEntry->asPath(&entryPath);
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000393 }
394 entryPath.transform(transform);
395
396 if (SkRegion::kReplace_Op == clipEntry->getOp()) {
397 *outClipPath = entryPath;
398 } else {
399 SkPathOp op = region_op_to_pathops_op(clipEntry->getOp());
400 if (!Op(*outClipPath, entryPath, op, outClipPath)) {
401 return false;
402 }
403 }
404 }
405
406 if (outClipPath->isInverseFillType()) {
407 // The bounds are slightly outset to ensure this is correct in the
408 // face of floating-point accuracy and possible SkRegion bitmap
409 // approximations.
410 SkRect clipBounds = SkRect::Make(clipRegion.getBounds());
411 clipBounds.outset(SK_Scalar1, SK_Scalar1);
412 if (!calculate_inverse_path(clipBounds, *outClipPath, outClipPath)) {
413 return false;
414 }
415 }
416 return true;
417}
418#endif
419
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +0000420// TODO(vandebo): Take advantage of SkClipStack::getSaveCount(), the PDF
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000421// graphic state stack, and the fact that we can know all the clips used
422// on the page to optimize this.
423void GraphicStackState::updateClip(const SkClipStack& clipStack,
424 const SkRegion& clipRegion,
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000425 const SkPoint& translation) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000426 if (clipStack == currentEntry()->fClipStack) {
427 return;
428 }
429
430 while (fStackDepth > 0) {
431 pop();
432 if (clipStack == currentEntry()->fClipStack) {
433 return;
434 }
435 }
436 push();
437
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +0000438 currentEntry()->fClipStack = clipStack;
439 currentEntry()->fClipRegion = clipRegion;
440
441 SkMatrix transform;
442 transform.setTranslate(translation.fX, translation.fY);
443
444#ifdef SK_PDF_USE_PATHOPS
445 SkPath clipPath;
446 if (get_clip_stack_path(transform, clipStack, clipRegion, &clipPath)) {
447 emit_clip(&clipPath, NULL, fContentStream);
448 return;
449 }
450#endif
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000451 // gsState->initialEntry()->fClipStack/Region specifies the clip that has
452 // already been applied. (If this is a top level device, then it specifies
453 // a clip to the content area. If this is a layer, then it specifies
454 // the clip in effect when the layer was created.) There's no need to
455 // reapply that clip; SKCanvas's SkDrawIter will draw anything outside the
456 // initial clip on the parent layer. (This means there's a bug if the user
457 // expands the clip and then uses any xfer mode that uses dst:
458 // http://code.google.com/p/skia/issues/detail?id=228 )
robertphillips@google.comc0290622012-07-16 21:20:03 +0000459 SkClipStack::Iter iter;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000460 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
461
462 // If the clip stack does anything other than intersect or if it uses
463 // an inverse fill type, we have to fall back to the clip region.
464 bool needRegion = false;
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000465 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000466 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000467 if (clipEntry->getOp() != SkRegion::kIntersect_Op ||
468 clipEntry->isInverseFilled()) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000469 needRegion = true;
470 break;
471 }
472 }
473
474 if (needRegion) {
475 SkPath clipPath;
476 SkAssertResult(clipRegion.getBoundaryPath(&clipPath));
477 emit_clip(&clipPath, NULL, fContentStream);
478 } else {
479 skip_clip_stack_prefix(fEntries[0].fClipStack, clipStack, &iter);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000480 const SkClipStack::Element* clipEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000481 for (clipEntry = iter.next(); clipEntry; clipEntry = iter.next()) {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000482 SkASSERT(clipEntry->getOp() == SkRegion::kIntersect_Op);
483 switch (clipEntry->getType()) {
484 case SkClipStack::Element::kRect_Type: {
485 SkRect translatedClip;
486 transform.mapRect(&translatedClip, clipEntry->getRect());
487 emit_clip(NULL, &translatedClip, fContentStream);
488 break;
489 }
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000490 default: {
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000491 SkPath translatedPath;
commit-bot@chromium.org5a346a82014-02-16 16:01:14 +0000492 clipEntry->asPath(&translatedPath);
493 translatedPath.transform(transform, &translatedPath);
bsalomon@google.com8182fa02012-12-04 14:06:06 +0000494 emit_clip(&translatedPath, NULL, fContentStream);
495 break;
496 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000497 }
498 }
499 }
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000500}
501
502void GraphicStackState::updateMatrix(const SkMatrix& matrix) {
503 if (matrix == currentEntry()->fMatrix) {
504 return;
505 }
506
507 if (currentEntry()->fMatrix.getType() != SkMatrix::kIdentity_Mask) {
508 SkASSERT(fStackDepth > 0);
509 SkASSERT(fEntries[fStackDepth].fClipStack ==
510 fEntries[fStackDepth -1].fClipStack);
511 pop();
512
513 SkASSERT(currentEntry()->fMatrix.getType() == SkMatrix::kIdentity_Mask);
514 }
515 if (matrix.getType() == SkMatrix::kIdentity_Mask) {
516 return;
517 }
518
519 push();
520 SkPDFUtils::AppendTransform(matrix, fContentStream);
521 currentEntry()->fMatrix = matrix;
522}
523
524void GraphicStackState::updateDrawingState(const GraphicStateEntry& state) {
525 // PDF treats a shader as a color, so we only set one or the other.
526 if (state.fShaderIndex >= 0) {
527 if (state.fShaderIndex != currentEntry()->fShaderIndex) {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000528 SkPDFUtils::ApplyPattern(state.fShaderIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000529 currentEntry()->fShaderIndex = state.fShaderIndex;
530 }
531 } else {
532 if (state.fColor != currentEntry()->fColor ||
533 currentEntry()->fShaderIndex >= 0) {
534 emit_pdf_color(state.fColor, fContentStream);
535 fContentStream->writeText("RG ");
536 emit_pdf_color(state.fColor, fContentStream);
537 fContentStream->writeText("rg\n");
538 currentEntry()->fColor = state.fColor;
539 currentEntry()->fShaderIndex = -1;
540 }
541 }
542
543 if (state.fGraphicStateIndex != currentEntry()->fGraphicStateIndex) {
vandebo@chromium.org6112c212011-05-13 03:50:38 +0000544 SkPDFUtils::ApplyGraphicState(state.fGraphicStateIndex, fContentStream);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000545 currentEntry()->fGraphicStateIndex = state.fGraphicStateIndex;
546 }
547
548 if (state.fTextScaleX) {
549 if (state.fTextScaleX != currentEntry()->fTextScaleX) {
550 SkScalar pdfScale = SkScalarMul(state.fTextScaleX,
551 SkIntToScalar(100));
552 SkPDFScalar::Append(pdfScale, fContentStream);
553 fContentStream->writeText(" Tz\n");
554 currentEntry()->fTextScaleX = state.fTextScaleX;
555 }
556 if (state.fTextFill != currentEntry()->fTextFill) {
557 SK_COMPILE_ASSERT(SkPaint::kFill_Style == 0, enum_must_match_value);
558 SK_COMPILE_ASSERT(SkPaint::kStroke_Style == 1,
559 enum_must_match_value);
560 SK_COMPILE_ASSERT(SkPaint::kStrokeAndFill_Style == 2,
561 enum_must_match_value);
562 fContentStream->writeDecAsText(state.fTextFill);
563 fContentStream->writeText(" Tr\n");
564 currentEntry()->fTextFill = state.fTextFill;
565 }
566 }
567}
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000568
fmalita6987dca2014-11-13 08:33:37 -0800569SkBaseDevice* SkPDFDevice::onCreateCompatibleDevice(const CreateInfo& cinfo) {
senorblancob0e89dc2014-10-20 14:03:12 -0700570 // PDF does not support image filters, so render them on CPU.
571 // Note that this rendering is done at "screen" resolution (100dpi), not
572 // printer resolution.
573 // FIXME: It may be possible to express some filters natively using PDF
574 // to improve quality and file size (http://skbug.com/3043)
fmalita6987dca2014-11-13 08:33:37 -0800575 if (kImageFilter_Usage == cinfo.fUsage) {
576 return SkBitmapDevice::Create(cinfo.fInfo);
senorblancob0e89dc2014-10-20 14:03:12 -0700577 }
fmalita6987dca2014-11-13 08:33:37 -0800578 SkISize size = SkISize::Make(cinfo.fInfo.width(), cinfo.fInfo.height());
halcanarya1f1ee92015-02-20 06:17:26 -0800579 return SkPDFDevice::Create(size, fRasterDpi, fCanon);
bsalomon@google.come97f0852011-06-17 13:10:25 +0000580}
581
582
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000583struct ContentEntry {
584 GraphicStateEntry fState;
585 SkDynamicMemoryWStream fContent;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000586 SkAutoTDelete<ContentEntry> fNext;
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000587
588 // If the stack is too deep we could get Stack Overflow.
589 // So we manually destruct the object.
590 ~ContentEntry() {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000591 ContentEntry* val = fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000592 while (val != NULL) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000593 ContentEntry* valNext = val->fNext.detach();
edisonn@google.com2e6a69b2013-02-05 23:13:39 +0000594 // When the destructor is called, fNext is NULL and exits.
595 delete val;
596 val = valNext;
597 }
598 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000599};
600
601// A helper class to automatically finish a ContentEntry at the end of a
602// drawing method and maintain the state needed between set up and finish.
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000603class ScopedContentEntry {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000604public:
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000605 ScopedContentEntry(SkPDFDevice* device, const SkDraw& draw,
606 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000607 : fDevice(device),
608 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000609 fXfermode(SkXfermode::kSrcOver_Mode),
610 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000611 init(draw.fClipStack, *draw.fClip, *draw.fMatrix, paint, hasText);
612 }
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000613 ScopedContentEntry(SkPDFDevice* device, const SkClipStack* clipStack,
614 const SkRegion& clipRegion, const SkMatrix& matrix,
615 const SkPaint& paint, bool hasText = false)
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000616 : fDevice(device),
617 fContentEntry(NULL),
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000618 fXfermode(SkXfermode::kSrcOver_Mode),
619 fDstFormXObject(NULL) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000620 init(clipStack, clipRegion, matrix, paint, hasText);
621 }
622
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000623 ~ScopedContentEntry() {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000624 if (fContentEntry) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000625 SkPath* shape = &fShape;
626 if (shape->isEmpty()) {
627 shape = NULL;
628 }
629 fDevice->finishContentEntry(fXfermode, fDstFormXObject, shape);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000630 }
reed@google.comfc641d02012-09-20 17:52:20 +0000631 SkSafeUnref(fDstFormXObject);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000632 }
633
634 ContentEntry* entry() { return fContentEntry; }
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000635
636 /* Returns true when we explicitly need the shape of the drawing. */
637 bool needShape() {
638 switch (fXfermode) {
639 case SkXfermode::kClear_Mode:
640 case SkXfermode::kSrc_Mode:
641 case SkXfermode::kSrcIn_Mode:
642 case SkXfermode::kSrcOut_Mode:
643 case SkXfermode::kDstIn_Mode:
644 case SkXfermode::kDstOut_Mode:
645 case SkXfermode::kSrcATop_Mode:
646 case SkXfermode::kDstATop_Mode:
647 case SkXfermode::kModulate_Mode:
648 return true;
649 default:
650 return false;
651 }
652 }
653
654 /* Returns true unless we only need the shape of the drawing. */
655 bool needSource() {
656 if (fXfermode == SkXfermode::kClear_Mode) {
657 return false;
658 }
659 return true;
660 }
661
662 /* If the shape is different than the alpha component of the content, then
663 * setShape should be called with the shape. In particular, images and
664 * devices have rectangular shape.
665 */
666 void setShape(const SkPath& shape) {
667 fShape = shape;
668 }
669
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000670private:
671 SkPDFDevice* fDevice;
672 ContentEntry* fContentEntry;
673 SkXfermode::Mode fXfermode;
reed@google.comfc641d02012-09-20 17:52:20 +0000674 SkPDFFormXObject* fDstFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +0000675 SkPath fShape;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000676
677 void init(const SkClipStack* clipStack, const SkRegion& clipRegion,
678 const SkMatrix& matrix, const SkPaint& paint, bool hasText) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000679 // Shape has to be flatten before we get here.
680 if (matrix.hasPerspective()) {
681 NOT_IMPLEMENTED(!matrix.hasPerspective(), false);
vandebo@chromium.orgdc37e202013-10-18 20:16:34 +0000682 return;
683 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000684 if (paint.getXfermode()) {
685 paint.getXfermode()->asMode(&fXfermode);
686 }
687 fContentEntry = fDevice->setUpContentEntry(clipStack, clipRegion,
688 matrix, paint, hasText,
689 &fDstFormXObject);
690 }
691};
692
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000693////////////////////////////////////////////////////////////////////////////////
694
halcanarya1f1ee92015-02-20 06:17:26 -0800695SkPDFDevice::SkPDFDevice(SkISize pageSize,
696 SkScalar rasterDpi,
697 SkPDFCanon* canon,
698 bool flip)
reed89443ab2014-06-27 11:34:19 -0700699 : fPageSize(pageSize)
halcanarya1f1ee92015-02-20 06:17:26 -0800700 , fContentSize(pageSize)
701 , fExistingClipRegion(SkIRect::MakeSize(pageSize))
702 , fAnnotations(NULL)
703 , fResourceDict(NULL)
reed89443ab2014-06-27 11:34:19 -0700704 , fLastContentEntry(NULL)
705 , fLastMarginContentEntry(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800706 , fDrawingArea(kContent_DrawingArea)
reed89443ab2014-06-27 11:34:19 -0700707 , fClipStack(NULL)
halcanarya1f1ee92015-02-20 06:17:26 -0800708 , fFontGlyphUsage(SkNEW(SkPDFGlyphSetMap))
709 , fRasterDpi(rasterDpi)
710 , fCanon(canon) {
711 SkASSERT(pageSize.width() > 0);
712 SkASSERT(pageSize.height() > 0);
713 fLegacyBitmap.setInfo(
714 SkImageInfo::MakeUnknown(pageSize.width(), pageSize.height()));
715 if (flip) {
716 // Skia generally uses the top left as the origin but PDF
717 // natively has the origin at the bottom left. This matrix
718 // corrects for that. But that only needs to be done once, we
719 // don't do it when layering.
720 fInitialTransform.setTranslate(0, SkIntToScalar(pageSize.fHeight));
721 fInitialTransform.preScale(SK_Scalar1, -SK_Scalar1);
722 } else {
723 fInitialTransform.setIdentity();
724 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000725}
726
727SkPDFDevice::~SkPDFDevice() {
vandebo@chromium.org98594282011-07-25 22:34:12 +0000728 this->cleanUp(true);
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000729}
730
731void SkPDFDevice::init() {
reed@google.com2a006c12012-09-19 17:05:55 +0000732 fAnnotations = NULL;
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000733 fResourceDict = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000734 fContentEntries.free();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000735 fLastContentEntry = NULL;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000736 fMarginContentEntries.free();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +0000737 fLastMarginContentEntry = NULL;
vandebo@chromium.org98594282011-07-25 22:34:12 +0000738 fDrawingArea = kContent_DrawingArea;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +0000739 if (fFontGlyphUsage.get() == NULL) {
halcanary792c80f2015-02-20 07:21:05 -0800740 fFontGlyphUsage.reset(SkNEW(SkPDFGlyphSetMap));
vandebo@chromium.org98594282011-07-25 22:34:12 +0000741 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000742}
743
vandebo@chromium.org98594282011-07-25 22:34:12 +0000744void SkPDFDevice::cleanUp(bool clearFontUsage) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000745 fGraphicStateResources.unrefAll();
746 fXObjectResources.unrefAll();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +0000747 fFontResources.unrefAll();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000748 fShaderResources.unrefAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000749 SkSafeUnref(fAnnotations);
reed@google.comfc641d02012-09-20 17:52:20 +0000750 SkSafeUnref(fResourceDict);
epoger@google.comb58772f2013-03-08 09:09:10 +0000751 fNamedDestinations.deleteAll();
reed@google.com2a006c12012-09-19 17:05:55 +0000752
vandebo@chromium.org98594282011-07-25 22:34:12 +0000753 if (clearFontUsage) {
754 fFontGlyphUsage->reset();
755 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000756}
757
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000758void SkPDFDevice::drawPaint(const SkDraw& d, const SkPaint& paint) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000759 SkPaint newPaint = paint;
760 newPaint.setStyle(SkPaint::kFill_Style);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000761 ScopedContentEntry content(this, d, newPaint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000762 internalDrawPaint(newPaint, content.entry());
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000763}
764
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000765void SkPDFDevice::internalDrawPaint(const SkPaint& paint,
766 ContentEntry* contentEntry) {
767 if (!contentEntry) {
768 return;
769 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000770 SkRect bbox = SkRect::MakeWH(SkIntToScalar(this->width()),
771 SkIntToScalar(this->height()));
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000772 SkMatrix inverse;
commit-bot@chromium.orgd2cfa742013-09-20 18:58:30 +0000773 if (!contentEntry->fState.fMatrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000774 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000775 }
vandebo@chromium.org77bcaa32011-04-15 20:57:37 +0000776 inverse.mapRect(&bbox);
777
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000778 SkPDFUtils::AppendRectangle(bbox, &contentEntry->fContent);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000779 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000780 &contentEntry->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000781}
782
783void SkPDFDevice::drawPoints(const SkDraw& d, SkCanvas::PointMode mode,
784 size_t count, const SkPoint* points,
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000785 const SkPaint& passedPaint) {
786 if (count == 0) {
787 return;
788 }
789
epoger@google.comb58772f2013-03-08 09:09:10 +0000790 if (handlePointAnnotation(points, count, *d.fMatrix, passedPaint)) {
791 return;
792 }
793
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000794 // SkDraw::drawPoints converts to multiple calls to fDevice->drawPath.
795 // We only use this when there's a path effect because of the overhead
796 // of multiple calls to setUpContentEntry it causes.
797 if (passedPaint.getPathEffect()) {
798 if (d.fClip->isEmpty()) {
799 return;
800 }
801 SkDraw pointDraw(d);
802 pointDraw.fDevice = this;
803 pointDraw.drawPoints(mode, count, points, passedPaint, true);
804 return;
805 }
806
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000807 const SkPaint* paint = &passedPaint;
808 SkPaint modifiedPaint;
809
810 if (mode == SkCanvas::kPoints_PointMode &&
811 paint->getStrokeCap() != SkPaint::kRound_Cap) {
812 modifiedPaint = *paint;
813 paint = &modifiedPaint;
814 if (paint->getStrokeWidth()) {
815 // PDF won't draw a single point with square/butt caps because the
816 // orientation is ambiguous. Draw a rectangle instead.
817 modifiedPaint.setStyle(SkPaint::kFill_Style);
818 SkScalar strokeWidth = paint->getStrokeWidth();
819 SkScalar halfStroke = SkScalarHalf(strokeWidth);
820 for (size_t i = 0; i < count; i++) {
821 SkRect r = SkRect::MakeXYWH(points[i].fX, points[i].fY, 0, 0);
822 r.inset(-halfStroke, -halfStroke);
823 drawRect(d, r, modifiedPaint);
824 }
825 return;
826 } else {
827 modifiedPaint.setStrokeCap(SkPaint::kRound_Cap);
828 }
829 }
830
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000831 ScopedContentEntry content(this, d, *paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000832 if (!content.entry()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000833 return;
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +0000834 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000835
836 switch (mode) {
837 case SkCanvas::kPolygon_PointMode:
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000838 SkPDFUtils::MoveTo(points[0].fX, points[0].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000839 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000840 for (size_t i = 1; i < count; i++) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000841 SkPDFUtils::AppendLine(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000842 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000843 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000844 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000845 break;
846 case SkCanvas::kLines_PointMode:
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000847 for (size_t i = 0; i < count/2; i++) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000848 SkPDFUtils::MoveTo(points[i * 2].fX, points[i * 2].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000849 &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000850 SkPDFUtils::AppendLine(points[i * 2 + 1].fX,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +0000851 points[i * 2 + 1].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000852 &content.entry()->fContent);
853 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000854 }
855 break;
856 case SkCanvas::kPoints_PointMode:
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000857 SkASSERT(paint->getStrokeCap() == SkPaint::kRound_Cap);
858 for (size_t i = 0; i < count; i++) {
859 SkPDFUtils::MoveTo(points[i].fX, points[i].fY,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000860 &content.entry()->fContent);
861 SkPDFUtils::ClosePath(&content.entry()->fContent);
862 SkPDFUtils::StrokePath(&content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000863 }
864 break;
865 default:
866 SkASSERT(false);
867 }
868}
869
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000870void SkPDFDevice::drawRect(const SkDraw& d, const SkRect& rect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000871 const SkPaint& paint) {
commit-bot@chromium.org969fd6a2013-05-14 18:16:40 +0000872 SkRect r = rect;
873 r.sort();
874
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000875 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000876 if (d.fClip->isEmpty()) {
877 return;
878 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000879 SkPath path;
880 path.addRect(r);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000881 drawPath(d, path, paint, NULL, true);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000882 return;
883 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000884
epoger@google.comb58772f2013-03-08 09:09:10 +0000885 if (handleRectAnnotation(r, *d.fMatrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000886 return;
887 }
888
vandebo@chromium.org13d14a92011-05-24 23:12:41 +0000889 ScopedContentEntry content(this, d, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000890 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000891 return;
892 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000893 SkPDFUtils::AppendRectangle(r, &content.entry()->fContent);
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +0000894 SkPDFUtils::PaintPath(paint.getStyle(), SkPath::kWinding_FillType,
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000895 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000896}
897
reed89443ab2014-06-27 11:34:19 -0700898void SkPDFDevice::drawRRect(const SkDraw& draw, const SkRRect& rrect, const SkPaint& paint) {
scroggo@google.coma8e33a92013-11-08 18:02:53 +0000899 SkPath path;
900 path.addRRect(rrect);
901 this->drawPath(draw, path, paint, NULL, true);
902}
903
reed89443ab2014-06-27 11:34:19 -0700904void SkPDFDevice::drawOval(const SkDraw& draw, const SkRect& oval, const SkPaint& paint) {
905 SkPath path;
906 path.addOval(oval);
907 this->drawPath(draw, path, paint, NULL, true);
908}
909
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000910void SkPDFDevice::drawPath(const SkDraw& d, const SkPath& origPath,
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000911 const SkPaint& paint, const SkMatrix* prePathMatrix,
912 bool pathIsMutable) {
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000913 SkPath modifiedPath;
914 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
915
916 SkMatrix matrix = *d.fMatrix;
917 if (prePathMatrix) {
918 if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) {
919 if (!pathIsMutable) {
920 pathPtr = &modifiedPath;
921 pathIsMutable = true;
922 }
923 origPath.transform(*prePathMatrix, pathPtr);
924 } else {
commit-bot@chromium.org92362382014-03-18 12:51:48 +0000925 matrix.preConcat(*prePathMatrix);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000926 }
927 }
vandebo@chromium.org02cc5aa2011-01-25 22:06:29 +0000928
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000929 if (paint.getPathEffect()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000930 if (d.fClip->isEmpty()) {
931 return;
932 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000933 if (!pathIsMutable) {
934 pathPtr = &modifiedPath;
935 pathIsMutable = true;
936 }
937 bool fill = paint.getFillPath(origPath, pathPtr);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000938
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +0000939 SkPaint noEffectPaint(paint);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000940 noEffectPaint.setPathEffect(NULL);
941 if (fill) {
942 noEffectPaint.setStyle(SkPaint::kFill_Style);
943 } else {
944 noEffectPaint.setStyle(SkPaint::kStroke_Style);
945 noEffectPaint.setStrokeWidth(0);
946 }
947 drawPath(d, *pathPtr, noEffectPaint, NULL, true);
vandebo@chromium.org7d71f7f2010-10-26 19:51:44 +0000948 return;
949 }
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000950
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000951#ifdef SK_PDF_USE_PATHOPS
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000952 if (handleInversePath(d, origPath, paint, pathIsMutable, prePathMatrix)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +0000953 return;
954 }
955#endif
956
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000957 if (handleRectAnnotation(pathPtr->getBounds(), matrix, paint)) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +0000958 return;
959 }
960
edisonn@google.coma9ebd162013-10-07 13:22:21 +0000961 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000962 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +0000963 return;
964 }
vandebo@chromium.org683001c2012-05-09 17:17:51 +0000965 SkPDFUtils::EmitPath(*pathPtr, paint.getStyle(),
966 &content.entry()->fContent);
vandebo@chromium.orgff390322011-05-17 18:58:44 +0000967 SkPDFUtils::PaintPath(paint.getStyle(), pathPtr->getFillType(),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +0000968 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +0000969}
970
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000971void SkPDFDevice::drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
972 const SkRect* src, const SkRect& dst,
commit-bot@chromium.orgeed779d2013-08-16 10:24:37 +0000973 const SkPaint& paint,
974 SkCanvas::DrawBitmapRectFlags flags) {
975 // TODO: this code path must be updated to respect the flags parameter
edisonn@google.com2ae67e72013-02-12 01:06:38 +0000976 SkMatrix matrix;
977 SkRect bitmapBounds, tmpSrc, tmpDst;
978 SkBitmap tmpBitmap;
979
980 bitmapBounds.isetWH(bitmap.width(), bitmap.height());
981
982 // Compute matrix from the two rectangles
983 if (src) {
984 tmpSrc = *src;
985 } else {
986 tmpSrc = bitmapBounds;
987 }
988 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
989
990 const SkBitmap* bitmapPtr = &bitmap;
991
992 // clip the tmpSrc to the bounds of the bitmap, and recompute dstRect if
993 // needed (if the src was clipped). No check needed if src==null.
994 if (src) {
995 if (!bitmapBounds.contains(*src)) {
996 if (!tmpSrc.intersect(bitmapBounds)) {
997 return; // nothing to draw
998 }
999 // recompute dst, based on the smaller tmpSrc
1000 matrix.mapRect(&tmpDst, tmpSrc);
1001 }
1002
1003 // since we may need to clamp to the borders of the src rect within
1004 // the bitmap, we extract a subset.
1005 // TODO: make sure this is handled in drawBitmap and remove from here.
1006 SkIRect srcIR;
1007 tmpSrc.roundOut(&srcIR);
1008 if (!bitmap.extractSubset(&tmpBitmap, srcIR)) {
1009 return;
1010 }
1011 bitmapPtr = &tmpBitmap;
1012
1013 // Since we did an extract, we need to adjust the matrix accordingly
1014 SkScalar dx = 0, dy = 0;
1015 if (srcIR.fLeft > 0) {
1016 dx = SkIntToScalar(srcIR.fLeft);
1017 }
1018 if (srcIR.fTop > 0) {
1019 dy = SkIntToScalar(srcIR.fTop);
1020 }
1021 if (dx || dy) {
1022 matrix.preTranslate(dx, dy);
1023 }
1024 }
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001025 this->drawBitmap(draw, *bitmapPtr, matrix, paint);
edisonn@google.com2ae67e72013-02-12 01:06:38 +00001026}
1027
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001028void SkPDFDevice::drawBitmap(const SkDraw& d, const SkBitmap& bitmap,
robertphillips@google.com9bf380c2013-07-25 12:10:42 +00001029 const SkMatrix& matrix, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001030 if (d.fClip->isEmpty()) {
1031 return;
1032 }
1033
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001034 SkMatrix transform = matrix;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001035 transform.postConcat(*d.fMatrix);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001036 this->internalDrawBitmap(transform, d.fClipStack, *d.fClip, bitmap, NULL,
1037 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001038}
1039
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001040void SkPDFDevice::drawSprite(const SkDraw& d, const SkBitmap& bitmap,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001041 int x, int y, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001042 if (d.fClip->isEmpty()) {
1043 return;
1044 }
1045
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00001046 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001047 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001048 this->internalDrawBitmap(matrix, d.fClipStack, *d.fClip, bitmap, NULL,
1049 paint);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001050}
1051
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001052void SkPDFDevice::drawText(const SkDraw& d, const void* text, size_t len,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001053 SkScalar x, SkScalar y, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001054 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1055 if (paint.getMaskFilter() != NULL) {
1056 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1057 // making text unreadable (e.g. same text twice when using CSS shadows).
1058 return;
1059 }
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001060 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001061 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001062 if (!content.entry()) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001063 return;
1064 }
1065
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001066 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001067 const uint16_t* glyphIDs = NULL;
reed@google.comaec40662014-04-18 19:29:07 +00001068 int numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001069 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001070
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001071 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001072 align_text(glyphCacheProc, textPaint, glyphIDs, numGlyphs, &x, &y);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001073 content.entry()->fContent.writeText("BT\n");
1074 set_text_transform(x, y, textPaint.getTextSkewX(),
1075 &content.entry()->fContent);
reed@google.comaec40662014-04-18 19:29:07 +00001076 int consumedGlyphCount = 0;
halcanary2f912f32014-10-16 09:53:20 -07001077
1078 SkTDArray<uint16_t> glyphIDsCopy(glyphIDs, numGlyphs);
1079
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001080 while (numGlyphs > consumedGlyphCount) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001081 updateFont(textPaint, glyphIDs[consumedGlyphCount], content.entry());
1082 SkPDFFont* font = content.entry()->fState.fFont;
halcanary2f912f32014-10-16 09:53:20 -07001083
1084 int availableGlyphs = font->glyphsToPDFFontEncoding(
1085 glyphIDsCopy.begin() + consumedGlyphCount,
1086 numGlyphs - consumedGlyphCount);
1087 fFontGlyphUsage->noteGlyphUsage(
1088 font, glyphIDsCopy.begin() + consumedGlyphCount,
1089 availableGlyphs);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001090 SkString encodedString =
halcanary2f912f32014-10-16 09:53:20 -07001091 SkPDFString::FormatString(glyphIDsCopy.begin() + consumedGlyphCount,
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001092 availableGlyphs, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001093 content.entry()->fContent.writeText(encodedString.c_str());
vandebo@chromium.org01294102011-02-28 19:52:18 +00001094 consumedGlyphCount += availableGlyphs;
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001095 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001096 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001097 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001098}
1099
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001100void SkPDFDevice::drawPosText(const SkDraw& d, const void* text, size_t len,
fmalita05c4a432014-09-29 06:29:53 -07001101 const SkScalar pos[], int scalarsPerPos,
1102 const SkPoint& offset, const SkPaint& paint) {
edisonn@google.comb62f93f2013-03-24 18:05:10 +00001103 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1104 if (paint.getMaskFilter() != NULL) {
1105 // Don't pretend we support drawing MaskFilters, it makes for artifacts
1106 // making text unreadable (e.g. same text twice when using CSS shadows).
1107 return;
1108 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001109 SkASSERT(1 == scalarsPerPos || 2 == scalarsPerPos);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001110 SkPaint textPaint = calculate_text_paint(paint);
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001111 ScopedContentEntry content(this, d, textPaint, true);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001112 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001113 return;
1114 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001115
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001116 SkGlyphStorage storage(0);
bungeman22edc832014-10-03 07:55:58 -07001117 const uint16_t* glyphIDs = NULL;
1118 size_t numGlyphs = force_glyph_encoding(paint, text, len, &storage, &glyphIDs);
vandebo@chromium.org4e1cc6a2013-01-25 19:27:23 +00001119 textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001120
1121 SkDrawCacheProc glyphCacheProc = textPaint.getDrawCacheProc();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001122 content.entry()->fContent.writeText("BT\n");
1123 updateFont(textPaint, glyphIDs[0], content.entry());
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001124 for (size_t i = 0; i < numGlyphs; i++) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001125 SkPDFFont* font = content.entry()->fState.fFont;
vandebo@chromium.org01294102011-02-28 19:52:18 +00001126 uint16_t encodedValue = glyphIDs[i];
1127 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
bungeman22edc832014-10-03 07:55:58 -07001128 // The current pdf font cannot encode the current glyph.
1129 // Try to get a pdf font which can encode the current glyph.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001130 updateFont(textPaint, glyphIDs[i], content.entry());
bungeman22edc832014-10-03 07:55:58 -07001131 font = content.entry()->fState.fFont;
1132 if (font->glyphsToPDFFontEncoding(&encodedValue, 1) != 1) {
1133 SkDEBUGFAIL("PDF could not encode glyph.");
1134 continue;
1135 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001136 }
bungeman22edc832014-10-03 07:55:58 -07001137
vandebo@chromium.org98594282011-07-25 22:34:12 +00001138 fFontGlyphUsage->noteGlyphUsage(font, &encodedValue, 1);
fmalita05c4a432014-09-29 06:29:53 -07001139 SkScalar x = offset.x() + pos[i * scalarsPerPos];
1140 SkScalar y = offset.y() + (2 == scalarsPerPos ? pos[i * scalarsPerPos + 1] : 0);
1141
bungeman@google.com9a87cee2011-08-23 17:02:18 +00001142 align_text(glyphCacheProc, textPaint, glyphIDs + i, 1, &x, &y);
bungeman22edc832014-10-03 07:55:58 -07001143 set_text_transform(x, y, textPaint.getTextSkewX(), &content.entry()->fContent);
vandebo@chromium.orgcae5fba2011-03-28 19:03:50 +00001144 SkString encodedString =
bungeman22edc832014-10-03 07:55:58 -07001145 SkPDFString::FormatString(&encodedValue, 1, font->multiByteGlyphs());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001146 content.entry()->fContent.writeText(encodedString.c_str());
1147 content.entry()->fContent.writeText(" Tj\n");
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001148 }
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001149 content.entry()->fContent.writeText("ET\n");
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001150}
1151
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001152void SkPDFDevice::drawVertices(const SkDraw& d, SkCanvas::VertexMode,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001153 int vertexCount, const SkPoint verts[],
1154 const SkPoint texs[], const SkColor colors[],
1155 SkXfermode* xmode, const uint16_t indices[],
1156 int indexCount, const SkPaint& paint) {
vandebo@chromium.orgfb0b0ed2011-04-15 20:01:17 +00001157 if (d.fClip->isEmpty()) {
1158 return;
1159 }
reed@google.com85e143c2013-12-30 15:51:25 +00001160 // TODO: implement drawVertices
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001161}
1162
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001163void SkPDFDevice::drawDevice(const SkDraw& d, SkBaseDevice* device,
1164 int x, int y, const SkPaint& paint) {
fmalita6987dca2014-11-13 08:33:37 -08001165 // our onCreateCompatibleDevice() always creates SkPDFDevice subclasses.
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001166 SkPDFDevice* pdfDevice = static_cast<SkPDFDevice*>(device);
ctguil@chromium.orgf4ff39c2011-05-24 19:55:05 +00001167 if (pdfDevice->isContentEmpty()) {
vandebo@chromium.orgee7a9562011-05-24 17:38:01 +00001168 return;
1169 }
1170
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001171 SkMatrix matrix;
reed@google.coma6d59f62011-03-07 21:29:21 +00001172 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
vandebo@chromium.org13d14a92011-05-24 23:12:41 +00001173 ScopedContentEntry content(this, d.fClipStack, *d.fClip, matrix, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001174 if (!content.entry()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001175 return;
1176 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001177 if (content.needShape()) {
1178 SkPath shape;
1179 shape.addRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y),
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00001180 SkIntToScalar(device->width()),
1181 SkIntToScalar(device->height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001182 content.setShape(shape);
1183 }
1184 if (!content.needSource()) {
1185 return;
1186 }
vandebo@chromium.org1aef2ed2011-02-03 21:46:10 +00001187
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001188 SkAutoTUnref<SkPDFFormXObject> xObject(new SkPDFFormXObject(pdfDevice));
1189 SkPDFUtils::DrawFormXObject(this->addXObjectResource(xObject.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001190 &content.entry()->fContent);
vandebo@chromium.org98594282011-07-25 22:34:12 +00001191
1192 // Merge glyph sets from the drawn device.
1193 fFontGlyphUsage->merge(pdfDevice->getFontGlyphUsage());
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001194}
1195
reed89443ab2014-06-27 11:34:19 -07001196SkImageInfo SkPDFDevice::imageInfo() const {
1197 return fLegacyBitmap.info();
1198}
1199
robertphillips@google.com40a1ae42012-07-13 15:36:15 +00001200void SkPDFDevice::onAttachToCanvas(SkCanvas* canvas) {
1201 INHERITED::onAttachToCanvas(canvas);
1202
1203 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
1204 fClipStack = canvas->getClipStack();
1205}
1206
1207void SkPDFDevice::onDetachFromCanvas() {
1208 INHERITED::onDetachFromCanvas();
1209
1210 fClipStack = NULL;
1211}
1212
reed4a8126e2014-09-22 07:29:03 -07001213SkSurface* SkPDFDevice::newSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1214 return SkSurface::NewRaster(info, &props);
reed89443ab2014-06-27 11:34:19 -07001215}
1216
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001217ContentEntry* SkPDFDevice::getLastContentEntry() {
1218 if (fDrawingArea == kContent_DrawingArea) {
1219 return fLastContentEntry;
1220 } else {
1221 return fLastMarginContentEntry;
1222 }
1223}
1224
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001225SkAutoTDelete<ContentEntry>* SkPDFDevice::getContentEntries() {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001226 if (fDrawingArea == kContent_DrawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001227 return &fContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001228 } else {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001229 return &fMarginContentEntries;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001230 }
1231}
1232
1233void SkPDFDevice::setLastContentEntry(ContentEntry* contentEntry) {
1234 if (fDrawingArea == kContent_DrawingArea) {
1235 fLastContentEntry = contentEntry;
1236 } else {
1237 fLastMarginContentEntry = contentEntry;
1238 }
1239}
1240
1241void SkPDFDevice::setDrawingArea(DrawingArea drawingArea) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001242 // A ScopedContentEntry only exists during the course of a draw call, so
1243 // this can't be called while a ScopedContentEntry exists.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001244 fDrawingArea = drawingArea;
1245}
1246
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001247SkPDFResourceDict* SkPDFDevice::getResourceDict() {
reed@google.comfc641d02012-09-20 17:52:20 +00001248 if (NULL == fResourceDict) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001249 fResourceDict = SkNEW(SkPDFResourceDict);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001250
1251 if (fGraphicStateResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001252 for (int i = 0; i < fGraphicStateResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001253 fResourceDict->insertResourceAsReference(
1254 SkPDFResourceDict::kExtGState_ResourceType,
1255 i, fGraphicStateResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001256 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001257 }
1258
1259 if (fXObjectResources.count()) {
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001260 for (int i = 0; i < fXObjectResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001261 fResourceDict->insertResourceAsReference(
1262 SkPDFResourceDict::kXObject_ResourceType,
1263 i, fXObjectResources[i]);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001264 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001265 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001266
1267 if (fFontResources.count()) {
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001268 for (int i = 0; i < fFontResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001269 fResourceDict->insertResourceAsReference(
1270 SkPDFResourceDict::kFont_ResourceType,
1271 i, fFontResources[i]);
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001272 }
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001273 }
1274
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001275 if (fShaderResources.count()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001276 SkAutoTUnref<SkPDFDict> patterns(new SkPDFDict());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001277 for (int i = 0; i < fShaderResources.count(); i++) {
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001278 fResourceDict->insertResourceAsReference(
1279 SkPDFResourceDict::kPattern_ResourceType,
1280 i, fShaderResources[i]);
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001281 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001282 }
vandebo@chromium.orgfc166672013-07-22 18:31:24 +00001283 }
1284 return fResourceDict;
1285}
1286
vandebo@chromium.orgf0ec2662011-05-29 05:55:42 +00001287const SkTDArray<SkPDFFont*>& SkPDFDevice::getFontResources() const {
1288 return fFontResources;
1289}
1290
reed@google.com2a006c12012-09-19 17:05:55 +00001291SkPDFArray* SkPDFDevice::copyMediaBox() const {
1292 // should this be a singleton?
1293 SkAutoTUnref<SkPDFInt> zero(SkNEW_ARGS(SkPDFInt, (0)));
vandebo@chromium.orgf7c15762011-02-01 22:19:44 +00001294
reed@google.com2a006c12012-09-19 17:05:55 +00001295 SkPDFArray* mediaBox = SkNEW(SkPDFArray);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001296 mediaBox->reserve(4);
1297 mediaBox->append(zero.get());
1298 mediaBox->append(zero.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001299 mediaBox->appendInt(fPageSize.fWidth);
1300 mediaBox->appendInt(fPageSize.fHeight);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001301 return mediaBox;
1302}
1303
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001304SkStream* SkPDFDevice::content() const {
reed@google.com5667afc2011-06-27 14:42:15 +00001305 SkMemoryStream* result = new SkMemoryStream;
1306 result->setData(this->copyContentToData())->unref();
1307 return result;
1308}
1309
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001310void SkPDFDevice::copyContentEntriesToData(ContentEntry* entry,
1311 SkWStream* data) const {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001312 // TODO(ctguil): For margins, I'm not sure fExistingClipStack/Region is the
1313 // right thing to pass here.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001314 GraphicStackState gsState(fExistingClipStack, fExistingClipRegion, data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001315 while (entry != NULL) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001316 SkPoint translation;
1317 translation.iset(this->getOrigin());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001318 translation.negate();
1319 gsState.updateClip(entry->fState.fClipStack, entry->fState.fClipRegion,
1320 translation);
1321 gsState.updateMatrix(entry->fState.fMatrix);
1322 gsState.updateDrawingState(entry->fState);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001323
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001324 SkAutoDataUnref copy(entry->fContent.copyToData());
robertphillips@google.com59f46b82012-07-10 17:30:58 +00001325 data->write(copy->data(), copy->size());
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001326 entry = entry->fNext.get();
1327 }
1328 gsState.drainStack();
1329}
1330
reed@google.com5667afc2011-06-27 14:42:15 +00001331SkData* SkPDFDevice::copyContentToData() const {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001332 SkDynamicMemoryWStream data;
1333 if (fInitialTransform.getType() != SkMatrix::kIdentity_Mask) {
1334 SkPDFUtils::AppendTransform(fInitialTransform, &data);
vandebo@chromium.orgc2a9b7f2011-02-24 23:22:30 +00001335 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001336
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001337 // TODO(aayushkumar): Apply clip along the margins. Currently, webkit
1338 // colors the contentArea white before it starts drawing into it and
1339 // that currently acts as our clip.
1340 // Also, think about adding a transform here (or assume that the values
1341 // sent across account for that)
1342 SkPDFDevice::copyContentEntriesToData(fMarginContentEntries.get(), &data);
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001343
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001344 // If the content area is the entire page, then we don't need to clip
1345 // the content area (PDF area clips to the page size). Otherwise,
1346 // we have to clip to the content area; we've already applied the
1347 // initial transform, so just clip to the device size.
1348 if (fPageSize != fContentSize) {
robertphillips@google.com8637a362012-04-10 18:32:35 +00001349 SkRect r = SkRect::MakeWH(SkIntToScalar(this->width()),
1350 SkIntToScalar(this->height()));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001351 emit_clip(NULL, &r, &data);
1352 }
vandebo@chromium.org98594282011-07-25 22:34:12 +00001353
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001354 SkPDFDevice::copyContentEntriesToData(fContentEntries.get(), &data);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001355
reed@google.com5667afc2011-06-27 14:42:15 +00001356 // potentially we could cache this SkData, and only rebuild it if we
1357 // see that our state has changed.
1358 return data.copyToData();
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001359}
1360
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001361#ifdef SK_PDF_USE_PATHOPS
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001362/* Draws an inverse filled path by using Path Ops to compute the positive
1363 * inverse using the current clip as the inverse bounds.
1364 * Return true if this was an inverse path and was properly handled,
1365 * otherwise returns false and the normal drawing routine should continue,
1366 * either as a (incorrect) fallback or because the path was not inverse
1367 * in the first place.
1368 */
1369bool SkPDFDevice::handleInversePath(const SkDraw& d, const SkPath& origPath,
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001370 const SkPaint& paint, bool pathIsMutable,
1371 const SkMatrix* prePathMatrix) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001372 if (!origPath.isInverseFillType()) {
1373 return false;
1374 }
1375
1376 if (d.fClip->isEmpty()) {
1377 return false;
1378 }
1379
1380 SkPath modifiedPath;
1381 SkPath* pathPtr = const_cast<SkPath*>(&origPath);
1382 SkPaint noInversePaint(paint);
1383
1384 // Merge stroking operations into final path.
1385 if (SkPaint::kStroke_Style == paint.getStyle() ||
1386 SkPaint::kStrokeAndFill_Style == paint.getStyle()) {
1387 bool doFillPath = paint.getFillPath(origPath, &modifiedPath);
1388 if (doFillPath) {
1389 noInversePaint.setStyle(SkPaint::kFill_Style);
1390 noInversePaint.setStrokeWidth(0);
1391 pathPtr = &modifiedPath;
1392 } else {
1393 // To be consistent with the raster output, hairline strokes
1394 // are rendered as non-inverted.
1395 modifiedPath.toggleInverseFillType();
1396 drawPath(d, modifiedPath, paint, NULL, true);
1397 return true;
1398 }
1399 }
1400
1401 // Get bounds of clip in current transform space
1402 // (clip bounds are given in device space).
1403 SkRect bounds;
1404 SkMatrix transformInverse;
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001405 SkMatrix totalMatrix = *d.fMatrix;
1406 if (prePathMatrix) {
1407 totalMatrix.preConcat(*prePathMatrix);
1408 }
1409 if (!totalMatrix.invert(&transformInverse)) {
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001410 return false;
1411 }
1412 bounds.set(d.fClip->getBounds());
1413 transformInverse.mapRect(&bounds);
1414
1415 // Extend the bounds by the line width (plus some padding)
1416 // so the edge doesn't cause a visible stroke.
1417 bounds.outset(paint.getStrokeWidth() + SK_Scalar1,
1418 paint.getStrokeWidth() + SK_Scalar1);
1419
1420 if (!calculate_inverse_path(bounds, *pathPtr, &modifiedPath)) {
1421 return false;
1422 }
1423
edisonn@google.coma9ebd162013-10-07 13:22:21 +00001424 drawPath(d, modifiedPath, noInversePaint, prePathMatrix, true);
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001425 return true;
1426}
commit-bot@chromium.orgd2623a12013-08-08 02:52:05 +00001427#endif
commit-bot@chromium.org92ffe7d2013-07-31 22:54:31 +00001428
epoger@google.comb58772f2013-03-08 09:09:10 +00001429bool SkPDFDevice::handleRectAnnotation(const SkRect& r, const SkMatrix& matrix,
1430 const SkPaint& p) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001431 SkAnnotation* annotationInfo = p.getAnnotation();
1432 if (!annotationInfo) {
1433 return false;
1434 }
1435 SkData* urlData = annotationInfo->find(SkAnnotationKeys::URL_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001436 if (urlData) {
1437 handleLinkToURL(urlData, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001438 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001439 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001440 SkData* linkToName = annotationInfo->find(
1441 SkAnnotationKeys::Link_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001442 if (linkToName) {
1443 handleLinkToNamedDest(linkToName, r, matrix);
reed@google.com44699382013-10-31 17:28:30 +00001444 return p.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001445 }
1446 return false;
1447}
1448
1449bool SkPDFDevice::handlePointAnnotation(const SkPoint* points, size_t count,
1450 const SkMatrix& matrix,
1451 const SkPaint& paint) {
1452 SkAnnotation* annotationInfo = paint.getAnnotation();
1453 if (!annotationInfo) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001454 return false;
1455 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001456 SkData* nameData = annotationInfo->find(
1457 SkAnnotationKeys::Define_Named_Dest_Key());
epoger@google.comb58772f2013-03-08 09:09:10 +00001458 if (nameData) {
1459 for (size_t i = 0; i < count; i++) {
1460 defineNamedDestination(nameData, points[i], matrix);
1461 }
reed@google.com44699382013-10-31 17:28:30 +00001462 return paint.getAnnotation() != NULL;
epoger@google.comb58772f2013-03-08 09:09:10 +00001463 }
1464 return false;
1465}
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001466
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001467SkPDFDict* SkPDFDevice::createLinkAnnotation(const SkRect& r,
1468 const SkMatrix& matrix) {
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001469 SkMatrix transform = matrix;
1470 transform.postConcat(fInitialTransform);
1471 SkRect translatedRect;
1472 transform.mapRect(&translatedRect, r);
1473
reed@google.com2a006c12012-09-19 17:05:55 +00001474 if (NULL == fAnnotations) {
1475 fAnnotations = SkNEW(SkPDFArray);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001476 }
epoger@google.comb58772f2013-03-08 09:09:10 +00001477 SkPDFDict* annotation(SkNEW_ARGS(SkPDFDict, ("Annot")));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001478 annotation->insertName("Subtype", "Link");
epoger@google.comb58772f2013-03-08 09:09:10 +00001479 fAnnotations->append(annotation);
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001480
epoger@google.comb58772f2013-03-08 09:09:10 +00001481 SkAutoTUnref<SkPDFArray> border(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001482 border->reserve(3);
1483 border->appendInt(0); // Horizontal corner radius.
1484 border->appendInt(0); // Vertical corner radius.
1485 border->appendInt(0); // Width, 0 = no border.
1486 annotation->insert("Border", border.get());
1487
epoger@google.comb58772f2013-03-08 09:09:10 +00001488 SkAutoTUnref<SkPDFArray> rect(SkNEW(SkPDFArray));
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001489 rect->reserve(4);
1490 rect->appendScalar(translatedRect.fLeft);
1491 rect->appendScalar(translatedRect.fTop);
1492 rect->appendScalar(translatedRect.fRight);
1493 rect->appendScalar(translatedRect.fBottom);
1494 annotation->insert("Rect", rect.get());
1495
epoger@google.comb58772f2013-03-08 09:09:10 +00001496 return annotation;
1497}
epoger@google.com1cad8982013-03-06 00:05:13 +00001498
epoger@google.comb58772f2013-03-08 09:09:10 +00001499void SkPDFDevice::handleLinkToURL(SkData* urlData, const SkRect& r,
1500 const SkMatrix& matrix) {
1501 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1502
1503 SkString url(static_cast<const char *>(urlData->data()),
1504 urlData->size() - 1);
1505 SkAutoTUnref<SkPDFDict> action(SkNEW_ARGS(SkPDFDict, ("Action")));
1506 action->insertName("S", "URI");
1507 action->insert("URI", SkNEW_ARGS(SkPDFString, (url)))->unref();
1508 annotation->insert("A", action.get());
1509}
1510
1511void SkPDFDevice::handleLinkToNamedDest(SkData* nameData, const SkRect& r,
1512 const SkMatrix& matrix) {
1513 SkAutoTUnref<SkPDFDict> annotation(createLinkAnnotation(r, matrix));
1514 SkString name(static_cast<const char *>(nameData->data()),
1515 nameData->size() - 1);
1516 annotation->insert("Dest", SkNEW_ARGS(SkPDFName, (name)))->unref();
1517}
1518
1519struct NamedDestination {
1520 const SkData* nameData;
1521 SkPoint point;
1522
1523 NamedDestination(const SkData* nameData, const SkPoint& point)
1524 : nameData(nameData), point(point) {
1525 nameData->ref();
1526 }
1527
1528 ~NamedDestination() {
1529 nameData->unref();
1530 }
1531};
1532
1533void SkPDFDevice::defineNamedDestination(SkData* nameData, const SkPoint& point,
1534 const SkMatrix& matrix) {
1535 SkMatrix transform = matrix;
1536 transform.postConcat(fInitialTransform);
1537 SkPoint translatedPoint;
1538 transform.mapXY(point.x(), point.y(), &translatedPoint);
1539 fNamedDestinations.push(
1540 SkNEW_ARGS(NamedDestination, (nameData, translatedPoint)));
1541}
1542
1543void SkPDFDevice::appendDestinations(SkPDFDict* dict, SkPDFObject* page) {
1544 int nDest = fNamedDestinations.count();
1545 for (int i = 0; i < nDest; i++) {
1546 NamedDestination* dest = fNamedDestinations[i];
1547 SkAutoTUnref<SkPDFArray> pdfDest(SkNEW(SkPDFArray));
1548 pdfDest->reserve(5);
1549 pdfDest->append(SkNEW_ARGS(SkPDFObjRef, (page)))->unref();
1550 pdfDest->appendName("XYZ");
1551 pdfDest->appendScalar(dest->point.x());
1552 pdfDest->appendScalar(dest->point.y());
1553 pdfDest->appendInt(0); // Leave zoom unchanged
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001554 dict->insert(static_cast<const char *>(dest->nameData->data()),
1555 pdfDest);
epoger@google.comb58772f2013-03-08 09:09:10 +00001556 }
vandebo@chromium.org238be8c2012-07-13 20:06:02 +00001557}
1558
reed@google.comfc641d02012-09-20 17:52:20 +00001559SkPDFFormXObject* SkPDFDevice::createFormXObjectFromDevice() {
1560 SkPDFFormXObject* xobject = SkNEW_ARGS(SkPDFFormXObject, (this));
vandebo@chromium.org98594282011-07-25 22:34:12 +00001561 // We always draw the form xobjects that we create back into the device, so
1562 // we simply preserve the font usage instead of pulling it out and merging
1563 // it back in later.
1564 cleanUp(false); // Reset this device to have no content.
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001565 init();
reed@google.comfc641d02012-09-20 17:52:20 +00001566 return xobject;
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001567}
1568
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001569void SkPDFDevice::drawFormXObjectWithMask(int xObjectIndex,
1570 SkPDFFormXObject* mask,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001571 const SkClipStack* clipStack,
1572 const SkRegion& clipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001573 SkXfermode::Mode mode,
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001574 bool invertClip) {
1575 if (clipRegion.isEmpty() && !invertClip) {
1576 return;
1577 }
1578
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001579 SkAutoTUnref<SkPDFGraphicState> sMaskGS(
1580 SkPDFGraphicState::GetSMaskGraphicState(
1581 mask, invertClip, SkPDFGraphicState::kAlpha_SMaskMode));
1582
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001583 SkMatrix identity;
1584 identity.reset();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001585 SkPaint paint;
1586 paint.setXfermodeMode(mode);
1587 ScopedContentEntry content(this, clipStack, clipRegion, identity, paint);
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001588 if (!content.entry()) {
1589 return;
1590 }
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001591 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001592 &content.entry()->fContent);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001593 SkPDFUtils::DrawFormXObject(xObjectIndex, &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001594
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001595 sMaskGS.reset(SkPDFGraphicState::GetNoSMaskGraphicState());
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001596 SkPDFUtils::ApplyGraphicState(addGraphicStateResource(sMaskGS.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001597 &content.entry()->fContent);
vandebo@chromium.org466f3d62011-05-18 23:06:29 +00001598}
1599
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001600ContentEntry* SkPDFDevice::setUpContentEntry(const SkClipStack* clipStack,
1601 const SkRegion& clipRegion,
1602 const SkMatrix& matrix,
1603 const SkPaint& paint,
1604 bool hasText,
reed@google.comfc641d02012-09-20 17:52:20 +00001605 SkPDFFormXObject** dst) {
1606 *dst = NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001607 if (clipRegion.isEmpty()) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001608 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001609 }
1610
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001611 // The clip stack can come from an SkDraw where it is technically optional.
1612 SkClipStack synthesizedClipStack;
1613 if (clipStack == NULL) {
1614 if (clipRegion == fExistingClipRegion) {
1615 clipStack = &fExistingClipStack;
1616 } else {
1617 // GraphicStackState::updateClip expects the clip stack to have
1618 // fExistingClip as a prefix, so start there, then set the clip
1619 // to the passed region.
1620 synthesizedClipStack = fExistingClipStack;
1621 SkPath clipPath;
1622 clipRegion.getBoundaryPath(&clipPath);
reed@google.com00177082011-10-12 14:34:30 +00001623 synthesizedClipStack.clipDevPath(clipPath, SkRegion::kReplace_Op,
1624 false);
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001625 clipStack = &synthesizedClipStack;
1626 }
1627 }
1628
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001629 SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;
1630 if (paint.getXfermode()) {
1631 paint.getXfermode()->asMode(&xfermode);
1632 }
1633
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001634 // For the following modes, we want to handle source and destination
1635 // separately, so make an object of what's already there.
1636 if (xfermode == SkXfermode::kClear_Mode ||
1637 xfermode == SkXfermode::kSrc_Mode ||
1638 xfermode == SkXfermode::kSrcIn_Mode ||
1639 xfermode == SkXfermode::kDstIn_Mode ||
1640 xfermode == SkXfermode::kSrcOut_Mode ||
1641 xfermode == SkXfermode::kDstOut_Mode ||
1642 xfermode == SkXfermode::kSrcATop_Mode ||
1643 xfermode == SkXfermode::kDstATop_Mode ||
1644 xfermode == SkXfermode::kModulate_Mode) {
1645 if (!isContentEmpty()) {
reed@google.comfc641d02012-09-20 17:52:20 +00001646 *dst = createFormXObjectFromDevice();
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001647 SkASSERT(isContentEmpty());
1648 } else if (xfermode != SkXfermode::kSrc_Mode &&
1649 xfermode != SkXfermode::kSrcOut_Mode) {
1650 // Except for Src and SrcOut, if there isn't anything already there,
1651 // then we're done.
1652 return NULL;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001653 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001654 }
ctguil@chromium.org769fa6a2011-08-20 00:36:18 +00001655 // TODO(vandebo): Figure out how/if we can handle the following modes:
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001656 // Xor, Plus.
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001657
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001658 // Dst xfer mode doesn't draw source at all.
1659 if (xfermode == SkXfermode::kDst_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001660 return NULL;
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001661 }
1662
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001663 ContentEntry* entry;
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001664 SkAutoTDelete<ContentEntry> newEntry;
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001665
1666 ContentEntry* lastContentEntry = getLastContentEntry();
1667 if (lastContentEntry && lastContentEntry->fContent.getOffset() == 0) {
1668 entry = lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001669 } else {
1670 newEntry.reset(new ContentEntry);
1671 entry = newEntry.get();
1672 }
1673
vandebo@chromium.org78dad542011-05-11 18:46:03 +00001674 populateGraphicStateEntryFromPaint(matrix, *clipStack, clipRegion, paint,
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001675 hasText, &entry->fState);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001676 if (lastContentEntry && xfermode != SkXfermode::kDstOver_Mode &&
1677 entry->fState.compareInitialState(lastContentEntry->fState)) {
1678 return lastContentEntry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001679 }
1680
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001681 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001682 if (!lastContentEntry) {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001683 contentEntries->reset(entry);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001684 setLastContentEntry(entry);
vandebo@chromium.org25adce82011-05-09 08:05:01 +00001685 } else if (xfermode == SkXfermode::kDstOver_Mode) {
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001686 entry->fNext.reset(contentEntries->detach());
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001687 contentEntries->reset(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001688 } else {
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001689 lastContentEntry->fNext.reset(entry);
1690 setLastContentEntry(entry);
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001691 }
commit-bot@chromium.orge0294402013-08-29 22:14:04 +00001692 newEntry.detach();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001693 return entry;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001694}
1695
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001696void SkPDFDevice::finishContentEntry(SkXfermode::Mode xfermode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001697 SkPDFFormXObject* dst,
1698 SkPath* shape) {
1699 if (xfermode != SkXfermode::kClear_Mode &&
1700 xfermode != SkXfermode::kSrc_Mode &&
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001701 xfermode != SkXfermode::kDstOver_Mode &&
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001702 xfermode != SkXfermode::kSrcIn_Mode &&
1703 xfermode != SkXfermode::kDstIn_Mode &&
1704 xfermode != SkXfermode::kSrcOut_Mode &&
1705 xfermode != SkXfermode::kDstOut_Mode &&
1706 xfermode != SkXfermode::kSrcATop_Mode &&
1707 xfermode != SkXfermode::kDstATop_Mode &&
1708 xfermode != SkXfermode::kModulate_Mode) {
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001709 SkASSERT(!dst);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001710 return;
1711 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001712 if (xfermode == SkXfermode::kDstOver_Mode) {
1713 SkASSERT(!dst);
1714 ContentEntry* firstContentEntry = getContentEntries()->get();
1715 if (firstContentEntry->fContent.getOffset() == 0) {
1716 // For DstOver, an empty content entry was inserted before the rest
1717 // of the content entries. If nothing was drawn, it needs to be
1718 // removed.
1719 SkAutoTDelete<ContentEntry>* contentEntries = getContentEntries();
1720 contentEntries->reset(firstContentEntry->fNext.detach());
1721 }
1722 return;
1723 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001724 if (!dst) {
1725 SkASSERT(xfermode == SkXfermode::kSrc_Mode ||
1726 xfermode == SkXfermode::kSrcOut_Mode);
1727 return;
1728 }
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001729
1730 ContentEntry* contentEntries = getContentEntries()->get();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001731 SkASSERT(dst);
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001732 SkASSERT(!contentEntries->fNext.get());
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001733 // Changing the current content into a form-xobject will destroy the clip
1734 // objects which is fine since the xobject will already be clipped. However
1735 // if source has shape, we need to clip it too, so a copy of the clip is
1736 // saved.
ctguil@chromium.org8dcf74f2011-07-12 21:56:27 +00001737 SkClipStack clipStack = contentEntries->fState.fClipStack;
1738 SkRegion clipRegion = contentEntries->fState.fClipRegion;
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001739
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001740 SkMatrix identity;
1741 identity.reset();
1742 SkPaint stockPaint;
1743
reed@google.comfc641d02012-09-20 17:52:20 +00001744 SkAutoTUnref<SkPDFFormXObject> srcFormXObject;
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001745 if (isContentEmpty()) {
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001746 // If nothing was drawn and there's no shape, then the draw was a
1747 // no-op, but dst needs to be restored for that to be true.
1748 // If there is shape, then an empty source with Src, SrcIn, SrcOut,
1749 // DstIn, DstAtop or Modulate reduces to Clear and DstOut or SrcAtop
1750 // reduces to Dst.
1751 if (shape == NULL || xfermode == SkXfermode::kDstOut_Mode ||
1752 xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001753 ScopedContentEntry content(this, &fExistingClipStack,
1754 fExistingClipRegion, identity,
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001755 stockPaint);
1756 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1757 &content.entry()->fContent);
1758 return;
1759 } else {
1760 xfermode = SkXfermode::kClear_Mode;
1761 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001762 } else {
1763 SkASSERT(!fContentEntries->fNext.get());
reed@google.comfc641d02012-09-20 17:52:20 +00001764 srcFormXObject.reset(createFormXObjectFromDevice());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001765 }
1766
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001767 // TODO(vandebo) srcFormXObject may contain alpha, but here we want it
1768 // without alpha.
1769 if (xfermode == SkXfermode::kSrcATop_Mode) {
1770 // TODO(vandebo): In order to properly support SrcATop we have to track
1771 // the shape of what's been drawn at all times. It's the intersection of
1772 // the non-transparent parts of the device and the outlines (shape) of
1773 // all images and devices drawn.
1774 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001775 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001776 SkXfermode::kSrcOver_Mode, true);
1777 } else {
1778 SkAutoTUnref<SkPDFFormXObject> dstMaskStorage;
1779 SkPDFFormXObject* dstMask = srcFormXObject.get();
1780 if (shape != NULL) {
1781 // Draw shape into a form-xobject.
1782 SkDraw d;
1783 d.fMatrix = &identity;
1784 d.fClip = &clipRegion;
1785 d.fClipStack = &clipStack;
1786 SkPaint filledPaint;
1787 filledPaint.setColor(SK_ColorBLACK);
1788 filledPaint.setStyle(SkPaint::kFill_Style);
1789 this->drawPath(d, *shape, filledPaint, NULL, true);
1790
1791 dstMaskStorage.reset(createFormXObjectFromDevice());
1792 dstMask = dstMaskStorage.get();
1793 }
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001794 drawFormXObjectWithMask(addXObjectResource(dst), dstMask,
1795 &fExistingClipStack, fExistingClipRegion,
1796 SkXfermode::kSrcOver_Mode, true);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001797 }
1798
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001799 if (xfermode == SkXfermode::kClear_Mode) {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001800 return;
1801 } else if (xfermode == SkXfermode::kSrc_Mode ||
1802 xfermode == SkXfermode::kDstATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001803 ScopedContentEntry content(this, &fExistingClipStack,
1804 fExistingClipRegion, identity, stockPaint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001805 if (content.entry()) {
1806 SkPDFUtils::DrawFormXObject(
1807 this->addXObjectResource(srcFormXObject.get()),
1808 &content.entry()->fContent);
1809 }
1810 if (xfermode == SkXfermode::kSrc_Mode) {
1811 return;
1812 }
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001813 } else if (xfermode == SkXfermode::kSrcATop_Mode) {
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001814 ScopedContentEntry content(this, &fExistingClipStack,
1815 fExistingClipRegion, identity, stockPaint);
commit-bot@chromium.org7542dc82013-12-03 21:08:46 +00001816 if (content.entry()) {
1817 SkPDFUtils::DrawFormXObject(this->addXObjectResource(dst),
1818 &content.entry()->fContent);
1819 }
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001820 }
1821
1822 SkASSERT(xfermode == SkXfermode::kSrcIn_Mode ||
1823 xfermode == SkXfermode::kDstIn_Mode ||
1824 xfermode == SkXfermode::kSrcOut_Mode ||
1825 xfermode == SkXfermode::kDstOut_Mode ||
1826 xfermode == SkXfermode::kSrcATop_Mode ||
1827 xfermode == SkXfermode::kDstATop_Mode ||
1828 xfermode == SkXfermode::kModulate_Mode);
1829
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001830 if (xfermode == SkXfermode::kSrcIn_Mode ||
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001831 xfermode == SkXfermode::kSrcOut_Mode ||
1832 xfermode == SkXfermode::kSrcATop_Mode) {
1833 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()), dst,
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001834 &fExistingClipStack, fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001835 SkXfermode::kSrcOver_Mode,
1836 xfermode == SkXfermode::kSrcOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001837 } else {
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001838 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
1839 if (xfermode == SkXfermode::kModulate_Mode) {
1840 drawFormXObjectWithMask(addXObjectResource(srcFormXObject.get()),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001841 dst, &fExistingClipStack,
1842 fExistingClipRegion,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001843 SkXfermode::kSrcOver_Mode, false);
1844 mode = SkXfermode::kMultiply_Mode;
1845 }
1846 drawFormXObjectWithMask(addXObjectResource(dst), srcFormXObject.get(),
commit-bot@chromium.org4e8f1e52013-12-17 23:38:28 +00001847 &fExistingClipStack, fExistingClipRegion, mode,
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001848 xfermode == SkXfermode::kDstOut_Mode);
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001849 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001850}
1851
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001852bool SkPDFDevice::isContentEmpty() {
ctguil@chromium.org9510ccc2011-07-27 00:10:51 +00001853 ContentEntry* contentEntries = getContentEntries()->get();
1854 if (!contentEntries || contentEntries->fContent.getOffset() == 0) {
1855 SkASSERT(!contentEntries || !contentEntries->fNext.get());
vandebo@chromium.org481aef62011-05-24 16:39:05 +00001856 return true;
1857 }
1858 return false;
1859}
1860
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001861void SkPDFDevice::populateGraphicStateEntryFromPaint(
1862 const SkMatrix& matrix,
1863 const SkClipStack& clipStack,
1864 const SkRegion& clipRegion,
1865 const SkPaint& paint,
1866 bool hasText,
1867 GraphicStateEntry* entry) {
reed@google.com6f4e4732014-05-22 18:53:10 +00001868 NOT_IMPLEMENTED(paint.getPathEffect() != NULL, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001869 NOT_IMPLEMENTED(paint.getMaskFilter() != NULL, false);
1870 NOT_IMPLEMENTED(paint.getColorFilter() != NULL, false);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001871
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001872 entry->fMatrix = matrix;
1873 entry->fClipStack = clipStack;
1874 entry->fClipRegion = clipRegion;
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +00001875 entry->fColor = SkColorSetA(paint.getColor(), 0xFF);
1876 entry->fShaderIndex = -1;
vandebo@chromium.org48543272011-02-08 19:28:07 +00001877
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001878 // PDF treats a shader as a color, so we only set one or the other.
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001879 SkAutoTUnref<SkPDFObject> pdfShader;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001880 const SkShader* shader = paint.getShader();
1881 SkColor color = paint.getColor();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001882 if (shader) {
1883 // PDF positions patterns relative to the initial transform, so
1884 // we need to apply the current transform to the shader parameters.
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001885 SkMatrix transform = matrix;
vandebo@chromium.org75f97e42011-04-11 23:24:18 +00001886 transform.postConcat(fInitialTransform);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001887
1888 // PDF doesn't support kClamp_TileMode, so we simulate it by making
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001889 // a pattern the size of the current clip.
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001890 SkIRect bounds = clipRegion.getBounds();
vandebo@chromium.org293a7582012-03-16 19:50:37 +00001891
1892 // We need to apply the initial transform to bounds in order to get
1893 // bounds in a consistent coordinate system.
1894 SkRect boundsTemp;
1895 boundsTemp.set(bounds);
1896 fInitialTransform.mapRect(&boundsTemp);
1897 boundsTemp.roundOut(&bounds);
1898
halcanary792c80f2015-02-20 07:21:05 -08001899 SkScalar rasterScale =
1900 SkIntToScalar(fRasterDpi) / DPI_FOR_RASTER_SCALE_ONE;
1901 pdfShader.reset(SkPDFShader::GetPDFShader(
1902 fCanon, fRasterDpi, *shader, transform, bounds, rasterScale));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001903
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001904 if (pdfShader.get()) {
1905 // pdfShader has been canonicalized so we can directly compare
1906 // pointers.
1907 int resourceIndex = fShaderResources.find(pdfShader.get());
1908 if (resourceIndex < 0) {
1909 resourceIndex = fShaderResources.count();
1910 fShaderResources.push(pdfShader.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001911 pdfShader.get()->ref();
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +00001912 }
1913 entry->fShaderIndex = resourceIndex;
1914 } else {
1915 // A color shader is treated as an invalid shader so we don't have
1916 // to set a shader just for a color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001917 SkShader::GradientInfo gradientInfo;
1918 SkColor gradientColor;
1919 gradientInfo.fColors = &gradientColor;
1920 gradientInfo.fColorOffsets = NULL;
1921 gradientInfo.fColorCount = 1;
1922 if (shader->asAGradient(&gradientInfo) ==
1923 SkShader::kColor_GradientType) {
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001924 entry->fColor = SkColorSetA(gradientColor, 0xFF);
1925 color = gradientColor;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001926 }
1927 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001928 }
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001929
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001930 SkAutoTUnref<SkPDFGraphicState> newGraphicState;
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001931 if (color == paint.getColor()) {
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001932 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001933 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, paint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001934 } else {
1935 SkPaint newPaint = paint;
1936 newPaint.setColor(color);
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001937 newGraphicState.reset(
halcanary792c80f2015-02-20 07:21:05 -08001938 SkPDFGraphicState::GetGraphicStateForPaint(fCanon, newPaint));
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001939 }
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001940 int resourceIndex = addGraphicStateResource(newGraphicState.get());
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001941 entry->fGraphicStateIndex = resourceIndex;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001942
vandebo@chromium.org9fbdf872011-05-09 07:55:58 +00001943 if (hasText) {
1944 entry->fTextScaleX = paint.getTextScaleX();
1945 entry->fTextFill = paint.getStyle();
1946 } else {
1947 entry->fTextScaleX = 0;
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00001948 }
1949}
1950
vandebo@chromium.org6112c212011-05-13 03:50:38 +00001951int SkPDFDevice::addGraphicStateResource(SkPDFGraphicState* gs) {
1952 // Assumes that gs has been canonicalized (so we can directly compare
1953 // pointers).
1954 int result = fGraphicStateResources.find(gs);
1955 if (result < 0) {
1956 result = fGraphicStateResources.count();
1957 fGraphicStateResources.push(gs);
1958 gs->ref();
1959 }
1960 return result;
1961}
1962
vandebo@chromium.org3b416212013-10-30 20:48:05 +00001963int SkPDFDevice::addXObjectResource(SkPDFObject* xObject) {
1964 // Assumes that xobject has been canonicalized (so we can directly compare
1965 // pointers).
1966 int result = fXObjectResources.find(xObject);
1967 if (result < 0) {
1968 result = fXObjectResources.count();
1969 fXObjectResources.push(xObject);
1970 xObject->ref();
1971 }
1972 return result;
1973}
1974
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001975void SkPDFDevice::updateFont(const SkPaint& paint, uint16_t glyphID,
1976 ContentEntry* contentEntry) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001977 SkTypeface* typeface = paint.getTypeface();
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001978 if (contentEntry->fState.fFont == NULL ||
1979 contentEntry->fState.fTextSize != paint.getTextSize() ||
1980 !contentEntry->fState.fFont->hasGlyph(glyphID)) {
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001981 int fontIndex = getFontResourceIndex(typeface, glyphID);
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001982 contentEntry->fContent.writeText("/");
1983 contentEntry->fContent.writeText(SkPDFResourceDict::getResourceName(
1984 SkPDFResourceDict::kFont_ResourceType,
1985 fontIndex).c_str());
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00001986 contentEntry->fContent.writeText(" ");
1987 SkPDFScalar::Append(paint.getTextSize(), &contentEntry->fContent);
1988 contentEntry->fContent.writeText(" Tf\n");
1989 contentEntry->fState.fFont = fFontResources[fontIndex];
vandebo@chromium.org2a22e102011-01-25 21:01:34 +00001990 }
1991}
1992
ctguil@chromium.org9db86bb2011-03-04 21:43:27 +00001993int SkPDFDevice::getFontResourceIndex(SkTypeface* typeface, uint16_t glyphID) {
halcanary792c80f2015-02-20 07:21:05 -08001994 SkAutoTUnref<SkPDFFont> newFont(
1995 SkPDFFont::GetFontResource(fCanon, typeface, glyphID));
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00001996 int resourceIndex = fFontResources.find(newFont.get());
1997 if (resourceIndex < 0) {
1998 resourceIndex = fFontResources.count();
1999 fFontResources.push(newFont.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00002000 newFont.get()->ref();
vandebo@chromium.org28be72b2010-11-11 21:37:00 +00002001 }
2002 return resourceIndex;
2003}
2004
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002005void SkPDFDevice::internalDrawBitmap(const SkMatrix& origMatrix,
vandebo@chromium.org78dad542011-05-11 18:46:03 +00002006 const SkClipStack* clipStack,
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002007 const SkRegion& origClipRegion,
2008 const SkBitmap& origBitmap,
vandebo@chromium.orgbefebb82011-01-29 01:38:50 +00002009 const SkIRect* srcRect,
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002010 const SkPaint& paint) {
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002011 SkMatrix matrix = origMatrix;
2012 SkRegion perspectiveBounds;
2013 const SkRegion* clipRegion = &origClipRegion;
2014 SkBitmap perspectiveBitmap;
2015 const SkBitmap* bitmap = &origBitmap;
2016 SkBitmap tmpSubsetBitmap;
2017
2018 // Rasterize the bitmap using perspective in a new bitmap.
2019 if (origMatrix.hasPerspective()) {
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002020 if (fRasterDpi == 0) {
2021 return;
2022 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002023 SkBitmap* subsetBitmap;
2024 if (srcRect) {
2025 if (!origBitmap.extractSubset(&tmpSubsetBitmap, *srcRect)) {
2026 return;
2027 }
2028 subsetBitmap = &tmpSubsetBitmap;
2029 } else {
2030 subsetBitmap = &tmpSubsetBitmap;
2031 *subsetBitmap = origBitmap;
2032 }
2033 srcRect = NULL;
2034
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002035 // Transform the bitmap in the new space, without taking into
2036 // account the initial transform.
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002037 SkPath perspectiveOutline;
2038 perspectiveOutline.addRect(
2039 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2040 SkIntToScalar(subsetBitmap->height())));
2041 perspectiveOutline.transform(origMatrix);
2042
2043 // TODO(edisonn): perf - use current clip too.
2044 // Retrieve the bounds of the new shape.
2045 SkRect bounds = perspectiveOutline.getBounds();
2046
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002047 // Transform the bitmap in the new space, taking into
2048 // account the initial transform.
2049 SkMatrix total = origMatrix;
2050 total.postConcat(fInitialTransform);
2051 total.postScale(SkIntToScalar(fRasterDpi) /
2052 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE),
2053 SkIntToScalar(fRasterDpi) /
2054 SkIntToScalar(DPI_FOR_RASTER_SCALE_ONE));
2055 SkPath physicalPerspectiveOutline;
2056 physicalPerspectiveOutline.addRect(
2057 SkRect::MakeWH(SkIntToScalar(subsetBitmap->width()),
2058 SkIntToScalar(subsetBitmap->height())));
2059 physicalPerspectiveOutline.transform(total);
2060
2061 SkScalar scaleX = physicalPerspectiveOutline.getBounds().width() /
2062 bounds.width();
2063 SkScalar scaleY = physicalPerspectiveOutline.getBounds().height() /
2064 bounds.height();
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002065
2066 // TODO(edisonn): A better approach would be to use a bitmap shader
2067 // (in clamp mode) and draw a rect over the entire bounding box. Then
2068 // intersect perspectiveOutline to the clip. That will avoid introducing
2069 // alpha to the image while still giving good behavior at the edge of
2070 // the image. Avoiding alpha will reduce the pdf size and generation
2071 // CPU time some.
2072
reed@google.com9ebcac52014-01-24 18:53:42 +00002073 const int w = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().width());
2074 const int h = SkScalarCeilToInt(physicalPerspectiveOutline.getBounds().height());
reed84825042014-09-02 12:50:45 -07002075 if (!perspectiveBitmap.tryAllocN32Pixels(w, h)) {
reed@google.com9ebcac52014-01-24 18:53:42 +00002076 return;
2077 }
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002078 perspectiveBitmap.eraseColor(SK_ColorTRANSPARENT);
2079
reed89443ab2014-06-27 11:34:19 -07002080 SkCanvas canvas(perspectiveBitmap);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002081
2082 SkScalar deltaX = bounds.left();
2083 SkScalar deltaY = bounds.top();
2084
2085 SkMatrix offsetMatrix = origMatrix;
2086 offsetMatrix.postTranslate(-deltaX, -deltaY);
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002087 offsetMatrix.postScale(scaleX, scaleY);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002088
2089 // Translate the draw in the new canvas, so we perfectly fit the
2090 // shape in the bitmap.
2091 canvas.setMatrix(offsetMatrix);
2092
2093 canvas.drawBitmap(*subsetBitmap, SkIntToScalar(0), SkIntToScalar(0));
2094
2095 // Make sure the final bits are in the bitmap.
2096 canvas.flush();
2097
edisonn@google.com73a7ea32013-11-11 20:55:15 +00002098 // In the new space, we use the identity matrix translated
2099 // and scaled to reflect DPI.
2100 matrix.setScale(1 / scaleX, 1 / scaleY);
2101 matrix.postTranslate(deltaX, deltaY);
2102
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002103 perspectiveBounds.setRect(
2104 SkIRect::MakeXYWH(SkScalarFloorToInt(bounds.x()),
2105 SkScalarFloorToInt(bounds.y()),
2106 SkScalarCeilToInt(bounds.width()),
2107 SkScalarCeilToInt(bounds.height())));
2108 clipRegion = &perspectiveBounds;
2109 srcRect = NULL;
2110 bitmap = &perspectiveBitmap;
2111 }
2112
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002113 SkMatrix scaled;
2114 // Adjust for origin flip.
vandebo@chromium.org663515b2012-01-05 18:45:27 +00002115 scaled.setScale(SK_Scalar1, -SK_Scalar1);
2116 scaled.postTranslate(0, SK_Scalar1);
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002117 // Scale the image up from 1x1 to WxH.
halcanaryf622a6c2014-10-24 12:54:53 -07002118 SkIRect subset = bitmap->bounds();
reed@google.coma6d59f62011-03-07 21:29:21 +00002119 scaled.postScale(SkIntToScalar(subset.width()),
2120 SkIntToScalar(subset.height()));
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002121 scaled.postConcat(matrix);
edisonn@google.com9cf0cb12013-10-16 18:32:35 +00002122 ScopedContentEntry content(this, clipStack, *clipRegion, scaled, paint);
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002123 if (!content.entry() || (srcRect && !subset.intersect(*srcRect))) {
2124 return;
2125 }
2126 if (content.needShape()) {
2127 SkPath shape;
vandebo@chromium.orgfd3c8c22013-10-30 21:00:47 +00002128 shape.addRect(SkRect::MakeWH(SkIntToScalar(subset.width()),
2129 SkIntToScalar( subset.height())));
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002130 shape.transform(matrix);
2131 content.setShape(shape);
2132 }
2133 if (!content.needSource()) {
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002134 return;
2135 }
2136
halcanarydaefa5b2014-08-27 13:00:54 -07002137 SkAutoTUnref<SkPDFObject> image(
halcanary792c80f2015-02-20 07:21:05 -08002138 SkPDFCreateImageObject(fCanon, *bitmap, subset));
vandebo@chromium.org25adce82011-05-09 08:05:01 +00002139 if (!image) {
2140 return;
2141 }
vandebo@chromium.org7e2ff7c2010-11-03 23:55:28 +00002142
vandebo@chromium.org3b416212013-10-30 20:48:05 +00002143 SkPDFUtils::DrawFormXObject(this->addXObjectResource(image.get()),
vandebo@chromium.orgb069c8c2011-05-24 17:19:38 +00002144 &content.entry()->fContent);
vandebo@chromium.org9b49dc02010-10-20 22:23:29 +00002145}